code
stringlengths 2
1.05M
|
---|
import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import App from './containers/App';
import configureStore from './store';
import 'bootstrap/dist/css/bootstrap.css';
import './styles/index.css';
const store = configureStore();
render((
<Provider store={store}>
<App/>
</Provider>
), document.getElementById('layout'));
|
import React from 'react';
import {Clickable} from '../Clickable';
import {ReactSwap} from '../../src/Component';
export function Deep() {
return (
<div data-e2e="deep">
<h2>Deep Swap</h2>
<ReactSwap>
<div>
<h3 data-swap-handler={1} style={{marginLeft: 20, cursor: 'pointer'}}>
Click me
</h3>
</div>
<div>
<h3 data-swap-handler={1} style={{marginLeft: 20, cursor: 'pointer'}}>
Unclick me
</h3>
<div style={{marginLeft: 50}}>
<Clickable />
</div>
</div>
</ReactSwap>
</div>
);
}
|
var hutia = require('../index');
var app = hutia();
app.set('logger', 'dev');
app.set('session', { secret: 'hutia-secret', cookie: { maxAge: 60 * 60 * 1000 }});
app.set('dbpath', './hutia/test/db/mydb.db');
app.root = './hutia/test/www';
app.start(function(){
console.log('server is running...');
});
|
const logger = require('./utils/logger'),
configParser = require('./parsers/configParser'),
styleParser = require('./parsers/styleParser'),
filesReader = require('./utils/filesReader'),
filesWriter = require('./utils/filesWriter'),
dataConstructor = require('./utils/dataConstructor'),
minificationReport = require('./utils/minificationReport'),
freqAnalyzer = require('./replacer/freqAnalyzer'),
replacer = require('./replacer')
function unbemify (configObject) {
const startTime = process.hrtime(),
config = configParser(configObject),
data = dataConstructor(config)
logger.log('Unbemify started ...')
return filesReader(data)
.then(() => {
const selectors = styleParser(data.style.content),
selectorsData = freqAnalyzer(selectors, data, config)
replacer(selectorsData, data)
return filesWriter(data)
.then(() => minificationReport(selectorsData, data, startTime))
})
.catch(logger.error)
}
module.exports = unbemify
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
'use strict';
var AnimatedWithChildren = require('./AnimatedWithChildren');
var Animated = require('./Animated');
var AnimatedValue = require('./AnimatedValue');
var Interpolation = require('./Interpolation');
var AnimatedInterpolation = require('./AnimatedInterpolation');
import type { InterpolationConfigType } from './Interpolation';
class AnimatedAddition extends AnimatedWithChildren {
_a: Animated;
_b: Animated;
_aListener: number;
_bListener: number;
_listeners: {[key: number]: ValueListenerCallback};
constructor(a: Animated | number, b: Animated | number) {
super();
this._a = typeof a === 'number' ? new AnimatedValue(a) : a;
this._b = typeof b === 'number' ? new AnimatedValue(b) : b;
this._listeners = {};
}
__getValue(): number {
return this._a.__getValue() + this._b.__getValue();
}
addListener(callback: ValueListenerCallback): string {
if (!this._aListener && this._a.addListener) {
this._aListener = this._a.addListener(() => {
for (var key in this._listeners) {
this._listeners[key]({value: this.__getValue()});
}
})
}
if (!this._bListener && this._b.addListener) {
this._bListener = this._b.addListener(() => {
for (var key in this._listeners) {
this._listeners[key]({value: this.__getValue()});
}
})
}
var id = guid();
this._listeners[id] = callback;
return id;
}
removeListener(id: string): void {
delete this._listeners[id];
}
interpolate(config: InterpolationConfigType): AnimatedInterpolation {
return new AnimatedInterpolation(this, Interpolation.create(config));
}
__attach(): void {
this._a.__addChild(this);
this._b.__addChild(this);
}
__detach(): void {
this._a.__removeChild(this);
this._b.__removeChild(this);
}
}
module.exports = AnimatedAddition;
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Passes each element in the array to the given callback.
*
* @function Phaser.Utils.Array.Each
* @since 3.4.0
*
* @param {array} array - The array to search.
* @param {function} callback - A callback to be invoked for each item in the array.
* @param {object} context - The context in which the callback is invoked.
* @param {...*} [args] - Additional arguments that will be passed to the callback, after the current array item.
*
* @return {array} The input array.
*/
var Each = function (array, callback, context)
{
var i;
var args = [ null ];
for (i = 3; i < arguments.length; i++)
{
args.push(arguments[i]);
}
for (i = 0; i < array.length; i++)
{
args[0] = array[i];
callback.apply(context, args);
}
return array;
};
module.exports = Each;
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
// LN - Also read http://guides.rubyonrails.org/asset_pipeline.html Comments
// below are based on that.
//
// Provided by Rails support gems
//= require jquery
//= require jquery_ujs
//
// Required custom libraries (lib/assets/javascripts/)
//= require trackerFunctions2
//
// Required vendor libraries (app/vendor/javascripts/)
// require jquery.cookies.2.2.0
// require ajax # Not strictly needed. Use jQuery or jQuery.ajax() instead.
//= require OpenLayers/OpenLayers
//= require OpenLayers3/ol3
//= require highcharts
//= require pusher.min
//
// This takes care of everything in app/assets/javascripts
// NOTE: 'require_tree .' is disabled because it causes double loading.
// Page-specific app/assets/javascripts files are included explicitly in
// their corresponding view html along with this file.
// require_tree .
|
var spec = function () {
return jasmine.getEnv().currentSpec;
};
var createDataArray = function (rows, cols) {
spec().data = [];
rows = rows || 100;
cols = cols || 4;
for (var i = 0; i < rows; i++) {
var row = [i];
for (var j = 0; j < cols - 1; j++) {
row.push(String.fromCharCode(65 + j % 20).toLowerCase() + (j / 20 | 0 || '')); // | 0 is parseInt - see http://jsperf.com/math-floor-vs-math-round-vs-parseint/18
}
spec().data.push(row);
}
};
var getData = function (row, col) {
return spec().data[row][col];
};
var getTotalRows = function () {
return spec().data.length;
};
var getTotalColumns = function () {
return spec().data[0].length;
};
|
import React, {Component} from 'react';
class Square extends Component{
render(){
return (<button type="button" id={this.props.id}
onClick={() => this.props.onClick(this.props)}
className="Square">
{this.props.text}
</button>);
}
}
export default Square;
|
/*!
* Bootstrap v3.0.3 (http://getbootstrap.com)
* Copyright 2013 Twitter, Inc.
* Licensed under http://www.apache.org/licenses/LICENSE-2.0
*/
if ("undefined" == typeof jQuery) throw new Error("Bootstrap requires jQuery"); + function(a) {
"use strict";
function b() {
var a = document.createElement("bootstrap"),
b = {
WebkitTransition: "webkitTransitionEnd",
MozTransition: "transitionend",
OTransition: "oTransitionEnd otransitionend",
transition: "transitionend"
};
for (var c in b)
if (void 0 !== a.style[c]) return {
end: b[c]
}
}
a.fn.emulateTransitionEnd = function(b) {
var c = !1,
d = this;
a(this).one(a.support.transition.end, function() {
c = !0
});
var e = function() {
c || a(d).trigger(a.support.transition.end)
};
return setTimeout(e, b), this
}, a(function() {
a.support.transition = b()
})
}(jQuery), + function(a) {
"use strict";
var b = '[data-dismiss="alert"]',
c = function(c) {
a(c).on("click", b, this.close)
};
c.prototype.close = function(b) {
function c() {
f.trigger("closed.bs.alert").remove()
}
var d = a(this),
e = d.attr("data-target");
e || (e = d.attr("href"), e = e && e.replace(/.*(?=#[^\s]*$)/, ""));
var f = a(e);
b && b.preventDefault(), f.length || (f = d.hasClass("alert") ? d : d.parent()), f.trigger(b = a.Event("close.bs.alert")), b.isDefaultPrevented() || (f.removeClass("in"), a.support.transition && f.hasClass("fade") ? f.one(a.support.transition.end, c).emulateTransitionEnd(150) : c())
};
var d = a.fn.alert;
a.fn.alert = function(b) {
return this.each(function() {
var d = a(this),
e = d.data("bs.alert");
e || d.data("bs.alert", e = new c(this)), "string" == typeof b && e[b].call(d)
})
}, a.fn.alert.Constructor = c, a.fn.alert.noConflict = function() {
return a.fn.alert = d, this
}, a(document).on("click.bs.alert.data-api", b, c.prototype.close)
}(jQuery), + function(a) {
"use strict";
var b = function(c, d) {
this.$element = a(c), this.options = a.extend({}, b.DEFAULTS, d)
};
b.DEFAULTS = {
loadingText: "loading..."
}, b.prototype.setState = function(a) {
var b = "disabled",
c = this.$element,
d = c.is("input") ? "val" : "html",
e = c.data();
a += "Text", e.resetText || c.data("resetText", c[d]()), c[d](e[a] || this.options[a]), setTimeout(function() {
"loadingText" == a ? c.addClass(b).attr(b, b) : c.removeClass(b).removeAttr(b)
}, 0)
}, b.prototype.toggle = function() {
var a = this.$element.closest('[data-toggle="buttons"]'),
b = !0;
if (a.length) {
var c = this.$element.find("input");
"radio" === c.prop("type") && (c.prop("checked") && this.$element.hasClass("active") ? b = !1 : a.find(".active").removeClass("active")), b && c.prop("checked", !this.$element.hasClass("active")).trigger("change")
}
b && this.$element.toggleClass("active")
};
var c = a.fn.button;
a.fn.button = function(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.button"),
f = "object" == typeof c && c;
e || d.data("bs.button", e = new b(this, f)), "toggle" == c ? e.toggle() : c && e.setState(c)
})
}, a.fn.button.Constructor = b, a.fn.button.noConflict = function() {
return a.fn.button = c, this
}, a(document).on("click.bs.button.data-api", "[data-toggle^=button]", function(b) {
var c = a(b.target);
c.hasClass("btn") || (c = c.closest(".btn")), c.button("toggle"), b.preventDefault()
})
}(jQuery), + function(a) {
"use strict";
var b = function(b, c) {
this.$element = a(b), this.$indicators = this.$element.find(".carousel-indicators"), this.options = c, this.paused = this.sliding = this.interval = this.$active = this.$items = null, "hover" == this.options.pause && this.$element.on("mouseenter", a.proxy(this.pause, this)).on("mouseleave", a.proxy(this.cycle, this))
};
b.DEFAULTS = {
interval: 5e3,
pause: "hover",
wrap: !0
}, b.prototype.cycle = function(b) {
return b || (this.paused = !1), this.interval && clearInterval(this.interval), this.options.interval && !this.paused && (this.interval = setInterval(a.proxy(this.next, this), this.options.interval)), this
}, b.prototype.getActiveIndex = function() {
return this.$active = this.$element.find(".item.active"), this.$items = this.$active.parent().children(), this.$items.index(this.$active)
}, b.prototype.to = function(b) {
var c = this,
d = this.getActiveIndex();
return b > this.$items.length - 1 || 0 > b ? void 0 : this.sliding ? this.$element.one("slid.bs.carousel", function() {
c.to(b)
}) : d == b ? this.pause().cycle() : this.slide(b > d ? "next" : "prev", a(this.$items[b]))
}, b.prototype.pause = function(b) {
return b || (this.paused = !0), this.$element.find(".next, .prev").length && a.support.transition.end && (this.$element.trigger(a.support.transition.end), this.cycle(!0)), this.interval = clearInterval(this.interval), this
}, b.prototype.next = function() {
return this.sliding ? void 0 : this.slide("next")
}, b.prototype.prev = function() {
return this.sliding ? void 0 : this.slide("prev")
}, b.prototype.slide = function(b, c) {
var d = this.$element.find(".item.active"),
e = c || d[b](),
f = this.interval,
g = "next" == b ? "left" : "right",
h = "next" == b ? "first" : "last",
i = this;
if (!e.length) {
if (!this.options.wrap) return;
e = this.$element.find(".item")[h]()
}
this.sliding = !0, f && this.pause();
var j = a.Event("slide.bs.carousel", {
relatedTarget: e[0],
direction: g
});
if (!e.hasClass("active")) {
if (this.$indicators.length && (this.$indicators.find(".active").removeClass("active"), this.$element.one("slid.bs.carousel", function() {
var b = a(i.$indicators.children()[i.getActiveIndex()]);
b && b.addClass("active")
})), a.support.transition && this.$element.hasClass("slide")) {
if (this.$element.trigger(j), j.isDefaultPrevented()) return;
e.addClass(b), e[0].offsetWidth, d.addClass(g), e.addClass(g), d.one(a.support.transition.end, function() {
e.removeClass([b, g].join(" ")).addClass("active"), d.removeClass(["active", g].join(" ")), i.sliding = !1, setTimeout(function() {
i.$element.trigger("slid.bs.carousel")
}, 0)
}).emulateTransitionEnd(600)
} else {
if (this.$element.trigger(j), j.isDefaultPrevented()) return;
d.removeClass("active"), e.addClass("active"), this.sliding = !1, this.$element.trigger("slid.bs.carousel")
}
return f && this.cycle(), this
}
};
var c = a.fn.carousel;
a.fn.carousel = function(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.carousel"),
f = a.extend({}, b.DEFAULTS, d.data(), "object" == typeof c && c),
g = "string" == typeof c ? c : f.slide;
e || d.data("bs.carousel", e = new b(this, f)), "number" == typeof c ? e.to(c) : g ? e[g]() : f.interval && e.pause().cycle()
})
}, a.fn.carousel.Constructor = b, a.fn.carousel.noConflict = function() {
return a.fn.carousel = c, this
}, a(document).on("click.bs.carousel.data-api", "[data-slide], [data-slide-to]", function(b) {
var c, d = a(this),
e = a(d.attr("data-target") || (c = d.attr("href")) && c.replace(/.*(?=#[^\s]+$)/, "")),
f = a.extend({}, e.data(), d.data()),
g = d.attr("data-slide-to");
g && (f.interval = !1), e.carousel(f), (g = d.attr("data-slide-to")) && e.data("bs.carousel").to(g), b.preventDefault()
}), a(window).on("load", function() {
a('[data-ride="carousel"]').each(function() {
var b = a(this);
b.carousel(b.data())
})
})
}(jQuery), + function(a) {
"use strict";
var b = function(c, d) {
this.$element = a(c), this.options = a.extend({}, b.DEFAULTS, d), this.transitioning = null, this.options.parent && (this.$parent = a(this.options.parent)), this.options.toggle && this.toggle()
};
b.DEFAULTS = {
toggle: !0
}, b.prototype.dimension = function() {
var a = this.$element.hasClass("width");
return a ? "width" : "height"
}, b.prototype.show = function() {
if (!this.transitioning && !this.$element.hasClass("in")) {
var b = a.Event("show.bs.collapse");
if (this.$element.trigger(b), !b.isDefaultPrevented()) {
var c = this.$parent && this.$parent.find("> .panel > .in");
if (c && c.length) {
var d = c.data("bs.collapse");
if (d && d.transitioning) return;
c.collapse("hide"), d || c.data("bs.collapse", null)
}
var e = this.dimension();
this.$element.removeClass("collapse").addClass("collapsing")[e](0), this.transitioning = 1;
var f = function() {
this.$element.removeClass("collapsing").addClass("in")[e]("auto"), this.transitioning = 0, this.$element.trigger("shown.bs.collapse")
};
if (!a.support.transition) return f.call(this);
var g = a.camelCase(["scroll", e].join("-"));
this.$element.one(a.support.transition.end, a.proxy(f, this)).emulateTransitionEnd(350)[e](this.$element[0][g])
}
}
}, b.prototype.hide = function() {
if (!this.transitioning && this.$element.hasClass("in")) {
var b = a.Event("hide.bs.collapse");
if (this.$element.trigger(b), !b.isDefaultPrevented()) {
var c = this.dimension();
this.$element[c](this.$element[c]())[0].offsetHeight, this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"), this.transitioning = 1;
var d = function() {
this.transitioning = 0, this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")
};
return a.support.transition ? (this.$element[c](0).one(a.support.transition.end, a.proxy(d, this)).emulateTransitionEnd(350), void 0) : d.call(this)
}
}
}, b.prototype.toggle = function() {
this[this.$element.hasClass("in") ? "hide" : "show"]()
};
var c = a.fn.collapse;
a.fn.collapse = function(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.collapse"),
f = a.extend({}, b.DEFAULTS, d.data(), "object" == typeof c && c);
e || d.data("bs.collapse", e = new b(this, f)), "string" == typeof c && e[c]()
})
}, a.fn.collapse.Constructor = b, a.fn.collapse.noConflict = function() {
return a.fn.collapse = c, this
}, a(document).on("click.bs.collapse.data-api", "[data-toggle=collapse]", function(b) {
var c, d = a(this),
e = d.attr("data-target") || b.preventDefault() || (c = d.attr("href")) && c.replace(/.*(?=#[^\s]+$)/, ""),
f = a(e),
g = f.data("bs.collapse"),
h = g ? "toggle" : d.data(),
i = d.attr("data-parent"),
j = i && a(i);
g && g.transitioning || (j && j.find('[data-toggle=collapse][data-parent="' + i + '"]').not(d).addClass("collapsed"), d[f.hasClass("in") ? "addClass" : "removeClass"]("collapsed")), f.collapse(h)
})
}(jQuery), + function(a) {
"use strict";
function b() {
a(d).remove(), a(e).each(function(b) {
var d = c(a(this));
d.hasClass("open") && (d.trigger(b = a.Event("hide.bs.dropdown")), b.isDefaultPrevented() || d.removeClass("open").trigger("hidden.bs.dropdown"))
})
}
function c(b) {
var c = b.attr("data-target");
c || (c = b.attr("href"), c = c && /#/.test(c) && c.replace(/.*(?=#[^\s]*$)/, ""));
var d = c && a(c);
return d && d.length ? d : b.parent()
}
var d = ".dropdown-backdrop",
e = "[data-toggle=dropdown]",
f = function(b) {
a(b).on("click.bs.dropdown", this.toggle)
};
f.prototype.toggle = function(d) {
var e = a(this);
if (!e.is(".disabled, :disabled")) {
var f = c(e),
g = f.hasClass("open");
if (b(), !g) {
if ("ontouchstart" in document.documentElement && !f.closest(".navbar-nav").length && a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click", b), f.trigger(d = a.Event("show.bs.dropdown")), d.isDefaultPrevented()) return;
f.toggleClass("open").trigger("shown.bs.dropdown"), e.focus()
}
return !1
}
}, f.prototype.keydown = function(b) {
if (/(38|40|27)/.test(b.keyCode)) {
var d = a(this);
if (b.preventDefault(), b.stopPropagation(), !d.is(".disabled, :disabled")) {
var f = c(d),
g = f.hasClass("open");
if (!g || g && 27 == b.keyCode) return 27 == b.which && f.find(e).focus(), d.click();
var h = a("[role=menu] li:not(.divider):visible a", f);
if (h.length) {
var i = h.index(h.filter(":focus"));
38 == b.keyCode && i > 0 && i--, 40 == b.keyCode && i < h.length - 1 && i++, ~i || (i = 0), h.eq(i).focus()
}
}
}
};
var g = a.fn.dropdown;
a.fn.dropdown = function(b) {
return this.each(function() {
var c = a(this),
d = c.data("bs.dropdown");
d || c.data("bs.dropdown", d = new f(this)), "string" == typeof b && d[b].call(c)
})
}, a.fn.dropdown.Constructor = f, a.fn.dropdown.noConflict = function() {
return a.fn.dropdown = g, this
}, a(document).on("click.bs.dropdown.data-api", b).on("click.bs.dropdown.data-api", ".dropdown form", function(a) {
a.stopPropagation()
}).on("click.bs.dropdown.data-api", e, f.prototype.toggle).on("keydown.bs.dropdown.data-api", e + ", [role=menu]", f.prototype.keydown)
}(jQuery), + function(a) {
"use strict";
var b = function(b, c) {
this.options = c, this.$element = a(b), this.$backdrop = this.isShown = null, this.options.remote && this.$element.load(this.options.remote)
};
b.DEFAULTS = {
backdrop: !0,
keyboard: !0,
show: !0
}, b.prototype.toggle = function(a) {
return this[this.isShown ? "hide" : "show"](a)
}, b.prototype.show = function(b) {
var c = this,
d = a.Event("show.bs.modal", {
relatedTarget: b
});
this.$element.trigger(d), this.isShown || d.isDefaultPrevented() || (this.isShown = !0, this.escape(), this.$element.on("click.dismiss.modal", '[data-dismiss="modal"]', a.proxy(this.hide, this)), this.backdrop(function() {
var d = a.support.transition && c.$element.hasClass("fade");
c.$element.parent().length || c.$element.appendTo(document.body), c.$element.show(), d && c.$element[0].offsetWidth, c.$element.addClass("in").attr("aria-hidden", !1), c.enforceFocus();
var e = a.Event("shown.bs.modal", {
relatedTarget: b
});
d ? c.$element.find(".modal-dialog").one(a.support.transition.end, function() {
c.$element.focus().trigger(e)
}).emulateTransitionEnd(300) : c.$element.focus().trigger(e)
}))
}, b.prototype.hide = function(b) {
b && b.preventDefault(), b = a.Event("hide.bs.modal"), this.$element.trigger(b), this.isShown && !b.isDefaultPrevented() && (this.isShown = !1, this.escape(), a(document).off("focusin.bs.modal"), this.$element.removeClass("in").attr("aria-hidden", !0).off("click.dismiss.modal"), a.support.transition && this.$element.hasClass("fade") ? this.$element.one(a.support.transition.end, a.proxy(this.hideModal, this)).emulateTransitionEnd(300) : this.hideModal())
}, b.prototype.enforceFocus = function() {
a(document).off("focusin.bs.modal").on("focusin.bs.modal", a.proxy(function(a) {
this.$element[0] === a.target || this.$element.has(a.target).length || this.$element.focus()
}, this))
}, b.prototype.escape = function() {
this.isShown && this.options.keyboard ? this.$element.on("keyup.dismiss.bs.modal", a.proxy(function(a) {
27 == a.which && this.hide()
}, this)) : this.isShown || this.$element.off("keyup.dismiss.bs.modal")
}, b.prototype.hideModal = function() {
var a = this;
this.$element.hide(), this.backdrop(function() {
a.removeBackdrop(), a.$element.trigger("hidden.bs.modal")
})
}, b.prototype.removeBackdrop = function() {
this.$backdrop && this.$backdrop.remove(), this.$backdrop = null
}, b.prototype.backdrop = function(b) {
var c = this.$element.hasClass("fade") ? "fade" : "";
if (this.isShown && this.options.backdrop) {
var d = a.support.transition && c;
if (this.$backdrop = a('<div class="modal-backdrop ' + c + '" />').appendTo(document.body), this.$element.on("click.dismiss.modal", a.proxy(function(a) {
a.target === a.currentTarget && ("static" == this.options.backdrop ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this))
}, this)), d && this.$backdrop[0].offsetWidth, this.$backdrop.addClass("in"), !b) return;
d ? this.$backdrop.one(a.support.transition.end, b).emulateTransitionEnd(150) : b()
} else !this.isShown && this.$backdrop ? (this.$backdrop.removeClass("in"), a.support.transition && this.$element.hasClass("fade") ? this.$backdrop.one(a.support.transition.end, b).emulateTransitionEnd(150) : b()) : b && b()
};
var c = a.fn.modal;
a.fn.modal = function(c, d) {
return this.each(function() {
var e = a(this),
f = e.data("bs.modal"),
g = a.extend({}, b.DEFAULTS, e.data(), "object" == typeof c && c);
f || e.data("bs.modal", f = new b(this, g)), "string" == typeof c ? f[c](d) : g.show && f.show(d)
})
}, a.fn.modal.Constructor = b, a.fn.modal.noConflict = function() {
return a.fn.modal = c, this
}, a(document).on("click.bs.modal.data-api", '[data-toggle="modal"]', function(b) {
var c = a(this),
d = c.attr("href"),
e = a(c.attr("data-target") || d && d.replace(/.*(?=#[^\s]+$)/, "")),
f = e.data("modal") ? "toggle" : a.extend({
remote: !/#/.test(d) && d
}, e.data(), c.data());
b.preventDefault(), e.modal(f, this).one("hide", function() {
c.is(":visible") && c.focus()
})
}), a(document).on("show.bs.modal", ".modal", function() {
a(document.body).addClass("modal-open")
}).on("hidden.bs.modal", ".modal", function() {
a(document.body).removeClass("modal-open")
})
}(jQuery), + function(a) {
"use strict";
var b = function(a, b) {
this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null, this.init("tooltip", a, b)
};
b.DEFAULTS = {
animation: !0,
placement: "top",
selector: !1,
template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: "hover focus",
title: "",
delay: 0,
html: !1,
container: !1
}, b.prototype.init = function(b, c, d) {
this.enabled = !0, this.type = b, this.$element = a(c), this.options = this.getOptions(d);
for (var e = this.options.trigger.split(" "), f = e.length; f--;) {
var g = e[f];
if ("click" == g) this.$element.on("click." + this.type, this.options.selector, a.proxy(this.toggle, this));
else if ("manual" != g) {
var h = "hover" == g ? "mouseenter" : "focus",
i = "hover" == g ? "mouseleave" : "blur";
this.$element.on(h + "." + this.type, this.options.selector, a.proxy(this.enter, this)), this.$element.on(i + "." + this.type, this.options.selector, a.proxy(this.leave, this))
}
}
this.options.selector ? this._options = a.extend({}, this.options, {
trigger: "manual",
selector: ""
}) : this.fixTitle()
}, b.prototype.getDefaults = function() {
return b.DEFAULTS
}, b.prototype.getOptions = function(b) {
return b = a.extend({}, this.getDefaults(), this.$element.data(), b), b.delay && "number" == typeof b.delay && (b.delay = {
show: b.delay,
hide: b.delay
}), b
}, b.prototype.getDelegateOptions = function() {
var b = {},
c = this.getDefaults();
return this._options && a.each(this._options, function(a, d) {
c[a] != d && (b[a] = d)
}), b
}, b.prototype.enter = function(b) {
var c = b instanceof this.constructor ? b : a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs." + this.type);
return clearTimeout(c.timeout), c.hoverState = "in", c.options.delay && c.options.delay.show ? (c.timeout = setTimeout(function() {
"in" == c.hoverState && c.show()
}, c.options.delay.show), void 0) : c.show()
}, b.prototype.leave = function(b) {
var c = b instanceof this.constructor ? b : a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs." + this.type);
return clearTimeout(c.timeout), c.hoverState = "out", c.options.delay && c.options.delay.hide ? (c.timeout = setTimeout(function() {
"out" == c.hoverState && c.hide()
}, c.options.delay.hide), void 0) : c.hide()
}, b.prototype.show = function() {
var b = a.Event("show.bs." + this.type);
if (this.hasContent() && this.enabled) {
if (this.$element.trigger(b), b.isDefaultPrevented()) return;
var c = this.tip();
this.setContent(), this.options.animation && c.addClass("fade");
var d = "function" == typeof this.options.placement ? this.options.placement.call(this, c[0], this.$element[0]) : this.options.placement,
e = /\s?auto?\s?/i,
f = e.test(d);
f && (d = d.replace(e, "") || "top"), c.detach().css({
top: 0,
left: 0,
display: "block"
}).addClass(d), this.options.container ? c.appendTo(this.options.container) : c.insertAfter(this.$element);
var g = this.getPosition(),
h = c[0].offsetWidth,
i = c[0].offsetHeight;
if (f) {
var j = this.$element.parent(),
k = d,
l = document.documentElement.scrollTop || document.body.scrollTop,
m = "body" == this.options.container ? window.innerWidth : j.outerWidth(),
n = "body" == this.options.container ? window.innerHeight : j.outerHeight(),
o = "body" == this.options.container ? 0 : j.offset().left;
d = "bottom" == d && g.top + g.height + i - l > n ? "top" : "top" == d && g.top - l - i < 0 ? "bottom" : "right" == d && g.right + h > m ? "left" : "left" == d && g.left - h < o ? "right" : d, c.removeClass(k).addClass(d)
}
var p = this.getCalculatedOffset(d, g, h, i);
this.applyPlacement(p, d), this.$element.trigger("shown.bs." + this.type)
}
}, b.prototype.applyPlacement = function(a, b) {
var c, d = this.tip(),
e = d[0].offsetWidth,
f = d[0].offsetHeight,
g = parseInt(d.css("margin-top"), 10),
h = parseInt(d.css("margin-left"), 10);
isNaN(g) && (g = 0), isNaN(h) && (h = 0), a.top = a.top + g, a.left = a.left + h, d.offset(a).addClass("in");
var i = d[0].offsetWidth,
j = d[0].offsetHeight;
if ("top" == b && j != f && (c = !0, a.top = a.top + f - j), /bottom|top/.test(b)) {
var k = 0;
a.left < 0 && (k = -2 * a.left, a.left = 0, d.offset(a), i = d[0].offsetWidth, j = d[0].offsetHeight), this.replaceArrow(k - e + i, i, "left")
} else this.replaceArrow(j - f, j, "top");
c && d.offset(a)
}, b.prototype.replaceArrow = function(a, b, c) {
this.arrow().css(c, a ? 50 * (1 - a / b) + "%" : "")
}, b.prototype.setContent = function() {
var a = this.tip(),
b = this.getTitle();
a.find(".tooltip-inner")[this.options.html ? "html" : "text"](b), a.removeClass("fade in top bottom left right")
}, b.prototype.hide = function() {
function b() {
"in" != c.hoverState && d.detach()
}
var c = this,
d = this.tip(),
e = a.Event("hide.bs." + this.type);
return this.$element.trigger(e), e.isDefaultPrevented() ? void 0 : (d.removeClass("in"), a.support.transition && this.$tip.hasClass("fade") ? d.one(a.support.transition.end, b).emulateTransitionEnd(150) : b(), this.$element.trigger("hidden.bs." + this.type), this)
}, b.prototype.fixTitle = function() {
var a = this.$element;
(a.attr("title") || "string" != typeof a.attr("data-original-title")) && a.attr("data-original-title", a.attr("title") || "").attr("title", "")
}, b.prototype.hasContent = function() {
return this.getTitle()
}, b.prototype.getPosition = function() {
var b = this.$element[0];
return a.extend({}, "function" == typeof b.getBoundingClientRect ? b.getBoundingClientRect() : {
width: b.offsetWidth,
height: b.offsetHeight
}, this.$element.offset())
}, b.prototype.getCalculatedOffset = function(a, b, c, d) {
return "bottom" == a ? {
top: b.top + b.height,
left: b.left + b.width / 2 - c / 2
} : "top" == a ? {
top: b.top - d,
left: b.left + b.width / 2 - c / 2
} : "left" == a ? {
top: b.top + b.height / 2 - d / 2,
left: b.left - c
} : {
top: b.top + b.height / 2 - d / 2,
left: b.left + b.width
}
}, b.prototype.getTitle = function() {
var a, b = this.$element,
c = this.options;
return a = b.attr("data-original-title") || ("function" == typeof c.title ? c.title.call(b[0]) : c.title)
}, b.prototype.tip = function() {
return this.$tip = this.$tip || a(this.options.template)
}, b.prototype.arrow = function() {
return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow")
}, b.prototype.validate = function() {
this.$element[0].parentNode || (this.hide(), this.$element = null, this.options = null)
}, b.prototype.enable = function() {
this.enabled = !0
}, b.prototype.disable = function() {
this.enabled = !1
}, b.prototype.toggleEnabled = function() {
this.enabled = !this.enabled
}, b.prototype.toggle = function(b) {
var c = b ? a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs." + this.type) : this;
c.tip().hasClass("in") ? c.leave(c) : c.enter(c)
}, b.prototype.destroy = function() {
this.hide().$element.off("." + this.type).removeData("bs." + this.type)
};
var c = a.fn.tooltip;
a.fn.tooltip = function(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.tooltip"),
f = "object" == typeof c && c;
e || d.data("bs.tooltip", e = new b(this, f)), "string" == typeof c && e[c]()
})
}, a.fn.tooltip.Constructor = b, a.fn.tooltip.noConflict = function() {
return a.fn.tooltip = c, this
}
}(jQuery), + function(a) {
"use strict";
var b = function(a, b) {
this.init("popover", a, b)
};
if (!a.fn.tooltip) throw new Error("Popover requires tooltip.js");
b.DEFAULTS = a.extend({}, a.fn.tooltip.Constructor.DEFAULTS, {
placement: "right",
trigger: "click",
content: "",
template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
}), b.prototype = a.extend({}, a.fn.tooltip.Constructor.prototype), b.prototype.constructor = b, b.prototype.getDefaults = function() {
return b.DEFAULTS
}, b.prototype.setContent = function() {
var a = this.tip(),
b = this.getTitle(),
c = this.getContent();
a.find(".popover-title")[this.options.html ? "html" : "text"](b), a.find(".popover-content")[this.options.html ? "html" : "text"](c), a.removeClass("fade top bottom left right in"), a.find(".popover-title").html() || a.find(".popover-title").hide()
}, b.prototype.hasContent = function() {
return this.getTitle() || this.getContent()
}, b.prototype.getContent = function() {
var a = this.$element,
b = this.options;
return a.attr("data-content") || ("function" == typeof b.content ? b.content.call(a[0]) : b.content)
}, b.prototype.arrow = function() {
return this.$arrow = this.$arrow || this.tip().find(".arrow")
}, b.prototype.tip = function() {
return this.$tip || (this.$tip = a(this.options.template)), this.$tip
};
var c = a.fn.popover;
a.fn.popover = function(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.popover"),
f = "object" == typeof c && c;
e || d.data("bs.popover", e = new b(this, f)), "string" == typeof c && e[c]()
})
}, a.fn.popover.Constructor = b, a.fn.popover.noConflict = function() {
return a.fn.popover = c, this
}
}(jQuery), + function(a) {
"use strict";
function b(c, d) {
var e, f = a.proxy(this.process, this);
this.$element = a(c).is("body") ? a(window) : a(c), this.$body = a("body"), this.$scrollElement = this.$element.on("scroll.bs.scroll-spy.data-api", f), this.options = a.extend({}, b.DEFAULTS, d), this.selector = (this.options.target || (e = a(c).attr("href")) && e.replace(/.*(?=#[^\s]+$)/, "") || "") + " .nav li > a", this.offsets = a([]), this.targets = a([]), this.activeTarget = null, this.refresh(), this.process()
}
b.DEFAULTS = {
offset: 10
}, b.prototype.refresh = function() {
var b = this.$element[0] == window ? "offset" : "position";
this.offsets = a([]), this.targets = a([]);
var c = this;
this.$body.find(this.selector).map(function() {
var d = a(this),
e = d.data("target") || d.attr("href"),
f = /^#\w/.test(e) && a(e);
return f && f.length && [
[f[b]().top + (!a.isWindow(c.$scrollElement.get(0)) && c.$scrollElement.scrollTop()), e]
] || null
}).sort(function(a, b) {
return a[0] - b[0]
}).each(function() {
c.offsets.push(this[0]), c.targets.push(this[1])
})
}, b.prototype.process = function() {
var a, b = this.$scrollElement.scrollTop() + this.options.offset,
c = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight,
d = c - this.$scrollElement.height(),
e = this.offsets,
f = this.targets,
g = this.activeTarget;
if (b >= d) return g != (a = f.last()[0]) && this.activate(a);
for (a = e.length; a--;) g != f[a] && b >= e[a] && (!e[a + 1] || b <= e[a + 1]) && this.activate(f[a])
}, b.prototype.activate = function(b) {
this.activeTarget = b, a(this.selector).parents(".active").removeClass("active");
var c = this.selector + '[data-target="' + b + '"],' + this.selector + '[href="' + b + '"]',
d = a(c).parents("li").addClass("active");
d.parent(".dropdown-menu").length && (d = d.closest("li.dropdown").addClass("active")), d.trigger("activate.bs.scrollspy")
};
var c = a.fn.scrollspy;
a.fn.scrollspy = function(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.scrollspy"),
f = "object" == typeof c && c;
e || d.data("bs.scrollspy", e = new b(this, f)), "string" == typeof c && e[c]()
})
}, a.fn.scrollspy.Constructor = b, a.fn.scrollspy.noConflict = function() {
return a.fn.scrollspy = c, this
}, a(window).on("load", function() {
a('[data-spy="scroll"]').each(function() {
var b = a(this);
b.scrollspy(b.data())
})
})
}(jQuery), + function(a) {
"use strict";
var b = function(b) {
this.element = a(b)
};
b.prototype.show = function() {
var b = this.element,
c = b.closest("ul:not(.dropdown-menu)"),
d = b.data("target");
if (d || (d = b.attr("href"), d = d && d.replace(/.*(?=#[^\s]*$)/, "")), !b.parent("li").hasClass("active")) {
var e = c.find(".active:last a")[0],
f = a.Event("show.bs.tab", {
relatedTarget: e
});
if (b.trigger(f), !f.isDefaultPrevented()) {
var g = a(d);
this.activate(b.parent("li"), c), this.activate(g, g.parent(), function() {
b.trigger({
type: "shown.bs.tab",
relatedTarget: e
})
})
}
}
}, b.prototype.activate = function(b, c, d) {
function e() {
f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"), b.addClass("active"), g ? (b[0].offsetWidth, b.addClass("in")) : b.removeClass("fade"), b.parent(".dropdown-menu") && b.closest("li.dropdown").addClass("active"), d && d()
}
var f = c.find("> .active"),
g = d && a.support.transition && f.hasClass("fade");
g ? f.one(a.support.transition.end, e).emulateTransitionEnd(150) : e(), f.removeClass("in")
};
var c = a.fn.tab;
a.fn.tab = function(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.tab");
e || d.data("bs.tab", e = new b(this)), "string" == typeof c && e[c]()
})
}, a.fn.tab.Constructor = b, a.fn.tab.noConflict = function() {
return a.fn.tab = c, this
}, a(document).on("click.bs.tab.data-api", '[data-toggle="tab"], [data-toggle="pill"]', function(b) {
b.preventDefault(), a(this).tab("show")
})
}(jQuery), + function(a) {
"use strict";
var b = function(c, d) {
this.options = a.extend({}, b.DEFAULTS, d), this.$window = a(window).on("scroll.bs.affix.data-api", a.proxy(this.checkPosition, this)).on("click.bs.affix.data-api", a.proxy(this.checkPositionWithEventLoop, this)), this.$element = a(c), this.affixed = this.unpin = null, this.checkPosition()
};
b.RESET = "affix affix-top affix-bottom", b.DEFAULTS = {
offset: 0
}, b.prototype.checkPositionWithEventLoop = function() {
setTimeout(a.proxy(this.checkPosition, this), 1)
}, b.prototype.checkPosition = function() {
if (this.$element.is(":visible")) {
var c = a(document).height(),
d = this.$window.scrollTop(),
e = this.$element.offset(),
f = this.options.offset,
g = f.top,
h = f.bottom;
"object" != typeof f && (h = g = f), "function" == typeof g && (g = f.top()), "function" == typeof h && (h = f.bottom());
var i = null != this.unpin && d + this.unpin <= e.top ? !1 : null != h && e.top + this.$element.height() >= c - h ? "bottom" : null != g && g >= d ? "top" : !1;
this.affixed !== i && (this.unpin && this.$element.css("top", ""), this.affixed = i, this.unpin = "bottom" == i ? e.top - d : null, this.$element.removeClass(b.RESET).addClass("affix" + (i ? "-" + i : "")), "bottom" == i && this.$element.offset({
top: document.body.offsetHeight - h - this.$element.height()
}))
}
};
var c = a.fn.affix;
a.fn.affix = function(c) {
return this.each(function() {
var d = a(this),
e = d.data("bs.affix"),
f = "object" == typeof c && c;
e || d.data("bs.affix", e = new b(this, f)), "string" == typeof c && e[c]()
})
}, a.fn.affix.Constructor = b, a.fn.affix.noConflict = function() {
return a.fn.affix = c, this
}, a(window).on("load", function() {
a('[data-spy="affix"]').each(function() {
var b = a(this),
c = b.data();
c.offset = c.offset || {}, c.offsetBottom && (c.offset.bottom = c.offsetBottom), c.offsetTop && (c.offset.top = c.offsetTop), b.affix(c)
})
})
}(jQuery);
|
var Schemas = {}
Mensajes = new Mongo.Collection('mensajes')
Schemas.Mensaje = new SimpleSchema({
texto: {
type: String,
autoform: {
label: false,
autofocus: true
}
},
fecha: {
type: Date,
autoValue: function() {
return this.value || (this.isInsert && new Date)
}
},
usuario: {
type: String,
autoValue: function() {
var user = Meteor.user()
return user.profile.name
}
},
salon: {
type: String
}
})
Mensajes.attachSchema(Schemas.Mensaje)
Salones = new Mongo.Collection('salones')
Schemas.Salon = new SimpleSchema({
nombre: {
type: String,
index: true,
unique: true
}
})
Salones.attachSchema(Schemas.Salon)
|
/// <reference path="../typings/tsd.d.ts"/>
var clone = require('clone');
var gulp = require('gulp');
var jade = require('gulp-jade');
var plumber = require('gulp-plumber');
var fileUtils = require('../src/util/fileutils');
gulp.task('jade', ['jade-root', 'jade-sub']);
gulp.task('jade-release', ['jade-root-release', 'jade-sub-release']);
gulp.task('jade-root', jadeRootTask(true));
gulp.task('jade-root-release', jadeRootTask(false));
function jadeRootTask(debug) {
return function () {
return gulp.src('src/public/**/*.jade')
.pipe(plumber())
.pipe(jade({ data: { debug: debug } }))
.pipe(gulp.dest('app/public/'));
};
}
gulp.task('jade-sub', jadeSubTask(true));
gulp.task('jade-sub-release', jadeSubTask(false));
function jadeSubTask(debug) {
return function () {
return fileUtils.getAppNames('src')
.then(function (apps) {
return parallel(apps.map(function (app) {
var data = {};
try {
data = require('../src/' + app + '/resources/ja.json');
} catch (ex) {
}
data.debug = debug;
data.appRoot = '/' + app + '/';
return gulp.src(['src/' + app + '/**/*.jade', '!**/template/**'])
.pipe(plumber())
.pipe(jade({ data: data }))
.pipe(gulp.dest('app/' + app));
}));
});
};
}
function parallel(taskStreams) {
return Promise.all(taskStreams.map(function (stream) {
return new Promise(function (resolve, reject) {
stream.on('end', resolve);
});
}));
}
|
module.exports = require('./bio')
|
module.exports = (function() {
'use strict';
var router = require('express').Router(),
path = require('path');
router.get('*', serveApp);
function serveApp(request, response) {
response.sendFile(path.resolve(__dirname, '../public_html/index.html'));
}
return router;
})();
|
var Sequelize = require("sequelize");
var sequelize = new Sequelize('asterisk', 'root', '1234', {
host: 'localhost',
port: 3306,
dialect: 'mysql',
define: {
timestamps: false,
}
});
var Peer = sequelize.define('sippeers', {
id: Sequelize.BIGINT,
name: Sequelize.STRING
});
Peer.findAll().success(function(peers) {
console.log(peers);
});
|
/**
* Prepro.js - A JavaScript based preprocesssor language for JavaScript
*
* Copyright (c) 2011 - 2016 Juerg Lehni
* http://scratchdisk.com/
*
* Prepro.js is a simple preprocesssor for JavaScript that speaks JavaScript,
* written in JavaScript, allowing preprocessing to either happen at build time
* or compile time. It is very useful for libraries that are built for
* distribution, but can be also compiled from separate sources directly for
* development, supporting build time switches.
*
* Distributed under the MIT license.
*/
var fs = require('fs'),
vm = require('vm'),
path = require('path'),
assign = require('object-assign');
// We need to use the parent's require() method.
var parent = module.parent;
// Create the context within which we will run the source files, inheriting from
// the global scope:
var scope = Object.create(global);
// Set up __dirname and __filename based on the parent module.
// NOTE: This isn't always right, e.g. when prepro is used in conjunction with
// the node-qunit module. We have a fall-back for this scenario in the include()
// method below.
scope.__dirname = path.dirname(parent.filename);
scope.__filename = parent.filename;
// Create a fake require method that redirects to the parent module.
scope.require = function(uri) {
// If the uri is relative, resolve it in relation to the context's current
// __dirname, otherwise pass it on directly to the parent module's require:
return parent.require(/^\./.test(uri)
? path.resolve(context.__dirname, uri) : uri);
};
// Expose require properties through fake require() method
scope.require.extensions = require.extensions;
scope.require.cache = require.cache;
scope.require.resolve = require.resolve;
// Used to load and run source files within the same context:
scope.include = function(uri, options) {
var filename = path.resolve(context.__dirname, uri),
source;
// Try loading the file first.
try {
source = fs.readFileSync(filename, 'utf8');
} catch (e) {
// If we fail, then __dirname is wrong and we need to loop through the
// other sibling modules until we find the right directory. As a
// convention, the file loading through Prepro.js should be called
// load.js, which then can be found here:
var children = parent.children;
// Start at the back as that's the most likely place for the including
// module to be found.
for (var i = children.length - 1; i >= 0; i--) {
try {
var child = children[i];
if (/load.js$/.test(child.id)) {
var dirname = path.dirname(child.id);
filename = path.resolve(dirname, uri);
source = fs.readFileSync(filename, 'utf8');
// If we're still here, the file exists in which case we can
// set the new __dirname.
context.__dirname = dirname;
break;
}
} catch (e) {
// Keep on trying.
}
}
}
// For relative includes, we save the current directory and then add the
// uri to __dirname:
var prevDirname = context.__dirname,
// If asked to not export, deactivate exporting locally
module = options && options.exports === false ? undefined : parent;
context.module = module;
context.exports = module && module.exports;
context.__dirname = path.dirname(filename);
context.__filename = filename;
vm.runInContext(source, context, filename);
context.__dirname = prevDirname;
return parent.exports;
};
var context = vm.createContext(scope);
exports.include = function(file, options) {
var exports = context.include(file),
namespace = options && options.namespace;
if (namespace)
context[namespace] = exports;
return exports;
};
exports.setup = function(func) {
var res = func.call();
if (res) {
assign(scope, res);
}
};
exports.context = context;
|
export function random(from=null,to=null,interpolation=null){
if(from==null){
from=0;
to=1;
}else if(from!=null && to==null){
to=from;
from=0;
}
const delta=to-from;
if(interpolation==null){
interpolation=(n)=>{
return n;
}
}
return from+(interpolation(Math.random())*delta);
}
export function chance(c){
return random()<=c;
}
|
/**
* @module JSON Object Signing and Encryption (JOSE)
*/
const JWK = require('./jose/JWK')
const JWKSet = require('./jose/JWKSet')
const JWT = require('./jose/JWT')
const JWD = require('./jose/JWD')
const Base64URLSchema = require('./schemas/Base64URLSchema')
const JOSEHeaderSchema = require('./schemas/JOSEHeaderSchema')
const JWKSchema = require('./schemas/JWKSchema')
const JWKSetSchema = require('./schemas/JWKSetSchema')
const JWTClaimsSetSchema = require('./schemas/JWTClaimsSetSchema')
const JWTSchema = require('./schemas/JWTSchema')
/**
* Export
*/
module.exports = {
JWK,
JWKSet,
JWT,
JWD,
Base64URLSchema,
JOSEHeaderSchema,
JWKSchema,
JWKSetSchema,
JWTClaimsSetSchema,
JWTSchema
}
|
var OFF = 0, WARN = 1, ERROR = 2;
module.exports = exports = {
"env": {
"node": true,
"browser": true,
"mocha": true,
"jquery": true,
"es6": true
},
"extends": "eslint:recommended",
// Overrides from recommended set
"rules": {
// Ignore unused vars that start with underscore
"no-unused-vars": [ ERROR, { "args": "all", "argsIgnorePattern": "^_" } ],
// Possible Errors
"no-unexpected-multiline": ERROR,
// All JSDoc comments must be valid
"valid-jsdoc": [ ERROR, {
"requireReturn": false,
"requireReturnDescription": false,
"requireParamDescription": true,
"prefer": {
"return": "returns"
}
}],
// Produce warnings when something is commented as TODO or FIXME
"no-warning-comments": [ WARN, {
"terms": [ "TODO", "FIXME" ],
"location": "start"
}],
// Whitespace
"indent": [ERROR, 4],
"no-trailing-spaces": ERROR,
"space-before-blocks": ERROR,
"keyword-spacing": ERROR,
"semi-spacing": ERROR,
"comma-spacing": ERROR,
"space-infix-ops": ERROR,
"space-in-parens": ERROR,
"array-bracket-spacing": ERROR,
// Low Risk
"curly": ERROR,
"brace-style": [ERROR, "stroustrup"],
"semi": ERROR,
"comma-style": ERROR,
"comma-dangle": ERROR,
"max-statements-per-line": ERROR,
"quotes": [ERROR, "single", { "avoidEscape": true }],
// Medium Risk
"eqeqeq": ERROR,
"no-nested-ternary": ERROR,
"no-new-object": ERROR,
"no-eval": ERROR,
"no-extend-native": ERROR,
"no-implicit-coercion": [ERROR, { "allow": ["!!"] } ],
"no-extra-boolean-cast": ERROR,
// Renaming
"camelcase": ERROR,
"new-cap": ERROR,
"func-names": ERROR,
"no-useless-rename": ERROR,
// High Risk
"strict": ERROR,
"no-loop-func": ERROR,
"max-len": [ERROR, 120],
"max-lines": [ERROR, {"max": 600, "skipBlankLines": true, "skipComments": true}],
"max-params": [ERROR, 6],
"max-statements": [ERROR, 35],
"max-depth": [ERROR, 5]
}
};
|
/**
* Blueprint API Configuration
* (sails.config.blueprints)
*
* These settings are for the global configuration of blueprint routes and
* request options (which impact the behavior of blueprint actions).
*
* You may also override any of these settings on a per-controller basis
* by defining a '_config' key in your controller defintion, and assigning it
* a configuration object with overrides for the settings in this file.
* A lot of the configuration options below affect so-called "CRUD methods",
* or your controllers' `find`, `create`, `update`, and `destroy` actions.
*
* It's important to realize that, even if you haven't defined these yourself, as long as
* a model exists with the same name as the controller, Sails will respond with built-in CRUD
* logic in the form of a JSON API, including support for sort, pagination, and filtering.
*
* For more information on the blueprint API, check out:
* http://sailsjs.org/#/documentation/reference/blueprint-api
*
* For more information on the settings in this file, see:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.blueprints.html
*
*/
module.exports.blueprints = {
/***************************************************************************
* *
* Action routes speed up the backend development workflow by *
* eliminating the need to manually bind routes. When enabled, GET, POST, *
* PUT, and DELETE routes will be generated for every one of a controller's *
* actions. *
* *
* If an `index` action exists, additional naked routes will be created for *
* it. Finally, all `actions` blueprints support an optional path *
* parameter, `id`, for convenience. *
* *
* `actions` are enabled by default, and can be OK for production-- *
* however, if you'd like to continue to use controller/action autorouting *
* in a production deployment, you must take great care not to *
* inadvertently expose unsafe/unintentional controller logic to GET *
* requests. *
* *
***************************************************************************/
actions: false,
/***************************************************************************
* *
* RESTful routes (`sails.config.blueprints.rest`) *
* *
* REST blueprints are the automatically generated routes Sails uses to *
* expose a conventional REST API on top of a controller's `find`, *
* `create`, `update`, and `destroy` actions. *
* *
* For example, a BoatController with `rest` enabled generates the *
* following routes: *
* ::::::::::::::::::::::::::::::::::::::::::::::::::::::: *
* GET /boat -> BoatController.find *
* GET /boat/:id -> BoatController.findOne *
* POST /boat -> BoatController.create *
* PUT /boat/:id -> BoatController.update *
* DELETE /boat/:id -> BoatController.destroy *
* *
* `rest` blueprint routes are enabled by default, and are suitable for use *
* in a production scenario, as long you take standard security precautions *
* (combine w/ policies, etc.) *
* *
***************************************************************************/
rest: true,
/***************************************************************************
* *
* Shortcut routes are simple helpers to provide access to a *
* controller's CRUD methods from your browser's URL bar. When enabled, *
* GET, POST, PUT, and DELETE routes will be generated for the *
* controller's`find`, `create`, `update`, and `destroy` actions. *
* *
* `shortcuts` are enabled by default, but should be disabled in *
* production. *
* *
***************************************************************************/
shortcuts: false,
/***************************************************************************
* *
* An optional mount path for all blueprint routes on a controller, *
* including `rest`, `actions`, and `shortcuts`. This allows you to take *
* advantage of blueprint routing, even if you need to namespace your API *
* methods. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
***************************************************************************/
prefix: '/api',
/***************************************************************************
* *
* Whether to pluralize controller names in blueprint routes. *
* *
* (NOTE: This only applies to blueprint autoroutes, not manual routes from *
* `sails.config.routes`) *
* *
* For example, REST blueprints for `FooController` with `pluralize` *
* enabled: *
* GET /foos/:id? *
* POST /foos *
* PUT /foos/:id? *
* DELETE /foos/:id? *
* *
***************************************************************************/
pluralize: true,
/***************************************************************************
* *
* Whether the blueprint controllers should populate model fetches with *
* data from other models which are linked by associations *
* *
* If you have a lot of data in one-to-many associations, leaving this on *
* may result in very heavy api calls *
* *
***************************************************************************/
populate: false,
/****************************************************************************
* *
* Whether to run Model.watch() in the find and findOne blueprint actions. *
* Can be overridden on a per-model basis. *
* *
****************************************************************************/
autoWatch: true,
/****************************************************************************
* *
* The default number of records to show in the response from a "find" *
* action. Doubles as the default size of populated arrays if populate is *
* true. *
* *
****************************************************************************/
defaultLimit: 30
};
|
/**
* StoryController
*
* @description :: Server-side logic for managing stories
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
like : function (req, res) {
StoryLike
.create({
story : req.param('id'),
createdBy : req.user[0].id
})
.exec(function (err, like) {
if (err) {
res.badRequest(err);
} else {
res.json(like);
}
});
},
unlike : function (req, res) {
StoryLike
.destroy({
story : req.param('id'),
createdBy : req.user[0].id
})
.exec(function (err, like) {
if (err) {
res.badRequest(err);
} else {
res.json(like);
}
});
},
};
|
/***********************************************************************************************************************
*
* CONSOLE LOGGER
*
* this exports a functions that we can use in our app
*
* @type {Node.js}
*
**********************************************************************************************************************/
const fs = require("fs-extra"); // https://nodejs.org/api/fs.html
const path = require("path"); // https://nodejs.org/api/path.html
const moment = require("moment"); // https://momentjs.com/
const chalk = require("chalk"); // https://www.npmjs.com/package/chalk
// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
let logFilePath = path.join(appDirectory, "server", "logs", moment().format("YYYYMMDD") + ".console.log");
const cleanChalkedMessage = message => {
// https://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings#answer-29497680
// remove ANSI escape codes that got inserted by chalk.
message = message.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
return `[${moment().format("dddd, DD.MM.YYYY HH:mm:ss.SSSS")}] ${message}\r\n`;
};
moment.locale("de"); // TODO: make config setting
exports.info = message => {
console.log(`${chalk.magenta(moment().format("HH:mm:ss.SSSS"))} ${chalk.yellow("🔍")} ${message}`);
fs.appendFile(logFilePath, cleanChalkedMessage(message), "utf8", err => {
if (err) throw err;
});
};
exports.debug = message => {
console.log(`${chalk.magenta(moment().format("HH:mm:ss.SSSS"))} ${chalk.cyan("🔧")} ${message}`);
fs.appendFile(logFilePath, cleanChalkedMessage(message), "utf8", err => {
if (err) throw err;
});
};
exports.warn = message => {
console.log(`${chalk.magenta(moment().format("HH:mm:ss.SSSS"))} ${chalk.yellow("🔥")} ${message}`);
fs.appendFile(logFilePath, cleanChalkedMessage(message), "utf8", err => {
if (err) throw err;
});
};
exports.error = message => {
console.log(
`${chalk.magenta(moment().format("HH:mm:ss.SSSS"))} ${chalk.red("💀💀")} ${message} ${chalk.red("💀💀")}`
);
fs.appendFile(logFilePath, cleanChalkedMessage(message), "utf8", err => {
if (err) throw err;
});
};
exports.success = message => {
console.log(
`${chalk.magenta(moment().format("HH:mm:ss.SSSS"))} ${chalk.green("👌👏")} ${chalk.green(message)} ${chalk.green(
"√√"
)}`
);
fs.appendFile(logFilePath, cleanChalkedMessage(message), "utf8", err => {
if (err) throw err;
});
};
|
const bunyan = require('bunyan');
const bformat = require('bunyan-format');
const path = require('path');
const formatOut = bformat({ color: true });
const pathLog = path.resolve(__dirname, '..', 'logs.json');
/**
* the logger
* @param {string} _name - name that will be used for log traces
* @returns - the log object
*/
const log = (_name) => {
const _log = bunyan.createLogger({
name: _name,
streams: [
{ stream: formatOut },
{ path: pathLog },
],
serializers: {
req: bunyan.stdSerializers.req,
},
});
return _log;
};
module.exports = log;
|
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var util = require('util');
var stream = require('stream');
var repl = require('repl');
var argv = require('optimist').usage('Usage: dogescript <file>').argv;
var parser = require('../lib/parser');
var compile = require('../lib/compile');
if (argv._[0]) {
var file = fs.readFile(path.resolve(process.cwd(), argv._[0]), {encoding: 'utf-8'}, function (err, script) {
var output = compile(parser.parse(script.toString()));
process.stdout.write(output);
});
} else {
// streamy inheritance stuff
// boilerblate from the docs
function Stream () {
stream.Transform.call(this);
}
util.inherits(Stream, stream.Transform);
// see streams documentation
Stream.prototype._transform = function (chunk, encoding, callback) {
var script = compile(parser.parse(chunk.toString()));
var lines = script.split("\n");
for (var i = 0; i < lines.length; i++) {
// ignore empty lines
if (lines[i] !== '') this.push(lines[i] + '\n');
}
callback();
}
var ds = new Stream();
// pipe stdin through the dogescript translator to the repl
repl.start({
prompt : "DOGE> ",
input : ds,
output : process.stdout
});
// begin streaming stdin to the dg translator and repl
process.stdin.pipe(ds);
}
|
(function($, window) {
'use strict';
$.fn.sideIndex = function(opts) {
var $context = this,
debug = true,
// Array containing a reference to all the elements in the side index.
sideIndexElements = [],
currentRef = null,
// Structure of the side index
$sideIndexTemplate = $('<nav />', {'id': 'side-index'}).append($('<ul />')),
// Structure of each side index element
$indexElementTemplate = $('<li />', {'class': 'side-index-item'}).append($('<a />')),
// Structure of the selected index item indicator
$positionIndicatorTemplate = $('<div />', {'id': 'side-index-indicator'}),
// Plugin default values for optional parameters
defaults = {
// Top margin in pixels for the side index. Use it to prevent overlapping with a fixed topbar
indexTop: 100,
// Height pixel offset to apply when positioning the viewport to any of the selected positions
// Useful when there is a fixed topbar that can overlap the upper part of the selected section
targetTopOffset: 0
},
options;
/**
* Gets the information of all the indexable elements of the page @asyncnd returns it in an array.
*/
var getNavElements = function() {
var navElements = [],
$inexableElements;
// Get the data of all the indexable elements in the document.
$('[data-side-index]', $context).each(function() {
var indicatorText = $(this).data('sideIndexIndicator'),
indexText = $(this).data('sideIndex'),
id = $(this).attr('id');
navElements.push({
pos: $(this).offset().top,
text: indexText || id,
indicator: indicatorText || indexText || id,
ref: id
});
});
// Sort all the indexed elements by their position in the document
// Note that the order in the HTML document may noy correspond to the order in the screen!
navElements.sort(function(a, b) {
return a.pos - b.pos;
});
return navElements;
};
/**
* Build an array that contains a references to the elements in the side index.
* It will be used to detect the location of the finger when swiping over the side index.
*/
var buildIndexArray = function() {
var docOffset = $(window).scrollTop();
$('.side-index-item', $context).each(function() {
sideIndexElements.push({
pos: $(this).offset().top - docOffset,
obj: $(this)
});
});
if (debug) {
console.log("Side index elements:");
$.each(sideIndexElements, function() {
console.log(this.pos, this.obj.data('target'));
});
}
};
/**
* Build the side index DOM, appending an item for each nav element
*/
var buildSideIndex = function() {
var $sideIndex = $sideIndexTemplate.clone(),
$indexElement,
windowHeight = $(window).height(),
navElements = getNavElements(),
i;
for (i = 0; i < navElements.length; i++) {
$indexElement = $indexElementTemplate
.clone()
.data('target', navElements[i].ref)
.data('indicator', navElements[i].indicator)
.text(navElements[i].text);
$('ul', $sideIndex).append($indexElement);
}
// Set the size of the side index according to the given options
$sideIndex.css('height', (windowHeight + 30) + 'px');
$('ul', $sideIndex).css('height', (windowHeight - options.indexTop) + 'px');
$context.append($sideIndex);
buildIndexArray();
};
/**
* Show a marker that indicates which section is the user scrolling to
*/
var placeMarker = function(text) {
var $indicator = $positionIndicatorTemplate.clone();
$context.find('#side-index-indicator').remove();
$indicator.text(text);
$context.append($indicator);
};
/**
* Bring the viewport to the position specified by $sideIndexElement
*
* @param $sideIndexElement Element of the side index that stores the reference to the element to scroll to
* @param showMarker boolean Should I show a marker indicating the current position?
*/
var goToRef = function($sideIndexElement, showMarker) {
var target;
// Prevent scrolling to the same section
if (currentRef != $sideIndexElement.data('target')) {
currentRef = $sideIndexElement.data('target');
if (debug) {
console.log("Moving the viewport to ", $sideIndexElement.data('target'));
}
// Set the URL search part to the corresponding indexed section id.
if (window.history.replaceState) {
// If possible, replace the history state to prevent multiple "backs" to go to the previous page
window.history.replaceState(window.history.state, document.title, '#' + $sideIndexElement.data('target'));
} else {
window.location.hash = $sideIndexElement.data('target');
}
// Scroll to the appropriate section
target = $('#' + $sideIndexElement.data('target'));
window.scrollTo(0, target.offset().top + options.targetTopOffset);
if (showMarker) {
placeMarker($sideIndexElement.data('indicator'));
}
}
};
var bindEvents = function() {
$context
.on('touchstart', '#side-index', function(e) {
// Prevent scrolling the document if the swipe starts in the side index
e.preventDefault();
})
.on('touchmove', '#side-index', function(e) {
var y = e.originalEvent.touches[0].clientY,
i;
for (i = 0; i < sideIndexElements.length; i++) {
if (y < sideIndexElements[i].pos) {
break;
}
}
// If the finger is avobe the first index element, go to the first element
if (i === 0) {
i = 1;
}
if (debug) {
console.log("Finger at Y ", y);
console.log("Over position " + i, sideIndexElements[i - 1].obj.data('target'));
}
goToRef(sideIndexElements[i - 1].obj, true);
e.preventDefault();
})
.on('touchend', '#side-index', function() {
$context.find('#side-index-indicator').fadeOut('fast');
})
.on('click', '.side-index-item', function() {
// If a side index element is tapped, just go to the corresponding section
goToRef($(this), false);
});
};
options = $.extend({}, defaults, opts);
buildSideIndex();
bindEvents();
};
}(jQuery, window));
|
module.exports = {"NotoSansHebrew":{"bold":"NotoSansHebrew-Bold.ttf","normal":"NotoSansHebrew-Regular.ttf","italics":"NotoSansHebrew-Regular.ttf","bolditalics":"NotoSansHebrew-Bold.ttf"}};
|
/**! github.com/bfontaine/shortjs -- MIT license */
(function( root, factory ) {
if (typeof define == 'function' && define.amd) {
define(factory);
} else if (typeof exports == 'object') {
module.exports = factory();
} else {
root.short = factory();
}
})( this, function() {
"use strict";
var filters = [];
var short = function short( text, opts ) {
return short.filter( text, opts );
};
short.addFilter = function addFilter( pattern, fn ) {
filters.push([pattern, fn]);
};
short.filter = function filter( text, opts ) {
var len = filters.length,
i = 0,
f, res;
opts = opts || {};
for (; i<len; i++) {
f = filters[i];
if (f[0].test(text)) {
res = f[1](text, opts);
if (res !== false) {
text = res;
}
}
}
return text;
};
/* Builtin Filters */
// short numbers
short.addFilter(/^\d+(?:\.\d+)?$/, (function() {
var units = [
{ suffix: "P", factor: 1e15 },
{ suffix: "T", factor: 1e12 },
{ suffix: "G", factor: 1e9 },
{ suffix: "M", factor: 1e6 },
{ suffix: "k", factor: 1e3 },
],
unitsLen = units.length;
function roundOneDecimal( n ) {
return (0|(n * 10)) / 10;
}
return function( text, opts ) {
var n = +text,
unit;
if (isNaN(n)) {
return false;
}
for (var i=0; i<unitsLen; i++) {
unit = units[i];
if (n >= unit.factor) {
n = roundOneDecimal(n/unit.factor);
if (n%1 === 0 && opts.forcePoint) {
n = "" + n + ".0";
}
return "" + n + unit.suffix;
}
}
return "" + roundOneDecimal(n);
};
})());
return short;
});
|
// Modified from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
// on 7/10/2014
/**
* Apply the given function on each element in an array
* @param array
* @param callback called with (element, index, array)
*/
var forEach = function (array, callback) {
var k;
if (array == null) {
throw new TypeError(" this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(array);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as the this value and
// argument list containing kValue, k, and O.
callback.call(array, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
module.exports = forEach;
|
const webpack = require('webpack');
module.exports = {
entry: [
'./static/js/app.js',
],
output: {
path: __dirname + '/static/js/build/',
filename: 'bundle.min.js',
},
module: {
loaders: [
{ test: /\.jsx?$/, loaders: ['react-hot', 'babel-loader'], exclude: /node_modules/ },
],
},
plugins: [
new webpack.NoErrorsPlugin(),
// new webpack.optimize.UglifyJsPlugin({
// compress: { warnings: false },
// }),
],
};
|
const five = require('johnny-five');
const board = new five.Board();
board.on('ready', function () {
const motors = new five.Motors([
{ pins: { dir: 12, pwm: 11 }, invertPWM: true },
{ pins: { dir: 4, pwm: 5}, invertPWM: true }
]);
board.repl.inject({
motors: motors
});
});
|
/** @jsx React.DOM */
'use strict';
var React = require('react');
var superagent = require('superagent');
module.exports = React.createClass({
getInitialState: function() {
return {data: []};
},
componentWillMount: function() {
superagent.get('/stats')
.end(function(res) {
var data = {
remainingPercent: (res.body.remaining / res.body.cap * 100).toFixed(2),
remainingMb: (res.body.remaining / 1024 / 1024).toFixed(2),
cap: res.body.cap / 1024 / 1024
}
this.setState({data: data})
}.bind(this))
},
render: function() {
return (
<div className="stats pull-right">{this.state.data.remainingPercent}% ({this.state.data.remainingMb} of {this.state.data.cap} MB) remaining.</div>
);
}
});
|
import { call, isAuthError } from '../API'
import { getToken } from './SessionStorage'
export function getGroups() {
return new Promise((resolve) => {
chrome.storage.local.get({ 'group_items': {} }, (items) => {
resolve(items.group_items)
})
})
}
export function addGroup(item) {
return new Promise((resolve, reject) => {
if (item) {
getGroups().then((items) => {
let groups = items
groups[item.gid] = item
chrome.storage.local.set({ "group_items": groups }, () => {
resolve(groups)
})
})
} else {
reject({ error: 'item is undefined' })
}
})
}
export function fetchGroupByUrl(url) {
let shortName = url.match(/vk.com\/([\w\.]+)/)
return new Promise((resolve, reject) => {
if (shortName) {
let eventMatch = shortName[1].match(/event(\d+)/)
if (eventMatch) {
shortName = eventMatch
}
getToken().then((token) => {
fetchGroup(shortName[1], token)
.then((data) => {
if (!data.error) {
addGroup(data)
.then(resolve)
.catch(reject)
} else {
if (isAuthError(data)) {
reject({ error: 'Ошибка авторизации' })
} else {
reject({ error: 'Группа не найдена' })
}
}
})
})
} else {
reject({ error: 'Неверный формат ссылки' })
}
})
}
async function fetchGroup (name, accessToken) {
const response = await call('groups.getById', { group_id: name, access_token: accessToken })
if (response.error) {
return response
} else {
return normalizeGroup(response.response[0])
}
}
// Should standartize two API versions responses:
// gid, is_closed, name, photo, photo_big, photo_medium, screen_name, type
// id, is_closed, name, photo_50, photo_100, photo_200, screen_name, type
function normalizeGroup(data) {
return {
gid: `-${data['gid'] || data['id']}`,
is_closed: data['is_closed'],
name: data['name'],
photo: data['photo_50'] || data['photo'],
photo_big: data['photo_big'] || data['photo_200'],
photo_medium: data['photo_medium'] || data['photo_100'],
screen_name: data['screen_name'],
type: data['type']
}
}
export function refreshGroups(accessToken) {
getGroups().then((groups) => {
let refreshedGroups = {}
Object.keys(groups).forEach((key) => {
})
})
}
export function removeGroup(groupId) {
return new Promise((resolve, reject) => {
if (groupId) {
getGroups().then((items) => {
let groups = items
delete groups[groupId]
chrome.storage.local.set({ "group_items": groups }, () => {
resolve(groups)
})
})
} else {
reject({ error: 'item is undefined' })
}
})
}
|
App.Models.Board = Backbone.Model.extend({
paramRoot: 'board',
defaults: {
name: null
},
initialize: function (board) {
this.board = board;
this.initiatives = new App.Collections.Initiatives(
this.board.initiatives,
{
board_id: this.board.id
}
);
this.collection = this.initiatives;
}
});
|
class CenteredSprite extends Phaser.Sprite {
//initialization code in the constructor
constructor(game, key) {
super(game, game.world.centerX, game.world.centerY, key);
game.add.existing(this);
this.anchor.set(0.5);
}
update() {}
}
export default CenteredSprite;
|
module.exports = emitEvent;
function emitEvent(object, type, event) {
var onevent = "on" + type;
if (object[onevent]) {
object[onevent](event);
}
object.emitArg(type, event);
}
|
// Put your development configuration here.
//
// This is useful when using a separate API
// endpoint in development than in production.
//
// window.ENV.public_key = '123456'
window.ENV.api_url = 'http://localhost:3000/api'
//window.ENV.api_url = 'http://109.202.68.147:8041/api'
|
function Archive(command, params, item) {
if (command !== 'archive' || !Match.test(params, String)) {
return;
}
let channel = params.trim();
let room;
if (channel === '') {
room = RocketChat.models.Rooms.findOneById(item.rid);
channel = room.name;
} else {
channel = channel.replace('#', '');
room = RocketChat.models.Rooms.findOneByName(channel);
}
const user = Meteor.users.findOne(Meteor.userId());
if (!room) {
return RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
_id: Random.id(),
rid: item.rid,
ts: new Date(),
msg: TAPi18n.__('Channel_doesnt_exist', {
postProcess: 'sprintf',
sprintf: [channel],
}, user.language),
});
}
// You can not archive direct messages.
if (room.t === 'd') {
return;
}
if (room.archived) {
RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
_id: Random.id(),
rid: item.rid,
ts: new Date(),
msg: TAPi18n.__('Duplicate_archived_channel_name', {
postProcess: 'sprintf',
sprintf: [channel],
}, user.language),
});
return;
}
Meteor.call('archiveRoom', room._id);
RocketChat.models.Messages.createRoomArchivedByRoomIdAndUser(room._id, Meteor.user());
RocketChat.Notifications.notifyUser(Meteor.userId(), 'message', {
_id: Random.id(),
rid: item.rid,
ts: new Date(),
msg: TAPi18n.__('Channel_Archived', {
postProcess: 'sprintf',
sprintf: [channel],
}, user.language),
});
return Archive;
}
RocketChat.slashCommands.add('archive', Archive, {
description: 'Archive',
params: '#channel',
});
|
exports.Configuration = {
apiEndpoint: 'https://brookelaw.prismic.io/api',
// -- Access token if the Master is not open
accessToken: 'MC5VdHJBWGdFQUFENWZrQ0ZH.WO-_ve-_ve-_vX1jJe-_ve-_vTcgYA5377-977-9YO-_ve-_ve-_vUzvv73vv73vv73vv71t77-977-977-9Vu-_ve-_vQ',
// OAuth
clientId: 'UtrAXgEAACdfkCFF',
clientSecret: 'e5e9335d42ba94973440c67b844f87c8',
// -- Links resolution rules
linkResolver: function(ctx, doc) {
if (doc.isBroken) return false;
return '/documents/' + doc.id + '/' + doc.slug + (ctx.maybeRef ? '?ref=' + ctx.maybeRef : '');
}
};
|
;(function(){
// CommonJS require()
function require(p){
var path = require.resolve(p)
, mod = require.modules[path];
if (!mod) throw new Error('failed to require "' + p + '"');
if (!mod.exports) {
mod.exports = {};
mod.call(mod.exports, mod, mod.exports, require.relative(path));
}
return mod.exports;
}
require.modules = {};
require.resolve = function (path){
var orig = path
, reg = path + '.js'
, index = path + '/index.js';
return require.modules[reg] && reg
|| require.modules[index] && index
|| orig;
};
require.register = function (path, fn){
require.modules[path] = fn;
};
require.relative = function (parent) {
return function(p){
if ('.' != p.charAt(0)) return require(p);
var path = parent.split('/')
, segs = p.split('/');
path.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if ('..' == seg) path.pop();
else if ('.' != seg) path.push(seg);
}
return require(path.join('/'));
};
};
require.register("browser/debug.js", function(module, exports, require){
module.exports = function(type){
return function(){
}
};
}); // module: browser/debug.js
require.register("browser/diff.js", function(module, exports, require){
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
var JsDiff = (function() {
/*jshint maxparams: 5*/
function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) };
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&');
n = n.replace(/</g, '<');
n = n.replace(/>/g, '>');
n = n.replace(/"/g, '"');
return n;
}
var Diff = function(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
};
Diff.prototype = {
diff: function(oldString, newString) {
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return [{ value: newString }];
}
if (!newString) {
return [{ value: oldString, removed: true }];
}
if (!oldString) {
return [{ value: newString, added: true }];
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }];
// Seed editLength = 0
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
return bestPath[0].components;
}
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
var basePath;
var addPath = bestPath[diagonalPath-1],
removePath = bestPath[diagonalPath+1];
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined;
}
var canAdd = addPath && addPath.newPos+1 < newLen;
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
} else {
basePath = clonePath(addPath);
basePath.newPos++;
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
}
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
return basePath.components;
} else {
bestPath[diagonalPath] = basePath;
}
}
}
},
pushComponent: function(components, value, added, removed) {
var last = components[components.length-1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length-1] =
{value: this.join(last.value, value), added: added, removed: removed };
} else {
components.push({value: value, added: added, removed: removed });
}
},
extractCommon: function(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
newPos++;
oldPos++;
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
}
basePath.newPos = newPos;
return oldPos;
},
equals: function(left, right) {
var reWhitespace = /\S/;
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
return true;
} else {
return left === right;
}
},
join: function(left, right) {
return left + right;
},
tokenize: function(value) {
return value;
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
LineDiff.tokenize = function(value) {
return value.split(/^/m);
};
return {
Diff: Diff,
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
ret.push('Index: ' + fileName);
ret.push('===================================================================');
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
}
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
function contextLines(lines) {
return lines.map(function(entry) { return ' ' + entry; });
}
function eofNL(curRange, i, current) {
var last = diff[diff.length-2],
isLast = i === diff.length-2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
// Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
var prev = diff[i-1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
eofNL(curRange, i, current);
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0; newRangeStart = 0; curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
applyPatch: function(oldStr, uniDiff) {
var diffstr = uniDiff.split('\n');
var diff = [];
var remEOFNL = false,
addEOFNL = false;
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
if(diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({
start:meh[3],
oldlength:meh[2],
oldlines:[],
newlength:meh[4],
newlines:[]
});
} else if(diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') {
remEOFNL = true;
} else if(diffstr[i-1][0] === '-') {
addEOFNL = true;
}
}
}
var str = oldStr.split('\n');
for (var i = diff.length - 1; i >= 0; i--) {
var d = diff[i];
for (var j = 0; j < d.oldlength; j++) {
if(str[d.start-1+j] !== d.oldlines[j]) {
return false;
}
}
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
}
if (remEOFNL) {
while (!str[str.length-1]) {
str.pop();
}
} else if (addEOFNL) {
str.push('');
}
return str.join('\n');
},
convertChangesToXML: function(changes){
var ret = [];
for ( var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) {
ret.push('</ins>');
} else if (change.removed) {
ret.push('</del>');
}
}
return ret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){
var ret = [], change;
for ( var i = 0; i < changes.length; i++) {
change = changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
}
return ret;
}
};
})();
if (typeof module !== 'undefined') {
module.exports = JsDiff;
}
}); // module: browser/diff.js
require.register("browser/events.js", function(module, exports, require){
/**
* Module exports.
*/
exports.EventEmitter = EventEmitter;
/**
* Check if `obj` is an array.
*/
function isArray(obj) {
return '[object Array]' == {}.toString.call(obj);
}
/**
* Event emitter constructor.
*
* @api public
*/
function EventEmitter(){};
/**
* Adds a listener.
*
* @api public
*/
EventEmitter.prototype.on = function (name, fn) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = fn;
} else if (isArray(this.$events[name])) {
this.$events[name].push(fn);
} else {
this.$events[name] = [this.$events[name], fn];
}
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
/**
* Adds a volatile listener.
*
* @api public
*/
EventEmitter.prototype.once = function (name, fn) {
var self = this;
function on () {
self.removeListener(name, on);
fn.apply(this, arguments);
};
on.listener = fn;
this.on(name, on);
return this;
};
/**
* Removes a listener.
*
* @api public
*/
EventEmitter.prototype.removeListener = function (name, fn) {
if (this.$events && this.$events[name]) {
var list = this.$events[name];
if (isArray(list)) {
var pos = -1;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
pos = i;
break;
}
}
if (pos < 0) {
return this;
}
list.splice(pos, 1);
if (!list.length) {
delete this.$events[name];
}
} else if (list === fn || (list.listener && list.listener === fn)) {
delete this.$events[name];
}
}
return this;
};
/**
* Removes all listeners for an event.
*
* @api public
*/
EventEmitter.prototype.removeAllListeners = function (name) {
if (name === undefined) {
this.$events = {};
return this;
}
if (this.$events && this.$events[name]) {
this.$events[name] = null;
}
return this;
};
/**
* Gets all listeners for a certain event.
*
* @api public
*/
EventEmitter.prototype.listeners = function (name) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = [];
}
if (!isArray(this.$events[name])) {
this.$events[name] = [this.$events[name]];
}
return this.$events[name];
};
/**
* Emits an event.
*
* @api public
*/
EventEmitter.prototype.emit = function (name) {
if (!this.$events) {
return false;
}
var handler = this.$events[name];
if (!handler) {
return false;
}
var args = [].slice.call(arguments, 1);
if ('function' == typeof handler) {
handler.apply(this, args);
} else if (isArray(handler)) {
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);
}
} else {
return false;
}
return true;
};
}); // module: browser/events.js
require.register("browser/fs.js", function(module, exports, require){
}); // module: browser/fs.js
require.register("browser/path.js", function(module, exports, require){
}); // module: browser/path.js
require.register("browser/progress.js", function(module, exports, require){
/**
* Expose `Progress`.
*/
module.exports = Progress;
/**
* Initialize a new `Progress` indicator.
*/
function Progress() {
this.percent = 0;
this.size(0);
this.fontSize(11);
this.font('helvetica, arial, sans-serif');
}
/**
* Set progress size to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.size = function(n){
this._size = n;
return this;
};
/**
* Set text to `str`.
*
* @param {String} str
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.text = function(str){
this._text = str;
return this;
};
/**
* Set font size to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
* @api public
*/
Progress.prototype.fontSize = function(n){
this._fontSize = n;
return this;
};
/**
* Set font `family`.
*
* @param {String} family
* @return {Progress} for chaining
*/
Progress.prototype.font = function(family){
this._font = family;
return this;
};
/**
* Update percentage to `n`.
*
* @param {Number} n
* @return {Progress} for chaining
*/
Progress.prototype.update = function(n){
this.percent = n;
return this;
};
/**
* Draw on `ctx`.
*
* @param {CanvasRenderingContext2d} ctx
* @return {Progress} for chaining
*/
Progress.prototype.draw = function(ctx){
var percent = Math.min(this.percent, 100)
, size = this._size
, half = size / 2
, x = half
, y = half
, rad = half - 1
, fontSize = this._fontSize;
ctx.font = fontSize + 'px ' + this._font;
var angle = Math.PI * 2 * (percent / 100);
ctx.clearRect(0, 0, size, size);
// outer circle
ctx.strokeStyle = '#9f9f9f';
ctx.beginPath();
ctx.arc(x, y, rad, 0, angle, false);
ctx.stroke();
// inner circle
ctx.strokeStyle = '#eee';
ctx.beginPath();
ctx.arc(x, y, rad - 1, 0, angle, true);
ctx.stroke();
// text
var text = this._text || (percent | 0) + '%'
, w = ctx.measureText(text).width;
ctx.fillText(
text
, x - w / 2 + 1
, y + fontSize / 2 - 1);
return this;
};
}); // module: browser/progress.js
require.register("browser/tty.js", function(module, exports, require){
exports.isatty = function(){
return true;
};
exports.getWindowSize = function(){
if ('innerHeight' in global) {
return [global.innerHeight, global.innerWidth];
} else {
// In a Web Worker, the DOM Window is not available.
return [640, 480];
}
};
}); // module: browser/tty.js
require.register("context.js", function(module, exports, require){
/**
* Expose `Context`.
*/
module.exports = Context;
/**
* Initialize a new `Context`.
*
* @api private
*/
function Context(){}
/**
* Set or get the context `Runnable` to `runnable`.
*
* @param {Runnable} runnable
* @return {Context}
* @api private
*/
Context.prototype.runnable = function(runnable){
if (0 == arguments.length) return this._runnable;
this.test = this._runnable = runnable;
return this;
};
/**
* Set test timeout `ms`.
*
* @param {Number} ms
* @return {Context} self
* @api private
*/
Context.prototype.timeout = function(ms){
this.runnable().timeout(ms);
return this;
};
/**
* Set test slowness threshold `ms`.
*
* @param {Number} ms
* @return {Context} self
* @api private
*/
Context.prototype.slow = function(ms){
this.runnable().slow(ms);
return this;
};
/**
* Inspect the context void of `._runnable`.
*
* @return {String}
* @api private
*/
Context.prototype.inspect = function(){
return JSON.stringify(this, function(key, val){
if ('_runnable' == key) return;
if ('test' == key) return;
return val;
}, 2);
};
}); // module: context.js
require.register("hook.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Runnable = require('./runnable');
/**
* Expose `Hook`.
*/
module.exports = Hook;
/**
* Initialize a new `Hook` with the given `title` and callback `fn`.
*
* @param {String} title
* @param {Function} fn
* @api private
*/
function Hook(title, fn) {
Runnable.call(this, title, fn);
this.type = 'hook';
}
/**
* Inherit from `Runnable.prototype`.
*/
function F(){};
F.prototype = Runnable.prototype;
Hook.prototype = new F;
Hook.prototype.constructor = Hook;
/**
* Get or set the test `err`.
*
* @param {Error} err
* @return {Error}
* @api public
*/
Hook.prototype.error = function(err){
if (0 == arguments.length) {
var err = this._error;
this._error = null;
return err;
}
this._error = err;
};
}); // module: hook.js
require.register("interfaces/bdd.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test')
, utils = require('../utils');
/**
* BDD-style interface:
*
* describe('Array', function(){
* describe('#indexOf()', function(){
* it('should return -1 when not present', function(){
*
* });
*
* it('should return the index when present', function(){
*
* });
* });
* });
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('pre-require', function(context, file, mocha){
/**
* Execute before running tests.
*/
context.before = function(fn){
suites[0].beforeAll(fn);
};
/**
* Execute after running tests.
*/
context.after = function(fn){
suites[0].afterAll(fn);
};
/**
* Execute before each test case.
*/
context.beforeEach = function(fn){
suites[0].beforeEach(fn);
};
/**
* Execute after each test case.
*/
context.afterEach = function(fn){
suites[0].afterEach(fn);
};
/**
* Describe a "suite" with the given `title`
* and callback `fn` containing nested suites
* and/or tests.
*/
context.describe = context.context = function(title, fn){
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
fn.call(suite);
suites.shift();
return suite;
};
/**
* Pending describe.
*/
context.xdescribe =
context.xcontext =
context.describe.skip = function(title, fn){
var suite = Suite.create(suites[0], title);
suite.pending = true;
suites.unshift(suite);
fn.call(suite);
suites.shift();
};
/**
* Exclusive suite.
*/
context.describe.only = function(title, fn){
var suite = context.describe(title, fn);
mocha.grep(suite.fullTitle());
};
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.it = context.specify = function(title, fn){
var suite = suites[0];
if (suite.pending) var fn = null;
var test = new Test(title, fn);
suite.addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.it.only = function(title, fn){
var test = context.it(title, fn);
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
mocha.grep(new RegExp(reString));
};
/**
* Pending test case.
*/
context.xit =
context.xspecify =
context.it.skip = function(title){
context.it(title);
};
});
};
}); // module: interfaces/bdd.js
require.register("interfaces/exports.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test');
/**
* TDD-style interface:
*
* exports.Array = {
* '#indexOf()': {
* 'should return -1 when the value is not present': function(){
*
* },
*
* 'should return the correct index when the value is present': function(){
*
* }
* }
* };
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('require', visit);
function visit(obj) {
var suite;
for (var key in obj) {
if ('function' == typeof obj[key]) {
var fn = obj[key];
switch (key) {
case 'before':
suites[0].beforeAll(fn);
break;
case 'after':
suites[0].afterAll(fn);
break;
case 'beforeEach':
suites[0].beforeEach(fn);
break;
case 'afterEach':
suites[0].afterEach(fn);
break;
default:
suites[0].addTest(new Test(key, fn));
}
} else {
var suite = Suite.create(suites[0], key);
suites.unshift(suite);
visit(obj[key]);
suites.shift();
}
}
}
};
}); // module: interfaces/exports.js
require.register("interfaces/index.js", function(module, exports, require){
exports.bdd = require('./bdd');
exports.tdd = require('./tdd');
exports.qunit = require('./qunit');
exports.exports = require('./exports');
}); // module: interfaces/index.js
require.register("interfaces/qunit.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test')
, utils = require('../utils');
/**
* QUnit-style interface:
*
* suite('Array');
*
* test('#length', function(){
* var arr = [1,2,3];
* ok(arr.length == 3);
* });
*
* test('#indexOf()', function(){
* var arr = [1,2,3];
* ok(arr.indexOf(1) == 0);
* ok(arr.indexOf(2) == 1);
* ok(arr.indexOf(3) == 2);
* });
*
* suite('String');
*
* test('#length', function(){
* ok('foo'.length == 3);
* });
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('pre-require', function(context, file, mocha){
/**
* Execute before running tests.
*/
context.before = function(fn){
suites[0].beforeAll(fn);
};
/**
* Execute after running tests.
*/
context.after = function(fn){
suites[0].afterAll(fn);
};
/**
* Execute before each test case.
*/
context.beforeEach = function(fn){
suites[0].beforeEach(fn);
};
/**
* Execute after each test case.
*/
context.afterEach = function(fn){
suites[0].afterEach(fn);
};
/**
* Describe a "suite" with the given `title`.
*/
context.suite = function(title){
if (suites.length > 1) suites.shift();
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
return suite;
};
/**
* Exclusive test-case.
*/
context.suite.only = function(title, fn){
var suite = context.suite(title, fn);
mocha.grep(suite.fullTitle());
};
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.test = function(title, fn){
var test = new Test(title, fn);
suites[0].addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.test.only = function(title, fn){
var test = context.test(title, fn);
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
mocha.grep(new RegExp(reString));
};
/**
* Pending test case.
*/
context.test.skip = function(title){
context.test(title);
};
});
};
}); // module: interfaces/qunit.js
require.register("interfaces/tdd.js", function(module, exports, require){
/**
* Module dependencies.
*/
var Suite = require('../suite')
, Test = require('../test')
, utils = require('../utils');;
/**
* TDD-style interface:
*
* suite('Array', function(){
* suite('#indexOf()', function(){
* suiteSetup(function(){
*
* });
*
* test('should return -1 when not present', function(){
*
* });
*
* test('should return the index when present', function(){
*
* });
*
* suiteTeardown(function(){
*
* });
* });
* });
*
*/
module.exports = function(suite){
var suites = [suite];
suite.on('pre-require', function(context, file, mocha){
/**
* Execute before each test case.
*/
context.setup = function(fn){
suites[0].beforeEach(fn);
};
/**
* Execute after each test case.
*/
context.teardown = function(fn){
suites[0].afterEach(fn);
};
/**
* Execute before the suite.
*/
context.suiteSetup = function(fn){
suites[0].beforeAll(fn);
};
/**
* Execute after the suite.
*/
context.suiteTeardown = function(fn){
suites[0].afterAll(fn);
};
/**
* Describe a "suite" with the given `title`
* and callback `fn` containing nested suites
* and/or tests.
*/
context.suite = function(title, fn){
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
fn.call(suite);
suites.shift();
return suite;
};
/**
* Pending suite.
*/
context.suite.skip = function(title, fn) {
var suite = Suite.create(suites[0], title);
suite.pending = true;
suites.unshift(suite);
fn.call(suite);
suites.shift();
};
/**
* Exclusive test-case.
*/
context.suite.only = function(title, fn){
var suite = context.suite(title, fn);
mocha.grep(suite.fullTitle());
};
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.test = function(title, fn){
var suite = suites[0];
if (suite.pending) var fn = null;
var test = new Test(title, fn);
suite.addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.test.only = function(title, fn){
var test = context.test(title, fn);
var reString = '^' + utils.escapeRegexp(test.fullTitle()) + '$';
mocha.grep(new RegExp(reString));
};
/**
* Pending test case.
*/
context.test.skip = function(title){
context.test(title);
};
});
};
}); // module: interfaces/tdd.js
require.register("mocha.js", function(module, exports, require){
/*!
* mocha
* Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var path = require('browser/path')
, utils = require('./utils');
/**
* Expose `Mocha`.
*/
exports = module.exports = Mocha;
/**
* Expose internals.
*/
exports.utils = utils;
exports.interfaces = require('./interfaces');
exports.reporters = require('./reporters');
exports.Runnable = require('./runnable');
exports.Context = require('./context');
exports.Runner = require('./runner');
exports.Suite = require('./suite');
exports.Hook = require('./hook');
exports.Test = require('./test');
/**
* Return image `name` path.
*
* @param {String} name
* @return {String}
* @api private
*/
function image(name) {
return __dirname + '/../images/' + name + '.png';
}
/**
* Setup mocha with `options`.
*
* Options:
*
* - `ui` name "bdd", "tdd", "exports" etc
* - `reporter` reporter instance, defaults to `mocha.reporters.Dot`
* - `globals` array of accepted globals
* - `timeout` timeout in milliseconds
* - `bail` bail on the first test failure
* - `slow` milliseconds to wait before considering a test slow
* - `ignoreLeaks` ignore global leaks
* - `grep` string or regexp to filter tests with
*
* @param {Object} options
* @api public
*/
function Mocha(options) {
options = options || {};
this.files = [];
this.options = options;
this.grep(options.grep);
this.suite = new exports.Suite('', new exports.Context);
this.ui(options.ui);
this.bail(options.bail);
this.reporter(options.reporter);
if (null != options.timeout) this.timeout(options.timeout);
if (options.slow) this.slow(options.slow);
}
/**
* Enable or disable bailing on the first failure.
*
* @param {Boolean} [bail]
* @api public
*/
Mocha.prototype.bail = function(bail){
if (0 == arguments.length) bail = true;
this.suite.bail(bail);
return this;
};
/**
* Add test `file`.
*
* @param {String} file
* @api public
*/
Mocha.prototype.addFile = function(file){
this.files.push(file);
return this;
};
/**
* Set reporter to `reporter`, defaults to "dot".
*
* @param {String|Function} reporter name or constructor
* @api public
*/
Mocha.prototype.reporter = function(reporter){
if ('function' == typeof reporter) {
this._reporter = reporter;
} else {
reporter = reporter || 'dot';
try {
this._reporter = require('./reporters/' + reporter);
} catch (err) {
this._reporter = require(reporter);
}
if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"');
}
return this;
};
/**
* Set test UI `name`, defaults to "bdd".
*
* @param {String} bdd
* @api public
*/
Mocha.prototype.ui = function(name){
name = name || 'bdd';
this._ui = exports.interfaces[name];
if (!this._ui) throw new Error('invalid interface "' + name + '"');
this._ui = this._ui(this.suite);
return this;
};
/**
* Load registered files.
*
* @api private
*/
Mocha.prototype.loadFiles = function(fn){
var self = this;
var suite = this.suite;
var pending = this.files.length;
this.files.forEach(function(file){
file = path.resolve(file);
suite.emit('pre-require', global, file, self);
suite.emit('require', require(file), file, self);
suite.emit('post-require', global, file, self);
--pending || (fn && fn());
});
};
/**
* Enable growl support.
*
* @api private
*/
Mocha.prototype._growl = function(runner, reporter) {
var notify = require('growl');
runner.on('end', function(){
var stats = reporter.stats;
if (stats.failures) {
var msg = stats.failures + ' of ' + runner.total + ' tests failed';
notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
} else {
notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
name: 'mocha'
, title: 'Passed'
, image: image('ok')
});
}
});
};
/**
* Add regexp to grep, if `re` is a string it is escaped.
*
* @param {RegExp|String} re
* @return {Mocha}
* @api public
*/
Mocha.prototype.grep = function(re){
this.options.grep = 'string' == typeof re
? new RegExp(utils.escapeRegexp(re))
: re;
return this;
};
/**
* Invert `.grep()` matches.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.invert = function(){
this.options.invert = true;
return this;
};
/**
* Ignore global leaks.
*
* @param {Boolean} ignore
* @return {Mocha}
* @api public
*/
Mocha.prototype.ignoreLeaks = function(ignore){
this.options.ignoreLeaks = !!ignore;
return this;
};
/**
* Enable global leak checking.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.checkLeaks = function(){
this.options.ignoreLeaks = false;
return this;
};
/**
* Enable growl support.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.growl = function(){
this.options.growl = true;
return this;
};
/**
* Ignore `globals` array or string.
*
* @param {Array|String} globals
* @return {Mocha}
* @api public
*/
Mocha.prototype.globals = function(globals){
this.options.globals = (this.options.globals || []).concat(globals);
return this;
};
/**
* Set the timeout in milliseconds.
*
* @param {Number} timeout
* @return {Mocha}
* @api public
*/
Mocha.prototype.timeout = function(timeout){
this.suite.timeout(timeout);
return this;
};
/**
* Set slowness threshold in milliseconds.
*
* @param {Number} slow
* @return {Mocha}
* @api public
*/
Mocha.prototype.slow = function(slow){
this.suite.slow(slow);
return this;
};
/**
* Makes all tests async (accepting a callback)
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.asyncOnly = function(){
this.options.asyncOnly = true;
return this;
};
/**
* Run tests and invoke `fn()` when complete.
*
* @param {Function} fn
* @return {Runner}
* @api public
*/
Mocha.prototype.run = function(fn){
if (this.files.length) this.loadFiles();
var suite = this.suite;
var options = this.options;
var runner = new exports.Runner(suite);
var reporter = new this._reporter(runner);
runner.ignoreLeaks = false !== options.ignoreLeaks;
runner.asyncOnly = options.asyncOnly;
if (options.grep) runner.grep(options.grep, options.invert);
if (options.globals) runner.globals(options.globals);
if (options.growl) this._growl(runner, reporter);
return runner.run(fn);
};
}); // modu
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({"dijit/nls/loading":{loadingState:"\u30ed\u30fc\u30c9\u4e2d...",errorState:"\u30a8\u30e9\u30fc\u304c\u767a\u751f\u3057\u307e\u3057\u305f\u3002",_localized:{}},"dijit/nls/common":{buttonOk:"OK",buttonCancel:"\u30ad\u30e3\u30f3\u30bb\u30eb",buttonSave:"\u4fdd\u5b58",itemClose:"\u9589\u3058\u308b",_localized:{}},"esri/identity/nls/identity":{lblItem:"\u30a2\u30a4\u30c6\u30e0",title:"\u30b5\u30a4\u30f3 \u30a4\u30f3",info:"{server} {resource} \u306e\u30a2\u30a4\u30c6\u30e0\u306b\u30a2\u30af\u30bb\u30b9\u3059\u308b\u306b\u306f\u30b5\u30a4\u30f3 \u30a4\u30f3\u3057\u3066\u304f\u3060\u3055\u3044",
oAuthInfo:"\u7d9a\u884c\u3059\u308b\u306b\u306f\u3001\u30b5\u30a4\u30f3 \u30a4\u30f3\u3057\u3066\u304f\u3060\u3055\u3044\u3002",lblUser:"\u30e6\u30fc\u30b6\u30fc\u540d:",lblPwd:"\u30d1\u30b9\u30ef\u30fc\u30c9:",lblOk:"OK",lblSigning:"\u30b5\u30a4\u30f3 \u30a4\u30f3\u3057\u3066\u3044\u307e\u3059...",lblCancel:"\u30ad\u30e3\u30f3\u30bb\u30eb",errorMsg:"\u30e6\u30fc\u30b6\u30fc\u540d\u307e\u305f\u306f\u30d1\u30b9\u30ef\u30fc\u30c9\u304c\u7121\u52b9\u3067\u3059\u3002\u3082\u3046\u4e00\u5ea6\u3084\u308a\u76f4\u3057\u3066\u304f\u3060\u3055\u3044\u3002",
invalidUser:"\u5165\u529b\u3057\u305f\u30e6\u30fc\u30b6\u30fc\u540d\u307e\u305f\u306f\u30d1\u30b9\u30ef\u30fc\u30c9\u304c\u6b63\u3057\u304f\u3042\u308a\u307e\u305b\u3093\u3002",forbidden:"\u30e6\u30fc\u30b6\u30fc\u540d\u3068\u30d1\u30b9\u30ef\u30fc\u30c9\u306f\u6709\u52b9\u3067\u3059\u304c\u3001\u3053\u306e\u30ea\u30bd\u30fc\u30b9\u3078\u306e\u30a2\u30af\u30bb\u30b9\u6a29\u304c\u3042\u308a\u307e\u305b\u3093\u3002",noAuthService:"\u8a8d\u8a3c\u30b5\u30fc\u30d3\u30b9\u306b\u30a2\u30af\u30bb\u30b9\u3067\u304d\u307e\u305b\u3093\u3002",
_localized:{}},"dijit/form/nls/validate":{invalidMessage:"\u5165\u529b\u3057\u305f\u5024\u306f\u7121\u52b9\u3067\u3059\u3002",missingMessage:"\u3053\u306e\u5024\u306f\u5fc5\u9808\u3067\u3059\u3002",rangeMessage:"\u3053\u306e\u5024\u306f\u7bc4\u56f2\u5916\u3067\u3059\u3002",_localized:{}}});
|
"use strict"
const {T} = require(`../readFormat`)
module.exports = {
start: T.u16,
finish: T.u16,
delay: T.u16,
mode: T.u16,
}
|
import React from 'react';
import { mount } from 'enzyme';
import FontAwesome from 'react-fontawesome';
import LoadingPanel from '../index';
describe('<LoadingPanel />', () => {
it('should render the LoadingPanel component', () => {
const renderedComponent = mount(
<LoadingPanel />
);
expect(renderedComponent.contains(<FontAwesome name="gear" size="3x" spin />)).toBe(true);
});
});
|
var searchData=
[
['quantity',['Quantity',['../class_point85_1_1_caliper_1_1_unit_of_measure_1_1_quantity.html',1,'Point85.Caliper.UnitOfMeasure.Quantity'],['../class_point85_1_1_caliper_1_1_unit_of_measure_1_1_quantity.html#a258f7709c96a0a8987a567103dbfc4f0',1,'Point85.Caliper.UnitOfMeasure.Quantity.Quantity()'],['../class_point85_1_1_caliper_1_1_unit_of_measure_1_1_quantity.html#adc36ed9ecddbcf78a272b49a4f787aba',1,'Point85.Caliper.UnitOfMeasure.Quantity.Quantity(double amount, UnitOfMeasure uom)'],['../class_point85_1_1_caliper_1_1_unit_of_measure_1_1_quantity.html#a3f90cb724d9fff3d2fb29065e7befe48',1,'Point85.Caliper.UnitOfMeasure.Quantity.Quantity(double amount, Prefix prefix, Unit unit)'],['../class_point85_1_1_caliper_1_1_unit_of_measure_1_1_quantity.html#a3e8321aba3c9a800ee73c4a73af22a5d',1,'Point85.Caliper.UnitOfMeasure.Quantity.Quantity(double amount, Unit unit)']]]
];
|
var Marionette = require('backbone.marionette');
module.exports = VideoDetailsView = Marionette.ItemView.extend({
template: require('../../templates/video_details.hbs'),
events: {
'click a.back': 'goBack',
'click a.delete': 'deleteVideo'
},
goBack: function(e) {
e.preventDefault();
window.App.controller.home();
},
deleteVideo: function(e) {
e.preventDefault();
console.log('Deleting video');
window.App.data.videos.remove(this.model);
// this will actually send a DELETE to the server:
this.model.destroy();
window.App.controller.home();
}
});
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './NotFound.scss';
class NotFound extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
const { title } = this.props;
return (
<div>
<section className="hero is-danger is-fullheight">
<div className="hero-body">
<div className="container has-text-centered">
<h1 className="title is-1">{title}</h1>
</div>
</div>
</section>
</div>
);
}
}
export default withStyles(s)(NotFound);
|
Template.futureUsage.helpers({
capitalize: function (str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
});
Template.futureUsage.events({
//add your events here
});
Template.futureUsage.onCreated(function () {
//add your statement here
});
Template.futureUsage.onRendered(function () {
});
Template.futureUsage.onDestroyed(function () {
//add your statement here
});
|
var maxAccuracy = 100;
var watchL,watchC;
var meter2feet = 3.28084;
var feet2mile = 5280;
$(function(){
if ("geolocation" in navigator){
function iOSversion() {
if (/iP(hone|od|ad)/.test(navigator.platform)) {
var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
}
}
ver = iOSversion();
if(ver != undefined && ver[0]==12 && ver[1]==2){
msg = '<br/>Please allow Motion & Orientation Access in Settings > Safari for the compass to work';
} else {
msg = '<br/>Compass is not available on your device.<br/><br/>You can use the QR code to open this page on your mobile.<br/><img src="https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=https://geohashing.info/mobile/'+date+'/'+graticule+'&choe=UTF-8" />';
}
functional = true;
Compass.noSupport(function () {
$('#compass').html(msg);
functional = false;
});
if(functional){
initCompass();
}
} else {
$('#compass').html('<br/>Geolocation is not available on your device');
}
});
function initCompass(){
Compass.needGPS(function () {
$('#compass').html('<br/>GPS signal needed to get compass direction');
}).needMove(function () {
$('#compass').html('<br/>Please move to get orientation');
}).init(function () {
$('#compass').html('<br/><div id="arrow"><div></div></div>');
getHash();
watchL = setInterval(doWatch, 1000);
watchC = Compass.watch(function (angle) {
deviceHeading = angle;
setCompass();
});
});
}
var hash = null;
var loc = null;
var deviceHeading = 0;
var bearing = 0;
var accuracy = 999;
function getHash(){
$.getJSON(
'//data.geohashing.info/hash/'+date+'/'+graticule+'.json',
function(json){
hash = LatLon(json.lat, json.lng);
}
);
}
function getLocation(){
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(function(position){
loc = LatLon(position.coords.latitude, position.coords.longitude);
$('#accuracy').text(position.coords.accuracy + ' m / ' + (position.coords.accuracy*meter2feet).toFixed(0) + ' ft');
accuracy = position.coords.accuracy.toFixed(0);
if(accuracy > maxAccuracy){
$('#accuracy').addClass('low');
} else {
$('#accuracy').removeClass('low');
}
},function(){},options);
}
function setCompass(){
heading = 360-deviceHeading+bearing;
$('#arrow').css('-moz-transform', 'rotate('+heading+'deg)');
$('#arrow').css('-webkit-transform', 'rotate('+heading+'deg)');
$('#arrow').css('-o-transform', 'rotate('+heading+'deg)');
$('#arrow').css('-ms-transform', 'rotate('+heading+'deg)');
}
function doWatch(){
getLocation();
if(hash !== null && loc !== null){
$('#compass').show();
dist = loc.distanceTo(hash);
unit = 'm';
bearing = loc.bearingTo(hash);
if(dist < accuracy && accuracy < maxAccuracy){
$('#compass').addClass('reached');
$('#status').show();
var now = new Date();
$('#status').html('<h2>Congratulations!</h2><p>You have reached the<br/><br/><strong>'+date+' '+graticule+'</strong><br/><br/> hash on</p><p>'+now.toLocaleString()+'</p>');
} else {
$('#compass').removeClass('reached');
$('#status').hide();
}
var dist2 = dist*meter2feet;
if(dist > 9999){
dist = dist/1000;
unit = 'km';
}
unit2 = 'ft'
if(dist2 > feet2mile){
dist2 = dist2/feet2mile;
unit2 = 'mi';
}
$('#distance').text(dist.toFixed(2)+ ' ' + unit + ' / ' + dist2.toFixed(2)+' '+unit2);
}
}
|
(function() {
'use strict';
angular
.module('uniConnectApp')
.factory('Principal', Principal);
Principal.$inject = ['$q', 'Account'];
function Principal ($q, Account) {
var _identity,
_authenticated = false;
var service = {
authenticate: authenticate,
hasAnyAuthority: hasAnyAuthority,
hasAuthority: hasAuthority,
identity: identity,
isAuthenticated: isAuthenticated,
isIdentityResolved: isIdentityResolved
};
return service;
function authenticate (identity) {
_identity = identity;
_authenticated = identity !== null;
}
function hasAnyAuthority (authorities) {
if (!_authenticated || !_identity || !_identity.authorities) {
return false;
}
for (var i = 0; i < authorities.length; i++) {
if (_identity.authorities.indexOf(authorities[i]) !== -1) {
return true;
}
}
return false;
}
function hasAuthority (authority) {
if (!_authenticated) {
return $q.when(false);
}
return this.identity().then(function(_id) {
return _id.authorities && _id.authorities.indexOf(authority) !== -1;
}, function(){
return false;
});
}
function identity (force) {
var deferred = $q.defer();
if (force === true) {
_identity = undefined;
}
// check and see if we have retrieved the identity data from the server.
// if we have, reuse it by immediately resolving
if (angular.isDefined(_identity)) {
deferred.resolve(_identity);
return deferred.promise;
}
// retrieve the identity data from the server, update the identity object, and then resolve.
Account.get().$promise
.then(getAccountThen)
.catch(getAccountCatch);
return deferred.promise;
function getAccountThen (account) {
_identity = account.data;
_authenticated = true;
deferred.resolve(_identity);
}
function getAccountCatch () {
_identity = null;
_authenticated = false;
deferred.resolve(_identity);
}
}
function isAuthenticated () {
return _authenticated;
}
function isIdentityResolved () {
return angular.isDefined(_identity);
}
}
})();
|
(function() {
var AgileBoard = function() {};
var PlanningBoard = function() {};
PlanningBoard.prototype = {
init: function(routes) {
var self = this;
self.routes = routes;
$(function() {
self.initSortable();
});
},
// If there are no changes
backSortable: function($oldColumn) {
$oldColumn.sortable('cancel');
},
successSortable: function($oldColumn, $column) {
clearErrorMessage();
var r = new RegExp(/\d+/)
var ids = [];
ids.push({
column: $column,
id: $column.data('id'),
to: true
});
ids.push({
column: $oldColumn,
id: $oldColumn.data('id'),
from: true
});
for (var i = 0; i < ids.length; i++) {
var current = ids[i];
var headerSelector = '.version-planning-board thead tr th[data-column-id="' + current.id + '"]';
var $columnHeader = $(headerSelector);
var columnText = $columnHeader.text();
var currentIssuesAmount = ~~columnText.match(r);
currentIssuesAmount = (current.from) ? currentIssuesAmount - 1 : currentIssuesAmount + 1;
$columnHeader.text(columnText.replace(r, currentIssuesAmount));
}
},
errorSortable: function($oldColumn, responseText) {
try {
var errors = JSON.parse(responseText);
} catch(e) {
};
var alertMessage = '';
$oldColumn.sortable('cancel');
if (errors && errors.length > 0) {
for (var i = 0; i < errors.length; i++) {
alertMessage += errors[i] + '\n';
}
}
if (alertMessage) {
setErrorMessage(alertMessage);
};
},
initSortable: function() {
var self = this;
var $issuesCols = $(".issue-version-col");
$issuesCols.sortable({
connectWith: ".issue-version-col",
start: function(event, ui) {
var $item = $(ui.item);
$item.attr('oldColumnId', $item.parent().data('id'));
$item.attr('oldPosition', $item.index());
},
stop: function(event, ui) {
var $item = $(ui.item);
var sender = ui.sender;
var $column = $item.parents('.issue-version-col');
var issue_id = $item.data('id');
var version_id = $column.attr("data-id");
var order = $column.sortable('serialize');
var positions = {};
var oldId = $item.attr('oldColumnId');
var $oldColumn = $('.ui-sortable[data-id="' + oldId + '"]');
if(!self.hasChange($item)){
self.backSortable($column);
return;
}
$column.find('.issue-card').each(function(i, e) {
var $e = $(e);
positions[$e.data('id')] = { position: $e.index() };
});
$.ajax({
url: self.routes.update_agile_board_path,
type: 'PUT',
data: {
issue: {
fixed_version_id: version_id
},
positions: positions,
id: issue_id
},
success: function(data, status, xhr) {
self.successSortable($oldColumn, $column);
},
error: function(xhr, status, error) {
self.errorSortable($oldColumn, xhr.responseText);
}
});
}
}).disableSelection();
$issuesCols.sortable( "option", "cancel", "div.pagination-wrapper" );
},
hasChange: function($item){
var column = $item.parents('.issue-version-col');
return $item.attr('oldColumnId') != column.data('id') || // Checks a version change
$item.attr('oldPosition') != $item.index();
},
}
AgileBoard.prototype = {
init: function(routes) {
var self = this;
self.routes = routes;
$(function() {
self.initSortable();
self.initDraggable();
self.initDroppable();
});
},
// ----- estimated hours ------
recalculateEstimateHours: function(oldStatusId, newStatusId, value){
oldStatusElement = $('th[data-column-id="' + oldStatusId + '"]');
newStatusElement = $('th[data-column-id="' + newStatusId + '"]');
oldStatusElement.each(function(i, elem){
changeHtmlNumber(elem, -value);
});
newStatusElement.each(function(i, elem){
changeHtmlNumber(elem, value);
});
},
successSortable: function(oldStatusId, newStatusId, oldSwimLaneId, newSwimLaneId) {
clearErrorMessage();
decHtmlNumber('th[data-column-id="' + oldStatusId + '"] span.count');
incHtmlNumber('th[data-column-id="' + newStatusId + '"] span.count');
decHtmlNumber('tr.group.swimlane[data-id="' + oldSwimLaneId + '"] td span.count');
incHtmlNumber('tr.group.swimlane[data-id="' + newSwimLaneId + '"] td span.count');
},
// If there are no changes
backSortable: function($oldColumn) {
$oldColumn.sortable('cancel');
},
errorSortable: function($oldColumn, responseText) {
try {
var errors = JSON.parse(responseText);
} catch(e) {
};
var alertMessage = '';
$oldColumn.sortable('cancel');
if (errors && errors.length > 0) {
for (var i = 0; i < errors.length; i++) {
alertMessage += errors[i] + '\n';
}
}
if (alertMessage) {
setErrorMessage(alertMessage);
}
},
initSortable: function() {
var self = this;
var $issuesCols = $(".issue-status-col");
$issuesCols.sortable({
connectWith: ".issue-status-col",
start: function(event, ui) {
var $item = $(ui.item);
$item.attr('oldColumnId', $item.parent().data('id'));
$item.attr('oldSwimLaneId', $item.parents('tr.swimlane').data('id'));
$item.attr('oldSwimLaneField', $item.parents('tr.swimlane').attr('data-field'));
$item.attr('oldPosition', $item.index());
},
stop: function(event, ui) {
var $item = $(ui.item);
var sender = ui.sender;
var $column = $item.parents('.issue-status-col');
var $swimlane = $item.parents('tr.swimlane');
var issue_id = $item.data('id');
var newStatusId = $column.data("id");
var order = $column.sortable('serialize');
var swimLaneId = $swimlane.data('id')
var swimLaneField = $swimlane.attr('data-field');
var positions = {};
var oldStatusId = $item.attr('oldColumnId');
var oldSwimLaneId = $item.attr('oldSwimLaneId');
var oldSwimLaneField = $item.attr('oldSwimLaneField');
var $oldColumn = $('.ui-sortable[data-id="' + oldStatusId + '"]');
if(!self.hasChange($item)){
self.backSortable($column);
return;
}
if ($column.hasClass("closed")){
$item.addClass("float-left")
}
else{
$item.removeClass("closed-issue");
$item.removeClass("float-left")
}
$column.find('.issue-card').each(function(i, e) {
var $e = $(e);
positions[$e.data('id')] = { position: $e.index() };
});
var params = {
issue: {
status_id: newStatusId
},
positions: positions,
id: issue_id
}
params['issue'][swimLaneField] = swimLaneId;
$.ajax({
url: self.routes.update_agile_board_path,
type: 'PUT',
data: params,
success: function(data, status, xhr) {
self.successSortable(oldStatusId, newStatusId, oldSwimLaneId, swimLaneId);
$($item).replaceWith(data);
estimatedHours = $($item).find("span.hours");
if(estimatedHours.size() > 0){
hours = $(estimatedHours).html().replace(/(\(|\)|h)?/g, '');
self.recalculateEstimateHours(oldStatusId, newStatusId, hours);
}
},
error: function(xhr, status, error) {
self.errorSortable($oldColumn, xhr.responseText);
}
});
}
}).disableSelection();
},
initDraggable: function() {
if ($("#group_by").val() != "assigned_to"){
$(".assignable-user").draggable({
helper: "clone",
start: function startDraggable(event, ui) {
$(ui.helper).addClass("draggable-active")
}
});
}
},
hasChange: function($item){
var column = $item.parents('.issue-status-col');
var swimlane = $item.parents('tr.swimlane');
return $item.attr('oldColumnId') != column.data('id') || // Checks the status change
$item.attr('oldSwimLaneId') != swimlane.data('id') ||
$item.attr('oldPosition') != $item.index();
},
initDroppable: function() {
var self = this;
$(".issue-card").droppable({
activeClass: 'droppable-active',
hoverClass: 'droppable-hover',
accept: '.assignable-user',
tolerance: 'pointer',
drop: function(event, ui) {
var $self = $(this);
$.ajax({
url: self.routes.update_agile_board_path,
type: "PUT",
dataType: "html",
data: {
issue: {
assigned_to_id: ui.draggable.data("id")
},
id: $self.data("id")
},
success: function(data, status, xhr){
$self.replaceWith(data);
},
error:function(xhr, status, error) {
alert(error);
}
});
$self.find("p.info").show();
$self.find("p.info").html(ui.draggable.clone());
}
});
},
}
window.AgileBoard = AgileBoard;
window.PlanningBoard = PlanningBoard;
$.fn.StickyHeader = function() {
return this.each(function() {
var
$this = $(this),
$body = $('body'),
$html = $body.parent(),
$hideButton = $body.find('#hideSidebarButton'),
$fullScreenButton = $body.find('.icon-fullscreen'),
$containerFixed,
$tableFixed,
$tableRows,
$tableFixedRows,
containerWidth,
offset,
tableHeight,
tableHeadHeight,
tableOffsetTop,
tableOffsetBottom,
tmp;
function init() {
$this.wrap('<div class="container-fixed" />');
$tableFixed = $this.clone();
$containerFixed = $this.parents('.container-fixed');
$tableFixed
.find('tbody')
.remove()
.end()
.css({'display': 'table', 'top': '0px', 'position': 'fixed'})
.insertBefore($this)
.hide();
}
function resizeFixed() {
containerWidth = $containerFixed.width();
tableHeadHeight = $this.find("thead").height() + 3;
$tableRows = $this.find('thead th');
$tableFixedRows = $tableFixed.find('th');
$tableFixed.css({'width': containerWidth});
$tableRows.each(function(i) {
tmp = jQuery(this).width();
jQuery($tableFixedRows[i]).css('width', tmp);
});
}
function scrollFixed() {
tableHeight = $this.height();
tableHeadHeight = $this.find("thead").height();
offset = $(window).scrollTop();
tableOffsetTop = $this.offset().top;
tableOffsetBottom = tableOffsetTop + tableHeight - tableHeadHeight;
resizeFixed();
if (offset < tableOffsetTop || offset > tableOffsetBottom) {
$tableFixed.css('display', 'none');
} else if (offset >= tableOffsetTop && offset <= tableOffsetBottom) {
$tableFixed.css('display', 'table');
// Fix for chrome not redrawing header
$tableFixed.css('z-index', '1');
setTimeout(function(){
$tableFixed.css('z-index', '');
}, 0);
}
}
$hideButton.click(function() {
resizeFixed();
});
function bindScroll() {
if ($html.hasClass('agile-board-fullscreen')) {
$('div.agile-board.autoscroll').scroll(scrollFixed);
$(window).unbind('scroll');
} else {
$(window).scroll(scrollFixed);
$('div.agile-board.autoscroll').unbind('scroll');
$tableFixed.hide();
}
}
$fullScreenButton.click(function() {
bindScroll();
});
$(window).resize(resizeFixed);
init();
bindScroll();
});
};
})();
function setErrorMessage(message) {
$('div#agile-board-errors').html(message).show();
setTimeout(clearErrorMessage,3000);
}
function clearErrorMessage() {
$('div#agile-board-errors').html('').hide();
}
function incHtmlNumber(element) {
$(element).html(~~$(element).html() + 1);
}
function decHtmlNumber(element) {
$(element).html(~~$(element).html() - 1);
}
function changeHtmlNumber(element, number){
elementWithHours = $(element).find("span.hours");
if (elementWithHours.size() > 0){
old_value = $(elementWithHours).html().replace(/(\(|\)|h)/);
new_value = parseFloat(old_value)+ parseFloat(number);
if (new_value > 0)
$(elementWithHours).html(new_value.toFixed(2) + "h");
else
$(elementWithHours).remove();
}
else{
new_value = number;
$(element).append("<span class='hours'>" + new_value + "h</span>");
}
}
function observeIssueSearchfield(fieldId, url) {
$('#'+fieldId).each(function() {
var $this = $(this);
$this.addClass('autocomplete');
$this.attr('data-value-was', $this.val());
var check = function() {
var val = $this.val();
if ($this.attr('data-value-was') != val){
$this.attr('data-value-was', val);
$.ajax({
url: url,
type: 'get',
data: {q: $this.val()},
beforeSend: function(){ $this.addClass('ajax-loading'); },
complete: function(){ $this.removeClass('ajax-loading'); }
});
}
};
var reset = function() {
if (timer) {
clearInterval(timer);
timer = setInterval(check, 300);
}
};
var timer = setInterval(check, 300);
$this.bind('keyup click mousemove', reset);
});
}
function recalculateHours() {
var backlogSum = 0;
$('.versions-planning-board td:nth-child(2) .issue-card').each(function(i, elem){
hours = parseFloat($(elem).data('estimated-hours'));
backlogSum += hours;
})
$('.versions-planning-board .backlog-hours').text('(' + backlogSum.toFixed(2) + 'h)');
var currentSum = 0;
$('.versions-planning-board td:nth-child(3) .issue-card').each(function(i, elem){
hours = parseFloat($(elem).data('estimated-hours'));
currentSum += hours;
})
$('.versions-planning-board .current-hours').text('(' + currentSum.toFixed(2) + 'h)');
}
function getToolTipInfo(node, url){
var issue_id = $(node).parents(".issue-card").data("id");
var tip = $(node).children(".tip");
if( $(tip).html() && $(tip).html().trim() != "")
return;
$.ajax({
url: url,
type: "get",
dataType: "html",
data: {
id: issue_id
},
success: function(data, status, xhr){
$(tip).html(data);
},
error:function(xhr, status, error) {
$(tip).html(error);
}
});
}
$(document).ready(function(){
$('table.issues-board').StickyHeader();
$('div#agile-board-errors').click(function(){
$(this).animate({top: -$(this).outerHeight()}, 500);
});
$('.tooltip').mouseenter(getToolTipInfo);
});
|
(function () {
'use strict';
/**
* @param {typeof Base} Base
* @param {$rootScope.Scope} $scope
* @param {ModalManager} modalManager
* @param {Waves} waves
* @param {BalanceWatcher} balanceWatcher
* @param {User} user
* @param {app.utils} utils
* @param {PromiseControl} PromiseControl
*/
const controller = function (Base, $scope, modalManager, waves, balanceWatcher, user, utils, PromiseControl) {
const { SIGN_TYPE, WAVES_ID } = require('@waves/signature-adapter');
const { BigNumber } = require('@waves/bignumber');
const ds = require('data-service');
const $ = require('jquery');
const BASE_64_PREFIX = 'base64:';
class TokensCtrl extends Base {
/**
* @type {boolean}
*/
focusName = false;
/**
* @type {PromiseControl}
*/
_findNamePC = null;
/**
* @type {boolean}
*/
agreeConditions = false;
/**
* @type {boolean}
*/
nameWarning = false;
/**
* Link to angular form object
* @type {form.FormController}
*/
createForm = null;
/**
* @type {string}
*/
assetId = '';
/**
* Token name
* @type {string}
*/
name = '';
/**
* Token description
* @type {string}
*/
description = '';
/**
* Can reissue this token
* @type {boolean}
*/
issue = true;
/**
* Count of generated tokens
* @type {BigNumber}
*/
count = null;
/**
* Precision of token
* @type {number}
*/
precision = 0;
/**
* @type {BigNumber}
*/
maxCoinsCount = WavesApp.maxCoinsCount;
/**
* Has money for fee
* @type {boolean}
*/
invalid = false;
/**
* @type {string}
*/
script = '';
/**
* @type {boolean}
*/
isValidScript = true;
/**
* @type {boolean}
*/
scriptPending = false;
/**
* @type {Money}
*/
fee = null;
/**
* @type {boolean}
*/
hasAssetScript = false;
/**
* @type {Signable}
*/
signable = null;
/**
* @type {JQueryXHR | null}
* @private
*/
_scriptValidationXHR = null;
/**
* @type {Money}
* @private
*/
_balance;
/**
* @type {boolean}
*/
isNFT = false;
/**
* @type {args}
*/
signPending = false;
/**
* @type {Array}
* @private
*/
_listeners = [];
constructor() {
super($scope);
this.receive(balanceWatcher.change, this._onChangeBalance, this);
this.observe('precision', this._onChangePrecision);
this.observe('script', this._onChangeScript);
this.observe([
'name',
'count',
'script',
'precision',
'description',
'issue',
'hasAssetScript',
'fee'
], this.createSignable);
this.observe([
'count',
'precision',
'issue'
], this._setIsNFT);
this._getFee();
this.observe('isNFT', this._getFee);
this.observeOnce('createForm', () => {
this.receive(utils.observe(this.createForm, '$valid'), this.createSignable, this);
});
const signPendingListener = $scope.$on('signPendingChange', (event, data) => {
this.signPending = data;
});
this._listeners.push(signPendingListener);
}
$onDestroy() {
super.$onDestroy();
this._listeners.forEach(listener => listener());
}
/**
* @param {boolean} focus
*/
onNameFocus(focus) {
this.focusName = !!focus;
}
generate(signable) {
return modalManager.showConfirmTx(signable)
.then(() => this._reset());
}
sendAnalytics() {
analytics.send({ name: 'Token Generation Info Show', target: 'ui' });
}
getSignable() {
return this.signable;
}
createSignable() {
this._verifyName().then(
res => {
this.nameWarning = res;
$scope.$apply();
}
);
if (!this.name || !this.createForm || !this.createForm.$valid) {
this.assetId = '';
return null;
}
const precision = Number(this.precision.toString());
const quantity = (this.count || new BigNumber(0)).mul(Math.pow(10, precision));
const script = this.hasAssetScript && this.script ? `${BASE_64_PREFIX}${this.script}` : '';
const tx = waves.node.transactions.createTransaction({
type: SIGN_TYPE.ISSUE,
name: this.name,
description: this.description,
reissuable: this.issue,
quantity,
precision,
script,
fee: this.fee
});
this.signable = ds.signature.getSignatureApi().makeSignable({ type: tx.type, data: tx });
this.signable.getId().then(id => {
this.assetId = id;
utils.safeApply($scope);
});
}
/**
* @return {*}
* @private
*/
_verifyName() {
if (this._findNamePC != null) {
this._findNamePC.abort();
}
this._findNamePC = new PromiseControl(utils.wait(1000));
return this._findNamePC
.then(() => utils.assetNameWarning(this.name));
}
/**
* @return {null}
* @private
*/
_onChangeScript() {
if (this._scriptValidationXHR) {
this._scriptValidationXHR.abort();
this.scriptPending = false;
}
const script = this.script.replace(BASE_64_PREFIX, '');
if (!script) {
this.isValidScript = true;
this.scriptPending = false;
return null;
}
this.isValidScript = true;
this.scriptPending = true;
this._scriptValidationXHR = $.ajax({
method: 'POST',
url: `${user.getSetting('network.node')}/utils/script/estimate`,
data: script
});
this._scriptValidationXHR
.then(() => {
this.isValidScript = true;
})
.catch(() => {
this.isValidScript = false;
})
.always(() => {
this.scriptPending = false;
$scope.$apply();
});
}
/**
* @param {BigNumber} value
* @private
*/
_onChangePrecision({ value }) {
if (value && value <= 8) {
this.maxCoinsCount = WavesApp.maxCoinsCount.div(Math.pow(10, Number(value)));
}
}
/**
* Current can i send transaction (balance gt fee)
* @private
*/
_onChangeBalance() {
this._balance = balanceWatcher.getBalance()[WAVES_ID];
this.invalid = (!this.fee || !this._balance) ||
this._balance.getTokens().lt(this.fee.getTokens());
$scope.$apply();
}
/**
* @private
*/
_reset() {
this.name = '';
this.description = '';
this.issue = true;
this.count = new BigNumber(0);
this.precision = 0;
this.maxCoinsCount = WavesApp.maxCoinsCount;
this.script = '';
this.hasAssetScript = false;
this.createForm.$setPristine();
this.createForm.$setUntouched();
$scope.$apply();
}
/**
* @private
*/
_setIsNFT() {
const { count, precision, issue } = this;
const nftCount = count && count.eq(1);
const nftPrecision = precision === 0;
this.isNFT = !issue && nftCount && nftPrecision;
}
/**
* @private
*/
_getFee() {
waves.node.getFee({
type: SIGN_TYPE.ISSUE,
reissue: this.issue,
precision: this.precision,
quantity: this.count
})
.then(money => {
this.fee = money;
this._onChangeBalance();
$scope.$apply();
});
}
}
return new TokensCtrl();
};
controller.$inject = ['Base', '$scope', 'modalManager',
'waves', 'balanceWatcher', 'user', 'utils', 'PromiseControl'];
angular.module('app.tokens')
.controller('TokensCtrl', controller);
})();
|
$(window).load(function () {
for (var key in Frequencies.keys) {
$('#key').append($('<option>').text(key));
}
var musicSheet = new MusicSheet('C', 100, 100);
var sheetView = new MusicSheetView(musicSheet, $('#musicSheet'));
$('#playButton').click(function () {
musicSheet.stop();
musicSheet.play(function () {
sheetView.paintCanvas();
});
});
$('#stopButton').click(function () {
musicSheet.stop();
});
$('#loadButton').click(function () {
$('#file').click();
});
$('#settingsButton').click(function () {
$('#key').val(musicSheet.key);
$('#sheetLength').val(musicSheet.sheet.length);
$('#noteDelay').val(musicSheet.noteDelay);
$('#settingsModal').modal('show');
});
$('#saveButton').click(function () {
var blob = new Blob([musicSheet.serialize()], {type: "text/plain;charset=utf-8"});
saveAs(blob, $('#fileName').val());
$('#saveModal').modal('hide');
});
$('#file').change(function () {
var files = $('#file')[0].files;
if (files.length == 0) {
return;
}
var reader = new FileReader();
reader.onload = function (event) {
$('#loadButton').popover('hide');
try {
musicSheet.load(event.target.result);
$('#fileName').val(files[0].name);
sheetView.resize();
} catch (exception) {
showAlert('Oh no!', 'Couldn\'t load the file you selected. Did you pick the right file?');
}
$('#file').val('');
};
reader.readAsText(files[0]);
$('#loadButton').popover('show');
});
$('#saveSettingsButton').click(function () {
var key = $('#key').val();
var sheetLength = parseInt($('#sheetLength').val());
var noteDelay = parseInt($('#noteDelay').val());
musicSheet.reset(key, sheetLength, noteDelay);
sheetView.resize();
$('#settingsModal').modal('hide');
});
$('#settingsForm').bootstrapValidator({
submitButtons: '#saveSettingsButton',
live: 'enabled',
fields: {
sheetLength: {
validators: {
notEmpty: {
message: 'Sheet length is required.'
},
greaterThan: {
message: 'Sheet length must be at least 1.',
value: 1,
inclusive: false
},
lessThan: {
message: 'Sheet length can be at most 1000.',
value: 1000,
inclusive: false
}
}
},
noteDelay: {
validators: {
notEmpty: {
message: 'Beat interval is required.'
},
integer: {
message: 'Beat interval must be a whole number.'
},
greaterThan: {
message: 'Beat interval must be greater than 0.',
value: 0,
inclusive: true
}
}
}
}
});
function showAlert(title, body) {
$('#alertModal .modal-title').html(title);
$('#alertModal .modal-body').html(body);
$('#alertModal').modal('show');
}
});
|
const IngredientFilterInput = require('../presentational/ingredient-filter-input')
const { connect } = require('react-redux')
const { updateIngredientFilter } = require('../../store/actions/filters')
function mapDispatchToProps (dispatch) {
return {
onIngredientInput (name) {
dispatch(updateIngredientFilter(name))
}
}
}
function mapStateToProps (state) {
return {
value: ''
}
}
module.exports = connect(mapStateToProps, mapDispatchToProps)(IngredientFilterInput)
|
// タートルを生成する
var t = createTurtle();
// 屋根を書く
t.rt(30);// 30度右を向く
t.fd(50);// 50歩前に進む
t.rt(120);
t.fd(50);
t.rt(120);
t.fd(50);
// 本体を書く
t.lt(90);
t.fd(50);
t.lt(90);
t.fd(50);
t.lt(90);
t.fd(50);
t.lt(90);
t.fd(50);
|
/*! Select2 4.1.0-beta.0 | https://github.com/select2/select2/blob/master/LICENSE.md */
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/lt",[],function(){function n(n,e,i,t){return n%10==1&&(n%100<11||n%100>19)?e:n%10>=2&&n%10<=9&&(n%100<11||n%100>19)?i:t}return{inputTooLong:function(e){var i=e.input.length-e.maximum,t="Pašalinkite "+i+" simbol";return t+=n(i,"į","ius","ių")},inputTooShort:function(e){var i=e.minimum-e.input.length,t="Įrašykite dar "+i+" simbol";return t+=n(i,"į","ius","ių")},loadingMore:function(){return"Kraunama daugiau rezultatų…"},maximumSelected:function(e){var i="Jūs galite pasirinkti tik "+e.maximum+" element";return i+=n(e.maximum,"ą","us","ų")},noResults:function(){return"Atitikmenų nerasta"},searching:function(){return"Ieškoma…"},removeAllItems:function(){return"Pašalinti visus elementus"}}}),n.define,n.require}();
|
// @flow
import {connect} from 'react-redux'
import {goBack} from 'react-router-redux'
import {deleteProject, saveToServer} from '../actions/project'
import EditProject from '../components/edit-project'
import * as select from '../selectors'
function mapStateToProps (state, props) {
const currentProject = select.currentProject(state, props)
const currentBundle = select.currentBundle(state, props) || {}
return {
bundleName: currentBundle.name,
project: currentProject
}
}
function mapDispatchToProps (dispatch: Dispatch, props) {
return {
close: () => dispatch(goBack()),
deleteProject: () => dispatch(deleteProject(props.params.projectId, props.params.regionId)),
save: opts => dispatch(saveToServer(opts))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(EditProject)
|
this.NesDb = this.NesDb || {};
NesDb[ 'C6FEF52264372FAB620D1E5EE6A3E60E46262775' ] = {
"$": {
"name": "Hokuto no Ken 4: Shichisei Hakenden: Hokuto Shinken no Kanata e",
"altname": "北斗の拳4 七星覇拳伝 北斗神拳の彼方へ",
"class": "Licensed",
"catalog": "TDF-97",
"publisher": "Toei Animation",
"developer": "Office Koukan",
"region": "Japan",
"players": "1",
"date": "1991-03-29"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "63469396",
"sha1": "C6FEF52264372FAB620D1E5EE6A3E60E46262775",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2010-07-22"
},
"board": [
{
"$": {
"type": "HVC-SNROM",
"pcb": "HVC-SNROM-09",
"mapper": "1"
},
"prg": [
{
"$": {
"name": "TDF-97-0 PRG",
"size": "256k",
"crc": "63469396",
"sha1": "C6FEF52264372FAB620D1E5EE6A3E60E46262775"
}
}
],
"wram": [
{
"$": {
"size": "8k",
"battery": "1"
}
}
],
"vram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "MMC1B2"
}
}
]
}
]
}
]
};
|
import React, { Component, PropTypes } from 'react';
const propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
skills: PropTypes.array,
child: PropTypes.element
};
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
liked: 0,
skills: props.skills
};
this.click = this.clickLiked.bind(this);
this.add = this.addSkill.bind(this);
}
clickLiked() {
let num = this.state.liked;
this.setState({liked: ++num});
}
addSkill() {
let skills = this.state.skills;
if (skills) {
skills.push(this.refs.skill.value);
this.setState({skills});
}
}
render() {
return (
<div className="profile">
<h3>Fucking Cool Name: {this.props.name} </h3>
<h3>Fucking Cool Age: {this.props.age} </h3>
<h3>Fucking Cool Skills: {this.state.skills ? this.state.skills.join(',') : 'No Skills'} </h3>
<div> {this.props.child} </div>
<div onClick={this.click}>liked: {this.state.liked} </div>
<input type="text" ref="skill" />
<button onClick={this.add}>add skill</button>
</div>
);
}
}
Profile.propTypes = propTypes;
export default Profile;
|
function sort(matrix) {
return matrix.sort();
}
|
/*********************************************************#
# @@ScriptName: view.js
# @@Author: Konstantinos Vaggelakos<kozze89@gmail.com>
# @@Create Date: 2013-09-11 15:48:39
# @@Modify Date: 2013-09-16 19:18:01
# @@Function:
#*********************************************************/
var fs = require('fs'),
vectorize = require('./vectorize');
exports.view = function(req, res) {
var path = vectorize.uploadUrl + req.params.id;
fs.readdir('public/' + path, function(err, files) {
if (err) {
return console.error('There was an error reading the files: ' + err);
}
var imageUrls = [];
files.forEach(function(file) {
imageUrls.push('/' + path + '/' + file);
});
res.render('view', {images: imageUrls});
});
};
exports.json = function(req, res) {
var path = vectorize.uploadUrl + req.params.id;
fs.readdir('public/' + path, function(err, files) {
if (err) {
return console.error('There was an error reading the files: ' + err);
}
var imageUrls = [];
files.forEach(function(file) {
imageUrls.push('http://' + req.headers.host + '/' + path + '/' + file);
});
res.json({images: imageUrls});
});
};
|
// Imports [persistiq.js](lib/persistiq.js.html)
module.exports = require('./lib/persistiq');
|
/*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2016, Juerg Lehni & Jonathan Puckey
* http://scratchdisk.com/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
// Based on goog.graphics.AffineTransform, as part of the Closure Library.
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
/**
* @name Matrix
*
* @class An affine transform performs a linear mapping from 2D coordinates
* to other 2D coordinates that preserves the "straightness" and
* "parallelness" of lines.
*
* Such a coordinate transformation can be represented by a 3 row by 3
* column matrix with an implied last row of [ 0 0 1 ]. This matrix
* transforms source coordinates (x,y) into destination coordinates (x',y')
* by considering them to be a column vector and multiplying the coordinate
* vector by the matrix according to the following process:
*
* [ x ] [ a b tx ] [ x ] [ a * x + b * y + tx ]
* [ y ] = [ c d ty ] [ y ] = [ c * x + d * y + ty ]
* [ 1 ] [ 0 0 1 ] [ 1 ] [ 1 ]
*
* This class is optimized for speed and minimizes calculations based on its
* knowledge of the underlying matrix (as opposed to say simply performing
* matrix multiplication).
*/
var Matrix = Base.extend(/** @lends Matrix# */{
_class: 'Matrix',
/**
* Creates a 2D affine transform.
*
* @param {Number} a the a property of the transform
* @param {Number} c the c property of the transform
* @param {Number} b the b property of the transform
* @param {Number} d the d property of the transform
* @param {Number} tx the tx property of the transform
* @param {Number} ty the ty property of the transform
*/
initialize: function Matrix(arg) {
var count = arguments.length,
ok = true;
if (count === 6) {
this.set.apply(this, arguments);
} else if (count === 1) {
if (arg instanceof Matrix) {
this.set(arg._a, arg._c, arg._b, arg._d, arg._tx, arg._ty);
} else if (Array.isArray(arg)) {
this.set.apply(this, arg);
} else {
ok = false;
}
} else if (count === 0) {
this.reset();
} else {
ok = false;
}
if (!ok)
throw new Error('Unsupported matrix parameters');
},
/**
* Sets this transform to the matrix specified by the 6 values.
*
* @param {Number} a the a property of the transform
* @param {Number} c the c property of the transform
* @param {Number} b the b property of the transform
* @param {Number} d the d property of the transform
* @param {Number} tx the tx property of the transform
* @param {Number} ty the ty property of the transform
* @return {Matrix} this affine transform
*/
set: function(a, c, b, d, tx, ty, _dontNotify) {
this._a = a;
this._c = c;
this._b = b;
this._d = d;
this._tx = tx;
this._ty = ty;
if (!_dontNotify)
this._changed();
return this;
},
_serialize: function(options) {
return Base.serialize(this.getValues(), options);
},
_changed: function() {
var owner = this._owner;
if (owner) {
// If owner has #applyMatrix set, directly bake the change in now.
if (owner._applyMatrix) {
owner.transform(null, true);
} else {
owner._changed(/*#=*/Change.GEOMETRY);
}
}
},
/**
* @return {Matrix} a copy of this transform
*/
clone: function() {
return new Matrix(this._a, this._c, this._b, this._d,
this._tx, this._ty);
},
/**
* Checks whether the two matrices describe the same transformation.
*
* @param {Matrix} matrix the matrix to compare this matrix to
* @return {Boolean} {@true if the matrices are equal}
*/
equals: function(mx) {
return mx === this || mx && this._a === mx._a && this._b === mx._b
&& this._c === mx._c && this._d === mx._d
&& this._tx === mx._tx && this._ty === mx._ty
|| false;
},
/**
* @return {String} a string representation of this transform
*/
toString: function() {
var f = Formatter.instance;
return '[[' + [f.number(this._a), f.number(this._b),
f.number(this._tx)].join(', ') + '], ['
+ [f.number(this._c), f.number(this._d),
f.number(this._ty)].join(', ') + ']]';
},
/**
* Resets the matrix by setting its values to the ones of the identity
* matrix that results in no transformation.
*/
reset: function(_dontNotify) {
this._a = this._d = 1;
this._c = this._b = this._tx = this._ty = 0;
if (!_dontNotify)
this._changed();
return this;
},
/**
* Attempts to apply the matrix to the content of item that it belongs to,
* meaning its transformation is baked into the item's content or children.
*
* @param {Boolean} recursively controls whether to apply transformations
* recursively on children
* @return {Boolean} {@true if the matrix was applied}
*/
apply: function(recursively, _setApplyMatrix) {
var owner = this._owner;
if (owner) {
owner.transform(null, true, Base.pick(recursively, true),
_setApplyMatrix);
// If the matrix was successfully applied, it will be reset now.
return this.isIdentity();
}
return false;
},
/**
* Concatenates this transform with a translate transformation.
*
* @name Matrix#translate
* @function
* @param {Point} point the vector to translate by
* @return {Matrix} this affine transform
*/
/**
* Concatenates this transform with a translate transformation.
*
* @name Matrix#translate
* @function
* @param {Number} dx the distance to translate in the x direction
* @param {Number} dy the distance to translate in the y direction
* @return {Matrix} this affine transform
*/
translate: function(/* point */) {
var point = Point.read(arguments),
x = point.x,
y = point.y;
this._tx += x * this._a + y * this._b;
this._ty += x * this._c + y * this._d;
this._changed();
return this;
},
/**
* Concatenates this transform with a scaling transformation.
*
* @name Matrix#scale
* @function
* @param {Number} scale the scaling factor
* @param {Point} [center] the center for the scaling transformation
* @return {Matrix} this affine transform
*/
/**
* Concatenates this transform with a scaling transformation.
*
* @name Matrix#scale
* @function
* @param {Number} hor the horizontal scaling factor
* @param {Number} ver the vertical scaling factor
* @param {Point} [center] the center for the scaling transformation
* @return {Matrix} this affine transform
*/
scale: function(/* scale, center */) {
var scale = Point.read(arguments),
center = Point.read(arguments, 0, { readNull: true });
if (center)
this.translate(center);
this._a *= scale.x;
this._c *= scale.x;
this._b *= scale.y;
this._d *= scale.y;
if (center)
this.translate(center.negate());
this._changed();
return this;
},
/**
* Concatenates this transform with a rotation transformation around an
* anchor point.
*
* @name Matrix#rotate
* @function
* @param {Number} angle the angle of rotation measured in degrees
* @param {Point} center the anchor point to rotate around
* @return {Matrix} this affine transform
*/
/**
* Concatenates this transform with a rotation transformation around an
* anchor point.
*
* @name Matrix#rotate
* @function
* @param {Number} angle the angle of rotation measured in degrees
* @param {Number} x the x coordinate of the anchor point
* @param {Number} y the y coordinate of the anchor point
* @return {Matrix} this affine transform
*/
rotate: function(angle /*, center */) {
angle *= Math.PI / 180;
var center = Point.read(arguments, 1),
// Concatenate rotation matrix into this one
x = center.x,
y = center.y,
cos = Math.cos(angle),
sin = Math.sin(angle),
tx = x - x * cos + y * sin,
ty = y - x * sin - y * cos,
a = this._a,
b = this._b,
c = this._c,
d = this._d;
this._a = cos * a + sin * b;
this._b = -sin * a + cos * b;
this._c = cos * c + sin * d;
this._d = -sin * c + cos * d;
this._tx += tx * a + ty * b;
this._ty += tx * c + ty * d;
this._changed();
return this;
},
/**
* Concatenates this transform with a shear transformation.
*
* @name Matrix#shear
* @function
* @param {Point} shear the shear factor in x and y direction
* @param {Point} [center] the center for the shear transformation
* @return {Matrix} this affine transform
*/
/**
* Concatenates this transform with a shear transformation.
*
* @name Matrix#shear
* @function
* @param {Number} hor the horizontal shear factor
* @param {Number} ver the vertical shear factor
* @param {Point} [center] the center for the shear transformation
* @return {Matrix} this affine transform
*/
shear: function(/* shear, center */) {
// Do not modify point, center, since that would arguments of which
// we're reading from!
var shear = Point.read(arguments),
center = Point.read(arguments, 0, { readNull: true });
if (center)
this.translate(center);
var a = this._a,
c = this._c;
this._a += shear.y * this._b;
this._c += shear.y * this._d;
this._b += shear.x * a;
this._d += shear.x * c;
if (center)
this.translate(center.negate());
this._changed();
return this;
},
/**
* Concatenates this transform with a skew transformation.
*
* @name Matrix#skew
* @function
* @param {Point} skew the skew angles in x and y direction in degrees
* @param {Point} [center] the center for the skew transformation
* @return {Matrix} this affine transform
*/
/**
* Concatenates this transform with a skew transformation.
*
* @name Matrix#skew
* @function
* @param {Number} hor the horizontal skew angle in degrees
* @param {Number} ver the vertical skew angle in degrees
* @param {Point} [center] the center for the skew transformation
* @return {Matrix} this affine transform
*/
skew: function(/* skew, center */) {
var skew = Point.read(arguments),
center = Point.read(arguments, 0, { readNull: true }),
toRadians = Math.PI / 180,
shear = new Point(Math.tan(skew.x * toRadians),
Math.tan(skew.y * toRadians));
return this.shear(shear, center);
},
/**
* Appends the specified matrix to this matrix. This is the equivalent of
* multiplying `(this matrix) * (specified matrix)`.
*
* @param {Matrix} matrix the matrix to append
* @return {Matrix} this matrix, modified
*/
append: function(mx) {
var a1 = this._a,
b1 = this._b,
c1 = this._c,
d1 = this._d,
a2 = mx._a,
b2 = mx._b,
c2 = mx._c,
d2 = mx._d,
tx2 = mx._tx,
ty2 = mx._ty;
this._a = a2 * a1 + c2 * b1;
this._b = b2 * a1 + d2 * b1;
this._c = a2 * c1 + c2 * d1;
this._d = b2 * c1 + d2 * d1;
this._tx += tx2 * a1 + ty2 * b1;
this._ty += tx2 * c1 + ty2 * d1;
this._changed();
return this;
},
/**
* Returns a new matrix as the result of appending the specified matrix to
* this matrix. This is the equivalent of multiplying
* `(this matrix) * (specified matrix)`.
*
* @param {Matrix} matrix the matrix to append
* @return {Matrix} the newly created matrix
*/
appended: function(mx) {
return this.clone().append(mx);
},
/**
* Prepends the specified matrix to this matrix. This is the equivalent of
* multiplying `(specified matrix) * (this matrix)`.
*
* @param {Matrix} matrix the matrix to prepend
* @return {Matrix} this matrix, modified
*/
prepend: function(mx) {
var a1 = this._a,
b1 = this._b,
c1 = this._c,
d1 = this._d,
tx1 = this._tx,
ty1 = this._ty,
a2 = mx._a,
b2 = mx._b,
c2 = mx._c,
d2 = mx._d,
tx2 = mx._tx,
ty2 = mx._ty;
this._a = a2 * a1 + b2 * c1;
this._b = a2 * b1 + b2 * d1;
this._c = c2 * a1 + d2 * c1;
this._d = c2 * b1 + d2 * d1;
this._tx = a2 * tx1 + b2 * ty1 + tx2;
this._ty = c2 * tx1 + d2 * ty1 + ty2;
this._changed();
return this;
},
/**
* Returns a new matrix as the result of prepending the specified matrix
* to this matrix. This is the equivalent of multiplying
* `(specified matrix) s* (this matrix)`.
*
* @param {Matrix} matrix the matrix to prepend
* @return {Matrix} the newly created matrix
*/
prepended: function(mx) {
return this.clone().prepend(mx);
},
/**
* Inverts the matrix, causing it to perform the opposite transformation.
* If the matrix is not invertible (in which case {@link #isSingular()}
* returns true), `null` is returned.
*
* @return {Matrix} this matrix, or `null`, if the matrix is singular.
*/
invert: function() {
var a = this._a,
b = this._b,
c = this._c,
d = this._d,
tx = this._tx,
ty = this._ty,
det = a * d - b * c,
res = null;
if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
this._a = d / det;
this._b = -b / det;
this._c = -c / det;
this._d = a / det;
this._tx = (b * ty - d * tx) / det;
this._ty = (c * tx - a * ty) / det;
res = this;
}
return res;
},
/**
* Creates a new matrix that is the inversion of this matrix, causing it to
* perform the opposite transformation. If the matrix is not invertible (in
* which case {@link #isSingular()} returns true), `null` is returned.
*
* @return {Matrix} this matrix, or `null`, if the matrix is singular.
*/
inverted: function() {
return this.clone().invert();
},
/**
* @deprecated, use use {@link #append(matrix)} instead.
*/
concatenate: '#append',
/**
* @deprecated, use use {@link #prepend(matrix)} instead.
*/
preConcatenate: '#prepend',
/**
* @deprecated, use use {@link #appended(matrix)} instead.
*/
chain: '#appended',
/**
* A private helper function to create a clone of this matrix, without the
* translation factored in.
*
* @return {Matrix} a clone of this matrix, with {@link #tx} and {@link #ty}
* set to `0`.
*/
_shiftless: function() {
return new Matrix(this._a, this._c, this._b, this._d, 0, 0);
},
_orNullIfIdentity: function() {
return this.isIdentity() ? null : this;
},
/**
* @return {Boolean} whether this transform is the identity transform
*/
isIdentity: function() {
return this._a === 1 && this._c === 0 && this._b === 0 && this._d === 1
&& this._tx === 0 && this._ty === 0;
},
/**
* Returns whether the transform is invertible. A transform is not
* invertible if the determinant is 0 or any value is non-finite or NaN.
*
* @return {Boolean} whether the transform is invertible
*/
isInvertible: function() {
var det = this._a * this._d - this._b * this._c;
return det && !isNaN(det) && isFinite(this._tx) && isFinite(this._ty);
},
/**
* Checks whether the matrix is singular or not. Singular matrices cannot be
* inverted.
*
* @return {Boolean} whether the matrix is singular
*/
isSingular: function() {
return !this.isInvertible();
},
/**
* Transforms a point and returns the result.
*
* @name Matrix#transform
* @function
* @param {Point} point the point to be transformed
* @return {Point} the transformed point
*/
/**
* Transforms an array of coordinates by this matrix and stores the results
* into the destination array, which is also returned.
*
* @name Matrix#transform
* @function
* @param {Number[]} src the array containing the source points
* as x, y value pairs
* @param {Number[]} dst the array into which to store the transformed
* point pairs
* @param {Number} count the number of points to transform
* @return {Number[]} the dst array, containing the transformed coordinates
*/
transform: function(/* point | */ src, dst, count) {
return arguments.length < 3
// TODO: Check for rectangle and use _tranformBounds?
? this._transformPoint(Point.read(arguments))
: this._transformCoordinates(src, dst, count);
},
/**
* A faster version of transform that only takes one point and does not
* attempt to convert it.
*/
_transformPoint: function(point, dest, _dontNotify) {
var x = point.x,
y = point.y;
if (!dest)
dest = new Point();
return dest.set(
x * this._a + y * this._b + this._tx,
x * this._c + y * this._d + this._ty,
_dontNotify);
},
_transformCoordinates: function(src, dst, count) {
for (var i = 0, max = 2 * count; i < max; i += 2) {
var x = src[i],
y = src[i + 1];
dst[i] = x * this._a + y * this._b + this._tx;
dst[i + 1] = x * this._c + y * this._d + this._ty;
}
return dst;
},
_transformCorners: function(rect) {
var x1 = rect.x,
y1 = rect.y,
x2 = x1 + rect.width,
y2 = y1 + rect.height,
coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
return this._transformCoordinates(coords, coords, 4);
},
/**
* Returns the 'transformed' bounds rectangle by transforming each corner
* point and finding the new bounding box to these points. This is not
* really the transformed rectangle!
*/
_transformBounds: function(bounds, dest, _dontNotify) {
var coords = this._transformCorners(bounds),
min = coords.slice(0, 2),
max = min.slice();
for (var i = 2; i < 8; i++) {
var val = coords[i],
j = i & 1;
if (val < min[j]) {
min[j] = val;
} else if (val > max[j]) {
max[j] = val;
}
}
if (!dest)
dest = new Rectangle();
return dest.set(min[0], min[1], max[0] - min[0], max[1] - min[1],
_dontNotify);
},
/**
* Inverse transforms a point and returns the result.
*
* @param {Point} point the point to be transformed
*/
inverseTransform: function(/* point */) {
return this._inverseTransform(Point.read(arguments));
},
_inverseTransform: function(point, dest, _dontNotify) {
var a = this._a,
b = this._b,
c = this._c,
d = this._d,
tx = this._tx,
ty = this._ty,
det = a * d - b * c,
res = null;
if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
var x = point.x - this._tx,
y = point.y - this._ty;
if (!dest)
dest = new Point();
res = dest.set(
(x * d - y * b) / det,
(y * a - x * c) / det,
_dontNotify);
}
return res;
},
/**
* Attempts to decompose the affine transformation described by this matrix
* into `scaling`, `rotation` and `shearing`, and returns an object with
* these properties if it succeeded, `null` otherwise.
*
* @return {Object} the decomposed matrix, or `null` if decomposition is not
* possible
*/
decompose: function() {
// http://dev.w3.org/csswg/css3-2d-transforms/#matrix-decomposition
// http://stackoverflow.com/questions/4361242/
// https://github.com/wisec/DOMinator/blob/master/layout/style/nsStyleAnimation.cpp#L946
var a = this._a, b = this._b, c = this._c, d = this._d;
if (Numerical.isZero(a * d - b * c))
return null;
var scaleX = Math.sqrt(a * a + b * b);
a /= scaleX;
b /= scaleX;
var shear = a * c + b * d;
c -= a * shear;
d -= b * shear;
var scaleY = Math.sqrt(c * c + d * d);
c /= scaleY;
d /= scaleY;
shear /= scaleY;
// a * d - b * c should now be 1 or -1
if (a * d < b * c) {
a = -a;
b = -b;
// We don't need c & d anymore, but if we did, we'd have to do this:
// c = -c;
// d = -d;
shear = -shear;
scaleX = -scaleX;
}
return {
scaling: new Point(scaleX, scaleY),
rotation: -Math.atan2(b, a) * 180 / Math.PI,
shearing: shear
};
},
/**
* The value that affects the transformation along the x axis when scaling
* or rotating, positioned at (0, 0) in the transformation matrix.
*
* @name Matrix#a
* @type Number
*/
/**
* The value that affects the transformation along the y axis when rotating
* or skewing, positioned at (1, 0) in the transformation matrix.
*
* @name Matrix#c
* @type Number
*/
/**
* The value that affects the transformation along the x axis when rotating
* or skewing, positioned at (0, 1) in the transformation matrix.
*
* @name Matrix#b
* @type Number
*/
/**
* The value that affects the transformation along the y axis when scaling
* or rotating, positioned at (1, 1) in the transformation matrix.
*
* @name Matrix#d
* @type Number
*/
/**
* The distance by which to translate along the x axis, positioned at (2, 0)
* in the transformation matrix.
*
* @name Matrix#tx
* @type Number
*/
/**
* The distance by which to translate along the y axis, positioned at (2, 1)
* in the transformation matrix.
*
* @name Matrix#ty
* @type Number
*/
/**
* The transform values as an array, in the same sequence as they are passed
* to {@link #initialize(a, c, b, d, tx, ty)}.
*
* @bean
* @type Number[]
*/
getValues: function() {
return [ this._a, this._c, this._b, this._d, this._tx, this._ty ];
},
/**
* The translation of the matrix as a vector.
*
* @bean
* @type Point
*/
getTranslation: function() {
// No decomposition is required to extract translation.
return new Point(this._tx, this._ty);
},
/**
* The scaling values of the matrix, if it can be decomposed.
*
* @bean
* @type Point
* @see #decompose()
*/
getScaling: function() {
return (this.decompose() || {}).scaling;
},
/**
* The rotation angle of the matrix, if it can be decomposed.
*
* @bean
* @type Number
* @see #decompose()
*/
getRotation: function() {
return (this.decompose() || {}).rotation;
},
/**
* Applies this matrix to the specified Canvas Context.
*
* @param {CanvasRenderingContext2D} ctx
*/
applyToContext: function(ctx) {
if (!this.isIdentity()) {
ctx.transform(this._a, this._c, this._b, this._d,
this._tx, this._ty);
}
}
}, Base.each(['a', 'c', 'b', 'd', 'tx', 'ty'], function(key) {
// Create getters and setters for all internal attributes.
var part = Base.capitalize(key),
prop = '_' + key;
this['get' + part] = function() {
return this[prop];
};
this['set' + part] = function(value) {
this[prop] = value;
this._changed();
};
}, {}));
|
// https://www.reddit.com/r/dailyprogrammer/comments/q2v2k/2232012_challenge_14_easy/
"use strict";
const sequenceBlockReverse = (sequence, blockSize) => {
let result = [];
for (let i=0; i<sequence.length; i+=blockSize) {
result = result.concat(sequence.slice(i,i+blockSize).reverse());
}
return result;
}
console.log(sequenceBlockReverse([12,24,32,44,55,66],2));
console.log(sequenceBlockReverse([1,2,3,4,5,6,7,8,9],3));
|
'use strict';
var gulp = require('gulp'),
lazypipe = require('lazypipe'),
karma = require('gulp-karma'),
runSequence = require('run-sequence'),
bump = require('gulp-bump'),
tagVersion = require('gulp-tag-version'),
git = require('gulp-git'),
jshint = require('gulp-jshint');
function getJSHintPipe(rc) {
return lazypipe()
.pipe(jshint, rc || '.jshintrc')
.pipe(jshint.reporter, 'jshint-stylish')
.pipe(jshint.reporter, 'fail');
}
gulp.task('jshint', ['jshint:src', 'jshint:gulpfile']);
gulp.task('jshint:src', function() {
return gulp.src('index.js')
.pipe(getJSHintPipe()());
});
gulp.task('jshint:gulpfile', function() {
return gulp.src('gulpfile.js')
.pipe(getJSHintPipe()());
});
function karmaPipe(action) {
return gulp.src('test/**/*.js')
.pipe(karma({
configFile: 'karma.conf.js',
action: action
})).on('error', function(err) {
throw err;
});
}
gulp.task('karma:watch', function() {
return karmaPipe('watch');
});
gulp.task('karma', function() {
return karmaPipe('run');
});
gulp.task('bump', function() {
return gulp.src('package.json')
.pipe(bump({ type: gulp.env.type || 'patch' }))
.pipe(gulp.dest('./'));
});
gulp.task('bump-commit', function() {
var version = require('./package.json').version;
return gulp.src(['package.json'])
.pipe(git.commit('Release v' + version));
});
gulp.task('tag', function() {
return gulp.src('package.json')
.pipe(tagVersion());
});
gulp.task('release', function(cb) {
runSequence(
'jshint',
'bump',
'bump-commit',
'tag',
cb
);
});
gulp.task('default', ['jshint', 'karma']);
|
const defaults = {
// Disable
enabled: true,
// Custom media title
title: '',
// Logging to console
debug: false,
// Auto play (if supported)
autoplay: false,
// Only allow one media playing at once (vimeo only)
autopause: true,
// Allow inline playback on iOS (this effects YouTube/Vimeo - HTML5 requires the attribute present)
// TODO: Remove iosNative fullscreen option in favour of this (logic needs work)
playsinline: true,
// Default time to skip when rewind/fast forward
seekTime: 10,
// Default volume
volume: 1,
muted: false,
// Pass a custom duration
duration: null,
// Display the media duration on load in the current time position
// If you have opted to display both duration and currentTime, this is ignored
displayDuration: true,
// Invert the current time to be a countdown
invertTime: true,
// Clicking the currentTime inverts it's value to show time left rather than elapsed
toggleInvert: true,
// Aspect ratio (for embeds)
ratio: '16:9',
// Click video container to play/pause
clickToPlay: true,
// Auto hide the controls
hideControls: true,
// Reset to start when playback ended
resetOnEnd: false,
// Disable the standard context menu
disableContextMenu: true,
// Sprite (for icons)
loadSprite: true,
iconPrefix: 'plyr',
iconUrl: 'https://cdn.plyr.io/3.5.2/plyr.svg',
// Blank video (used to prevent errors on source change)
blankVideo: 'https://cdn.plyr.io/static/blank.mp4',
// Quality default
quality: {
default: 576,
options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240],
},
// Set loops
loop: {
active: false,
// start: null,
// end: null,
},
// Speed default and options to display
speed: {
selected: 1,
options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2],
},
// Keyboard shortcut settings
keyboard: {
focused: true,
global: false,
},
// Display tooltips
tooltips: {
controls: false,
seek: true,
},
// Captions settings
captions: {
active: false,
language: 'auto',
// Listen to new tracks added after Plyr is initialized.
// This is needed for streaming captions, but may result in unselectable options
update: false,
},
// Fullscreen settings
fullscreen: {
enabled: true, // Allow fullscreen?
fallback: true, // Fallback using full viewport/window
iosNative: false, // Use the native fullscreen in iOS (disables custom controls)
},
// Local storage
storage: {
enabled: true,
key: 'plyr',
},
// Default controls
controls: [
'play-large',
// 'restart',
// 'rewind',
'play',
// 'fast-forward',
'progress',
'current-time',
'mute',
'volume',
'captions',
'settings',
'pip',
'airplay',
// 'download',
'fullscreen',
],
settings: ['captions', 'quality', 'speed'],
// Localisation
i18n: {
restart: 'Restart',
rewind: 'Rewind {seektime}s',
play: 'Play',
pause: 'Pause',
fastForward: 'Forward {seektime}s',
seek: 'Seek',
seekLabel: '{currentTime} of {duration}',
played: 'Played',
buffered: 'Buffered',
currentTime: 'Current time',
duration: 'Duration',
volume: 'Volume',
mute: 'Mute',
unmute: 'Unmute',
enableCaptions: 'Enable captions',
disableCaptions: 'Disable captions',
download: 'Download',
enterFullscreen: 'Enter fullscreen',
exitFullscreen: 'Exit fullscreen',
frameTitle: 'Player for {title}',
captions: 'Captions',
settings: 'Settings',
menuBack: 'Go back to previous menu',
speed: 'Speed',
normal: 'Normal',
quality: 'Quality',
loop: 'Loop',
start: 'Start',
end: 'End',
all: 'All',
reset: 'Reset',
disabled: 'Disabled',
enabled: 'Enabled',
advertisement: 'Ad',
qualityBadge: {
2160: '4K',
1440: 'HD',
1080: 'HD',
720: 'HD',
576: 'SD',
480: 'SD',
},
},
// URLs
urls: {
download: null,
vimeo: {
sdk: 'https://player.vimeo.com/api/player.js',
iframe: 'https://player.vimeo.com/video/{0}?{1}',
api: 'https://vimeo.com/api/v2/video/{0}.json',
},
youtube: {
sdk: 'https://www.youtube.com/iframe_api',
api:
'https://www.googleapis.com/youtube/v3/videos?id={0}&key={1}&fields=items(snippet(title))&part=snippet',
},
googleIMA: {
sdk: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js',
},
},
// Custom control listeners
listeners: {
seek: null,
play: null,
pause: null,
restart: null,
rewind: null,
fastForward: null,
mute: null,
volume: null,
captions: null,
download: null,
fullscreen: null,
pip: null,
airplay: null,
speed: null,
quality: null,
loop: null,
language: null,
},
// Events to watch and bubble
events: [
// Events to watch on HTML5 media elements and bubble
// https://developer.mozilla.org/en/docs/Web/Guide/Events/Media_events
'ended',
'progress',
'stalled',
'playing',
'waiting',
'canplay',
'canplaythrough',
'loadstart',
'loadeddata',
'loadedmetadata',
'timeupdate',
'volumechange',
'play',
'pause',
'error',
'seeking',
'seeked',
'emptied',
'ratechange',
'cuechange',
// Custom events
'download',
'enterfullscreen',
'exitfullscreen',
'captionsenabled',
'captionsdisabled',
'languagechange',
'controlshidden',
'controlsshown',
'ready',
// YouTube
'statechange',
// Quality
'qualitychange',
// Ads
'adsloaded',
'adscontentpause',
'adscontentresume',
'adstarted',
'adsmidpoint',
'adscomplete',
'adsallcomplete',
'adsimpression',
'adsclick',
],
// Selectors
// Change these to match your template if using custom HTML
selectors: {
editable: 'input, textarea, select, [contenteditable]',
container: '.plyr',
controls: {
container: null,
wrapper: '.plyr__controls',
},
labels: '[data-plyr]',
buttons: {
play: '[data-plyr="play"]',
pause: '[data-plyr="pause"]',
restart: '[data-plyr="restart"]',
rewind: '[data-plyr="rewind"]',
fastForward: '[data-plyr="fast-forward"]',
mute: '[data-plyr="mute"]',
captions: '[data-plyr="captions"]',
download: '[data-plyr="download"]',
fullscreen: '[data-plyr="fullscreen"]',
pip: '[data-plyr="pip"]',
airplay: '[data-plyr="airplay"]',
settings: '[data-plyr="settings"]',
loop: '[data-plyr="loop"]',
},
inputs: {
seek: '[data-plyr="seek"]',
volume: '[data-plyr="volume"]',
speed: '[data-plyr="speed"]',
language: '[data-plyr="language"]',
quality: '[data-plyr="quality"]',
},
display: {
currentTime: '.plyr__time--current',
duration: '.plyr__time--duration',
buffer: '.plyr__progress__buffer',
loop: '.plyr__progress__loop', // Used later
volume: '.plyr__volume--display',
},
progress: '.plyr__progress',
captions: '.plyr__captions',
caption: '.plyr__caption',
menu: {
quality: '.js-plyr__menu__list--quality',
},
},
// Class hooks added to the player in different states
classNames: {
type: 'plyr--{0}',
provider: 'plyr--{0}',
video: 'plyr__video-wrapper',
embed: 'plyr__video-embed',
embedContainer: 'plyr__video-embed__container',
poster: 'plyr__poster',
posterEnabled: 'plyr__poster-enabled',
ads: 'plyr__ads',
control: 'plyr__control',
controlPressed: 'plyr__control--pressed',
playing: 'plyr--playing',
paused: 'plyr--paused',
stopped: 'plyr--stopped',
loading: 'plyr--loading',
hover: 'plyr--hover',
tooltip: 'plyr__tooltip',
cues: 'plyr__cues',
hidden: 'plyr__sr-only',
hideControls: 'plyr--hide-controls',
isIos: 'plyr--is-ios',
isTouch: 'plyr--is-touch',
uiSupported: 'plyr--full-ui',
noTransition: 'plyr--no-transition',
display: {
time: 'plyr__time',
},
menu: {
value: 'plyr__menu__value',
badge: 'plyr__badge',
open: 'plyr--menu-open',
},
captions: {
enabled: 'plyr--captions-enabled',
active: 'plyr--captions-active',
},
fullscreen: {
enabled: 'plyr--fullscreen-enabled',
fallback: 'plyr--fullscreen-fallback',
},
pip: {
supported: 'plyr--pip-supported',
active: 'plyr--pip-active',
},
airplay: {
supported: 'plyr--airplay-supported',
active: 'plyr--airplay-active',
},
tabFocus: 'plyr__tab-focus',
previewThumbnails: {
// Tooltip thumbs
thumbContainer: 'plyr__preview-thumb',
thumbContainerShown: 'plyr__preview-thumb--is-shown',
imageContainer: 'plyr__preview-thumb__image-container',
timeContainer: 'plyr__preview-thumb__time-container',
// Scrubbing
scrubbingContainer: 'plyr__preview-scrubbing',
scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown',
},
},
// Embed attributes
attributes: {
embed: {
provider: 'data-plyr-provider',
id: 'data-plyr-embed-id',
},
},
// API keys
keys: {
google: null,
},
// Advertisements plugin
// Register for an account here: http://vi.ai/publisher-video-monetization/?aid=plyrio
ads: {
enabled: false,
publisherId: '',
tagUrl: '',
},
// Preview Thumbnails plugin
previewThumbnails: {
enabled: false,
src: '',
},
// Vimeo plugin
vimeo: {
byline: false,
portrait: false,
title: false,
speed: true,
transparent: false,
},
// YouTube plugin
youtube: {
noCookie: false, // Whether to use an alternative version of YouTube without cookies
rel: 0, // No related vids
showinfo: 0, // Hide info
iv_load_policy: 3, // Hide annotations
modestbranding: 1, // Hide logos as much as possible (they still show one in the corner when paused)
},
};
export default defaults;
|
var app = app || {};
(function(){
app.TestButton = React.createClass({displayName: "TestButton",
handleClick: function() {
this.props.submitTestTask(this.props.btnType);
},
render: function() {
return ( React.createElement("button", {onClick: this.handleClick,
className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) );
}
});
app.CodeEditor = React.createClass({displayName: "CodeEditor",
handleType:function(){
this.props.updateCode(this.editor.session.getValue());
},
componentDidMount:function(){
this.editor = ace.edit("codeeditor");
this.editor.setTheme("ace/theme/clouds_midnight");
this.editor.setOptions({
fontSize: "1.2em"
});
this.editor.session.setMode("ace/mode/"+this.props.language);
},
render:function(){
return (
React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType})
);
}
});
app.UrlEditor = React.createClass({displayName: "UrlEditor",
getInitialState: function(){
return {
url_vaild:true
}
},
handleChange:function(){
//if url valid, update state, if not, warn
},
render: function(){
return (
React.createElement("input", {className: "input-url input-right", ref: "urlInput", placeholder: "Type Server or App Url"})
);
}
});
})();
|
import test from 'ava';
import mE from '../';
/* Suppress console info/warnings, we really couldn't care less about them. */
console.info = () => { };
console.warn = () => { };
test('Arrow Function Export', t => {
const moduleExport = mE(module);
moduleExport(() => { });
t.is(typeof module.exports, 'function', 'Default export is not a function');
t.pass();
});
test('Bare Function Export', t => {
const moduleExport = mE(module);
moduleExport(() => { });
t.is(typeof module.exports, 'function', 'Default export is not a function');
t.pass();
});
test('Named Function Export', t => {
const moduleExport = mE(module);
function NamedFunc() { }
moduleExport(NamedFunc);
t.is(typeof module.exports, 'function', 'Default export is not a function');
t.pass();
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ClusterDetailView = function (_React$Component) {
_inherits(ClusterDetailView, _React$Component);
function ClusterDetailView(props) {
_classCallCheck(this, ClusterDetailView);
//Create event binding here
var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ClusterDetailView).call(this, props));
_this.onWindowClick = _this.onWindowClick.bind(_this);
_this.mainComponentStyle = _this.mainComponentStyle.bind(_this);
_this.containerStyle = _this.backdropStyle.bind(_this);
return _this;
}
_createClass(ClusterDetailView, [{
key: 'onWindowClick',
value: function () {
function onWindowClick(event) {
event.stopPropagation();
}
return onWindowClick;
}()
}, {
key: 'backdropStyle',
value: function () {
function backdropStyle() {
var style = {
position: "fixed",
width: "100%",
height: "100%",
backgroundColor: "rgba(0, 0, 0, 0.5)",
top: "0",
left: "0"
};
return style;
}
return backdropStyle;
}()
}, {
key: 'mainComponentStyle',
value: function () {
function mainComponentStyle() {
var style = {
zIndex: "100",
border: "solid 1px black",
position: "fixed",
left: "12.5%",
top: "5%",
height: "90%",
width: "75%",
backgroundColor: "#FFFFFF"
};
return Object.assign({}, style, this.props.style);
}
return mainComponentStyle;
}()
}, {
key: 'render',
value: function () {
function render() {
return _react2['default'].createElement(
'div',
{ style: this.backdropStyle(), onClick: this.props.onClick },
_react2['default'].createElement(
'div',
{ style: this.mainComponentStyle(), onClick: this.onWindowClick },
this.props.element
)
);
}
return render;
}()
}]);
return ClusterDetailView;
}(_react2['default'].Component);
ClusterDetailView.propTypes = {
onClick: _react2['default'].PropTypes.func,
element: _react2['default'].PropTypes.element.isRequired,
style: _react2['default'].PropTypes.object
};
ClusterDetailView.defaultProps = {
style: {}
};
exports['default'] = ClusterDetailView;
|
var tap = require('tap');
var xelement = require('../lib/xelement');
var fs = require('fs');
var xmlString = "";
var xeleCatalog;
tap.test("Parsing xml", function (t) {
xmlString = fs.readFileSync('./sampledata.xml', 'utf8');
try {
xeleCatalog = xelement.Parse(xmlString);
t.equal(xeleCatalog.name, "catalog");
t.equal(xeleCatalog.elements.length, 12);
}
catch (e) {
t.bailout("unable to parse the xml...");
}
t.done();
});
//Creating a new instance
tap.test("Create new instance", function (t) {
var ele = new xelement.XElement("Root");
ele.value = "Sample Value";
ele.attr.Attr1 = "att val 1";
t.equal(ele.name , "Root");
t.equal(ele.value, "Sample Value");
t.equal(ele.attr.Attr1, "att val 1");
t.done();
});
//descendants
tap.test("Get all descendants(author)", function (t) {
var descs = xeleCatalog.descendants('author', true);
t.equal(descs.length, 12);
t.end();
});
//descendantsAndSelf
tap.test("Get all descendants and self(author)", function (t) {
var descs = xeleCatalog.descendantsAndSelf('author');
t.equal(descs[0].name, "catalog");
t.equal(descs.length, 13);
t.end();
});
//descendantFirst
tap.test("Get first descendant(author)", function (t) {
var fd = xeleCatalog.descendantFirst('author1');
t.equal(fd, undefined);
fd = xeleCatalog.descendantFirst('author');
t.equal(fd.name, "author");
t.equal(fd.value, "Gambardella, Matthew");
t.end();
});
//ancestor
tap.test("Get ancestor of element(author)", function (t) {
var fd = xeleCatalog.descendantFirst('author');
var ba = fd.ancestor('book', true)
t.equal(ba.name, 'book');
t.equal(ba.attr.id, "bk101");
ba = fd.ancestor('catalog')
t.equal(ba.name, 'catalog');
t.end();
});
//siblings
tap.test("Get siblings of (book)", function (t) {
var fd = xeleCatalog.descendantFirst('book');
var siblings = fd.siblings();
t.equal(siblings.length, 11);
var foundSelf = false;
for (var i = 0; i < siblings.length; i++) {
if (siblings[i] == fd) {
foundSelf = true;
break;
}
}
t.equal(foundSelf, false);
t.equal(fd.firstElement().siblings("genre")[0].value, "Computer");
t.end();
});
//element
tap.test("Get element with name", function (t) {
var fd = xeleCatalog.element('book1');
t.equal(fd, undefined);
fd = xeleCatalog.element('book');
t.equal(fd.name, 'book');
t.equal(fd.attr.id, "bk101");
t.end();
});
//elements
tap.test("Get elements with book name", function (t) {
var eles = xeleCatalog.getElements('book', true);
t.equal(eles.length, 12);
var isAllBooks = true;
for (var i = 0; i < eles.length; i++) {
if (eles[i].name != "book") {
isAllBooks = false;
break;
}
}
t.equal(isAllBooks, true);
t.end();
});
//firstElement
tap.test("Get elements first element", function (t) {
var fe = xeleCatalog.firstElement();
t.equal(fe.name, "book");
t.equal(fe.attr.id, "bk101");
t.end();
});
//lastElement
tap.test("Get elements last element", function (t) {
var fe = xeleCatalog.lastElement();
t.equal(fe.name, "book");
t.equal(fe.attr.id, "bk112");
t.end();
});
//previousSibling
tap.test("Get previous sibling element", function (t) {
var fd = xeleCatalog.descendantFirst('title', true);
var ps = fd.previousSibling();
t.equal(ps.name, "author");
t.equal(fd.previousSibling().previousSibling(), undefined);
t.end();
});
//nextSibling
tap.test("Get next sibling element", function (t) {
var fd = xeleCatalog.descendantFirst('publish_date');
var ps = fd.nextSibling();
t.equal(ps.name, "description");
t.equal(fd.nextSibling().nextSibling(), undefined);
t.end();
});
//index
tap.test("Get index of element", function (t) {
var fd = xeleCatalog.elements.where(function (o) { return o.attr.id == "bk104"; });
t.equal(fd[0].index(), 3);
t.end();
});
//setAttr
tap.test("Get set Attribute of element", function (t) {
var fd = xeleCatalog.descendantFirst('book');
fd.setAttr('NewAttr', '100');
t.equal(fd.attr.NewAttr, '100');
fd.setAttr('NewAttr', '1001');
t.equal(fd.attr.NewAttr, '1001');
t.end();
});
//getAttr
tap.test("Get get Attribute of element", function (t) {
var fd = xeleCatalog.descendantFirst('book');
t.equal(fd.getAttr('NewAttr'), '1001');
t.equal(fd.getAttr('XYZ'), '');
t.end();
});
//removeAttr
tap.test("Get get Attribute of element", function (t) {
var fd = xeleCatalog.descendantFirst('book');
fd.removeAttr('NewAttr');
t.equal(fd.attr["NewAttr"], undefined);
t.end();
});
/*
//element
tap.test("Get element by name", function (t) {
var fd = xeleCatalog.descendantFirst('book');
var dsc = fd.element('publish_date');
t.equal(dsc.name , "publish_date");
t.end();
});*/
//add
tap.test("Add element", function (t) {
var dummy = {};
xeleCatalog.add(dummy);//adding invalid object
t.equal(xeleCatalog.lastElement().attr.id, "bk112");
//adding single element
var newBook = new xelement.XElement("book");
newBook.attr.id = "bk113";
xeleCatalog.add(newBook);
t.equal(xeleCatalog.lastElement().attr.id, "bk113");
var newElements = [];
for (var i = 0; i < 5; i++) {
newBook = new xelement.XElement("book");
newBook.attr.id = "bk" + (113 + i).toString();
newElements.push(newBook);
}
xeleCatalog.add(newElements); //Adding range of elements
t.equal(xeleCatalog.lastElement().attr.id, "bk117");
t.end();
});
//createElement
tap.test("Create clement", function (t) {
var newEle = xeleCatalog.createElement("TestElement");
newEle.value = "100";
t.equal(xeleCatalog.lastElement().name, newEle.name);
t.end();
});
//setElementValue
tap.test("Set element value", function (t) {
xeleCatalog.setElementValue("TestElement", 1001);
t.equal(xeleCatalog.lastElement().value, 1001);
xeleCatalog.setElementValue("TestElement1", 123);
t.equal(xeleCatalog.lastElement().value, 123);
t.end();
});
//getElementValue
tap.test("Get element value", function (t) {
var vl = xeleCatalog.getElementValue("TestElement1", true);
t.equal(vl, 123);
t.equal(xeleCatalog.getElementValue("ElementDoneExists"), "");
t.end();
});
//toXmlString
tap.test("To Xml String", function (t) {
var vl = xeleCatalog.descendantFirst('book');
var cln = xelement.Parse(vl.toXmlString());
t.equal(vl.name, cln.name);
t.equal(vl.elements.length, cln.elements.length);
t.end();
});
//************************EXTENSIONS***********************
//where extension
tap.test("where extension", function (t) {
var wr = xeleCatalog.descendants("book").where(function (o) { return o.attr.id == "bk109" });
t.equal(wr[0].name, "book");
t.equal(wr[0].attr.id, "bk109");
t.end();
});
//select
tap.test("select extension", function (t) {
var wr = xeleCatalog.descendants("author").select(function (o) { return o.value; });
t.equal(wr[8], "Kress, Peter");
t.end();
});
//selectMany
tap.test("select many extension", function (t) {
var wr = xeleCatalog.descendants("book").selectMany(function (o) { return o.firstElement() });
t.equal(wr[8].value, "Kress, Peter");
t.end();
});
/*
//indexOf extension
tap.test("remove extension", function (t) {
var wr = xeleCatalog.descendants("book");
var item = wr[7];
t.equal(wr.indexOf(item),7);
t.end();
});*/
/*
//remove extension
tap.test("remove extension", function (t) {
var wr = xeleCatalog.descendants("book");
var item = wr[7];
var c = wr.length;
wr.remove(item);
t.equal(wr.length + 1, c);
t.end();
});*/
//forEach
tap.test("select many extension", function (t) {
var wr = xeleCatalog.descendants("book");
wr.forEach(function (o) {
o.setAttr('newAttr', 'someValue');
});
var isUpdated = true;
for (var i = 0; i < wr.length; i++) {
if (wr[i].attr.newAttr != "someValue") {
isUpdated = false;
break;
}
}
t.equal(isUpdated, true);
t.end();
});
/*
tap.test("indexOf extension", function (t) {
var wr = xeleCatalog.descendants("book");
var book8 = wr.where(function (o) {
return o.attr.id == "bk108";
});
t.equal(wr.indexOf(book8[0]), 7);
t.end();
});*/
//**************END OF EXTENSIONS**************************
//remove
tap.test("remove a element", function (t) {
var wr = xeleCatalog.element("TestElement1");
t.equal(xeleCatalog.lastElement().name, "TestElement1");
wr.remove();
t.equal(xeleCatalog.lastElement().name, "TestElement");
t.end();
});
//removeAll
tap.test("remove all elements from a element", function (t) {
var fb = xeleCatalog.descendantFirst('book');
t.equal(fb.elements.length, 6);
fb.removeAll();
t.equal(fb.elements.length, 0);
t.end();
});
|
'use strict';
var User = require('../models/User.js');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
module.exports = function(router) {
router.use(bodyParser.json());
/*****************************************************
//POST to /user to create a user
*****************************************************/
router.post('/users', function(req, res) {
if (!req.body.name) {
res.json({msg: 'Invalid input.'});
}
var newUser = new User({
name: req.body.name,
favMovie: req.body.favMovie,
favArtist: req.body.favArtist,
favFood: req.body.favFood,
nameID: req.body.name.toLowerCase()
});
User.findOne({nameID: req.body.name.toLowerCase()}, function(err, doc) {
if (err) {
console.log(err);
} else if (doc) {
res.json({msg: 'User already exists.'});
} else {
newUser.save(function(error, data) {
if (error) {
console.log(error);
}
res.json({name: newUser.name, favMovie: newUser.favMovie, favArtist: newUser.favArtist, favFood: newUser.favFood});
});
}
});
}); //End POST
/*****************************************************
//GET from /users to read all users or a specific user
*****************************************************/
router.get('/users', function(req, res) {
User.find({},{_id:0, __v:0, nameID:0}, function(err, data) {
if (err) {
console.log(err);
} else {
res.json(data);
}
})
}); //End GET
router.get('/users/:name', function(req, res) {
var userID = req.params.name.toLowerCase();
User.findOne({nameID: userID}, {_id:0, __v:0, nameID:0}, function(err, data) {
if (err) {
console.log(err);
} else if (data == null) {
res.json({msg: 'User does not exist.'});
} else {
res.json(data);
}
});
}); //End GET
/*****************************************************
//PUT to /users to update a user
*****************************************************/
router.put('/users/:name', function(req, res) {
if (!req.body.name) {
res.json({msg:'Invalid input.'})
} else if (req.params.name.toLowerCase() !== req.body.name.toLowerCase()) {
res.json({msg:'User could not be updated.'});
} else {
var userID = req.body.name.toLowerCase();
var currUser = new User({
name: req.body.name,
favMovie: req.body.favMovie,
favArtist: req.body.favArtist,
favFood: req.body.favFood,
nameID: userID
});
User.findOne({nameID: userID}, function(err, data) {
if (err) {
console.log(err);
} else if (data == null) {
res.json({msg: 'User does not exist.'});
} else {
currUser._id = data._id;
User.update({nameID: userID}, currUser, function(error) {
if (error) {
console.log(error);
} else {
res.json({msg: req.body.name + ' has been updated!'});
}
});
}
});
}
}); //End PUT
/*****************************************************
//DELETE to /users to delete a user
*****************************************************/
router.delete('/users/:name', function(req, res) {
User.findOne({nameID: req.params.name.toLowerCase()}, function(err, data) {
if (err) {
console.log(err);
} else if (data == null) {
res.json({msg: 'User does not exist.'});
} else {
User.remove({nameID:req.params.name.toLowerCase()}, function(err) {
if (err) {
console.log(err);
} else {
res.json({msg: 'User was deleted.'});
}
});
}
});
}); //End DELETE
} //End module.exports
|
"use strict";
var path = require('path'),
_ = require('lodash'),
fs = require('fs-extra'),
Pattern = require('./object_factory').Pattern,
CompileState = require('./object_factory').CompileState,
pph = require('./pseudopattern_hunter'),
mp = require('./markdown_parser'),
plutils = require('./utilities'),
dataLoader = require('./data_loader')(),
patternEngines = require('./pattern_engines'),
lh = require('./lineage_hunter'),
lih = require('./list_item_hunter'),
smh = require('./style_modifier_hunter'),
ph = require('./parameter_hunter'),
jsonCopy = require('./json_copy'),
ch = require('./changes_hunter');
const markdown_parser = new mp();
const changes_hunter = new ch();
var pattern_assembler = function () {
// HELPER FUNCTIONS
function getPartial(partialName, patternlab) {
//look for exact partial matches
for (var i = 0; i < patternlab.patterns.length; i++) {
if (patternlab.patterns[i].patternPartial === partialName) {
return patternlab.patterns[i];
}
}
//else look by verbose syntax
for (var i = 0; i < patternlab.patterns.length; i++) {
switch (partialName) {
case patternlab.patterns[i].relPath:
case patternlab.patterns[i].verbosePartial:
return patternlab.patterns[i];
}
}
//return the fuzzy match if all else fails
for (var i = 0; i < patternlab.patterns.length; i++) {
var partialParts = partialName.split('-'),
partialType = partialParts[0],
partialNameEnd = partialParts.slice(1).join('-');
if (patternlab.patterns[i].patternPartial.split('-')[0] === partialType && patternlab.patterns[i].patternPartial.indexOf(partialNameEnd) > -1) {
return patternlab.patterns[i];
}
}
plutils.warning('Could not find pattern referenced with partial syntax ' + partialName + '. This can occur when a pattern was renamed, moved, or no longer exists but it still called within a different template somewhere.');
return undefined;
}
function buildListItems(container) {
//combine all list items into one structure
var list = [];
for (var item in container.listitems) {
if (container.listitems.hasOwnProperty(item)) {
list.push(container.listitems[item]);
}
}
container.listItemArray = plutils.shuffle(list);
for (var i = 1; i <= container.listItemArray.length; i++) {
var tempItems = [];
if (i === 1) {
tempItems.push(container.listItemArray[0]);
container.listitems['' + i ] = tempItems;
} else {
for (var c = 1; c <= i; c++) {
tempItems.push(container.listItemArray[c - 1]);
container.listitems['' + i ] = tempItems;
}
}
}
}
/*
* Deprecated in favor of .md 'status' frontmatter inside a pattern. Still used for unit tests at this time.
* Will be removed in future versions
*/
function setState(pattern, patternlab, displayDeprecatedWarning) {
if (patternlab.config.patternStates && patternlab.config.patternStates[pattern.patternPartial]) {
if (displayDeprecatedWarning) {
plutils.error("Deprecation Warning: Using patternlab-config.json patternStates object will be deprecated in favor of the state frontmatter key associated with individual pattern markdown files.");
console.log("This feature will still work in it's current form this release (but still be overridden by the new parsing method), and will be removed in the future.");
}
pattern.patternState = patternlab.config.patternStates[pattern.patternPartial];
}
}
function addPattern(pattern, patternlab) {
//add the link to the global object
patternlab.data.link[pattern.patternPartial] = '/patterns/' + pattern.patternLink;
//only push to array if the array doesn't contain this pattern
var isNew = true;
for (var i = 0; i < patternlab.patterns.length; i++) {
//so we need the identifier to be unique, which patterns[i].relPath is
if (pattern.relPath === patternlab.patterns[i].relPath) {
//if relPath already exists, overwrite that element
patternlab.patterns[i] = pattern;
patternlab.partials[pattern.patternPartial] = pattern.extendedTemplate || pattern.template;
isNew = false;
break;
}
}
// if the pattern is new, we must register it with various data structures!
if (isNew) {
if (patternlab.config.debug) {
console.log('found new pattern ' + pattern.patternPartial);
}
// do global registration
if (pattern.isPattern) {
patternlab.partials[pattern.patternPartial] = pattern.extendedTemplate || pattern.template;
// do plugin-specific registration
pattern.registerPartial();
} else {
patternlab.partials[pattern.patternPartial] = pattern.patternDesc;
}
patternlab.graph.add(pattern);
patternlab.patterns.push(pattern);
}
}
function addSubtypePattern(subtypePattern, patternlab) {
patternlab.subtypePatterns[subtypePattern.patternPartial] = subtypePattern;
}
// Render a pattern on request. Long-term, this should probably go away.
function renderPattern(pattern, data, partials) {
// if we've been passed a full Pattern, it knows what kind of template it
// is, and how to render itself, so we just call its render method
if (pattern instanceof Pattern) {
return pattern.render(data, partials);
} else {
// otherwise, assume it's a plain mustache template string, and we
// therefore just need to create a dummpy pattern to be able to render
// it
var dummyPattern = Pattern.createEmpty({extendedTemplate: pattern});
return patternEngines.mustache.renderPattern(dummyPattern, data, partials);
}
}
function parsePatternMarkdown(currentPattern, patternlab) {
try {
var markdownFileName = path.resolve(patternlab.config.paths.source.patterns, currentPattern.subdir, currentPattern.fileName + ".md");
changes_hunter.checkLastModified(currentPattern, markdownFileName);
var markdownFileContents = fs.readFileSync(markdownFileName, 'utf8');
var markdownObject = markdown_parser.parse(markdownFileContents);
if (!plutils.isObjectEmpty(markdownObject)) {
//set keys and markdown itself
currentPattern.patternDescExists = true;
currentPattern.patternDesc = markdownObject.markdown;
//Add all markdown to the currentPattern, including frontmatter
currentPattern.allMarkdown = markdownObject;
//consider looping through all keys eventually. would need to blacklist some properties and whitelist others
if (markdownObject.state) {
currentPattern.patternState = markdownObject.state;
}
if (markdownObject.order) {
currentPattern.order = markdownObject.order;
}
if (markdownObject.hidden) {
currentPattern.hidden = markdownObject.hidden;
}
if (markdownObject.excludeFromStyleguide) {
currentPattern.excludeFromStyleguide = markdownObject.excludeFromStyleguide;
}
if (markdownObject.tags) {
currentPattern.tags = markdownObject.tags;
}
if (markdownObject.title) {
currentPattern.patternName = markdownObject.title;
}
if (markdownObject.links) {
currentPattern.links = markdownObject.links;
}
} else {
if (patternlab.config.debug) {
console.log('error processing markdown for ' + currentPattern.patternPartial);
}
}
if (patternlab.config.debug) {
console.log('found pattern-specific markdown for ' + currentPattern.patternPartial);
}
}
catch (err) {
// do nothing when file not found
if (err.code !== 'ENOENT') {
console.log('there was an error setting pattern keys after markdown parsing of the companion file for pattern ' + currentPattern.patternPartial);
console.log(err);
}
}
}
/**
* A helper that unravels a pattern looking for partials or listitems to unravel.
* The goal is really to convert pattern.template into pattern.extendedTemplate
* @param pattern - the pattern to decompose
* @param patternlab - global data store
* @param ignoreLineage - whether or not to hunt for lineage for this pattern
*/
function decomposePattern(pattern, patternlab, ignoreLineage) {
var lineage_hunter = new lh(),
list_item_hunter = new lih();
pattern.extendedTemplate = pattern.template;
//find how many partials there may be for the given pattern
var foundPatternPartials = pattern.findPartials();
//find any listItem blocks that within the pattern, even if there are no partials
list_item_hunter.process_list_item_partials(pattern, patternlab);
// expand any partials present in this pattern; that is, drill down into
// the template and replace their calls in this template with rendered
// results
if (pattern.engine.expandPartials && (foundPatternPartials !== null && foundPatternPartials.length > 0)) {
// eslint-disable-next-line
expandPartials(foundPatternPartials, list_item_hunter, patternlab, pattern);
// update the extendedTemplate in the partials object in case this
// pattern is consumed later
patternlab.partials[pattern.patternPartial] = pattern.extendedTemplate;
}
//find pattern lineage
if (!ignoreLineage) {
lineage_hunter.find_lineage(pattern, patternlab);
}
//add to patternlab object so we can look these up later.
addPattern(pattern, patternlab);
}
function processPatternIterative(relPath, patternlab) {
var relativeDepth = (relPath.match(/\w(?=\\)|\w(?=\/)/g) || []).length;
if (relativeDepth > 2) {
console.log('');
plutils.warning('Warning:');
plutils.warning('A pattern file: ' + relPath + ' was found greater than 2 levels deep from ' + patternlab.config.paths.source.patterns + '.');
plutils.warning('It\'s strongly suggested to not deviate from the following structure under _patterns/');
plutils.warning('[patternType]/[patternSubtype]/[patternName].[patternExtension]');
console.log('');
plutils.warning('While Pattern Lab may still function, assets may 404 and frontend links may break. Consider yourself warned. ');
plutils.warning('Read More: http://patternlab.io/docs/pattern-organization.html');
console.log('');
}
//check if the found file is a top-level markdown file
var fileObject = path.parse(relPath);
if (fileObject.ext === '.md') {
try {
var proposedDirectory = path.resolve(patternlab.config.paths.source.patterns, fileObject.dir, fileObject.name);
var proposedDirectoryStats = fs.statSync(proposedDirectory);
if (proposedDirectoryStats.isDirectory()) {
var subTypeMarkdownFileContents = fs.readFileSync(proposedDirectory + '.md', 'utf8');
var subTypeMarkdown = markdown_parser.parse(subTypeMarkdownFileContents);
var subTypePattern = new Pattern(relPath, null, patternlab);
subTypePattern.patternSectionSubtype = true;
subTypePattern.patternLink = subTypePattern.name + '/index.html';
subTypePattern.patternDesc = subTypeMarkdown.markdown;
subTypePattern.flatPatternPath = subTypePattern.flatPatternPath + '-' + subTypePattern.fileName;
subTypePattern.isPattern = false;
subTypePattern.engine = null;
addSubtypePattern(subTypePattern, patternlab);
return subTypePattern;
}
} catch (err) {
// no file exists, meaning it's a pattern markdown file
if (err.code !== 'ENOENT') {
console.log(err);
}
}
}
var pseudopattern_hunter = new pph();
//extract some information
var filename = fileObject.base;
var ext = fileObject.ext;
var patternsPath = patternlab.config.paths.source.patterns;
// skip non-pattern files
if (!patternEngines.isPatternFile(filename, patternlab)) { return null; }
//make a new Pattern Object
var currentPattern = new Pattern(relPath, null, patternlab);
//if file is named in the syntax for variants
if (patternEngines.isPseudoPatternJSON(filename)) {
return currentPattern;
}
//can ignore all non-supported files at this point
if (patternEngines.isFileExtensionSupported(ext) === false) {
return currentPattern;
}
//see if this file has a state
setState(currentPattern, patternlab, true);
//look for a json file for this template
try {
var jsonFilename = path.resolve(patternsPath, currentPattern.subdir, currentPattern.fileName);
let configData = dataLoader.loadDataFromFile(jsonFilename, fs);
if (configData) {
currentPattern.jsonFileData = configData;
if (patternlab.config.debug) {
console.log('processPatternIterative: found pattern-specific config data for ' + currentPattern.patternPartial);
}
}
}
catch (err) {
console.log('There was an error parsing sibling JSON for ' + currentPattern.relPath);
console.log(err);
}
//look for a listitems.json file for this template
try {
var listJsonFileName = path.resolve(patternsPath, currentPattern.subdir, currentPattern.fileName + ".listitems");
let listItemsConfig = dataLoader.loadDataFromFile(listJsonFileName, fs);
if (listItemsConfig) {
currentPattern.listitems = listItemsConfig;
buildListItems(currentPattern);
if (patternlab.config.debug) {
console.log('found pattern-specific listitems config for ' + currentPattern.patternPartial);
}
}
}
catch (err) {
console.log('There was an error parsing sibling listitem JSON for ' + currentPattern.relPath);
console.log(err);
}
//look for a markdown file for this template
parsePatternMarkdown(currentPattern, patternlab);
//add the raw template to memory
var templatePath = path.resolve(patternsPath, currentPattern.relPath);
currentPattern.template = fs.readFileSync(templatePath, 'utf8');
//find any stylemodifiers that may be in the current pattern
currentPattern.stylePartials = currentPattern.findPartialsWithStyleModifiers();
//find any pattern parameters that may be in the current pattern
currentPattern.parameteredPartials = currentPattern.findPartialsWithPatternParameters();
[templatePath, jsonFilename, listJsonFileName].forEach(file => {
changes_hunter.checkLastModified(currentPattern, file);
});
changes_hunter.checkBuildState(currentPattern, patternlab);
//add currentPattern to patternlab.patterns array
addPattern(currentPattern, patternlab);
//look for a pseudo pattern by checking if there is a file containing same name, with ~ in it, ending in .json
pseudopattern_hunter.find_pseudopatterns(currentPattern, patternlab);
return currentPattern;
}
function processPatternRecursive(file, patternlab) {
//find current pattern in patternlab object using var file as a partial
var currentPattern, i;
for (i = 0; i < patternlab.patterns.length; i++) {
if (patternlab.patterns[i].relPath === file) {
currentPattern = patternlab.patterns[i];
}
}
//return if processing an ignored file
if (typeof currentPattern === 'undefined') { return; }
//we are processing a markdown only pattern
if (currentPattern.engine === null) { return; }
//call our helper method to actually unravel the pattern with any partials
decomposePattern(currentPattern, patternlab);
}
/**
* Finds patterns that were modified and need to be rebuilt. For clean patterns load the already
* rendered markup.
*
* @param lastModified
* @param patternlab
*/
function markModifiedPatterns(lastModified, patternlab) {
/**
* If the given array exists, apply a function to each of its elements
* @param {Array} array
* @param {Function} func
*/
const forEachExisting = (array, func) => {
if (array) {
array.forEach(func);
}
};
const modifiedOrNot = _.groupBy(
patternlab.patterns,
p => changes_hunter.needsRebuild(lastModified, p) ? 'modified' : 'notModified');
// For all unmodified patterns load their rendered template output
forEachExisting(modifiedOrNot.notModified, cleanPattern => {
const xp = path.join(patternlab.config.paths.public.patterns, cleanPattern.getPatternLink(patternlab, 'markupOnly'));
// Pattern with non-existing markupOnly files were already marked for rebuild and thus are not "CLEAN"
cleanPattern.patternPartialCode = fs.readFileSync(xp, 'utf8');
});
// For all patterns that were modified, schedule them for rebuild
forEachExisting(modifiedOrNot.modified, p => p.compileState = CompileState.NEEDS_REBUILD);
return modifiedOrNot;
}
function expandPartials(foundPatternPartials, list_item_hunter, patternlab, currentPattern) {
var style_modifier_hunter = new smh(),
parameter_hunter = new ph();
if (patternlab.config.debug) {
console.log('found partials for ' + currentPattern.patternPartial);
}
// determine if the template contains any pattern parameters. if so they
// must be immediately consumed
parameter_hunter.find_parameters(currentPattern, patternlab);
//do something with the regular old partials
for (var i = 0; i < foundPatternPartials.length; i++) {
var partial = currentPattern.findPartial(foundPatternPartials[i]);
var partialPath;
//identify which pattern this partial corresponds to
for (var j = 0; j < patternlab.patterns.length; j++) {
if (patternlab.patterns[j].patternPartial === partial ||
patternlab.patterns[j].relPath.indexOf(partial) > -1)
{
partialPath = patternlab.patterns[j].relPath;
}
}
//recurse through nested partials to fill out this extended template.
processPatternRecursive(partialPath, patternlab);
//complete assembly of extended template
//create a copy of the partial so as to not pollute it after the getPartial call.
var partialPattern = getPartial(partial, patternlab);
var cleanPartialPattern = jsonCopy(partialPattern, `partial pattern ${partial}`);
//if partial has style modifier data, replace the styleModifier value
if (currentPattern.stylePartials && currentPattern.stylePartials.length > 0) {
style_modifier_hunter.consume_style_modifier(cleanPartialPattern, foundPatternPartials[i], patternlab);
}
currentPattern.extendedTemplate = currentPattern.extendedTemplate.replace(foundPatternPartials[i], cleanPartialPattern.extendedTemplate);
}
}
function parseDataLinksHelper(patternlab, obj, key) {
var linkRE, dataObjAsString, linkMatches;
//check for 'link.patternPartial'
linkRE = /(?:'|")(link\.[A-z0-9-_]+)(?:'|")/g;
//stringify the passed in object
dataObjAsString = JSON.stringify(obj);
if (!dataObjAsString) { return obj; }
//find matches
linkMatches = dataObjAsString.match(linkRE);
if (linkMatches) {
for (var i = 0; i < linkMatches.length; i++) {
var dataLink = linkMatches[i];
if (dataLink && dataLink.split('.').length >= 2) {
//get the partial the link refers to
var linkPatternPartial = dataLink.split('.')[1].replace('"', '').replace("'", "");
var pattern = getPartial(linkPatternPartial, patternlab);
if (pattern !== undefined) {
//get the full built link and replace it
var fullLink = patternlab.data.link[linkPatternPartial];
if (fullLink) {
fullLink = path.normalize(fullLink).replace(/\\/g, '/');
if (patternlab.config.debug) {
console.log('expanded data link from ' + dataLink + ' to ' + fullLink + ' inside ' + key);
}
//also make sure our global replace didn't mess up a protocol
fullLink = fullLink.replace(/:\//g, '://');
dataObjAsString = dataObjAsString.replace('link.' + linkPatternPartial, fullLink);
}
} else {
if (patternlab.config.debug) {
console.log('pattern not found for', dataLink, 'inside', key);
}
}
}
}
}
var dataObj;
try {
dataObj = JSON.parse(dataObjAsString);
} catch (err) {
console.log('There was an error parsing JSON for ' + key);
console.log(err);
}
return dataObj;
}
//look for pattern links included in data files.
//these will be in the form of link.* WITHOUT {{}}, which would still be there from direct pattern inclusion
function parseDataLinks(patternlab) {
//look for link.* such as link.pages-blog as a value
patternlab.data = parseDataLinksHelper(patternlab, patternlab.data, 'data.json');
//loop through all patterns
for (var i = 0; i < patternlab.patterns.length; i++) {
patternlab.patterns[i].jsonFileData = parseDataLinksHelper(patternlab, patternlab.patterns[i].jsonFileData, patternlab.patterns[i].patternPartial);
}
}
return {
mark_modified_patterns: function (lastModified, patternlab) {
return markModifiedPatterns(lastModified, patternlab);
},
find_pattern_partials: function (pattern) {
return pattern.findPartials();
},
find_pattern_partials_with_style_modifiers: function (pattern) {
return pattern.findPartialsWithStyleModifiers();
},
find_pattern_partials_with_parameters: function (pattern) {
return pattern.findPartialsWithPatternParameters();
},
find_list_items: function (pattern) {
return pattern.findListItems();
},
setPatternState: function (pattern, patternlab, displayDeprecatedWarning) {
setState(pattern, patternlab, displayDeprecatedWarning);
},
addPattern: function (pattern, patternlab) {
addPattern(pattern, patternlab);
},
addSubtypePattern: function (subtypePattern, patternlab) {
addSubtypePattern(subtypePattern, patternlab);
},
decomposePattern: function (pattern, patternlab, ignoreLineage) {
decomposePattern(pattern, patternlab, ignoreLineage);
},
renderPattern: function (template, data, partials) {
return renderPattern(template, data, partials);
},
process_pattern_iterative: function (file, patternlab) {
return processPatternIterative(file, patternlab);
},
process_pattern_recursive: function (file, patternlab, additionalData) {
processPatternRecursive(file, patternlab, additionalData);
},
getPartial: function (partial, patternlab) {
return getPartial(partial, patternlab);
},
combine_listItems: function (patternlab) {
buildListItems(patternlab);
},
parse_data_links: function (patternlab) {
parseDataLinks(patternlab);
},
parse_data_links_specific: function (patternlab, data, label) {
return parseDataLinksHelper(patternlab, data, label);
},
parse_pattern_markdown: function (pattern, patternlab) {
parsePatternMarkdown(pattern, patternlab);
}
};
};
module.exports = pattern_assembler;
|
function followBoard(boardid) {
if (!boardid) {
return;
}
var data = {
id: boardid
};
$.ajax({
type: "POST",
url: "/board/collect",
data: data
}).done(function (response) {
if(!response.success) {
return console.error("Error:", response);
}
var likeA = $('button.follow-board');
if (likeA.hasClass('rbtn')) {
likeA.removeClass('rbtn');
} else {
likeA.addClass('rbtn');
}
}).error(function(res){
if (res.status == 401) {
$('#signin_modal').modal('show');
}
});
}
// 关注 Board
$(document).on('click', 'button.follow-board', function (event) {
var datas = event.currentTarget.dataset;
auth(function(result) {
if (!result) {
return;
}
if (!datas.id) {
return;
}
followBoard(datas.id);
});
});
|
import app from "./config/app"
import http from "http"
const port = app.get('port')
http.createServer(app).listen(port, ()=>{
console.log('server is running:'+ port)
})
|
import React from 'react';
import { mount } from 'enzyme';
import { expect } from 'chai';
import { createStore } from 'redux';
import rootReducer from '../reducers/rootReducer';
import initialState from '../reducers/initialState';
import { Provider } from 'react-redux';
import ProductTable from './ProductTable'; // eslint-disable-line import/no-named-as-default
import * as types from '../constants/actionTypes';
describe('<ProductTable />', () => {
const products = [{
id: 1,
name: 'test',
description: 'test',
price: 1
}];
let store;
beforeEach((done) => {
store = createStore(rootReducer, initialState);
const unsubscribe = store.subscribe(() => {
unsubscribe();
done();
});
store.dispatch({
type: types.PRODUCTS_REQUEST_SUCCESS,
result: [...products]
});
});
it('should render a ProductTableRow for each product', () => {
const wrapper = mount(
<Provider store={store}>
<ProductTable />
</Provider>
);
const rows = wrapper.find('ProductTableRow');
expect(rows.length).to.equal(products.length);
});
});
|
// Generated by CoffeeScript 1.4.0
/**
* @package Blogs
* @category modules
* @author Nazar Mokrynskyi <nazar@mokrynskyi.com>
* @copyright Copyright (c) 2015, Nazar Mokrynskyi
* @license MIT License, see license.txt
*/
(function() {
(function(L) {
return Polymer({
publish: {
comments_enabled: false
},
ready: function() {
this.jsonld = JSON.parse(this.querySelector('script').innerHTML);
return this.posts = this.jsonld['@graph'];
}
});
})(cs.Language);
}).call(this);
|
var gulp = require('gulp');
var runSequence = require('run-sequence');
gulp.task('build', function() {
var args = [
'unrevAssets',
['browserify', 'sass', 'vendor', 'images', 'xmlMin'],
'html'
];
if (!global.isWatching) {
args.splice(2, 0, 'revAssets');
}
runSequence.apply(this, args);
});
|
// MySQL Client
// -------
const inherits = require('inherits');
const defer = require('lodash/defer');
const map = require('lodash/map');
const { promisify } = require('util');
const Client = require('../../client');
const Transaction = require('./transaction');
const QueryCompiler = require('./query/compiler');
const SchemaCompiler = require('./schema/compiler');
const TableCompiler = require('./schema/tablecompiler');
const ColumnCompiler = require('./schema/columncompiler');
const { makeEscape } = require('../../query/string');
// Always initialize with the "QueryBuilder" and "QueryCompiler"
// objects, which extend the base 'lib/query/builder' and
// 'lib/query/compiler', respectively.
function Client_MySQL(config) {
Client.call(this, config);
}
inherits(Client_MySQL, Client);
Object.assign(Client_MySQL.prototype, {
dialect: 'mysql',
driverName: 'mysql',
_driver() {
return require('mysql');
},
queryCompiler() {
return new QueryCompiler(this, ...arguments);
},
schemaCompiler() {
return new SchemaCompiler(this, ...arguments);
},
tableCompiler() {
return new TableCompiler(this, ...arguments);
},
columnCompiler() {
return new ColumnCompiler(this, ...arguments);
},
transaction() {
return new Transaction(this, ...arguments);
},
_escapeBinding: makeEscape(),
wrapIdentifierImpl(value) {
return value !== '*' ? `\`${value.replace(/`/g, '``')}\`` : '*';
},
// Get a raw connection, called by the `pool` whenever a new
// connection needs to be added to the pool.
acquireRawConnection() {
return new Promise((resolver, rejecter) => {
const connection = this.driver.createConnection(this.connectionSettings);
connection.on('error', (err) => {
connection.__knex__disposed = err;
});
connection.connect((err) => {
if (err) {
// if connection is rejected, remove listener that was registered above...
connection.removeAllListeners();
return rejecter(err);
}
resolver(connection);
});
});
},
// Used to explicitly close a connection, called internally by the pool
// when a connection times out or the pool is shutdown.
async destroyRawConnection(connection) {
try {
const end = promisify((cb) => connection.end(cb));
return await end();
} catch (err) {
connection.__knex__disposed = err;
} finally {
// see discussion https://github.com/knex/knex/pull/3483
defer(() => connection.removeAllListeners());
}
},
validateConnection(connection) {
if (
connection.state === 'connected' ||
connection.state === 'authenticated'
) {
return true;
}
return false;
},
// Grab a connection, run the query via the MySQL streaming interface,
// and pass that through to the stream we've sent back to the client.
_stream(connection, obj, stream, options) {
options = options || {};
const queryOptions = Object.assign({ sql: obj.sql }, obj.options);
return new Promise((resolver, rejecter) => {
stream.on('error', rejecter);
stream.on('end', resolver);
const queryStream = connection
.query(queryOptions, obj.bindings)
.stream(options);
queryStream.on('error', (err) => {
rejecter(err);
stream.emit('error', err);
});
queryStream.pipe(stream);
});
},
// Runs the query on the specified connection, providing the bindings
// and any other necessary prep work.
_query(connection, obj) {
if (!obj || typeof obj === 'string') obj = { sql: obj };
return new Promise(function (resolver, rejecter) {
if (!obj.sql) {
resolver();
return;
}
const queryOptions = Object.assign({ sql: obj.sql }, obj.options);
connection.query(queryOptions, obj.bindings, function (
err,
rows,
fields
) {
if (err) return rejecter(err);
obj.response = [rows, fields];
resolver(obj);
});
});
},
// Process the response as returned from the query.
processResponse(obj, runner) {
if (obj == null) return;
const { response } = obj;
const { method } = obj;
const rows = response[0];
const fields = response[1];
if (obj.output) return obj.output.call(runner, rows, fields);
switch (method) {
case 'select':
case 'pluck':
case 'first': {
if (method === 'pluck') {
return map(rows, obj.pluck);
}
return method === 'first' ? rows[0] : rows;
}
case 'insert':
return [rows.insertId];
case 'del':
case 'update':
case 'counter':
return rows.affectedRows;
default:
return response;
}
},
canCancelQuery: true,
async cancelQuery(connectionToKill) {
const conn = await this.acquireConnection();
try {
return await this.query(conn, {
method: 'raw',
sql: 'KILL QUERY ?',
bindings: [connectionToKill.threadId],
options: {},
});
} finally {
await this.releaseConnection(conn);
}
},
});
module.exports = Client_MySQL;
|
var expect = require('chai').expect,
through = require('through2'),
Vinyl = require('vinyl'),
fs = require('fs'),
path = require('path'),
concatCss = require('../');
function expected(file) {
var base = path.join(process.cwd(), 'test/expected');
var filepath = path.resolve(base, file);
return new Vinyl({
path: filepath,
cwd: process.cwd(),
base: base,
contents: fs.readFileSync(filepath)
});
}
function fixture(file) {
var base = path.join(process.cwd(), 'test/fixtures');
var filepath = path.join(base, file);
return new Vinyl({
path: filepath,
cwd: process.cwd(),
base: base,
contents: fs.readFileSync(filepath)
});
}
describe('gulp-concat-css', function() {
it('should only bubble up imports', function(done) {
var now = Date.now();
var stream = concatCss('build/bundle-bubbleonly.css', {inlineImports: false, rebaseUrls: false});
var expectedFile = expected('build/bundle-bubbleonly.css');
stream
.pipe(through.obj(function(file, enc, cb) {
//fs.writeFileSync("bundle.css", file.contents);
expect(String(file.contents)).to.be.equal(String(expectedFile.contents));
expect(path.basename(file.path)).to.be.equal(path.basename(expectedFile.path));
expect(file.cwd, "cwd").to.be.equal(expectedFile.cwd);
expect(file.relative, "relative").to.be.equal(expectedFile.relative);
console.log('Execution time: ' + (Date.now() - now) + 'ms');
done();
}));
stream.write(fixture('main.css'));
stream.write(fixture('vendor/vendor.css'));
stream.end();
});
it('should only rebase urls', function(done) {
var now = Date.now();
var stream = concatCss('build/bundle-rebase.css', {inlineImports: false});
var expectedFile = expected('build/bundle-rebase.css');
stream
.pipe(through.obj(function(file, enc, cb) {
//fs.writeFileSync("bundle.css", file.contents);
expect(String(file.contents)).to.be.equal(String(expectedFile.contents));
expect(path.basename(file.path)).to.be.equal(path.basename(expectedFile.path));
expect(file.cwd, "cwd").to.be.equal(expectedFile.cwd);
expect(file.relative, "relative").to.be.equal(expectedFile.relative);
console.log('Execution time: ' + (Date.now() - now) + 'ms');
done();
}));
stream.write(fixture('main.css'));
stream.write(fixture('vendor/vendor.css'));
stream.end();
});
it('should only inline imports', function(done) {
var now = Date.now();
var stream = concatCss('build/bundle-import.css', {inlineImports: true, rebaseUrls: false});
var expectedFile = expected('build/bundle-import.css');
stream
.pipe(through.obj(function(file, enc, cb) {
//fs.writeFileSync("bundle.css", file.contents);
expect(String(file.contents)).to.be.equal(String(expectedFile.contents));
expect(path.basename(file.path)).to.be.equal(path.basename(expectedFile.path));
expect(file.cwd, "cwd").to.be.equal(expectedFile.cwd);
expect(file.relative, "relative").to.be.equal(expectedFile.relative);
console.log('Execution time: ' + (Date.now() - now) + 'ms');
done();
}));
stream.write(fixture('main.css'));
stream.write(fixture('vendor/vendor.css'));
stream.end();
});
it('should concat, rebase urls, inline imports and bubble up external imports', function(done) {
var now = Date.now();
var stream = concatCss('build/bundle-all.css');
var expectedFile = expected('build/bundle-all.css');
stream
.pipe(through.obj(function(file, enc, cb) {
//fs.writeFileSync("bundle.css", file.contents);
expect(String(file.contents)).to.be.equal(String(expectedFile.contents));
expect(path.basename(file.path)).to.be.equal(path.basename(expectedFile.path));
expect(file.cwd, "cwd").to.be.equal(expectedFile.cwd);
expect(file.relative, "relative").to.be.equal(expectedFile.relative);
console.log('Execution time: ' + (Date.now() - now) + 'ms');
done();
}));
stream.write(fixture('main.css'));
stream.write(fixture('vendor/vendor.css'));
stream.end();
});
it('should not crash if no file is provided', function(done) {
var stream = concatCss('build/bundle-all.css');
stream
.on('error', function() {
done(false);
})
.pipe(through.obj(function(file, enc, cb) {
done(false);
}, function() {
done();
}));
stream.end();
});
});
|
"use strict";
var mainElm;
var internalReq;
var internalReqFailures = 0;
var currentLocation = parseLocation();
var initialLoad = false;
var viewedIds = [];
var moreTextUsed = [];
var quotesLimit = 0;
function pushId(id) {
keepArrayFresh.apply(viewedIds, [id, quotesLimit * 0.9]);
};
function keepArrayFresh(id, limit) {
limit = limit || 2;
if (this.indexOf(id) === -1) {
this.push(id);
}
if (this.length > limit) {
this.splice(0, 1);
}
}
function parseLocation() {
return {
href: window.location.href,
pathname: window.location.pathname
};
}
window.onpopstate = function(event) {
event.preventDefault();
if ('state' in window.history && event.state !== null &&event.state.quote !== null && initialLoad) {
populateQuote(event.state.quote);
}
if (!initialLoad) {
initialLoad = true
}
}
function randomBoolean() {
return Math.random() >= 0.5 ? true : false;
}
function randomInt(min, max) {
min ? min : min = 0;
max ? max : max = 1;
return (Math.random() * (max - min + 1) + min)|0;
}
function randomFloat(min, max) {
min ? min : min = 0;
max ? max : max = 1;
return Math.random() * (max - min + 1) + min;
}
function getNewRandom(min, max, current) {
var newRandom = randomInt(min, max);
return newRandom !== current ? newRandom : getNewRandom(min, max, current);
}
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
|| window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
function recursiveCheckForElement(element, tag) {
if (!element || !element.tagName) {
return false;
}
if (element.tagName.toLowerCase() === tag) {
return element;
}
return recursiveCheckForElement(element.parentNode, tag)
}
function createQuoteElm(quote) {
pushId(quote._id);
var quoteElm = document.createElement('article');
var text = document.createElement('h1');
var link = document.createElement('a');
var footer = document.createElement('footer');
var cite = document.createElement('cite');
var time = document.createElement('time');
var moreLink = document.createElement('a');
//var permLink = document.createElement('a');
var paragraph = document.createElement('p');
quote.date && time.setAttribute('datetime', quote.date);
time.textContent = quote.date ? " on " + moment(quote.date).zone("05:00").format('LL').toString() : "";
cite.innerHTML = quote.who? "—" + quote.who : "";
quote.date && cite.appendChild(time);
/*permLink.href = "/"+ quote._id;
permLink.textContent = "Permalink"
permLink.addEventListener('click', function(event) {
event.preventDefault();
loadQuote("/"+ quote._id);
return false;
});*/
moreLink.href = "/random";
moreLink.addEventListener('click', function(event) {
event.preventDefault();
loadQuote(null);
return false;
});
var moreTextOptions = [
"Who else is he?",
"He's who?",
"Crazy. What else?",
"Is that all?",
"More, more!",
"That can't be right.",
"That's just stupid",
"You're kidding",
"Is that really him?",
"What else ya got?",
"Rob Ford is who now?",
"Uhhh who?",
"Who is he, again?",
"Any more?",
"Gimme another"
];
var moreText = moreTextOptions.filter(function(string){
return moreTextUsed.indexOf(string) === -1;
}).sort(function() {
return 0.5 - Math.random();
})[0];
keepArrayFresh.apply(moreTextUsed, [moreText, moreTextOptions.length-1]);
moreLink.textContent = moreText;
var citation = paragraph.cloneNode(false);
citation.appendChild(cite)
footer.appendChild(citation);
/*var perma = paragraph.cloneNode(false);
perma.appendChild(permLink);
perma.classList.add('small-text');
footer.appendChild(perma);*/
moreLink.classList.add('button');
moreLink.classList.add('more');
var more = document.createElement('div');
more.appendChild(moreLink);
footer.appendChild(more);
link.href = quote.link;
link.target = "_blank";
link.textContent = quote.text;
text.appendChild(link);
text.title = quote.altText;
quoteElm.appendChild(text);
quoteElm.appendChild(footer);
quoteElm.classList.add('quote');
quoteElm.classList.add('container');
return quoteElm;
}
function populateQuote(quote) {
var contentElm = document.getElementById('content');
var oldQuoteElm = contentElm.querySelector('article.quote');
var quoteElm = createQuoteElm(quote);
quoteElm.classList.add('new');
contentElm.appendChild(quoteElm);
quoteElm.clientHeight;
quoteElm.classList.remove('new');
oldQuoteElm.parentNode.removeChild(oldQuoteElm);
}
function loadQuote(url) {
var cacheBreaker = new Date();
cacheBreaker = cacheBreaker.getTime();
url = url ? url + "?r=" + cacheBreaker : "/random?not=" + viewedIds.join(",");
internalReq = new XMLHttpRequest();
internalReq.open("GET", url);
internalReq.timeout = 10000;
internalReq.setRequestHeader('Content-Type', 'application/json');
internalReq.setRequestHeader('accept', 'application/json');
internalReq.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
var thisReq = internalReq;
var mainElm = document.getElementById('main');
var contentElm = document.getElementById('content');
var oldQuoteElm = contentElm.querySelector('article.quote');
mainElm.classList.add('loading')
internalReq.onload = function() {
var quote;
switch(internalReq.status) {
case 200:
quote = JSON.parse(internalReq.responseText);
populateQuote(quote);
history.pushState && history.pushState({quote: quote}, "Rob Ford is: " + quote.text, "/" + quote.slug);
document.title = "Rob Ford is: " + quote.text;
if (window.ga) {//if google analytics;
ga('send', 'pageview', {
'page': '/' + quote.slug,
'title': document.title
});
}
internalReqFailures = 0;
break;
default:
console.log('Could not load quote ' + url + ' . Status:' + internalReq.status);
if (internalReqFailures < 2) {
loadQuote('/random');
}
internalReqFailures++;
}
mainElm.classList.remove('loading')
}
internalReq.onerror = function(event) {
event.preventDefault();
console.log(internalReq);
}
internalReq.onabort = function() {
}
internalReq.ontimeout = function() {
}
internalReq.onprogress = function(event) {
}
internalReq.send(null);
}
document.addEventListener("DOMContentLoaded", function(event) {
mainElm = document.querySelector('main');
mainElm.classList.add('loading-initial');
})
window.onload = function() {
setTimeout(function() {
mainElm.classList.remove('loading-initial');
}, 500);
var loadQuoteElm = document.getElementById('load-quote');
if (loadQuoteElm) {
var toLoadId = loadQuoteElm.getAttribute('data-quote-id');
loadQuote(toLoadId ? '/' + toLoadId : null);
}
quotesLimit = typeof limit !== "undefined" ? limit : 0;
var overlayTrigger = document.getElementById('overlay-trigger');
if (overlayTrigger) {
overlayTrigger.onclick = function(event) {
event.preventDefault();
document.body.classList.toggle('show-overlay');
};
}
}
|
/*
TimelineJS - ver. 2015-09-18-15-26-18 - 2015-09-18
Copyright (c) 2012-2015 Northwestern University
a project of the Northwestern University Knight Lab, originally created by Zach Wise
https://github.com/NUKnightLab/TimelineJS3
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/* **********************************************
Begin TL.js
********************************************** */
/*!
TL
*/
(function (root) {
root.TL = {
VERSION: '0.1',
_originalL: root.TL
};
}(this));
/* TL.Debug
Debug mode
================================================== */
TL.debug = true;
/* TL.Bind
================================================== */
TL.Bind = function (/*Function*/ fn, /*Object*/ obj) /*-> Object*/ {
return function () {
return fn.apply(obj, arguments);
};
};
/* Trace (console.log)
================================================== */
trace = function( msg ) {
if (TL.debug) {
if (window.console) {
console.log(msg);
} else if ( typeof( jsTrace ) != 'undefined' ) {
jsTrace.send( msg );
} else {
//alert(msg);
}
}
}
/* **********************************************
Begin TL.Util.js
********************************************** */
/* TL.Util
Class of utilities
================================================== */
TL.Util = {
mergeData: function(data_main, data_to_merge) {
var x;
for (x in data_to_merge) {
if (Object.prototype.hasOwnProperty.call(data_to_merge, x)) {
data_main[x] = data_to_merge[x];
}
}
return data_main;
},
// like TL.Util.mergeData but takes an arbitrarily long list of sources to merge.
extend: function (/*Object*/ dest) /*-> Object*/ { // merge src properties into dest
var sources = Array.prototype.slice.call(arguments, 1);
for (var j = 0, len = sources.length, src; j < len; j++) {
src = sources[j] || {};
TL.Util.mergeData(dest, src);
}
return dest;
},
isEven: function(n) {
return n == parseFloat(n)? !(n%2) : void 0;
},
findArrayNumberByUniqueID: function(id, array, prop, defaultVal) {
var _n = defaultVal || 0;
for (var i = 0; i < array.length; i++) {
if (array[i].data[prop] == id) {
_n = i;
}
};
return _n;
},
convertUnixTime: function(str) {
var _date, _months, _year, _month, _day, _time, _date_array = [],
_date_str = {
ymd:"",
time:"",
time_array:[],
date_array:[],
full_array:[]
};
_date_str.ymd = str.split(" ")[0];
_date_str.time = str.split(" ")[1];
_date_str.date_array = _date_str.ymd.split("-");
_date_str.time_array = _date_str.time.split(":");
_date_str.full_array = _date_str.date_array.concat(_date_str.time_array)
for(var i = 0; i < _date_str.full_array.length; i++) {
_date_array.push( parseInt(_date_str.full_array[i]) )
}
_date = new Date(_date_array[0], _date_array[1], _date_array[2], _date_array[3], _date_array[4], _date_array[5]);
_months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
_year = _date.getFullYear();
_month = _months[_date.getMonth()];
_day = _date.getDate();
_time = _month + ', ' + _day + ' ' + _year;
return _time;
},
setData: function (obj, data) {
obj.data = TL.Util.extend({}, obj.data, data);
if (obj.data.unique_id === "") {
obj.data.unique_id = TL.Util.unique_ID(6);
}
},
stamp: (function () {
var lastId = 0, key = '_tl_id';
return function (/*Object*/ obj) {
obj[key] = obj[key] || ++lastId;
return obj[key];
};
}()),
isArray: (function () {
// Use compiler's own isArray when available
if (Array.isArray) {
return Array.isArray;
}
// Retain references to variables for performance
// optimization
var objectToStringFn = Object.prototype.toString,
arrayToStringResult = objectToStringFn.call([]);
return function (subject) {
return objectToStringFn.call(subject) === arrayToStringResult;
};
}()),
getRandomNumber: function(range) {
return Math.floor(Math.random() * range);
},
unique_ID: function(size, prefix) {
var getRandomNumber = function(range) {
return Math.floor(Math.random() * range);
};
var getRandomChar = function() {
var chars = "abcdefghijklmnopqurstuvwxyz";
return chars.substr( getRandomNumber(32), 1 );
};
var randomID = function(size) {
var str = "";
for(var i = 0; i < size; i++) {
str += getRandomChar();
}
return str;
};
if (prefix) {
return prefix + "-" + randomID(size);
} else {
return "tl-" + randomID(size);
}
},
ensureUniqueKey: function(obj, candidate) {
if (!candidate) { candidate = TL.Util.unique_ID(6); }
if (!(candidate in obj)) { return candidate; }
var root = candidate.match(/^(.+)(-\d+)?$/)[1];
var similar_ids = [];
// get an alternative
for (key in obj) {
if (key.match(/^(.+?)(-\d+)?$/)[1] == root) {
similar_ids.push(key);
}
}
candidate = root + "-" + (similar_ids.length + 1);
for (var counter = similar_ids.length; similar_ids.indexOf(candidate) != -1; counter++) {
candidate = root + '-' + counter;
}
return candidate;
},
htmlify: function(str) {
//if (str.match(/<\s*p[^>]*>([^<]*)<\s*\/\s*p\s*>/)) {
if (str.match(/<p>[\s\S]*?<\/p>/)) {
return str;
} else {
return "<p>" + str + "</p>";
}
},
/* * Turns plain text links into real links
================================================== */
linkify: function(text,targets,is_touch) {
var make_link = function(url, link_text, prefix) {
if (!prefix) {
prefix = "";
}
var MAX_LINK_TEXT_LENGTH = 30;
if (link_text && link_text.length > MAX_LINK_TEXT_LENGTH) {
link_text = link_text.substring(0,MAX_LINK_TEXT_LENGTH) + "\u2026"; // unicode ellipsis
}
return prefix + "<a class='tl-makelink' target='_blank' href='" + url + "' onclick='void(0)'>" + link_text + "</a>";
}
// http://, https://, ftp://
var urlPattern = /\b(?:https?|ftp):\/\/([a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|])/gim;
// www. sans http:// or https://
var pseudoUrlPattern = /(^|[^\/>])(www\.[\S]+(\b|$))/gim;
// Email addresses
var emailAddressPattern = /([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)/gim;
return text
.replace(urlPattern, function(match, url_sans_protocol, offset, string) {
// Javascript doesn't support negative lookbehind assertions, so
// we need to handle risk of matching URLs in legit hrefs
if (offset > 0) {
var prechar = string[offset-1];
if (prechar == '"' || prechar == "'" || prechar == "=") {
return match;
}
}
return make_link(match, url_sans_protocol);
})
.replace(pseudoUrlPattern, function(match, beforePseudo, pseudoUrl, offset, string) {
return make_link('http://' + pseudoUrl, pseudoUrl, beforePseudo);
})
.replace(emailAddressPattern, function(match, email, offset, string) {
return make_link('mailto:' + email, email);
});
},
unlinkify: function(text) {
if(!text) return text;
text = text.replace(/<a\b[^>]*>/i,"");
text = text.replace(/<\/a>/i, "");
return text;
},
getParamString: function (obj) {
var params = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
params.push(i + '=' + obj[i]);
}
}
return '?' + params.join('&');
},
formatNum: function (num, digits) {
var pow = Math.pow(10, digits || 5);
return Math.round(num * pow) / pow;
},
falseFn: function () {
return false;
},
requestAnimFrame: (function () {
function timeoutDefer(callback) {
window.setTimeout(callback, 1000 / 60);
}
var requestFn = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
timeoutDefer;
return function (callback, context, immediate, contextEl) {
callback = context ? TL.Util.bind(callback, context) : callback;
if (immediate && requestFn === timeoutDefer) {
callback();
} else {
requestFn(callback, contextEl);
}
};
}()),
bind: function (/*Function*/ fn, /*Object*/ obj) /*-> Object*/ {
return function () {
return fn.apply(obj, arguments);
};
},
template: function (str, data) {
return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
var value = data[key];
if (!data.hasOwnProperty(key)) {
throw new Error('No value provided for variable ' + str);
}
return value;
});
},
hexToRgb: function(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
if (TL.Util.css_named_colors[hex.toLowerCase()]) {
hex = TL.Util.css_named_colors[hex.toLowerCase()];
}
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
},
// given an object with r, g, and b keys, or a string of the form 'rgb(mm,nn,ll)', return a CSS hex string including the leading '#' character
rgbToHex: function(rgb) {
var r,g,b;
if (typeof(rgb) == 'object') {
r = rgb.r;
g = rgb.g;
b = rgb.b;
} else if (typeof(rgb.match) == 'function'){
var parts = rgb.match(/^rgb\((\d+),(\d+),(\d+)\)$/);
if (parts) {
r = parts[1];
g = parts[2];
b = parts[3];
}
}
if (isNaN(r) || isNaN(b) || isNaN(g)) {
throw "Invalid RGB argument";
}
return "#" + TL.Util.intToHexString(r) + TL.Util.intToHexString(g) + TL.Util.intToHexString(b);
},
colorObjToHex: function(o) {
var parts = [o.r, o.g, o.b];
return TL.Util.rgbToHex("rgb(" + parts.join(',') + ")")
},
css_named_colors: {
"aliceblue": "#f0f8ff",
"antiquewhite": "#faebd7",
"aqua": "#00ffff",
"aquamarine": "#7fffd4",
"azure": "#f0ffff",
"beige": "#f5f5dc",
"bisque": "#ffe4c4",
"black": "#000000",
"blanchedalmond": "#ffebcd",
"blue": "#0000ff",
"blueviolet": "#8a2be2",
"brown": "#a52a2a",
"burlywood": "#deb887",
"cadetblue": "#5f9ea0",
"chartreuse": "#7fff00",
"chocolate": "#d2691e",
"coral": "#ff7f50",
"cornflowerblue": "#6495ed",
"cornsilk": "#fff8dc",
"crimson": "#dc143c",
"cyan": "#00ffff",
"darkblue": "#00008b",
"darkcyan": "#008b8b",
"darkgoldenrod": "#b8860b",
"darkgray": "#a9a9a9",
"darkgreen": "#006400",
"darkkhaki": "#bdb76b",
"darkmagenta": "#8b008b",
"darkolivegreen": "#556b2f",
"darkorange": "#ff8c00",
"darkorchid": "#9932cc",
"darkred": "#8b0000",
"darksalmon": "#e9967a",
"darkseagreen": "#8fbc8f",
"darkslateblue": "#483d8b",
"darkslategray": "#2f4f4f",
"darkturquoise": "#00ced1",
"darkviolet": "#9400d3",
"deeppink": "#ff1493",
"deepskyblue": "#00bfff",
"dimgray": "#696969",
"dodgerblue": "#1e90ff",
"firebrick": "#b22222",
"floralwhite": "#fffaf0",
"forestgreen": "#228b22",
"fuchsia": "#ff00ff",
"gainsboro": "#dcdcdc",
"ghostwhite": "#f8f8ff",
"gold": "#ffd700",
"goldenrod": "#daa520",
"gray": "#808080",
"green": "#008000",
"greenyellow": "#adff2f",
"honeydew": "#f0fff0",
"hotpink": "#ff69b4",
"indianred": "#cd5c5c",
"indigo": "#4b0082",
"ivory": "#fffff0",
"khaki": "#f0e68c",
"lavender": "#e6e6fa",
"lavenderblush": "#fff0f5",
"lawngreen": "#7cfc00",
"lemonchiffon": "#fffacd",
"lightblue": "#add8e6",
"lightcoral": "#f08080",
"lightcyan": "#e0ffff",
"lightgoldenrodyellow": "#fafad2",
"lightgray": "#d3d3d3",
"lightgreen": "#90ee90",
"lightpink": "#ffb6c1",
"lightsalmon": "#ffa07a",
"lightseagreen": "#20b2aa",
"lightskyblue": "#87cefa",
"lightslategray": "#778899",
"lightsteelblue": "#b0c4de",
"lightyellow": "#ffffe0",
"lime": "#00ff00",
"limegreen": "#32cd32",
"linen": "#faf0e6",
"magenta": "#ff00ff",
"maroon": "#800000",
"mediumaquamarine": "#66cdaa",
"mediumblue": "#0000cd",
"mediumorchid": "#ba55d3",
"mediumpurple": "#9370db",
"mediumseagreen": "#3cb371",
"mediumslateblue": "#7b68ee",
"mediumspringgreen": "#00fa9a",
"mediumturquoise": "#48d1cc",
"mediumvioletred": "#c71585",
"midnightblue": "#191970",
"mintcream": "#f5fffa",
"mistyrose": "#ffe4e1",
"moccasin": "#ffe4b5",
"navajowhite": "#ffdead",
"navy": "#000080",
"oldlace": "#fdf5e6",
"olive": "#808000",
"olivedrab": "#6b8e23",
"orange": "#ffa500",
"orangered": "#ff4500",
"orchid": "#da70d6",
"palegoldenrod": "#eee8aa",
"palegreen": "#98fb98",
"paleturquoise": "#afeeee",
"palevioletred": "#db7093",
"papayawhip": "#ffefd5",
"peachpuff": "#ffdab9",
"peru": "#cd853f",
"pink": "#ffc0cb",
"plum": "#dda0dd",
"powderblue": "#b0e0e6",
"purple": "#800080",
"rebeccapurple": "#663399",
"red": "#ff0000",
"rosybrown": "#bc8f8f",
"royalblue": "#4169e1",
"saddlebrown": "#8b4513",
"salmon": "#fa8072",
"sandybrown": "#f4a460",
"seagreen": "#2e8b57",
"seashell": "#fff5ee",
"sienna": "#a0522d",
"silver": "#c0c0c0",
"skyblue": "#87ceeb",
"slateblue": "#6a5acd",
"slategray": "#708090",
"snow": "#fffafa",
"springgreen": "#00ff7f",
"steelblue": "#4682b4",
"tan": "#d2b48c",
"teal": "#008080",
"thistle": "#d8bfd8",
"tomato": "#ff6347",
"turquoise": "#40e0d0",
"violet": "#ee82ee",
"wheat": "#f5deb3",
"white": "#ffffff",
"whitesmoke": "#f5f5f5",
"yellow": "#ffff00",
"yellowgreen": "#9acd32"
},
ratio: {
square: function(size) {
var s = {
w: 0,
h: 0
}
if (size.w > size.h && size.h > 0) {
s.h = size.h;
s.w = size.h;
} else {
s.w = size.w;
s.h = size.w;
}
return s;
},
r16_9: function(size) {
if (size.w !== null && size.w !== "") {
return Math.round((size.w / 16) * 9);
} else if (size.h !== null && size.h !== "") {
return Math.round((size.h / 9) * 16);
} else {
return 0;
}
},
r4_3: function(size) {
if (size.w !== null && size.w !== "") {
return Math.round((size.w / 4) * 3);
} else if (size.h !== null && size.h !== "") {
return Math.round((size.h / 3) * 4);
}
}
},
getObjectAttributeByIndex: function(obj, index) {
if(typeof obj != 'undefined') {
var i = 0;
for (var attr in obj){
if (index === i){
return obj[attr];
}
i++;
}
return "";
} else {
return "";
}
},
getUrlVars: function(string) {
var str,
vars = [],
hash,
hashes;
str = string.toString();
if (str.match('&')) {
str = str.replace("&", "&");
} else if (str.match('&')) {
str = str.replace("&", "&");
} else if (str.match('&')) {
str = str.replace("&", "&");
}
hashes = str.slice(str.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
/**
* Remove any leading or trailing whitespace from the given string.
* If `str` is undefined or does not have a `replace` function, return
* an empty string.
*/
trim: function(str) {
if (str && typeof(str.replace) == 'function') {
return str.replace(/^\s+|\s+$/g, '');
}
return "";
},
slugify: function(str) {
// borrowed from http://stackoverflow.com/a/5782563/102476
str = TL.Util.trim(str);
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
var to = "aaaaaeeeeeiiiiooooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
str = str.replace(/^([0-9])/,'_$1');
return str;
},
maxDepth: function(ary) {
// given a sorted array of 2-tuples of numbers, count how many "deep" the items are.
// that is, what is the maximum number of tuples that occupy any one moment
// each tuple should also be sorted
var stack = [];
var max_depth = 0;
for (var i = 0; i < ary.length; i++) {
stack.push(ary[i]);
if (stack.length > 1) {
var top = stack[stack.length - 1]
var bottom_idx = -1;
for (var j = 0; j < stack.length - 1; j++) {
if (stack[j][1] < top[0]) {
bottom_idx = j;
}
};
if (bottom_idx >= 0) {
stack = stack.slice(bottom_idx + 1);
}
}
if (stack.length > max_depth) {
max_depth = stack.length;
}
};
return max_depth;
},
pad: function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
},
intToHexString: function(i) {
return TL.Util.pad(parseInt(i,10).toString(16));
},
findNextGreater: function(list, current, default_value) {
// given a sorted list and a current value which *might* be in the list,
// return the next greatest value if the current value is >= the last item in the list, return default,
// or if default is undefined, return input value
for (var i = 0; i < list.length; i++) {
if (current < list[i]) {
return list[i];
}
}
return (default_value) ? default_value : current;
},
findNextLesser: function(list, current, default_value) {
// given a sorted list and a current value which *might* be in the list,
// return the next lesser value if the current value is <= the last item in the list, return default,
// or if default is undefined, return input value
for (var i = list.length - 1; i >= 0; i--) {
if (current > list[i]) {
return list[i];
}
}
return (default_value) ? default_value : current;
},
isEmptyObject: function(o) {
var properties = []
if (Object.keys) {
properties = Object.keys(o);
} else { // all this to support IE 8
for (var p in o) if (Object.prototype.hasOwnProperty.call(o,p)) properties.push(p);
}
for (var i = 0; i < properties.length; i++) {
var k = properties[i];
if (o[k] != null && typeof o[k] != "string") return false;
if (TL.Util.trim(o[k]).length != 0) return false;
}
return true;
},
parseYouTubeTime: function(s) {
// given a YouTube start time string in a reasonable format, reduce it to a number of seconds as an integer.
if (typeof(s) == 'string') {
parts = s.match(/^\s*(\d+h)?(\d+m)?(\d+s)?\s*/i);
if (parts) {
var hours = parseInt(parts[1]) || 0;
var minutes = parseInt(parts[2]) || 0;
var seconds = parseInt(parts[3]) || 0;
return seconds + (minutes * 60) + (hours * 60 * 60);
}
} else if (typeof(s) == 'number') {
return s;
}
return 0;
},
/**
* Try to make seamless the process of interpreting a URL to a web page which embeds an image for sharing purposes
* as a direct image link. Some services have predictable transformations we can use rather than explain to people
* this subtlety.
*/
transformImageURL: function(url) {
return url.replace(/(.*)www.dropbox.com\/(.*)/, '$1dl.dropboxusercontent.com/$2')
}
};
/* **********************************************
Begin TL.Data.js
********************************************** */
// Expects TL to be visible in scope
;(function(TL){
/* Zepto v1.1.2-15-g59d3fe5 - zepto event ajax form ie - zeptojs.com/license */
var Zepto = (function() {
var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter,
document = window.document,
elementDisplay = {}, classCache = {},
cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 },
fragmentRE = /^\s*<(\w+|!)[^>]*>/,
singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rootNodeRE = /^(?:body|html)$/i,
capitalRE = /([A-Z])/g,
// special attributes that should be get/set via method calls
methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'],
adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ],
table = document.createElement('table'),
tableRow = document.createElement('tr'),
containers = {
'tr': document.createElement('tbody'),
'tbody': table, 'thead': table, 'tfoot': table,
'td': tableRow, 'th': tableRow,
'*': document.createElement('div')
},
readyRE = /complete|loaded|interactive/,
classSelectorRE = /^\.([\w-]+)$/,
idSelectorRE = /^#([\w-]*)$/,
simpleSelectorRE = /^[\w-]*$/,
class2type = {},
toString = class2type.toString,
zepto = {},
camelize, uniq,
tempParent = document.createElement('div'),
propMap = {
'tabindex': 'tabIndex',
'readonly': 'readOnly',
'for': 'htmlFor',
'class': 'className',
'maxlength': 'maxLength',
'cellspacing': 'cellSpacing',
'cellpadding': 'cellPadding',
'rowspan': 'rowSpan',
'colspan': 'colSpan',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'contenteditable': 'contentEditable'
},
isArray = Array.isArray ||
function(object){ return object instanceof Array }
zepto.matches = function(element, selector) {
if (!selector || !element || element.nodeType !== 1) return false
var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector ||
element.oMatchesSelector || element.matchesSelector
if (matchesSelector) return matchesSelector.call(element, selector)
// fall back to performing a selector:
var match, parent = element.parentNode, temp = !parent
if (temp) (parent = tempParent).appendChild(element)
match = ~zepto.qsa(parent, selector).indexOf(element)
temp && tempParent.removeChild(element)
return match
}
function type(obj) {
return obj == null ? String(obj) :
class2type[toString.call(obj)] || "object"
}
function isFunction(value) { return type(value) == "function" }
function isWindow(obj) { return obj != null && obj == obj.window }
function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE }
function isObject(obj) { return type(obj) == "object" }
function isPlainObject(obj) {
return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype
}
function likeArray(obj) { return typeof obj.length == 'number' }
function compact(array) { return filter.call(array, function(item){ return item != null }) }
function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array }
camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) }
function dasherize(str) {
return str.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/_/g, '-')
.toLowerCase()
}
uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) }
function classRE(name) {
return name in classCache ?
classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)'))
}
function maybeAddPx(name, value) {
return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value
}
function defaultDisplay(nodeName) {
var element, display
if (!elementDisplay[nodeName]) {
element = document.createElement(nodeName)
document.body.appendChild(element)
display = getComputedStyle(element, '').getPropertyValue("display")
element.parentNode.removeChild(element)
display == "none" && (display = "block")
elementDisplay[nodeName] = display
}
return elementDisplay[nodeName]
}
function children(element) {
return 'children' in element ?
slice.call(element.children) :
$.map(element.childNodes, function(node){ if (node.nodeType == 1) return node })
}
// `$.zepto.fragment` takes a html string and an optional tag name
// to generate DOM nodes nodes from the given html string.
// The generated DOM nodes are returned as an array.
// This function can be overriden in plugins for example to make
// it compatible with browsers that don't support the DOM fully.
zepto.fragment = function(html, name, properties) {
var dom, nodes, container
// A special case optimization for a single tag
if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1))
if (!dom) {
if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>")
if (name === undefined) name = fragmentRE.test(html) && RegExp.$1
if (!(name in containers)) name = '*'
container = containers[name]
container.innerHTML = '' + html
dom = $.each(slice.call(container.childNodes), function(){
container.removeChild(this)
})
}
if (isPlainObject(properties)) {
nodes = $(dom)
$.each(properties, function(key, value) {
if (methodAttributes.indexOf(key) > -1) nodes[key](value)
else nodes.attr(key, value)
})
}
return dom
}
// `$.zepto.Z` swaps out the prototype of the given `dom` array
// of nodes with `$.fn` and thus supplying all the Zepto functions
// to the array. Note that `__proto__` is not supported on Internet
// Explorer. This method can be overriden in plugins.
zepto.Z = function(dom, selector) {
dom = dom || []
dom.__proto__ = $.fn
dom.selector = selector || ''
return dom
}
// `$.zepto.isZ` should return `true` if the given object is a Zepto
// collection. This method can be overriden in plugins.
zepto.isZ = function(object) {
return object instanceof zepto.Z
}
// `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and
// takes a CSS selector and an optional context (and handles various
// special cases).
// This method can be overriden in plugins.
zepto.init = function(selector, context) {
var dom
// If nothing given, return an empty Zepto collection
if (!selector) return zepto.Z()
// Optimize for string selectors
else if (typeof selector == 'string') {
selector = selector.trim()
// If it's a html fragment, create nodes from it
// Note: In both Chrome 21 and Firefox 15, DOM error 12
// is thrown if the fragment doesn't begin with <
if (selector[0] == '<' && fragmentRE.test(selector))
dom = zepto.fragment(selector, RegExp.$1, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// If it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// If a function is given, call it when the DOM is ready
else if (isFunction(selector)) return $(document).ready(selector)
// If a Zepto collection is given, just return it
else if (zepto.isZ(selector)) return selector
else {
// normalize array if an array of nodes is given
if (isArray(selector)) dom = compact(selector)
// Wrap DOM nodes.
else if (isObject(selector))
dom = [selector], selector = null
// If it's a html fragment, create nodes from it
else if (fragmentRE.test(selector))
dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null
// If there's a context, create a collection on that context first, and select
// nodes from there
else if (context !== undefined) return $(context).find(selector)
// And last but no least, if it's a CSS selector, use it to select nodes.
else dom = zepto.qsa(document, selector)
}
// create a new Zepto collection from the nodes found
return zepto.Z(dom, selector)
}
// `$` will be the base `Zepto` object. When calling this
// function just call `$.zepto.init, which makes the implementation
// details of selecting nodes and creating Zepto collections
// patchable in plugins.
$ = function(selector, context){
return zepto.init(selector, context)
}
function extend(target, source, deep) {
for (key in source)
if (deep && (isPlainObject(source[key]) || isArray(source[key]))) {
if (isPlainObject(source[key]) && !isPlainObject(target[key]))
target[key] = {}
if (isArray(source[key]) && !isArray(target[key]))
target[key] = []
extend(target[key], source[key], deep)
}
else if (source[key] !== undefined) target[key] = source[key]
}
// Copy all but undefined properties from one or more
// objects to the `target` object.
$.extend = function(target){
var deep, args = slice.call(arguments, 1)
if (typeof target == 'boolean') {
deep = target
target = args.shift()
}
args.forEach(function(arg){ extend(target, arg, deep) })
return target
}
// `$.zepto.qsa` is Zepto's CSS selector implementation which
// uses `document.querySelectorAll` and optimizes for some special cases, like `#id`.
// This method can be overriden in plugins.
zepto.qsa = function(element, selector){
var found,
maybeID = selector[0] == '#',
maybeClass = !maybeID && selector[0] == '.',
nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked
isSimple = simpleSelectorRE.test(nameOnly)
return (isDocument(element) && isSimple && maybeID) ?
( (found = element.getElementById(nameOnly)) ? [found] : [] ) :
(element.nodeType !== 1 && element.nodeType !== 9) ? [] :
slice.call(
isSimple && !maybeID ?
maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class
element.getElementsByTagName(selector) : // Or a tag
element.querySelectorAll(selector) // Or it's not simple, and we need to query all
)
}
function filtered(nodes, selector) {
return selector == null ? $(nodes) : $(nodes).filter(selector)
}
$.contains = function(parent, node) {
return parent !== node && parent.contains(node)
}
function funcArg(context, arg, idx, payload) {
return isFunction(arg) ? arg.call(context, idx, payload) : arg
}
function setAttribute(node, name, value) {
value == null ? node.removeAttribute(name) : node.setAttribute(name, value)
}
// access className property while respecting SVGAnimatedString
function className(node, value){
var klass = node.className,
svg = klass && klass.baseVal !== undefined
if (value === undefined) return svg ? klass.baseVal : klass
svg ? (klass.baseVal = value) : (node.className = value)
}
// "true" => true
// "false" => false
// "null" => null
// "42" => 42
// "42.5" => 42.5
// "08" => "08"
// JSON => parse if valid
// String => self
function deserializeValue(value) {
var num
try {
return value ?
value == "true" ||
( value == "false" ? false :
value == "null" ? null :
!/^0/.test(value) && !isNaN(num = Number(value)) ? num :
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value )
: value
} catch(e) {
return value
}
}
$.type = type
$.isFunction = isFunction
$.isWindow = isWindow
$.isArray = isArray
$.isPlainObject = isPlainObject
$.isEmptyObject = function(obj) {
var name
for (name in obj) return false
return true
}
$.inArray = function(elem, array, i){
return emptyArray.indexOf.call(array, elem, i)
}
$.camelCase = camelize
$.trim = function(str) {
return str == null ? "" : String.prototype.trim.call(str)
}
// plugin compatibility
$.uuid = 0
$.support = { }
$.expr = { }
$.map = function(elements, callback){
var value, values = [], i, key
if (likeArray(elements))
for (i = 0; i < elements.length; i++) {
value = callback(elements[i], i)
if (value != null) values.push(value)
}
else
for (key in elements) {
value = callback(elements[key], key)
if (value != null) values.push(value)
}
return flatten(values)
}
$.each = function(elements, callback){
var i, key
if (likeArray(elements)) {
for (i = 0; i < elements.length; i++)
if (callback.call(elements[i], i, elements[i]) === false) return elements
} else {
for (key in elements)
if (callback.call(elements[key], key, elements[key]) === false) return elements
}
return elements
}
$.grep = function(elements, callback){
return filter.call(elements, callback)
}
if (window.JSON) $.parseJSON = JSON.parse
// Populate the class2type map
$.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase()
})
// Define methods that will be available on all
// Zepto collections
$.fn = {
// Because a collection acts like an array
// copy over these useful array functions.
forEach: emptyArray.forEach,
reduce: emptyArray.reduce,
push: emptyArray.push,
sort: emptyArray.sort,
indexOf: emptyArray.indexOf,
concat: emptyArray.concat,
// `map` and `slice` in the jQuery API work differently
// from their array counterparts
map: function(fn){
return $($.map(this, function(el, i){ return fn.call(el, i, el) }))
},
slice: function(){
return $(slice.apply(this, arguments))
},
ready: function(callback){
// need to check if document.body exists for IE as that browser reports
// document ready when it hasn't yet created the body element
if (readyRE.test(document.readyState) && document.body) callback($)
else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false)
return this
},
get: function(idx){
return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length]
},
toArray: function(){ return this.get() },
size: function(){
return this.length
},
remove: function(){
return this.each(function(){
if (this.parentNode != null)
this.parentNode.removeChild(this)
})
},
each: function(callback){
emptyArray.every.call(this, function(el, idx){
return callback.call(el, idx, el) !== false
})
return this
},
filter: function(selector){
if (isFunction(selector)) return this.not(this.not(selector))
return $(filter.call(this, function(element){
return zepto.matches(element, selector)
}))
},
add: function(selector,context){
return $(uniq(this.concat($(selector,context))))
},
is: function(selector){
return this.length > 0 && zepto.matches(this[0], selector)
},
not: function(selector){
var nodes=[]
if (isFunction(selector) && selector.call !== undefined)
this.each(function(idx){
if (!selector.call(this,idx)) nodes.push(this)
})
else {
var excludes = typeof selector == 'string' ? this.filter(selector) :
(likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector)
this.forEach(function(el){
if (excludes.indexOf(el) < 0) nodes.push(el)
})
}
return $(nodes)
},
has: function(selector){
return this.filter(function(){
return isObject(selector) ?
$.contains(this, selector) :
$(this).find(selector).size()
})
},
eq: function(idx){
return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1)
},
first: function(){
var el = this[0]
return el && !isObject(el) ? el : $(el)
},
last: function(){
var el = this[this.length - 1]
return el && !isObject(el) ? el : $(el)
},
find: function(selector){
var result, $this = this
if (typeof selector == 'object')
result = $(selector).filter(function(){
var node = this
return emptyArray.some.call($this, function(parent){
return $.contains(parent, node)
})
})
else if (this.length == 1) result = $(zepto.qsa(this[0], selector))
else result = this.map(function(){ return zepto.qsa(this, selector) })
return result
},
closest: function(selector, context){
var node = this[0], collection = false
if (typeof selector == 'object') collection = $(selector)
while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector)))
node = node !== context && !isDocument(node) && node.parentNode
return $(node)
},
parents: function(selector){
var ancestors = [], nodes = this
while (nodes.length > 0)
nodes = $.map(nodes, function(node){
if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) {
ancestors.push(node)
return node
}
})
return filtered(ancestors, selector)
},
parent: function(selector){
return filtered(uniq(this.pluck('parentNode')), selector)
},
children: function(selector){
return filtered(this.map(function(){ return children(this) }), selector)
},
contents: function() {
return this.map(function() { return slice.call(this.childNodes) })
},
siblings: function(selector){
return filtered(this.map(function(i, el){
return filter.call(children(el.parentNode), function(child){ return child!==el })
}), selector)
},
empty: function(){
return this.each(function(){ this.innerHTML = '' })
},
// `pluck` is borrowed from Prototype.js
pluck: function(property){
return $.map(this, function(el){ return el[property] })
},
show: function(){
return this.each(function(){
this.style.display == "none" && (this.style.display = '')
if (getComputedStyle(this, '').getPropertyValue("display") == "none")
this.style.display = defaultDisplay(this.nodeName)
})
},
replaceWith: function(newContent){
return this.before(newContent).remove()
},
wrap: function(structure){
var func = isFunction(structure)
if (this[0] && !func)
var dom = $(structure).get(0),
clone = dom.parentNode || this.length > 1
return this.each(function(index){
$(this).wrapAll(
func ? structure.call(this, index) :
clone ? dom.cloneNode(true) : dom
)
})
},
wrapAll: function(structure){
if (this[0]) {
$(this[0]).before(structure = $(structure))
var children
// drill down to the inmost element
while ((children = structure.children()).length) structure = children.first()
$(structure).append(this)
}
return this
},
wrapInner: function(structure){
var func = isFunction(structure)
return this.each(function(index){
var self = $(this), contents = self.contents(),
dom = func ? structure.call(this, index) : structure
contents.length ? contents.wrapAll(dom) : self.append(dom)
})
},
unwrap: function(){
this.parent().each(function(){
$(this).replaceWith($(this).children())
})
return this
},
clone: function(){
return this.map(function(){ return this.cloneNode(true) })
},
hide: function(){
return this.css("display", "none")
},
toggle: function(setting){
return this.each(function(){
var el = $(this)
;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide()
})
},
prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') },
next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') },
html: function(html){
return arguments.length === 0 ?
(this.length > 0 ? this[0].innerHTML : null) :
this.each(function(idx){
var originHtml = this.innerHTML
$(this).empty().append( funcArg(this, html, idx, originHtml) )
})
},
text: function(text){
return arguments.length === 0 ?
(this.length > 0 ? this[0].textContent : null) :
this.each(function(){ this.textContent = (text === undefined) ? '' : ''+text })
},
attr: function(name, value){
var result
return (typeof name == 'string' && value === undefined) ?
(this.length == 0 || this[0].nodeType !== 1 ? undefined :
(name == 'value' && this[0].nodeName == 'INPUT') ? this.val() :
(!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result
) :
this.each(function(idx){
if (this.nodeType !== 1) return
if (isObject(name)) for (key in name) setAttribute(this, key, name[key])
else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name)))
})
},
removeAttr: function(name){
return this.each(function(){ this.nodeType === 1 && setAttribute(this, name) })
},
prop: function(name, value){
name = propMap[name] || name
return (value === undefined) ?
(this[0] && this[0][name]) :
this.each(function(idx){
this[name] = funcArg(this, value, idx, this[name])
})
},
data: function(name, value){
var data = this.attr('data-' + name.replace(capitalRE, '-$1').toLowerCase(), value)
return data !== null ? deserializeValue(data) : undefined
},
val: function(value){
return arguments.length === 0 ?
(this[0] && (this[0].multiple ?
$(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') :
this[0].value)
) :
this.each(function(idx){
this.value = funcArg(this, value, idx, this.value)
})
},
offset: function(coordinates){
if (coordinates) return this.each(function(index){
var $this = $(this),
coords = funcArg(this, coordinates, index, $this.offset()),
parentOffset = $this.offsetParent().offset(),
props = {
top: coords.top - parentOffset.top,
left: coords.left - parentOffset.left
}
if ($this.css('position') == 'static') props['position'] = 'relative'
$this.css(props)
})
if (this.length==0) return null
var obj = this[0].getBoundingClientRect()
return {
left: obj.left + window.pageXOffset,
top: obj.top + window.pageYOffset,
width: Math.round(obj.width),
height: Math.round(obj.height)
}
},
css: function(property, value){
if (arguments.length < 2) {
var element = this[0], computedStyle = getComputedStyle(element, '')
if(!element) return
if (typeof property == 'string')
return element.style[camelize(property)] || computedStyle.getPropertyValue(property)
else if (isArray(property)) {
var props = {}
$.each(isArray(property) ? property: [property], function(_, prop){
props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop))
})
return props
}
}
var css = ''
if (type(property) == 'string') {
if (!value && value !== 0)
this.each(function(){ this.style.removeProperty(dasherize(property)) })
else
css = dasherize(property) + ":" + maybeAddPx(property, value)
} else {
for (key in property)
if (!property[key] && property[key] !== 0)
this.each(function(){ this.style.removeProperty(dasherize(key)) })
else
css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';'
}
return this.each(function(){ this.style.cssText += ';' + css })
},
index: function(element){
return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0])
},
hasClass: function(name){
if (!name) return false
return emptyArray.some.call(this, function(el){
return this.test(className(el))
}, classRE(name))
},
addClass: function(name){
if (!name) return this
return this.each(function(idx){
classList = []
var cls = className(this), newName = funcArg(this, name, idx, cls)
newName.split(/\s+/g).forEach(function(klass){
if (!$(this).hasClass(klass)) classList.push(klass)
}, this)
classList.length && className(this, cls + (cls ? " " : "") + classList.join(" "))
})
},
removeClass: function(name){
return this.each(function(idx){
if (name === undefined) return className(this, '')
classList = className(this)
funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){
classList = classList.replace(classRE(klass), " ")
})
className(this, classList.trim())
})
},
toggleClass: function(name, when){
if (!name) return this
return this.each(function(idx){
var $this = $(this), names = funcArg(this, name, idx, className(this))
names.split(/\s+/g).forEach(function(klass){
(when === undefined ? !$this.hasClass(klass) : when) ?
$this.addClass(klass) : $this.removeClass(klass)
})
})
},
scrollTop: function(value){
if (!this.length) return
var hasScrollTop = 'scrollTop' in this[0]
if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
return this.each(hasScrollTop ?
function(){ this.scrollTop = value } :
function(){ this.scrollTo(this.scrollX, value) })
},
scrollLeft: function(value){
if (!this.length) return
var hasScrollLeft = 'scrollLeft' in this[0]
if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset
return this.each(hasScrollLeft ?
function(){ this.scrollLeft = value } :
function(){ this.scrollTo(value, this.scrollY) })
},
position: function() {
if (!this.length) return
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset()
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( $(elem).css('margin-top') ) || 0
offset.left -= parseFloat( $(elem).css('margin-left') ) || 0
// Add offsetParent borders
parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0
parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
}
},
offsetParent: function() {
return this.map(function(){
var parent = this.offsetParent || document.body
while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static")
parent = parent.offsetParent
return parent
})
}
}
// for now
$.fn.detach = $.fn.remove
// Generate the `width` and `height` functions
;['width', 'height'].forEach(function(dimension){
var dimensionProperty =
dimension.replace(/./, function(m){ return m[0].toUpperCase() })
$.fn[dimension] = function(value){
var offset, el = this[0]
if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] :
isDocument(el) ? el.documentElement['scroll' + dimensionProperty] :
(offset = this.offset()) && offset[dimension]
else return this.each(function(idx){
el = $(this)
el.css(dimension, funcArg(this, value, idx, el[dimension]()))
})
}
})
function traverseNode(node, fun) {
fun(node)
for (var key in node.childNodes) traverseNode(node.childNodes[key], fun)
}
// Generate the `after`, `prepend`, `before`, `append`,
// `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods.
adjacencyOperators.forEach(function(operator, operatorIndex) {
var inside = operatorIndex % 2 //=> prepend, append
$.fn[operator] = function(){
// arguments can be nodes, arrays of nodes, Zepto objects and HTML strings
var argType, nodes = $.map(arguments, function(arg) {
argType = type(arg)
return argType == "object" || argType == "array" || arg == null ?
arg : zepto.fragment(arg)
}),
parent, copyByClone = this.length > 1
if (nodes.length < 1) return this
return this.each(function(_, target){
parent = inside ? target : target.parentNode
// convert all methods to a "before" operation
target = operatorIndex == 0 ? target.nextSibling :
operatorIndex == 1 ? target.firstChild :
operatorIndex == 2 ? target :
null
nodes.forEach(function(node){
if (copyByClone) node = node.cloneNode(true)
else if (!parent) return $(node).remove()
traverseNode(parent.insertBefore(node, target), function(el){
if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' &&
(!el.type || el.type === 'text/javascript') && !el.src)
window['eval'].call(window, el.innerHTML)
})
})
})
}
// after => insertAfter
// prepend => prependTo
// before => insertBefore
// append => appendTo
$.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){
$(html)[operator](this)
return this
}
})
zepto.Z.prototype = $.fn
// Export internal API functions in the `$.zepto` namespace
zepto.uniq = uniq
zepto.deserializeValue = deserializeValue
$.zepto = zepto
return $
})()
window.Zepto = Zepto
window.$ === undefined && (window.$ = Zepto)
;(function($){
var $$ = $.zepto.qsa, _zid = 1, undefined,
slice = Array.prototype.slice,
isFunction = $.isFunction,
isString = function(obj){ return typeof obj == 'string' },
handlers = {},
specialEvents={},
focusinSupported = 'onfocusin' in window,
focus = { focus: 'focusin', blur: 'focusout' },
hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' }
specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents'
function zid(element) {
return element._zid || (element._zid = _zid++)
}
function findHandlers(element, event, fn, selector) {
event = parse(event)
if (event.ns) var matcher = matcherFor(event.ns)
return (handlers[zid(element)] || []).filter(function(handler) {
return handler
&& (!event.e || handler.e == event.e)
&& (!event.ns || matcher.test(handler.ns))
&& (!fn || zid(handler.fn) === zid(fn))
&& (!selector || handler.sel == selector)
})
}
function parse(event) {
var parts = ('' + event).split('.')
return {e: parts[0], ns: parts.slice(1).sort().join(' ')}
}
function matcherFor(ns) {
return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)')
}
function eventCapture(handler, captureSetting) {
return handler.del &&
(!focusinSupported && (handler.e in focus)) ||
!!captureSetting
}
function realEvent(type) {
return hover[type] || (focusinSupported && focus[type]) || type
}
function add(element, events, fn, data, selector, delegator, capture){
var id = zid(element), set = (handlers[id] || (handlers[id] = []))
events.split(/\s/).forEach(function(event){
if (event == 'ready') return $(document).ready(fn)
var handler = parse(event)
handler.fn = fn
handler.sel = selector
// emulate mouseenter, mouseleave
if (handler.e in hover) fn = function(e){
var related = e.relatedTarget
if (!related || (related !== this && !$.contains(this, related)))
return handler.fn.apply(this, arguments)
}
handler.del = delegator
var callback = delegator || fn
handler.proxy = function(e){
e = compatible(e)
if (e.isImmediatePropagationStopped()) return
e.data = data
var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args))
if (result === false) e.preventDefault(), e.stopPropagation()
return result
}
handler.i = set.length
set.push(handler)
if ('addEventListener' in element)
element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
}
function remove(element, events, fn, selector, capture){
var id = zid(element)
;(events || '').split(/\s/).forEach(function(event){
findHandlers(element, event, fn, selector).forEach(function(handler){
delete handlers[id][handler.i]
if ('removeEventListener' in element)
element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture))
})
})
}
$.event = { add: add, remove: remove }
$.proxy = function(fn, context) {
if (isFunction(fn)) {
var proxyFn = function(){ return fn.apply(context, arguments) }
proxyFn._zid = zid(fn)
return proxyFn
} else if (isString(context)) {
return $.proxy(fn[context], fn)
} else {
throw new TypeError("expected function")
}
}
$.fn.bind = function(event, data, callback){
return this.on(event, data, callback)
}
$.fn.unbind = function(event, callback){
return this.off(event, callback)
}
$.fn.one = function(event, selector, data, callback){
return this.on(event, selector, data, callback, 1)
}
var returnTrue = function(){return true},
returnFalse = function(){return false},
ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/,
eventMethods = {
preventDefault: 'isDefaultPrevented',
stopImmediatePropagation: 'isImmediatePropagationStopped',
stopPropagation: 'isPropagationStopped'
}
function compatible(event, source) {
if (source || !event.isDefaultPrevented) {
source || (source = event)
$.each(eventMethods, function(name, predicate) {
var sourceMethod = source[name]
event[name] = function(){
this[predicate] = returnTrue
return sourceMethod && sourceMethod.apply(source, arguments)
}
event[predicate] = returnFalse
})
if (source.defaultPrevented !== undefined ? source.defaultPrevented :
'returnValue' in source ? source.returnValue === false :
source.getPreventDefault && source.getPreventDefault())
event.isDefaultPrevented = returnTrue
}
return event
}
function createProxy(event) {
var key, proxy = { originalEvent: event }
for (key in event)
if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key]
return compatible(proxy, event)
}
$.fn.delegate = function(selector, event, callback){
return this.on(event, selector, callback)
}
$.fn.undelegate = function(selector, event, callback){
return this.off(event, selector, callback)
}
$.fn.live = function(event, callback){
$(document.body).delegate(this.selector, event, callback)
return this
}
$.fn.die = function(event, callback){
$(document.body).undelegate(this.selector, event, callback)
return this
}
$.fn.on = function(event, selector, data, callback, one){
var autoRemove, delegator, $this = this
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.on(type, selector, data, fn, one)
})
return $this
}
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = data, data = selector, selector = undefined
if (isFunction(data) || data === false)
callback = data, data = undefined
if (callback === false) callback = returnFalse
return $this.each(function(_, element){
if (one) autoRemove = function(e){
remove(element, e.type, callback)
return callback.apply(this, arguments)
}
if (selector) delegator = function(e){
var evt, match = $(e.target).closest(selector, element).get(0)
if (match && match !== element) {
evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element})
return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1)))
}
}
add(element, event, callback, data, selector, delegator || autoRemove)
})
}
$.fn.off = function(event, selector, callback){
var $this = this
if (event && !isString(event)) {
$.each(event, function(type, fn){
$this.off(type, selector, fn)
})
return $this
}
if (!isString(selector) && !isFunction(callback) && callback !== false)
callback = selector, selector = undefined
if (callback === false) callback = returnFalse
return $this.each(function(){
remove(this, event, callback, selector)
})
}
$.fn.trigger = function(event, args){
event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event)
event._args = args
return this.each(function(){
// items in the collection might not be DOM elements
if('dispatchEvent' in this) this.dispatchEvent(event)
else $(this).triggerHandler(event, args)
})
}
// triggers event handlers on current element just as if an event occurred,
// doesn't trigger an actual event, doesn't bubble
$.fn.triggerHandler = function(event, args){
var e, result
this.each(function(i, element){
e = createProxy(isString(event) ? $.Event(event) : event)
e._args = args
e.target = element
$.each(findHandlers(element, event.type || event), function(i, handler){
result = handler.proxy(e)
if (e.isImmediatePropagationStopped()) return false
})
})
return result
}
// shortcut methods for `.bind(event, fn)` for each event type
;('focusin focusout load resize scroll unload click dblclick '+
'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+
'change select keydown keypress keyup error').split(' ').forEach(function(event) {
$.fn[event] = function(callback) {
return callback ?
this.bind(event, callback) :
this.trigger(event)
}
})
;['focus', 'blur'].forEach(function(name) {
$.fn[name] = function(callback) {
if (callback) this.bind(name, callback)
else this.each(function(){
try { this[name]() }
catch(e) {}
})
return this
}
})
$.Event = function(type, props) {
if (!isString(type)) props = type, type = props.type
var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true
if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name])
event.initEvent(type, bubbles, true)
return compatible(event)
}
})(Zepto)
;(function($){
var jsonpID = 0,
document = window.document,
key,
name,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
scriptTypeRE = /^(?:text|application)\/javascript/i,
xmlTypeRE = /^(?:text|application)\/xml/i,
jsonType = 'application/json',
htmlType = 'text/html',
blankRE = /^\s*$/
// trigger a custom event and return false if it was cancelled
function triggerAndReturn(context, eventName, data) {
var event = $.Event(eventName)
$(context).trigger(event, data)
return !event.isDefaultPrevented()
}
// trigger an Ajax "global" event
function triggerGlobal(settings, context, eventName, data) {
if (settings.global) return triggerAndReturn(context || document, eventName, data)
}
// Number of active Ajax requests
$.active = 0
function ajaxStart(settings) {
if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart')
}
function ajaxStop(settings) {
if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop')
}
// triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable
function ajaxBeforeSend(xhr, settings) {
var context = settings.context
if (settings.beforeSend.call(context, xhr, settings) === false ||
triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false)
return false
triggerGlobal(settings, context, 'ajaxSend', [xhr, settings])
}
function ajaxSuccess(data, xhr, settings, deferred) {
var context = settings.context, status = 'success'
settings.success.call(context, data, status, xhr)
if (deferred) deferred.resolveWith(context, [data, status, xhr])
triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data])
ajaxComplete(status, xhr, settings)
}
// type: "timeout", "error", "abort", "parsererror"
function ajaxError(error, type, xhr, settings, deferred) {
var context = settings.context
settings.error.call(context, xhr, type, error)
if (deferred) deferred.rejectWith(context, [xhr, type, error])
triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type])
ajaxComplete(type, xhr, settings)
}
// status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
function ajaxComplete(status, xhr, settings) {
var context = settings.context
settings.complete.call(context, xhr, status)
triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings])
ajaxStop(settings)
}
// Empty function, used as default callback
function empty() {}
$.ajaxJSONP = function(options, deferred){
if (!('type' in options)) return $.ajax(options)
var _callbackName = options.jsonpCallback,
callbackName = ($.isFunction(_callbackName) ?
_callbackName() : _callbackName) || ('jsonp' + (++jsonpID)),
script = document.createElement('script'),
originalCallback = window[callbackName],
responseData,
abort = function(errorType) {
$(script).triggerHandler('error', errorType || 'abort')
},
xhr = { abort: abort }, abortTimeout
if (deferred) deferred.promise(xhr)
$(script).on('load error', function(e, errorType){
clearTimeout(abortTimeout)
$(script).off().remove()
if (e.type == 'error' || !responseData) {
ajaxError(null, errorType || 'error', xhr, options, deferred)
} else {
ajaxSuccess(responseData[0], xhr, options, deferred)
}
window[callbackName] = originalCallback
if (responseData && $.isFunction(originalCallback))
originalCallback(responseData[0])
originalCallback = responseData = undefined
})
if (ajaxBeforeSend(xhr, options) === false) {
abort('abort')
return xhr
}
window[callbackName] = function(){
responseData = arguments
}
script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName)
document.head.appendChild(script)
if (options.timeout > 0) abortTimeout = setTimeout(function(){
abort('timeout')
}, options.timeout)
return xhr
}
$.ajaxSettings = {
// Default type of request
type: 'GET',
// Callback that is executed before request
beforeSend: empty,
// Callback that is executed if the request succeeds
success: empty,
// Callback that is executed the the server drops error
error: empty,
// Callback that is executed on request complete (both: error and success)
complete: empty,
// The context for the callbacks
context: null,
// Whether to trigger "global" Ajax events
global: true,
// Transport
xhr: function () {
return new window.XMLHttpRequest()
},
// MIME types mapping
// IIS returns Javascript as "application/x-javascript"
accepts: {
script: 'text/javascript, application/javascript, application/x-javascript',
json: jsonType,
xml: 'application/xml, text/xml',
html: htmlType,
text: 'text/plain'
},
// Whether the request is to another domain
crossDomain: false,
// Default timeout
timeout: 0,
// Whether data should be serialized to string
processData: true,
// Whether the browser should be allowed to cache GET responses
cache: true
}
function mimeToDataType(mime) {
if (mime) mime = mime.split(';', 2)[0]
return mime && ( mime == htmlType ? 'html' :
mime == jsonType ? 'json' :
scriptTypeRE.test(mime) ? 'script' :
xmlTypeRE.test(mime) && 'xml' ) || 'text'
}
function appendQuery(url, query) {
if (query == '') return url
return (url + '&' + query).replace(/[&?]{1,2}/, '?')
}
// serialize payload and append it to the URL for GET requests
function serializeData(options) {
if (options.processData && options.data && $.type(options.data) != "string")
options.data = $.param(options.data, options.traditional)
if (options.data && (!options.type || options.type.toUpperCase() == 'GET'))
options.url = appendQuery(options.url, options.data), options.data = undefined
}
$.ajax = function(options){
var settings = $.extend({}, options || {}),
deferred = $.Deferred && $.Deferred()
for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key]
ajaxStart(settings)
if (!settings.crossDomain) settings.crossDomain = /^([\w-]+:)?\/\/([^\/]+)/.test(settings.url) &&
RegExp.$2 != window.location.host
if (!settings.url) settings.url = window.location.toString()
serializeData(settings)
if (settings.cache === false) settings.url = appendQuery(settings.url, '_=' + Date.now())
var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url)
if (dataType == 'jsonp' || hasPlaceholder) {
if (!hasPlaceholder)
settings.url = appendQuery(settings.url,
settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?')
return $.ajaxJSONP(settings, deferred)
}
var mime = settings.accepts[dataType],
headers = { },
setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] },
protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol,
xhr = settings.xhr(),
nativeSetHeader = xhr.setRequestHeader,
abortTimeout
if (deferred) deferred.promise(xhr)
if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest')
setHeader('Accept', mime || '*/*')
if (mime = settings.mimeType || mime) {
if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0]
xhr.overrideMimeType && xhr.overrideMimeType(mime)
}
if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET'))
setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded')
if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name])
xhr.setRequestHeader = setHeader
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
xhr.onreadystatechange = empty
clearTimeout(abortTimeout)
var result, error = false
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) {
dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'))
result = xhr.responseText
try {
// http://perfectionkills.com/global-eval-what-are-the-options/
if (dataType == 'script') (1,eval)(result)
else if (dataType == 'xml') result = xhr.responseXML
else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result)
} catch (e) { error = e }
if (error) ajaxError(error, 'parsererror', xhr, settings, deferred)
else ajaxSuccess(result, xhr, settings, deferred)
} else {
ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred)
}
}
}
if (ajaxBeforeSend(xhr, settings) === false) {
xhr.abort()
ajaxError(null, 'abort', xhr, settings, deferred)
return xhr
}
if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name]
var async = 'async' in settings ? settings.async : true
xhr.open(settings.type, settings.url, async, settings.username, settings.password)
for (name in headers) nativeSetHeader.apply(xhr, headers[name])
if (settings.timeout > 0) abortTimeout = setTimeout(function(){
xhr.onreadystatechange = empty
xhr.abort()
ajaxError(null, 'timeout', xhr, settings, deferred)
}, settings.timeout)
// avoid sending empty string (#319)
xhr.send(settings.data ? settings.data : null)
return xhr
}
// handle optional data/success arguments
function parseArguments(url, data, success, dataType) {
var hasData = !$.isFunction(data)
return {
url: url,
data: hasData ? data : undefined,
success: !hasData ? data : $.isFunction(success) ? success : undefined,
dataType: hasData ? dataType || success : success
}
}
$.get = function(url, data, success, dataType){
return $.ajax(parseArguments.apply(null, arguments))
}
$.post = function(url, data, success, dataType){
var options = parseArguments.apply(null, arguments)
options.type = 'POST'
return $.ajax(options)
}
$.getJSON = function(url, data, success){
var options = parseArguments.apply(null, arguments)
options.dataType = 'json'
return $.ajax(options)
}
$.fn.load = function(url, data, success){
if (!this.length) return this
var self = this, parts = url.split(/\s/), selector,
options = parseArguments(url, data, success),
callback = options.success
if (parts.length > 1) options.url = parts[0], selector = parts[1]
options.success = function(response){
self.html(selector ?
$('<div>').html(response.replace(rscript, "")).find(selector)
: response)
callback && callback.apply(self, arguments)
}
$.ajax(options)
return this
}
var escape = encodeURIComponent
function serialize(params, obj, traditional, scope){
var type, array = $.isArray(obj), hash = $.isPlainObject(obj)
$.each(obj, function(key, value) {
type = $.type(value)
if (scope) key = traditional ? scope :
scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']'
// handle data in serializeArray() format
if (!scope && array) params.add(value.name, value.value)
// recurse into nested objects
else if (type == "array" || (!traditional && type == "object"))
serialize(params, value, traditional, key)
else params.add(key, value)
})
}
$.param = function(obj, traditional){
var params = []
params.add = function(k, v){ this.push(escape(k) + '=' + escape(v)) }
serialize(params, obj, traditional)
return params.join('&').replace(/%20/g, '+')
}
})(Zepto)
;(function($){
$.fn.serializeArray = function() {
var result = [], el
$([].slice.call(this.get(0).elements)).each(function(){
el = $(this)
var type = el.attr('type')
if (this.nodeName.toLowerCase() != 'fieldset' &&
!this.disabled && type != 'submit' && type != 'reset' && type != 'button' &&
((type != 'radio' && type != 'checkbox') || this.checked))
result.push({
name: el.attr('name'),
value: el.val()
})
})
return result
}
$.fn.serialize = function(){
var result = []
this.serializeArray().forEach(function(elm){
result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value))
})
return result.join('&')
}
$.fn.submit = function(callback) {
if (callback) this.bind('submit', callback)
else if (this.length) {
var event = $.Event('submit')
this.eq(0).trigger(event)
if (!event.isDefaultPrevented()) this.get(0).submit()
}
return this
}
})(Zepto)
;(function($){
// __proto__ doesn't exist on IE<11, so redefine
// the Z function to use object extension instead
if (!('__proto__' in {})) {
$.extend($.zepto, {
Z: function(dom, selector){
dom = dom || []
$.extend(dom, $.fn)
dom.selector = selector || ''
dom.__Z = true
return dom
},
// this is a kludge but works
isZ: function(object){
return $.type(object) === 'array' && '__Z' in object
}
})
}
// getComputedStyle shouldn't freak out when called
// without a valid element as argument
try {
getComputedStyle(undefined)
} catch(e) {
var nativeGetComputedStyle = getComputedStyle;
window.getComputedStyle = function(element){
try {
return nativeGetComputedStyle(element)
} catch(e) {
return null
}
}
}
})(Zepto)
TL.getJSON = Zepto.getJSON;
TL.ajax = Zepto.ajax;
})(TL)
// Based on https://github.com/madrobby/zepto/blob/5585fe00f1828711c04208372265a5d71e3238d1/src/ajax.js
// Zepto.js
// (c) 2010-2012 Thomas Fuchs
// Zepto.js may be freely distributed under the MIT license.
/*
Copyright (c) 2010-2012 Thomas Fuchs
http://zeptojs.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* **********************************************
Begin TL.Class.js
********************************************** */
/* TL.Class
Class powers the OOP facilities of the library.
================================================== */
TL.Class = function () {};
TL.Class.extend = function (/*Object*/ props) /*-> Class*/ {
// extended class with the new prototype
var NewClass = function () {
if (this.initialize) {
this.initialize.apply(this, arguments);
}
};
// instantiate class without calling constructor
var F = function () {};
F.prototype = this.prototype;
var proto = new F();
proto.constructor = NewClass;
NewClass.prototype = proto;
// add superclass access
NewClass.superclass = this.prototype;
// add class name
//proto.className = props;
//inherit parent's statics
for (var i in this) {
if (this.hasOwnProperty(i) && i !== 'prototype' && i !== 'superclass') {
NewClass[i] = this[i];
}
}
// mix static properties into the class
if (props.statics) {
TL.Util.extend(NewClass, props.statics);
delete props.statics;
}
// mix includes into the prototype
if (props.includes) {
TL.Util.extend.apply(null, [proto].concat(props.includes));
delete props.includes;
}
// merge options
if (props.options && proto.options) {
props.options = TL.Util.extend({}, proto.options, props.options);
}
// mix given properties into the prototype
TL.Util.extend(proto, props);
// allow inheriting further
NewClass.extend = TL.Class.extend;
// method for adding properties to prototype
NewClass.include = function (props) {
TL.Util.extend(this.prototype, props);
};
return NewClass;
};
/* **********************************************
Begin TL.Events.js
********************************************** */
/* TL.Events
adds custom events functionality to TL classes
================================================== */
TL.Events = {
addEventListener: function (/*String*/ type, /*Function*/ fn, /*(optional) Object*/ context) {
var events = this._tl_events = this._tl_events || {};
events[type] = events[type] || [];
events[type].push({
action: fn,
context: context || this
});
return this;
},
hasEventListeners: function (/*String*/ type) /*-> Boolean*/ {
var k = '_tl_events';
return (k in this) && (type in this[k]) && (this[k][type].length > 0);
},
removeEventListener: function (/*String*/ type, /*Function*/ fn, /*(optional) Object*/ context) {
if (!this.hasEventListeners(type)) {
return this;
}
for (var i = 0, events = this._tl_events, len = events[type].length; i < len; i++) {
if (
(events[type][i].action === fn) &&
(!context || (events[type][i].context === context))
) {
events[type].splice(i, 1);
return this;
}
}
return this;
},
fireEvent: function (/*String*/ type, /*(optional) Object*/ data) {
if (!this.hasEventListeners(type)) {
return this;
}
var event = TL.Util.mergeData({
type: type,
target: this
}, data);
var listeners = this._tl_events[type].slice();
for (var i = 0, len = listeners.length; i < len; i++) {
listeners[i].action.call(listeners[i].context || this, event);
}
return this;
}
};
TL.Events.on = TL.Events.addEventListener;
TL.Events.off = TL.Events.removeEventListener;
TL.Events.fire = TL.Events.fireEvent;
/* **********************************************
Begin TL.Browser.js
********************************************** */
/*
Based on Leaflet Browser
TL.Browser handles different browser and feature detections for internal use.
*/
(function() {
var ua = navigator.userAgent.toLowerCase(),
doc = document.documentElement,
ie = 'ActiveXObject' in window,
webkit = ua.indexOf('webkit') !== -1,
phantomjs = ua.indexOf('phantom') !== -1,
android23 = ua.search('android [23]') !== -1,
mobile = typeof orientation !== 'undefined',
msPointer = navigator.msPointerEnabled && navigator.msMaxTouchPoints && !window.PointerEvent,
pointer = (window.PointerEvent && navigator.pointerEnabled && navigator.maxTouchPoints) || msPointer,
ie3d = ie && ('transition' in doc.style),
webkit3d = ('WebKitCSSMatrix' in window) && ('m11' in new window.WebKitCSSMatrix()) && !android23,
gecko3d = 'MozPerspective' in doc.style,
opera3d = 'OTransition' in doc.style,
opera = window.opera;
var retina = 'devicePixelRatio' in window && window.devicePixelRatio > 1;
if (!retina && 'matchMedia' in window) {
var matches = window.matchMedia('(min-resolution:144dpi)');
retina = matches && matches.matches;
}
var touch = !window.L_NO_TOUCH && !phantomjs && (pointer || 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch));
TL.Browser = {
ie: ie,
ielt9: ie && !document.addEventListener,
webkit: webkit,
//gecko: (ua.indexOf('gecko') !== -1) && !webkit && !window.opera && !ie,
firefox: (ua.indexOf('gecko') !== -1) && !webkit && !window.opera && !ie,
android: ua.indexOf('android') !== -1,
android23: android23,
chrome: ua.indexOf('chrome') !== -1,
ie3d: ie3d,
webkit3d: webkit3d,
gecko3d: gecko3d,
opera3d: opera3d,
any3d: !window.L_DISABLE_3D && (ie3d || webkit3d || gecko3d || opera3d) && !phantomjs,
mobile: mobile,
mobileWebkit: mobile && webkit,
mobileWebkit3d: mobile && webkit3d,
mobileOpera: mobile && window.opera,
touch: !! touch,
msPointer: !! msPointer,
pointer: !! pointer,
retina: !! retina,
orientation: function() {
var w = window.innerWidth,
h = window.innerHeight,
_orientation = "portrait";
if (w > h) {
_orientation = "landscape";
}
if (Math.abs(window.orientation) == 90) {
//_orientation = "landscape";
}
trace(_orientation);
return _orientation;
}
};
}());
/* **********************************************
Begin TL.Load.js
********************************************** */
/* TL.Load
Loads External Javascript and CSS
================================================== */
TL.Load = (function (doc) {
var loaded = [];
function isLoaded(url) {
var i = 0,
has_loaded = false;
for (i = 0; i < loaded.length; i++) {
if (loaded[i] == url) {
has_loaded = true;
}
}
if (has_loaded) {
return true;
} else {
loaded.push(url);
return false;
}
}
return {
css: function (urls, callback, obj, context) {
if (!isLoaded(urls)) {
TL.LoadIt.css(urls, callback, obj, context);
} else {
callback();
}
},
js: function (urls, callback, obj, context) {
if (!isLoaded(urls)) {
TL.LoadIt.js(urls, callback, obj, context);
} else {
callback();
}
}
};
})(this.document);
/*jslint browser: true, eqeqeq: true, bitwise: true, newcap: true, immed: true, regexp: false */
/*
LazyLoad makes it easy and painless to lazily load one or more external
JavaScript or CSS files on demand either during or after the rendering of a web
page.
Supported browsers include Firefox 2+, IE6+, Safari 3+ (including Mobile
Safari), Google Chrome, and Opera 9+. Other browsers may or may not work and
are not officially supported.
Visit https://github.com/rgrove/lazyload/ for more info.
Copyright (c) 2011 Ryan Grove <ryan@wonko.com>
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the 'Software'), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@module lazyload
@class LazyLoad
@static
@version 2.0.3 (git)
*/
TL.LoadIt = (function (doc) {
// -- Private Variables ------------------------------------------------------
// User agent and feature test information.
var env,
// Reference to the <head> element (populated lazily).
head,
// Requests currently in progress, if any.
pending = {},
// Number of times we've polled to check whether a pending stylesheet has
// finished loading. If this gets too high, we're probably stalled.
pollCount = 0,
// Queued requests.
queue = {css: [], js: []},
// Reference to the browser's list of stylesheets.
styleSheets = doc.styleSheets;
// -- Private Methods --------------------------------------------------------
/**
Creates and returns an HTML element with the specified name and attributes.
@method createNode
@param {String} name element name
@param {Object} attrs name/value mapping of element attributes
@return {HTMLElement}
@private
*/
function createNode(name, attrs) {
var node = doc.createElement(name), attr;
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
node.setAttribute(attr, attrs[attr]);
}
}
return node;
}
/**
Called when the current pending resource of the specified type has finished
loading. Executes the associated callback (if any) and loads the next
resource in the queue.
@method finish
@param {String} type resource type ('css' or 'js')
@private
*/
function finish(type) {
var p = pending[type],
callback,
urls;
if (p) {
callback = p.callback;
urls = p.urls;
urls.shift();
pollCount = 0;
// If this is the last of the pending URLs, execute the callback and
// start the next request in the queue (if any).
if (!urls.length) {
callback && callback.call(p.context, p.obj);
pending[type] = null;
queue[type].length && load(type);
}
}
}
/**
Populates the <code>env</code> variable with user agent and feature test
information.
@method getEnv
@private
*/
function getEnv() {
var ua = navigator.userAgent;
env = {
// True if this browser supports disabling async mode on dynamically
// created script nodes. See
// http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order
async: doc.createElement('script').async === true
};
(env.webkit = /AppleWebKit\//.test(ua))
|| (env.ie = /MSIE/.test(ua))
|| (env.opera = /Opera/.test(ua))
|| (env.gecko = /Gecko\//.test(ua))
|| (env.unknown = true);
}
/**
Loads the specified resources, or the next resource of the specified type
in the queue if no resources are specified. If a resource of the specified
type is already being loaded, the new request will be queued until the
first request has been finished.
When an array of resource URLs is specified, those URLs will be loaded in
parallel if it is possible to do so while preserving execution order. All
browsers support parallel loading of CSS, but only Firefox and Opera
support parallel loading of scripts. In other browsers, scripts will be
queued and loaded one at a time to ensure correct execution order.
@method load
@param {String} type resource type ('css' or 'js')
@param {String|Array} urls (optional) URL or array of URLs to load
@param {Function} callback (optional) callback function to execute when the
resource is loaded
@param {Object} obj (optional) object to pass to the callback function
@param {Object} context (optional) if provided, the callback function will
be executed in this object's context
@private
*/
function load(type, urls, callback, obj, context) {
var _finish = function () { finish(type); },
isCSS = type === 'css',
nodes = [],
i, len, node, p, pendingUrls, url;
env || getEnv();
if (urls) {
// If urls is a string, wrap it in an array. Otherwise assume it's an
// array and create a copy of it so modifications won't be made to the
// original.
urls = typeof urls === 'string' ? [urls] : urls.concat();
// Create a request object for each URL. If multiple URLs are specified,
// the callback will only be executed after all URLs have been loaded.
//
// Sadly, Firefox and Opera are the only browsers capable of loading
// scripts in parallel while preserving execution order. In all other
// browsers, scripts must be loaded sequentially.
//
// All browsers respect CSS specificity based on the order of the link
// elements in the DOM, regardless of the order in which the stylesheets
// are actually downloaded.
if (isCSS || env.async || env.gecko || env.opera) {
// Load in parallel.
queue[type].push({
urls : urls,
callback: callback,
obj : obj,
context : context
});
} else {
// Load sequentially.
for (i = 0, len = urls.length; i < len; ++i) {
queue[type].push({
urls : [urls[i]],
callback: i === len - 1 ? callback : null, // callback is only added to the last URL
obj : obj,
context : context
});
}
}
}
// If a previous load request of this type is currently in progress, we'll
// wait our turn. Otherwise, grab the next item in the queue.
if (pending[type] || !(p = pending[type] = queue[type].shift())) {
return;
}
head || (head = doc.head || doc.getElementsByTagName('head')[0]);
pendingUrls = p.urls;
for (i = 0, len = pendingUrls.length; i < len; ++i) {
url = pendingUrls[i];
if (isCSS) {
node = env.gecko ? createNode('style') : createNode('link', {
href: url,
rel : 'stylesheet'
});
} else {
node = createNode('script', {src: url});
node.async = false;
}
node.className = 'lazyload';
node.setAttribute('charset', 'utf-8');
if (env.ie && !isCSS) {
node.onreadystatechange = function () {
if (/loaded|complete/.test(node.readyState)) {
node.onreadystatechange = null;
_finish();
}
};
} else if (isCSS && (env.gecko || env.webkit)) {
// Gecko and WebKit don't support the onload event on link nodes.
if (env.webkit) {
// In WebKit, we can poll for changes to document.styleSheets to
// figure out when stylesheets have loaded.
p.urls[i] = node.href; // resolve relative URLs (or polling won't work)
pollWebKit();
} else {
// In Gecko, we can import the requested URL into a <style> node and
// poll for the existence of node.sheet.cssRules. Props to Zach
// Leatherman for calling my attention to this technique.
node.innerHTML = '@import "' + url + '";';
pollGecko(node);
}
} else {
node.onload = node.onerror = _finish;
}
nodes.push(node);
}
for (i = 0, len = nodes.length; i < len; ++i) {
head.appendChild(nodes[i]);
}
}
/**
Begins polling to determine when the specified stylesheet has finished loading
in Gecko. Polling stops when all pending stylesheets have loaded or after 10
seconds (to prevent stalls).
Thanks to Zach Leatherman for calling my attention to the @import-based
cross-domain technique used here, and to Oleg Slobodskoi for an earlier
same-domain implementation. See Zach's blog for more details:
http://www.zachleat.com/web/2010/07/29/load-css-dynamically/
@method pollGecko
@param {HTMLElement} node Style node to poll.
@private
*/
function pollGecko(node) {
var hasRules;
try {
// We don't really need to store this value or ever refer to it again, but
// if we don't store it, Closure Compiler assumes the code is useless and
// removes it.
hasRules = !!node.sheet.cssRules;
} catch (ex) {
// An exception means the stylesheet is still loading.
pollCount += 1;
if (pollCount < 200) {
setTimeout(function () { pollGecko(node); }, 50);
} else {
// We've been polling for 10 seconds and nothing's happened. Stop
// polling and finish the pending requests to avoid blocking further
// requests.
hasRules && finish('css');
}
return;
}
// If we get here, the stylesheet has loaded.
finish('css');
}
/**
Begins polling to determine when pending stylesheets have finished loading
in WebKit. Polling stops when all pending stylesheets have loaded or after 10
seconds (to prevent stalls).
@method pollWebKit
@private
*/
function pollWebKit() {
var css = pending.css, i;
if (css) {
i = styleSheets.length;
// Look for a stylesheet matching the pending URL.
while (--i >= 0) {
if (styleSheets[i].href === css.urls[0]) {
finish('css');
break;
}
}
pollCount += 1;
if (css) {
if (pollCount < 200) {
setTimeout(pollWebKit, 50);
} else {
// We've been polling for 10 seconds and nothing's happened, which may
// indicate that the stylesheet has been removed from the document
// before it had a chance to load. Stop polling and finish the pending
// request to prevent blocking further requests.
finish('css');
}
}
}
}
return {
/**
Requests the specified CSS URL or URLs and executes the specified
callback (if any) when they have finished loading. If an array of URLs is
specified, the stylesheets will be loaded in parallel and the callback
will be executed after all stylesheets have finished loading.
@method css
@param {String|Array} urls CSS URL or array of CSS URLs to load
@param {Function} callback (optional) callback function to execute when
the specified stylesheets are loaded
@param {Object} obj (optional) object to pass to the callback function
@param {Object} context (optional) if provided, the callback function
will be executed in this object's context
@static
*/
css: function (urls, callback, obj, context) {
load('css', urls, callback, obj, context);
},
/**
Requests the specified JavaScript URL or URLs and executes the specified
callback (if any) when they have finished loading. If an array of URLs is
specified and the browser supports it, the scripts will be loaded in
parallel and the callback will be executed after all scripts have
finished loading.
Currently, only Firefox and Opera support parallel loading of scripts while
preserving execution order. In other browsers, scripts will be
queued and loaded one at a time to ensure correct execution order.
@method js
@param {String|Array} urls JS URL or array of JS URLs to load
@param {Function} callback (optional) callback function to execute when
the specified scripts are loaded
@param {Object} obj (optional) object to pass to the callback function
@param {Object} context (optional) if provided, the callback function
will be executed in this object's context
@static
*/
js: function (urls, callback, obj, context) {
load('js', urls, callback, obj, context);
}
};
})(this.document);
/* **********************************************
Begin TL.TimelineConfig.js
********************************************** */
/* TL.TimelineConfig
separate the configuration from the display (TL.Timeline)
to make testing easier
================================================== */
TL.TimelineConfig = TL.Class.extend({
includes: [],
initialize: function (data) {
this.title = '';
this.scale = '';
this.events = [];
this.eras = [];
this.event_dict = {}; // despite name, all slides (events + title) indexed by slide.unique_id
this.messages = {
errors: [],
warnings: []
};
// Initialize the data
if (typeof data === 'object' && data.events) {
this.scale = data.scale;
this.events = [];
this._ensureValidScale(data.events);
if (data.title) {
var title_id = this._assignID(data.title);
this._tidyFields(data.title);
this.title = data.title;
this.event_dict[title_id] = this.title;
}
for (var i = 0; i < data.events.length; i++) {
try {
this.addEvent(data.events[i], true);
} catch (e) {
this.logError("Event " + i + ": " + e);
}
}
if (data.eras) {
for (var i = 0; i < data.eras.length; i++) {
try {
this.addEra(data.eras[i], true);
} catch (e) {
this.logError("Era " + i + ": " + e);
}
}
}
TL.DateUtil.sortByDate(this.events);
TL.DateUtil.sortByDate(this.eras);
}
},
logError: function(msg) {
trace(msg);
this.messages.errors.push(msg);
},
/*
* Return any accumulated error messages. If `sep` is passed, it should be a string which will be used to join all messages, resulting in a string return value. Otherwise,
* errors will be returned as an array.
*/
getErrors: function(sep) {
if (sep) {
return this.messages.errors.join(sep);
} else {
return this.messages.errors;
}
},
/*
* Perform any sanity checks we can before trying to use this to make a timeline. Returns nothing, but errors will be logged
* such that after this is called, one can test `this.isValid()` to see if everything is OK.
*/
validate: function() {
if (typeof(this.events) == "undefined" || typeof(this.events.length) == "undefined" || this.events.length == 0) {
this.logError("Timeline configuration has no events.")
}
},
isValid: function() {
return this.messages.errors.length == 0;
},
/* Add an event (including cleaning/validation) and return the unique id.
* All event data validation should happen in here.
* Throws: string errors for any validation problems.
*/
addEvent: function(data, defer_sort) {
var event_id = this._assignID(data);
if (typeof(data.start_date) == 'undefined') {
throw(event_id + " is missing a start_date");
} else {
this._processDates(data);
this._tidyFields(data);
}
this.events.push(data);
this.event_dict[event_id] = data;
if (!defer_sort) {
TL.DateUtil.sortByDate(this.events);
}
return event_id;
},
addEra: function(data, defer_sort) {
var event_id = this._assignID(data);
if (typeof(data.start_date) == 'undefined') {
throw(event_id + " is missing a start_date");
} else {
this._processDates(data);
this._tidyFields(data);
}
this.eras.push(data);
this.event_dict[event_id] = data;
if (!defer_sort) {
TL.DateUtil.sortByDate(this.eras);
}
return event_id;
},
/**
* Given a slide, verify that its ID is unique, or assign it one which is.
* The assignment happens in this function, and the assigned ID is also
* the return value. Not thread-safe, because ids are not reserved
* when assigned here.
*/
_assignID: function(slide) {
var slide_id = slide.unique_id;
if (!TL.Util.trim(slide_id)) {
// give it an ID if it doesn't have one
slide_id = (slide.text) ? TL.Util.slugify(slide.text.headline) : null;
}
// make sure it's unique and add it.
slide.unique_id = TL.Util.ensureUniqueKey(this.event_dict,slide_id);
return slide.unique_id
},
/**
* Given an array of slide configs (the events), ensure that each one has a distinct unique_id. The id of the title
* is also passed in because in most ways it functions as an event slide, and the event IDs must also all be unique
* from the title ID.
*/
_makeUniqueIdentifiers: function(title_id, array) {
var used = [title_id];
// establish which IDs are assigned and if any appear twice, clear out successors.
for (var i = 0; i < array.length; i++) {
if (TL.Util.trim(array[i].unique_id)) {
array[i].unique_id = TL.Util.slugify(array[i].unique_id); // enforce valid
if (used.indexOf(array[i].unique_id) == -1) {
used.push(array[i].unique_id);
} else { // it was already used, wipe it out
array[i].unique_id = '';
}
}
};
if (used.length != (array.length + 1)) {
// at least some are yet to be assigned
for (var i = 0; i < array.length; i++) {
if (!array[i].unique_id) {
// use the headline for the unique ID if it's available
var slug = (array[i].text) ? TL.Util.slugify(array[i].text.headline) : null;
if (!slug) {
slug = TL.Util.unique_ID(6); // or generate a random ID
}
if (used.indexOf(slug) != -1) {
slug = slug + '-' + i; // use the index to get a unique ID.
}
used.push(slug);
array[i].unique_id = slug;
}
}
}
},
_ensureValidScale: function(events) {
if(!this.scale) {
trace("Determining scale dynamically");
this.scale = "human"; // default to human unless there's a slide which is explicitly 'cosmological' or one which has a cosmological year
for (var i = 0; i < events.length; i++) {
if (events[i].scale == 'cosmological') {
this.scale = 'cosmological';
break;
}
if (events[i].start_date && typeof(events[i].start_date.year) != "undefined") {
var d = new TL.BigDate(events[i].start_date);
var year = d.data.date_obj.year;
if(year < -271820 || year > 275759) {
this.scale = "cosmological";
break;
}
}
}
}
var dateCls = TL.DateUtil.SCALE_DATE_CLASSES[this.scale];
if (!dateCls) { this.logError("Don't know how to process dates on scale "+this.scale); }
},
/*
Given a thing which has a start_date and optionally an end_date, make sure that it is an instance
of the correct date class (for human or cosmological scale). For slides, remove redundant end dates
(people frequently configure an end date which is the same as the start date).
*/
_processDates: function(slide_or_era) {
var dateCls = TL.DateUtil.SCALE_DATE_CLASSES[this.scale];
if(!(slide_or_era.start_date instanceof dateCls)) {
var start_date = slide_or_era.start_date;
slide_or_era.start_date = new dateCls(start_date);
// eliminate redundant end dates.
if (typeof(slide_or_era.end_date) != 'undefined' && !(slide_or_era.end_date instanceof dateCls)) {
var end_date = slide_or_era.end_date;
var equal = true;
for (property in start_date) {
equal = equal && (start_date[property] == end_date[property]);
}
if (equal) {
trace("End date same as start date is redundant; dropping end date");
delete slide_or_era.end_date;
} else {
slide_or_era.end_date = new dateCls(end_date);
}
}
}
},
/**
* Return the earliest date that this config knows about, whether it's a slide or an era
*/
getEarliestDate: function() {
// counting that dates were sorted in initialization
var date = this.events[0].start_date;
if (this.eras && this.eras.length > 0) {
if (this.eras[0].start_date.isBefore(date)) {
return this.eras[0].start_date;
}
}
return date;
},
/**
* Return the latest date that this config knows about, whether it's a slide or an era, taking end_dates into account.
*/
getLatestDate: function() {
var dates = [];
for (var i = 0; i < this.events.length; i++) {
if (this.events[i].end_date) {
dates.push({ date: this.events[i].end_date });
} else {
dates.push({ date: this.events[i].start_date });
}
}
for (var i = 0; i < this.eras.length; i++) {
if (this.eras[i].end_date) {
dates.push({ date: this.eras[i].end_date });
} else {
dates.push({ date: this.eras[i].start_date });
}
}
TL.DateUtil.sortByDate(dates, 'date');
return dates.slice(-1)[0].date;
},
_tidyFields: function(slide) {
function fillIn(obj,key,default_value) {
if (!default_value) default_value = '';
if (!obj.hasOwnProperty(key)) { obj[key] = default_value }
}
if (slide.group) {
slide.group = TL.Util.trim(slide.group);
}
if (!slide.text) {
slide.text = {};
}
fillIn(slide.text,'text');
fillIn(slide.text,'headline');
}
});
/* **********************************************
Begin TL.ConfigFactory.js
********************************************** */
/* TL.ConfigFactory.js
* Build TimelineConfig objects from other data sources
*/
;(function(TL){
/*
* Convert a URL to a Google Spreadsheet (typically a /pubhtml version but somewhat flexible) into an object with the spreadsheet key (ID) and worksheet ID.
If `url` is actually a string which is only letters, numbers, '-' and '_', then it's assumed to be an ID already. If we had a more precise way of testing to see if the input argument was a valid key, we might apply it, but I don't know where that's documented.
If we're pretty sure this isn't a bare key or a url that could be used to find a Google spreadsheet then return null.
*/
function parseGoogleSpreadsheetURL(url) {
parts = {
key: null,
worksheet: 0 // not really sure how to use this to get the feed for that sheet, so this is not ready except for first sheet right now
}
// key as url parameter (old-fashioned)
var pat = /\bkey=([-_A-Za-z0-9]+)&?/i;
if (url.match(pat)) {
parts.key = url.match(pat)[1];
// can we get a worksheet from this form?
} else if (url.match("docs.google.com/spreadsheets/d/")) {
var pos = url.indexOf("docs.google.com/spreadsheets/d/") + "docs.google.com/spreadsheets/d/".length;
var tail = url.substr(pos);
parts.key = tail.split('/')[0]
if (url.match(/\?gid=(\d+)/)) {
parts.worksheet = url.match(/\?gid=(\d+)/)[1];
}
} else if (url.match(/^\b[-_A-Za-z0-9]+$/)) {
parts.key = url;
}
if (parts.key) {
return parts;
} else {
return null;
}
}
function extractGoogleEntryData_V1(item) {
var item_data = {}
for (k in item) {
if (k.indexOf('gsx$') == 0) {
item_data[k.substr(4)] = item[k].$t;
}
}
if (TL.Util.isEmptyObject(item_data)) return null;
var d = {
media: {
caption: item_data.mediacaption || '',
credit: item_data.mediacredit || '',
url: item_data.media || '',
thumbnail: item_data.mediathumbnail || ''
},
text: {
headline: item_data.headline || '',
text: item_data.text || ''
},
group: item_data.tag || '',
type: item_data.type || ''
}
if (item_data.startdate) {
d['start_date'] = TL.Date.parseDate(item_data.startdate);
}
if (item_data.enddate) {
d['end_date'] = TL.Date.parseDate(item_data.enddate);
}
return d;
}
function extractGoogleEntryData_V3(item) {
function clean_integer(s) {
if (s) {
return s.replace(/[\s,]+/g,''); // doesn't handle '.' as comma separator, but how to distinguish that from decimal separator?
}
}
var item_data = {}
for (k in item) {
if (k.indexOf('gsx$') == 0) {
item_data[k.substr(4)] = TL.Util.trim(item[k].$t);
}
}
if (TL.Util.isEmptyObject(item_data)) return null;
var d = {
media: {
caption: item_data.mediacaption || '',
credit: item_data.mediacredit || '',
url: item_data.media || '',
thumbnail: item_data.mediathumbnail || ''
},
text: {
headline: item_data.headline || '',
text: item_data.text || ''
},
start_date: {
year: clean_integer(item_data.year),
month: clean_integer(item_data.month) || '',
day: clean_integer(item_data.day) || ''
},
end_date: {
year: clean_integer(item_data.endyear) || '',
month: clean_integer(item_data.endmonth) || '',
day: clean_integer(item_data.endday) || ''
},
display_date: item_data.displaydate || '',
type: item_data.type || ''
}
if (item_data.time) {
TL.Util.mergeData(d.start_date,TL.DateUtil.parseTime(item_data.time));
}
if (item_data.endtime) {
TL.Util.mergeData(d.end_date,TL.DateUtil.parseTime(item_data.endtime));
}
if (item_data.group) {
d.group = item_data.group;
}
if (d.end_date.year == '') {
var bad_date = d.end_date;
delete d.end_date;
if (bad_date.month != '' || bad_date.day != '' || bad_date.time != '') {
var label = d.text.headline ||
trace("Invalid end date for spreadsheet row. Must have a year if any other date fields are specified.");
trace(item);
}
}
if (item_data.background) {
if (item_data.background.match(/^(https?:)?\/\/?/)) { // support http, https, protocol relative, site relative
d['background'] = { 'url': item_data.background }
} else { // for now we'll trust it's a color
d['background'] = { 'color': item_data.background }
}
}
return d;
}
var getGoogleItemExtractor = function(data) {
if (typeof data.feed.entry === 'undefined'
|| data.feed.entry.length == 0) {
throw('No data entries found.');
}
var entry = data.feed.entry[0];
if (typeof entry.gsx$startdate !== 'undefined') {
return extractGoogleEntryData_V1;
} else if (typeof entry.gsx$year !== 'undefined') {
return extractGoogleEntryData_V3;
} else {
throw('Invalid data format.');
}
}
var buildGoogleFeedURL = function(parts) {
return "https://spreadsheets.google.com/feeds/list/" + parts.key + "/1/public/values?alt=json";
}
var jsonFromGoogleURL = function(url) {
var url = buildGoogleFeedURL(parseGoogleSpreadsheetURL(url));
var timeline_config = { 'events': [] };
var data = TL.ajax({
url: url,
async: false
});
data = JSON.parse(data.responseText);
return googleFeedJSONtoTimelineJSON(data);
}
var googleFeedJSONtoTimelineJSON = function(data) {
var timeline_config = { 'events': [], 'errors': [], 'eras': [] }
var extract = getGoogleItemExtractor(data);
for (var i = 0; i < data.feed.entry.length; i++) {
try {
var event = extract(data.feed.entry[i]);
if (event) { // blank rows return null
var row_type = 'event';
if (typeof(event.type) != 'undefined') {
row_type = event.type;
delete event.type;
}
if (row_type == 'title') {
timeline_config.title = event;
} else if (row_type == 'era') {
timeline_config.eras.push(event);
} else {
timeline_config.events.push(event);
}
}
} catch(e) {
if (e.message) {
e = e.message;
}
timeline_config.errors.push(e + " ["+ i +"]");
}
};
return timeline_config;
}
var makeConfig = function(url, callback) {
var key = parseGoogleSpreadsheetURL(url);
if (key) {
try {
var json = jsonFromGoogleURL(url);
} catch(e) {
tc = new TL.TimelineConfig();
if (e.name == 'NetworkError') {
tc.logError("Unable to read your Google Spreadsheet. Make sure you have published it to the web.")
} else {
tc.logError("An unexpected error occurred trying to read your spreadsheet data ["+e.name+"]");
}
callback(tc);
return;
}
var tc = new TL.TimelineConfig(json);
if (json.errors) {
for (var i = 0; i < json.errors.length; i++) {
tc.logError(json.errors[i]);
};
}
callback(tc);
} else {
TL.getJSON(url, function(data){
callback(new TL.TimelineConfig(data));
});
}
}
TL.ConfigFactory = {
// export for unit testing and use by authoring tool
parseGoogleSpreadsheetURL: parseGoogleSpreadsheetURL,
// export for unit testing
googleFeedJSONtoTimelineJSON: googleFeedJSONtoTimelineJSON,
fromGoogle: function(url) {
console.log("TL.ConfigFactory.fromGoogle is deprecated and will be removed soon. Use TL.ConfigFactory.makeConfig(url,callback)")
return jsonFromGoogleURL(url);
},
/*
* Given a URL to a Timeline data source, read the data, create a TimelineConfig
* object, and call the given `callback` function passing the created config as
* the only argument. This should be the main public interface to getting configs
* from any kind of URL, Google or direct JSON.
*/
makeConfig: makeConfig,
}
})(TL)
/* **********************************************
Begin TL.Language.js
********************************************** */
TL.Language = function(options) {
// borrowed from http://stackoverflow.com/a/14446414/102476
for (k in TL.Language.languages.en) {
this[k] = TL.Language.languages.en[k];
}
if (options && options.language && typeof(options.language) == 'string' && options.language != 'en') {
var code = options.language;
if (!(code in TL.Language.languages)) {
if (/\.json$/.test(code)) {
var url = code;
} else {
var fragment = "/locale/" + code + ".json";
var script_path = options.script_path || TL.Timeline.source_path;
if (/\/$/.test(script_path)) { fragment = fragment.substr(1)}
var url = script_path + fragment;
}
var self = this;
var xhr = TL.ajax({
url: url, async: false
});
if (xhr.status == 200) {
TL.Language.languages[code] = JSON.parse(xhr.responseText);
} else {
throw "Could not load language [" + code + "]: " + xhr.statusText;
}
}
TL.Util.mergeData(this,TL.Language.languages[code]);
}
}
TL.Language.formatNumber = function(val,mask) {
if (mask.match(/%(\.(\d+))?f/)) {
var match = mask.match(/%(\.(\d+))?f/);
var token = match[0];
if (match[2]) {
val = val.toFixed(match[2]);
}
return mask.replace(token,val);
}
// use mask as literal display value.
return mask;
}
/* TL.Util.mergeData is shallow, we have nested dicts.
This is a simplistic handling but should work.
*/
TL.Language.prototype.mergeData = function(lang_json) {
for (k in TL.Language.languages.en) {
if (lang_json[k]) {
if (typeof(this[k]) == 'object') {
TL.Util.mergeData(lang_json[k], this[k]);
} else {
this[k] = lang_json[k]; // strings, mostly
}
}
}
}
TL.Language.fallback = { messages: {} }; // placeholder to satisfy IE8 early compilation
TL.Language.prototype.getMessage = function(k) {
return this.messages[k] || TL.Language.fallback.messages[k] || k;
}
TL.Language.prototype._ = TL.Language.prototype.getMessage; // keep it concise
TL.Language.prototype.formatDate = function(date, format_name) {
if (date.constructor == Date) {
return this.formatJSDate(date, format_name);
}
if (date.constructor == TL.BigYear) {
return this.formatBigYear(date, format_name);
}
if (date.data && date.data.date_obj) {
return this.formatDate(date.data.date_obj, format_name);
}
trace("Unfamiliar date presented for formatting");
return date.toString();
}
TL.Language.prototype.formatBigYear = function(bigyear, format_name) {
var the_year = bigyear.year;
var format_list = this.bigdateformats[format_name] || this.bigdateformats['fallback'];
if (format_list) {
for (var i = 0; i < format_list.length; i++) {
var tuple = format_list[i];
if (Math.abs(the_year / tuple[0]) > 1) {
// will we ever deal with distant future dates?
return TL.Language.formatNumber(Math.abs(the_year / tuple[0]),tuple[1])
}
};
return the_year.toString();
} else {
trace("Language file dateformats missing cosmological. Falling back.");
return TL.Language.formatNumber(the_year,format_name);
}
}
TL.Language.prototype.formatJSDate = function(js_date, format_name) {
// ultimately we probably want this to work with TL.Date instead of (in addition to?) JS Date
// utc, timezone and timezoneClip are carry over from Steven Levithan implementation. We probably aren't going to use them.
var self = this;
var formatPeriod = function(fmt, value) {
var formats = self.period_labels[fmt];
if (formats) {
var fmt = (value < 12) ? formats[0] : formats[1];
}
return "<span class='tl-timeaxis-timesuffix'>" + fmt + "</span>";
}
var utc = false,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g;
if (!format_name) {
format_name = 'full';
}
var mask = this.dateformats[format_name] || TL.Language.fallback.dateformats[format_name];
if (!mask) {
mask = format_name; // allow custom format strings
}
var _ = utc ? "getUTC" : "get",
d = js_date[_ + "Date"](),
D = js_date[_ + "Day"](),
m = js_date[_ + "Month"](),
y = js_date[_ + "FullYear"](),
H = js_date[_ + "Hours"](),
M = js_date[_ + "Minutes"](),
s = js_date[_ + "Seconds"](),
L = js_date[_ + "Milliseconds"](),
o = utc ? 0 : js_date.getTimezoneOffset(),
year = "",
flags = {
d: d,
dd: TL.Util.pad(d),
ddd: this.date.day_abbr[D],
dddd: this.date.day[D],
m: m + 1,
mm: TL.Util.pad(m + 1),
mmm: this.date.month_abbr[m],
mmmm: this.date.month[m],
yy: String(y).slice(2),
yyyy: (y < 0 && this.has_negative_year_modifier()) ? Math.abs(y) : y,
h: H % 12 || 12,
hh: TL.Util.pad(H % 12 || 12),
H: H,
HH: TL.Util.pad(H),
M: M,
MM: TL.Util.pad(M),
s: s,
ss: TL.Util.pad(s),
l: TL.Util.pad(L, 3),
L: TL.Util.pad(L > 99 ? Math.round(L / 10) : L),
t: formatPeriod('t',H),
tt: formatPeriod('tt',H),
T: formatPeriod('T',H),
TT: formatPeriod('TT',H),
Z: utc ? "UTC" : (String(js_date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + TL.Util.pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
};
var formatted = mask.replace(TL.Language.DATE_FORMAT_TOKENS, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
return this._applyEra(formatted, y);
}
TL.Language.prototype.has_negative_year_modifier = function() {
return Boolean(this.era_labels.negative_year.prefix || this.era_labels.negative_year.suffix);
}
TL.Language.prototype._applyEra = function(formatted_date, original_year) {
// trusts that the formatted_date was property created with a non-negative year if there are
// negative affixes to be applied
var labels = (original_year < 0) ? this.era_labels.negative_year : this.era_labels.positive_year;
var result = '';
if (labels.prefix) { result += '<span>' + labels.prefix + '</span> ' }
result += formatted_date;
if (labels.suffix) { result += ' <span>' + labels.suffix + '</span>' }
return result;
}
TL.Language.DATE_FORMAT_TOKENS = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g;
TL.Language.languages = {
/*
This represents the canonical list of message keys which translation files should handle. The existence of the 'en.json' file should not mislead you.
It is provided more as a starting point for someone who wants to provide a
new translation since the form for non-default languages (JSON not JS) is slightly different from what appears below. Also, those files have some message keys grandfathered in from TimelineJS2 which we'd rather not have to
get "re-translated" if we use them.
*/
en: {
name: "English",
lang: "en",
messages: {
loading: "Loading",
wikipedia: "From Wikipedia, the free encyclopedia",
error: "Error"
},
date: {
month: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
month_abbr: ["Jan.", "Feb.", "March", "April", "May", "June", "July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."],
day: ["Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
day_abbr: ["Sun.","Mon.", "Tues.", "Wed.", "Thurs.", "Fri.", "Sat."]
},
era_labels: { // specify prefix or suffix to apply to formatted date. Blanks mean no change.
positive_year: {
prefix: '',
suffix: ''
},
negative_year: { // if either of these is specified, the year will be converted to positive before they are applied
prefix: '',
suffix: 'BCE'
}
},
period_labels: { // use of t/tt/T/TT legacy of original Timeline date format
t: ['a', 'p'],
tt: ['am', 'pm'],
T: ['A', 'P'],
TT: ['AM', 'PM']
},
dateformats: {
year: "yyyy",
month_short: "mmm",
month: "mmmm yyyy",
full_short: "mmm d",
full: "mmmm d',' yyyy",
time: "h:MM:ss TT' <small>'mmmm d',' yyyy'</small>'",
time_short: "h:MM:ss TT",
time_no_seconds_short: "h:MM TT",
time_no_minutes_short: "h TT",
time_no_seconds_small_date: "h:MM TT' <small>'mmmm d',' yyyy'</small>'",
time_milliseconds: "l",
full_long: "mmm d',' yyyy 'at' h:MM TT",
full_long_small_date: "h:MM TT' <small>mmm d',' yyyy'</small>'"
},
bigdateformats: {
fallback: [ // a list of tuples, with t[0] an order of magnitude and t[1] a format string. format string syntax may change...
[1000000000,"%.2f billion years ago"],
[1000000,"%.1f million years ago"],
[1000,"%.1f thousand years ago"],
[1, "%f years ago"]
],
compact: [
[1000000000,"%.2f bya"],
[1000000,"%.1f mya"],
[1000,"%.1f kya"],
[1, "%f years ago"]
],
verbose: [
[1000000000,"%.2f billion years ago"],
[1000000,"%.1f million years ago"],
[1000,"%.1f thousand years ago"],
[1, "%f years ago"]
]
}
}
}
TL.Language.fallback = new TL.Language();
/* **********************************************
Begin TL.I18NMixins.js
********************************************** */
/* TL.I18NMixins
assumes that its class has an options object with a TL.Language instance
================================================== */
TL.I18NMixins = {
getLanguage: function() {
if (this.options && this.options.language) {
return this.options.language;
}
trace("Expected a language option");
return TL.Language.fallback;
},
_: function(msg) {
return this.getLanguage()._(msg);
}
}
/* **********************************************
Begin TL.Ease.js
********************************************** */
/* The equations defined here are open source under BSD License.
* http://www.robertpenner.com/easing_terms_of_use.html (c) 2003 Robert Penner
* Adapted to single time-based by
* Brian Crescimanno <brian.crescimanno@gmail.com>
* Ken Snyder <kendsnyder@gmail.com>
*/
/** MIT License
*
* KeySpline - use bezier curve for transition easing function
* Copyright (c) 2012 Gaetan Renaudeau <renaudeau.gaetan@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/**
* KeySpline - use bezier curve for transition easing function
* is inspired from Firefox's nsSMILKeySpline.cpp
* Usage:
* var spline = new KeySpline(0.25, 0.1, 0.25, 1.0)
* spline.get(x) => returns the easing value | x must be in [0, 1] range
*/
TL.Easings = {
ease: [0.25, 0.1, 0.25, 1.0],
linear: [0.00, 0.0, 1.00, 1.0],
easein: [0.42, 0.0, 1.00, 1.0],
easeout: [0.00, 0.0, 0.58, 1.0],
easeinout: [0.42, 0.0, 0.58, 1.0]
};
TL.Ease = {
KeySpline: function(a) {
//KeySpline: function(mX1, mY1, mX2, mY2) {
this.get = function(aX) {
if (a[0] == a[1] && a[2] == a[3]) return aX; // linear
return CalcBezier(GetTForX(aX), a[1], a[3]);
}
function A(aA1, aA2) {
return 1.0 - 3.0 * aA2 + 3.0 * aA1;
}
function B(aA1, aA2) {
return 3.0 * aA2 - 6.0 * aA1;
}
function C(aA1) {
return 3.0 * aA1;
}
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
function CalcBezier(aT, aA1, aA2) {
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
}
// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
function GetSlope(aT, aA1, aA2) {
return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
}
function GetTForX(aX) {
// Newton raphson iteration
var aGuessT = aX;
for (var i = 0; i < 4; ++i) {
var currentSlope = GetSlope(aGuessT, a[0], a[2]);
if (currentSlope == 0.0) return aGuessT;
var currentX = CalcBezier(aGuessT, a[0], a[2]) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
},
easeInSpline: function(t) {
var spline = new TL.Ease.KeySpline(TL.Easings.easein);
return spline.get(t);
},
easeInOutExpo: function(t) {
var spline = new TL.Ease.KeySpline(TL.Easings.easein);
return spline.get(t);
},
easeOut: function(t) {
return Math.sin(t * Math.PI / 2);
},
easeOutStrong: function(t) {
return (t == 1) ? 1 : 1 - Math.pow(2, - 10 * t);
},
easeIn: function(t) {
return t * t;
},
easeInStrong: function(t) {
return (t == 0) ? 0 : Math.pow(2, 10 * (t - 1));
},
easeOutBounce: function(pos) {
if ((pos) < (1 / 2.75)) {
return (7.5625 * pos * pos);
} else if (pos < (2 / 2.75)) {
return (7.5625 * (pos -= (1.5 / 2.75)) * pos + .75);
} else if (pos < (2.5 / 2.75)) {
return (7.5625 * (pos -= (2.25 / 2.75)) * pos + .9375);
} else {
return (7.5625 * (pos -= (2.625 / 2.75)) * pos + .984375);
}
},
easeInBack: function(pos) {
var s = 1.70158;
return (pos) * pos * ((s + 1) * pos - s);
},
easeOutBack: function(pos) {
var s = 1.70158;
return (pos = pos - 1) * pos * ((s + 1) * pos + s) + 1;
},
bounce: function(t) {
if (t < (1 / 2.75)) {
return 7.5625 * t * t;
}
if (t < (2 / 2.75)) {
return 7.5625 * (t -= (1.5 / 2.75)) * t + 0.75;
}
if (t < (2.5 / 2.75)) {
return 7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375;
}
return 7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375;
},
bouncePast: function(pos) {
if (pos < (1 / 2.75)) {
return (7.5625 * pos * pos);
} else if (pos < (2 / 2.75)) {
return 2 - (7.5625 * (pos -= (1.5 / 2.75)) * pos + .75);
} else if (pos < (2.5 / 2.75)) {
return 2 - (7.5625 * (pos -= (2.25 / 2.75)) * pos + .9375);
} else {
return 2 - (7.5625 * (pos -= (2.625 / 2.75)) * pos + .984375);
}
},
swingTo: function(pos) {
var s = 1.70158;
return (pos -= 1) * pos * ((s + 1) * pos + s) + 1;
},
swingFrom: function(pos) {
var s = 1.70158;
return pos * pos * ((s + 1) * pos - s);
},
elastic: function(pos) {
return -1 * Math.pow(4, - 8 * pos) * Math.sin((pos * 6 - 1) * (2 * Math.PI) / 2) + 1;
},
spring: function(pos) {
return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
},
blink: function(pos, blinks) {
return Math.round(pos * (blinks || 5)) % 2;
},
pulse: function(pos, pulses) {
return (-Math.cos((pos * ((pulses || 5) - .5) * 2) * Math.PI) / 2) + .5;
},
wobble: function(pos) {
return (-Math.cos(pos * Math.PI * (9 * pos)) / 2) + 0.5;
},
sinusoidal: function(pos) {
return (-Math.cos(pos * Math.PI) / 2) + 0.5;
},
flicker: function(pos) {
var pos = pos + (Math.random() - 0.5) / 5;
return easings.sinusoidal(pos < 0 ? 0 : pos > 1 ? 1 : pos);
},
mirror: function(pos) {
if (pos < 0.5) return easings.sinusoidal(pos * 2);
else return easings.sinusoidal(1 - (pos - 0.5) * 2);
},
// accelerating from zero velocity
easeInQuad: function (t) { return t*t },
// decelerating to zero velocity
easeOutQuad: function (t) { return t*(2-t) },
// acceleration until halfway, then deceleration
easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },
// accelerating from zero velocity
easeInCubic: function (t) { return t*t*t },
// decelerating to zero velocity
easeOutCubic: function (t) { return (--t)*t*t+1 },
// acceleration until halfway, then deceleration
easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 },
// accelerating from zero velocity
easeInQuart: function (t) { return t*t*t*t },
// decelerating to zero velocity
easeOutQuart: function (t) { return 1-(--t)*t*t*t },
// acceleration until halfway, then deceleration
easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t },
// accelerating from zero velocity
easeInQuint: function (t) { return t*t*t*t*t },
// decelerating to zero velocity
easeOutQuint: function (t) { return 1+(--t)*t*t*t*t },
// acceleration until halfway, then deceleration
easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t }
};
/*
Math.easeInExpo = function (t, b, c, d) {
return c * Math.pow( 2, 10 * (t/d - 1) ) + b;
};
// exponential easing out - decelerating to zero velocity
Math.easeOutExpo = function (t, b, c, d) {
return c * ( -Math.pow( 2, -10 * t/d ) + 1 ) + b;
};
// exponential easing in/out - accelerating until halfway, then decelerating
Math.easeInOutExpo = function (t, b, c, d) {
t /= d/2;
if (t < 1) return c/2 * Math.pow( 2, 10 * (t - 1) ) + b;
t--;
return c/2 * ( -Math.pow( 2, -10 * t) + 2 ) + b;
};
*/
/* **********************************************
Begin TL.Animate.js
********************************************** */
/* TL.Animate
Basic animation
================================================== */
TL.Animate = function(el, options) {
var animation = new tlanimate(el, options),
webkit_timeout;
/*
// POSSIBLE ISSUE WITH WEBKIT FUTURE BUILDS
var onWebKitTimeout = function() {
animation.stop(true);
}
if (TL.Browser.webkit) {
webkit_timeout = setTimeout(function(){onWebKitTimeout()}, options.duration);
}
*/
return animation;
};
/* Based on: Morpheus
https://github.com/ded/morpheus - (c) Dustin Diaz 2011
License MIT
================================================== */
window.tlanimate = (function() {
var doc = document,
win = window,
perf = win.performance,
perfNow = perf && (perf.now || perf.webkitNow || perf.msNow || perf.mozNow),
now = perfNow ? function () { return perfNow.call(perf) } : function () { return +new Date() },
html = doc.documentElement,
fixTs = false, // feature detected below
thousand = 1000,
rgbOhex = /^rgb\(|#/,
relVal = /^([+\-])=([\d\.]+)/,
numUnit = /^(?:[\+\-]=?)?\d+(?:\.\d+)?(%|in|cm|mm|em|ex|pt|pc|px)$/,
rotate = /rotate\(((?:[+\-]=)?([\-\d\.]+))deg\)/,
scale = /scale\(((?:[+\-]=)?([\d\.]+))\)/,
skew = /skew\(((?:[+\-]=)?([\-\d\.]+))deg, ?((?:[+\-]=)?([\-\d\.]+))deg\)/,
translate = /translate\(((?:[+\-]=)?([\-\d\.]+))px, ?((?:[+\-]=)?([\-\d\.]+))px\)/,
// these elements do not require 'px'
unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1, transform: 1};
// which property name does this browser use for transform
var transform = function () {
var styles = doc.createElement('a').style,
props = ['webkitTransform', 'MozTransform', 'OTransform', 'msTransform', 'Transform'],
i;
for (i = 0; i < props.length; i++) {
if (props[i] in styles) return props[i]
};
}();
// does this browser support the opacity property?
var opacity = function () {
return typeof doc.createElement('a').style.opacity !== 'undefined'
}();
// initial style is determined by the elements themselves
var getStyle = doc.defaultView && doc.defaultView.getComputedStyle ?
function (el, property) {
property = property == 'transform' ? transform : property
property = camelize(property)
var value = null,
computed = doc.defaultView.getComputedStyle(el, '');
computed && (value = computed[property]);
return el.style[property] || value;
} : html.currentStyle ?
function (el, property) {
property = camelize(property)
if (property == 'opacity') {
var val = 100
try {
val = el.filters['DXImageTransform.Microsoft.Alpha'].opacity
} catch (e1) {
try {
val = el.filters('alpha').opacity
} catch (e2) {
}
}
return val / 100
}
var value = el.currentStyle ? el.currentStyle[property] : null
return el.style[property] || value
} :
function (el, property) {
return el.style[camelize(property)]
}
var frame = function () {
// native animation frames
// http://webstuff.nfshost.com/anim-timing/Overview.html
// http://dev.chromium.org/developers/design-documents/requestanimationframe-implementation
return win.requestAnimationFrame ||
win.webkitRequestAnimationFrame ||
win.mozRequestAnimationFrame ||
win.msRequestAnimationFrame ||
win.oRequestAnimationFrame ||
function (callback) {
win.setTimeout(function () {
callback(+new Date())
}, 17) // when I was 17..
}
}()
var children = []
frame(function(timestamp) {
// feature-detect if rAF and now() are of the same scale (epoch or high-res),
// if not, we have to do a timestamp fix on each frame
fixTs = timestamp > 1e12 != now() > 1e12
})
function has(array, elem, i) {
if (Array.prototype.indexOf) return array.indexOf(elem)
for (i = 0; i < array.length; ++i) {
if (array[i] === elem) return i
}
}
function render(timestamp) {
var i, count = children.length
// if we're using a high res timer, make sure timestamp is not the old epoch-based value.
// http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision
if (perfNow && timestamp > 1e12) timestamp = now()
if (fixTs) timestamp = now()
for (i = count; i--;) {
children[i](timestamp)
}
children.length && frame(render)
}
function live(f) {
if (children.push(f) === 1) frame(render)
}
function die(f) {
var rest, index = has(children, f)
if (index >= 0) {
rest = children.slice(index + 1)
children.length = index
children = children.concat(rest)
}
}
function parseTransform(style, base) {
var values = {}, m
if (m = style.match(rotate)) values.rotate = by(m[1], base ? base.rotate : null)
if (m = style.match(scale)) values.scale = by(m[1], base ? base.scale : null)
if (m = style.match(skew)) {values.skewx = by(m[1], base ? base.skewx : null); values.skewy = by(m[3], base ? base.skewy : null)}
if (m = style.match(translate)) {values.translatex = by(m[1], base ? base.translatex : null); values.translatey = by(m[3], base ? base.translatey : null)}
return values
}
function formatTransform(v) {
var s = ''
if ('rotate' in v) s += 'rotate(' + v.rotate + 'deg) '
if ('scale' in v) s += 'scale(' + v.scale + ') '
if ('translatex' in v) s += 'translate(' + v.translatex + 'px,' + v.translatey + 'px) '
if ('skewx' in v) s += 'skew(' + v.skewx + 'deg,' + v.skewy + 'deg)'
return s
}
function rgb(r, g, b) {
return '#' + (1 << 24 | r << 16 | g << 8 | b).toString(16).slice(1)
}
// convert rgb and short hex to long hex
function toHex(c) {
var m = c.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/)
return (m ? rgb(m[1], m[2], m[3]) : c)
.replace(/#(\w)(\w)(\w)$/, '#$1$1$2$2$3$3') // short skirt to long jacket
}
// change font-size => fontSize etc.
function camelize(s) {
return s.replace(/-(.)/g, function (m, m1) {
return m1.toUpperCase()
})
}
// aren't we having it?
function fun(f) {
return typeof f == 'function'
}
function nativeTween(t) {
// default to a pleasant-to-the-eye easeOut (like native animations)
return Math.sin(t * Math.PI / 2)
}
/**
* Core tween method that requests each frame
* @param duration: time in milliseconds. defaults to 1000
* @param fn: tween frame callback function receiving 'position'
* @param done {optional}: complete callback function
* @param ease {optional}: easing method. defaults to easeOut
* @param from {optional}: integer to start from
* @param to {optional}: integer to end at
* @returns method to stop the animation
*/
function tween(duration, fn, done, ease, from, to) {
ease = fun(ease) ? ease : morpheus.easings[ease] || nativeTween
var time = duration || thousand
, self = this
, diff = to - from
, start = now()
, stop = 0
, end = 0
function run(t) {
var delta = t - start
if (delta > time || stop) {
to = isFinite(to) ? to : 1
stop ? end && fn(to) : fn(to)
die(run)
return done && done.apply(self)
}
// if you don't specify a 'to' you can use tween as a generic delta tweener
// cool, eh?
isFinite(to) ?
fn((diff * ease(delta / time)) + from) :
fn(ease(delta / time))
}
live(run)
return {
stop: function (jump) {
stop = 1
end = jump // jump to end of animation?
if (!jump) done = null // remove callback if not jumping to end
}
}
}
/**
* generic bezier method for animating x|y coordinates
* minimum of 2 points required (start and end).
* first point start, last point end
* additional control points are optional (but why else would you use this anyway ;)
* @param points: array containing control points
[[0, 0], [100, 200], [200, 100]]
* @param pos: current be(tween) position represented as float 0 - 1
* @return [x, y]
*/
function bezier(points, pos) {
var n = points.length, r = [], i, j
for (i = 0; i < n; ++i) {
r[i] = [points[i][0], points[i][1]]
}
for (j = 1; j < n; ++j) {
for (i = 0; i < n - j; ++i) {
r[i][0] = (1 - pos) * r[i][0] + pos * r[parseInt(i + 1, 10)][0]
r[i][1] = (1 - pos) * r[i][1] + pos * r[parseInt(i + 1, 10)][1]
}
}
return [r[0][0], r[0][1]]
}
// this gets you the next hex in line according to a 'position'
function nextColor(pos, start, finish) {
var r = [], i, e, from, to
for (i = 0; i < 6; i++) {
from = Math.min(15, parseInt(start.charAt(i), 16))
to = Math.min(15, parseInt(finish.charAt(i), 16))
e = Math.floor((to - from) * pos + from)
e = e > 15 ? 15 : e < 0 ? 0 : e
r[i] = e.toString(16)
}
return '#' + r.join('')
}
// this retreives the frame value within a sequence
function getTweenVal(pos, units, begin, end, k, i, v) {
if (k == 'transform') {
v = {}
for (var t in begin[i][k]) {
v[t] = (t in end[i][k]) ? Math.round(((end[i][k][t] - begin[i][k][t]) * pos + begin[i][k][t]) * thousand) / thousand : begin[i][k][t]
}
return v
} else if (typeof begin[i][k] == 'string') {
return nextColor(pos, begin[i][k], end[i][k])
} else {
// round so we don't get crazy long floats
v = Math.round(((end[i][k] - begin[i][k]) * pos + begin[i][k]) * thousand) / thousand
// some css properties don't require a unit (like zIndex, lineHeight, opacity)
if (!(k in unitless)) v += units[i][k] || 'px'
return v
}
}
// support for relative movement via '+=n' or '-=n'
function by(val, start, m, r, i) {
return (m = relVal.exec(val)) ?
(i = parseFloat(m[2])) && (start + (m[1] == '+' ? 1 : -1) * i) :
parseFloat(val)
}
/**
* morpheus:
* @param element(s): HTMLElement(s)
* @param options: mixed bag between CSS Style properties & animation options
* - {n} CSS properties|values
* - value can be strings, integers,
* - or callback function that receives element to be animated. method must return value to be tweened
* - relative animations start with += or -= followed by integer
* - duration: time in ms - defaults to 1000(ms)
* - easing: a transition method - defaults to an 'easeOut' algorithm
* - complete: a callback method for when all elements have finished
* - bezier: array of arrays containing x|y coordinates that define the bezier points. defaults to none
* - this may also be a function that receives element to be animated. it must return a value
*/
function morpheus(elements, options) {
var els = elements ? (els = isFinite(elements.length) ? elements : [elements]) : [], i
, complete = options.complete
, duration = options.duration
, ease = options.easing
, points = options.bezier
, begin = []
, end = []
, units = []
, bez = []
, originalLeft
, originalTop
if (points) {
// remember the original values for top|left
originalLeft = options.left;
originalTop = options.top;
delete options.right;
delete options.bottom;
delete options.left;
delete options.top;
}
for (i = els.length; i--;) {
// record beginning and end states to calculate positions
begin[i] = {}
end[i] = {}
units[i] = {}
// are we 'moving'?
if (points) {
var left = getStyle(els[i], 'left')
, top = getStyle(els[i], 'top')
, xy = [by(fun(originalLeft) ? originalLeft(els[i]) : originalLeft || 0, parseFloat(left)),
by(fun(originalTop) ? originalTop(els[i]) : originalTop || 0, parseFloat(top))]
bez[i] = fun(points) ? points(els[i], xy) : points
bez[i].push(xy)
bez[i].unshift([
parseInt(left, 10),
parseInt(top, 10)
])
}
for (var k in options) {
switch (k) {
case 'complete':
case 'duration':
case 'easing':
case 'bezier':
continue
}
var v = getStyle(els[i], k), unit
, tmp = fun(options[k]) ? options[k](els[i]) : options[k]
if (typeof tmp == 'string' &&
rgbOhex.test(tmp) &&
!rgbOhex.test(v)) {
delete options[k]; // remove key :(
continue; // cannot animate colors like 'orange' or 'transparent'
// only #xxx, #xxxxxx, rgb(n,n,n)
}
begin[i][k] = k == 'transform' ? parseTransform(v) :
typeof tmp == 'string' && rgbOhex.test(tmp) ?
toHex(v).slice(1) :
parseFloat(v)
end[i][k] = k == 'transform' ? parseTransform(tmp, begin[i][k]) :
typeof tmp == 'string' && tmp.charAt(0) == '#' ?
toHex(tmp).slice(1) :
by(tmp, parseFloat(v));
// record original unit
(typeof tmp == 'string') && (unit = tmp.match(numUnit)) && (units[i][k] = unit[1])
}
}
// ONE TWEEN TO RULE THEM ALL
return tween.apply(els, [duration, function (pos, v, xy) {
// normally not a fan of optimizing for() loops, but we want something
// fast for animating
for (i = els.length; i--;) {
if (points) {
xy = bezier(bez[i], pos)
els[i].style.left = xy[0] + 'px'
els[i].style.top = xy[1] + 'px'
}
for (var k in options) {
v = getTweenVal(pos, units, begin, end, k, i)
k == 'transform' ?
els[i].style[transform] = formatTransform(v) :
k == 'opacity' && !opacity ?
(els[i].style.filter = 'alpha(opacity=' + (v * 100) + ')') :
(els[i].style[camelize(k)] = v)
}
}
}, complete, ease])
}
// expose useful methods
morpheus.tween = tween
morpheus.getStyle = getStyle
morpheus.bezier = bezier
morpheus.transform = transform
morpheus.parseTransform = parseTransform
morpheus.formatTransform = formatTransform
morpheus.easings = {}
return morpheus
})();
/* **********************************************
Begin TL.Point.js
********************************************** */
/* TL.Point
Inspired by Leaflet
TL.Point represents a point with x and y coordinates.
================================================== */
TL.Point = function (/*Number*/ x, /*Number*/ y, /*Boolean*/ round) {
this.x = (round ? Math.round(x) : x);
this.y = (round ? Math.round(y) : y);
};
TL.Point.prototype = {
add: function (point) {
return this.clone()._add(point);
},
_add: function (point) {
this.x += point.x;
this.y += point.y;
return this;
},
subtract: function (point) {
return this.clone()._subtract(point);
},
// destructive subtract (faster)
_subtract: function (point) {
this.x -= point.x;
this.y -= point.y;
return this;
},
divideBy: function (num, round) {
return new TL.Point(this.x / num, this.y / num, round);
},
multiplyBy: function (num) {
return new TL.Point(this.x * num, this.y * num);
},
distanceTo: function (point) {
var x = point.x - this.x,
y = point.y - this.y;
return Math.sqrt(x * x + y * y);
},
round: function () {
return this.clone()._round();
},
// destructive round
_round: function () {
this.x = Math.round(this.x);
this.y = Math.round(this.y);
return this;
},
clone: function () {
return new TL.Point(this.x, this.y);
},
toString: function () {
return 'Point(' +
TL.Util.formatNum(this.x) + ', ' +
TL.Util.formatNum(this.y) + ')';
}
};
/* **********************************************
Begin TL.DomMixins.js
********************************************** */
/* TL.DomMixins
DOM methods used regularly
Assumes there is a _el.container and animator
================================================== */
TL.DomMixins = {
/* Adding, Hiding, Showing etc
================================================== */
show: function(animate) {
if (animate) {
/*
this.animator = TL.Animate(this._el.container, {
left: -(this._el.container.offsetWidth * n) + "px",
duration: this.options.duration,
easing: this.options.ease
});
*/
} else {
this._el.container.style.display = "block";
}
},
hide: function(animate) {
this._el.container.style.display = "none";
},
addTo: function(container) {
container.appendChild(this._el.container);
this.onAdd();
},
removeFrom: function(container) {
container.removeChild(this._el.container);
this.onRemove();
},
/* Animate to Position
================================================== */
animatePosition: function(pos, el) {
var ani = {
duration: this.options.duration,
easing: this.options.ease
};
for (var name in pos) {
if (pos.hasOwnProperty(name)) {
ani[name] = pos[name] + "px";
}
}
if (this.animator) {
this.animator.stop();
}
this.animator = TL.Animate(el, ani);
},
/* Events
================================================== */
onLoaded: function() {
this.fire("loaded", this.data);
},
onAdd: function() {
this.fire("added", this.data);
},
onRemove: function() {
this.fire("removed", this.data);
},
/* Set the Position
================================================== */
setPosition: function(pos, el) {
for (var name in pos) {
if (pos.hasOwnProperty(name)) {
if (el) {
el.style[name] = pos[name] + "px";
} else {
this._el.container.style[name] = pos[name] + "px";
};
}
}
},
getPosition: function() {
return TL.Dom.getPosition(this._el.container);
}
};
/* **********************************************
Begin TL.Dom.js
********************************************** */
/* TL.Dom
Utilities for working with the DOM
================================================== */
TL.Dom = {
get: function(id) {
return (typeof id === 'string' ? document.getElementById(id) : id);
},
getByClass: function(id) {
if (id) {
return document.getElementsByClassName(id);
}
},
create: function(tagName, className, container) {
var el = document.createElement(tagName);
el.className = className;
if (container) {
container.appendChild(el);
}
return el;
},
createText: function(content, container) {
var el = document.createTextNode(content);
if (container) {
container.appendChild(el);
}
return el;
},
getTranslateString: function (point) {
return TL.Dom.TRANSLATE_OPEN +
point.x + 'px,' + point.y + 'px' +
TL.Dom.TRANSLATE_CLOSE;
},
setPosition: function (el, point) {
el._tl_pos = point;
if (TL.Browser.webkit3d) {
el.style[TL.Dom.TRANSFORM] = TL.Dom.getTranslateString(point);
if (TL.Browser.android) {
el.style['-webkit-perspective'] = '1000';
el.style['-webkit-backface-visibility'] = 'hidden';
}
} else {
el.style.left = point.x + 'px';
el.style.top = point.y + 'px';
}
},
getPosition: function(el){
var pos = {
x: 0,
y: 0
}
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
pos.x += el.offsetLeft// - el.scrollLeft;
pos.y += el.offsetTop// - el.scrollTop;
el = el.offsetParent;
}
return pos;
},
testProp: function(props) {
var style = document.documentElement.style;
for (var i = 0; i < props.length; i++) {
if (props[i] in style) {
return props[i];
}
}
return false;
}
};
TL.Util.extend(TL.Dom, {
TRANSITION: TL.Dom.testProp(['transition', 'webkitTransition', 'OTransition', 'MozTransition', 'msTransition']),
TRANSFORM: TL.Dom.testProp(['transformProperty', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']),
TRANSLATE_OPEN: 'translate' + (TL.Browser.webkit3d ? '3d(' : '('),
TRANSLATE_CLOSE: TL.Browser.webkit3d ? ',0)' : ')'
});
/* **********************************************
Begin TL.DomUtil.js
********************************************** */
/* TL.DomUtil
Inspired by Leaflet
TL.DomUtil contains various utility functions for working with DOM
================================================== */
TL.DomUtil = {
get: function (id) {
return (typeof id === 'string' ? document.getElementById(id) : id);
},
getStyle: function (el, style) {
var value = el.style[style];
if (!value && el.currentStyle) {
value = el.currentStyle[style];
}
if (!value || value === 'auto') {
var css = document.defaultView.getComputedStyle(el, null);
value = css ? css[style] : null;
}
return (value === 'auto' ? null : value);
},
getViewportOffset: function (element) {
var top = 0,
left = 0,
el = element,
docBody = document.body;
do {
top += el.offsetTop || 0;
left += el.offsetLeft || 0;
if (el.offsetParent === docBody &&
TL.DomUtil.getStyle(el, 'position') === 'absolute') {
break;
}
el = el.offsetParent;
} while (el);
el = element;
do {
if (el === docBody) {
break;
}
top -= el.scrollTop || 0;
left -= el.scrollLeft || 0;
el = el.parentNode;
} while (el);
return new TL.Point(left, top);
},
create: function (tagName, className, container) {
var el = document.createElement(tagName);
el.className = className;
if (container) {
container.appendChild(el);
}
return el;
},
disableTextSelection: function () {
if (document.selection && document.selection.empty) {
document.selection.empty();
}
if (!this._onselectstart) {
this._onselectstart = document.onselectstart;
document.onselectstart = TL.Util.falseFn;
}
},
enableTextSelection: function () {
document.onselectstart = this._onselectstart;
this._onselectstart = null;
},
hasClass: function (el, name) {
return (el.className.length > 0) &&
new RegExp("(^|\\s)" + name + "(\\s|$)").test(el.className);
},
addClass: function (el, name) {
if (!TL.DomUtil.hasClass(el, name)) {
el.className += (el.className ? ' ' : '') + name;
}
},
removeClass: function (el, name) {
el.className = el.className.replace(/(\S+)\s*/g, function (w, match) {
if (match === name) {
return '';
}
return w;
}).replace(/^\s+/, '');
},
setOpacity: function (el, value) {
if (TL.Browser.ie) {
el.style.filter = 'alpha(opacity=' + Math.round(value * 100) + ')';
} else {
el.style.opacity = value;
}
},
testProp: function (props) {
var style = document.documentElement.style;
for (var i = 0; i < props.length; i++) {
if (props[i] in style) {
return props[i];
}
}
return false;
},
getTranslateString: function (point) {
return TL.DomUtil.TRANSLATE_OPEN +
point.x + 'px,' + point.y + 'px' +
TL.DomUtil.TRANSLATE_CLOSE;
},
getScaleString: function (scale, origin) {
var preTranslateStr = TL.DomUtil.getTranslateString(origin),
scaleStr = ' scale(' + scale + ') ',
postTranslateStr = TL.DomUtil.getTranslateString(origin.multiplyBy(-1));
return preTranslateStr + scaleStr + postTranslateStr;
},
setPosition: function (el, point) {
el._tl_pos = point;
if (TL.Browser.webkit3d) {
el.style[TL.DomUtil.TRANSFORM] = TL.DomUtil.getTranslateString(point);
if (TL.Browser.android) {
el.style['-webkit-perspective'] = '1000';
el.style['-webkit-backface-visibility'] = 'hidden';
}
} else {
el.style.left = point.x + 'px';
el.style.top = point.y + 'px';
}
},
getPosition: function (el) {
return el._tl_pos;
}
};
/* **********************************************
Begin TL.DomEvent.js
********************************************** */
/* TL.DomEvent
Inspired by Leaflet
DomEvent contains functions for working with DOM events.
================================================== */
// TODO stamp
TL.DomEvent = {
/* inpired by John Resig, Dean Edwards and YUI addEvent implementations */
addListener: function (/*HTMLElement*/ obj, /*String*/ type, /*Function*/ fn, /*Object*/ context) {
var id = TL.Util.stamp(fn),
key = '_tl_' + type + id;
if (obj[key]) {
return;
}
var handler = function (e) {
return fn.call(context || obj, e || TL.DomEvent._getEvent());
};
if (TL.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
this.addDoubleTapListener(obj, handler, id);
} else if ('addEventListener' in obj) {
if (type === 'mousewheel') {
obj.addEventListener('DOMMouseScroll', handler, false);
obj.addEventListener(type, handler, false);
} else if ((type === 'mouseenter') || (type === 'mouseleave')) {
var originalHandler = handler,
newType = (type === 'mouseenter' ? 'mouseover' : 'mouseout');
handler = function (e) {
if (!TL.DomEvent._checkMouse(obj, e)) {
return;
}
return originalHandler(e);
};
obj.addEventListener(newType, handler, false);
} else {
obj.addEventListener(type, handler, false);
}
} else if ('attachEvent' in obj) {
obj.attachEvent("on" + type, handler);
}
obj[key] = handler;
},
removeListener: function (/*HTMLElement*/ obj, /*String*/ type, /*Function*/ fn) {
var id = TL.Util.stamp(fn),
key = '_tl_' + type + id,
handler = obj[key];
if (!handler) {
return;
}
if (TL.Browser.touch && (type === 'dblclick') && this.removeDoubleTapListener) {
this.removeDoubleTapListener(obj, id);
} else if ('removeEventListener' in obj) {
if (type === 'mousewheel') {
obj.removeEventListener('DOMMouseScroll', handler, false);
obj.removeEventListener(type, handler, false);
} else if ((type === 'mouseenter') || (type === 'mouseleave')) {
obj.removeEventListener((type === 'mouseenter' ? 'mouseover' : 'mouseout'), handler, false);
} else {
obj.removeEventListener(type, handler, false);
}
} else if ('detachEvent' in obj) {
obj.detachEvent("on" + type, handler);
}
obj[key] = null;
},
_checkMouse: function (el, e) {
var related = e.relatedTarget;
if (!related) {
return true;
}
try {
while (related && (related !== el)) {
related = related.parentNode;
}
} catch (err) {
return false;
}
return (related !== el);
},
/*jshint noarg:false */ // evil magic for IE
_getEvent: function () {
var e = window.event;
if (!e) {
var caller = arguments.callee.caller;
while (caller) {
e = caller['arguments'][0];
if (e && window.Event === e.constructor) {
break;
}
caller = caller.caller;
}
}
return e;
},
/*jshint noarg:false */
stopPropagation: function (/*Event*/ e) {
if (e.stopPropagation) {
e.stopPropagation();
} else {
e.cancelBubble = true;
}
},
// TODO TL.Draggable.START
disableClickPropagation: function (/*HTMLElement*/ el) {
TL.DomEvent.addListener(el, TL.Draggable.START, TL.DomEvent.stopPropagation);
TL.DomEvent.addListener(el, 'click', TL.DomEvent.stopPropagation);
TL.DomEvent.addListener(el, 'dblclick', TL.DomEvent.stopPropagation);
},
preventDefault: function (/*Event*/ e) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
},
stop: function (e) {
TL.DomEvent.preventDefault(e);
TL.DomEvent.stopPropagation(e);
},
getWheelDelta: function (e) {
var delta = 0;
if (e.wheelDelta) {
delta = e.wheelDelta / 120;
}
if (e.detail) {
delta = -e.detail / 3;
}
return delta;
}
};
/* **********************************************
Begin TL.StyleSheet.js
********************************************** */
/* TL.StyleSheet
Style Sheet Object
================================================== */
TL.StyleSheet = TL.Class.extend({
includes: [TL.Events],
_el: {},
/* Constructor
================================================== */
initialize: function() {
// Borrowed from: http://davidwalsh.name/add-rules-stylesheets
this.style = document.createElement("style");
// WebKit hack :(
this.style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(this.style);
this.sheet = this.style.sheet;
},
addRule: function(selector, rules, index) {
var _index = 0;
if (index) {
_index = index;
}
if("insertRule" in this.sheet) {
this.sheet.insertRule(selector + "{" + rules + "}", _index);
}
else if("addRule" in this.sheet) {
this.sheet.addRule(selector, rules, _index);
}
},
/* Events
================================================== */
onLoaded: function(error) {
this._state.loaded = true;
this.fire("loaded", this.data);
}
});
/* **********************************************
Begin TL.Date.js
********************************************** */
/* TL.Date
Date object
MONTHS are 1-BASED, not 0-BASED (different from Javascript date objects)
================================================== */
//
// Class for human dates
//
TL.Date = TL.Class.extend({
// @data = ms, JS Date object, or JS dictionary with date properties
initialize: function (data, format, format_short) {
if (typeof(data) == 'number') {
this.data = {
format: "yyyy mmmm",
date_obj: new Date(data)
};
} else if(Date == data.constructor) {
this.data = {
format: "yyyy mmmm",
date_obj: data
};
} else {
this.data = JSON.parse(JSON.stringify(data)); // clone don't use by reference.
this._createDateObj();
}
this._setFormat(format, format_short);
},
setDateFormat: function(format) {
this.data.format = format;
},
getDisplayDate: function(language, format) {
if (this.data.display_date) {
return this.data.display_date;
}
if (!language) {
language = TL.Language.fallback;
}
if (language.constructor != TL.Language) {
trace("First argument to getDisplayDate must be TL.Language");
language = TL.Language.fallback;
}
var format_key = format || this.data.format;
return language.formatDate(this.data.date_obj, format_key);
},
getMillisecond: function() {
return this.getTime();
},
getTime: function() {
return this.data.date_obj.getTime();
},
isBefore: function(other_date) {
if (!this.data.date_obj.constructor == other_date.data.date_obj.constructor) {
throw("Can't compare TL.Dates on different scales") // but should be able to compare 'cosmological scale' dates once we get to that...
}
if ('isBefore' in this.data.date_obj) {
return this.data.date_obj['isBefore'](other_date.data.date_obj);
}
return this.data.date_obj < other_date.data.date_obj
},
isAfter: function(other_date) {
if (!this.data.date_obj.constructor == other_date.data.date_obj.constructor) {
throw("Can't compare TL.Dates on different scales") // but should be able to compare 'cosmological scale' dates once we get to that...
}
if ('isAfter' in this.data.date_obj) {
return this.data.date_obj['isAfter'](other_date.data.date_obj);
}
return this.data.date_obj > other_date.data.date_obj
},
// Return a new TL.Date which has been 'floored' at the given scale.
// @scale = string value from TL.Date.SCALES
floor: function(scale) {
var d = new Date(this.data.date_obj.getTime());
for (var i = 0; i < TL.Date.SCALES.length; i++) {
// for JS dates, we iteratively apply flooring functions
TL.Date.SCALES[i][2](d);
if (TL.Date.SCALES[i][0] == scale) return new TL.Date(d);
};
throw('invalid scale ' + scale);
},
/* Private Methods
================================================== */
_getDateData: function() {
var _date = {
year: 0,
month: 1, // stupid JS dates
day: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
};
// Merge data
TL.Util.mergeData(_date, this.data);
// Make strings into numbers
var DATE_PARTS = TL.Date.DATE_PARTS;
for (var ix in DATE_PARTS) {
var parsed = parseInt(_date[DATE_PARTS[ix]]);
if (isNaN(parsed)) {
parsed = (ix == 4 || ix == 5) ? 1 : 0; // month and day have diff baselines
}
_date[DATE_PARTS[ix]] = parsed;
}
if (_date.month > 0 && _date.month <= 12) { // adjust for JS's weirdness
_date.month = _date.month - 1;
}
return _date;
},
_createDateObj: function() {
var _date = this._getDateData();
this.data.date_obj = new Date(_date.year, _date.month, _date.day, _date.hour, _date.minute, _date.second, _date.millisecond);
if (this.data.date_obj.getFullYear() != _date.year) {
// Javascript has stupid defaults for two-digit years
this.data.date_obj.setFullYear(_date.year);
}
},
/* Find Best Format
* this may not work with 'cosmologic' dates, or with TL.Date if we
* support constructing them based on JS Date and time
================================================== */
findBestFormat: function(variant) {
var eval_array = TL.Date.DATE_PARTS,
format = "";
for (var i = 0; i < eval_array.length; i++) {
if ( this.data[eval_array[i]]) {
if (variant) {
if (!(variant in TL.Date.BEST_DATEFORMATS)) {
variant = 'short'; // legacy
}
} else {
variant = 'base'
}
return TL.Date.BEST_DATEFORMATS[variant][eval_array[i]];
}
};
return "";
},
_setFormat: function(format, format_short) {
if (format) {
this.data.format = format;
} else if (!this.data.format) {
this.data.format = this.findBestFormat();
}
if (format_short) {
this.data.format_short = format_short;
} else if (!this.data.format_short) {
this.data.format_short = this.findBestFormat(true);
}
}
});
// offer something that can figure out the right date class to return
TL.Date.makeDate = function(data) {
var date = new TL.Date(data);
if (!isNaN(date.getTime())) {
return date;
}
return new TL.BigDate(data);
}
TL.BigYear = TL.Class.extend({
initialize: function (year) {
this.year = parseInt(year);
if (isNaN(this.year)) { throw("Invalid year " + year) }
},
/* THERE ARE UNUSED ...
getDisplayText: function(tl_language) {
return this.year.toLocaleString(tl_language.lang);
},
getDisplayTextShort: function(tl_language) {
return this.year.toLocaleString(tl_language.lang);
},
*/
isBefore: function(that) {
return this.year < that.year;
},
isAfter: function(that) {
return this.year > that.year;
},
getTime: function() {
return this.year;
}
});
(function(cls){
// human scales
cls.SCALES = [ // ( name, units_per_tick, flooring function )
['millisecond',1, function(d) { }],
['second',1000, function(d) { d.setMilliseconds(0);}],
['minute',1000 * 60, function(d) { d.setSeconds(0);}],
['hour',1000 * 60 * 60, function(d) { d.setMinutes(0);}],
['day',1000 * 60 * 60 * 24, function(d) { d.setHours(0);}],
['month',1000 * 60 * 60 * 24 * 30, function(d) { d.setDate(1);}],
['year',1000 * 60 * 60 * 24 * 365, function(d) { d.setMonth(0);}],
['decade',1000 * 60 * 60 * 24 * 365 * 10, function(d) {
var real_year = d.getFullYear();
d.setFullYear( real_year - (real_year % 10))
}],
['century',1000 * 60 * 60 * 24 * 365 * 100, function(d) {
var real_year = d.getFullYear();
d.setFullYear( real_year - (real_year % 100))
}],
['millennium',1000 * 60 * 60 * 24 * 365 * 1000, function(d) {
var real_year = d.getFullYear();
d.setFullYear( real_year - (real_year % 1000))
}]
];
// Date parts from highest to lowest precision
cls.DATE_PARTS = ["millisecond", "second", "minute", "hour", "day", "month", "year"];
var ISO8601_SHORT_PATTERN = /^([\+-]?\d+?)(-\d{2}?)?(-\d{2}?)?$/;
// regex below from
// http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/
var ISO8601_PATTERN = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
/* For now, rather than extract parts from regexp, let's trust the browser.
* Famous last words...
* What about UTC vs local time?
* see also http://stackoverflow.com/questions/10005374/ecmascript-5-date-parse-results-for-iso-8601-test-cases
*/
cls.parseISODate = function(str) {
var d = new Date(str);
if (isNaN(d)) throw "Invalid date: " + str;
return {
year: d.getFullYear(),
month: d.getMonth() + 1,
day: d.getDate(),
hour: d.getHours(),
minute: d.getMinutes(),
second: d.getSeconds(),
millisecond: d.getMilliseconds()
}
}
cls.parseDate = function(str) {
if (str.match(ISO8601_SHORT_PATTERN)) {
// parse short specifically to avoid timezone offset confusion
// most browsers assume short is UTC, not local time.
var parts = str.match(ISO8601_SHORT_PATTERN).slice(1);
var d = { year: parts[0].replace('+','')} // year can be negative
if (parts[1]) { d['month'] = parts[1].replace('-',''); }
if (parts[2]) { d['day'] = parts[2].replace('-',''); }
return d;
}
if (str.match(ISO8601_PATTERN)) {
return cls.parseISODate(str);
}
if (str.match(/^\-?\d+$/)) {
return { year: str }
}
var parsed = {}
if (str.match(/\d+\/\d+\/\d+/)) { // mm/yy/dddd
var date = str.match(/\d+\/\d+\/\d+/)[0];
str = TL.Util.trim(str.replace(date,''));
var date_parts = date.split('/');
parsed.month = date_parts[0];
parsed.day = date_parts[1];
parsed.year = date_parts[2];
}
if (str.match(/\d+\/\d+/)) { // mm/yy
var date = str.match(/\d+\/\d+/)[0];
str = TL.Util.trim(str.replace(date,''));
var date_parts = date.split('/');
parsed.month = date_parts[0];
parsed.year = date_parts[1];
}
// todo: handle hours, minutes, seconds, millis other date formats, etc...
if (str.match(':')) {
var time_parts = str.split(':');
parsed.hour = time_parts[0];
parsed.minute = time_parts[1];
if (time_parts[2]) {
second_parts = time_parts[2].split('.');
parsed.second = second_parts[0];
parsed.millisecond = second_parts[1];
}
}
return parsed;
}
cls.BEST_DATEFORMATS = {
base: {
millisecond: 'time_short',
second: 'time',
minute: 'time_no_seconds_small_date',
hour: 'time_no_seconds_small_date',
day: 'full',
month: 'month',
year: 'year',
decade: 'year',
century: 'year',
millennium: 'year',
age: 'fallback',
epoch: 'fallback',
era: 'fallback',
eon: 'fallback',
eon2: 'fallback'
},
short: {
millisecond: 'time_short',
second: 'time_short',
minute: 'time_no_seconds_short',
hour: 'time_no_minutes_short',
day: 'full_short',
month: 'month_short',
year: 'year',
decade: 'year',
century: 'year',
millennium: 'year',
age: 'fallback',
epoch: 'fallback',
era: 'fallback',
eon: 'fallback',
eon2: 'fallback'
}
}
})(TL.Date)
//
// Class for cosmological dates
//
TL.BigDate = TL.Date.extend({
// @data = TL.BigYear object or JS dictionary with date properties
initialize: function(data, format, format_short) {
if (TL.BigYear == data.constructor) {
this.data = {
date_obj: data
}
} else {
this.data = JSON.parse(JSON.stringify(data));
this._createDateObj();
}
this._setFormat(format, format_short);
},
// Create date_obj
_createDateObj: function() {
var _date = this._getDateData();
this.data.date_obj = new TL.BigYear(_date.year);
},
// Return a new TL.BigDate which has been 'floored' at the given scale.
// @scale = string value from TL.BigDate.SCALES
floor: function(scale) {
for (var i = 0; i < TL.BigDate.SCALES.length; i++) {
if (TL.BigDate.SCALES[i][0] == scale) {
var floored = TL.BigDate.SCALES[i][2](this.data.date_obj);
return new TL.BigDate(floored);
}
};
throw('invalid scale ' + scale);
}
});
(function(cls){
// cosmo units are years, not millis
var AGE = 1000000;
var EPOCH = AGE * 10;
var ERA = EPOCH * 10;
var EON = ERA * 10;
var Floorer = function(unit) {
return function(a_big_year) {
var year = a_big_year.getTime();
return new TL.BigYear(Math.floor(year/unit) * unit);
}
}
// cosmological scales
cls.SCALES = [ // ( name, units_per_tick, flooring function )
['age',AGE, new Floorer(AGE)], // 1M years
['epoch',EPOCH, new Floorer(EPOCH)], // 10M years
['era',ERA, new Floorer(ERA)], // 100M years
['eon',EON, new Floorer(EON)] // 1B years
];
})(TL.BigDate)
/* **********************************************
Begin TL.DateUtil.js
********************************************** */
/* TL.DateUtil
Utilities for parsing time
================================================== */
TL.DateUtil = {
get: function (id) {
return (typeof id === 'string' ? document.getElementById(id) : id);
},
sortByDate: function(array,prop_name) { // only for use with slide data objects
var prop_name = prop_name || 'start_date';
array.sort(function(a,b){
if (a[prop_name].isBefore(b[prop_name])) return -1;
if (a[prop_name].isAfter(b[prop_name])) return 1;
return 0;
});
},
parseTime: function(time_str) {
var parsed = {
hour: null, minute: null, second: null, millisecond: null // conform to keys in TL.Date
}
var period = null;
var match = time_str.match(/(\s*[AaPp]\.?[Mm]\.?\s*)$/);
if (match) {
period = TL.Util.trim(match[0]);
time_str = TL.Util.trim(time_str.substring(0,time_str.lastIndexOf(period)));
}
var parts = [];
var no_separators = time_str.match(/^\s*(\d{1,2})(\d{2})\s*$/);
if (no_separators) {
parts = no_separators.slice(1);
} else {
parts = time_str.split(':');
if (parts.length == 1) {
parts = time_str.split('.');
}
}
if (parts.length > 4) { throw new Error("Invalid time: misuse of : or . as separator.");}
parsed.hour = parseInt(parts[0]);
if (period && period.toLowerCase()[0] == 'p' && parsed.hour != 12) {
parsed.hour += 12;
} else if (period && period.toLowerCase()[0] == 'a' && parsed.hour == 12) {
parsed.hour = 0;
}
if (isNaN(parsed.hour) || parsed.hour < 0 || parsed.hour > 23) {
throw new Error("Invalid time (hour) " + parsed.hour);
}
if (parts.length > 1) {
parsed.minute = parseInt(parts[1]);
if (isNaN(parsed.minute)) { throw new Error("Invalid time (minute)"); }
}
if (parts.length > 2) {
var sec_parts = parts[2].split(/[\.,]/);
parts = sec_parts.concat(parts.slice(3)) // deal with various methods of specifying fractional seconds
if (parts.length > 2) { throw new Error("Invalid time (seconds and fractional seconds)")}
parsed.second = parseInt(parts[0]);
if (isNaN(parsed.second)) { throw new Error("Invalid time (second)")}
if (parts.length == 2) {
var frac_secs = parseInt(parts[1]);
if (isNaN(frac_secs)) { throw new Error("Invalid time (fractional seconds)")}
parsed.millisecond = 100 * frac_secs;
}
}
return parsed;
},
SCALE_DATE_CLASSES: {
human: TL.Date,
cosmological: TL.BigDate
}
};
/* **********************************************
Begin TL.Draggable.js
********************************************** */
/* TL.Draggable
TL.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
TODO Enable constraints
================================================== */
TL.Draggable = TL.Class.extend({
includes: TL.Events,
_el: {},
mousedrag: {
down: "mousedown",
up: "mouseup",
leave: "mouseleave",
move: "mousemove"
},
touchdrag: {
down: "touchstart",
up: "touchend",
leave: "mouseleave",
move: "touchmove"
},
initialize: function (drag_elem, options, move_elem) {
// DOM ELements
this._el = {
drag: drag_elem,
move: drag_elem
};
if (move_elem) {
this._el.move = move_elem;
}
//Options
this.options = {
enable: {
x: true,
y: true
},
constraint: {
top: false,
bottom: false,
left: false,
right: false
},
momentum_multiplier: 2000,
duration: 1000,
ease: TL.Ease.easeInOutQuint
};
// Animation Object
this.animator = null;
// Drag Event Type
this.dragevent = this.mousedrag;
if (TL.Browser.touch) {
this.dragevent = this.touchdrag;
}
// Draggable Data
this.data = {
sliding: false,
direction: "none",
pagex: {
start: 0,
end: 0
},
pagey: {
start: 0,
end: 0
},
pos: {
start: {
x: 0,
y:0
},
end: {
x: 0,
y:0
}
},
new_pos: {
x: 0,
y: 0
},
new_pos_parent: {
x: 0,
y: 0
},
time: {
start: 0,
end: 0
},
touch: false
};
// Merge Data and Options
TL.Util.mergeData(this.options, options);
},
enable: function(e) {
this.data.pos.start = 0;
this._el.move.style.left = this.data.pos.start.x + "px";
this._el.move.style.top = this.data.pos.start.y + "px";
this._el.move.style.position = "absolute";
},
disable: function() {
TL.DomEvent.removeListener(this._el.drag, this.dragevent.down, this._onDragStart, this);
TL.DomEvent.removeListener(this._el.drag, this.dragevent.up, this._onDragEnd, this);
},
stopMomentum: function() {
if (this.animator) {
this.animator.stop();
}
},
updateConstraint: function(c) {
this.options.constraint = c;
},
/* Private Methods
================================================== */
_onDragStart: function(e) {
if (TL.Browser.touch) {
if (e.originalEvent) {
this.data.pagex.start = e.originalEvent.touches[0].screenX;
this.data.pagey.start = e.originalEvent.touches[0].screenY;
} else {
this.data.pagex.start = e.targetTouches[0].screenX;
this.data.pagey.start = e.targetTouches[0].screenY;
}
} else {
this.data.pagex.start = e.pageX;
this.data.pagey.start = e.pageY;
}
// Center element to finger or mouse
if (this.options.enable.x) {
this._el.move.style.left = this.data.pagex.start - (this._el.move.offsetWidth / 2) + "px";
}
if (this.options.enable.y) {
this._el.move.style.top = this.data.pagey.start - (this._el.move.offsetHeight / 2) + "px";
}
this.data.pos.start = TL.Dom.getPosition(this._el.drag);
this.data.time.start = new Date().getTime();
this.fire("dragstart", this.data);
TL.DomEvent.addListener(this._el.drag, this.dragevent.move, this._onDragMove, this);
TL.DomEvent.addListener(this._el.drag, this.dragevent.leave, this._onDragEnd, this);
},
_onDragEnd: function(e) {
this.data.sliding = false;
TL.DomEvent.removeListener(this._el.drag, this.dragevent.move, this._onDragMove, this);
TL.DomEvent.removeListener(this._el.drag, this.dragevent.leave, this._onDragEnd, this);
this.fire("dragend", this.data);
// momentum
this._momentum();
},
_onDragMove: function(e) {
e.preventDefault();
this.data.sliding = true;
if (TL.Browser.touch) {
if (e.originalEvent) {
this.data.pagex.end = e.originalEvent.touches[0].screenX;
this.data.pagey.end = e.originalEvent.touches[0].screenY;
} else {
this.data.pagex.end = e.targetTouches[0].screenX;
this.data.pagey.end = e.targetTouches[0].screenY;
}
} else {
this.data.pagex.end = e.pageX;
this.data.pagey.end = e.pageY;
}
this.data.pos.end = TL.Dom.getPosition(this._el.drag);
this.data.new_pos.x = -(this.data.pagex.start - this.data.pagex.end - this.data.pos.start.x);
this.data.new_pos.y = -(this.data.pagey.start - this.data.pagey.end - this.data.pos.start.y );
if (this.options.enable.x) {
this._el.move.style.left = this.data.new_pos.x + "px";
}
if (this.options.enable.y) {
this._el.move.style.top = this.data.new_pos.y + "px";
}
this.fire("dragmove", this.data);
},
_momentum: function() {
var pos_adjust = {
x: 0,
y: 0,
time: 0
},
pos_change = {
x: 0,
y: 0,
time: 0
},
swipe = false,
swipe_direction = "";
if (TL.Browser.touch) {
// Treat mobile multiplier differently
//this.options.momentum_multiplier = this.options.momentum_multiplier * 2;
}
pos_adjust.time = (new Date().getTime() - this.data.time.start) * 10;
pos_change.time = (new Date().getTime() - this.data.time.start) * 10;
pos_change.x = this.options.momentum_multiplier * (Math.abs(this.data.pagex.end) - Math.abs(this.data.pagex.start));
pos_change.y = this.options.momentum_multiplier * (Math.abs(this.data.pagey.end) - Math.abs(this.data.pagey.start));
pos_adjust.x = Math.round(pos_change.x / pos_change.time);
pos_adjust.y = Math.round(pos_change.y / pos_change.time);
this.data.new_pos.x = Math.min(this.data.pos.end.x + pos_adjust.x);
this.data.new_pos.y = Math.min(this.data.pos.end.y + pos_adjust.y);
if (!this.options.enable.x) {
this.data.new_pos.x = this.data.pos.start.x;
} else if (this.data.new_pos.x < 0) {
this.data.new_pos.x = 0;
}
if (!this.options.enable.y) {
this.data.new_pos.y = this.data.pos.start.y;
} else if (this.data.new_pos.y < 0) {
this.data.new_pos.y = 0;
}
// Detect Swipe
if (pos_change.time < 3000) {
swipe = true;
}
// Detect Direction
if (Math.abs(pos_change.x) > 10000) {
this.data.direction = "left";
if (pos_change.x > 0) {
this.data.direction = "right";
}
}
// Detect Swipe
if (Math.abs(pos_change.y) > 10000) {
this.data.direction = "up";
if (pos_change.y > 0) {
this.data.direction = "down";
}
}
this._animateMomentum();
if (swipe) {
this.fire("swipe_" + this.data.direction, this.data);
}
},
_animateMomentum: function() {
var pos = {
x: this.data.new_pos.x,
y: this.data.new_pos.y
},
animate = {
duration: this.options.duration,
easing: TL.Ease.easeOutStrong
};
if (this.options.enable.y) {
if (this.options.constraint.top || this.options.constraint.bottom) {
if (pos.y > this.options.constraint.bottom) {
pos.y = this.options.constraint.bottom;
} else if (pos.y < this.options.constraint.top) {
pos.y = this.options.constraint.top;
}
}
animate.top = Math.floor(pos.y) + "px";
}
if (this.options.enable.x) {
if (this.options.constraint.left || this.options.constraint.right) {
if (pos.x > this.options.constraint.left) {
pos.x = this.options.constraint.left;
} else if (pos.x < this.options.constraint.right) {
pos.x = this.options.constraint.right;
}
}
animate.left = Math.floor(pos.x) + "px";
}
this.animator = TL.Animate(this._el.move, animate);
this.fire("momentum", this.data);
}
});
/* **********************************************
Begin TL.Swipable.js
********************************************** */
/* TL.Swipable
TL.Draggable allows you to add dragging capabilities to any element. Supports mobile devices too.
TODO Enable constraints
================================================== */
TL.Swipable = TL.Class.extend({
includes: TL.Events,
_el: {},
mousedrag: {
down: "mousedown",
up: "mouseup",
leave: "mouseleave",
move: "mousemove"
},
touchdrag: {
down: "touchstart",
up: "touchend",
leave: "mouseleave",
move: "touchmove"
},
initialize: function (drag_elem, move_elem, options) {
// DOM ELements
this._el = {
drag: drag_elem,
move: drag_elem
};
if (move_elem) {
this._el.move = move_elem;
}
//Options
this.options = {
snap: false,
enable: {
x: true,
y: true
},
constraint: {
top: false,
bottom: false,
left: 0,
right: false
},
momentum_multiplier: 2000,
duration: 1000,
ease: TL.Ease.easeInOutQuint
};
// Animation Object
this.animator = null;
// Drag Event Type
this.dragevent = this.mousedrag;
if (TL.Browser.touch) {
this.dragevent = this.touchdrag;
}
// Draggable Data
this.data = {
sliding: false,
direction: "none",
pagex: {
start: 0,
end: 0
},
pagey: {
start: 0,
end: 0
},
pos: {
start: {
x: 0,
y:0
},
end: {
x: 0,
y:0
}
},
new_pos: {
x: 0,
y: 0
},
new_pos_parent: {
x: 0,
y: 0
},
time: {
start: 0,
end: 0
},
touch: false
};
// Merge Data and Options
TL.Util.mergeData(this.options, options);
},
enable: function(e) {
TL.DomEvent.addListener(this._el.drag, this.dragevent.down, this._onDragStart, this);
TL.DomEvent.addListener(this._el.drag, this.dragevent.up, this._onDragEnd, this);
this.data.pos.start = 0; //TL.Dom.getPosition(this._el.move);
this._el.move.style.left = this.data.pos.start.x + "px";
this._el.move.style.top = this.data.pos.start.y + "px";
this._el.move.style.position = "absolute";
//this._el.move.style.zIndex = "11";
//this._el.move.style.cursor = "move";
},
disable: function() {
TL.DomEvent.removeListener(this._el.drag, this.dragevent.down, this._onDragStart, this);
TL.DomEvent.removeListener(this._el.drag, this.dragevent.up, this._onDragEnd, this);
},
stopMomentum: function() {
if (this.animator) {
this.animator.stop();
}
},
updateConstraint: function(c) {
this.options.constraint = c;
// Temporary until issues are fixed
},
/* Private Methods
================================================== */
_onDragStart: function(e) {
if (this.animator) {
this.animator.stop();
}
if (TL.Browser.touch) {
if (e.originalEvent) {
this.data.pagex.start = e.originalEvent.touches[0].screenX;
this.data.pagey.start = e.originalEvent.touches[0].screenY;
} else {
this.data.pagex.start = e.targetTouches[0].screenX;
this.data.pagey.start = e.targetTouches[0].screenY;
}
} else {
this.data.pagex.start = e.pageX;
this.data.pagey.start = e.pageY;
}
// Center element to finger or mouse
if (this.options.enable.x) {
//this._el.move.style.left = this.data.pagex.start - (this._el.move.offsetWidth / 2) + "px";
}
if (this.options.enable.y) {
//this._el.move.style.top = this.data.pagey.start - (this._el.move.offsetHeight / 2) + "px";
}
this.data.pos.start = {x:this._el.move.offsetLeft, y:this._el.move.offsetTop};
this.data.time.start = new Date().getTime();
this.fire("dragstart", this.data);
TL.DomEvent.addListener(this._el.drag, this.dragevent.move, this._onDragMove, this);
TL.DomEvent.addListener(this._el.drag, this.dragevent.leave, this._onDragEnd, this);
},
_onDragEnd: function(e) {
this.data.sliding = false;
TL.DomEvent.removeListener(this._el.drag, this.dragevent.move, this._onDragMove, this);
TL.DomEvent.removeListener(this._el.drag, this.dragevent.leave, this._onDragEnd, this);
this.fire("dragend", this.data);
// momentum
this._momentum();
},
_onDragMove: function(e) {
var change = {
x:0,
y:0
}
//e.preventDefault();
this.data.sliding = true;
if (TL.Browser.touch) {
if (e.originalEvent) {
this.data.pagex.end = e.originalEvent.touches[0].screenX;
this.data.pagey.end = e.originalEvent.touches[0].screenY;
} else {
this.data.pagex.end = e.targetTouches[0].screenX;
this.data.pagey.end = e.targetTouches[0].screenY;
}
} else {
this.data.pagex.end = e.pageX;
this.data.pagey.end = e.pageY;
}
change.x = this.data.pagex.start - this.data.pagex.end;
change.y = this.data.pagey.start - this.data.pagey.end;
this.data.pos.end = {x:this._el.drag.offsetLeft, y:this._el.drag.offsetTop};
this.data.new_pos.x = -(change.x - this.data.pos.start.x);
this.data.new_pos.y = -(change.y - this.data.pos.start.y );
if (this.options.enable.x && ( Math.abs(change.x) > Math.abs(change.y) ) ) {
e.preventDefault();
this._el.move.style.left = this.data.new_pos.x + "px";
}
if (this.options.enable.y && ( Math.abs(change.y) > Math.abs(change.y) ) ) {
e.preventDefault();
this._el.move.style.top = this.data.new_pos.y + "px";
}
this.fire("dragmove", this.data);
},
_momentum: function() {
var pos_adjust = {
x: 0,
y: 0,
time: 0
},
pos_change = {
x: 0,
y: 0,
time: 0
},
swipe_detect = {
x: false,
y: false
},
swipe = false,
swipe_direction = "";
this.data.direction = null;
pos_adjust.time = (new Date().getTime() - this.data.time.start) * 10;
pos_change.time = (new Date().getTime() - this.data.time.start) * 10;
pos_change.x = this.options.momentum_multiplier * (Math.abs(this.data.pagex.end) - Math.abs(this.data.pagex.start));
pos_change.y = this.options.momentum_multiplier * (Math.abs(this.data.pagey.end) - Math.abs(this.data.pagey.start));
pos_adjust.x = Math.round(pos_change.x / pos_change.time);
pos_adjust.y = Math.round(pos_change.y / pos_change.time);
this.data.new_pos.x = Math.min(this.data.new_pos.x + pos_adjust.x);
this.data.new_pos.y = Math.min(this.data.new_pos.y + pos_adjust.y);
if (!this.options.enable.x) {
this.data.new_pos.x = this.data.pos.start.x;
} else if (this.options.constraint.left && this.data.new_pos.x > this.options.constraint.left) {
this.data.new_pos.x = this.options.constraint.left;
}
if (!this.options.enable.y) {
this.data.new_pos.y = this.data.pos.start.y;
} else if (this.data.new_pos.y < 0) {
this.data.new_pos.y = 0;
}
// Detect Swipe
if (pos_change.time < 2000) {
swipe = true;
}
if (this.options.enable.x && this.options.enable.y) {
if (Math.abs(pos_change.x) > Math.abs(pos_change.y)) {
swipe_detect.x = true;
} else {
swipe_detect.y = true;
}
} else if (this.options.enable.x) {
if (Math.abs(pos_change.x) > Math.abs(pos_change.y)) {
swipe_detect.x = true;
}
} else {
if (Math.abs(pos_change.y) > Math.abs(pos_change.x)) {
swipe_detect.y = true;
}
}
// Detect Direction and long swipe
if (swipe_detect.x) {
// Long Swipe
if (Math.abs(pos_change.x) > (this._el.drag.offsetWidth/2)) {
swipe = true;
}
if (Math.abs(pos_change.x) > 10000) {
this.data.direction = "left";
if (pos_change.x > 0) {
this.data.direction = "right";
}
}
}
if (swipe_detect.y) {
// Long Swipe
if (Math.abs(pos_change.y) > (this._el.drag.offsetHeight/2)) {
swipe = true;
}
if (Math.abs(pos_change.y) > 10000) {
this.data.direction = "up";
if (pos_change.y > 0) {
this.data.direction = "down";
}
}
}
if (pos_change.time < 1000 ) {
} else {
this._animateMomentum();
}
if (swipe && this.data.direction) {
this.fire("swipe_" + this.data.direction, this.data);
} else if (this.data.direction) {
this.fire("swipe_nodirection", this.data);
} else if (this.options.snap) {
this.animator.stop();
this.animator = TL.Animate(this._el.move, {
top: this.data.pos.start.y,
left: this.data.pos.start.x,
duration: this.options.duration,
easing: TL.Ease.easeOutStrong
});
}
},
_animateMomentum: function() {
var pos = {
x: this.data.new_pos.x,
y: this.data.new_pos.y
},
animate = {
duration: this.options.duration,
easing: TL.Ease.easeOutStrong
};
if (this.options.enable.y) {
if (this.options.constraint.top || this.options.constraint.bottom) {
if (pos.y > this.options.constraint.bottom) {
pos.y = this.options.constraint.bottom;
} else if (pos.y < this.options.constraint.top) {
pos.y = this.options.constraint.top;
}
}
animate.top = Math.floor(pos.y) + "px";
}
if (this.options.enable.x) {
if (this.options.constraint.left && pos.x >= this.options.constraint.left) {
pos.x = this.options.constraint.left;
}
if (this.options.constraint.right && pos.x < this.options.constraint.right) {
pos.x = this.options.constraint.right;
}
animate.left = Math.floor(pos.x) + "px";
}
this.animator = TL.Animate(this._el.move, animate);
this.fire("momentum", this.data);
}
});
/* **********************************************
Begin TL.MenuBar.js
********************************************** */
/* TL.MenuBar
Draggable component to control size
================================================== */
TL.MenuBar = TL.Class.extend({
includes: [TL.Events, TL.DomMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(elem, parent_elem, options) {
// DOM ELEMENTS
this._el = {
parent: {},
container: {},
button_backtostart: {},
button_zoomin: {},
button_zoomout: {},
arrow: {},
line: {},
coverbar: {},
grip: {}
};
this.collapsed = false;
if (typeof elem === 'object') {
this._el.container = elem;
} else {
this._el.container = TL.Dom.get(elem);
}
if (parent_elem) {
this._el.parent = parent_elem;
}
//Options
this.options = {
width: 600,
height: 600,
duration: 1000,
ease: TL.Ease.easeInOutQuint,
menubar_default_y: 0
};
// Animation
this.animator = {};
// Merge Data and Options
TL.Util.mergeData(this.options, options);
this._initLayout();
this._initEvents();
},
/* Public
================================================== */
show: function(d) {
var duration = this.options.duration;
if (d) {
duration = d;
}
/*
this.animator = TL.Animate(this._el.container, {
top: this.options.menubar_default_y + "px",
duration: duration,
easing: TL.Ease.easeOutStrong
});
*/
},
hide: function(top) {
/*
this.animator = TL.Animate(this._el.container, {
top: top,
duration: this.options.duration,
easing: TL.Ease.easeOutStrong
});
*/
},
toogleZoomIn: function(show) {
if (show) {
this._el.button_zoomin.className = "tl-menubar-button";
this._el.button_zoomout.className = "tl-menubar-button";
} else {
this._el.button_zoomin.className = "tl-menubar-button tl-menubar-button-inactive";
this._el.button_zoomout.className = "tl-menubar-button";
}
},
toogleZoomOut: function(show) {
if (show) {
this._el.button_zoomout.className = "tl-menubar-button";
this._el.button_zoomin.className = "tl-menubar-button";
} else {
this._el.button_zoomout.className = "tl-menubar-button tl-menubar-button-inactive";
this._el.button_zoomin.className = "tl-menubar-button";
}
},
setSticky: function(y) {
this.options.menubar_default_y = y;
},
/* Color
================================================== */
setColor: function(inverted) {
if (inverted) {
this._el.container.className = 'tl-menubar tl-menubar-inverted';
} else {
this._el.container.className = 'tl-menubar';
}
},
/* Update Display
================================================== */
updateDisplay: function(w, h, a, l) {
this._updateDisplay(w, h, a, l);
},
/* Events
================================================== */
_onButtonZoomIn: function(e) {
this.fire("zoom_in", e);
},
_onButtonZoomOut: function(e) {
this.fire("zoom_out", e);
},
_onButtonBackToStart: function(e) {
this.fire("back_to_start", e);
},
/* Private Methods
================================================== */
_initLayout: function () {
// Create Layout
this._el.button_zoomin = TL.Dom.create('span', 'tl-menubar-button', this._el.container);
this._el.button_zoomout = TL.Dom.create('span', 'tl-menubar-button', this._el.container);
this._el.button_backtostart = TL.Dom.create('span', 'tl-menubar-button', this._el.container);
if (TL.Browser.mobile) {
this._el.container.setAttribute("ontouchstart"," ");
}
this._el.button_backtostart.innerHTML = "<span class='tl-icon-goback'></span>";
this._el.button_zoomin.innerHTML = "<span class='tl-icon-zoom-in'></span>";
this._el.button_zoomout.innerHTML = "<span class='tl-icon-zoom-out'></span>";
},
_initEvents: function () {
TL.DomEvent.addListener(this._el.button_backtostart, 'click', this._onButtonBackToStart, this);
TL.DomEvent.addListener(this._el.button_zoomin, 'click', this._onButtonZoomIn, this);
TL.DomEvent.addListener(this._el.button_zoomout, 'click', this._onButtonZoomOut, this);
},
// Update Display
_updateDisplay: function(width, height, animate) {
if (width) {
this.options.width = width;
}
if (height) {
this.options.height = height;
}
}
});
/* **********************************************
Begin TL.Message.js
********************************************** */
/* TL.Message
================================================== */
TL.Message = TL.Class.extend({
includes: [TL.Events, TL.DomMixins, TL.I18NMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(data, options, add_to_container) {
// DOM ELEMENTS
this._el = {
parent: {},
container: {},
message_container: {},
loading_icon: {},
message: {}
};
//Options
this.options = {
width: 600,
height: 600,
message_class: "tl-message",
message_icon_class: "tl-loading-icon"
};
// Merge Data and Options
TL.Util.mergeData(this.data, data);
TL.Util.mergeData(this.options, options);
this._el.container = TL.Dom.create("div", this.options.message_class);
if (add_to_container) {
add_to_container.appendChild(this._el.container);
this._el.parent = add_to_container;
};
// Animation
this.animator = {};
this._initLayout();
this._initEvents();
},
/* Public
================================================== */
updateMessage: function(t) {
this._updateMessage(t);
},
/* Update Display
================================================== */
updateDisplay: function(w, h) {
this._updateDisplay(w, h);
},
_updateMessage: function(t) {
if (!t) {
this._el.message.innerHTML = this._('loading');
} else {
this._el.message.innerHTML = t;
}
},
/* Events
================================================== */
_onMouseClick: function() {
this.fire("clicked", this.options);
},
/* Private Methods
================================================== */
_initLayout: function () {
// Create Layout
this._el.message_container = TL.Dom.create("div", "tl-message-container", this._el.container);
this._el.loading_icon = TL.Dom.create("div", this.options.message_icon_class, this._el.message_container);
this._el.message = TL.Dom.create("div", "tl-message-content", this._el.message_container);
this._updateMessage();
},
_initEvents: function () {
TL.DomEvent.addListener(this._el.container, 'click', this._onMouseClick, this);
},
// Update Display
_updateDisplay: function(width, height, animate) {
}
});
/* **********************************************
Begin TL.MediaType.js
********************************************** */
/* TL.MediaType
Determines the type of media the url string is.
returns an object with .type and .id
You can add new media types by adding a regex
to match and the media class name to use to
render the media
TODO
Allow array so a slideshow can be a mediatype
================================================== */
TL.MediaType = function(m) {
var media = {},
media_types = [
{
type: "youtube",
name: "YouTube",
match_str: "^(https?:)?\/*(www.)?youtube|youtu\.be",
cls: TL.Media.YouTube
},
{
type: "vimeo",
name: "Vimeo",
match_str: "^(https?:)?\/*(player.)?vimeo\.com",
cls: TL.Media.Vimeo
},
{
type: "dailymotion",
name: "DailyMotion",
match_str: "^(https?:)?\/*(www.)?dailymotion\.com",
cls: TL.Media.DailyMotion
},
{
type: "vine",
name: "Vine",
match_str: "^(https?:)?\/*(www.)?vine\.co",
cls: TL.Media.Vine
},
{
type: "soundcloud",
name: "SoundCloud",
match_str: "^(https?:)?\/*(player.)?soundcloud\.com",
cls: TL.Media.SoundCloud
},
{
type: "twitter",
name: "Twitter",
match_str: "^(https?:)?\/*(www.)?twitter\.com",
cls: TL.Media.Twitter
},
{
type: "twitterembed",
name: "TwitterEmbed",
match_str: "<blockquote class=\"twitter-tweet\"",
cls: TL.Media.TwitterEmbed
},
{
type: "googlemaps",
name: "Google Map",
match_str: /google.+?\/maps\/@([-\d.]+),([-\d.]+),((?:[-\d.]+[zmayht],?)*)|google.+?\/maps\/search\/([\w\W]+)\/@([-\d.]+),([-\d.]+),((?:[-\d.]+[zmayht],?)*)|google.+?\/maps\/place\/([\w\W]+)\/@([-\d.]+),([-\d.]+),((?:[-\d.]+[zmayht],?)*)|google.+?\/maps\/dir\/([\w\W]+)\/([\w\W]+)\/@([-\d.]+),([-\d.]+),((?:[-\d.]+[zmayht],?)*)/,
cls: TL.Media.GoogleMap
},
{
type: "googleplus",
name: "Google+",
match_str: "^(https?:)?\/*plus.google",
cls: TL.Media.GooglePlus
},
{
type: "flickr",
name: "Flickr",
match_str: "^(https?:)?\/*(www.)?flickr.com\/photos",
cls: TL.Media.Flickr
},
{
type: "instagram",
name: "Instagram",
match_str: /^(https?:)?\/*(www.)?(instagr.am|^(https?:)?\/*(www.)?instagram.com)\/p\//,
cls: TL.Media.Instagram
},
{
type: "profile",
name: "Profile",
match_str: /^(https?:)?\/*(www.)?instagr.am\/[a-zA-Z0-9]{2,}|^(https?:)?\/*(www.)?instagram.com\/[a-zA-Z0-9]{2,}/,
cls: TL.Media.Profile
},
{
type: "documentcloud",
name: "Document Cloud",
match_str: /documentcloud.org\//,
cls: TL.Media.DocumentCloud
},
{
type: "image",
name: "Image",
match_str: /(jpg|jpeg|png|gif)(\?.*)?$/i,
cls: TL.Media.Image
},
{
type: "googledocs",
name: "Google Doc",
match_str: "^(https?:)?\/*[^.]*.google.com\/[^\/]*\/d\/[^\/]*\/[^\/]*\?usp=sharing|^(https?:)?\/*drive.google.com\/open\?id=[^\&]*\&authuser=0|^(https?:)?\/*drive.google.com\/open\?id=[^\&]*|^(https?:)?\/*[^.]*.googledrive.com\/host\/[^\/]*\/",
cls: TL.Media.GoogleDoc
},
{
type: "wikipedia",
name: "Wikipedia",
match_str: "^(https?:)?\/*(www.)?wikipedia\.org|^(https?:)?\/*([a-z][a-z].)?wikipedia\.org",
cls: TL.Media.Wikipedia
},
{
type: "spotify",
name: "spotify",
match_str: "spotify",
cls: TL.Media.Spotify
},
{
type: "iframe",
name: "iFrame",
match_str: "iframe",
cls: TL.Media.IFrame
},
{
type: "storify",
name: "Storify",
match_str: "storify",
cls: TL.Media.Storify
},
{
type: "blockquote",
name: "Quote",
match_str: "blockquote",
cls: TL.Media.Blockquote
},
// {
// type: "website",
// name: "Website",
// match_str: "https?://",
// cls: TL.Media.Website
// },
{
type: "imageblank",
name: "Imageblank",
match_str: "",
cls: TL.Media.Image
}
];
for (var i = 0; i < media_types.length; i++) {
if (m instanceof Array) {
return media = {
type: "slider",
cls: TL.Media.Slider
};
} else if (m.url.match(media_types[i].match_str)) {
media = media_types[i];
return media;
}
};
return false;
}
/* **********************************************
Begin TL.Media.js
********************************************** */
/* TL.Media
Main media template for media assets.
Takes a data object and populates a dom object
================================================== */
// TODO add link
TL.Media = TL.Class.extend({
includes: [TL.Events, TL.I18NMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(data, options, add_to_container) {
// DOM ELEMENTS
this._el = {
container: {},
content_container: {},
content: {},
content_item: {},
content_link: {},
caption: null,
credit: null,
parent: {},
link: null
};
// Player (If Needed)
this.player = null;
// Timer (If Needed)
this.timer = null;
this.load_timer = null;
// Message
this.message = null;
// Media ID
this.media_id = null;
// State
this._state = {
loaded: false,
show_meta: false,
media_loaded: false
};
// Data
this.data = {
unique_id: null,
url: null,
credit: null,
caption: null,
credit_alternate: null,
caption_alternate: null,
link: null,
link_target: null
};
//Options
this.options = {
api_key_flickr: "f2cc870b4d233dd0a5bfe73fd0d64ef0",
api_key_googlemaps: "AIzaSyB9dW8e_iRrATFa8g24qB6BDBGdkrLDZYI",
api_key_embedly: "", // ae2da610d1454b66abdf2e6a4c44026d
credit_height: 0,
caption_height: 0
};
this.animator = {};
// Merge Data and Options
TL.Util.mergeData(this.options, options);
TL.Util.mergeData(this.data, data);
this._el.container = TL.Dom.create("div", "tl-media");
if (this.data.unique_id) {
this._el.container.id = this.data.unique_id;
}
this._initLayout();
if (add_to_container) {
add_to_container.appendChild(this._el.container);
this._el.parent = add_to_container;
};
},
loadMedia: function() {
var self = this;
if (!this._state.loaded) {
try {
this.load_timer = setTimeout(function() {
self._loadMedia();
self._state.loaded = true;
self._updateDisplay();
}, 1200);
} catch (e) {
trace("Error loading media for ", this._media);
trace(e);
}
//this._state.loaded = true;
}
},
loadingMessage: function() {
this.message.updateMessage(this._('loading') + " " + this.options.media_name);
},
errorMessage: function(msg) {
if (msg) {
msg = this._('error') + ": " + msg;
} else {
msg = this._('error');
}
this.message.updateMessage(msg);
},
updateMediaDisplay: function(layout) {
if (this._state.loaded) {
if (TL.Browser.mobile) {
this._el.content_item.style.maxHeight = (this.options.height/2) + "px";
} else {
this._el.content_item.style.maxHeight = this.options.height - this.options.credit_height - this.options.caption_height - 30 + "px";
}
//this._el.content_item.style.maxWidth = this.options.width + "px";
this._el.container.style.maxWidth = this.options.width + "px";
// Fix for max-width issues in Firefox
if (TL.Browser.firefox) {
if (this._el.content_item.offsetWidth > this._el.content_item.offsetHeight) {
//this._el.content_item.style.width = "100%";
}
}
this._updateMediaDisplay(layout);
if (this._state.media_loaded) {
if (this._el.credit) {
this._el.credit.style.width = this._el.content_item.offsetWidth + "px";
}
if (this._el.caption) {
this._el.caption.style.width = this._el.content_item.offsetWidth + "px";
}
}
}
},
/* Media Specific
================================================== */
_loadMedia: function() {
},
_updateMediaDisplay: function(l) {
//this._el.content_item.style.maxHeight = (this.options.height - this.options.credit_height - this.options.caption_height - 16) + "px";
if(TL.Browser.firefox) {
this._el.content_item.style.maxWidth = this.options.width + "px";
this._el.content_item.style.width = "auto";
}
},
_getMeta: function() {
},
/* Public
================================================== */
show: function() {
},
hide: function() {
},
addTo: function(container) {
container.appendChild(this._el.container);
this.onAdd();
},
removeFrom: function(container) {
container.removeChild(this._el.container);
this.onRemove();
},
// Update Display
updateDisplay: function(w, h, l) {
this._updateDisplay(w, h, l);
},
stopMedia: function() {
this._stopMedia();
},
loadErrorDisplay: function(message) {
try {
this._el.content.removeChild(this._el.content_item);
} catch(e) {
// if this._el.content_item isn't a child of this._el then just keep truckin
}
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-loaderror", this._el.content);
this._el.content_item.innerHTML = "<div class='tl-icon-" + this.options.media_type + "'></div><p>" + message + "</p>";
// After Loaded
this.onLoaded(true);
},
/* Events
================================================== */
onLoaded: function(error) {
this._state.loaded = true;
this.fire("loaded", this.data);
if (this.message) {
this.message.hide();
}
if (!error) {
this.showMeta();
}
this.updateDisplay();
},
onMediaLoaded: function(e) {
this._state.media_loaded = true;
this.fire("media_loaded", this.data);
if (this._el.credit) {
this._el.credit.style.width = this._el.content_item.offsetWidth + "px";
}
if (this._el.caption) {
this._el.caption.style.width = this._el.content_item.offsetWidth + "px";
}
},
showMeta: function(credit, caption) {
this._state.show_meta = true;
// Credit
if (this.data.credit && this.data.credit != "") {
this._el.credit = TL.Dom.create("div", "tl-credit", this._el.content_container);
this._el.credit.innerHTML = this.options.autolink == true ? TL.Util.linkify(this.data.credit) : this.data.credit;
this.options.credit_height = this._el.credit.offsetHeight;
}
// Caption
if (this.data.caption && this.data.caption != "") {
this._el.caption = TL.Dom.create("div", "tl-caption", this._el.content_container);
this._el.caption.innerHTML = this.options.autolink == true ? TL.Util.linkify(this.data.caption) : this.data.caption;
this.options.caption_height = this._el.caption.offsetHeight;
}
if (!this.data.caption || !this.data.credit) {
this.getMeta();
}
},
getMeta: function() {
this._getMeta();
},
updateMeta: function() {
if (!this.data.credit && this.data.credit_alternate) {
this._el.credit = TL.Dom.create("div", "tl-credit", this._el.content_container);
this._el.credit.innerHTML = this.data.credit_alternate;
this.options.credit_height = this._el.credit.offsetHeight;
}
if (!this.data.caption && this.data.caption_alternate) {
this._el.caption = TL.Dom.create("div", "tl-caption", this._el.content_container);
this._el.caption.innerHTML = this.data.caption_alternate;
this.options.caption_height = this._el.caption.offsetHeight;
}
this.updateDisplay();
},
onAdd: function() {
this.fire("added", this.data);
},
onRemove: function() {
this.fire("removed", this.data);
},
/* Private Methods
================================================== */
_initLayout: function () {
// Message
this.message = new TL.Message({}, this.options);
this.message.addTo(this._el.container);
// Create Layout
this._el.content_container = TL.Dom.create("div", "tl-media-content-container", this._el.container);
// Link
if (this.data.link && this.data.link != "") {
this._el.link = TL.Dom.create("a", "tl-media-link", this._el.content_container);
this._el.link.href = this.data.link;
if (this.data.link_target && this.data.link_target != "") {
this._el.link.target = this.data.link_target;
} else {
this._el.link.target = "_blank";
}
this._el.content = TL.Dom.create("div", "tl-media-content", this._el.link);
} else {
this._el.content = TL.Dom.create("div", "tl-media-content", this._el.content_container);
}
},
// Update Display
_updateDisplay: function(w, h, l) {
if (w) {
this.options.width = w;
}
//this._el.container.style.width = this.options.width + "px";
if (h) {
this.options.height = h;
}
if (l) {
this.options.layout = l;
}
if (this._el.credit) {
this.options.credit_height = this._el.credit.offsetHeight;
}
if (this._el.caption) {
this.options.caption_height = this._el.caption.offsetHeight + 5;
}
this.updateMediaDisplay(this.options.layout);
},
_stopMedia: function() {
}
});
/* **********************************************
Begin TL.Media.Blockquote.js
********************************************** */
/* TL.Media.Blockquote
================================================== */
TL.Media.Blockquote = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-blockquote", this._el.content);
this._el.content_container.className = "tl-media-content-container tl-media-content-container-text";
// Get Media ID
this.media_id = this.data.url;
// API Call
this._el.content_item.innerHTML = this.media_id;
// After Loaded
this.onLoaded();
},
updateMediaDisplay: function() {
},
_updateMediaDisplay: function() {
}
});
/* **********************************************
Begin TL.Media.DailyMotion.js
********************************************** */
/* TL.Media.DailyMotion
================================================== */
TL.Media.DailyMotion = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-dailymotion", this._el.content);
// Get Media ID
if (this.data.url.match("video")) {
this.media_id = this.data.url.split("video\/")[1].split(/[?&]/)[0];
} else {
this.media_id = this.data.url.split("embed\/")[1].split(/[?&]/)[0];
}
// API URL
api_url = "http://www.dailymotion.com/embed/video/" + this.media_id;
// API Call
this._el.content_item.innerHTML = "<iframe autostart='false' frameborder='0' width='100%' height='100%' src='" + api_url + "'></iframe>"
// After Loaded
this.onLoaded();
},
// Update Media Display
_updateMediaDisplay: function() {
this._el.content_item.style.height = TL.Util.ratio.r16_9({w:this._el.content_item.offsetWidth}) + "px";
}
});
/* **********************************************
Begin TL.Media.DocumentCloud.js
********************************************** */
/* TL.Media.DocumentCloud
================================================== */
TL.Media.DocumentCloud = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var self = this;
// Loading Message
this.loadingMessage();
// Create Dom elements
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-documentcloud tl-media-shadow", this._el.content);
this._el.content_item.id = TL.Util.unique_ID(7)
// Check url
if(this.data.url.match(/\.html$/)) {
this.data.url = this._transformURL(this.data.url);
} else if(!(this.data.url.match(/.(json|js)$/))) {
trace("DOCUMENT CLOUD IN URL BUT INVALID SUFFIX");
}
// Load viewer API
TL.Load.js([
'//s3.documentcloud.org/viewer/loader.js',
'//s3.amazonaws.com/s3.documentcloud.org/viewer/viewer.js'],
function() {
self.createMedia();
}
);
},
// Viewer API needs js, not html
_transformURL: function(url) {
return url.replace(/(.*)\.html$/, '$1.js')
},
// Update Media Display
_updateMediaDisplay: function() {
this._el.content_item.style.height = this.options.height + "px";
//this._el.content_item.style.width = this.options.width + "px";
},
createMedia: function() {
// DocumentCloud API call
DV.load(this.data.url, {
container: '#'+this._el.content_item.id,
showSidebar: false
});
this.onLoaded();
},
/* Events
================================================== */
});
/* **********************************************
Begin TL.Media.Flickr.js
********************************************** */
/* TL.Media.Flickr
================================================== */
TL.Media.Flickr = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Link
this._el.content_link = TL.Dom.create("a", "", this._el.content);
this._el.content_link.href = this.data.url;
this._el.content_link.target = "_blank";
// Photo
this._el.content_item = TL.Dom.create("img", "tl-media-item tl-media-image tl-media-flickr tl-media-shadow", this._el.content_link);
// Media Loaded Event
this._el.content_item.addEventListener('load', function(e) {
self.onMediaLoaded();
});
// Get Media ID
this.establishMediaID();
// API URL
api_url = "https://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=" + this.options.api_key_flickr + "&photo_id=" + this.media_id + "&format=json&jsoncallback=?";
// API Call
TL.getJSON(api_url, function(d) {
if (d.stat == "ok") {
self.createMedia(d);
} else {
self.loadErrorDisplay("Photo not found or private.");
}
});
},
establishMediaID: function() {
var marker = 'flickr.com/photos/';
var idx = this.data.url.indexOf(marker);
if (idx == -1) { throw "Invalid Flickr URL"; }
var pos = idx + marker.length;
this.media_id = this.data.url.substr(pos).split("/")[1];
},
createMedia: function(d) {
trace(d);
var best_size = this.sizes(this.options.height),
size = d.sizes.size[d.sizes.size.length - 2].source;
self = this;
for(var i = 0; i < d.sizes.size.length; i++) {
if (d.sizes.size[i].label == best_size) {
size = d.sizes.size[i].source;
}
}
// Set Image Source
this._el.content_item.src = size;
// After Loaded
this.onLoaded();
},
_getMeta: function() {
var self = this,
api_url;
// API URL
api_url = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + this.options.api_key_flickr + "&photo_id=" + this.media_id + "&format=json&jsoncallback=?";
// API Call
TL.getJSON(api_url, function(d) {
self.data.credit_alternate = "<a href='" + self.data.url + "' target='_blank'>" + d.photo.owner.realname + "</a>";
self.data.caption_alternate = d.photo.title._content + " " + d.photo.description._content;
self.updateMeta();
});
},
sizes: function(s) {
var _size = "";
if (s <= 75) {
if (s <= 0) {
_size = "Large";
} else {
_size = "Thumbnail";
}
} else if (s <= 180) {
_size = "Small";
} else if (s <= 240) {
_size = "Small 320";
} else if (s <= 375) {
_size = "Medium";
} else if (s <= 480) {
_size = "Medium 640";
} else if (s <= 600) {
_size = "Large";
} else {
_size = "Large";
}
return _size;
}
});
/* **********************************************
Begin TL.Media.GoogleDoc.js
********************************************** */
/* TL.Media.GoogleDoc
================================================== */
TL.Media.GoogleDoc = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe", this._el.content);
// Get Media ID
if (this.data.url.match("open\?id\=")) {
this.media_id = this.data.url.split("open\?id\=")[1];
if (this.data.url.match("\&authuser\=0")) {
url = this.media_id.match("\&authuser\=0")[0];
};
} else if (this.data.url.match(/file\/d\/([^/]*)\/?/)) {
var doc_id = this.data.url.match(/file\/d\/([^/]*)\/?/)[1];
url = 'https://drive.google.com/file/d/' + doc_id + '/preview'
} else {
url = this.data.url;
}
// this URL makes something suitable for an img src but what if it's not an image?
// api_url = "http://www.googledrive.com/host/" + this.media_id + "/";
this._el.content_item.innerHTML = "<iframe class='doc' frameborder='0' width='100%' height='100%' src='" + url + "'></iframe>";
// After Loaded
this.onLoaded();
},
// Update Media Display
_updateMediaDisplay: function() {
this._el.content_item.style.height = this.options.height + "px";
}
});
/* **********************************************
Begin TL.Media.GooglePlus.js
********************************************** */
/* TL.Media.GooglePlus
================================================== */
TL.Media.GooglePlus = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-googleplus", this._el.content);
// Get Media ID
this.media_id = this.data.url;
// API URL
api_url = this.media_id;
// API Call
this._el.content_item.innerHTML = "<iframe frameborder='0' width='100%' height='100%' src='" + api_url + "'></iframe>"
// After Loaded
this.onLoaded();
},
// Update Media Display
_updateMediaDisplay: function() {
this._el.content_item.style.height = this.options.height + "px";
}
});
/* **********************************************
Begin TL.Media.IFrame.js
********************************************** */
/* TL.Media.IFrame
================================================== */
TL.Media.IFrame = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe", this._el.content);
// Get Media ID
this.media_id = this.data.url;
// API URL
api_url = this.media_id;
// API Call
this._el.content_item.innerHTML = api_url;
// After Loaded
this.onLoaded();
},
// Update Media Display
_updateMediaDisplay: function() {
this._el.content_item.style.height = this.options.height + "px";
}
});
/* **********************************************
Begin TL.Media.Image.js
********************************************** */
/* TL.Media.Image
Produces image assets.
Takes a data object and populates a dom object
================================================== */
TL.Media.Image = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var self = this,
image_class = "tl-media-item tl-media-image tl-media-shadow";
// Loading Message
this.loadingMessage();
if (this.data.url.match(/.png(\?.*)?$/) || this.data.url.match(/.svg(\?.*)?$/)) {
image_class = "tl-media-item tl-media-image"
}
// Link
if (this.data.link) {
this._el.content_link = TL.Dom.create("a", "", this._el.content);
this._el.content_link.href = this.data.link;
this._el.content_link.target = "_blank";
this._el.content_item = TL.Dom.create("img", image_class, this._el.content_link);
} else {
this._el.content_item = TL.Dom.create("img", image_class, this._el.content);
}
// Media Loaded Event
this._el.content_item.addEventListener('load', function(e) {
self.onMediaLoaded();
});
this._el.content_item.src = TL.Util.transformImageURL(this.data.url);
this.onLoaded();
},
_updateMediaDisplay: function(layout) {
if(TL.Browser.firefox) {
//this._el.content_item.style.maxWidth = (this.options.width/2) - 40 + "px";
this._el.content_item.style.width = "auto";
}
}
});
/* **********************************************
Begin TL.Media.Instagram.js
********************************************** */
/* TL.Media.Instagram
================================================== */
TL.Media.Instagram = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Get Media ID
this.media_id = this.data.url.split("\/p\/")[1].split("/")[0];
// Link
this._el.content_link = TL.Dom.create("a", "", this._el.content);
this._el.content_link.href = this.data.url;
this._el.content_link.target = "_blank";
// Photo
this._el.content_item = TL.Dom.create("img", "tl-media-item tl-media-image tl-media-instagram tl-media-shadow", this._el.content_link);
// Media Loaded Event
this._el.content_item.addEventListener('load', function(e) {
self.onMediaLoaded();
});
// Set source
this._el.content_item.src = "http://instagr.am/p/" + this.media_id + "/media/?size=" + this.sizes(this._el.content.offsetWidth);
// API URL
api_url = "http://api.instagram.com/oembed?url=http://instagr.am/p/" + this.media_id + "&callback=?";
// After Loaded
this.onLoaded();
},
_getMeta: function() {
var self = this,
api_url;
// API URL
api_url = "http://api.instagram.com/oembed?url=http://instagr.am/p/" + this.media_id + "&callback=?";
// API Call
TL.getJSON(api_url, function(d) {
self.data.credit_alternate = "<a href='" + d.author_url + "' target='_blank'>" + d.author_name + "</a>";
self.data.caption_alternate = d.title;
self.updateMeta();
});
},
sizes: function(s) {
var _size = "";
if (s <= 150) {
_size = "t";
} else if (s <= 306) {
_size = "m";
} else {
_size = "l";
}
return _size;
}
});
/* **********************************************
Begin TL.Media.GoogleMap.js
********************************************** */
/* TL.Media.Map
================================================== */
TL.Media.GoogleMap = TL.Media.extend({
includes: [TL.Events],
_API_KEY: "AIzaSyB9dW8e_iRrATFa8g24qB6BDBGdkrLDZYI",
/* Load the media
================================================== */
_loadMedia: function() {
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-map tl-media-shadow", this._el.content);
// Get Media ID
this.media_id = this.data.url;
// API Call
this.mapframe = TL.Dom.create("iframe", "", this._el.content_item);
window.stash = this;
this.mapframe.width = "100%";
this.mapframe.height = "100%";
this.mapframe.frameBorder = "0";
this.mapframe.src = this.makeGoogleMapsEmbedURL(this.media_id, this.options.api_key_googlemaps);
// After Loaded
this.onLoaded();
},
_updateMediaDisplay: function() {
if (this._state.loaded) {
var dimensions = TL.Util.ratio.square({w:this._el.content_item.offsetWidth});
this._el.content_item.style.height = dimensions.h + "px";
}
},
makeGoogleMapsEmbedURL: function(url,api_key) {
// Test with https://docs.google.com/spreadsheets/d/1zCpvtRdftlR5fBPppmy_-SkGIo7RMwoPUiGFZDAXbTc/edit
var Streetview = false;
function determineMapMode(url){
function parseDisplayMode(display_mode, param_string) {
// Set the zoom param
if (display_mode.slice(-1) == "z") {
param_string["zoom"] = display_mode;
// Set the maptype to something other than "roadmap"
} else if (display_mode.slice(-1) == "m") {
// TODO: make this somehow interpret the correct zoom level
// until then fake it by using Google's default zoom level
param_string["zoom"] = 14;
param_string["maptype"] = "satellite";
// Set all the fun streetview params
} else if (display_mode.slice(-1) == "t") {
Streetview = true;
// streetview uses "location" instead of "center"
// "place" mode doesn't have the center param, so we may need to grab that now
if (mapmode == "place") {
var center = url.match(regexes["place"])[3] + "," + url.match(regexes["place"])[4];
} else {
var center = param_string["center"];
delete param_string["center"];
}
// Clear out all the other params -- this is so hacky
param_string = {};
param_string["location"] = center;
streetview_params = display_mode.split(",");
for (param in param_defs["streetview"]) {
var i = parseInt(param) + 1;
if (param_defs["streetview"][param] == "pitch" && streetview_params[i] == "90t"){
// Although 90deg is the horizontal default in the URL, 0 is horizontal default for embed URL. WHY??
// https://developers.google.com/maps/documentation/javascript/streetview
param_string[param_defs["streetview"][param]] = 0;
} else {
param_string[param_defs["streetview"][param]] = streetview_params[i].slice(0,-1);
}
}
}
return param_string;
}
function determineMapModeURL(mapmode, match) {
var param_string = {};
var url_root = match[1], display_mode = match[match.length - 1];
for (param in param_defs[mapmode]) {
// skip first 2 matches, because they reflect the URL and not params
var i = parseInt(param)+2;
if (param_defs[mapmode][param] == "center") {
param_string[param_defs[mapmode][param]] = match[i] + "," + match[++i];
} else {
param_string[param_defs[mapmode][param]] = match[i];
}
}
param_string = parseDisplayMode(display_mode, param_string);
param_string["key"] = api_key;
if (Streetview == true) {
mapmode = "streetview";
} else {
}
return (url_root + "/embed/v1/" + mapmode + TL.Util.getParamString(param_string));
}
mapmode = "view";
if (url.match(regexes["place"])) {
mapmode = "place";
} else if (url.match(regexes["directions"])) {
mapmode = "directions";
} else if (url.match(regexes["search"])) {
mapmode = "search";
}
return determineMapModeURL(mapmode, url.match(regexes[mapmode]));
}
// These must be in the order they appear in the original URL
// "key" param not included since it's not in the URL structure
// Streetview "location" param not included since it's captured as "center"
// Place "center" param ...um...
var param_defs = {
"view": ["center"],
"place": ["q", "center"],
"directions": ["origin", "destination", "center"],
"search": ["q", "center"],
"streetview": ["fov", "heading", "pitch"]
};
// Set up regex parts to make updating these easier if Google changes them
var root_url_regex = /(https:\/\/.+google.+?\/maps)/;
var coords_regex = /@([-\d.]+),([-\d.]+)/;
var address_regex = /([\w\W]+)/;
// Data doesn't seem to get used for anything
var data_regex = /data=[\S]*/;
// Capture the parameters that determine what map tiles to use
// In roadmap view, mode URLs include zoom paramater (e.g. "14z")
// In satellite (or "earth") view, URLs include a distance parameter (e.g. "84511m")
// In streetview, URLs include paramaters like "3a,75y,49.76h,90t" -- see http://stackoverflow.com/a/22988073
var display_mode_regex = /,((?:[-\d.]+[zmayht],?)*)/;
var regexes = {
view: new RegExp(root_url_regex.source + "/" + coords_regex.source + display_mode_regex.source),
place: new RegExp(root_url_regex.source + "/place/" + address_regex.source + "/" + coords_regex.source + display_mode_regex.source),
directions: new RegExp(root_url_regex.source + "/dir/" + address_regex.source + "/" + address_regex.source + "/" + coords_regex.source + display_mode_regex.source),
search: new RegExp(root_url_regex.source + "/search/" + address_regex.source + "/" + coords_regex.source + display_mode_regex.source)
};
return determineMapMode(url);
}
});
/* **********************************************
Begin TL.Media.Profile.js
********************************************** */
/* TL.Media.Profile
================================================== */
TL.Media.Profile = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
// Loading Message
this.loadingMessage();
this._el.content_item = TL.Dom.create("img", "tl-media-item tl-media-image tl-media-profile tl-media-shadow", this._el.content);
this._el.content_item.src = this.data.url;
this.onLoaded();
},
_updateMediaDisplay: function(layout) {
if(TL.Browser.firefox) {
this._el.content_item.style.maxWidth = (this.options.width/2) - 40 + "px";
}
}
});
/* **********************************************
Begin TL.Media.Slider.js
********************************************** */
/* TL.Media.SLider
Produces a Slider
Takes a data object and populates a dom object
TODO
Placeholder
================================================== */
TL.Media.Slider = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
this._el.content_item = TL.Dom.create("img", "tl-media-item tl-media-image", this._el.content);
this._el.content_item.src = this.data.url;
this.onLoaded();
}
});
/* **********************************************
Begin TL.Media.SoundCloud.js
********************************************** */
/* TL.Media.SoundCloud
================================================== */
TL.Media.SoundCloud = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-soundcloud tl-media-shadow", this._el.content);
// Get Media ID
this.media_id = this.data.url;
// API URL
api_url = "http://soundcloud.com/oembed?url=" + this.media_id + "&format=js&callback=?"
// API Call
TL.getJSON(api_url, function(d) {
self.createMedia(d);
});
},
createMedia: function(d) {
this._el.content_item.innerHTML = d.html;
// After Loaded
this.onLoaded();
}
});
/* **********************************************
Begin TL.Media.Spotify.js
********************************************** */
/* TL.Media.Spotify
================================================== */
TL.Media.Spotify = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-spotify", this._el.content);
// Get Media ID
if (this.data.url.match("open.spotify.com/track/")) {
this.media_id = "spotify:track:" + this.data.url.split("open.spotify.com/track/")[1];
} else if (this.data.url.match("spotify:track:")) {
this.media_id = this.data.url;
} else if (this.data.url.match("/playlist/")) {
var user = this.data.url.split("open.spotify.com/user/")[1].split("/playlist/")[0];
this.media_id = "spotify:user:" + user + ":playlist:" + this.data.url.split("/playlist/")[1];
} else if (this.data.url.match(":playlist:")) {
this.media_id = this.data.url;
}
// API URL
api_url = "http://embed.spotify.com/?uri=" + this.media_id + "&theme=white&view=coverart";
this.player = TL.Dom.create("iframe", "tl-media-shadow", this._el.content_item);
this.player.width = "100%";
this.player.height = "100%";
this.player.frameBorder = "0";
this.player.src = api_url;
// After Loaded
this.onLoaded();
},
// Update Media Display
_updateMediaDisplay: function(l) {
var _height = this.options.height,
_player_height = 0,
_player_width = 0;
if (TL.Browser.mobile) {
_height = (this.options.height/2);
} else {
_height = this.options.height - this.options.credit_height - this.options.caption_height - 30;
}
this._el.content_item.style.maxHeight = "none";
trace(_height);
trace(this.options.width)
if (_height > this.options.width) {
trace("height is greater")
_player_height = this.options.width + 80 + "px";
_player_width = this.options.width + "px";
} else {
trace("width is greater")
trace(this.options.width)
_player_height = _height + "px";
_player_width = _height - 80 + "px";
}
this.player.style.width = _player_width;
this.player.style.height = _player_height;
if (this._el.credit) {
this._el.credit.style.width = _player_width;
}
if (this._el.caption) {
this._el.caption.style.width = _player_width;
}
},
_stopMedia: function() {
// Need spotify stop code
}
});
/* **********************************************
Begin TL.Media.Storify.js
********************************************** */
/* TL.Media.Storify
================================================== */
TL.Media.Storify = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var content;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-storify", this._el.content);
// Get Media ID
this.media_id = this.data.url;
// Content
content = "<iframe frameborder='0' width='100%' height='100%' src='" + this.media_id + "/embed'></iframe>";
content += "<script src='" + this.media_id + ".js'></script>";
// API Call
this._el.content_item.innerHTML = content;
// After Loaded
this.onLoaded();
},
// Update Media Display
_updateMediaDisplay: function() {
this._el.content_item.style.height = this.options.height + "px";
}
});
/* **********************************************
Begin TL.Media.Text.js
********************************************** */
TL.Media.Text = TL.Class.extend({
includes: [TL.Events],
// DOM ELEMENTS
_el: {
container: {},
content_container: {},
content: {},
headline: {},
date: {}
},
// Data
data: {
unique_id: "",
headline: "headline",
text: "text"
},
// Options
options: {
title: false
},
/* Constructor
================================================== */
initialize: function(data, options, add_to_container) {
TL.Util.setData(this, data);
// Merge Options
TL.Util.mergeData(this.options, options);
this._el.container = TL.Dom.create("div", "tl-text");
this._el.container.id = this.data.unique_id;
this._initLayout();
if (add_to_container) {
add_to_container.appendChild(this._el.container);
};
},
/* Adding, Hiding, Showing etc
================================================== */
show: function() {
},
hide: function() {
},
addTo: function(container) {
container.appendChild(this._el.container);
//this.onAdd();
},
removeFrom: function(container) {
container.removeChild(this._el.container);
},
headlineHeight: function() {
return this._el.headline.offsetHeight + 40;
},
addDateText: function(str) {
this._el.date.innerHTML = str;
},
/* Events
================================================== */
onLoaded: function() {
this.fire("loaded", this.data);
},
onAdd: function() {
this.fire("added", this.data);
},
onRemove: function() {
this.fire("removed", this.data);
},
/* Private Methods
================================================== */
_initLayout: function () {
// Create Layout
this._el.content_container = TL.Dom.create("div", "tl-text-content-container", this._el.container);
// Date
this._el.date = TL.Dom.create("h3", "tl-headline-date", this._el.content_container);
// Headline
if (this.data.headline != "") {
var headline_class = "tl-headline";
if (this.options.title) {
headline_class = "tl-headline tl-headline-title";
}
this._el.headline = TL.Dom.create("h2", headline_class, this._el.content_container);
this._el.headline.innerHTML = this.data.headline;
}
// Text
if (this.data.text != "") {
var text_content = "";
text_content += TL.Util.htmlify(this.options.autolink == true ? TL.Util.linkify(this.data.text) : this.data.text);
this._el.content = TL.Dom.create("div", "tl-text-content", this._el.content_container);
this._el.content.innerHTML = text_content;
}
// Fire event that the slide is loaded
this.onLoaded();
}
});
/* **********************************************
Begin TL.Media.Twitter.js
********************************************** */
/* TL.Media.Twitter
Produces Twitter Display
================================================== */
TL.Media.Twitter = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-twitter", this._el.content);
this._el.content_container.className = "tl-media-content-container tl-media-content-container-text";
// Get Media ID
if (this.data.url.match("status\/")) {
this.media_id = this.data.url.split("status\/")[1];
} else if (url.match("statuses\/")) {
this.media_id = this.data.url.split("statuses\/")[1];
} else {
this.media_id = "";
}
// API URL
api_url = "https://api.twitter.com/1/statuses/oembed.json?id=" + this.media_id + "&omit_script=true&include_entities=true&callback=?";
// API Call
TL.ajax({
type: 'GET',
url: api_url,
dataType: 'json', //json data type
success: function(d){
self.createMedia(d);
},
error:function(xhr, type){
var error_text = "";
error_text += "Unable to load Tweet. <br/>" + self.media_id + "<br/>" + type;
self.loadErrorDisplay(error_text);
}
});
},
createMedia: function(d) {
var tweet = "",
tweet_text = "",
tweetuser = "",
tweet_status_temp = "",
tweet_status_url = "",
tweet_status_date = "";
// TWEET CONTENT
tweet_text = d.html.split("<\/p>\—")[0] + "</p></blockquote>";
tweetuser = d.author_url.split("twitter.com\/")[1];
tweet_status_temp = d.html.split("<\/p>\—")[1].split("<a href=\"")[1];
tweet_status_url = tweet_status_temp.split("\"\>")[0];
tweet_status_date = tweet_status_temp.split("\"\>")[1].split("<\/a>")[0];
// Open links in new window
tweet_text = tweet_text.replace(/<a href/ig, '<a class="tl-makelink" target="_blank" href');
// TWEET CONTENT
tweet += tweet_text;
// TWEET AUTHOR
tweet += "<div class='vcard'>";
tweet += "<a href='" + tweet_status_url + "' class='twitter-date' target='_blank'>" + tweet_status_date + "</a>";
tweet += "<div class='author'>";
tweet += "<a class='screen-name url' href='" + d.author_url + "' target='_blank'>";
tweet += "<span class='avatar'></span>";
tweet += "<span class='fn'>" + d.author_name + " <span class='tl-icon-twitter'></span></span>";
tweet += "<span class='nickname'>@" + tweetuser + "<span class='thumbnail-inline'></span></span>";
tweet += "</a>";
tweet += "</div>";
tweet += "</div>";
// Add to DOM
this._el.content_item.innerHTML = tweet;
// After Loaded
this.onLoaded();
},
updateMediaDisplay: function() {
},
_updateMediaDisplay: function() {
}
});
/* **********************************************
Begin TL.Media.Vimeo.js
********************************************** */
/* TL.Media.Vimeo
================================================== */
TL.Media.Vimeo = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-vimeo tl-media-shadow", this._el.content);
// Get Media ID
this.media_id = this.data.url.split(/video\/|\/\/vimeo\.com\//)[1].split(/[?&]/)[0];
// API URL
api_url = "https://player.vimeo.com/video/" + this.media_id + "?api=1&title=0&byline=0&portrait=0&color=ffffff";
this.player = TL.Dom.create("iframe", "", this._el.content_item);
// Media Loaded Event
this.player.addEventListener('load', function(e) {
self.onMediaLoaded();
});
this.player.width = "100%";
this.player.height = "100%";
this.player.frameBorder = "0";
this.player.src = api_url;
// After Loaded
this.onLoaded();
},
// Update Media Display
_updateMediaDisplay: function() {
this._el.content_item.style.height = TL.Util.ratio.r16_9({w:this._el.content_item.offsetWidth}) + "px";
},
_stopMedia: function() {
try {
this.player.contentWindow.postMessage(JSON.stringify({method: "pause"}), "https://player.vimeo.com");
}
catch(err) {
trace(err);
}
}
});
/* **********************************************
Begin TL.Media.Vine.js
********************************************** */
/* TL.Media.Vine
================================================== */
TL.Media.Vine = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-iframe tl-media-vine tl-media-shadow", this._el.content);
// Get Media ID
this.media_id = this.data.url.split("vine.co/v/")[1];
// API URL
api_url = "https://vine.co/v/" + this.media_id + "/embed/simple";
// API Call
this._el.content_item.innerHTML = "<iframe frameborder='0' width='100%' height='100%' src='" + api_url + "'></iframe><script async src='http://platform.vine.co/static/scripts/embed.js' charset='utf-8'></script>"
// After Loaded
this.onLoaded();
},
// Update Media Display
_updateMediaDisplay: function() {
var size = TL.Util.ratio.square({w:this._el.content_item.offsetWidth , h:this.options.height});
this._el.content_item.style.height = size.h + "px";
}
});
/* **********************************************
Begin TL.Media.Website.js
********************************************** */
/* TL.Media.Website
Uses Embedly
http://embed.ly/docs/api/extract/endpoints/1/extract
================================================== */
TL.Media.Website = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var self = this;
// Loading Message
this.loadingMessage();
// Get Media ID
this.media_id = this.data.url.replace(/.*?:\/\//g, "");
if (this.options.api_key_embedly) {
// API URL
api_url = "http://api.embed.ly/1/extract?key=" + this.options.api_key_embedly + "&url=" + this.media_id + "&callback=?";
// API Call
TL.getJSON(api_url, function(d) {
self.createMedia(d);
});
} else {
this.createCardContent();
}
},
createCardContent: function() {
(function(w, d){
var id='embedly-platform', n = 'script';
if (!d.getElementById(id)){
w.embedly = w.embedly || function() {(w.embedly.q = w.embedly.q || []).push(arguments);};
var e = d.createElement(n); e.id = id; e.async=1;
e.src = ('https:' === document.location.protocol ? 'https' : 'http') + '://cdn.embedly.com/widgets/platform.js';
var s = d.getElementsByTagName(n)[0];
s.parentNode.insertBefore(e, s);
}
})(window, document);
var content = "<a href=\"" + this.data.url + "\" class=\"embedly-card\">" + this.data.url + "</a>";
this._setContent(content);
},
createMedia: function(d) { // this costs API credits...
var content = "";
content += "<h4><a href='" + this.data.url + "' target='_blank'>" + d.title + "</a></h4>";
if (d.images) {
if (d.images[0]) {
trace(d.images[0].url);
content += "<img src='" + d.images[0].url + "' />";
}
}
if (d.favicon_url) {
content += "<img class='tl-media-website-icon' src='" + d.favicon_url + "' />";
}
content += "<span class='tl-media-website-description'>" + d.provider_name + "</span><br/>";
content += "<p>" + d.description + "</p>";
this._setContent(content);
},
_setContent: function(content) {
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-website", this._el.content);
this._el.content_container.className = "tl-media-content-container tl-media-content-container-text";
this._el.content_item.innerHTML = content;
// After Loaded
this.onLoaded();
},
updateMediaDisplay: function() {
},
_updateMediaDisplay: function() {
}
});
/* **********************************************
Begin TL.Media.Wikipedia.js
********************************************** */
/* TL.Media.Wikipedia
================================================== */
TL.Media.Wikipedia = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var api_url,
api_language,
self = this;
// Loading Message
this.loadingMessage();
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-wikipedia", this._el.content);
this._el.content_container.className = "tl-media-content-container tl-media-content-container-text";
// Get Media ID
this.media_id = this.data.url.split("wiki\/")[1].split("#")[0].replace("_", " ");
this.media_id = this.media_id.replace(" ", "%20");
api_language = this.data.url.split("//")[1].split(".wikipedia")[0];
// API URL
api_url = "http://" + api_language + ".wikipedia.org/w/api.php?action=query&prop=extracts|pageimages&redirects=&titles=" + this.media_id + "&exintro=1&format=json&callback=?";
// API Call
TL.ajax({
type: 'GET',
url: api_url,
dataType: 'json', //json data type
success: function(d){
self.createMedia(d);
},
error:function(xhr, type){
var error_text = "";
error_text += "Unable to load Wikipedia entry. <br/>" + self.media_id + "<br/>" + type;
self.loadErrorDisplay(error_text);
}
});
},
createMedia: function(d) {
var wiki = "";
if (d.query) {
var content = "",
wiki = {
entry: {},
title: "",
text: "",
extract: "",
paragraphs: 1,
page_image: "",
text_array: []
};
wiki.entry = TL.Util.getObjectAttributeByIndex(d.query.pages, 0);
wiki.extract = wiki.entry.extract;
wiki.title = wiki.entry.title;
wiki.page_image = wiki.entry.thumbnail;
if (wiki.extract.match("<p>")) {
wiki.text_array = wiki.extract.split("<p>");
} else {
wiki.text_array.push(wiki.extract);
}
for(var i = 0; i < wiki.text_array.length; i++) {
if (i+1 <= wiki.paragraphs && i+1 < wiki.text_array.length) {
wiki.text += "<p>" + wiki.text_array[i+1];
}
}
content += "<span class='tl-icon-wikipedia'></span>";
content += "<div class='tl-wikipedia-title'><h4><a href='" + this.data.url + "' target='_blank'>" + wiki.title + "</a></h4>";
content += "<span class='tl-wikipedia-source'>" + this._('wikipedia') + "</span></div>";
if (wiki.page_image) {
//content += "<img class='tl-wikipedia-pageimage' src='" + wiki.page_image.source +"'>";
}
content += wiki.text;
if (wiki.extract.match("REDIRECT")) {
} else {
// Add to DOM
this._el.content_item.innerHTML = content;
// After Loaded
this.onLoaded();
}
}
},
updateMediaDisplay: function() {
},
_updateMediaDisplay: function() {
}
});
/* **********************************************
Begin TL.Media.YouTube.js
********************************************** */
/* TL.Media.YouTube
================================================== */
TL.Media.YouTube = TL.Media.extend({
includes: [TL.Events],
/* Load the media
================================================== */
_loadMedia: function() {
var self = this,
url_vars;
// Loading Message
this.loadingMessage();
this.youtube_loaded = false;
// Create Dom element
this._el.content_item = TL.Dom.create("div", "tl-media-item tl-media-youtube tl-media-shadow", this._el.content);
this._el.content_item.id = TL.Util.unique_ID(7)
// URL Vars
url_vars = TL.Util.getUrlVars(this.data.url);
// Get Media ID
this.media_id = {};
if (this.data.url.match('v=')) {
this.media_id.id = url_vars["v"];
} else if (this.data.url.match('\/embed\/')) {
this.media_id.id = this.data.url.split("embed\/")[1].split(/[?&]/)[0];
} else if (this.data.url.match(/v\/|v=|youtu\.be\//)){
this.media_id.id = this.data.url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0];
} else {
trace("YOUTUBE IN URL BUT NOT A VALID VIDEO");
}
this.media_id.start = TL.Util.parseYouTubeTime(url_vars["t"]);
this.media_id.hd = Boolean(typeof(url_vars["hd"]) != 'undefined');
// API Call
TL.Load.js('https://www.youtube.com/iframe_api', function() {
self.createMedia();
});
},
// Update Media Display
_updateMediaDisplay: function() {
//this.el.content_item = document.getElementById(this._el.content_item.id);
this._el.content_item.style.height = TL.Util.ratio.r16_9({w:this.options.width}) + "px";
this._el.content_item.style.width = this.options.width + "px";
},
_stopMedia: function() {
if (this.youtube_loaded) {
try {
if(this.player.getPlayerState() == YT.PlayerState.PLAYING) {
this.player.pauseVideo();
}
}
catch(err) {
trace(err);
}
}
},
createMedia: function() {
var self = this;
clearTimeout(this.timer);
if(typeof YT != 'undefined' && typeof YT.Player != 'undefined') {
// Create Player
this.player = new YT.Player(this._el.content_item.id, {
playerVars: {
enablejsapi: 1,
color: 'white',
autohide: 1,
showinfo: 0,
theme: 'light',
start: this.media_id.start,
fs: 0,
rel: 0
},
videoId: this.media_id.id,
events: {
onReady: function() {
self.onPlayerReady();
// After Loaded
self.onLoaded();
},
'onStateChange': self.onStateChange
}
});
} else {
this.timer = setTimeout(function() {
self.createMedia();
}, 1000);
}
},
/* Events
================================================== */
onPlayerReady: function(e) {
this.youtube_loaded = true;
this._el.content_item = document.getElementById(this._el.content_item.id);
this.onMediaLoaded();
},
onStateChange: function(e) {
if(e.data == YT.PlayerState.ENDED) {
e.target.seekTo(0);
e.target.pauseVideo();
}
}
});
/* **********************************************
Begin TL.Slide.js
********************************************** */
/* TL.Slide
Creates a slide. Takes a data object and
populates the slide with content.
================================================== */
TL.Slide = TL.Class.extend({
includes: [TL.Events, TL.DomMixins, TL.I18NMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(data, options, title_slide) {
// DOM Elements
this._el = {
container: {},
scroll_container: {},
background: {},
content_container: {},
content: {}
};
// Components
this._media = null;
this._mediaclass = {};
this._text = {};
// State
this._state = {
loaded: false
};
this.has = {
headline: false,
text: false,
media: false,
title: false,
background: {
image: false,
color: false,
color_value :""
}
}
this.has.title = title_slide;
// Data
this.data = {
unique_id: null,
background: null,
start_date: null,
end_date: null,
location: null,
text: null,
media: null,
autolink: true
};
// Options
this.options = {
// animation
duration: 1000,
slide_padding_lr: 40,
ease: TL.Ease.easeInSpline,
width: 600,
height: 600,
skinny_size: 650,
media_name: ""
};
// Actively Displaying
this.active = false;
// Animation Object
this.animator = {};
// Merge Data and Options
TL.Util.mergeData(this.options, options);
TL.Util.mergeData(this.data, data);
this._initLayout();
this._initEvents();
},
/* Adding, Hiding, Showing etc
================================================== */
show: function() {
this.animator = TL.Animate(this._el.slider_container, {
left: -(this._el.container.offsetWidth * n) + "px",
duration: this.options.duration,
easing: this.options.ease
});
},
hide: function() {
},
setActive: function(is_active) {
this.active = is_active;
if (this.active) {
if (this.data.background) {
this.fire("background_change", this.has.background);
}
this.loadMedia();
} else {
this.stopMedia();
}
},
addTo: function(container) {
container.appendChild(this._el.container);
//this.onAdd();
},
removeFrom: function(container) {
container.removeChild(this._el.container);
},
updateDisplay: function(w, h, l) {
this._updateDisplay(w, h, l);
},
loadMedia: function() {
if (this._media && !this._state.loaded) {
this._media.loadMedia();
this._state.loaded = true;
}
},
stopMedia: function() {
if (this._media && this._state.loaded) {
this._media.stopMedia();
}
},
getBackground: function() {
return this.has.background;
},
scrollToTop: function() {
this._el.container.scrollTop = 0;
},
getFormattedDate: function() {
if (TL.Util.trim(this.data.display_date).length > 0) {
return this.data.display_date;
}
var date_text = "";
if(!this.has.title) {
if (this.data.end_date) {
date_text = " — " + this.data.end_date.getDisplayDate(this.getLanguage());
}
if (this.data.start_date) {
date_text = this.data.start_date.getDisplayDate(this.getLanguage()) + date_text;
}
}
return date_text;
},
/* Events
================================================== */
/* Private Methods
================================================== */
_initLayout: function () {
// Create Layout
this._el.container = TL.Dom.create("div", "tl-slide");
if (this.has.title) {
this._el.container.className = "tl-slide tl-slide-titleslide";
}
if (this.data.unique_id) {
this._el.container.id = this.data.unique_id;
}
this._el.scroll_container = TL.Dom.create("div", "tl-slide-scrollable-container", this._el.container);
this._el.content_container = TL.Dom.create("div", "tl-slide-content-container", this._el.scroll_container);
this._el.content = TL.Dom.create("div", "tl-slide-content", this._el.content_container);
this._el.background = TL.Dom.create("div", "tl-slide-background", this._el.container);
// Style Slide Background
if (this.data.background) {
if (this.data.background.url) {
this.has.background.image = true;
this._el.container.className += ' tl-full-image-background';
//this._el.container.style.backgroundImage="url('" + this.data.background.url + "')";
this.has.background.color_value = "#000";
this._el.background.style.backgroundImage = "url('" + this.data.background.url + "')";
this._el.background.style.display = "block";
}
if (this.data.background.color) {
this.has.background.color = true;
this._el.container.className += ' tl-full-color-background';
this.has.background.color_value = this.data.background.color;
//this._el.container.style.backgroundColor = this.data.background.color;
//this._el.background.style.backgroundColor = this.data.background.color;
//this._el.background.style.display = "block";
}
if (this.data.background.text_background) {
this._el.container.className += ' tl-text-background';
}
}
// Determine Assets for layout and loading
if (this.data.media && this.data.media.url && this.data.media.url != "") {
this.has.media = true;
}
if (this.data.text && this.data.text.text) {
this.has.text = true;
}
if (this.data.text && this.data.text.headline) {
this.has.headline = true;
}
// Create Media
if (this.has.media) {
// Determine the media type
this.data.media.mediatype = TL.MediaType(this.data.media);
this.options.media_name = this.data.media.mediatype.name;
this.options.media_type = this.data.media.mediatype.type;
this.options.autolink = this.data.autolink;
// Create a media object using the matched class name
this._media = new this.data.media.mediatype.cls(this.data.media, this.options);
}
// Create Text
if (this.has.text || this.has.headline) {
this._text = new TL.Media.Text(this.data.text, {title:this.has.title,language: this.options.language, autolink: this.data.autolink });
this._text.addDateText(this.getFormattedDate());
}
// Add to DOM
if (!this.has.text && !this.has.headline && this.has.media) {
this._el.container.className += ' tl-slide-media-only';
this._media.addTo(this._el.content);
} else if (this.has.headline && this.has.media && !this.has.text) {
this._el.container.className += ' tl-slide-media-only';
this._text.addTo(this._el.content);
this._media.addTo(this._el.content);
} else if (this.has.text && this.has.media) {
this._media.addTo(this._el.content);
this._text.addTo(this._el.content);
} else if (this.has.text || this.has.headline) {
this._el.container.className += ' tl-slide-text-only';
this._text.addTo(this._el.content);
}
// Fire event that the slide is loaded
this.onLoaded();
},
_initEvents: function() {
},
// Update Display
_updateDisplay: function(width, height, layout) {
var content_width,
content_padding_left = this.options.slide_padding_lr,
content_padding_right = this.options.slide_padding_lr;
if (width) {
this.options.width = width;
} else {
this.options.width = this._el.container.offsetWidth;
}
content_width = this.options.width - (this.options.slide_padding_lr * 2);
if(TL.Browser.mobile && (this.options.width <= this.options.skinny_size)) {
content_padding_left = 0;
content_padding_right = 0;
content_width = this.options.width;
} else if (layout == "landscape") {
} else if (this.options.width <= this.options.skinny_size) {
content_padding_left = 50;
content_padding_right = 50;
content_width = this.options.width - content_padding_left - content_padding_right;
} else {
}
this._el.content.style.paddingLeft = content_padding_left + "px";
this._el.content.style.paddingRight = content_padding_right + "px";
this._el.content.style.width = content_width + "px";
if (height) {
this.options.height = height;
//this._el.scroll_container.style.height = this.options.height + "px";
} else {
this.options.height = this._el.container.offsetHeight;
}
if (this._media) {
if (!this.has.text && this.has.headline) {
this._media.updateDisplay(content_width, (this.options.height - this._text.headlineHeight()), layout);
} else if (!this.has.text && !this.has.headline) {
this._media.updateDisplay(content_width, this.options.height, layout);
} else if (this.options.width <= this.options.skinny_size) {
this._media.updateDisplay(content_width, this.options.height, layout);
} else {
this._media.updateDisplay(content_width/2, this.options.height, layout);
}
}
}
});
/* **********************************************
Begin TL.SlideNav.js
********************************************** */
/* TL.SlideNav
encapsulate DOM display/events for the
'next' and 'previous' buttons on a slide.
================================================== */
// TODO null out data
TL.SlideNav = TL.Class.extend({
includes: [TL.Events, TL.DomMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(data, options, add_to_container) {
// DOM ELEMENTS
this._el = {
container: {},
content_container: {},
icon: {},
title: {},
description: {}
};
// Media Type
this.mediatype = {};
// Data
this.data = {
title: "Navigation",
description: "Description",
date: "Date"
};
//Options
this.options = {
direction: "previous"
};
this.animator = null;
// Merge Data and Options
TL.Util.mergeData(this.options, options);
TL.Util.mergeData(this.data, data);
this._el.container = TL.Dom.create("div", "tl-slidenav-" + this.options.direction);
if (TL.Browser.mobile) {
this._el.container.setAttribute("ontouchstart"," ");
}
this._initLayout();
this._initEvents();
if (add_to_container) {
add_to_container.appendChild(this._el.container);
};
},
/* Update Content
================================================== */
update: function(slide) {
var d = {
title: "",
description: "",
date: slide.getFormattedDate()
};
if (slide.data.text) {
if (slide.data.text.headline) {
d.title = slide.data.text.headline;
}
}
this._update(d);
},
/* Color
================================================== */
setColor: function(inverted) {
if (inverted) {
this._el.content_container.className = 'tl-slidenav-content-container tl-slidenav-inverted';
} else {
this._el.content_container.className = 'tl-slidenav-content-container';
}
},
/* Events
================================================== */
_onMouseClick: function() {
this.fire("clicked", this.options);
},
/* Private Methods
================================================== */
_update: function(d) {
// update data
this.data = TL.Util.mergeData(this.data, d);
// Title
this._el.title.innerHTML = TL.Util.unlinkify(this.data.title);
// Date
this._el.description.innerHTML = TL.Util.unlinkify(this.data.date);
},
_initLayout: function () {
// Create Layout
this._el.content_container = TL.Dom.create("div", "tl-slidenav-content-container", this._el.container);
this._el.icon = TL.Dom.create("div", "tl-slidenav-icon", this._el.content_container);
this._el.title = TL.Dom.create("div", "tl-slidenav-title", this._el.content_container);
this._el.description = TL.Dom.create("div", "tl-slidenav-description", this._el.content_container);
this._el.icon.innerHTML = " "
this._update();
},
_initEvents: function () {
TL.DomEvent.addListener(this._el.container, 'click', this._onMouseClick, this);
}
});
/* **********************************************
Begin TL.StorySlider.js
********************************************** */
/* StorySlider
is the central class of the API - it is used to create a StorySlider
Events:
nav_next
nav_previous
slideDisplayUpdate
loaded
slideAdded
slideLoaded
slideRemoved
================================================== */
TL.StorySlider = TL.Class.extend({
includes: TL.Events,
/* Private Methods
================================================== */
initialize: function (elem, data, options, init) {
// DOM ELEMENTS
this._el = {
container: {},
background: {},
slider_container_mask: {},
slider_container: {},
slider_item_container: {}
};
this._nav = {};
this._nav.previous = {};
this._nav.next = {};
// Slide Spacing
this.slide_spacing = 0;
// Slides Array
this._slides = [];
// Swipe Object
this._swipable;
// Preload Timer
this.preloadTimer;
// Message
this._message;
// Current Slide
this.current_id = '';
// Data Object
this.data = {};
this.options = {
id: "",
layout: "portrait",
width: 600,
height: 600,
default_bg_color: {r:255, g:255, b:255},
slide_padding_lr: 40, // padding on slide of slide
start_at_slide: 1,
slide_default_fade: "0%", // landscape fade
// animation
duration: 1000,
ease: TL.Ease.easeInOutQuint,
// interaction
dragging: true,
trackResize: true
};
// Main element ID
if (typeof elem === 'object') {
this._el.container = elem;
this.options.id = TL.Util.unique_ID(6, "tl");
} else {
this.options.id = elem;
this._el.container = TL.Dom.get(elem);
}
if (!this._el.container.id) {
this._el.container.id = this.options.id;
}
// Animation Object
this.animator = null;
// Merge Data and Options
TL.Util.mergeData(this.options, options);
TL.Util.mergeData(this.data, data);
if (init) {
this.init();
}
},
init: function() {
this._initLayout();
this._initEvents();
this._initData();
this._updateDisplay();
// Go to initial slide
this.goTo(this.options.start_at_slide);
this._onLoaded();
},
/* Slides
================================================== */
_addSlide:function(slide) {
slide.addTo(this._el.slider_item_container);
slide.on('added', this._onSlideAdded, this);
slide.on('background_change', this._onBackgroundChange, this);
},
_createSlide: function(d, title_slide, n) {
var slide = new TL.Slide(d, this.options, title_slide);
this._addSlide(slide);
if(n < 0) {
this._slides.push(slide);
} else {
this._slides.splice(n, 0, slide);
}
},
_createSlides: function(array) {
for (var i = 0; i < array.length; i++) {
if (array[i].unique_id == "") {
array[i].unique_id = TL.Util.unique_ID(6, "tl-slide");
}
this._createSlide(array[i], false, -1);
}
},
_removeSlide: function(slide) {
slide.removeFrom(this._el.slider_item_container);
slide.off('added', this._onSlideRemoved, this);
slide.off('background_change', this._onBackgroundChange);
},
_destroySlide: function(n) {
this._removeSlide(this._slides[n]);
this._slides.splice(n, 1);
},
_findSlideIndex: function(n) {
var _n = n;
if (typeof n == 'string' || n instanceof String) {
_n = TL.Util.findArrayNumberByUniqueID(n, this._slides, "unique_id");
}
return _n;
},
/* Public
================================================== */
updateDisplay: function(w, h, a, l) {
this._updateDisplay(w, h, a, l);
},
// Create a slide
createSlide: function(d, n) {
this._createSlide(d, false, n);
},
// Create Many Slides from an array
createSlides: function(array) {
this._createSlides(array);
},
// Destroy slide by index
destroySlide: function(n) {
this._destroySlide(n);
},
// Destroy slide by id
destroySlideId: function(id) {
this.destroySlide(this._findSlideIndex(id));
},
/* Navigation
================================================== */
goTo: function(n, fast, displayupdate) {
var self = this;
this.changeBackground({color_value:"", image:false});
// Clear Preloader Timer
if (this.preloadTimer) {
clearTimeout(this.preloadTimer);
}
// Set Slide Active State
for (var i = 0; i < this._slides.length; i++) {
this._slides[i].setActive(false);
}
if (n < this._slides.length && n >= 0) {
this.current_id = this._slides[n].data.unique_id;
// Stop animation
if (this.animator) {
this.animator.stop();
}
if (this._swipable) {
this._swipable.stopMomentum();
}
if (fast) {
this._el.slider_container.style.left = -(this.slide_spacing * n) + "px";
this._onSlideChange(displayupdate);
} else {
this.animator = TL.Animate(this._el.slider_container, {
left: -(this.slide_spacing * n) + "px",
duration: this.options.duration,
easing: this.options.ease,
complete: this._onSlideChange(displayupdate)
});
}
// Set Slide Active State
this._slides[n].setActive(true);
// Update Navigation and Info
if (this._slides[n + 1]) {
this.showNav(this._nav.next, true);
this._nav.next.update(this._slides[n + 1]);
} else {
this.showNav(this._nav.next, false);
}
if (this._slides[n - 1]) {
this.showNav(this._nav.previous, true);
this._nav.previous.update(this._slides[n - 1]);
} else {
this.showNav(this._nav.previous, false);
}
// Preload Slides
this.preloadTimer = setTimeout(function() {
self.preloadSlides(n);
}, this.options.duration);
}
},
goToId: function(id, fast, displayupdate) {
this.goTo(this._findSlideIndex(id), fast, displayupdate);
},
preloadSlides: function(n) {
if (this._slides[n + 1]) {
this._slides[n + 1].loadMedia();
this._slides[n + 1].scrollToTop();
}
if (this._slides[n + 2]) {
this._slides[n + 2].loadMedia();
this._slides[n + 2].scrollToTop();
}
if (this._slides[n - 1]) {
this._slides[n - 1].loadMedia();
this._slides[n - 1].scrollToTop();
}
if (this._slides[n - 2]) {
this._slides[n - 2].loadMedia();
this._slides[n - 2].scrollToTop();
}
},
next: function() {
var n = this._findSlideIndex(this.current_id);
if ((n + 1) < (this._slides.length)) {
this.goTo(n + 1);
} else {
this.goTo(n);
}
},
previous: function() {
var n = this._findSlideIndex(this.current_id);
if (n - 1 >= 0) {
this.goTo(n - 1);
} else {
this.goTo(n);
}
},
showNav: function(nav_obj, show) {
if (this.options.width <= 500 && TL.Browser.mobile) {
} else {
if (show) {
nav_obj.show();
} else {
nav_obj.hide();
}
}
},
changeBackground: function(bg) {
var bg_color = {r:256, g:256, b:256},
bg_color_rgb;
if (bg.color_value && bg.color_value != "") {
bg_color = TL.Util.hexToRgb(bg.color_value);
if (!bg_color) {
trace("Invalid color value " + bg.color_value);
bg_color = this.options.default_bg_color;
}
} else {
bg_color = this.options.default_bg_color;
bg.color_value = "rgb(" + bg_color.r + " , " + bg_color.g + ", " + bg_color.b + ")";
}
bg_color_rgb = bg_color.r + "," + bg_color.g + "," + bg_color.b;
this._el.background.style.backgroundImage = "none";
if (bg.color_value) {
this._el.background.style.backgroundColor = bg.color_value;
} else {
this._el.background.style.backgroundColor = "transparent";
}
if (bg_color.r < 255 || bg_color.g < 255 || bg_color.b < 255 || bg.image) {
this._nav.next.setColor(true);
this._nav.previous.setColor(true);
} else {
this._nav.next.setColor(false);
this._nav.previous.setColor(false);
}
},
/* Private Methods
================================================== */
// Update Display
_updateDisplay: function(width, height, animate, layout) {
var nav_pos, _layout;
if(typeof layout === 'undefined'){
_layout = this.options.layout;
} else {
_layout = layout;
}
this.options.layout = _layout;
this.slide_spacing = this.options.width*2;
if (width) {
this.options.width = width;
} else {
this.options.width = this._el.container.offsetWidth;
}
if (height) {
this.options.height = height;
} else {
this.options.height = this._el.container.offsetHeight;
}
//this._el.container.style.height = this.options.height;
// position navigation
nav_pos = (this.options.height/2);
this._nav.next.setPosition({top:nav_pos});
this._nav.previous.setPosition({top:nav_pos});
// Position slides
for (var i = 0; i < this._slides.length; i++) {
this._slides[i].updateDisplay(this.options.width, this.options.height, _layout);
this._slides[i].setPosition({left:(this.slide_spacing * i), top:0});
};
// Go to the current slide
this.goToId(this.current_id, true, true);
},
// Reposition and redraw slides
_updateDrawSlides: function() {
var _layout = this.options.layout;
for (var i = 0; i < this._slides.length; i++) {
this._slides[i].updateDisplay(this.options.width, this.options.height, _layout);
this._slides[i].setPosition({left:(this.slide_spacing * i), top:0});
};
this.goToId(this.current_id, true, false);
},
/* Init
================================================== */
_initLayout: function () {
this._el.container.className += ' tl-storyslider';
// Create Layout
this._el.slider_container_mask = TL.Dom.create('div', 'tl-slider-container-mask', this._el.container);
this._el.background = TL.Dom.create('div', 'tl-slider-background tl-animate', this._el.container);
this._el.slider_container = TL.Dom.create('div', 'tl-slider-container tlanimate', this._el.slider_container_mask);
this._el.slider_item_container = TL.Dom.create('div', 'tl-slider-item-container', this._el.slider_container);
// Update Size
this.options.width = this._el.container.offsetWidth;
this.options.height = this._el.container.offsetHeight;
// Create Navigation
this._nav.previous = new TL.SlideNav({title: "Previous", description: "description"}, {direction:"previous"});
this._nav.next = new TL.SlideNav({title: "Next",description: "description"}, {direction:"next"});
// add the navigation to the dom
this._nav.next.addTo(this._el.container);
this._nav.previous.addTo(this._el.container);
this._el.slider_container.style.left="0px";
if (TL.Browser.touch) {
//this._el.slider_touch_mask = TL.Dom.create('div', 'tl-slider-touch-mask', this._el.slider_container_mask);
this._swipable = new TL.Swipable(this._el.slider_container_mask, this._el.slider_container, {
enable: {x:true, y:false},
snap: true
});
this._swipable.enable();
// Message
this._message = new TL.Message({}, {
message_class: "tl-message-full",
message_icon_class: "tl-icon-swipe-left"
});
this._message.updateMessage("Swipe to Navigate<br><span class='tl-button'>OK</span>");
this._message.addTo(this._el.container);
}
},
_initEvents: function () {
this._nav.next.on('clicked', this._onNavigation, this);
this._nav.previous.on('clicked', this._onNavigation, this);
if (this._message) {
this._message.on('clicked', this._onMessageClick, this);
}
if (this._swipable) {
this._swipable.on('swipe_left', this._onNavigation, this);
this._swipable.on('swipe_right', this._onNavigation, this);
this._swipable.on('swipe_nodirection', this._onSwipeNoDirection, this);
}
},
_initData: function() {
if(this.data.title) {
this._createSlide(this.data.title, true, -1);
}
this._createSlides(this.data.events);
},
/* Events
================================================== */
_onBackgroundChange: function(e) {
var n = this._findSlideIndex(this.current_id);
var slide_background = this._slides[n].getBackground();
this.changeBackground(e);
this.fire("colorchange", slide_background);
},
_onMessageClick: function(e) {
this._message.hide();
},
_onSwipeNoDirection: function(e) {
this.goToId(this.current_id);
},
_onNavigation: function(e) {
if (e.direction == "next" || e.direction == "left") {
this.next();
} else if (e.direction == "previous" || e.direction == "right") {
this.previous();
}
this.fire("nav_" + e.direction, this.data);
},
_onSlideAdded: function(e) {
trace("slideadded")
this.fire("slideAdded", this.data);
},
_onSlideRemoved: function(e) {
this.fire("slideRemoved", this.data);
},
_onSlideChange: function(displayupdate) {
if (!displayupdate) {
this.fire("change", {unique_id: this.current_id});
}
},
_onMouseClick: function(e) {
},
_fireMouseEvent: function (e) {
if (!this._loaded) {
return;
}
var type = e.type;
type = (type === 'mouseenter' ? 'mouseover' : (type === 'mouseleave' ? 'mouseout' : type));
if (!this.hasEventListeners(type)) {
return;
}
if (type === 'contextmenu') {
TL.DomEvent.preventDefault(e);
}
this.fire(type, {
latlng: "something", //this.mouseEventToLatLng(e),
layerPoint: "something else" //this.mouseEventToLayerPoint(e)
});
},
_onLoaded: function() {
this.fire("loaded", this.data);
}
});
/* **********************************************
Begin TL.TimeNav.js
********************************************** */
/* TL.TimeNav
================================================== */
TL.TimeNav = TL.Class.extend({
includes: [TL.Events, TL.DomMixins],
_el: {},
/* Constructor
================================================== */
initialize: function (elem, timeline_config, options, init) {
// DOM ELEMENTS
this._el = {
parent: {},
container: {},
slider: {},
slider_background: {},
line: {},
marker_container_mask: {},
marker_container: {},
marker_item_container: {},
timeaxis: {},
timeaxis_background: {},
attribution: {}
};
this.collapsed = false;
if (typeof elem === 'object') {
this._el.container = elem;
} else {
this._el.container = TL.Dom.get(elem);
}
this.config = timeline_config;
//Options
this.options = {
width: 600,
height: 600,
duration: 1000,
ease: TL.Ease.easeInOutQuint,
has_groups: false,
optimal_tick_width: 50,
scale_factor: 2, // How many screen widths wide should the timeline be
marker_padding: 5,
timenav_height_min: 150, // Minimum timenav height
marker_height_min: 30, // Minimum Marker Height
marker_width_min: 100, // Minimum Marker Width
zoom_sequence: [0.5, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] // Array of Fibonacci numbers for TimeNav zoom levels http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
};
// Animation
this.animator = null;
// Markers Array
this._markers = [];
// Eras Array
this._eras = [];
this.has_eras = false;
// Groups Array
this._groups = [];
// Row Height
this._calculated_row_height = 100;
// Current Marker
this.current_id = "";
// TimeScale
this.timescale = {};
// TimeAxis
this.timeaxis = {};
this.axishelper = {};
// Max Rows
this.max_rows = 6;
// Animate CSS
this.animate_css = false;
// Swipe Object
this._swipable;
// Merge Data and Options
TL.Util.mergeData(this.options, options);
if (init) {
this.init();
}
},
init: function() {
this._initLayout();
this._initEvents();
this._initData();
this._updateDisplay();
this._onLoaded();
},
/* Public
================================================== */
positionMarkers: function() {
this._positionMarkers();
},
/* Update Display
================================================== */
updateDisplay: function(w, h, a, l) {
this._updateDisplay(w, h, a, l);
},
/* TimeScale
================================================== */
_getTimeScale: function() {
/* maybe the establishing config values (marker_height_min and max_rows) should be
separated from making a TimeScale object, which happens in another spot in this file with duplicate mapping of properties of this TimeNav into the TimeScale options object? */
// Set Max Rows
var marker_height_min = 0;
try {
marker_height_min = parseInt(this.options.marker_height_min);
} catch(e) {
trace("Invalid value for marker_height_min option.");
marker_height_min = 30;
}
if (marker_height_min == 0) {
trace("marker_height_min option must not be zero.")
marker_height_min = 30;
}
this.max_rows = Math.round((this.options.height - this._el.timeaxis_background.offsetHeight - (this.options.marker_padding)) / marker_height_min);
if (this.max_rows < 1) {
this.max_rows = 1;
}
return new TL.TimeScale(this.config, {
display_width: this._el.container.offsetWidth,
screen_multiplier: this.options.scale_factor,
max_rows: this.max_rows
});
},
_updateTimeScale: function(new_scale) {
this.options.scale_factor = new_scale;
this._updateDrawTimeline();
},
zoomIn: function() { // move the the next "higher" scale factor
var new_scale = TL.Util.findNextGreater(this.options.zoom_sequence, this.options.scale_factor);
if (new_scale == this.options.zoom_sequence[this.options.zoom_sequence.length-1]) {
this.fire("zoomtoggle", {zoom:"in", show:false});
} else {
this.fire("zoomtoggle", {zoom:"in", show:true});
}
this.setZoomFactor(new_scale);
},
zoomOut: function() { // move the the next "lower" scale factor
var new_scale = TL.Util.findNextLesser(this.options.zoom_sequence, this.options.scale_factor);
if (new_scale == this.options.zoom_sequence[0]) {
this.fire("zoomtoggle", {zoom:"out", show:false});
} else {
this.fire("zoomtoggle", {zoom:"out", show:true});
}
this.setZoomFactor(new_scale);
},
setZoom: function(level) {
var zoom_factor = this.options.zoom_sequence[level];
if (typeof(zoom_factor) == 'number') {
this.setZoomFactor(zoom_factor);
} else {
console.log("Invalid zoom level. Please use a number between 0 and " + (this.options.zoom_sequence.length - 1));
}
},
setZoomFactor: function(factor) {
this.options.scale_factor = factor;
//this._updateDrawTimeline(true);
this.goToId(this.current_id, !this._updateDrawTimeline(true), true);
},
/* Groups
================================================== */
_createGroups: function() {
var group_labels = this.timescale.getGroupLabels();
if (group_labels) {
this.options.has_groups = true;
for (var i = 0; i < group_labels.length; i++) {
this._createGroup(group_labels[i]);
}
}
},
_createGroup: function(group_label) {
var group = new TL.TimeGroup(group_label);
this._addGroup(group);
this._groups.push(group);
},
_addGroup:function(group) {
group.addTo(this._el.container);
},
_positionGroups: function() {
if (this.options.has_groups) {
var available_height = (this.options.height - this._el.timeaxis_background.offsetHeight ),
group_height = Math.floor((available_height /this.timescale.getNumberOfRows()) - this.options.marker_padding),
group_labels = this.timescale.getGroupLabels();
for (var i = 0, group_rows = 0; i < this._groups.length; i++) {
var group_y = Math.floor(group_rows * (group_height + this.options.marker_padding));
this._groups[i].setRowPosition(group_y, this._calculated_row_height + this.options.marker_padding/2);
this._groups[i].setAlternateRowColor(TL.Util.isEven(i));
group_rows += this._groups[i].data.rows; // account for groups spanning multiple rows
}
}
},
/* Markers
================================================== */
_addMarker:function(marker) {
marker.addTo(this._el.marker_item_container);
marker.on('markerclick', this._onMarkerClick, this);
marker.on('added', this._onMarkerAdded, this);
},
_createMarker: function(data, n) {
var marker = new TL.TimeMarker(data, this.options);
this._addMarker(marker);
if(n < 0) {
this._markers.push(marker);
} else {
this._markers.splice(n, 0, marker);
}
},
_createMarkers: function(array) {
for (var i = 0; i < array.length; i++) {
this._createMarker(array[i], -1);
}
},
_removeMarker: function(marker) {
marker.removeFrom(this._el.marker_item_container);
//marker.off('added', this._onMarkerRemoved, this);
},
_destroyMarker: function(n) {
this._removeMarker(this._markers[n]);
this._markers.splice(n, 1);
},
_positionMarkers: function(fast) {
// POSITION X
for (var i = 0; i < this._markers.length; i++) {
var pos = this.timescale.getPositionInfo(i);
if (fast) {
this._markers[i].setClass("tl-timemarker tl-timemarker-fast");
} else {
this._markers[i].setClass("tl-timemarker");
}
this._markers[i].setPosition({left:pos.start});
this._markers[i].setWidth(pos.width);
};
},
_assignRowsToMarkers: function() {
var available_height = (this.options.height - this._el.timeaxis_background.offsetHeight - (this.options.marker_padding)),
marker_height = Math.floor((available_height /this.timescale.getNumberOfRows()) - this.options.marker_padding);
this._calculated_row_height = Math.floor(available_height /this.timescale.getNumberOfRows());
for (var i = 0; i < this._markers.length; i++) {
// Set Height
this._markers[i].setHeight(marker_height);
//Position by Row
var row = this.timescale.getPositionInfo(i).row;
var marker_y = Math.floor(row * (marker_height + this.options.marker_padding)) + this.options.marker_padding;
var remainder_height = available_height - marker_y + this.options.marker_padding;
this._markers[i].setRowPosition(marker_y, remainder_height);
};
},
_resetMarkersActive: function() {
for (var i = 0; i < this._markers.length; i++) {
this._markers[i].setActive(false);
};
},
_findMarkerIndex: function(n) {
var _n = -1;
if (typeof n == 'string' || n instanceof String) {
_n = TL.Util.findArrayNumberByUniqueID(n, this._markers, "unique_id", _n);
}
return _n;
},
/* ERAS
================================================== */
_createEras: function(array) {
for (var i = 0; i < array.length; i++) {
this._createEra(array[i], -1);
}
},
_createEra: function(data, n) {
var era = new TL.TimeEra(data, this.options);
this._addEra(era);
if(n < 0) {
this._eras.push(era);
} else {
this._eras.splice(n, 0, era);
}
},
_addEra:function(era) {
era.addTo(this._el.marker_item_container);
era.on('added', this._onEraAdded, this);
},
_removeEra: function(era) {
era.removeFrom(this._el.marker_item_container);
//marker.off('added', this._onMarkerRemoved, this);
},
_destroyEra: function(n) {
this._removeEra(this._eras[n]);
this._eras.splice(n, 1);
},
_positionEras: function(fast) {
// POSITION X
for (var i = 0; i < this._eras.length; i++) {
var pos = {
start:0,
end:0,
width:0
};
pos.start = this.timescale.getPosition(this._eras[i].data.start_date.getTime());
pos.end = this.timescale.getPosition(this._eras[i].data.end_date.getTime());
pos.width = pos.end - pos.start;
if (fast) {
this._eras[i].setClass("tl-timeera tl-timeera-fast");
} else {
this._eras[i].setClass("tl-timeera");
}
this._eras[i].setPosition({left:pos.start});
this._eras[i].setWidth(pos.width);
this._eras[i].setColor(i);
};
},
/* Public
================================================== */
// Create a marker
createMarker: function(d, n) {
this._createMarker(d, n);
},
// Create many markers from an array
createMarkers: function(array) {
this._createMarkers(array);
},
// Destroy marker by index
destroyMarker: function(n) {
this._destroyMarker(n);
},
// Destroy marker by id
destroyMarkerId: function(id) {
this.destroyMarker(this._findMarkerIndex(id));
},
/* Navigation
================================================== */
goTo: function(n, fast, css_animation) {
var self = this,
_ease = this.options.ease,
_duration = this.options.duration,
_n = (n < 0) ? 0 : n;
// Set Marker active state
this._resetMarkersActive();
if(n >= 0 && n < this._markers.length) {
this._markers[n].setActive(true);
}
// Stop animation
if (this.animator) {
this.animator.stop();
}
if (fast) {
this._el.slider.className = "tl-timenav-slider";
this._el.slider.style.left = -this._markers[_n].getLeft() + (this.options.width/2) + "px";
} else {
if (css_animation) {
this._el.slider.className = "tl-timenav-slider tl-timenav-slider-animate";
this.animate_css = true;
this._el.slider.style.left = -this._markers[_n].getLeft() + (this.options.width/2) + "px";
} else {
this._el.slider.className = "tl-timenav-slider";
this.animator = TL.Animate(this._el.slider, {
left: -this._markers[_n].getLeft() + (this.options.width/2) + "px",
duration: _duration,
easing: _ease
});
}
}
if(n >= 0 && n < this._markers.length) {
this.current_id = this._markers[n].data.unique_id;
} else {
this.current_id = '';
}
},
goToId: function(id, fast, css_animation) {
this.goTo(this._findMarkerIndex(id), fast, css_animation);
},
/* Events
================================================== */
_onLoaded: function() {
this.fire("loaded", this.config);
},
_onMarkerAdded: function(e) {
this.fire("dateAdded", this.config);
},
_onEraAdded: function(e) {
this.fire("eraAdded", this.config);
},
_onMarkerRemoved: function(e) {
this.fire("dateRemoved", this.config);
},
_onMarkerClick: function(e) {
// Go to the clicked marker
this.goToId(e.unique_id);
this.fire("change", {unique_id: e.unique_id});
},
_onMouseScroll: function(e) {
var delta = 0,
scroll_to = 0,
constraint = {
right: -(this.timescale.getPixelWidth() - (this.options.width/2)),
left: this.options.width/2
};
if (!e) {
e = window.event;
}
if (e.originalEvent) {
e = e.originalEvent;
}
// Webkit and browsers able to differntiate between up/down and left/right scrolling
if (typeof e.wheelDeltaX != 'undefined' ) {
delta = e.wheelDeltaY/6;
if (Math.abs(e.wheelDeltaX) > Math.abs(e.wheelDeltaY)) {
delta = e.wheelDeltaX/6;
} else {
//delta = e.wheelDeltaY/6;
delta = 0;
}
}
if (delta) {
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
// Stop from scrolling too far
scroll_to = parseInt(this._el.slider.style.left.replace("px", "")) + delta;
if (scroll_to > constraint.left) {
scroll_to = constraint.left;
} else if (scroll_to < constraint.right) {
scroll_to = constraint.right;
}
if (this.animate_css) {
this._el.slider.className = "tl-timenav-slider";
this.animate_css = false;
}
this._el.slider.style.left = scroll_to + "px";
},
_onDragMove: function(e) {
if (this.animate_css) {
this._el.slider.className = "tl-timenav-slider";
this.animate_css = false;
}
},
/* Private Methods
================================================== */
// Update Display
_updateDisplay: function(width, height, animate) {
if (width) {
this.options.width = width;
}
if (height && height != this.options.height) {
this.options.height = height;
this.timescale = this._getTimeScale();
}
// Size Markers
this._assignRowsToMarkers();
// Size swipable area
this._el.slider_background.style.width = this.timescale.getPixelWidth() + this.options.width + "px";
this._el.slider_background.style.left = -(this.options.width/2) + "px";
this._el.slider.style.width = this.timescale.getPixelWidth() + this.options.width + "px";
// Update Swipable constraint
this._swipable.updateConstraint({top: false,bottom: false,left: (this.options.width/2),right: -(this.timescale.getPixelWidth() - (this.options.width/2))});
// Go to the current slide
this.goToId(this.current_id, true);
},
_drawTimeline: function(fast) {
this.timescale = this._getTimeScale();
this.timeaxis.drawTicks(this.timescale, this.options.optimal_tick_width);
this._positionMarkers(fast);
this._assignRowsToMarkers();
this._createGroups();
this._positionGroups();
if (this.has_eras) {
this._positionEras(fast);
}
},
_updateDrawTimeline: function(check_update) {
var do_update = false;
// Check to see if redraw is needed
if (check_update) {
/* keep this aligned with _getTimeScale or reduce code duplication */
var temp_timescale = new TL.TimeScale(this.config, {
display_width: this._el.container.offsetWidth,
screen_multiplier: this.options.scale_factor,
max_rows: this.max_rows
});
if (this.timescale.getMajorScale() == temp_timescale.getMajorScale()
&& this.timescale.getMinorScale() == temp_timescale.getMinorScale()) {
do_update = true;
}
} else {
do_update = true;
}
// Perform update or redraw
if (do_update) {
this.timescale = this._getTimeScale();
this.timeaxis.positionTicks(this.timescale, this.options.optimal_tick_width);
this._positionMarkers();
this._assignRowsToMarkers();
this._positionGroups();
if (this.has_eras) {
this._positionEras();
}
this._updateDisplay();
} else {
this._drawTimeline(true);
}
return do_update;
},
/* Init
================================================== */
_initLayout: function () {
// Create Layout
this._el.attribution = TL.Dom.create('div', 'tl-attribution', this._el.container);
this._el.line = TL.Dom.create('div', 'tl-timenav-line', this._el.container);
this._el.slider = TL.Dom.create('div', 'tl-timenav-slider', this._el.container);
this._el.slider_background = TL.Dom.create('div', 'tl-timenav-slider-background', this._el.slider);
this._el.marker_container_mask = TL.Dom.create('div', 'tl-timenav-container-mask', this._el.slider);
this._el.marker_container = TL.Dom.create('div', 'tl-timenav-container', this._el.marker_container_mask);
this._el.marker_item_container = TL.Dom.create('div', 'tl-timenav-item-container', this._el.marker_container);
this._el.timeaxis = TL.Dom.create('div', 'tl-timeaxis', this._el.slider);
this._el.timeaxis_background = TL.Dom.create('div', 'tl-timeaxis-background', this._el.container);
// Knight Lab Logo
this._el.attribution.innerHTML = "<a href='http://timeline.knightlab.com' target='_blank'><span class='tl-knightlab-logo'></span>Timeline JS</a>"
// Time Axis
this.timeaxis = new TL.TimeAxis(this._el.timeaxis, this.options);
// Swipable
this._swipable = new TL.Swipable(this._el.slider_background, this._el.slider, {
enable: {x:true, y:false},
constraint: {top: false,bottom: false,left: (this.options.width/2),right: false},
snap: false
});
this._swipable.enable();
},
_initEvents: function () {
// Drag Events
this._swipable.on('dragmove', this._onDragMove, this);
// Scroll Events
TL.DomEvent.addListener(this._el.container, 'mousewheel', this._onMouseScroll, this);
TL.DomEvent.addListener(this._el.container, 'DOMMouseScroll', this._onMouseScroll, this);
},
_initData: function() {
// Create Markers and then add them
this._createMarkers(this.config.events);
if (this.config.eras) {
this.has_eras = true;
this._createEras(this.config.eras);
}
this._drawTimeline();
}
});
/* **********************************************
Begin TL.TimeMarker.js
********************************************** */
/* TL.TimeMarker
================================================== */
TL.TimeMarker = TL.Class.extend({
includes: [TL.Events, TL.DomMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(data, options) {
// DOM Elements
this._el = {
container: {},
content_container: {},
media_container: {},
timespan: {},
line_left: {},
line_right: {},
content: {},
text: {},
media: {},
};
// Components
this._text = {};
// State
this._state = {
loaded: false
};
// Data
this.data = {
unique_id: "",
background: null,
date: {
year: 0,
month: 0,
day: 0,
hour: 0,
minute: 0,
second: 0,
millisecond: 0,
thumbnail: "",
format: ""
},
text: {
headline: "",
text: ""
},
media: null
};
// Options
this.options = {
duration: 1000,
ease: TL.Ease.easeInSpline,
width: 600,
height: 600,
marker_width_min: 100 // Minimum Marker Width
};
// Actively Displaying
this.active = false;
// Animation Object
this.animator = {};
// End date
this.has_end_date = false;
// Merge Data and Options
TL.Util.mergeData(this.options, options);
TL.Util.mergeData(this.data, data);
this._initLayout();
this._initEvents();
},
/* Adding, Hiding, Showing etc
================================================== */
show: function() {
},
hide: function() {
},
setActive: function(is_active) {
this.active = is_active;
if (this.active && this.has_end_date) {
this._el.container.className = 'tl-timemarker tl-timemarker-with-end tl-timemarker-active';
} else if (this.active){
this._el.container.className = 'tl-timemarker tl-timemarker-active';
} else if (this.has_end_date){
this._el.container.className = 'tl-timemarker tl-timemarker-with-end';
} else {
this._el.container.className = 'tl-timemarker';
}
},
addTo: function(container) {
container.appendChild(this._el.container);
},
removeFrom: function(container) {
container.removeChild(this._el.container);
},
updateDisplay: function(w, h) {
this._updateDisplay(w, h);
},
loadMedia: function() {
if (this._media && !this._state.loaded) {
this._media.loadMedia();
this._state.loaded = true;
}
},
stopMedia: function() {
if (this._media && this._state.loaded) {
this._media.stopMedia();
}
},
getLeft: function() {
return this._el.container.style.left.slice(0, -2);
},
getTime: function() { // TODO does this need to know about the end date?
return this.data.start_date.getTime();
},
getEndTime: function() {
if (this.data.end_date) {
return this.data.end_date.getTime();
} else {
return false;
}
},
setHeight: function(h) {
var text_line_height = 12,
text_lines = 1;
this._el.content_container.style.height = h + "px";
this._el.timespan_content.style.height = h + "px";
// Handle Line height for better display of text
if (h <= 30) {
this._el.content.className = "tl-timemarker-content tl-timemarker-content-small";
} else {
this._el.content.className = "tl-timemarker-content";
}
if (h <= 56) {
TL.DomUtil.addClass(this._el.content_container, "tl-timemarker-content-container-small");
} else {
TL.DomUtil.removeClass(this._el.content_container, "tl-timemarker-content-container-small");
}
// Handle number of lines visible vertically
if (TL.Browser.webkit) {
text_lines = Math.floor(h / (text_line_height + 2));
if (text_lines < 1) {
text_lines = 1;
}
this._text.className = "tl-headline";
this._text.style.webkitLineClamp = text_lines;
} else {
text_lines = h / text_line_height;
if (text_lines > 1) {
this._text.className = "tl-headline tl-headline-fadeout";
} else {
this._text.className = "tl-headline";
}
this._text.style.height = (text_lines * text_line_height) + "px";
}
},
setWidth: function(w) {
if (this.data.end_date) {
this._el.container.style.width = w + "px";
if (w > this.options.marker_width_min) {
this._el.content_container.style.width = w + "px";
this._el.content_container.className = "tl-timemarker-content-container tl-timemarker-content-container-long";
} else {
this._el.content_container.style.width = this.options.marker_width_min + "px";
this._el.content_container.className = "tl-timemarker-content-container";
}
}
},
setClass: function(n) {
this._el.container.className = n;
},
setRowPosition: function(n, remainder) {
this.setPosition({top:n});
this._el.timespan.style.height = remainder + "px";
if (remainder < 56) {
//TL.DomUtil.removeClass(this._el.content_container, "tl-timemarker-content-container-small");
}
},
/* Events
================================================== */
_onMarkerClick: function(e) {
this.fire("markerclick", {unique_id:this.data.unique_id});
},
/* Private Methods
================================================== */
_initLayout: function () {
//trace(this.data)
// Create Layout
this._el.container = TL.Dom.create("div", "tl-timemarker");
if (this.data.unique_id) {
this._el.container.id = this.data.unique_id + "-marker";
}
if (this.data.end_date) {
this.has_end_date = true;
this._el.container.className = 'tl-timemarker tl-timemarker-with-end';
}
this._el.timespan = TL.Dom.create("div", "tl-timemarker-timespan", this._el.container);
this._el.timespan_content = TL.Dom.create("div", "tl-timemarker-timespan-content", this._el.timespan);
this._el.content_container = TL.Dom.create("div", "tl-timemarker-content-container", this._el.container);
this._el.content = TL.Dom.create("div", "tl-timemarker-content", this._el.content_container);
this._el.line_left = TL.Dom.create("div", "tl-timemarker-line-left", this._el.timespan);
this._el.line_right = TL.Dom.create("div", "tl-timemarker-line-right", this._el.timespan);
// Thumbnail or Icon
if (this.data.media) {
this._el.media_container = TL.Dom.create("div", "tl-timemarker-media-container", this._el.content);
if (this.data.media.thumbnail && this.data.media.thumbnail != "") {
this._el.media = TL.Dom.create("img", "tl-timemarker-media", this._el.media_container);
this._el.media.src = TL.Util.transformImageURL(this.data.media.thumbnail);
} else {
var media_type = TL.MediaType(this.data.media).type;
this._el.media = TL.Dom.create("span", "tl-icon-" + media_type, this._el.media_container);
}
}
// Text
this._el.text = TL.Dom.create("div", "tl-timemarker-text", this._el.content);
this._text = TL.Dom.create("h2", "tl-headline", this._el.text);
if (this.data.text.headline && this.data.text.headline != "") {
this._text.innerHTML = TL.Util.unlinkify(this.data.text.headline);
} else if (this.data.text.text && this.data.text.text != "") {
this._text.innerHTML = TL.Util.unlinkify(this.data.text.text);
} else if (this.data.media.caption && this.data.media.caption != "") {
this._text.innerHTML = TL.Util.unlinkify(this.data.media.caption);
}
// Fire event that the slide is loaded
this.onLoaded();
},
_initEvents: function() {
TL.DomEvent.addListener(this._el.container, 'click', this._onMarkerClick, this);
},
// Update Display
_updateDisplay: function(width, height, layout) {
if (width) {
this.options.width = width;
}
if (height) {
this.options.height = height;
}
}
});
/* **********************************************
Begin TL.TimeEra.js
********************************************** */
/* TL.TimeMarker
================================================== */
TL.TimeEra = TL.Class.extend({
includes: [TL.Events, TL.DomMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(data, options) {
// DOM Elements
this._el = {
container: {},
background: {},
content_container: {},
content: {},
text: {}
};
// Components
this._text = {};
// State
this._state = {
loaded: false
};
// Data
this.data = {
unique_id: "",
date: {
year: 0,
month: 0,
day: 0,
hour: 0,
minute: 0,
second: 0,
millisecond: 0,
thumbnail: "",
format: ""
},
text: {
headline: "",
text: ""
}
};
// Options
this.options = {
duration: 1000,
ease: TL.Ease.easeInSpline,
width: 600,
height: 600,
marker_width_min: 100 // Minimum Marker Width
};
// Actively Displaying
this.active = false;
// Animation Object
this.animator = {};
// End date
this.has_end_date = false;
// Merge Data and Options
TL.Util.mergeData(this.options, options);
TL.Util.mergeData(this.data, data);
this._initLayout();
this._initEvents();
},
/* Adding, Hiding, Showing etc
================================================== */
show: function() {
},
hide: function() {
},
setActive: function(is_active) {
},
addTo: function(container) {
container.appendChild(this._el.container);
},
removeFrom: function(container) {
container.removeChild(this._el.container);
},
updateDisplay: function(w, h) {
this._updateDisplay(w, h);
},
getLeft: function() {
return this._el.container.style.left.slice(0, -2);
},
getTime: function() { // TODO does this need to know about the end date?
return this.data.start_date.getTime();
},
getEndTime: function() {
if (this.data.end_date) {
return this.data.end_date.getTime();
} else {
return false;
}
},
setHeight: function(h) {
var text_line_height = 12,
text_lines = 1;
this._el.content_container.style.height = h + "px";
this._el.content.className = "tl-timeera-content";
// Handle number of lines visible vertically
if (TL.Browser.webkit) {
text_lines = Math.floor(h / (text_line_height + 2));
if (text_lines < 1) {
text_lines = 1;
}
this._text.className = "tl-headline";
this._text.style.webkitLineClamp = text_lines;
} else {
text_lines = h / text_line_height;
if (text_lines > 1) {
this._text.className = "tl-headline tl-headline-fadeout";
} else {
this._text.className = "tl-headline";
}
this._text.style.height = (text_lines * text_line_height) + "px";
}
},
setWidth: function(w) {
if (this.data.end_date) {
this._el.container.style.width = w + "px";
if (w > this.options.marker_width_min) {
this._el.content_container.style.width = w + "px";
this._el.content_container.className = "tl-timeera-content-container tl-timeera-content-container-long";
} else {
this._el.content_container.style.width = this.options.marker_width_min + "px";
this._el.content_container.className = "tl-timeera-content-container";
}
}
},
setClass: function(n) {
this._el.container.className = n;
},
setRowPosition: function(n, remainder) {
this.setPosition({top:n});
if (remainder < 56) {
//TL.DomUtil.removeClass(this._el.content_container, "tl-timeera-content-container-small");
}
},
setColor: function(color_num) {
this._el.container.className = 'tl-timeera tl-timeera-color' + color_num;
},
/* Events
================================================== */
/* Private Methods
================================================== */
_initLayout: function () {
//trace(this.data)
// Create Layout
this._el.container = TL.Dom.create("div", "tl-timeera");
if (this.data.unique_id) {
this._el.container.id = this.data.unique_id + "-era";
}
if (this.data.end_date) {
this.has_end_date = true;
this._el.container.className = 'tl-timeera tl-timeera-with-end';
}
this._el.content_container = TL.Dom.create("div", "tl-timeera-content-container", this._el.container);
this._el.background = TL.Dom.create("div", "tl-timeera-background", this._el.content_container);
this._el.content = TL.Dom.create("div", "tl-timeera-content", this._el.content_container);
// Text
this._el.text = TL.Dom.create("div", "tl-timeera-text", this._el.content);
this._text = TL.Dom.create("h2", "tl-headline", this._el.text);
if (this.data.text.headline && this.data.text.headline != "") {
this._text.innerHTML = TL.Util.unlinkify(this.data.text.headline);
}
// Fire event that the slide is loaded
this.onLoaded();
},
_initEvents: function() {
},
// Update Display
_updateDisplay: function(width, height, layout) {
if (width) {
this.options.width = width;
}
if (height) {
this.options.height = height;
}
}
});
/* **********************************************
Begin TL.TimeGroup.js
********************************************** */
/* TL.TimeGroup
================================================== */
TL.TimeGroup = TL.Class.extend({
includes: [TL.Events, TL.DomMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(data) {
// DOM ELEMENTS
this._el = {
parent: {},
container: {},
message: {}
};
//Options
this.options = {
width: 600,
height: 600
};
// Data
this.data = {
label: "",
rows: 1
};
this._el.container = TL.Dom.create("div", "tl-timegroup");
// Merge Data
TL.Util.mergeData(this.data, data);
// Animation
this.animator = {};
this._initLayout();
this._initEvents();
},
/* Public
================================================== */
/* Update Display
================================================== */
updateDisplay: function(w, h) {
},
setRowPosition: function(n, h) {
this.options.height = h * this.data.rows;
this.setPosition({top:n});
this._el.container.style.height = this.options.height + "px";
},
setAlternateRowColor: function(alternate) {
if (alternate) {
this._el.container.className = "tl-timegroup tl-timegroup-alternate";
} else {
this._el.container.className = "tl-timegroup";
}
},
/* Events
================================================== */
_onMouseClick: function() {
this.fire("clicked", this.options);
},
/* Private Methods
================================================== */
_initLayout: function () {
// Create Layout
this._el.message = TL.Dom.create("div", "tl-timegroup-message", this._el.container);
this._el.message.innerHTML = this.data.label;
},
_initEvents: function () {
TL.DomEvent.addListener(this._el.container, 'click', this._onMouseClick, this);
},
// Update Display
_updateDisplay: function(width, height, animate) {
}
});
/* **********************************************
Begin TL.TimeScale.js
********************************************** */
/* TL.TimeScale
Strategies for laying out the timenav
make a new one if the slides change
TODOS: deal with clustering
================================================== */
TL.TimeScale = TL.Class.extend({
initialize: function (timeline_config, options) {
var slides = timeline_config.events;
this._scale = timeline_config.scale;
options = TL.Util.mergeData({ // establish defaults
display_width: 500,
screen_multiplier: 3,
max_rows: null
}, options);
this._display_width = options.display_width;
this._screen_multiplier = options.screen_multiplier;
this._pixel_width = this._screen_multiplier * this._display_width;
this._group_labels = undefined;
this._positions = [];
this._pixels_per_milli = 0;
this._earliest = timeline_config.getEarliestDate().getTime();
this._latest = timeline_config.getLatestDate().getTime();
this._span_in_millis = this._latest - this._earliest;
if (this._span_in_millis <= 0) {
this._span_in_millis = this._computeDefaultSpan(timeline_config);
}
this._average = (this._span_in_millis)/slides.length;
this._pixels_per_milli = this.getPixelWidth() / this._span_in_millis;
this._axis_helper = TL.AxisHelper.getBestHelper(this);
this._scaled_padding = (1/this.getPixelsPerTick()) * (this._display_width/2)
this._computePositionInfo(slides, options.max_rows);
},
_computeDefaultSpan: function(timeline_config) {
// this gets called when all events are at the same instant,
// or maybe when the span_in_millis is > 0 but still below a desired threshold
// TODO: does this need smarts about eras?
if (timeline_config.scale == 'human') {
var formats = {}
for (var i = 0; i < timeline_config.events.length; i++) {
var fmt = timeline_config.events[i].start_date.findBestFormat();
formats[fmt] = (formats[fmt]) ? formats[fmt] + 1 : 1;
};
for (var i = TL.Date.SCALES.length - 1; i >= 0; i--) {
if (formats.hasOwnProperty(TL.Date.SCALES[i][0])) {
var scale = TL.Date.SCALES[TL.Date.SCALES.length - 1]; // default
if (TL.Date.SCALES[i+1]) {
scale = TL.Date.SCALES[i+1]; // one larger than the largest in our data
}
return scale[1]
}
};
return 365 * 24 * 60 * 60 * 1000; // default to a year?
}
return 200000; // what is the right handling for cosmo dates?
},
getGroupLabels: function() { /*
return an array of objects, one per group, in the order (top to bottom) that the groups are expected to appear. Each object will have two properties:
* label (the string as specified in one or more 'group' properties of events in the configuration)
* rows (the number of rows occupied by events associated with the label. )
*/
return (this._group_labels || []);
},
getScale: function() {
return this._scale;
},
getNumberOfRows: function() {
return this._number_of_rows
},
getPixelWidth: function() {
return this._pixel_width;
},
getPosition: function(time_in_millis) {
// be careful using millis, as they won't scale to cosmological time.
// however, we're moving to make the arg to this whatever value
// comes from TL.Date.getTime() which could be made smart about that --
// so it may just be about the naming.
return ( time_in_millis - this._earliest ) * this._pixels_per_milli
},
getPositionInfo: function(idx) {
return this._positions[idx];
},
getPixelsPerTick: function() {
return this._axis_helper.getPixelsPerTick(this._pixels_per_milli);
},
getTicks: function() {
return {
major: this._axis_helper.getMajorTicks(this),
minor: this._axis_helper.getMinorTicks(this) }
},
getDateFromTime: function(t) {
if(this._scale == 'human') {
return new TL.Date(t);
} else if(this._scale == 'cosmological') {
return new TL.BigDate(new TL.BigYear(t));
}
throw("Don't know how to get date from time for "+this._scale);
},
getMajorScale: function() {
return this._axis_helper.major.name;
},
getMinorScale: function() {
return this._axis_helper.minor.name;
},
_assessGroups: function(slides) {
var groups = [];
var empty_group = false;
for (var i = 0; i < slides.length; i++) {
if(slides[i].group) {
if(groups.indexOf(slides[i].group) < 0) {
groups.push(slides[i].group);
} else {
empty_group = true;
}
}
};
if (groups.length && empty_group) {
groups.push('');
}
return groups;
},
/* Compute the marker row positions, minimizing the number of
overlaps.
@positions = list of objects from this._positions
@rows_left = number of rows available (assume > 0)
*/
_computeRowInfo: function(positions, rows_left) {
var lasts_in_row = [];
var n_overlaps = 0;
for (var i = 0; i < positions.length; i++) {
var pos_info = positions[i];
var overlaps = [];
// See if we can add item to an existing row without
// overlapping the previous item in that row
delete pos_info.row;
for (var j = 0; j < lasts_in_row.length; j++) {
overlaps.push(lasts_in_row[j].end - pos_info.start);
if(overlaps[j] <= 0) {
pos_info.row = j;
lasts_in_row[j] = pos_info;
break;
}
}
// If we couldn't add to an existing row without overlap...
if (typeof(pos_info.row) == 'undefined') {
if (rows_left === null) {
// Make a new row
pos_info.row = lasts_in_row.length;
lasts_in_row.push(pos_info);
} else if (rows_left > 0) {
// Make a new row
pos_info.row = lasts_in_row.length;
lasts_in_row.push(pos_info);
rows_left--;
} else {
// Add to existing row with minimum overlap.
var min_overlap = Math.min.apply(null, overlaps);
var idx = overlaps.indexOf(min_overlap);
pos_info.row = idx;
if (pos_info.end > lasts_in_row[idx].end) {
lasts_in_row[idx] = pos_info;
}
n_overlaps++;
}
}
}
return {n_rows: lasts_in_row.length, n_overlaps: n_overlaps};
},
/* Compute marker positions. If using groups, this._number_of_rows
will never be less than the number of groups.
@max_rows = total number of available rows
@default_marker_width should be in pixels
*/
_computePositionInfo: function(slides, max_rows, default_marker_width) {
default_marker_width = default_marker_width || 100;
var groups = [];
var empty_group = false;
// Set start/end/width; enumerate groups
for (var i = 0; i < slides.length; i++) {
var pos_info = {
start: this.getPosition(slides[i].start_date.getTime())
};
this._positions.push(pos_info);
if (typeof(slides[i].end_date) != 'undefined') {
var end_pos = this.getPosition(slides[i].end_date.getTime());
pos_info.width = end_pos - pos_info.start;
if (pos_info.width > default_marker_width) {
pos_info.end = pos_info.start + pos_info.width;
} else {
pos_info.end = pos_info.start + default_marker_width;
}
} else {
pos_info.width = default_marker_width;
pos_info.end = pos_info.start + default_marker_width;
}
if(slides[i].group) {
if(groups.indexOf(slides[i].group) < 0) {
groups.push(slides[i].group);
}
} else {
empty_group = true;
}
}
if(!(groups.length)) {
var result = this._computeRowInfo(this._positions, max_rows);
this._number_of_rows = result.n_rows;
} else {
if(empty_group) {
groups.push("");
}
// Init group info
var group_info = [];
for(var i = 0; i < groups.length; i++) {
group_info[i] = {
label: groups[i],
idx: i,
positions: [],
n_rows: 1, // default
n_overlaps: 0
};
}
for(var i = 0; i < this._positions.length; i++) {
var pos_info = this._positions[i];
pos_info.group = groups.indexOf(slides[i].group || "");
pos_info.row = 0;
var gi = group_info[pos_info.group];
for(var j = gi.positions.length - 1; j >= 0; j--) {
if(gi.positions[j].end > pos_info.start) {
gi.n_overlaps++;
}
}
gi.positions.push(pos_info);
}
var n_rows = groups.length; // start with 1 row per group
while(true) {
// Count free rows available
var rows_left = Math.max(0, max_rows - n_rows);
if(!rows_left) {
break; // no free rows, nothing to do
}
// Sort by # overlaps, idx
group_info.sort(function(a, b) {
if(a.n_overlaps > b.n_overlaps) {
return -1;
} else if(a.n_overlaps < b.n_overlaps) {
return 1;
}
return a.idx - b.idx;
});
if(!group_info[0].n_overlaps) {
break; // no overlaps, nothing to do
}
// Distribute free rows among groups with overlaps
var n_rows = 0;
for(var i = 0; i < group_info.length; i++) {
var gi = group_info[i];
if(gi.n_overlaps && rows_left) {
var res = this._computeRowInfo(gi.positions, gi.n_rows + 1);
gi.n_rows = res.n_rows; // update group info
gi.n_overlaps = res.n_overlaps;
rows_left--; // update rows left
}
n_rows += gi.n_rows; // update rows used
}
}
// Set number of rows
this._number_of_rows = n_rows;
// Set group labels; offset row positions
this._group_labels = [];
group_info.sort(function(a, b) {return a.idx - b.idx; });
for(var i = 0, row_offset = 0; i < group_info.length; i++) {
this._group_labels.push({
label: group_info[i].label,
rows: group_info[i].n_rows
});
for(var j = 0; j < group_info[i].positions.length; j++) {
var pos_info = group_info[i].positions[j];
pos_info.row += row_offset;
}
row_offset += group_info[i].n_rows;
}
}
}
});
/* **********************************************
Begin TL.TimeAxis.js
********************************************** */
/* TL.TimeAxis
Display element for showing timescale ticks
================================================== */
TL.TimeAxis = TL.Class.extend({
includes: [TL.Events, TL.DomMixins, TL.I18NMixins],
_el: {},
/* Constructor
================================================== */
initialize: function(elem, options) {
// DOM Elements
this._el = {
container: {},
content_container: {},
major: {},
minor: {},
};
// Components
this._text = {};
// State
this._state = {
loaded: false
};
// Data
this.data = {};
// Options
this.options = {
duration: 1000,
ease: TL.Ease.easeInSpline,
width: 600,
height: 600
};
// Actively Displaying
this.active = false;
// Animation Object
this.animator = {};
// Axis Helper
this.axis_helper = {};
// Minor tick dom element array
this.minor_ticks = [];
// Minor tick dom element array
this.major_ticks = [];
// Date Format Lookup, map TL.Date.SCALES names to...
this.dateformat_lookup = {
millisecond: 'time_milliseconds', // ...TL.Language.<code>.dateformats
second: 'time_short',
minute: 'time_no_seconds_short',
hour: 'time_no_minutes_short',
day: 'full_short',
month: 'month_short',
year: 'year',
decade: 'year',
century: 'year',
millennium: 'year',
age: 'compact', // ...TL.Language.<code>.bigdateformats
epoch: 'compact',
era: 'compact',
eon: 'compact',
eon2: 'compact'
}
// Main element
if (typeof elem === 'object') {
this._el.container = elem;
} else {
this._el.container = TL.Dom.get(elem);
}
// Merge Data and Options
TL.Util.mergeData(this.options, options);
this._initLayout();
this._initEvents();
},
/* Adding, Hiding, Showing etc
================================================== */
show: function() {
},
hide: function() {
},
addTo: function(container) {
container.appendChild(this._el.container);
},
removeFrom: function(container) {
container.removeChild(this._el.container);
},
updateDisplay: function(w, h) {
this._updateDisplay(w, h);
},
getLeft: function() {
return this._el.container.style.left.slice(0, -2);
},
drawTicks: function(timescale, optimal_tick_width) {
var ticks = timescale.getTicks();
var controls = {
minor: {
el: this._el.minor,
dateformat: this.dateformat_lookup[ticks['minor'].name],
ts_ticks: ticks['minor'].ticks,
tick_elements: this.minor_ticks
},
major: {
el: this._el.major,
dateformat: this.dateformat_lookup[ticks['major'].name],
ts_ticks: ticks['major'].ticks,
tick_elements: this.major_ticks
}
}
// FADE OUT
this._el.major.className = "tl-timeaxis-major";
this._el.minor.className = "tl-timeaxis-minor";
this._el.major.style.opacity = 0;
this._el.minor.style.opacity = 0;
// CREATE MAJOR TICKS
this.major_ticks = this._createTickElements(
ticks['major'].ticks,
this._el.major,
this.dateformat_lookup[ticks['major'].name]
);
// CREATE MINOR TICKS
this.minor_ticks = this._createTickElements(
ticks['minor'].ticks,
this._el.minor,
this.dateformat_lookup[ticks['minor'].name],
ticks['major'].ticks
);
this.positionTicks(timescale, optimal_tick_width, true);
// FADE IN
this._el.major.className = "tl-timeaxis-major tl-animate-opacity tl-timeaxis-animate-opacity";
this._el.minor.className = "tl-timeaxis-minor tl-animate-opacity tl-timeaxis-animate-opacity";
this._el.major.style.opacity = 1;
this._el.minor.style.opacity = 1;
},
_createTickElements: function(ts_ticks,tick_element,dateformat,ticks_to_skip) {
tick_element.innerHTML = "";
var skip_times = {}
if (ticks_to_skip){
for (var i = 0; i < ticks_to_skip.length; i++) {
skip_times[ticks_to_skip[i].getTime()] = true;
}
}
var tick_elements = []
for (var i = 0; i < ts_ticks.length; i++) {
var ts_tick = ts_ticks[i];
if (!(ts_tick.getTime() in skip_times)) {
var tick = TL.Dom.create("div", "tl-timeaxis-tick", tick_element),
tick_text = TL.Dom.create("span", "tl-timeaxis-tick-text tl-animate-opacity", tick);
tick_text.innerHTML = ts_tick.getDisplayDate(this.getLanguage(), dateformat);
tick_elements.push({
tick:tick,
tick_text:tick_text,
display_date:ts_tick.getDisplayDate(this.getLanguage(), dateformat),
date:ts_tick
});
}
}
return tick_elements;
},
positionTicks: function(timescale, optimal_tick_width, no_animate) {
// Handle Animation
if (no_animate) {
this._el.major.className = "tl-timeaxis-major";
this._el.minor.className = "tl-timeaxis-minor";
} else {
this._el.major.className = "tl-timeaxis-major tl-timeaxis-animate";
this._el.minor.className = "tl-timeaxis-minor tl-timeaxis-animate";
}
this._positionTickArray(this.major_ticks, timescale, optimal_tick_width);
this._positionTickArray(this.minor_ticks, timescale, optimal_tick_width);
},
_positionTickArray: function(tick_array, timescale, optimal_tick_width) {
// Poition Ticks & Handle density of ticks
if (tick_array[1] && tick_array[0]) {
var distance = ( timescale.getPosition(tick_array[1].date.getMillisecond()) - timescale.getPosition(tick_array[0].date.getMillisecond()) ),
fraction_of_array = 1;
if (distance < optimal_tick_width) {
fraction_of_array = Math.round(optimal_tick_width/timescale.getPixelsPerTick());
}
var show = 1;
for (var i = 0; i < tick_array.length; i++) {
var tick = tick_array[i];
// Poition Ticks
tick.tick.style.left = timescale.getPosition(tick.date.getMillisecond()) + "px";
tick.tick_text.innerHTML = tick.display_date;
// Handle density of ticks
if (fraction_of_array > 1) {
if (show >= fraction_of_array) {
show = 1;
tick.tick_text.style.opacity = 1;
tick.tick.className = "tl-timeaxis-tick";
} else {
show++;
tick.tick_text.style.opacity = 0;
tick.tick.className = "tl-timeaxis-tick tl-timeaxis-tick-hidden";
}
} else {
tick.tick_text.style.opacity = 1;
tick.tick.className = "tl-timeaxis-tick";
}
};
}
},
/* Events
================================================== */
/* Private Methods
================================================== */
_initLayout: function () {
this._el.content_container = TL.Dom.create("div", "tl-timeaxis-content-container", this._el.container);
this._el.major = TL.Dom.create("div", "tl-timeaxis-major", this._el.content_container);
this._el.minor = TL.Dom.create("div", "tl-timeaxis-minor", this._el.content_container);
// Fire event that the slide is loaded
this.onLoaded();
},
_initEvents: function() {
},
// Update Display
_updateDisplay: function(width, height, layout) {
if (width) {
this.options.width = width;
}
if (height) {
this.options.height = height;
}
}
});
/* **********************************************
Begin TL.AxisHelper.js
********************************************** */
/* TL.AxisHelper
Strategies for laying out the timenav
markers and time axis
Intended as a private class -- probably only known to TimeScale
================================================== */
TL.AxisHelper = TL.Class.extend({
initialize: function (options) {
if (options) {
this.scale = options.scale;
this.minor = options.minor;
this.major = options.major;
} else {
throw("Axis helper must be configured with options")
}
},
getPixelsPerTick: function(pixels_per_milli) {
return pixels_per_milli * this.minor.factor;
},
getMajorTicks: function(timescale) {
return this._getTicks(timescale, this.major)
},
getMinorTicks: function(timescale) {
return this._getTicks(timescale, this.minor)
},
_getTicks: function(timescale, option) {
var factor_scale = timescale._scaled_padding * option.factor;
var first_tick_time = timescale._earliest - factor_scale;
var last_tick_time = timescale._latest + factor_scale;
var ticks = []
for (var i = first_tick_time; i < last_tick_time; i += option.factor) {
ticks.push(timescale.getDateFromTime(i).floor(option.name));
}
return {
name: option.name,
ticks: ticks
}
}
});
(function(cls){ // add some class-level behavior
var HELPERS = {};
var setHelpers = function(scale_type, scales) {
HELPERS[scale_type] = [];
for (var idx = 0; idx < scales.length - 1; idx++) {
var minor = scales[idx];
var major = scales[idx+1];
HELPERS[scale_type].push(new cls({
scale: minor[3],
minor: { name: minor[0], factor: minor[1]},
major: { name: major[0], factor: major[1]}
}));
}
};
setHelpers('human', TL.Date.SCALES);
setHelpers('cosmological', TL.BigDate.SCALES);
cls.HELPERS = HELPERS;
cls.getBestHelper = function(ts,optimal_tick_width) {
if (typeof(optimal_tick_width) != 'number' ) {
optimal_tick_width = 100;
}
var ts_scale = ts.getScale();
var helpers = HELPERS[ts_scale];
if (!helpers) {
throw ("No AxisHelper available for "+ts_scale);
}
var prev = null;
for (var idx in helpers) {
var curr = helpers[idx];
var pixels_per_tick = curr.getPixelsPerTick(ts._pixels_per_milli);
if (pixels_per_tick > optimal_tick_width) {
if (prev == null) return curr;
var curr_dist = Math.abs(optimal_tick_width - pixels_per_tick);
var prev_dist = Math.abs(optimal_tick_width - pixels_per_tick);
if (curr_dist < prev_dist) {
return curr;
} else {
return prev;
}
}
prev = curr;
}
return helpers[helpers.length - 1]; // last resort
}
})(TL.AxisHelper);
/* **********************************************
Begin TL.Timeline.js
********************************************** */
/* TimelineJS
Designed and built by Zach Wise at KnightLab
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
================================================== */
/*
TODO
*/
/* Required Files
CodeKit Import
https://incident57.com/codekit/
================================================== */
// CORE
// @codekit-prepend "core/TL.js";
// @codekit-prepend "core/TL.Util.js";
// @codekit-prepend "data/TL.Data.js";
// @codekit-prepend "core/TL.Class.js";
// @codekit-prepend "core/TL.Events.js";
// @codekit-prepend "core/TL.Browser.js";
// @codekit-prepend "core/TL.Load.js";
// @codekit-prepend "core/TL.TimelineConfig.js";
// @codekit-prepend "core/TL.ConfigFactory.js";
// LANGUAGE
// @codekit-prepend "language/TL.Language.js";
// @codekit-prepend "language/TL.I18NMixins.js";
// ANIMATION
// @codekit-prepend "animation/TL.Ease.js";
// @codekit-prepend "animation/TL.Animate.js";
// DOM
// @codekit-prepend "dom/TL.Point.js";
// @codekit-prepend "dom/TL.DomMixins.js";
// @codekit-prepend "dom/TL.Dom.js";
// @codekit-prepend "dom/TL.DomUtil.js";
// @codekit-prepend "dom/TL.DomEvent.js";
// @codekit-prepend "dom/TL.StyleSheet.js";
// Date
// @codekit-prepend "date/TL.Date.js";
// @codekit-prepend "date/TL.DateUtil.js";
// UI
// @codekit-prepend "ui/TL.Draggable.js";
// @codekit-prepend "ui/TL.Swipable.js";
// @codekit-prepend "ui/TL.MenuBar.js";
// @codekit-prepend "ui/TL.Message.js";
// MEDIA
// @codekit-prepend "media/TL.MediaType.js";
// @codekit-prepend "media/TL.Media.js";
// MEDIA TYPES
// @codekit-prepend "media/types/TL.Media.Blockquote.js";
// @codekit-prepend "media/types/TL.Media.DailyMotion.js";
// @codekit-prepend "media/types/TL.Media.DocumentCloud.js";
// @codekit-prepend "media/types/TL.Media.Flickr.js";
// @codekit-prepend "media/types/TL.Media.GoogleDoc.js";
// @codekit-prepend "media/types/TL.Media.GooglePlus.js";
// @codekit-prepend "media/types/TL.Media.IFrame.js";
// @codekit-prepend "media/types/TL.Media.Image.js";
// @codekit-prepend "media/types/TL.Media.Instagram.js";
// @codekit-prepend "media/types/TL.Media.GoogleMap.js";
// @codekit-prepend "media/types/TL.Media.Profile.js";
// @codekit-prepend "media/types/TL.Media.Slider.js";
// @codekit-prepend "media/types/TL.Media.SoundCloud.js";
// @codekit-prepend "media/types/TL.Media.Spotify.js";
// @codekit-prepend "media/types/TL.Media.Storify.js";
// @codekit-prepend "media/types/TL.Media.Text.js";
// @codekit-prepend "media/types/TL.Media.Twitter.js";
// @codekit-prepend "media/types/TL.Media.Vimeo.js";
// @codekit-prepend "media/types/TL.Media.Vine.js";
// @codekit-prepend "media/types/TL.Media.Website.js";
// @codekit-prepend "media/types/TL.Media.Wikipedia.js";
// @codekit-prepend "media/types/TL.Media.YouTube.js";
// STORYSLIDER
// @codekit-prepend "slider/TL.Slide.js";
// @codekit-prepend "slider/TL.SlideNav.js";
// @codekit-prepend "slider/TL.StorySlider.js";
// TIMENAV
// @codekit-prepend "timenav/TL.TimeNav.js";
// @codekit-prepend "timenav/TL.TimeMarker.js";
// @codekit-prepend "timenav/TL.TimeEra.js";
// @codekit-prepend "timenav/TL.TimeGroup.js";
// @codekit-prepend "timenav/TL.TimeScale.js";
// @codekit-prepend "timenav/TL.TimeAxis.js";
// @codekit-prepend "timenav/TL.AxisHelper.js";
TL.Timeline = TL.Class.extend({
includes: [TL.Events, TL.I18NMixins],
/* Private Methods
================================================== */
initialize: function (elem, data, options) {
var self = this;
if (!options) { options = {}};
// Version
this.version = "3.2.6";
// Ready
this.ready = false;
// DOM ELEMENTS
this._el = {
container: {},
storyslider: {},
timenav: {},
menubar: {}
};
// Determine Container Element
if (typeof elem === 'object') {
this._el.container = elem;
} else {
this._el.container = TL.Dom.get(elem);
}
// Slider
this._storyslider = {};
// Style Sheet
this._style_sheet = new TL.StyleSheet();
// TimeNav
this._timenav = {};
// Message
this.message = new TL.Message({}, {
message_class: "tl-message-full"
});
// Menu Bar
this._menubar = {};
// Loaded State
this._loaded = {storyslider:false, timenav:false};
// Data Object
this.config = null;
this.options = {
script_path: "",
height: this._el.container.offsetHeight,
width: this._el.container.offsetWidth,
is_embed: false,
is_full_embed: false,
hash_bookmark: false,
default_bg_color: {r:255, g:255, b:255},
scale_factor: 2, // How many screen widths wide should the timeline be
layout: "landscape", // portrait or landscape
timenav_position: "bottom", // timeline on top or bottom
optimal_tick_width: 60, // optimal distance (in pixels) between ticks on axis
base_class: "tl-timeline", // removing tl-timeline will break all default stylesheets...
timenav_height: 175,
timenav_height_percentage: 25, // Overrides timenav height as a percentage of the screen
timenav_mobile_height_percentage: 40, // timenav height as a percentage on mobile devices
timenav_height_min: 175, // Minimum timenav height
marker_height_min: 30, // Minimum Marker Height
marker_width_min: 100, // Minimum Marker Width
marker_padding: 5, // Top Bottom Marker Padding
start_at_slide: 0,
start_at_end: false,
menubar_height: 0,
skinny_size: 650,
medium_size: 800,
relative_date: false, // Use momentjs to show a relative date from the slide.text.date.created_time field
use_bc: false, // Use declared suffix on dates earlier than 0
// animation
duration: 1000,
ease: TL.Ease.easeInOutQuint,
// interaction
dragging: true,
trackResize: true,
map_type: "stamen:toner-lite",
slide_padding_lr: 100, // padding on slide of slide
slide_default_fade: "0%", // landscape fade
zoom_sequence: [0.5, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89], // Array of Fibonacci numbers for TimeNav zoom levels
language: "en",
ga_property_id: null,
track_events: ['back_to_start','nav_next','nav_previous','zoom_in','zoom_out' ]
};
// Animation Objects
this.animator_timenav = null;
this.animator_storyslider = null;
this.animator_menubar = null;
// Merge Options
if (typeof(options.default_bg_color) == "string") {
var parsed = TL.Util.hexToRgb(options.default_bg_color); // will clear it out if its invalid
if (parsed) {
options.default_bg_color = parsed;
} else {
delete options.default_bg_color
trace("Invalid default background color. Ignoring.");
}
}
TL.Util.mergeData(this.options, options);
window.addEventListener("resize", function(e){
self.updateDisplay();
})
// Apply base class to container
this._el.container.className += ' tl-timeline';
if (this.options.is_embed) {
this._el.container.className += ' tl-timeline-embed';
}
if (this.options.is_full_embed) {
this._el.container.className += ' tl-timeline-full-embed';
}
// Add Message to DOM
this.message.addTo(this._el.container);
// Use Relative Date Calculations
// NOT YET IMPLEMENTED
if(this.options.relative_date) {
if (typeof(moment) !== 'undefined') {
self._loadLanguage(data);
} else {
TL.Load.js(this.options.script_path + "/library/moment.js", function() {
self._loadLanguage(data);
trace("LOAD MOMENTJS")
});
}
} else {
self._loadLanguage(data);
}
},
/* Load Language
================================================== */
_loadLanguage: function(data) {
var self = this;
this.options.language = new TL.Language(this.options);
this._initData(data);
},
/* Navigation
================================================== */
// Goto slide with id
goToId: function(id) {
if (this.current_id != id) {
this.current_id = id;
this._timenav.goToId(this.current_id);
this._storyslider.goToId(this.current_id, false, true);
this.fire("change", {unique_id: this.current_id}, this);
}
},
// Goto slide n
goTo: function(n) {
if(this.config.title) {
if(n == 0) {
this.goToId(this.config.title.unique_id);
} else {
this.goToId(this.config.events[n - 1].unique_id);
}
} else {
this.goToId(this.config.events[n].unique_id);
}
},
// Goto first slide
goToStart: function() {
this.goTo(0);
},
// Goto last slide
goToEnd: function() {
var _n = this.config.events.length - 1;
this.goTo(this.config.title ? _n + 1 : _n);
},
// Goto previous slide
goToPrev: function() {
this.goTo(this._getSlideIndex(this.current_id) - 1);
},
// Goto next slide
goToNext: function() {
this.goTo(this._getSlideIndex(this.current_id) + 1);
},
/* Event maniupluation
================================================== */
// Add an event
add: function(data) {
var unique_id = this.config.addEvent(data);
var n = this._getEventIndex(unique_id);
var d = this.config.events[n];
this._storyslider.createSlide(d, this.config.title ? n+1 : n);
this._storyslider._updateDrawSlides();
this._timenav.createMarker(d, n);
this._timenav._updateDrawTimeline(false);
this.fire("added", {unique_id: unique_id});
},
// Remove an event
remove: function(n) {
if(n >= 0 && n < this.config.events.length) {
// If removing the current, nav to new one first
if(this.config.events[n].unique_id == this.current_id) {
if(n < this.config.events.length - 1) {
this.goTo(n + 1);
} else {
this.goTo(n - 1);
}
}
var event = this.config.events.splice(n, 1);
this._storyslider.destroySlide(this.config.title ? n+1 : n);
this._storyslider._updateDrawSlides();
this._timenav.destroyMarker(n);
this._timenav._updateDrawTimeline(false);
this.fire("removed", {unique_id: event[0].unique_id});
}
},
removeId: function(id) {
this.remove(this._getEventIndex(id));
},
/* Get slide data
================================================== */
getData: function(n) {
if(this.config.title) {
if(n == 0) {
return this.config.title;
} else if(n > 0 && n <= this.config.events.length) {
return this.config.events[n - 1];
}
} else if(n >= 0 && n < this.config.events.length) {
return this.config.events[n];
}
return null;
},
getDataById: function(id) {
return this.getData(this._getSlideIndex(id));
},
/* Get slide object
================================================== */
getSlide: function(n) {
if(n >= 0 && n < this._storyslider._slides.length) {
return this._storyslider._slides[n];
}
return null;
},
getSlideById: function(id) {
return this.getSlide(this._getSlideIndex(id));
},
getCurrentSlide: function() {
return this.getSlideById(this.current_id);
},
/* Display
================================================== */
updateDisplay: function() {
if (this.ready) {
this._updateDisplay();
}
},
/*
Compute the height of the navigation section of the Timeline, taking into account
the possibility of an explicit height or height percentage, but also honoring the
`timenav_height_min` option value. If `timenav_height` is specified it takes precedence over `timenav_height_percentage` but in either case, if the resultant pixel height is less than `options.timenav_height_min` then the value of `options.timenav_height_min` will be returned. (A minor adjustment is made to the returned value to account for marker padding.)
Arguments:
@timenav_height (optional): an integer value for the desired height in pixels
@timenav_height_percentage (optional): an integer between 1 and 100
*/
_calculateTimeNavHeight: function(timenav_height, timenav_height_percentage) {
var height = 0;
if (timenav_height) {
height = timenav_height;
} else {
if (this.options.timenav_height_percentage || timenav_height_percentage) {
if (timenav_height_percentage) {
height = Math.round((this.options.height/100)*timenav_height_percentage);
} else {
height = Math.round((this.options.height/100)*this.options.timenav_height_percentage);
}
}
}
if (height < this.options.timenav_height_min) {
height = this.options.timenav_height_min;
}
height = height - (this.options.marker_padding * 2);
return height;
},
/* Private Methods
================================================== */
// Update View
_updateDisplay: function(timenav_height, animate, d) {
var duration = this.options.duration,
display_class = this.options.base_class,
menu_position = 0,
self = this;
if (d) {
duration = d;
}
// Update width and height
this.options.width = this._el.container.offsetWidth;
this.options.height = this._el.container.offsetHeight;
// Check if skinny
if (this.options.width <= this.options.skinny_size) {
display_class += " tl-skinny";
this.options.layout = "portrait";
} else if (this.options.width <= this.options.medium_size) {
display_class += " tl-medium";
this.options.layout = "landscape";
} else {
this.options.layout = "landscape";
}
// Detect Mobile and Update Orientation on Touch devices
if (TL.Browser.touch) {
this.options.layout = TL.Browser.orientation();
}
if (TL.Browser.mobile) {
display_class += " tl-mobile";
// Set TimeNav Height
this.options.timenav_height = this._calculateTimeNavHeight(timenav_height, this.options.timenav_mobile_height_percentage);
} else {
// Set TimeNav Height
this.options.timenav_height = this._calculateTimeNavHeight(timenav_height);
}
// LAYOUT
if (this.options.layout == "portrait") {
// Portrait
display_class += " tl-layout-portrait";
} else {
// Landscape
display_class += " tl-layout-landscape";
}
// Set StorySlider Height
this.options.storyslider_height = (this.options.height - this.options.timenav_height);
// Positon Menu
if (this.options.timenav_position == "top") {
menu_position = ( Math.ceil(this.options.timenav_height)/2 ) - (this._el.menubar.offsetHeight/2) - (39/2) ;
} else {
menu_position = Math.round(this.options.storyslider_height + 1 + ( Math.ceil(this.options.timenav_height)/2 ) - (this._el.menubar.offsetHeight/2) - (35/2));
}
if (animate) {
// Animate TimeNav
/*
if (this.animator_timenav) {
this.animator_timenav.stop();
}
this.animator_timenav = TL.Animate(this._el.timenav, {
height: (this.options.timenav_height) + "px",
duration: duration/4,
easing: TL.Ease.easeOutStrong,
complete: function () {
//self._map.updateDisplay(self.options.width, self.options.timenav_height, animate, d, self.options.menubar_height);
}
});
*/
this._el.timenav.style.height = Math.ceil(this.options.timenav_height) + "px";
// Animate StorySlider
if (this.animator_storyslider) {
this.animator_storyslider.stop();
}
this.animator_storyslider = TL.Animate(this._el.storyslider, {
height: this.options.storyslider_height + "px",
duration: duration/2,
easing: TL.Ease.easeOutStrong
});
// Animate Menubar
if (this.animator_menubar) {
this.animator_menubar.stop();
}
this.animator_menubar = TL.Animate(this._el.menubar, {
top: menu_position + "px",
duration: duration/2,
easing: TL.Ease.easeOutStrong
});
} else {
// TimeNav
this._el.timenav.style.height = Math.ceil(this.options.timenav_height) + "px";
// StorySlider
this._el.storyslider.style.height = this.options.storyslider_height + "px";
// Menubar
this._el.menubar.style.top = menu_position + "px";
}
if (this.message) {
this.message.updateDisplay(this.options.width, this.options.height);
}
// Update Component Displays
this._timenav.updateDisplay(this.options.width, this.options.timenav_height, animate);
this._storyslider.updateDisplay(this.options.width, this.options.storyslider_height, animate, this.options.layout);
// Apply class
this._el.container.className = display_class;
},
// Update hashbookmark in the url bar
_updateHashBookmark: function(id) {
var hash = "#" + "event-" + id.toString();
if (window.location.protocol != 'file:') {
window.history.replaceState(null, "Browsing TimelineJS", hash);
}
this.fire("hash_updated", {unique_id:this.current_id, hashbookmark:"#" + "event-" + id.toString()}, this);
},
/* Init
================================================== */
// Initialize the data
_initData: function(data) {
var self = this;
if (typeof data == 'string') {
var self = this;
TL.ConfigFactory.makeConfig(data, function(config) {
self.setConfig(config);
});
} else if (TL.TimelineConfig == data.constructor) {
this.setConfig(data);
} else {
this.setConfig(new TL.TimelineConfig(data));
}
},
setConfig: function(config) {
this.config = config;
this.config.validate();
if (this.config.isValid()) {
this._onDataLoaded();
} else {
this.showMessage("<strong>"+ this._('error') +":</strong> " + this.config.getErrors('<br>'));
// should we set 'self.ready'? if not, it won't resize,
// but most resizing would only work
// if more setup happens
}
},
// Initialize the layout
_initLayout: function () {
var self = this;
this._el.container.innerHTML = "";
// Create Layout
if (this.options.timenav_position == "top") {
this._el.timenav = TL.Dom.create('div', 'tl-timenav', this._el.container);
this._el.storyslider = TL.Dom.create('div', 'tl-storyslider', this._el.container);
} else {
this._el.storyslider = TL.Dom.create('div', 'tl-storyslider', this._el.container);
this._el.timenav = TL.Dom.create('div', 'tl-timenav', this._el.container);
}
this._el.menubar = TL.Dom.create('div', 'tl-menubar', this._el.container);
// Initial Default Layout
this.options.width = this._el.container.offsetWidth;
this.options.height = this._el.container.offsetHeight;
this._el.storyslider.style.top = "1px";
// Set TimeNav Height
this.options.timenav_height = this._calculateTimeNavHeight();
// Create TimeNav
this._timenav = new TL.TimeNav(this._el.timenav, this.config, this.options);
this._timenav.on('loaded', this._onTimeNavLoaded, this);
this._timenav.options.height = this.options.timenav_height;
this._timenav.init();
// intial_zoom cannot be applied before the timenav has been created
if (this.options.initial_zoom) {
// at this point, this.options refers to the merged set of options
this.setZoom(this.options.initial_zoom);
}
// Create StorySlider
this._storyslider = new TL.StorySlider(this._el.storyslider, this.config, this.options);
this._storyslider.on('loaded', this._onStorySliderLoaded, this);
this._storyslider.init();
// Create Menu Bar
this._menubar = new TL.MenuBar(this._el.menubar, this._el.container, this.options);
// LAYOUT
if (this.options.layout == "portrait") {
this.options.storyslider_height = (this.options.height - this.options.timenav_height - 1);
} else {
this.options.storyslider_height = (this.options.height - 1);
}
// Update Display
this._updateDisplay(false, true, 2000);
},
/* Depends upon _initLayout because these events are on things the layout initializes */
_initEvents: function () {
// TimeNav Events
this._timenav.on('change', this._onTimeNavChange, this);
this._timenav.on('zoomtoggle', this._onZoomToggle, this);
// StorySlider Events
this._storyslider.on('change', this._onSlideChange, this);
this._storyslider.on('colorchange', this._onColorChange, this);
this._storyslider.on('nav_next', this._onStorySliderNext, this);
this._storyslider.on('nav_previous', this._onStorySliderPrevious, this);
// Menubar Events
this._menubar.on('zoom_in', this._onZoomIn, this);
this._menubar.on('zoom_out', this._onZoomOut, this);
this._menubar.on('back_to_start', this._onBackToStart, this);
},
/* Analytics
================================================== */
_initGoogleAnalytics: function() {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', this.options.ga_property_id, 'auto');
},
_initAnalytics: function() {
if (this.options.ga_property_id === null) { return; }
this._initGoogleAnalytics();
ga('send', 'pageview');
var events = this.options.track_events;
for (i=0; i < events.length; i++) {
var event_ = events[i];
this.addEventListener(event_, function(e) {
ga('send', 'event', e.type, 'clicked');
});
}
},
_onZoomToggle: function(e) {
if (e.zoom == "in") {
this._menubar.toogleZoomIn(e.show);
} else if (e.zoom == "out") {
this._menubar.toogleZoomOut(e.show);
}
},
/* Get index of event by id
================================================== */
_getEventIndex: function(id) {
for(var i = 0; i < this.config.events.length; i++) {
if(id == this.config.events[i].unique_id) {
return i;
}
}
return -1;
},
/* Get index of slide by id
================================================== */
_getSlideIndex: function(id) {
if(this.config.title && this.config.title.unique_id == id) {
return 0;
}
for(var i = 0; i < this.config.events.length; i++) {
if(id == this.config.events[i].unique_id) {
return this.config.title ? i+1 : i;
}
}
return -1;
},
/* Events
================================================== */
_onDataLoaded: function(e) {
this.fire("dataloaded");
this._initLayout();
this._initEvents();
this._initAnalytics();
if (this.message) {
this.message.hide();
}
this.ready = true;
},
showMessage: function(msg) {
if (this.message) {
this.message.updateMessage(msg);
} else {
trace("No message display available.")
trace(msg);
}
},
_onColorChange: function(e) {
this.fire("color_change", {unique_id:this.current_id}, this);
if (e.color || e.image) {
} else {
}
},
_onSlideChange: function(e) {
if (this.current_id != e.unique_id) {
this.current_id = e.unique_id;
this._timenav.goToId(this.current_id);
this._onChange(e);
}
},
_onTimeNavChange: function(e) {
if (this.current_id != e.unique_id) {
this.current_id = e.unique_id;
this._storyslider.goToId(this.current_id);
this._onChange(e);
}
},
_onChange: function(e) {
this.fire("change", {unique_id:this.current_id}, this);
if (this.options.hash_bookmark && this.current_id) {
this._updateHashBookmark(this.current_id);
}
},
_onBackToStart: function(e) {
this._storyslider.goTo(0);
this.fire("back_to_start", {unique_id:this.current_id}, this);
},
/**
* Zoom in and zoom out should be part of the public API.
*/
zoomIn: function() {
this._timenav.zoomIn();
},
zoomOut: function() {
this._timenav.zoomOut();
},
setZoom: function(level) {
this._timenav.setZoom(level);
},
_onZoomIn: function(e) {
this._timenav.zoomIn();
this.fire("zoom_in", {zoom_level:this._timenav.options.scale_factor}, this);
},
_onZoomOut: function(e) {
this._timenav.zoomOut();
this.fire("zoom_out", {zoom_level:this._timenav.options.scale_factor}, this);
},
_onTimeNavLoaded: function() {
this._loaded.timenav = true;
this._onLoaded();
},
_onStorySliderLoaded: function() {
this._loaded.storyslider = true;
this._onLoaded();
},
_onStorySliderNext: function(e) {
this.fire("nav_next", e);
},
_onStorySliderPrevious: function(e) {
this.fire("nav_previous", e);
},
_onLoaded: function() {
if (this._loaded.storyslider && this._loaded.timenav) {
this.fire("loaded", this.config);
// Go to proper slide
if (this.options.hash_bookmark && window.location.hash != "") {
this.goToId(window.location.hash.replace("#event-", ""));
} else {
if(this.options.start_at_end == "true" || this.options.start_at_slide > this.config.events.length ) {
this.goToEnd();
} else {
this.goTo(this.options.start_at_slide);
}
if (this.options.hash_bookmark ) {
this._updateHashBookmark(this.current_id);
}
}
}
}
});
TL.Timeline.source_path = (function() {
var script_tags = document.getElementsByTagName('script');
var src = script_tags[script_tags.length-1].src;
return src.substr(0,src.lastIndexOf('/'));
})();
|
module.exports = function (grunt) {
// Project configuration.
grunt.initConfig({
pkg: '<json:package.json>',
meta: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %>\n' +
'<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' +
' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */'
},
concat: {
dist: {
src: [
'<banner:meta.banner>',
'<file_strip_banner:<%= pkg.name %>>'
],
dest: 'dist/<%= pkg.name %>'
}
},
min: {
dist: {
src: [
'<banner:meta.banner>',
'<config:concat.dist.dest>'
],
dest: 'dist/<%= pkg.nameMinified %>'
}
},
test: {
files: ['test/**/*.js']
},
lint: {
files: [
'grunt.js',
'Guide.js',
'test/**/*.js'
]
},
watch: {
files: '<config:lint.files>',
tasks: 'lint test'
},
jshint: {
options: {
curly: true,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
noarg: true,
sub: true,
undef: true,
boss: true,
eqnull: true,
browser: true,
evil: false
},
globals: {
exports: true,
module: false
}
},
uglify: {}
});
// Default task.
grunt.registerTask('default', 'test lint concat min');
};
|
var util = require('util');
var _ = require('lodash');
var Column = require('./column'),
Marshal = require('./marshal');
var Row = module.exports = function Row(data, schema)
{
var row = [];
row.__proto__ = Row.prototype;
var defaultNameDeserializer = new Marshal(schema.default_name_type || row.nameType),
defaultValueDeserializer = new Marshal(schema.default_value_type || row.valueType);
var nameTypes = schema.name_types,
valueTypes = schema.value_types;
// Build a name-to-index lookup map for efficiency.
var nameToIndex = _.reduce(data.columns, function(map, member)
{
var name = member.name;
// `SELECT *` queries contain a vestigial `KEY` column.
if (name == 'KEY')
return map;
// Individual columns may specify custom name and value deserializers.
// `CompositeType` columns make use of the former.
var deserializeNameType = nameTypes && nameTypes[name],
deserializeValueType = valueTypes && valueTypes[name];
var deserializeName = (deserializeNameType ? new Marshal(deserializeNameType) : defaultNameDeserializer).deserialize,
deserializeValue = (deserializeValueType ? new Marshal(deserializeValueType) : defaultValueDeserializer).deserialize;
var deserializedName = deserializeName(name),
value = schema.noDeserialize ? member.value : deserializeValue(member.value),
column = new Column(deserializedName, value, new Date(member.timestamp / 1000), member.ttl);
map[deserializedName] = row.push(column) - 1;
return map;
}, {});
Object.defineProperties(row,
{
'nameToIndex': { 'value': nameToIndex },
'schema': { 'value': schema },
'key': { 'value': data.key }
});
return row;
};
Row.prototype =
{
'__proto__': Array.prototype,
get count()
{
return this.length;
}
};
Row.prototype.nameType = Row.prototype.valueType = 'BytesType';
/**
* Returns a human-readable representation of the row.
*
* @returns {String} The string representation.
*/
Row.prototype.toString = Row.prototype.inspect = function toString()
{
var self = this;
var columns = [];
_.forOwn(this.nameToIndex, function(columnIndex, name)
{
columns.push(name);
});
var key = Array.isArray(this.key) ? this.key.join(':') : this.key;
return util.format("<Row: Key: '%s', ColumnCount: %s, Columns: [ '%s' ]>", key, this.length, columns);
};
/**
* Retrieves a column by name.
*
* @param {String} name The column name.
* @returns {Column} The column.
*/
Row.prototype.get = function get(name)
{
return this[this.nameToIndex[name]];
};
/**
* Iterates over the row, executing the `callback` function for each column in
* the `row`. The `callback` is bound to the `context` and invoked with four
* arguments: `(name, value, timestamp, ttl)`. If the `callback`'s arity is five
* or greater, it will be invoked with three additional arguments:
* `(column, index, row)`.
*
* @param {Function} callback The callback function.
* @param {Mixed} [context] The `this` binding of the `callback`.
*/
var forEach = [].forEach;
Row.prototype.forEach = function each(callback, context)
{
if (callback && typeof context != 'undefined')
callback = _.bind(callback, context);
function eachRow(column, index, row)
{
var name = column.name,
value = column.value,
timestamp = column.timestamp,
ttl = column.ttl;
if (callback.length == 4)
return callback(name, value, timestamp, ttl);
callback(name, value, timestamp, ttl, column, index, row);
}
return forEach.call(this, eachRow);
};
/**
* Extracts columns from the `start` index up to, but not including, the
* `end` index.
*
* @param {Number} [start] Indicates where to start the selection.
* @param {Number} [end] Indicates where to end the selection.
* @returns {Row} The new row.
*/
var slice = [].slice;
Row.prototype.slice = function indexSlice(start, end)
{
var columns = slice.call(this, start, end);
return new Row({ 'key': this.key, 'columns': columns }, this.schema);
};
/**
* Extracts columns from the `start` name up to, but not including, the `end`
* name. The comparisons are performed lexicographically.
*
* @param {String} [start] Indicates where to start the selection.
* @param {String} [end] Indicates where to end the selection.
* @returns {Row} The new row.
*/
Row.prototype.nameSlice = function nameSlice(start, end)
{
var self = this,
columns = [];
start == null && (start = ' ');
end == null && (end = '~');
_.forOwn(this.nameToIndex, function(index, key)
{
if (key >= start && key < end)
columns.push(self[index]);
});
return new Row({ 'key': this.key, 'columns': columns }, this.schema);
};
Row.fromThrift = function fromThrift(key, columns, columnFamily)
{
var isCounter = columnFamily.isCounter,
definition = columnFamily.definition;
var schema =
{
'default_value_type': definition.default_validation_class,
'default_name_type': definition.comparator_type
};
var valueTypes = schema.value_types = {},
columnData = definition.column_metadata;
if (Array.isArray(columnData))
{
_.each(columnData, function(datum)
{
valueTypes[datum.name] = datum.validation_class;
});
}
// Counter columns are already deserialized.
if (isCounter)
schema.noDeserialize = true;
var data =
{
'key': key,
'columns': _.map(columns, function(column)
{
// TODO: Implement super columns.
return column[isCounter ? 'counter_column' : 'column'];
})
};
return new Row(data, schema);
};
|
export default function(state = {}, action) {
if (action.type === 'TAB_DEFAULT') {
state[action.payload.page] = action.payload.tab
return Object.assign({}, state)
}
return state
}
|
"use strict";
const common = require('./common');
const {DEFAULT_ADMIN, makeDefaultUser, PROMISE_DELAY} = require('./common');
const makeTests = require('./factory');
function userGetter(userName) {
return new Promise(resolve => {
setTimeout(() => {
resolve(userName == 'admin' ? DEFAULT_ADMIN : makeDefaultUser(userName))
}, PROMISE_DELAY)
})
}
function getTokenAsync() {
return new Promise(resolve => {
setTimeout(() => resolve('SECRET'), PROMISE_DELAY)
})
}
const auth = require('..')(
getTokenAsync(),
userGetter,
{token: {exp: (user) => Math.floor(Date.now() / 1000) + (60 * 60)}}
);
describe('promises', () => makeTests(auth));
|
var repo = require(process.cwd()+'/repo');
var usersInfo = require(process.cwd()+'/bot/utilities/users');
var _ = require('underscore');
module.exports = function(bot, db, data) {
if(!bot.getDJ())
return bot.sendChat('There is no DJ playing!');
if(data.params.length > 0){
if(_.contains(usersInfo.usersThatPropped, data.user.id))
return bot.sendChat('@' + data.user.username + ', you have already given a flame for this song!');
if (data.params.length === 1) {
if (data.params[0].substr(0, 1) === "@" && data.params[0] !== "@"+data.user.username) {
var recipient = bot.getUserByName(data.params[0].replace("@", ""), true);
repo.propsUser(db, recipient, function(user){
usersInfo.usersThatPropped.push(data.user.id);
bot.sendChat('Yoooo keep up the good work @' + recipient.username + '! @' + data.user.username + ' thinks your song is :fire: :fire: :fire:! ' +
'You now have ' + user.props + ' flames! :fire: ');
});
}
else if(data.params[0].substr(0, 1) === "@" && data.params[0] === "@" + data.user.username){
bot.sendChat('Wow @' + data.user.username + ' ... Love yourself in private weirdo... :confounded:');
}
else {
bot.sendChat("@" + data.user.username + " you need to @[username] to give a flame to someone");
}
} else {
bot.sendChat("@" + data.user.username + " you can give fire to one person");
}
}
else if(data.user.username !== bot.getDJ().username){
if(_.contains(usersInfo.usersThatPropped, data.user.id))
return bot.sendChat('@' + data.user.username + ', you have already given a flame for this song!');
repo.propsUser(db, bot.getDJ(), function(user){
usersInfo.usersThatPropped.push(data.user.id);
bot.sendChat('Yoooo keep up the good work @' + bot.getDJ().username + '! @' + data.user.username + ' thinks your song is :fire: :fire: :fire:! ' +
'You now have ' + user.props + ' flames! :fire: ');
});
}
else{
bot.sendChat('Wow @' + data.user.username + ' ... Love yourself in private weirdo... :confounded:');
}
};
|
require('./slider');
module.exports = 'ui.bootstrap-slider';
|
/**
* @license Gibberish-AES
* A lightweight Javascript Libray for OpenSSL compatible AES CBC encryption.
*
* Author: Mark Percival
* Email: mark@mpercival.com
* Copyright: Mark Percival - http://mpercival.com 2008
*
* With thanks to:
* Josh Davis - http://www.josh-davis.org/ecmaScrypt
* Chris Veness - http://www.movable-type.co.uk/scripts/aes.html
* Michel I. Gallant - http://www.jensign.com/
* Jean-Luc Cooke <jlcooke@certainkey.com> 2012-07-12: added strhex + invertArr to compress G2X/G3X/G9X/GBX/GEX/SBox/SBoxInv/Rcon saving over 7KB, and added encString, decString, also made the MD5 routine more easlier compressible using yuicompressor.
*
* License: MIT
*
* Usage: GibberishAES.enc("secret", "password")
* Outputs: AES Encrypted text encoded in Base64
*/
(function (root, factory) {
if (typeof exports === 'object') {
// Node.
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else {
// Browser globals (root is window)
root.GibberishAES = factory();
}
}(this, function () {
'use strict';
var Nr = 14,
/* Default to 256 Bit Encryption */
Nk = 8,
Decrypt = false,
enc_utf8 = function(s)
{
try {
return unescape(encodeURIComponent(s));
}
catch(e) {
throw 'Error on UTF-8 encode';
}
},
dec_utf8 = function(s)
{
try {
return decodeURIComponent(escape(s));
}
catch(e) {
throw ('Bad Key');
}
},
padBlock = function(byteArr)
{
var array = [], cpad, i;
if (byteArr.length < 16) {
cpad = 16 - byteArr.length;
array = [cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad, cpad];
}
for (i = 0; i < byteArr.length; i++)
{
array[i] = byteArr[i];
}
return array;
},
block2s = function(block, lastBlock)
{
var string = '', padding, i;
if (lastBlock) {
padding = block[15];
if (padding > 16) {
throw ('Decryption error: Maybe bad key');
}
if (padding === 16) {
return '';
}
for (i = 0; i < 16 - padding; i++) {
string += String.fromCharCode(block[i]);
}
} else {
for (i = 0; i < 16; i++) {
string += String.fromCharCode(block[i]);
}
}
return string;
},
a2h = function(numArr)
{
var string = '', i;
for (i = 0; i < numArr.length; i++) {
string += (numArr[i] < 16 ? '0': '') + numArr[i].toString(16);
}
return string;
},
h2a = function(s)
{
var ret = [];
s.replace(/(..)/g,
function(s) {
ret.push(parseInt(s, 16));
});
return ret;
},
s2a = function(string, binary) {
var array = [], i;
if (! binary) {
string = enc_utf8(string);
}
for (i = 0; i < string.length; i++)
{
array[i] = string.charCodeAt(i);
}
return array;
},
size = function(newsize)
{
switch (newsize)
{
case 128:
Nr = 10;
Nk = 4;
break;
case 192:
Nr = 12;
Nk = 6;
break;
case 256:
Nr = 14;
Nk = 8;
break;
default:
throw ('Invalid Key Size Specified:' + newsize);
}
},
randArr = function(num) {
var result = [], i;
for (i = 0; i < num; i++) {
result = result.concat(Math.floor(Math.random() * 256));
}
return result;
},
openSSLKey = function(passwordArr, saltArr) {
// Number of rounds depends on the size of the AES in use
// 3 rounds for 256
// 2 rounds for the key, 1 for the IV
// 2 rounds for 128
// 1 round for the key, 1 round for the IV
// 3 rounds for 192 since it's not evenly divided by 128 bits
var rounds = Nr >= 12 ? 3: 2,
key = [],
iv = [],
md5_hash = [],
result = [],
data00 = passwordArr.concat(saltArr),
i;
md5_hash[0] = MD5(data00);
result = md5_hash[0];
for (i = 1; i < rounds; i++) {
md5_hash[i] = MD5(md5_hash[i - 1].concat(data00));
result = result.concat(md5_hash[i]);
}
key = result.slice(0, 4 * Nk);
iv = result.slice(4 * Nk, 4 * Nk + 16);
return {
key: key,
iv: iv
};
},
rawEncrypt = function(plaintext, key, iv) {
// plaintext, key and iv as byte arrays
key = expandKey(key);
var numBlocks = Math.ceil(plaintext.length / 16),
blocks = [],
i,
cipherBlocks = [];
for (i = 0; i < numBlocks; i++) {
blocks[i] = padBlock(plaintext.slice(i * 16, i * 16 + 16));
}
if (plaintext.length % 16 === 0) {
blocks.push([16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16]);
// CBC OpenSSL padding scheme
numBlocks++;
}
for (i = 0; i < blocks.length; i++) {
blocks[i] = (i === 0) ? xorBlocks(blocks[i], iv) : xorBlocks(blocks[i], cipherBlocks[i - 1]);
cipherBlocks[i] = encryptBlock(blocks[i], key);
}
return cipherBlocks;
},
rawDecrypt = function(cryptArr, key, iv, binary) {
// cryptArr, key and iv as byte arrays
key = expandKey(key);
var numBlocks = cryptArr.length / 16,
cipherBlocks = [],
i,
plainBlocks = [],
string = '';
for (i = 0; i < numBlocks; i++) {
cipherBlocks.push(cryptArr.slice(i * 16, (i + 1) * 16));
}
for (i = cipherBlocks.length - 1; i >= 0; i--) {
plainBlocks[i] = decryptBlock(cipherBlocks[i], key);
plainBlocks[i] = (i === 0) ? xorBlocks(plainBlocks[i], iv) : xorBlocks(plainBlocks[i], cipherBlocks[i - 1]);
}
for (i = 0; i < numBlocks - 1; i++) {
string += block2s(plainBlocks[i]);
}
string += block2s(plainBlocks[i], true);
return binary ? string : dec_utf8(string);
},
encryptBlock = function(block, words) {
Decrypt = false;
var state = addRoundKey(block, words, 0),
round;
for (round = 1; round < (Nr + 1); round++) {
state = subBytes(state);
state = shiftRows(state);
if (round < Nr) {
state = mixColumns(state);
}
//last round? don't mixColumns
state = addRoundKey(state, words, round);
}
return state;
},
decryptBlock = function(block, words) {
Decrypt = true;
var state = addRoundKey(block, words, Nr),
round;
for (round = Nr - 1; round > -1; round--) {
state = shiftRows(state);
state = subBytes(state);
state = addRoundKey(state, words, round);
if (round > 0) {
state = mixColumns(state);
}
//last round? don't mixColumns
}
return state;
},
subBytes = function(state) {
var S = Decrypt ? SBoxInv: SBox,
temp = [],
i;
for (i = 0; i < 16; i++) {
temp[i] = S[state[i]];
}
return temp;
},
shiftRows = function(state) {
var temp = [],
shiftBy = Decrypt ? [0, 13, 10, 7, 4, 1, 14, 11, 8, 5, 2, 15, 12, 9, 6, 3] : [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11],
i;
for (i = 0; i < 16; i++) {
temp[i] = state[shiftBy[i]];
}
return temp;
},
mixColumns = function(state) {
var t = [],
c;
if (!Decrypt) {
for (c = 0; c < 4; c++) {
t[c * 4] = G2X[state[c * 4]] ^ G3X[state[1 + c * 4]] ^ state[2 + c * 4] ^ state[3 + c * 4];
t[1 + c * 4] = state[c * 4] ^ G2X[state[1 + c * 4]] ^ G3X[state[2 + c * 4]] ^ state[3 + c * 4];
t[2 + c * 4] = state[c * 4] ^ state[1 + c * 4] ^ G2X[state[2 + c * 4]] ^ G3X[state[3 + c * 4]];
t[3 + c * 4] = G3X[state[c * 4]] ^ state[1 + c * 4] ^ state[2 + c * 4] ^ G2X[state[3 + c * 4]];
}
}else {
for (c = 0; c < 4; c++) {
t[c*4] = GEX[state[c*4]] ^ GBX[state[1+c*4]] ^ GDX[state[2+c*4]] ^ G9X[state[3+c*4]];
t[1+c*4] = G9X[state[c*4]] ^ GEX[state[1+c*4]] ^ GBX[state[2+c*4]] ^ GDX[state[3+c*4]];
t[2+c*4] = GDX[state[c*4]] ^ G9X[state[1+c*4]] ^ GEX[state[2+c*4]] ^ GBX[state[3+c*4]];
t[3+c*4] = GBX[state[c*4]] ^ GDX[state[1+c*4]] ^ G9X[state[2+c*4]] ^ GEX[state[3+c*4]];
}
}
return t;
},
addRoundKey = function(state, words, round) {
var temp = [],
i;
for (i = 0; i < 16; i++) {
temp[i] = state[i] ^ words[round][i];
}
return temp;
},
xorBlocks = function(block1, block2) {
var temp = [],
i;
for (i = 0; i < 16; i++) {
temp[i] = block1[i] ^ block2[i];
}
return temp;
},
expandKey = function(key) {
// Expects a 1d number array
var w = [],
temp = [],
i,
r,
t,
flat = [],
j;
for (i = 0; i < Nk; i++) {
r = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]];
w[i] = r;
}
for (i = Nk; i < (4 * (Nr + 1)); i++) {
w[i] = [];
for (t = 0; t < 4; t++) {
temp[t] = w[i - 1][t];
}
if (i % Nk === 0) {
temp = subWord(rotWord(temp));
temp[0] ^= Rcon[i / Nk - 1];
} else if (Nk > 6 && i % Nk === 4) {
temp = subWord(temp);
}
for (t = 0; t < 4; t++) {
w[i][t] = w[i - Nk][t] ^ temp[t];
}
}
for (i = 0; i < (Nr + 1); i++) {
flat[i] = [];
for (j = 0; j < 4; j++) {
flat[i].push(w[i * 4 + j][0], w[i * 4 + j][1], w[i * 4 + j][2], w[i * 4 + j][3]);
}
}
return flat;
},
subWord = function(w) {
// apply SBox to 4-byte word w
for (var i = 0; i < 4; i++) {
w[i] = SBox[w[i]];
}
return w;
},
rotWord = function(w) {
// rotate 4-byte word w left by one byte
var tmp = w[0],
i;
for (i = 0; i < 4; i++) {
w[i] = w[i + 1];
}
w[3] = tmp;
return w;
},
// jlcooke: 2012-07-12: added strhex + invertArr to compress G2X/G3X/G9X/GBX/GEX/SBox/SBoxInv/Rcon saving over 7KB, and added encString, decString
strhex = function(str,size) {
var i, ret = [];
for (i=0; i<str.length; i+=size){
ret[i/size] = parseInt(str.substr(i,size), 16);
}
return ret;
},
invertArr = function(arr) {
var i, ret = [];
for (i=0; i<arr.length; i++){
ret[arr[i]] = i;
}
return ret;
},
Gxx = function(a, b) {
var i, ret;
ret = 0;
for (i=0; i<8; i++) {
ret = ((b&1)===1) ? ret^a : ret;
/* xmult */
a = (a>0x7f) ? 0x11b^(a<<1) : (a<<1);
b >>>= 1;
}
return ret;
},
Gx = function(x) {
var i, r = [];
for (i=0; i<256; i++){
r[i] = Gxx(x, i);
}
return r;
},
// S-box
/*
SBox = [
99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171,
118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164,
114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113,
216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226,
235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214,
179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203,
190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69,
249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245,
188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68,
23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42,
144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73,
6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109,
141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37,
46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62,
181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225,
248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223,
140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187,
22], //*/ SBox = strhex('637c777bf26b6fc53001672bfed7ab76ca82c97dfa5947f0add4a2af9ca472c0b7fd9326363ff7cc34a5e5f171d8311504c723c31896059a071280e2eb27b27509832c1a1b6e5aa0523bd6b329e32f8453d100ed20fcb15b6acbbe394a4c58cfd0efaafb434d338545f9027f503c9fa851a3408f929d38f5bcb6da2110fff3d2cd0c13ec5f974417c4a77e3d645d197360814fdc222a908846eeb814de5e0bdbe0323a0a4906245cc2d3ac629195e479e7c8376d8dd54ea96c56f4ea657aae08ba78252e1ca6b4c6e8dd741f4bbd8b8a703eb5664803f60e613557b986c11d9ee1f8981169d98e949b1e87e9ce5528df8ca1890dbfe6426841992d0fb054bb16',2),
// Precomputed lookup table for the inverse SBox
/* SBoxInv = [
82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215,
251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222,
233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66,
250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73,
109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92,
204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21,
70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247,
228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2,
193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220,
234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173,
53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29,
41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75,
198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168,
51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81,
127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160,
224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97,
23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12,
125], //*/ SBoxInv = invertArr(SBox),
// Rijndael Rcon
/*
Rcon = [1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94,
188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145],
//*/ Rcon = strhex('01020408102040801b366cd8ab4d9a2f5ebc63c697356ad4b37dfaefc591',2),
/*
G2X = [
0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16,
0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e,
0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, 0x40, 0x42, 0x44, 0x46,
0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e,
0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76,
0x78, 0x7a, 0x7c, 0x7e, 0x80, 0x82, 0x84, 0x86, 0x88, 0x8a, 0x8c, 0x8e,
0x90, 0x92, 0x94, 0x96, 0x98, 0x9a, 0x9c, 0x9e, 0xa0, 0xa2, 0xa4, 0xa6,
0xa8, 0xaa, 0xac, 0xae, 0xb0, 0xb2, 0xb4, 0xb6, 0xb8, 0xba, 0xbc, 0xbe,
0xc0, 0xc2, 0xc4, 0xc6, 0xc8, 0xca, 0xcc, 0xce, 0xd0, 0xd2, 0xd4, 0xd6,
0xd8, 0xda, 0xdc, 0xde, 0xe0, 0xe2, 0xe4, 0xe6, 0xe8, 0xea, 0xec, 0xee,
0xf0, 0xf2, 0xf4, 0xf6, 0xf8, 0xfa, 0xfc, 0xfe, 0x1b, 0x19, 0x1f, 0x1d,
0x13, 0x11, 0x17, 0x15, 0x0b, 0x09, 0x0f, 0x0d, 0x03, 0x01, 0x07, 0x05,
0x3b, 0x39, 0x3f, 0x3d, 0x33, 0x31, 0x37, 0x35, 0x2b, 0x29, 0x2f, 0x2d,
0x23, 0x21, 0x27, 0x25, 0x5b, 0x59, 0x5f, 0x5d, 0x53, 0x51, 0x57, 0x55,
0x4b, 0x49, 0x4f, 0x4d, 0x43, 0x41, 0x47, 0x45, 0x7b, 0x79, 0x7f, 0x7d,
0x73, 0x71, 0x77, 0x75, 0x6b, 0x69, 0x6f, 0x6d, 0x63, 0x61, 0x67, 0x65,
0x9b, 0x99, 0x9f, 0x9d, 0x93, 0x91, 0x97, 0x95, 0x8b, 0x89, 0x8f, 0x8d,
0x83, 0x81, 0x87, 0x85, 0xbb, 0xb9, 0xbf, 0xbd, 0xb3, 0xb1, 0xb7, 0xb5,
0xab, 0xa9, 0xaf, 0xad, 0xa3, 0xa1, 0xa7, 0xa5, 0xdb, 0xd9, 0xdf, 0xdd,
0xd3, 0xd1, 0xd7, 0xd5, 0xcb, 0xc9, 0xcf, 0xcd, 0xc3, 0xc1, 0xc7, 0xc5,
0xfb, 0xf9, 0xff, 0xfd, 0xf3, 0xf1, 0xf7, 0xf5, 0xeb, 0xe9, 0xef, 0xed,
0xe3, 0xe1, 0xe7, 0xe5
], //*/ G2X = Gx(2),
/* G3X = [
0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d,
0x14, 0x17, 0x12, 0x11, 0x30, 0x33, 0x36, 0x35, 0x3c, 0x3f, 0x3a, 0x39,
0x28, 0x2b, 0x2e, 0x2d, 0x24, 0x27, 0x22, 0x21, 0x60, 0x63, 0x66, 0x65,
0x6c, 0x6f, 0x6a, 0x69, 0x78, 0x7b, 0x7e, 0x7d, 0x74, 0x77, 0x72, 0x71,
0x50, 0x53, 0x56, 0x55, 0x5c, 0x5f, 0x5a, 0x59, 0x48, 0x4b, 0x4e, 0x4d,
0x44, 0x47, 0x42, 0x41, 0xc0, 0xc3, 0xc6, 0xc5, 0xcc, 0xcf, 0xca, 0xc9,
0xd8, 0xdb, 0xde, 0xdd, 0xd4, 0xd7, 0xd2, 0xd1, 0xf0, 0xf3, 0xf6, 0xf5,
0xfc, 0xff, 0xfa, 0xf9, 0xe8, 0xeb, 0xee, 0xed, 0xe4, 0xe7, 0xe2, 0xe1,
0xa0, 0xa3, 0xa6, 0xa5, 0xac, 0xaf, 0xaa, 0xa9, 0xb8, 0xbb, 0xbe, 0xbd,
0xb4, 0xb7, 0xb2, 0xb1, 0x90, 0x93, 0x96, 0x95, 0x9c, 0x9f, 0x9a, 0x99,
0x88, 0x8b, 0x8e, 0x8d, 0x84, 0x87, 0x82, 0x81, 0x9b, 0x98, 0x9d, 0x9e,
0x97, 0x94, 0x91, 0x92, 0x83, 0x80, 0x85, 0x86, 0x8f, 0x8c, 0x89, 0x8a,
0xab, 0xa8, 0xad, 0xae, 0xa7, 0xa4, 0xa1, 0xa2, 0xb3, 0xb0, 0xb5, 0xb6,
0xbf, 0xbc, 0xb9, 0xba, 0xfb, 0xf8, 0xfd, 0xfe, 0xf7, 0xf4, 0xf1, 0xf2,
0xe3, 0xe0, 0xe5, 0xe6, 0xef, 0xec, 0xe9, 0xea, 0xcb, 0xc8, 0xcd, 0xce,
0xc7, 0xc4, 0xc1, 0xc2, 0xd3, 0xd0, 0xd5, 0xd6, 0xdf, 0xdc, 0xd9, 0xda,
0x5b, 0x58, 0x5d, 0x5e, 0x57, 0x54, 0x51, 0x52, 0x43, 0x40, 0x45, 0x46,
0x4f, 0x4c, 0x49, 0x4a, 0x6b, 0x68, 0x6d, 0x6e, 0x67, 0x64, 0x61, 0x62,
0x73, 0x70, 0x75, 0x76, 0x7f, 0x7c, 0x79, 0x7a, 0x3b, 0x38, 0x3d, 0x3e,
0x37, 0x34, 0x31, 0x32, 0x23, 0x20, 0x25, 0x26, 0x2f, 0x2c, 0x29, 0x2a,
0x0b, 0x08, 0x0d, 0x0e, 0x07, 0x04, 0x01, 0x02, 0x13, 0x10, 0x15, 0x16,
0x1f, 0x1c, 0x19, 0x1a
], //*/ G3X = Gx(3),
/*
G9X = [
0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53,
0x6c, 0x65, 0x7e, 0x77, 0x90, 0x99, 0x82, 0x8b, 0xb4, 0xbd, 0xa6, 0xaf,
0xd8, 0xd1, 0xca, 0xc3, 0xfc, 0xf5, 0xee, 0xe7, 0x3b, 0x32, 0x29, 0x20,
0x1f, 0x16, 0x0d, 0x04, 0x73, 0x7a, 0x61, 0x68, 0x57, 0x5e, 0x45, 0x4c,
0xab, 0xa2, 0xb9, 0xb0, 0x8f, 0x86, 0x9d, 0x94, 0xe3, 0xea, 0xf1, 0xf8,
0xc7, 0xce, 0xd5, 0xdc, 0x76, 0x7f, 0x64, 0x6d, 0x52, 0x5b, 0x40, 0x49,
0x3e, 0x37, 0x2c, 0x25, 0x1a, 0x13, 0x08, 0x01, 0xe6, 0xef, 0xf4, 0xfd,
0xc2, 0xcb, 0xd0, 0xd9, 0xae, 0xa7, 0xbc, 0xb5, 0x8a, 0x83, 0x98, 0x91,
0x4d, 0x44, 0x5f, 0x56, 0x69, 0x60, 0x7b, 0x72, 0x05, 0x0c, 0x17, 0x1e,
0x21, 0x28, 0x33, 0x3a, 0xdd, 0xd4, 0xcf, 0xc6, 0xf9, 0xf0, 0xeb, 0xe2,
0x95, 0x9c, 0x87, 0x8e, 0xb1, 0xb8, 0xa3, 0xaa, 0xec, 0xe5, 0xfe, 0xf7,
0xc8, 0xc1, 0xda, 0xd3, 0xa4, 0xad, 0xb6, 0xbf, 0x80, 0x89, 0x92, 0x9b,
0x7c, 0x75, 0x6e, 0x67, 0x58, 0x51, 0x4a, 0x43, 0x34, 0x3d, 0x26, 0x2f,
0x10, 0x19, 0x02, 0x0b, 0xd7, 0xde, 0xc5, 0xcc, 0xf3, 0xfa, 0xe1, 0xe8,
0x9f, 0x96, 0x8d, 0x84, 0xbb, 0xb2, 0xa9, 0xa0, 0x47, 0x4e, 0x55, 0x5c,
0x63, 0x6a, 0x71, 0x78, 0x0f, 0x06, 0x1d, 0x14, 0x2b, 0x22, 0x39, 0x30,
0x9a, 0x93, 0x88, 0x81, 0xbe, 0xb7, 0xac, 0xa5, 0xd2, 0xdb, 0xc0, 0xc9,
0xf6, 0xff, 0xe4, 0xed, 0x0a, 0x03, 0x18, 0x11, 0x2e, 0x27, 0x3c, 0x35,
0x42, 0x4b, 0x50, 0x59, 0x66, 0x6f, 0x74, 0x7d, 0xa1, 0xa8, 0xb3, 0xba,
0x85, 0x8c, 0x97, 0x9e, 0xe9, 0xe0, 0xfb, 0xf2, 0xcd, 0xc4, 0xdf, 0xd6,
0x31, 0x38, 0x23, 0x2a, 0x15, 0x1c, 0x07, 0x0e, 0x79, 0x70, 0x6b, 0x62,
0x5d, 0x54, 0x4f, 0x46
], //*/ G9X = Gx(9),
/* GBX = [
0x00, 0x0b, 0x16, 0x1d, 0x2c, 0x27, 0x3a, 0x31, 0x58, 0x53, 0x4e, 0x45,
0x74, 0x7f, 0x62, 0x69, 0xb0, 0xbb, 0xa6, 0xad, 0x9c, 0x97, 0x8a, 0x81,
0xe8, 0xe3, 0xfe, 0xf5, 0xc4, 0xcf, 0xd2, 0xd9, 0x7b, 0x70, 0x6d, 0x66,
0x57, 0x5c, 0x41, 0x4a, 0x23, 0x28, 0x35, 0x3e, 0x0f, 0x04, 0x19, 0x12,
0xcb, 0xc0, 0xdd, 0xd6, 0xe7, 0xec, 0xf1, 0xfa, 0x93, 0x98, 0x85, 0x8e,
0xbf, 0xb4, 0xa9, 0xa2, 0xf6, 0xfd, 0xe0, 0xeb, 0xda, 0xd1, 0xcc, 0xc7,
0xae, 0xa5, 0xb8, 0xb3, 0x82, 0x89, 0x94, 0x9f, 0x46, 0x4d, 0x50, 0x5b,
0x6a, 0x61, 0x7c, 0x77, 0x1e, 0x15, 0x08, 0x03, 0x32, 0x39, 0x24, 0x2f,
0x8d, 0x86, 0x9b, 0x90, 0xa1, 0xaa, 0xb7, 0xbc, 0xd5, 0xde, 0xc3, 0xc8,
0xf9, 0xf2, 0xef, 0xe4, 0x3d, 0x36, 0x2b, 0x20, 0x11, 0x1a, 0x07, 0x0c,
0x65, 0x6e, 0x73, 0x78, 0x49, 0x42, 0x5f, 0x54, 0xf7, 0xfc, 0xe1, 0xea,
0xdb, 0xd0, 0xcd, 0xc6, 0xaf, 0xa4, 0xb9, 0xb2, 0x83, 0x88, 0x95, 0x9e,
0x47, 0x4c, 0x51, 0x5a, 0x6b, 0x60, 0x7d, 0x76, 0x1f, 0x14, 0x09, 0x02,
0x33, 0x38, 0x25, 0x2e, 0x8c, 0x87, 0x9a, 0x91, 0xa0, 0xab, 0xb6, 0xbd,
0xd4, 0xdf, 0xc2, 0xc9, 0xf8, 0xf3, 0xee, 0xe5, 0x3c, 0x37, 0x2a, 0x21,
0x10, 0x1b, 0x06, 0x0d, 0x64, 0x6f, 0x72, 0x79, 0x48, 0x43, 0x5e, 0x55,
0x01, 0x0a, 0x17, 0x1c, 0x2d, 0x26, 0x3b, 0x30, 0x59, 0x52, 0x4f, 0x44,
0x75, 0x7e, 0x63, 0x68, 0xb1, 0xba, 0xa7, 0xac, 0x9d, 0x96, 0x8b, 0x80,
0xe9, 0xe2, 0xff, 0xf4, 0xc5, 0xce, 0xd3, 0xd8, 0x7a, 0x71, 0x6c, 0x67,
0x56, 0x5d, 0x40, 0x4b, 0x22, 0x29, 0x34, 0x3f, 0x0e, 0x05, 0x18, 0x13,
0xca, 0xc1, 0xdc, 0xd7, 0xe6, 0xed, 0xf0, 0xfb, 0x92, 0x99, 0x84, 0x8f,
0xbe, 0xb5, 0xa8, 0xa3
], //*/ GBX = Gx(0xb),
/*
GDX = [
0x00, 0x0d, 0x1a, 0x17, 0x34, 0x39, 0x2e, 0x23, 0x68, 0x65, 0x72, 0x7f,
0x5c, 0x51, 0x46, 0x4b, 0xd0, 0xdd, 0xca, 0xc7, 0xe4, 0xe9, 0xfe, 0xf3,
0xb8, 0xb5, 0xa2, 0xaf, 0x8c, 0x81, 0x96, 0x9b, 0xbb, 0xb6, 0xa1, 0xac,
0x8f, 0x82, 0x95, 0x98, 0xd3, 0xde, 0xc9, 0xc4, 0xe7, 0xea, 0xfd, 0xf0,
0x6b, 0x66, 0x71, 0x7c, 0x5f, 0x52, 0x45, 0x48, 0x03, 0x0e, 0x19, 0x14,
0x37, 0x3a, 0x2d, 0x20, 0x6d, 0x60, 0x77, 0x7a, 0x59, 0x54, 0x43, 0x4e,
0x05, 0x08, 0x1f, 0x12, 0x31, 0x3c, 0x2b, 0x26, 0xbd, 0xb0, 0xa7, 0xaa,
0x89, 0x84, 0x93, 0x9e, 0xd5, 0xd8, 0xcf, 0xc2, 0xe1, 0xec, 0xfb, 0xf6,
0xd6, 0xdb, 0xcc, 0xc1, 0xe2, 0xef, 0xf8, 0xf5, 0xbe, 0xb3, 0xa4, 0xa9,
0x8a, 0x87, 0x90, 0x9d, 0x06, 0x0b, 0x1c, 0x11, 0x32, 0x3f, 0x28, 0x25,
0x6e, 0x63, 0x74, 0x79, 0x5a, 0x57, 0x40, 0x4d, 0xda, 0xd7, 0xc0, 0xcd,
0xee, 0xe3, 0xf4, 0xf9, 0xb2, 0xbf, 0xa8, 0xa5, 0x86, 0x8b, 0x9c, 0x91,
0x0a, 0x07, 0x10, 0x1d, 0x3e, 0x33, 0x24, 0x29, 0x62, 0x6f, 0x78, 0x75,
0x56, 0x5b, 0x4c, 0x41, 0x61, 0x6c, 0x7b, 0x76, 0x55, 0x58, 0x4f, 0x42,
0x09, 0x04, 0x13, 0x1e, 0x3d, 0x30, 0x27, 0x2a, 0xb1, 0xbc, 0xab, 0xa6,
0x85, 0x88, 0x9f, 0x92, 0xd9, 0xd4, 0xc3, 0xce, 0xed, 0xe0, 0xf7, 0xfa,
0xb7, 0xba, 0xad, 0xa0, 0x83, 0x8e, 0x99, 0x94, 0xdf, 0xd2, 0xc5, 0xc8,
0xeb, 0xe6, 0xf1, 0xfc, 0x67, 0x6a, 0x7d, 0x70, 0x53, 0x5e, 0x49, 0x44,
0x0f, 0x02, 0x15, 0x18, 0x3b, 0x36, 0x21, 0x2c, 0x0c, 0x01, 0x16, 0x1b,
0x38, 0x35, 0x22, 0x2f, 0x64, 0x69, 0x7e, 0x73, 0x50, 0x5d, 0x4a, 0x47,
0xdc, 0xd1, 0xc6, 0xcb, 0xe8, 0xe5, 0xf2, 0xff, 0xb4, 0xb9, 0xae, 0xa3,
0x80, 0x8d, 0x9a, 0x97
], //*/ GDX = Gx(0xd),
/*
GEX = [
0x00, 0x0e, 0x1c, 0x12, 0x38, 0x36, 0x24, 0x2a, 0x70, 0x7e, 0x6c, 0x62,
0x48, 0x46, 0x54, 0x5a, 0xe0, 0xee, 0xfc, 0xf2, 0xd8, 0xd6, 0xc4, 0xca,
0x90, 0x9e, 0x8c, 0x82, 0xa8, 0xa6, 0xb4, 0xba, 0xdb, 0xd5, 0xc7, 0xc9,
0xe3, 0xed, 0xff, 0xf1, 0xab, 0xa5, 0xb7, 0xb9, 0x93, 0x9d, 0x8f, 0x81,
0x3b, 0x35, 0x27, 0x29, 0x03, 0x0d, 0x1f, 0x11, 0x4b, 0x45, 0x57, 0x59,
0x73, 0x7d, 0x6f, 0x61, 0xad, 0xa3, 0xb1, 0xbf, 0x95, 0x9b, 0x89, 0x87,
0xdd, 0xd3, 0xc1, 0xcf, 0xe5, 0xeb, 0xf9, 0xf7, 0x4d, 0x43, 0x51, 0x5f,
0x75, 0x7b, 0x69, 0x67, 0x3d, 0x33, 0x21, 0x2f, 0x05, 0x0b, 0x19, 0x17,
0x76, 0x78, 0x6a, 0x64, 0x4e, 0x40, 0x52, 0x5c, 0x06, 0x08, 0x1a, 0x14,
0x3e, 0x30, 0x22, 0x2c, 0x96, 0x98, 0x8a, 0x84, 0xae, 0xa0, 0xb2, 0xbc,
0xe6, 0xe8, 0xfa, 0xf4, 0xde, 0xd0, 0xc2, 0xcc, 0x41, 0x4f, 0x5d, 0x53,
0x79, 0x77, 0x65, 0x6b, 0x31, 0x3f, 0x2d, 0x23, 0x09, 0x07, 0x15, 0x1b,
0xa1, 0xaf, 0xbd, 0xb3, 0x99, 0x97, 0x85, 0x8b, 0xd1, 0xdf, 0xcd, 0xc3,
0xe9, 0xe7, 0xf5, 0xfb, 0x9a, 0x94, 0x86, 0x88, 0xa2, 0xac, 0xbe, 0xb0,
0xea, 0xe4, 0xf6, 0xf8, 0xd2, 0xdc, 0xce, 0xc0, 0x7a, 0x74, 0x66, 0x68,
0x42, 0x4c, 0x5e, 0x50, 0x0a, 0x04, 0x16, 0x18, 0x32, 0x3c, 0x2e, 0x20,
0xec, 0xe2, 0xf0, 0xfe, 0xd4, 0xda, 0xc8, 0xc6, 0x9c, 0x92, 0x80, 0x8e,
0xa4, 0xaa, 0xb8, 0xb6, 0x0c, 0x02, 0x10, 0x1e, 0x34, 0x3a, 0x28, 0x26,
0x7c, 0x72, 0x60, 0x6e, 0x44, 0x4a, 0x58, 0x56, 0x37, 0x39, 0x2b, 0x25,
0x0f, 0x01, 0x13, 0x1d, 0x47, 0x49, 0x5b, 0x55, 0x7f, 0x71, 0x63, 0x6d,
0xd7, 0xd9, 0xcb, 0xc5, 0xef, 0xe1, 0xf3, 0xfd, 0xa7, 0xa9, 0xbb, 0xb5,
0x9f, 0x91, 0x83, 0x8d
], //*/ GEX = Gx(0xe),
enc = function(string, pass, binary) {
// string, password in plaintext
var salt = randArr(8),
pbe = openSSLKey(s2a(pass, binary), salt),
key = pbe.key,
iv = pbe.iv,
cipherBlocks,
saltBlock = [[83, 97, 108, 116, 101, 100, 95, 95].concat(salt)];
string = s2a(string, binary);
cipherBlocks = rawEncrypt(string, key, iv);
// Spells out 'Salted__'
cipherBlocks = saltBlock.concat(cipherBlocks);
return Base64.encode(cipherBlocks);
},
dec = function(string, pass, binary) {
// string, password in plaintext
var cryptArr = Base64.decode(string),
salt = cryptArr.slice(8, 16),
pbe = openSSLKey(s2a(pass, binary), salt),
key = pbe.key,
iv = pbe.iv;
cryptArr = cryptArr.slice(16, cryptArr.length);
// Take off the Salted__ffeeddcc
string = rawDecrypt(cryptArr, key, iv, binary);
return string;
},
MD5 = function(numArr) {
function rotateLeft(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
}
function addUnsigned(lX, lY) {
var lX4,
lY4,
lX8,
lY8,
lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function f(x, y, z) {
return (x & y) | ((~x) & z);
}
function g(x, y, z) {
return (x & z) | (y & (~z));
}
function h(x, y, z) {
return (x ^ y ^ z);
}
function funcI(x, y, z) {
return (y ^ (x | (~z)));
}
function ff(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(f(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function gg(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(g(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function hh(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(h(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function ii(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(funcI(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function convertToWordArray(numArr) {
var lWordCount,
lMessageLength = numArr.length,
lNumberOfWords_temp1 = lMessageLength + 8,
lNumberOfWords_temp2 = (lNumberOfWords_temp1 - (lNumberOfWords_temp1 % 64)) / 64,
lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16,
lWordArray = [],
lBytePosition = 0,
lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (numArr[lByteCount] << lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount - (lByteCount % 4)) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
}
function wordToHex(lValue) {
var lByte,
lCount,
wordToHexArr = [];
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
wordToHexArr = wordToHexArr.concat(lByte);
}
return wordToHexArr;
}
/*function utf8Encode(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "",
n,
c;
for (n = 0; n < string.length; n++) {
c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}*/
var x = [],
k,
AA,
BB,
CC,
DD,
a,
b,
c,
d,
rnd = strhex('67452301efcdab8998badcfe10325476d76aa478e8c7b756242070dbc1bdceeef57c0faf4787c62aa8304613fd469501698098d88b44f7afffff5bb1895cd7be6b901122fd987193a679438e49b40821f61e2562c040b340265e5a51e9b6c7aad62f105d02441453d8a1e681e7d3fbc821e1cde6c33707d6f4d50d87455a14eda9e3e905fcefa3f8676f02d98d2a4c8afffa39428771f6816d9d6122fde5380ca4beea444bdecfa9f6bb4b60bebfbc70289b7ec6eaa127fad4ef308504881d05d9d4d039e6db99e51fa27cf8c4ac5665f4292244432aff97ab9423a7fc93a039655b59c38f0ccc92ffeff47d85845dd16fa87e4ffe2ce6e0a30143144e0811a1f7537e82bd3af2352ad7d2bbeb86d391',8);
x = convertToWordArray(numArr);
a = rnd[0];
b = rnd[1];
c = rnd[2];
d = rnd[3];
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = ff(a, b, c, d, x[k + 0], 7, rnd[4]);
d = ff(d, a, b, c, x[k + 1], 12, rnd[5]);
c = ff(c, d, a, b, x[k + 2], 17, rnd[6]);
b = ff(b, c, d, a, x[k + 3], 22, rnd[7]);
a = ff(a, b, c, d, x[k + 4], 7, rnd[8]);
d = ff(d, a, b, c, x[k + 5], 12, rnd[9]);
c = ff(c, d, a, b, x[k + 6], 17, rnd[10]);
b = ff(b, c, d, a, x[k + 7], 22, rnd[11]);
a = ff(a, b, c, d, x[k + 8], 7, rnd[12]);
d = ff(d, a, b, c, x[k + 9], 12, rnd[13]);
c = ff(c, d, a, b, x[k + 10], 17, rnd[14]);
b = ff(b, c, d, a, x[k + 11], 22, rnd[15]);
a = ff(a, b, c, d, x[k + 12], 7, rnd[16]);
d = ff(d, a, b, c, x[k + 13], 12, rnd[17]);
c = ff(c, d, a, b, x[k + 14], 17, rnd[18]);
b = ff(b, c, d, a, x[k + 15], 22, rnd[19]);
a = gg(a, b, c, d, x[k + 1], 5, rnd[20]);
d = gg(d, a, b, c, x[k + 6], 9, rnd[21]);
c = gg(c, d, a, b, x[k + 11], 14, rnd[22]);
b = gg(b, c, d, a, x[k + 0], 20, rnd[23]);
a = gg(a, b, c, d, x[k + 5], 5, rnd[24]);
d = gg(d, a, b, c, x[k + 10], 9, rnd[25]);
c = gg(c, d, a, b, x[k + 15], 14, rnd[26]);
b = gg(b, c, d, a, x[k + 4], 20, rnd[27]);
a = gg(a, b, c, d, x[k + 9], 5, rnd[28]);
d = gg(d, a, b, c, x[k + 14], 9, rnd[29]);
c = gg(c, d, a, b, x[k + 3], 14, rnd[30]);
b = gg(b, c, d, a, x[k + 8], 20, rnd[31]);
a = gg(a, b, c, d, x[k + 13], 5, rnd[32]);
d = gg(d, a, b, c, x[k + 2], 9, rnd[33]);
c = gg(c, d, a, b, x[k + 7], 14, rnd[34]);
b = gg(b, c, d, a, x[k + 12], 20, rnd[35]);
a = hh(a, b, c, d, x[k + 5], 4, rnd[36]);
d = hh(d, a, b, c, x[k + 8], 11, rnd[37]);
c = hh(c, d, a, b, x[k + 11], 16, rnd[38]);
b = hh(b, c, d, a, x[k + 14], 23, rnd[39]);
a = hh(a, b, c, d, x[k + 1], 4, rnd[40]);
d = hh(d, a, b, c, x[k + 4], 11, rnd[41]);
c = hh(c, d, a, b, x[k + 7], 16, rnd[42]);
b = hh(b, c, d, a, x[k + 10], 23, rnd[43]);
a = hh(a, b, c, d, x[k + 13], 4, rnd[44]);
d = hh(d, a, b, c, x[k + 0], 11, rnd[45]);
c = hh(c, d, a, b, x[k + 3], 16, rnd[46]);
b = hh(b, c, d, a, x[k + 6], 23, rnd[47]);
a = hh(a, b, c, d, x[k + 9], 4, rnd[48]);
d = hh(d, a, b, c, x[k + 12], 11, rnd[49]);
c = hh(c, d, a, b, x[k + 15], 16, rnd[50]);
b = hh(b, c, d, a, x[k + 2], 23, rnd[51]);
a = ii(a, b, c, d, x[k + 0], 6, rnd[52]);
d = ii(d, a, b, c, x[k + 7], 10, rnd[53]);
c = ii(c, d, a, b, x[k + 14], 15, rnd[54]);
b = ii(b, c, d, a, x[k + 5], 21, rnd[55]);
a = ii(a, b, c, d, x[k + 12], 6, rnd[56]);
d = ii(d, a, b, c, x[k + 3], 10, rnd[57]);
c = ii(c, d, a, b, x[k + 10], 15, rnd[58]);
b = ii(b, c, d, a, x[k + 1], 21, rnd[59]);
a = ii(a, b, c, d, x[k + 8], 6, rnd[60]);
d = ii(d, a, b, c, x[k + 15], 10, rnd[61]);
c = ii(c, d, a, b, x[k + 6], 15, rnd[62]);
b = ii(b, c, d, a, x[k + 13], 21, rnd[63]);
a = ii(a, b, c, d, x[k + 4], 6, rnd[64]);
d = ii(d, a, b, c, x[k + 11], 10, rnd[65]);
c = ii(c, d, a, b, x[k + 2], 15, rnd[66]);
b = ii(b, c, d, a, x[k + 9], 21, rnd[67]);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
return wordToHex(a).concat(wordToHex(b), wordToHex(c), wordToHex(d));
},
encString = function(plaintext, key, iv) {
var i;
plaintext = s2a(plaintext);
key = s2a(key);
for (i=key.length; i<32; i++){
key[i] = 0;
}
if (iv === undefined) {
// TODO: This is not defined anywhere... commented out...
// iv = genIV();
} else {
iv = s2a(iv);
for (i=iv.length; i<16; i++){
iv[i] = 0;
}
}
var ct = rawEncrypt(plaintext, key, iv);
var ret = [iv];
for (i=0; i<ct.length; i++){
ret[ret.length] = ct[i];
}
return Base64.encode(ret);
},
decString = function(ciphertext, key) {
var tmp = Base64.decode(ciphertext);
var iv = tmp.slice(0, 16);
var ct = tmp.slice(16, tmp.length);
var i;
key = s2a(key);
for (i=key.length; i<32; i++){
key[i] = 0;
}
var pt = rawDecrypt(ct, key, iv, false);
return pt;
},
Base64 = (function(){
// Takes a Nx16x1 byte array and converts it to Base64
var _chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
chars = _chars.split(''),
encode = function(b, withBreaks) {
var flatArr = [],
b64 = '',
i,
broken_b64,
totalChunks = Math.floor(b.length * 16 / 3);
for (i = 0; i < b.length * 16; i++) {
flatArr.push(b[Math.floor(i / 16)][i % 16]);
}
for (i = 0; i < flatArr.length; i = i + 3) {
b64 += chars[flatArr[i] >> 2];
b64 += chars[((flatArr[i] & 3) << 4) | (flatArr[i + 1] >> 4)];
if ( flatArr[i + 1] !== undefined ) {
b64 += chars[((flatArr[i + 1] & 15) << 2) | (flatArr[i + 2] >> 6)];
} else {
b64 += '=';
}
if ( flatArr[i + 2] !== undefined ) {
b64 += chars[flatArr[i + 2] & 63];
} else {
b64 += '=';
}
}
// OpenSSL is super particular about line breaks
broken_b64 = b64.slice(0, 64) + '\n';
for (i = 1; i < (Math.ceil(b64.length / 64)); i++) {
broken_b64 += b64.slice(i * 64, i * 64 + 64) + (Math.ceil(b64.length / 64) === i + 1 ? '': '\n');
}
return broken_b64;
},
decode = function(string) {
string = string.replace(/\n/g, '');
var flatArr = [],
c = [],
b = [],
i;
for (i = 0; i < string.length; i = i + 4) {
c[0] = _chars.indexOf(string.charAt(i));
c[1] = _chars.indexOf(string.charAt(i + 1));
c[2] = _chars.indexOf(string.charAt(i + 2));
c[3] = _chars.indexOf(string.charAt(i + 3));
b[0] = (c[0] << 2) | (c[1] >> 4);
b[1] = ((c[1] & 15) << 4) | (c[2] >> 2);
b[2] = ((c[2] & 3) << 6) | c[3];
flatArr.push(b[0], b[1], b[2]);
}
flatArr = flatArr.slice(0, flatArr.length - (flatArr.length % 16));
return flatArr;
};
//internet explorer
if(typeof Array.indexOf === "function") {
_chars = chars;
}
/*
//other way to solve internet explorer problem
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]===obj){
return i;
}
}
return -1;
}
}
*/
return {
"encode": encode,
"decode": decode
};
})();
return {
"size": size,
"h2a":h2a,
"expandKey":expandKey,
"encryptBlock":encryptBlock,
"decryptBlock":decryptBlock,
"Decrypt":Decrypt,
"s2a":s2a,
"rawEncrypt":rawEncrypt,
"rawDecrypt":rawDecrypt,
"dec":dec,
"openSSLKey":openSSLKey,
"a2h":a2h,
"enc":enc,
"Hash":{"MD5":MD5},
"Base64":Base64
};
}));
|
export const FAKE_AUTH_DELAY = 2000
export const FAKE_SCHEDULE_FETCHING_DELAY = 2000
|
search_result['619']=["topic_0000000000000146.html","PostVacancyController.VacancyService Property",""];
|
var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var Format = require('./format');
var config = require('./config');
var Spreadsheet = function(options) {
this.filename = options.filename;
this.path = path.join(config.directory, this.filename);
this.format = new Format(options);
this.rows = options.rows || [];
};
Spreadsheet.prototype.exists = function(callback) {
fs.exists(this.path, callback);
};
Spreadsheet.prototype.has = function(id, callback) {
var spreadsheet = this;
this.read(id, function(err, data) {
callback(err, !_.isEmpty(data));
});
};
Spreadsheet.prototype.stats = function(callback) {
var spreadsheet = this;
var stats = {
filename: spreadsheet.filename,
format: spreadsheet.format.format
};
fs.stat(path.join(config.directory, this.filename), function(err, data) {
if (err) return callback(err);
stats.size = data.size;
stats.updated = data.mtime;
spreadsheet.read(function(err, data) {
if (err) return callback(err);
stats.records = _.size(data);
callback(null, stats);
});
});
};
Spreadsheet.prototype.create = function(rows, callback) {
if (typeof rows === 'function') {
callback = rows;
rows = this.rows || [];
}
var spreadsheet = this;
var format = this.format;
spreadsheet.exists(function(exists) {
if (exists) return callback(new Error('Spreadsheet already exists'));
format.create(function(err, status) {
if (err) return callback(err);
if (rows.length === 0) return callback(null, status);
spreadsheet.add(rows, function(err, status) {
if (err) callback(err);
else callback(null, status);
});
});
});
};
Spreadsheet.prototype.destroy = function(callback) {
var spreadsheet = this;
fs.unlink(path.join(config.directory, spreadsheet.filename), function(err) {
if (err) callback(err);
else callback(null, {ok: true});
});
};
Spreadsheet.prototype.read = function(query, callback) {
if (typeof query === 'function') {
callback = query;
query = {};
} else if (typeof query === 'string') {
query = {_id: query};
}
var spreadsheet = this;
var format = this.format;
format.read(function(err, data) {
if (err) return callback(err);
spreadsheet.filter(data, query, function(err, data) {
if (err) callback(err);
else callback(null, data);
});
});
};
var filters = [ '_id', 'skip', 'limit', 'sort', 'reverse', 'columns' ];
Spreadsheet.prototype.filter = function(data, options, callback) {
if (_.isEmpty(options)) return callback(null, data);
var query = _.omit(options, filters);
if (!_.isEmpty(query)) data = _.where(data, query);
_.each(filters, function(filter) {
if (!_.has(options, filter)) return false;
switch (filter) {
case '_id':
var query = {};
var idAttr = _.keys(data[0])[0];
query[idAttr] = options._id;
data = _.where(data, query);
break;
case 'skip':
data = _.rest(data, parseInt(options.skip));
break;
case 'limit':
data = _.first(data, parseInt(options.limit));
break;
case 'sort':
data = _.sortBy(data, options.sort);
break;
case 'reverse':
if (options.reverse === true) {
data = data.reverse();
}
break;
case 'columns':
if (_.isArray(options.columns)) {
data = _.map(data, function(row) {
return _.pick(row, options.columns);
});
}
break;
}
});
callback(null, data);
};
Spreadsheet.prototype.remove = function(rowId, callback) {
this.format.remove(rowId, function(err, status) {
if (err) callback(err);
else callback(null, status);
});
};
Spreadsheet.prototype.add = function(rows, callback) {
if (!_.isArray(rows)) rows = [rows];
this.format.add(rows, function(err, status) {
if (err) callback(err);
else callback(null, status);
});
};
module.exports = Spreadsheet;
|
'use strict';
// SisoController
angular.module('sisoweb').controller('SisoController', ['$scope', '$http', '$location', 'Sisoweb',
function ($scope, $http, $location, Sisoweb) {
$scope.showCheckOutDiv = false;
// Create new Profile
$scope.create = function (req, res) {
// Create new Profile object
var sisoweb = new Sisoweb({
fname: this.fname,
mname: this.mname,
lname: this.lname,
mfname: this.mfname,
mlname: this.mlname,
contact: this.contact,
location: this.location,
time: this.time
});
// Redirect after save
sisoweb.$save(function (err) {
console.log('after save');
// Clear form fields
$scope.fname = '';
$scope.mname = '';
$scope.lname = '';
$scope.mfname = '';
$scope.mlname = '';
$scope.contact = '';
$scope.location = '';
$scope.time = '';
});
};
// Find a list of sisoweb
$scope.find = function () {
console.log('in find');
$scope.sisos = Sisoweb.query();
};
// Find a list user checkins for Manager
$scope.listByManager = function (req, res) {
console.log('in sisoweb client controller listByManager(firstname): '+this.mfname+', lastname: '+this.mlname);
Sisoweb.query({ mfname:this.mfname,mlname:this.mlname }, function (sisos) {
console.log('sisoweb.client.controller, response : '+JSON.stringify(sisos));
$scope.sisos = sisos;
// Clear form fields
$scope.mfname = '';
$scope.mlname = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list user checkins for Manager
$scope.findUser = function (req, res) {
console.log('in sisoweb client controller findUser(firstname): "+this.fname+", lastname: '+this.lname);
$scope.showMessageDiv = false;
$scope.showCheckOutDiv = false;
$scope.showNoUserFoundDiv = false;
Sisoweb.query({ fname:this.fname,lname:this.lname }, function (sisos) {
//console.log("sisoweb.client.controller, response : "+JSON.stringify(sisos));
$scope.siso = sisos[0];
// Clear form fields
$scope.mfname = '';
$scope.mlname = '';
var sisoObj = JSON.stringify($scope.siso);
//console.log("sisoweb.client.controller, Single response : "+ sisoObj);
if(undefined === sisoObj) {
$scope.showNoUserFoundDiv = true;
} else {
$scope.showCheckOutDiv = true;
}
}, function (errorResponse) {
//console.log('************ ERROR ****************');
$scope.error = errorResponse.data.message;
});
};
// Remove existing Profile
$scope.remove = function (siso) {
$scope.showCheckOutDiv = false;
$scope.showMessageDiv = true;
if (siso) {
//console.log('sisoweb.client.controller, $scope.remove - '+siso);
siso.$remove();
} else {
//console.log('sisoweb.client.controller, $scope.remove else ***** :'+JSON.stringify($scope.siso));
$scope.siso.$remove(function () {
$location.path('sisoweb');
});
}
};
}
]);
|
'use strict';
(function() {
// Firme Controller Spec
describe('FirmeController', function() {
// Initialize global variables
var FirmeController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Firme controller.
FirmeController = $controller('FirmeController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one firma object fetched from XHR', inject(function(Firme) {
// Create sample firma using the Firme service
var sampleFirma = new Firme({
title: 'Firma de test',
content: 'MEAN rocks!'
});
// Create a sample firme array that includes the new firma
var sampleFirme = [sampleFirma];
// Set GET response
$httpBackend.expectGET('firme').respond(sampleFirme);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.firme).toEqualData(sampleFirme);
}));
it('$scope.findOne() should create an array with one firma object fetched from XHR using a firmaId URL parameter', inject(function(Firme) {
// Define a sample firma object
var sampleFirma = new Firme({
title: 'An Firma about MEAN',
content: 'MEAN rocks!'
});
// Set the URL parameter
$stateParams.firmaId = '525a8422f6d0f87f0e407a45';
// Set GET response
$httpBackend.expectGET(/firme\/([0-9a-fA-F]{24})$/).respond(sampleFirma);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.firma).toEqualData(sampleFirma);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Firme) {
// Create a sample firma object
var sampleFirmaPostData = new Firme({
title: 'A Firma about MEAN',
content: 'MEAN rocks!'
});
// Create a sample firma response
var sampleFirmaResponse = new Firme({
_id: '525cf20451979dea2c000023',
title: 'A Firma about MEAN',
content: 'MEAN rocks!'
});
// Fixture mock form input values
scope.title = 'An Firma about MEAN';
scope.content = 'MEAN rocks!';
// Set POST response
$httpBackend.expectPOST('firme', sampleFirmaPostData).respond(sampleFirmaResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.title).toEqual('');
expect(scope.content).toEqual('');
// Test URL redirection after the firma was created
expect($location.path()).toBe('/firme/' + sampleFirmaResponse._id);
}));
it('$scope.update() should update a valid firma', inject(function(Firme) {
// Define a sample firma put data
var sampleFirmaPutData = new Firme({
_id: '525cf20451979dea2c000001',
title: 'An Firma about MEAN',
content: 'MEAN Rocks!'
});
// Mock firma in scope
scope.firma = sampleFirmaPutData;
// Set PUT response
$httpBackend.expectPUT(/firme\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/firme/' + sampleFirmaPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid firmaId and remove the firma from the scope', inject(function(Firme) {
// Create new firma object
var sampleFirma = new Firme({
_id: '525a8422f6d0f87f0e407a65'
});
// Create new firme array and include the firma
scope.firme = [sampleFirma];
// Set expected DELETE response
$httpBackend.expectDELETE(/firme\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleFirma);
$httpBackend.flush();
// Test array after successful delete
expect(scope.firme.length).toBe(0);
}));
});
}());
|
import assert from 'assert';
import rng from '../../src/rng.js';
import rngBrowser from '../../src/rng-browser.js';
describe('rng', () => {
test('Node.js RNG', () => {
const bytes = rng();
assert.equal(bytes.length, 16);
for (let i = 0; i < bytes.length; ++i) {
assert.equal(typeof bytes[i], 'number');
}
});
test('Browser without crypto.getRandomValues()', () => {
assert.throws(() => {
rngBrowser();
});
});
// Test of whatwgRNG missing for now since with esmodules we can no longer manipulate the
// require.cache.
});
|
var mongoose = require('mongoose');
var schema = mongoose.Schema({
date: { type: Date, default: Date.now },
code: {type: String, required: true, unique: true},
humanId: {type: String, required: true, unique: true}
});
module.exports = mongoose.model('QrCode', schema);
|
const razzleHeroku = require("razzle-heroku")
const graphqlRegexp = /\.(graphql|gql)$/
const graphqlLoader = {
test: graphqlRegexp,
exclude: /node_modules/,
loader: "graphql-tag/loader",
}
const isFileLoader = rule => !rule.test
module.exports = {
modify: (config, {target, dev}, webpack) => {
config = razzleHeroku(config, {target, dev}, webpack)
// Exclude graphql files from file loaders
const fileLoaderIndex = config.module.rules.findIndex(isFileLoader)
config.module.rules[fileLoaderIndex].exclude.push(graphqlRegexp)
// Push graphqlLoader to rules
config.module.rules.push(graphqlLoader)
return config
},
}
|
var Story = {
DEFAULT_STORY: 'LostIsland',
options: {
inCommandEvent: false,
commandEventCallback: null, /* function */
canMove: true
},
activeStory: null,
playerMoves: 0,
previousRoom: null,
activeRoom: null,
init: function (options) {
this.options = $.extend(
this.options,
options
);
// Build the Story Pool
Story.StoryPool = [];
Story.StoryPool['LostIsland'] = Story.LostIsland;
// Set Story
var story = $SM.get('story.activeStory');
if (story == undefined) story = Story.setDefaultStory();
Story.setStory(story);
// Update Player Moves
var moves = $SM.get('story.moves');
if (moves == undefined) moves = 0;
Story.playerMoves = moves;
// Load Story
Story.activeStory.init();
// Create Room Panel
var roomPanel = $('<div>').attr('id', 'gameRoomPanel').appendTo('#gameMain');
Story.updateRoomPanel();
Story.checkUISettings();
//subscribe to stateUpdates
$.Dispatch('stateUpdate').subscribe(Story.handleStateUpdates);
},
checkUISettings: function () {
if (!Engine.ui.roomPanel) {
$('#gameRoomPanel').css({ 'display': 'none' });
} else {
$('#gameRoomPanel').css({ 'display': 'block' });
}
},
updateRoomPanel: function () {
$('#gameRoomPanel').html(''); // Clear
var activeRoom = Room.getRoom(Story.activeRoom);
// Header
$('<div>').addClass('gamePanelHeader').text(Story.activeStory.STORY_NAME).appendTo('#gameRoomPanel');
$('<div>').addClass('gamePanelHeader').css({ 'font-size': '14px', 'margin-bottom' : '10px' }).text(activeRoom.name).appendTo('#gameRoomPanel');
// Exits
var northExit = activeRoom.exits['north'];
if (northExit == undefined) northExit = 'None';
else if (northExit.room.visited != undefined && northExit.room.visited) northExit = northExit.room.name;
else northExit = 'Unknown';
$('<div>').addClass('roomExitItem').html('<b>North</b> - ' + northExit).appendTo('#gameRoomPanel');
var eastExit = activeRoom.exits['east'];
if (eastExit == undefined) eastExit = 'None';
else if (eastExit.room.visited != undefined && eastExit.room.visited) eastExit = eastExit.room.name;
else eastExit = 'Unknown';
$('<div>').addClass('roomExitItem').html('<b>East</b> - ' + eastExit).appendTo('#gameRoomPanel');
var southExit = activeRoom.exits['south'];
if (southExit == undefined) southExit = 'None';
else if (southExit.room.visited != undefined && southExit.room.visited) southExit = southExit.room.name;
else southExit = 'Unknown';
$('<div>').addClass('roomExitItem').html('<b>South</b> - ' + southExit).appendTo('#gameRoomPanel');
var westExit = activeRoom.exits['west'];
if (westExit == undefined) westExit = 'None';
else if (westExit.room.visited != undefined && westExit.room.visited) westExit = westExit.room.name;
else westExit = 'Unknown';
$('<div>').addClass('roomExitItem').html('<b>West</b> - ' + westExit).appendTo('#gameRoomPanel');
},
go: function (direction) {
var activeRoom = Room.getRoom(Story.activeRoom);
if (direction == "back") {
if (Story.previousRoom == null) {
Notifications.notify("There is nowhere to go back too.");
return;
}
var previousRoom = Room.getRoom(Story.previousRoom);
previousRoom.canEnterFunc(); // Trigger Func
if (previousRoom.canEnter) {
var curRoom = activeRoom;
curRoom.triggerExit();
Notifications.clear(Commands.LAST_COMMAND); // Clear Notifications
Story.setRoom(previousRoom);
Story.previousRoom = curRoom;
} else {
Notifications.notify(previousRoom.lockedDesc);
}
}
if (activeRoom.exits[direction] === undefined) {
Notifications.notify("There is no exit '" + direction + "'.");
} else {
var exitRoom = activeRoom.exits[direction].room;
exitRoom.canEnterFunc(); // Trigger Func
if (exitRoom.canEnter) {
var curRoom = activeRoom;
if (activeRoom.exits[direction].onChange != undefined && typeof activeRoom.exits[direction].onChange == 'function') {
var result = activeRoom.exits[direction].onChange();
if (!result) {
return;
}
}
curRoom.triggerExit();
Notifications.clear(Commands.LAST_COMMAND); // Clear Notifications
Story.setRoom(exitRoom);
Story.previousRoom = curRoom;
} else {
Notifications.notify(exitRoom.lockedDesc);
}
}
},
look: function() {
Room.getRoom(Story.activeRoom).triggerLook();
},
setRoom: function(room) {
if (room === undefined) return;
if (typeof room != 'object') {
room = Room.getRoom(room);
}
Story.activeRoom = room.id;
$SM.set('story.room', Story.activeRoom);
$SM.set('story.moves', Story.playerMoves++);
// Trigger Room Enter
room.triggerEnter();
Story.updateRoomPanel();
},
setStory: function (story) {
if (story === undefined) return;
Story.activeStory = Story.StoryPool[story];
},
setDefaultStory: function () {
$SM.set('story.activeStory', Story.DEFAULT_STORY);
return Story.DEFAULT_STORY;
},
addStoryEvent: function (event) {
// Add event to story events
Events.Story.push(event);
Events.updateEventPool();
},
addEncounterEvent: function (encounter) {
// Add Encounter
Events.Encounters.push(encounter);
},
handleStateUpdates: function (e) {
}
};
|
describe('My suite', function () {
beforeEach(inject(function () {
<selection>someService</selection>
}));
});
|
/*
Rest Query
Copyright (c) 2014 - 2021 Cédric Ronvel
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
"use strict" ;
var restQuery = require( '..' ) ;
var Promise = require( 'seventh' ) ;
var log = restQuery.log.global.use( 'scripts' ) ;
module.exports = {
test: async function( app , args ) {
log.info( "This is a test script, arguments: %I" , args ) ;
} ,
nested: {
test: async function( app , args ) {
log.info( "This is a NESTED test script, arguments: %I" , args ) ;
}
}
} ;
|
(function (app) {
'use strict';
app.registerModule('d3s');
})(ApplicationConfiguration);
|
const webpack = require('webpack');
const argv = require('yargs').argv;
let webpackConfig = require('./webpack.config');
webpackConfig.devtool = '#inline-source-map';
delete webpackConfig.vue.loaders.sass;
delete webpackConfig.entry;
module.exports = function (config) {
config.set({
browsers : ['PhantomJS'],
frameworks : ['jasmine'],
reporters : ['spec', 'coverage'],
singleRun : !argv.watch,
files : [
'../node_modules/babel-polyfill/dist/polyfill.js',
'./spec.js'
],
preprocessors : {
'./spec.js': ['webpack', 'sourcemap']
},
webpack : webpackConfig,
webpackMiddleware: {
noInfo: true,
},
coverageReporter : {
dir : '../reports/coverage',
reporters: [
{type: 'lcov', subdir: '.'},
{type: 'text-summary'},
]
},
});
};
|
import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
// Import Style
// import styles from './Series.css';
import {fetchSeries} from '../SeriesActions';
import SeriesSectionsView from '../components/SeriesSections/SeriesSections'
class SeriesOverview extends Component {
componentDidMount() {
this.props.dispatch(fetchSeries());
}
render() {
return (
<div>
<h2 className="series-page-title">series</h2>
<div className="row">
<SeriesSectionsView series={this.props.series}/>
</div>
</div>
);
}
}
SeriesOverview.need = [() => {
return fetchSeries();
}
];
const mapStateToProps = (state) => {
return {series: state.series.data}
}
// const mapDispatchToProps = (dispatch) => {
// return {};
// };
SeriesOverview.propTypes = {
dispatch: PropTypes.func.isRequired
};
export default connect(mapStateToProps)(SeriesOverview);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.