code stringlengths 2 1.05M |
|---|
version https://git-lfs.github.com/spec/v1
oid sha256:08a16b5f0f20cf7bd4703290135812b212d199446e9af5aea65f81626aa4ad96
size 3239
|
/**
* Created by King Lee on 14-12-11.
*/
var db = require('./mysql/dboperator');
var userInfo = require('./userInfo.js').userInfo;
var user = require("./user.js");
var analysis = require('./module/analysis');
var consts = require('./util/consts');
var db = require('./mysql/dboperator');
//exports.onGetEnergy = function(req,res){
// var uid = parseInt(req.body["uid"]);
// var result = { error: "" };
// analysis.getInfo(uid,function(info){
// if(!info){
// console.log("没有这个账号");
// return;
// }
// var scores = analysis.getScore(info,consts.TYPE_TIME.TYPE_TIME_TODAY,consts.TYPE_SCORE.TYPE_SCORE_ENERGY,new Date());
// result.scores = scores[0];
// console.log(result);
// res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
// res.end(JSON.stringify(result));
// });
//};
exports.onGetEnergy = function(req,res){
var uid = parseInt(req.body["uid"]);
var result = { error: "" };
var date= new Date();
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
var aDate = year+"-"+month+"-"+day;
db.getEnergyCache(uid,aDate,function(err,result1){
if(err){
result.err=err;
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(result));
}
if(result1!=null&&result1.length>0){
result.scores = result1[0];
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(result));
}else{
analysis.getInfo(uid,function(info){
if(!info){
console.log("没有这个账号");
return;
}
var scores = analysis.getScore(info,consts.TYPE_TIME.TYPE_TIME_TODAY,consts.TYPE_SCORE.TYPE_SCORE_ENERGY,new Date());
db.getEnergyCache2(uid,function(err,res2){
if(err){
result.err=err;
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(result));
}
if(res2.length>0){
db.updateEnergyCacheDay(uid,scores[0],aDate,function(err){
if(err){
result.err=err;
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(result));
}
});
}else{
db.insertEnergyCache(uid,scores[0],aDate,function(err){
if(err){
result.err=err;
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(result));
}
});
}
});
result.scores = scores[0];
console.log(result);
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
res.end(JSON.stringify(result));
});
}
});
}; |
module.exports = function(Book) {
};
|
var Utils = require('./../utils')
module.exports = (function() {
var HasManyDoubleLinked = function(definition, instance) {
this.__factory = definition
this.instance = instance
}
HasManyDoubleLinked.prototype.injectGetter = function(options) {
var self = this, _options = options
var customEventEmitter = new Utils.CustomEventEmitter(function() {
var where = {}, options = _options || {};
//fully qualify
where[self.__factory.connectorDAO.tableName+"."+self.__factory.identifier] = self.instance.id
var primaryKeys = Utils._.keys(self.__factory.connectorDAO.rawAttributes)
, foreignKey = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0]
where[self.__factory.connectorDAO.tableName+"."+foreignKey] = {join: self.__factory.target.tableName+".id"}
if (options.where) {
Utils._.each(options.where, function(value, index) {
delete options.where[index];
options.where[self.__factory.target.tableName+"."+index] = value;
});
Utils._.extend(options.where, where)
} else {
options.where = where;
}
self.__factory.target.findAllJoin(self.__factory.connectorDAO.tableName, options)
.on('success', function(objects) { customEventEmitter.emit('success', objects) })
.on('error', function(err){ customEventEmitter.emit('error', err) })
.on('sql', function(sql) { customEventEmitter.emit('sql', sql)})
})
return customEventEmitter.run()
}
HasManyDoubleLinked.prototype.injectSetter = function(emitterProxy, oldAssociations, newAssociations) {
var self = this
destroyObsoleteAssociations
.call(this, oldAssociations, newAssociations)
.on('sql', function(sql) { emitterProxy.emit('sql', sql) })
.error(function(err) { emitterProxy.emit('error', err) })
.success(function() {
var chainer = new Utils.QueryChainer
, association = self.__factory.target.associations[self.__factory.associationAccessor]
, foreignIdentifier = association.isSelfAssociation ? association.foreignIdentifier : association.identifier
, unassociatedObjects = newAssociations.filter(function(obj) { return !obj.equalsOneOf(oldAssociations) })
unassociatedObjects.forEach(function(unassociatedObject) {
var attributes = {}
attributes[self.__factory.identifier] = self.instance.id
attributes[foreignIdentifier] = unassociatedObject.id
chainer.add(self.__factory.connectorDAO.create(attributes))
})
chainer
.run()
.success(function() { emitterProxy.emit('success', newAssociations) })
.error(function(err) { emitterProxy.emit('error', err) })
.on('sql', function(sql) { emitterProxy.emit('sql', sql) })
})
}
// private
var destroyObsoleteAssociations = function(oldAssociations, newAssociations) {
var self = this
return new Utils.CustomEventEmitter(function(emitter) {
var chainer = new Utils.QueryChainer()
var foreignIdentifier = self.__factory.target.associations[self.__factory.associationAccessor].identifier
var obsoleteAssociations = oldAssociations.filter(function(obj) { return !obj.equalsOneOf(newAssociations) })
if(obsoleteAssociations.length === 0) {
return emitter.emit('success', null)
}
obsoleteAssociations.forEach(function(associatedObject) {
var where = {}
, primaryKeys = Utils._.keys(self.__factory.connectorDAO.rawAttributes)
, foreignKey = primaryKeys.filter(function(pk) { return pk != self.__factory.identifier })[0]
, notFoundEmitters = []
where[self.__factory.identifier] = self.instance.id
where[foreignKey] = associatedObject.id
self.__factory.connectorDAO
.find({ where: where })
.success(function(connector) {
if(connector === null) {
notFoundEmitters.push(null)
} else {
chainer.add(connector.destroy())
}
if((chainer.emitters.length + notFoundEmitters.length) === obsoleteAssociations.length) {
// found all obsolete connectors and will delete them now
chainer
.run()
.success(function() { emitter.emit('success', null) })
.error(function(err) { emitter.emit('error', err) })
.on('sql', function(sql) { emitter.emit('sql', sql) })
}
})
.error(function(err) { emitter.emit('error', err) })
.on('sql', function(sql) { emitter.emit('sql', sql) })
})
}).run()
}
return HasManyDoubleLinked
})()
|
'use strict';
angular.module(ApplicationConfiguration.applicationModuleName)
.controller('SidenavController',
function(Authentication, Products, Menus) {
this.authentication = Authentication;
this.menu = Menus.getMenu('sidenav');
this.selected = '';
this.isSelected = function(item) {
return this.selected === item;
};
this.selectItem = function(item) {
console.log('selecting '+item);
this.selected = item;
};
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=document.js.map |
var virt = require("@nathanfaucett/virt"),
virtDOM = require("@nathanfaucett/virt-dom"),
css = require("@nathanfaucett/css"),
propTypes = require("@nathanfaucett/prop_types"),
domDimensions = require("@nathanfaucett/dom_dimensions"),
getImageDimensions = require("../../utils/getImageDimensions");
var ItemPrototype;
module.exports = Item;
function Item(props, children, context) {
var _this = this;
virt.Component.call(this, props, children, context);
this.state = {
loaded: false,
ratio: 1,
width: 0,
height: 0,
top: 0,
left: 0
};
this.onMouseOver = function(e) {
return _this.__onMouseOver(e);
};
this.onMouseOut = function(e) {
return _this.__onMouseOut(e);
};
this.onClick = function(e) {
return _this.__onClick(e);
};
this.onLoad = function(e) {
return _this.__onLoad(e);
};
}
virt.Component.extend(Item, "Item");
ItemPrototype = Item.prototype;
Item.propTypes = {
item: propTypes.object.isRequired,
height: propTypes.number.isRequired
};
Item.contextTypes = {
theme: propTypes.object.isRequired
};
ItemPrototype.__onLoad = function() {
if (!this.state.loaded) {
this.getImageDimensions();
}
};
ItemPrototype.__onMouseOver = function() {
this.setState({
hover: true
});
};
ItemPrototype.__onMouseOut = function() {
this.setState({
hover: false
});
};
ItemPrototype.getImageDimensions = function() {
var node = virtDOM.findDOMNode(this),
dims = getImageDimensions(
virtDOM.findDOMNode(this.refs.img),
domDimensions.width(node),
domDimensions.height(node)
);
this.setState({
loaded: true,
width: dims.width,
height: dims.height,
top: -dims.top,
left: -dims.left
});
};
ItemPrototype.getStyles = function() {
var context = this.context,
theme = context.theme,
state = this.state,
props = this.props,
styles = {
root: {
position: "relative",
height: props.height + "px",
overflow: "hidden"
},
hover: {
zIndex: 1,
display: "block",
cursor: "pointer",
position: "absolute",
width: "100%",
height: props.height + "px",
background: theme.palette.accent2Color // theme.palette.canvasColor
},
imgWrap: {
zIndex: 0,
position: "relative"
},
img: {
position: "absolute",
maxWidth: "inherit",
top: state.top + "px",
left: state.left + "px",
width: state.loaded ? state.width + "px" : "inherit",
height: state.loaded ? state.height + "px" : "inherit"
}
};
css.transition(styles.hover, "opacity 300ms cubic-bezier(.25,.8,.25,1)");
if (state.hover) {
css.opacity(styles.hover, 0.5);
} else {
css.opacity(styles.hover, 0);
}
return styles;
};
ItemPrototype.render = function() {
var styles = this.getStyles(),
item = this.props.item;
return (
virt.createView("div", {
className: "Item",
style: styles.root
},
virt.createView("a", {
onMouseOver: this.onMouseOver,
onMouseOut: this.onMouseOut,
href: "/residential_gallery/" + this.props.item.id,
style: styles.hover
}),
virt.createView("div", {
style: styles.imgWrap
},
virt.createView("img", {
onLoad: this.onLoad,
style: styles.img,
ref: "img",
src: item.thumbnail
})
)
)
);
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:fd4973a8a7ab92728eae7c3758d9109a74a8d538c88679427d919ec9bc4e3f44
size 8326
|
/*
# Also times each request
# Stops after given amount of requests
*/
var request = require('request');
var async = require('async');
var found = [];
var times = {};
var maxCalls=process.argv[2] && Number(process.argv[2]) || 10;
var totalCalls = 0;
var url = "https://www.raspberrypi.org/blog/the-little-computer-that-could/";
//var url = "http://localhost:3000/";
function tally() {
console.log("\nTallying data");
var sortedFound = found.sort();
var totalRequests =0;
sortedFound.forEach(function(foundServer) {
var entry = times[foundServer];
entry.average = (entry.runningTotal / entry.responses).toFixed(2);
totalRequests += entry.responses;
});
sortedFound.forEach(function(server) {
console.log("[" + server + "]\t" + times[server].average + " ms (avg)");
});
console.log("Total requests: " + totalRequests);
process.exit();
}
async.until(function() {
return totalCalls >= maxCalls;
}, function(cb) {
var ticksStart = new Date().getTime();
request.head(url,
function(err, res, body) {
var ticksEnd = new Date().getTime();
var servedBy = res.headers['x-served-by'];
if(found.indexOf(servedBy)==-1){
found.push(servedBy);
times[servedBy] = {runningTotal: 0, responses: 0}
}
var total = ticksEnd - ticksStart;
times[servedBy]["responses"] = times[servedBy]["responses"] +1;
times[servedBy]["runningTotal"] =times[servedBy]["runningTotal"] + total;
process.stdout.write(".")
totalCalls = totalCalls +1;
cb();
});
}, function() {
tally();
});
process.on('SIGINT', function() {
tally();
})
|
{
"name": "dictatemp3.js",
"url": "https://github.com/kdavis-mozilla/dictatemp3.js.git"
}
|
var animationManager = (function(){
var moduleOb = {};
var registeredAnimations = [];
var initTime = 0;
var len = 0;
var idled = true;
var playingAnimationsNum = 0;
function removeElement(ev){
var i = 0;
var animItem = ev.target;
while(i<len) {
if (registeredAnimations[i].animation === animItem) {
registeredAnimations.splice(i, 1);
i -= 1;
len -= 1;
if(!animItem.isPaused){
subtractPlayingCount();
}
}
i += 1;
}
}
function registerAnimation(element, animationData){
if(!element){
return null;
}
var i=0;
while(i<len){
if(registeredAnimations[i].elem == element && registeredAnimations[i].elem !== null ){
return registeredAnimations[i].animation;
}
i+=1;
}
var animItem = new AnimationItem();
animItem.setData(element, animationData);
setupAnimation(animItem, element);
return animItem;
}
function addPlayingCount(){
playingAnimationsNum += 1;
activate();
}
function subtractPlayingCount(){
playingAnimationsNum -= 1;
if(playingAnimationsNum === 0){
idled = true;
}
}
function setupAnimation(animItem, element){
animItem.addEventListener('destroy',removeElement);
animItem.addEventListener('_active',addPlayingCount);
animItem.addEventListener('_idle',subtractPlayingCount);
registeredAnimations.push({elem: element,animation:animItem});
len += 1;
}
function loadAnimation(params){
var animItem = new AnimationItem();
setupAnimation(animItem, null);
animItem.setParams(params);
return animItem;
}
function setSpeed(val,animation){
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.setSpeed(val, animation);
}
}
function setDirection(val, animation){
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.setDirection(val, animation);
}
}
function play(animation){
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.play(animation);
}
}
function moveFrame (value, animation) {
initTime = Date.now();
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.moveFrame(value,animation);
}
}
function resume(nowTime) {
var elapsedTime = nowTime - initTime;
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.advanceTime(elapsedTime);
}
initTime = nowTime;
if(!idled) {
requestAnimationFrame(resume);
}
}
function first(nowTime){
initTime = nowTime;
requestAnimationFrame(resume);
}
function pause(animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.pause(animation);
}
}
function goToAndStop(value,isFrame,animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.goToAndStop(value,isFrame,animation);
}
}
function stop(animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.stop(animation);
}
}
function togglePause(animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.togglePause(animation);
}
}
function destroy(animation) {
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.destroy(animation);
}
}
function searchAnimations(animationData, standalone, renderer){
var animElements = document.getElementsByClassName('bodymovin');
var i, len = animElements.length;
for(i=0;i<len;i+=1){
if(renderer){
animElements[i].setAttribute('data-bm-type',renderer);
}
registerAnimation(animElements[i], animationData);
}
if(standalone && len === 0){
if(!renderer){
renderer = 'svg';
}
var body = document.getElementsByTagName('body')[0];
body.innerHTML = '';
var div = document.createElement('div');
div.style.width = '100%';
div.style.height = '100%';
div.setAttribute('data-bm-type',renderer);
body.appendChild(div);
registerAnimation(div, animationData);
}
}
function resize(){
var i;
for(i=0;i<len;i+=1){
registeredAnimations[i].animation.resize();
}
}
function start(){
requestAnimationFrame(first);
}
function activate(){
if(idled){
idled = false;
if(Performance && Performance.now){
first(Performance.now);
} else {
requestAnimationFrame(first);
}
}
}
//start();
setTimeout(start,0);
moduleOb.registerAnimation = registerAnimation;
moduleOb.loadAnimation = loadAnimation;
moduleOb.setSpeed = setSpeed;
moduleOb.setDirection = setDirection;
moduleOb.play = play;
moduleOb.moveFrame = moveFrame;
moduleOb.pause = pause;
moduleOb.stop = stop;
moduleOb.togglePause = togglePause;
moduleOb.searchAnimations = searchAnimations;
moduleOb.resize = resize;
moduleOb.start = start;
moduleOb.goToAndStop = goToAndStop;
moduleOb.destroy = destroy;
return moduleOb;
}()); |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M20 12c0-2.54-1.19-4.81-3.04-6.27l-.68-4.06C16.12.71 15.28 0 14.31 0H9.7c-.98 0-1.82.71-1.98 1.67l-.67 4.06C5.19 7.19 4 9.45 4 12s1.19 4.81 3.05 6.27l.67 4.06c.16.96 1 1.67 1.98 1.67h4.61c.98 0 1.81-.71 1.97-1.67l.68-4.06C18.81 16.81 20 14.54 20 12zM6 12c0-3.31 2.69-6 6-6s6 2.69 6 6-2.69 6-6 6-6-2.69-6-6z"
}), 'WatchRounded'); |
version https://git-lfs.github.com/spec/v1
oid sha256:dfe5fa2ebffe79836b83fbd3beed535e24ad52427c400b2213e62ee494bcdc88
size 10638
|
version https://git-lfs.github.com/spec/v1
oid sha256:60116bcfa89b731940c3217d4fec2282f1a071ed0d89e789ec3c4a105157647c
size 6462
|
'use strict';
var prettify = require('gulp-jsbeautifier');
var diff = require('gulp-diff').diff;
var diffReporter = require('gulp-diff').reporter;
module.exports = function(gulp, conf) {
gulp.task('beautify', function() {
var task = gulp.src([
'!node_modules/**/*.js',
'!public/**/*.js',
'**/*.js'
], {
base: './'
})
.pipe(prettify({
config: '.jsbeautifyrc',
mode: 'VERIFY_AND_WRITE'
}))
.pipe(diff())
.pipe(diffReporter());
if (conf.args.write) {
// if task is run with `--write` then overwrite source files
task.pipe(gulp.dest('./'));
} else {
task.on('data', function(data) {
if (data.diff && Object.keys(data.diff).length) {
// record that there have been errors
gulp.fail = true;
}
});
}
return task;
});
};
|
module.exports = function (gulp, plugins) {
gulp.task('compileAssets', function(cb) {
plugins.sequence(
'clean:dev',
'jst:dev',
'sass:dev',
'autoprefix:dev',
'copy:dev',
'coffee:dev',
'svg:dev',
cb
);
});
};
|
import { escapeHTML } from '@rocket.chat/string-helpers';
import { Migrations } from '../../../app/migrations';
import { Rooms, Messages } from '../../../app/models';
Migrations.add({
version: 55,
up() {
Rooms.find({ topic: { $exists: 1, $ne: '' } }, { topic: 1 }).forEach(function(room) {
const topic = escapeHTML(room.topic);
Rooms.update({ _id: room._id }, { $set: { topic } });
Messages.update({ t: 'room_changed_topic', rid: room._id }, { $set: { msg: topic } });
});
},
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2020 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var GetTilesWithin = require('./GetTilesWithin');
/**
* @callback FindTileCallback
*
* @param {Phaser.Tilemaps.Tile} value - The Tile.
* @param {integer} index - The index of the tile.
* @param {Phaser.Tilemaps.Tile[]} array - An array of Tile objects.
*
* @return {boolean} Return `true` if the callback should run, otherwise `false`.
*/
/**
* Find the first tile in the given rectangular area (in tile coordinates) of the layer that
* satisfies the provided testing function. I.e. finds the first tile for which `callback` returns
* true. Similar to Array.prototype.find in vanilla JS.
*
* @function Phaser.Tilemaps.Components.FindTile
* @private
* @since 3.0.0
*
* @param {FindTileCallback} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter.
* @param {object} [context] - The context under which the callback should be run.
* @param {integer} [tileX=0] - The left most tile index (in tile coordinates) to use as the origin of the area to filter.
* @param {integer} [tileY=0] - The top most tile index (in tile coordinates) to use as the origin of the area to filter.
* @param {integer} [width=max width based on tileX] - How many tiles wide from the `tileX` index the area will be.
* @param {integer} [height=max height based on tileY] - How many tiles tall from the `tileY` index the area will be.
* @param {object} [filteringOptions] - Optional filters to apply when getting the tiles.
* @param {boolean} [filteringOptions.isNotEmpty=false] - If true, only return tiles that don't have -1 for an index.
* @param {boolean} [filteringOptions.isColliding=false] - If true, only return tiles that collide on at least one side.
* @param {boolean} [filteringOptions.hasInterestingFace=false] - If true, only return tiles that have at least one interesting face.
* @param {Phaser.Tilemaps.LayerData} layer - The Tilemap Layer to act upon.
*
* @return {?Phaser.Tilemaps.Tile} A Tile that matches the search, or null if no Tile found
*/
var FindTile = function (callback, context, tileX, tileY, width, height, filteringOptions, layer)
{
var tiles = GetTilesWithin(tileX, tileY, width, height, filteringOptions, layer);
return tiles.find(callback, context) || null;
};
module.exports = FindTile;
|
/*jshint jasmine: true */
/*global inject, module */
describe('Checklist utility service', function () {
'use strict';
var bbChecklistUtility,
items;
beforeEach(module('sky.checklist.utility'));
beforeEach(inject(function (_bbChecklistUtility_) {
bbChecklistUtility = _bbChecklistUtility_;
}));
beforeEach(function () {
items = [
{
prop1: 'A',
prop2: 'b'
},
{
prop1: 'c',
prop2: 'D'
},
{
prop1: 'E',
prop2: 'f'
}
];
});
describe('add() method', function () {
it('should add an item to the array if an item with matching properties doesn\'t already exist', function () {
var itemsCopy,
length = items.length,
newItem;
newItem = {
prop1: 'G',
prop2: 'h'
};
bbChecklistUtility.add(items, newItem);
length = items.length;
expect(items[length - 1]).toBe(newItem);
itemsCopy = items.slice(0);
bbChecklistUtility.add(
items,
{
prop1: 'A',
prop2: 'b'
}
);
expect(items).toEqual(itemsCopy);
});
it('should create and return a new array if one is not supplied', function () {
var newItems = bbChecklistUtility.add(null, {
a: 'b'
});
expect(newItems).toEqual([{
a: 'b'
}]);
});
});
describe('remove() method', function () {
it('should remove an item whose properties are the same as the specified object', function () {
var itemToRemove = items[0];
bbChecklistUtility.remove(items, {
prop1: 'A',
prop2: 'b'
});
expect(items[0]).not.toBe(itemToRemove);
});
});
describe('contains() method', function () {
it('should match an item with the same properties as the specified object', function () {
expect(bbChecklistUtility.contains(items, {
prop1: 'A',
prop2: 'b'
})).toBe(true);
expect(bbChecklistUtility.contains(items, {
prop1: 'a',
prop2: 'B'
})).toBe(false);
});
});
}); |
'use strict';
angular.module('palaso.ui.dc.picture', ['palaso.ui.dc.multitext', 'palaso.ui.notice',
'ngFileUpload'])
// Palaso UI Dictionary Control: Picture
.directive('dcPicture', [function () {
return {
restrict: 'E',
templateUrl: '/angular-app/languageforge/lexicon/editor/field/dc-picture.html',
scope: {
config: '=',
pictures: '=',
control: '='
},
controller: ['$scope', '$state', 'Upload', '$filter', 'sessionService', 'lexProjectService',
'lexConfigService', 'silNoticeService', 'modalService',
function ($scope, $state, Upload, $filter, sessionService, lexProjectService,
lexConfigService, notice, modalService) {
$scope.$state = $state;
$scope.upload = {};
$scope.upload.progress = 0;
$scope.upload.file = null;
$scope.fieldContainsData = lexConfigService.fieldContainsData;
$scope.getPictureUrl = function getPictureUrl(picture) {
if (isExternalReference(picture.fileName))
return '/Site/views/shared/image/placeholder.png';
return '/assets/lexicon/' + $scope.control.project.slug + '/pictures/' + picture.fileName;
};
$scope.getPictureDescription = function getPictureDescription(picture) {
if (!isExternalReference(picture.fileName)) return picture.fileName;
return 'This picture references an external file (' +
picture.fileName +
') and therefore cannot be synchronized. ' +
'To see the picture, link it to an internally referenced file. ' +
'Replace the file here or in FLEx, move or copy the file to the Linked Files folder.';
};
function isExternalReference(fileName) {
var isWindowsLink = (fileName.indexOf(':\\') >= 0);
var isLinuxLink = (fileName.indexOf('//') >= 0);
return isWindowsLink || isLinuxLink;
}
// strips the timestamp file prefix (returns everything after the '_')
function originalFileName(fileName) {
return fileName.substr(fileName.indexOf('_') + 1);
}
function addPicture(fileName) {
var newPicture = {};
var captionConfig = angular.copy($scope.config);
captionConfig.type = 'multitext';
newPicture.fileName = fileName;
newPicture.caption = $scope.control.makeValidModelRecursive(captionConfig, {});
$scope.pictures.push(newPicture);
}
$scope.deletePicture = function deletePicture(index) {
var fileName = $scope.pictures[index].fileName;
if (fileName) {
var deleteMsg = "Are you sure you want to delete the picture <b>'" +
originalFileName(fileName) + "'</b>";
modalService.showModalSimple('Delete Picture', deleteMsg, 'Cancel', 'Delete Picture').
then(function () {
$scope.pictures.splice(index, 1);
lexProjectService.removeMediaFile('sense-image', fileName, function (result) {
if (result.ok) {
if (!result.data.result) {
notice.push(notice.ERROR, result.data.errorMessage);
}
}
});
}, angular.noop);
} else {
$scope.pictures.splice(index, 1);
}
};
$scope.uploadFile = function uploadFile(file) {
if (!file || file.$error) return;
sessionService.getSession().then(function (session) {
if (file.size > session.fileSizeMax()) {
$scope.upload.progress = 0;
$scope.upload.file = null;
notice.push(notice.ERROR, '<b>' + file.name + '</b> (' +
$filter('bytes')(file.size) + ') is too large. It must be smaller than ' +
$filter('bytes')(session.fileSizeMax()) + '.');
return;
}
$scope.upload.file = file;
$scope.upload.progress = 0;
Upload.upload({
url: '/upload/lf-lexicon/sense-image',
data: { file: file }
}).then(function (response) {
var isUploadSuccess = response.data.result;
if (isUploadSuccess) {
$scope.upload.progress = 100.0;
addPicture(response.data.data.fileName);
$scope.upload.showAddPicture = false;
} else {
$scope.upload.progress = 0;
notice.push(notice.ERROR, response.data.data.errorMessage);
}
$scope.upload.file = null;
},
function (response) {
var errorMessage = $filter('translate')('Upload failed.');
if (response.status > 0) {
errorMessage += ' Status: ' + response.status;
if (response.statusText) {
errorMessage += ' ' + response.statusText;
}
if (response.data) {
errorMessage += '- ' + response.data;
}
}
$scope.upload.file = null;
notice.push(notice.ERROR, errorMessage);
},
function (evt) {
$scope.upload.progress = parseInt(100.0 * evt.loaded / evt.total);
});
});
};
}]
};
}]);
|
'use strict';
const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
let mainWindow = null;
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
app.on('ready', () => {
mainWindow = new BrowserWindow({
width: 480,
height: 320,
frame: false
});
mainWindow.loadURL(`file://${__dirname}/index.html`);
mainWindow.on('closed', () => { mainWindow = null; });
}); |
var CoreObject = require('core-object');
var gitRepoInfo = require('git-repo-info');
var RSVP = require('rsvp');
module.exports = CoreObject.extend({
init: function(options) {
this._super();
this._plugin = options.plugin;
},
generate: function() {
var commitHashLength = this._plugin.readConfig('commitHashLength');
var info = gitRepoInfo();
if (info === null || info.root === null) {
return RSVP.reject('Could not find git repository');
}
var sha = info.sha.slice(0, commitHashLength);
if (!sha) {
return RSVP.reject('Could not build revision with commit hash `' + sha + '`');
}
return RSVP.resolve({
revisionKey: sha,
timestamp: new Date().toISOString()
});
}
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.1.2.1_A3.2_T3;
* @section: 15.1.2.1, 12.3;
* @assertion: If Result(3).type is normal and its completion value is empty,
* then return the value undefined;
* @description: Empty statement;
*/
//CHECK#1
if (eval(";") !== undefined) {
$ERROR('#1: eval(";") === undefined. Actual: ' + (eval(";")));
}
|
const { join } = require('path')
const { settings } = require('../configuration.js')
module.exports = {
test: /\.(js|jsx)?(\.erb)?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
cacheDirectory: join(settings.cache_path, 'babel-loader')
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:39d6c67e59bc5b9ff49d231f4ea4cfeebff29c554af113291a8b19fd62dc0ceb
size 12752
|
// @flow
import React from 'react';
import { CookiesProvider } from 'react-cookie';
import { StaticRouter } from 'react-router-dom';
import { renderToString } from 'react-dom/server';
import type { $Request, $Response, NextFunction } from 'express';
import { HelmetProvider } from 'react-helmet-async';
import { ChunkExtractor } from '@loadable/server';
import { collectInitial, collectContext } from 'node-style-loader/collect';
import accept from '@hapi/accept';
import { getDefault } from '../../../shared/util/ModuleUtil';
import getWebpackSettings from '../../../shared/webpack-settings';
import { rootRoute } from '../../common/kernel';
import ReworkRootComponent from '../../app/ReworkRootComponent';
import { LanguageContext } from '../../common/accept-language-context';
import { SsrContext } from '../../common/ssr-context';
import { loadResource } from '../../common/use-async-resource/load-resource';
import ServerHooks from '../server-hooks';
import renderPage from './render-page';
export default async function serveReactRoute(req: $Request, res: $Response, next: NextFunction): Promise<void> {
try {
const serverHooks = ServerHooks.map(hookModule => {
const HookClass = getDefault(hookModule);
return new HookClass();
});
try {
const acceptedLanguages = Object.freeze(accept.languages(req.header('Accept-Language')));
const loadableResources = new Map();
const persistentValues = new Map();
let component = (
<SsrContext.Provider value={Object.freeze({ req, res, loadableResources, persistentValues })}>
<LanguageContext.Provider value={acceptedLanguages}>
{/* custom prop injected by universal-cookies */}
{/* $FlowFixMe */}
<CookiesProvider cookies={req.universalCookies}>
<ReworkRootComponent>
{rootRoute}
</ReworkRootComponent>
</CookiesProvider>
</LanguageContext.Provider>
</SsrContext.Provider>
);
// allow plugins to add components
for (const serverHook of serverHooks) {
if (serverHook.wrapRootComponent) {
component = serverHook.wrapRootComponent(component);
}
}
const [
appHtml, routingContext,
chunkExtractor, inlineStyles,
helmet,
] = await renderWithResources(loadableResources, () => {
/* eslint-disable no-shadow */
// will be populated by staticRouter
const routingContext = {};
const helmetContext = {};
// will be populated by collectChunks
const chunkExtractor = new ChunkExtractor({ statsFile: getLoadableStatFile() });
const finalJsx = chunkExtractor.collectChunks(
<HelmetProvider context={helmetContext}>
<StaticRouter location={req.url} context={routingContext}>
{component}
</StaticRouter>
</HelmetProvider>,
);
// a bit of a hack: if this is a redirect, don't bother loading resources. (need better way of passing this info)
if (routingContext.url && routingContext.url !== req.originalUrl) {
loadableResources.clear();
}
// There is no CSS entry point in dev mode
// so we collect inline CSS and return it
if (process.env.NODE_ENV === 'development') {
const initialInlineCss = collectInitial();
const [contextInlineCss, appHtml] = collectContext(() => renderToString(finalJsx));
return [appHtml, routingContext, chunkExtractor, initialInlineCss + contextInlineCss, helmetContext.helmet];
}
const appHtml = renderToString(finalJsx);
// there is no inline CSS in production
// important: Helmet must always be called after a render or it will cause a memory leak
return [appHtml, routingContext, chunkExtractor, '', helmetContext.helmet];
/* eslint-enable no-shadow */
});
// Somewhere a `<Redirect>` was rendered
if (routingContext.url && routingContext.url !== req.originalUrl) {
return void res.redirect(routingContext.status || 301, routingContext.url);
}
if (routingContext.status) {
res.status(routingContext.status);
}
let htmlParts = {
// initial style & pre-loaded JS
header: `
${chunkExtractor.getLinkTags()}
${chunkExtractor.getStyleTags()}
${inlineStyles}
`,
// initial react app
body: appHtml,
// inject main webpack bundle
footer: chunkExtractor.getScriptTags(),
helmet,
};
// allow plugins to edit HTML (add script, etc) before actual render.
for (const serverHook of serverHooks) {
if (serverHook.preRender) {
htmlParts = serverHook.preRender(htmlParts) || htmlParts;
}
}
// TODO:
// - get http-equiv meta from Helmet, and send them as actual headers.
// - add Link preload headers so our reverse proxy can use them for server push.
// TODO: collect chunks
// TODO: test if mapping front-back is correct
// TODO: check if @loadable/babel-plugin needs to be on both ends
res.send(renderPage(htmlParts));
} finally {
// allow plugins to cleanup
for (const serverHook of serverHooks) {
if (serverHook.postRequest) {
serverHook.postRequest();
}
}
}
} catch (e) {
next(e);
}
}
async function renderWithResources(loadableResources, renderApp) {
let hasNewLoadableResources;
let lastOutput;
do {
hasNewLoadableResources = false;
lastOutput = renderApp();
// load all new resources that were collected during this render
// eslint-disable-next-line no-await-in-loop
await Promise.all(
Array.from(loadableResources.values())
// eslint-disable-next-line no-loop-func
.map(async resource => {
if (resource.status) {
return;
}
// cause re-render
hasNewLoadableResources = true;
resource.status = await loadResource(resource.load);
}),
);
} while (hasNewLoadableResources);
return lastOutput;
}
const clientBuildDirectory = getWebpackSettings(/* is server */ false).output.path;
function getLoadableStatFile() {
return `${clientBuildDirectory}/loadable-stats.json`;
}
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import invariant from 'shared/invariant';
// Exports ReactDOM.createRoot
export const enableUserTimingAPI = __DEV__;
// Experimental error-boundary API that can recover from errors within a single
// render phase
export const enableGetDerivedStateFromCatch = false;
// Suspense
export const enableSuspense = false;
// Helps identify side effects in begin-phase lifecycle hooks and setState reducers:
export const debugRenderPhaseSideEffects = false;
// In some cases, StrictMode should also double-render lifecycles.
// This can be confusing for tests though,
// And it can be bad for performance in production.
// This feature flag can be used to control the behavior:
export const debugRenderPhaseSideEffectsForStrictMode = __DEV__;
// To preserve the "Pause on caught exceptions" behavior of the debugger, we
// replay the begin phase of a failed component inside invokeGuardedCallback.
export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__;
// Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
export const warnAboutDeprecatedLifecycles = false;
// Warn about legacy context API
export const warnAboutLegacyContextAPI = false;
// Gather advanced timing metrics for Profiler subtrees.
export const enableProfilerTimer = __PROFILE__;
// Only used in www builds.
export function addUserTimingListener() {
invariant(false, 'Not implemented.');
}
|
export class Vscroll {
constructor(vscroll) {
this.vscroll = vscroll;
}
factory(settings) {
return this.vscroll(settings);
}
} |
'use strict';
// Allow the use of non-minsafe AngularJS files. Automatically makes it
// minsafe compatible so Uglify does not destroy the ng references
module.exports = {
compiled: {
files: [{
expand: true,
cwd: '<%= paths.compiled.tld %>/concat/scripts',
src: [
// List of files that need to be made min-safe
'app.concat.js',
'app.vendor.js'
],
dest: '<%= paths.compiled.tld %>/concat/scripts'
}]
}
}; |
let test = require('tape');
function _test(name) {
test(`test ${name}`, t => {
t.plan(1);
t.pass(name);
t.end();
});
}
_test(`huey`);
_test(`dewey`);
setTimeout(function () {
_test(`louie`);
}, 100);
|
define({
"size.natural": "åå§å¤§å°",
"button.addimg.tooltip": "æå
¥å¾ç",
"floatingmenu.tab.img": "å¾ç",
"floatingmenu.tab.formatting": "æ ¼å¼",
"floatingmenu.tab.resize": "è°æ´å¤§å°",
"floatingmenu.tab.crop": "è£å",
"button.uploadimg.tooltip": "ä¸ä¼ å¾ç",
"button.uploadimg.label": "ä¸ä¼ ",
"button.img.align.left.tooltip": "左对é½",
"button.img.align.right.tooltip": "å³å¯¹é½",
"button.img.align.none.tooltip": "ä¸å¯¹é½",
"field.img.title.label": "æ é¢",
"field.img.title.tooltip": "æ é¢",
"field.img.label": "URL",
"field.img.tooltip": "æ¥æº",
"border ": "å¾çå¢å è¾¹æ¡",
"padding.increase ": "å¢å å¡«å
",
"padding.decrease ": "åå°å¡«å
",
"size.increase ": "å¢å¤§",
"size.decrease ": "åå°",
"Resize": "缩æ¾",
"Crop": "è£å",
"Reset": "éç½®",
"Accept": "æ¥å",
"Cancel": "åæ¶",
"height": "é«",
"width": "宽",
"button.toggle.tooltip": "åæ¢ä¿æå®½é«æ¯",
"field.img.src.label": "æ¥æº",
"field.img.src.tooltip": "æ¥æº"
});
|
import React, { PropTypes } from 'react';
import { Map } from 'immutable';
import cx from 'classnames';
import { getImageURLFromThread } from '../../utils';
const ImagePreview = ({ isExpanded, thread}) => {
return (
<div className={cx({
'flex justify-center items-center p2 bg-black rounded': isExpanded,
})}>
{
isExpanded
? <img src={getImageURLFromThread(thread)} />
: null
}
</div>
);
};
ImagePreview.propTypes = {
isExpanded: PropTypes.bool.isRequired,
thread: PropTypes.instanceOf(Map).isRequired,
};
export default ImagePreview;
|
/*!
* reveal.js
* http://lab.hakim.se/reveal-js
* MIT licensed
*
* Copyright (C) 2015 Hakim El Hattab, http://hakim.se
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(function () {
root.Reveal = factory();
return root.Reveal;
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS.
module.exports = factory();
} else {
// Browser globals.
root.Reveal = factory();
}
}(this, function () {
'use strict';
var Reveal;
var SLIDES_SELECTOR = '.slides section',
HORIZONTAL_SLIDES_SELECTOR = '.slides>section',
VERTICAL_SLIDES_SELECTOR = '.slides>section.present>section',
HOME_SLIDE_SELECTOR = '.slides>section:first-of-type',
// Configuration defaults, can be overridden at initialization time
config = {
// The "normal" size of the presentation, aspect ratio will be preserved
// when the presentation is scaled to fit different resolutions
width: 960,
height: 700,
// Factor of the display size that should remain empty around the content
margin: 0.1,
// Bounds for smallest/largest possible scale to apply to content
minScale: 0.2,
maxScale: 1.5,
// Display controls in the bottom right corner
controls: true,
// Display a presentation progress bar
progress: true,
// Display the page number of the current slide
slideNumber: false,
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Optional function that blocks keyboard events when retuning false
keyboardCondition: null,
// Enable the slide overview mode
overview: true,
// Vertical centering of slides
center: true,
// Enables touch navigation on devices with touch input
touch: true,
// Loop the presentation
loop: false,
// Change the presentation direction to be RTL
rtl: false,
// Turns fragments on and off globally
fragments: true,
// Flags if the presentation is running in an embedded mode,
// i.e. contained within a limited portion of the screen
embedded: false,
// Flags if we should show a help overlay when the questionmark
// key is pressed
help: true,
// Flags if it should be possible to pause the presentation (blackout)
pause: true,
// Flags if speaker notes should be visible to all viewers
showNotes: false,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0, this value can be overwritten
// by using a data-autoslide attribute on your slides
autoSlide: 0,
// Stop auto-sliding after user input
autoSlideStoppable: true,
// Enable slide navigation via mouse wheel
mouseWheel: false,
// Apply a 3D roll to links on hover
rollingLinks: false,
// Hides the address bar on mobile devices
hideAddressBar: true,
// Opens links in an iframe preview overlay
previewLinks: false,
// Exposes the reveal.js API through window.postMessage
postMessage: true,
// Dispatches all reveal.js events to the parent window through postMessage
postMessageEvents: false,
// Focuses body when page changes visiblity to ensure keyboard shortcuts work
focusBodyOnPageVisibilityChange: true,
// Transition style
transition: 'slide', // none/fade/slide/convex/concave/zoom
// Transition speed
transitionSpeed: 'default', // default/fast/slow
// Transition style for full page slide backgrounds
backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom
// Parallax background image
parallaxBackgroundImage: '', // CSS syntax, e.g. "a.jpg"
// Parallax background size
parallaxBackgroundSize: '', // CSS syntax, e.g. "3000px 2000px"
// Amount of pixels to move the parallax background per slide step
parallaxBackgroundHorizontal: null,
parallaxBackgroundVertical: null,
// Number of slides away from the current that are visible
viewDistance: 3,
// Script dependencies to load
dependencies: []
},
// Flags if reveal.js is loaded (has dispatched the 'ready' event)
loaded = false,
// Flags if the overview mode is currently active
overview = false,
// The horizontal and vertical index of the currently active slide
indexh,
indexv,
// The previous and current slide HTML elements
previousSlide,
currentSlide,
previousBackground,
// Slides may hold a data-state attribute which we pick up and apply
// as a class to the body. This list contains the combined state of
// all current slides.
state = [],
// The current scale of the presentation (see width/height config)
scale = 1,
// CSS transform that is currently applied to the slides container,
// split into two groups
slidesTransform = {
layout: '',
overview: ''
},
// Cached references to DOM elements
dom = {},
// Features supported by the browser, see #checkCapabilities()
features = {},
// Client is a mobile device, see #checkCapabilities()
isMobileDevice,
// Throttles mouse wheel navigation
lastMouseWheelStep = 0,
// Delays updates to the URL due to a Chrome thumbnailer bug
writeURLTimeout = 0,
// Flags if the interaction event listeners are bound
eventsAreBound = false,
// The current auto-slide duration
autoSlide = 0,
// Auto slide properties
autoSlidePlayer,
autoSlideTimeout = 0,
autoSlideStartTime = -1,
autoSlidePaused = false,
// Holds information about the currently ongoing touch input
touch = {
startX: 0,
startY: 0,
startSpan: 0,
startCount: 0,
captured: false,
threshold: 40
},
// Holds information about the keyboard shortcuts
keyboardShortcuts = {
'N , SPACE': 'Next slide',
'P': 'Previous slide',
'← , H': 'Navigate left',
'→ , L': 'Navigate right',
'↑ , K': 'Navigate up',
'↓ , J': 'Navigate down',
'Home': 'First slide',
'End': 'Last slide',
'B , .': 'Pause',
'F': 'Fullscreen',
'ESC, O': 'Slide overview'
};
/**
* Starts up the presentation if the client is capable.
*/
function initialize(options) {
checkCapabilities();
if (!features.transforms2d && !features.transforms3d) {
document.body.setAttribute('class', 'no-transforms');
// Since JS won't be running any further, we load all lazy
// loading elements upfront
var images = toArray(document.getElementsByTagName('img')),
iframes = toArray(document.getElementsByTagName('iframe'));
var lazyLoadable = images.concat(iframes);
for (var i = 0, len = lazyLoadable.length; i < len; i++) {
var element = lazyLoadable[i];
if (element.getAttribute('data-src')) {
element.setAttribute('src', element.getAttribute('data-src'));
element.removeAttribute('data-src');
}
}
// If the browser doesn't support core features we won't be
// using JavaScript to control the presentation
return;
}
// Cache references to key DOM elements
dom.wrapper = document.querySelector('.reveal');
dom.slides = document.querySelector('.reveal .slides');
// Force a layout when the whole page, incl fonts, has loaded
window.addEventListener('load', layout, false);
var query = Reveal.getQueryHash();
// Do not accept new dependencies via query config to avoid
// the potential of malicious script injection
if (typeof query['dependencies'] !== 'undefined') delete query['dependencies'];
// Copy options over to our config object
extend(config, options);
extend(config, query);
// Hide the address bar in mobile browsers
hideAddressBar();
// Loads the dependencies and continues to #start() once done
load();
}
/**
* Inspect the client to see what it's capable of, this
* should only happens once per runtime.
*/
function checkCapabilities() {
features.transforms3d = 'WebkitPerspective' in document.body.style ||
'MozPerspective' in document.body.style ||
'msPerspective' in document.body.style ||
'OPerspective' in document.body.style ||
'perspective' in document.body.style;
features.transforms2d = 'WebkitTransform' in document.body.style ||
'MozTransform' in document.body.style ||
'msTransform' in document.body.style ||
'OTransform' in document.body.style ||
'transform' in document.body.style;
features.requestAnimationFrameMethod = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame;
features.requestAnimationFrame = typeof features.requestAnimationFrameMethod === 'function';
features.canvas = !!document.createElement('canvas').getContext;
features.touch = !!('ontouchstart' in window);
// Transitions in the overview are disabled in desktop and
// mobile Safari due to lag
features.overviewTransitions = !/Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
isMobileDevice = /(iphone|ipod|ipad|android)/gi.test(navigator.userAgent);
}
/**
* Loads the dependencies of reveal.js. Dependencies are
* defined via the configuration option 'dependencies'
* and will be loaded prior to starting/binding reveal.js.
* Some dependencies may have an 'async' flag, if so they
* will load after reveal.js has been started up.
*/
function load() {
var scripts = [],
scriptsAsync = [],
scriptsToPreload = 0;
// Called once synchronous scripts finish loading
function proceed() {
if (scriptsAsync.length) {
// Load asynchronous scripts
head.js.apply(null, scriptsAsync);
}
start();
}
function loadScript(s) {
head.ready(s.src.match(/([\w\d_\-]*)\.?js$|[^\\\/]*$/i)[0], function () {
// Extension may contain callback functions
if (typeof s.callback === 'function') {
s.callback.apply(this);
}
if (--scriptsToPreload === 0) {
proceed();
}
});
}
for (var i = 0, len = config.dependencies.length; i < len; i++) {
var s = config.dependencies[i];
// Load if there's no condition or the condition is truthy
if (!s.condition || s.condition()) {
if (s.async) {
scriptsAsync.push(s.src);
} else {
scripts.push(s.src);
}
loadScript(s);
}
}
if (scripts.length) {
scriptsToPreload = scripts.length;
// Load synchronous scripts
head.js.apply(null, scripts);
} else {
proceed();
}
}
/**
* Starts up reveal.js by binding input events and navigating
* to the current URL deeplink if there is one.
*/
function start() {
// Make sure we've got all the DOM elements we need
setupDOM();
// Listen to messages posted to this window
setupPostMessage();
// Prevent iframes from scrolling the slides out of view
setupIframeScrollPrevention();
// Resets all vertical slides so that only the first is visible
resetVerticalSlides();
// Updates the presentation to match the current configuration values
configure();
// Read the initial hash
readURL();
// Update all backgrounds
updateBackground(true);
// Notify listeners that the presentation is ready but use a 1ms
// timeout to ensure it's not fired synchronously after #initialize()
setTimeout(function () {
// Enable transitions now that we're loaded
dom.slides.classList.remove('no-transition');
loaded = true;
dispatchEvent('ready', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
});
}, 1);
// Special setup and config is required when printing to PDF
if (isPrintingPDF()) {
removeEventListeners();
// The document needs to have loaded for the PDF layout
// measurements to be accurate
if (document.readyState === 'complete') {
setupPDF();
} else {
window.addEventListener('load', setupPDF);
}
}
}
/**
* Finds and stores references to DOM elements which are
* required by the presentation. If a required element is
* not found, it is created.
*/
function setupDOM() {
// Prevent transitions while we're loading
dom.slides.classList.add('no-transition');
// Background element
dom.background = createSingletonNode(dom.wrapper, 'div', 'backgrounds', null);
// Progress bar
dom.progress = createSingletonNode(dom.wrapper, 'div', 'progress', '<span></span>');
dom.progressbar = dom.progress.querySelector('span');
// Arrow controls
createSingletonNode(dom.wrapper, 'aside', 'controls',
'<button class="navigate-left" aria-label="previous slide"></button>' +
'<button class="navigate-right" aria-label="next slide"></button>' +
'<button class="navigate-up" aria-label="above slide"></button>' +
'<button class="navigate-down" aria-label="below slide"></button>');
// Slide number
dom.slideNumber = createSingletonNode(dom.wrapper, 'div', 'slide-number', '');
// Element containing notes that are visible to the audience
dom.speakerNotes = createSingletonNode(dom.wrapper, 'div', 'speaker-notes', null);
dom.speakerNotes.setAttribute('data-prevent-swipe', '');
// Overlay graphic which is displayed during the paused mode
createSingletonNode(dom.wrapper, 'div', 'pause-overlay', null);
// Cache references to elements
dom.controls = document.querySelector('.reveal .controls');
dom.theme = document.querySelector('#theme');
dom.wrapper.setAttribute('role', 'application');
// There can be multiple instances of controls throughout the page
dom.controlsLeft = toArray(document.querySelectorAll('.navigate-left'));
dom.controlsRight = toArray(document.querySelectorAll('.navigate-right'));
dom.controlsUp = toArray(document.querySelectorAll('.navigate-up'));
dom.controlsDown = toArray(document.querySelectorAll('.navigate-down'));
dom.controlsPrev = toArray(document.querySelectorAll('.navigate-prev'));
dom.controlsNext = toArray(document.querySelectorAll('.navigate-next'));
dom.statusDiv = createStatusDiv();
}
/**
* Creates a hidden div with role aria-live to announce the
* current slide content. Hide the div off-screen to make it
* available only to Assistive Technologies.
*/
function createStatusDiv() {
var statusDiv = document.getElementById('aria-status-div');
if (!statusDiv) {
statusDiv = document.createElement('div');
statusDiv.style.position = 'absolute';
statusDiv.style.height = '1px';
statusDiv.style.width = '1px';
statusDiv.style.overflow = 'hidden';
statusDiv.style.clip = 'rect( 1px, 1px, 1px, 1px )';
statusDiv.setAttribute('id', 'aria-status-div');
statusDiv.setAttribute('aria-live', 'polite');
statusDiv.setAttribute('aria-atomic', 'true');
dom.wrapper.appendChild(statusDiv);
}
return statusDiv;
}
/**
* Configures the presentation for printing to a static
* PDF.
*/
function setupPDF() {
var slideSize = getComputedSlideSize(window.innerWidth, window.innerHeight);
// Dimensions of the PDF pages
var pageWidth = Math.floor(slideSize.width * (1 + config.margin)),
pageHeight = Math.floor(slideSize.height * (1 + config.margin));
// Dimensions of slides within the pages
var slideWidth = slideSize.width,
slideHeight = slideSize.height;
// Let the browser know what page size we want to print
injectStyleSheet('@page{size:' + pageWidth + 'px ' + pageHeight + 'px; margin: 0;}');
// Limit the size of certain elements to the dimensions of the slide
injectStyleSheet('.reveal section>img, .reveal section>video, .reveal section>iframe{max-width: ' + slideWidth + 'px; max-height:' + slideHeight + 'px}');
document.body.classList.add('print-pdf');
document.body.style.width = pageWidth + 'px';
document.body.style.height = pageHeight + 'px';
// Add each slide's index as attributes on itself, we need these
// indices to generate slide numbers below
toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)).forEach(function (hslide, h) {
hslide.setAttribute('data-index-h', h);
if (hslide.classList.contains('stack')) {
toArray(hslide.querySelectorAll('section')).forEach(function (vslide, v) {
vslide.setAttribute('data-index-h', h);
vslide.setAttribute('data-index-v', v);
});
}
});
// Slide and slide background layout
toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR)).forEach(function (slide) {
// Vertical stacks are not centred since their section
// children will be
if (slide.classList.contains('stack') === false) {
// Center the slide inside of the page, giving the slide some margin
var left = (pageWidth - slideWidth) / 2,
top = (pageHeight - slideHeight) / 2;
var contentHeight = getAbsoluteHeight(slide);
var numberOfPages = Math.max(Math.ceil(contentHeight / pageHeight), 1);
// Center slides vertically
if (numberOfPages === 1 && config.center || slide.classList.contains('center')) {
top = Math.max((pageHeight - contentHeight) / 2, 0);
}
// Position the slide inside of the page
slide.style.left = left + 'px';
slide.style.top = top + 'px';
slide.style.width = slideWidth + 'px';
// TODO Backgrounds need to be multiplied when the slide
// stretches over multiple pages
var background = slide.querySelector('.slide-background');
if (background) {
background.style.width = pageWidth + 'px';
background.style.height = (pageHeight * numberOfPages) + 'px';
background.style.top = -top + 'px';
background.style.left = -left + 'px';
}
// Inject notes if `showNotes` is enabled
if (config.showNotes) {
var notes = getSlideNotes(slide);
if (notes) {
var notesSpacing = 8;
var notesElement = document.createElement('div');
notesElement.classList.add('speaker-notes');
notesElement.classList.add('speaker-notes-pdf');
notesElement.innerHTML = notes;
notesElement.style.left = (notesSpacing - left) + 'px';
notesElement.style.bottom = (notesSpacing - top) + 'px';
notesElement.style.width = (pageWidth - notesSpacing * 2) + 'px';
slide.appendChild(notesElement);
}
}
// Inject slide numbers if `slideNumbers` are enabled
if (config.slideNumber) {
var slideNumberH = parseInt(slide.getAttribute('data-index-h'), 10) + 1,
slideNumberV = parseInt(slide.getAttribute('data-index-v'), 10) + 1;
var numberElement = document.createElement('div');
numberElement.classList.add('slide-number');
numberElement.classList.add('slide-number-pdf');
numberElement.innerHTML = formatSlideNumber(slideNumberH, '.', slideNumberV);
background.appendChild(numberElement);
}
}
});
// Show all fragments
toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR + ' .fragment')).forEach(function (fragment) {
fragment.classList.add('visible');
});
}
/**
* This is an unfortunate necessity. Iframes can trigger the
* parent window to scroll, for example by focusing an input.
* This scrolling can not be prevented by hiding overflow in
* CSS so we have to resort to repeatedly checking if the
* browser has decided to offset our slides :(
*/
function setupIframeScrollPrevention() {
if (dom.slides.querySelector('iframe')) {
setInterval(function () {
if (dom.wrapper.scrollTop !== 0 || dom.wrapper.scrollLeft !== 0) {
dom.wrapper.scrollTop = 0;
dom.wrapper.scrollLeft = 0;
}
}, 500);
}
}
/**
* Creates an HTML element and returns a reference to it.
* If the element already exists the existing instance will
* be returned.
*/
function createSingletonNode(container, tagname, classname, innerHTML) {
// Find all nodes matching the description
var nodes = container.querySelectorAll('.' + classname);
// Check all matches to find one which is a direct child of
// the specified container
for (var i = 0; i < nodes.length; i++) {
var testNode = nodes[i];
if (testNode.parentNode === container) {
return testNode;
}
}
// If no node was found, create it now
var node = document.createElement(tagname);
node.classList.add(classname);
if (typeof innerHTML === 'string') {
node.innerHTML = innerHTML;
}
container.appendChild(node);
return node;
}
/**
* Creates the slide background elements and appends them
* to the background container. One element is created per
* slide no matter if the given slide has visible background.
*/
function createBackgrounds() {
var printMode = isPrintingPDF();
// Clear prior backgrounds
dom.background.innerHTML = '';
dom.background.classList.add('no-transition');
// Iterate over all horizontal slides
toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)).forEach(function (slideh) {
var backgroundStack;
if (printMode) {
backgroundStack = createBackground(slideh, slideh);
} else {
backgroundStack = createBackground(slideh, dom.background);
}
// Iterate over all vertical slides
toArray(slideh.querySelectorAll('section')).forEach(function (slidev) {
if (printMode) {
createBackground(slidev, slidev);
} else {
createBackground(slidev, backgroundStack);
}
backgroundStack.classList.add('stack');
});
});
// Add parallax background if specified
if (config.parallaxBackgroundImage) {
dom.background.style.backgroundImage = 'url("' + config.parallaxBackgroundImage + '")';
dom.background.style.backgroundSize = config.parallaxBackgroundSize;
// Make sure the below properties are set on the element - these properties are
// needed for proper transitions to be set on the element via CSS. To remove
// annoying background slide-in effect when the presentation starts, apply
// these properties after short time delay
setTimeout(function () {
dom.wrapper.classList.add('has-parallax-background');
}, 1);
} else {
dom.background.style.backgroundImage = '';
dom.wrapper.classList.remove('has-parallax-background');
}
}
/**
* Creates a background for the given slide.
*
* @param {HTMLElement} slide
* @param {HTMLElement} container The element that the background
* should be appended to
*/
function createBackground(slide, container) {
var data = {
background: slide.getAttribute('data-background'),
backgroundSize: slide.getAttribute('data-background-size'),
backgroundVideo: slide.getAttribute('data-background-video'),
backgroundIframe: slide.getAttribute('data-background-iframe'),
backgroundRepeat: slide.getAttribute('data-background-repeat'),
backgroundPosition: slide.getAttribute('data-background-position'),
backgroundTransition: slide.getAttribute('data-background-transition')
};
var element = document.createElement('div');
// Carry over custom classes from the slide to the background
element.className = 'slide-background ' + slide.className.replace(/present|past|future/, '');
// Create a hash for this combination of background settings.
// This is used to determine when two slide backgrounds are
// the same.
if (data.background || data.backgroundColor || data.backgroundVideo || data.backgroundIframe) {
element.setAttribute('data-background-hash', data.background +
data.backgroundSize +
data.backgroundVideo +
data.backgroundIframe +
data.backgroundColor +
data.backgroundRepeat +
data.backgroundPosition +
data.backgroundTransition);
}
// Additional and optional background properties
if (data.backgroundSize) element.style.backgroundSize = data.backgroundSize;
if (data.backgroundColor) element.style.backgroundColor = data.backgroundColor;
if (data.backgroundRepeat) element.style.backgroundRepeat = data.backgroundRepeat;
if (data.backgroundPosition) element.style.backgroundPosition = data.backgroundPosition;
if (data.backgroundTransition) element.setAttribute('data-background-transition', data.backgroundTransition);
container.appendChild(element);
// If backgrounds are being recreated, clear old classes
slide.classList.remove('has-dark-background');
slide.classList.remove('has-light-background');
// If this slide has a background color, add a class that
// signals if it is light or dark. If the slide has no background
// color, no class will be set
var computedBackgroundColor = window.getComputedStyle(element).backgroundColor;
if (computedBackgroundColor) {
var rgb = colorToRgb(computedBackgroundColor);
// Ignore fully transparent backgrounds. Some browsers return
// rgba(0,0,0,0) when reading the computed background color of
// an element with no background
if (rgb && rgb.a !== 0) {
if (colorBrightness(computedBackgroundColor) < 128) {
slide.classList.add('has-dark-background');
} else {
slide.classList.add('has-light-background');
}
}
}
return element;
}
/**
* Registers a listener to postMessage events, this makes it
* possible to call all reveal.js API methods from another
* window. For example:
*
* revealWindow.postMessage( JSON.stringify({
* method: 'slide',
* args: [ 2 ]
* }), '*' );
*/
function setupPostMessage() {
if (config.postMessage) {
window.addEventListener('message', function (event) {
var data = event.data;
// Make sure we're dealing with JSON
if (typeof data === 'string' && data.charAt(0) === '{' && data.charAt(data.length - 1) === '}') {
data = JSON.parse(data);
// Check if the requested method can be found
if (data.method && typeof Reveal[data.method] === 'function') {
Reveal[data.method].apply(Reveal, data.args);
}
}
}, false);
}
}
/**
* Applies the configuration settings from the config
* object. May be called multiple times.
*/
function configure(options) {
var numberOfSlides = dom.wrapper.querySelectorAll(SLIDES_SELECTOR).length;
dom.wrapper.classList.remove(config.transition);
// New config options may be passed when this method
// is invoked through the API after initialization
if (typeof options === 'object') extend(config, options);
// Force linear transition based on browser capabilities
if (features.transforms3d === false) config.transition = 'linear';
dom.wrapper.classList.add(config.transition);
dom.wrapper.setAttribute('data-transition-speed', config.transitionSpeed);
dom.wrapper.setAttribute('data-background-transition', config.backgroundTransition);
dom.controls.style.display = config.controls ? 'block' : 'none';
dom.progress.style.display = config.progress ? 'block' : 'none';
dom.slideNumber.style.display = config.slideNumber && !isPrintingPDF() ? 'block' : 'none';
if (config.rtl) {
dom.wrapper.classList.add('rtl');
} else {
dom.wrapper.classList.remove('rtl');
}
if (config.center) {
dom.wrapper.classList.add('center');
} else {
dom.wrapper.classList.remove('center');
}
// Exit the paused mode if it was configured off
if (config.pause === false) {
resume();
}
if (config.showNotes) {
dom.speakerNotes.classList.add('visible');
} else {
dom.speakerNotes.classList.remove('visible');
}
if (config.mouseWheel) {
document.addEventListener('DOMMouseScroll', onDocumentMouseScroll, false); // FF
document.addEventListener('mousewheel', onDocumentMouseScroll, false);
} else {
document.removeEventListener('DOMMouseScroll', onDocumentMouseScroll, false); // FF
document.removeEventListener('mousewheel', onDocumentMouseScroll, false);
}
// Rolling 3D links
if (config.rollingLinks) {
enableRollingLinks();
} else {
disableRollingLinks();
}
// Iframe link previews
if (config.previewLinks) {
enablePreviewLinks();
} else {
disablePreviewLinks();
enablePreviewLinks('[data-preview-link]');
}
// Remove existing auto-slide controls
if (autoSlidePlayer) {
autoSlidePlayer.destroy();
autoSlidePlayer = null;
}
// Generate auto-slide controls if needed
if (numberOfSlides > 1 && config.autoSlide && config.autoSlideStoppable && features.canvas && features.requestAnimationFrame) {
autoSlidePlayer = new Playback(dom.wrapper, function () {
return Math.min(Math.max((Date.now() - autoSlideStartTime) / autoSlide, 0), 1);
});
autoSlidePlayer.on('click', onAutoSlidePlayerClick);
autoSlidePaused = false;
}
// When fragments are turned off they should be visible
if (config.fragments === false) {
toArray(dom.slides.querySelectorAll('.fragment')).forEach(function (element) {
element.classList.add('visible');
element.classList.remove('current-fragment');
});
}
sync();
}
/**
* Binds all event listeners.
*/
function addEventListeners() {
eventsAreBound = true;
window.addEventListener('hashchange', onWindowHashChange, false);
window.addEventListener('resize', onWindowResize, false);
if (config.touch) {
dom.wrapper.addEventListener('touchstart', onTouchStart, false);
dom.wrapper.addEventListener('touchmove', onTouchMove, false);
dom.wrapper.addEventListener('touchend', onTouchEnd, false);
// Support pointer-style touch interaction as well
if (window.navigator.pointerEnabled) {
// IE 11 uses un-prefixed version of pointer events
dom.wrapper.addEventListener('pointerdown', onPointerDown, false);
dom.wrapper.addEventListener('pointermove', onPointerMove, false);
dom.wrapper.addEventListener('pointerup', onPointerUp, false);
} else if (window.navigator.msPointerEnabled) {
// IE 10 uses prefixed version of pointer events
dom.wrapper.addEventListener('MSPointerDown', onPointerDown, false);
dom.wrapper.addEventListener('MSPointerMove', onPointerMove, false);
dom.wrapper.addEventListener('MSPointerUp', onPointerUp, false);
}
}
if (config.keyboard) {
document.addEventListener('keydown', onDocumentKeyDown, false);
document.addEventListener('keypress', onDocumentKeyPress, false);
}
if (config.progress && dom.progress) {
dom.progress.addEventListener('click', onProgressClicked, false);
}
if (config.focusBodyOnPageVisibilityChange) {
var visibilityChange;
if ('hidden' in document) {
visibilityChange = 'visibilitychange';
} else if ('msHidden' in document) {
visibilityChange = 'msvisibilitychange';
} else if ('webkitHidden' in document) {
visibilityChange = 'webkitvisibilitychange';
}
if (visibilityChange) {
document.addEventListener(visibilityChange, onPageVisibilityChange, false);
}
}
// Listen to both touch and click events, in case the device
// supports both
var pointerEvents = ['touchstart', 'click'];
// Only support touch for Android, fixes double navigations in
// stock browser
if (navigator.userAgent.match(/android/gi)) {
pointerEvents = ['touchstart'];
}
pointerEvents.forEach(function (eventName) {
dom.controlsLeft.forEach(function (el) {
el.addEventListener(eventName, onNavigateLeftClicked, false);
});
dom.controlsRight.forEach(function (el) {
el.addEventListener(eventName, onNavigateRightClicked, false);
});
dom.controlsUp.forEach(function (el) {
el.addEventListener(eventName, onNavigateUpClicked, false);
});
dom.controlsDown.forEach(function (el) {
el.addEventListener(eventName, onNavigateDownClicked, false);
});
dom.controlsPrev.forEach(function (el) {
el.addEventListener(eventName, onNavigatePrevClicked, false);
});
dom.controlsNext.forEach(function (el) {
el.addEventListener(eventName, onNavigateNextClicked, false);
});
});
}
/**
* Unbinds all event listeners.
*/
function removeEventListeners() {
eventsAreBound = false;
document.removeEventListener('keydown', onDocumentKeyDown, false);
document.removeEventListener('keypress', onDocumentKeyPress, false);
window.removeEventListener('hashchange', onWindowHashChange, false);
window.removeEventListener('resize', onWindowResize, false);
dom.wrapper.removeEventListener('touchstart', onTouchStart, false);
dom.wrapper.removeEventListener('touchmove', onTouchMove, false);
dom.wrapper.removeEventListener('touchend', onTouchEnd, false);
// IE11
if (window.navigator.pointerEnabled) {
dom.wrapper.removeEventListener('pointerdown', onPointerDown, false);
dom.wrapper.removeEventListener('pointermove', onPointerMove, false);
dom.wrapper.removeEventListener('pointerup', onPointerUp, false);
}
// IE10
else if (window.navigator.msPointerEnabled) {
dom.wrapper.removeEventListener('MSPointerDown', onPointerDown, false);
dom.wrapper.removeEventListener('MSPointerMove', onPointerMove, false);
dom.wrapper.removeEventListener('MSPointerUp', onPointerUp, false);
}
if (config.progress && dom.progress) {
dom.progress.removeEventListener('click', onProgressClicked, false);
}
['touchstart', 'click'].forEach(function (eventName) {
dom.controlsLeft.forEach(function (el) {
el.removeEventListener(eventName, onNavigateLeftClicked, false);
});
dom.controlsRight.forEach(function (el) {
el.removeEventListener(eventName, onNavigateRightClicked, false);
});
dom.controlsUp.forEach(function (el) {
el.removeEventListener(eventName, onNavigateUpClicked, false);
});
dom.controlsDown.forEach(function (el) {
el.removeEventListener(eventName, onNavigateDownClicked, false);
});
dom.controlsPrev.forEach(function (el) {
el.removeEventListener(eventName, onNavigatePrevClicked, false);
});
dom.controlsNext.forEach(function (el) {
el.removeEventListener(eventName, onNavigateNextClicked, false);
});
});
}
/**
* Extend object a with the properties of object b.
* If there's a conflict, object b takes precedence.
*/
function extend(a, b) {
for (var i in b) {
a[i] = b[i];
}
}
/**
* Converts the target object to an array.
*/
function toArray(o) {
return Array.prototype.slice.call(o);
}
/**
* Utility for deserializing a value.
*/
function deserialize(value) {
if (typeof value === 'string') {
if (value === 'null') return null;
else if (value === 'true') return true;
else if (value === 'false') return false;
else if (value.match(/^\d+$/)) return parseFloat(value);
}
return value;
}
/**
* Measures the distance in pixels between point a
* and point b.
*
* @param {Object} a point with x/y properties
* @param {Object} b point with x/y properties
*/
function distanceBetween(a, b) {
var dx = a.x - b.x,
dy = a.y - b.y;
return Math.sqrt(dx * dx + dy * dy);
}
/**
* Applies a CSS transform to the target element.
*/
function transformElement(element, transform) {
element.style.WebkitTransform = transform;
element.style.MozTransform = transform;
element.style.msTransform = transform;
element.style.transform = transform;
}
/**
* Applies CSS transforms to the slides container. The container
* is transformed from two separate sources: layout and the overview
* mode.
*/
function transformSlides(transforms) {
// Pick up new transforms from arguments
if (typeof transforms.layout === 'string') slidesTransform.layout = transforms.layout;
if (typeof transforms.overview === 'string') slidesTransform.overview = transforms.overview;
// Apply the transforms to the slides container
if (slidesTransform.layout) {
transformElement(dom.slides, slidesTransform.layout + ' ' + slidesTransform.overview);
} else {
transformElement(dom.slides, slidesTransform.overview);
}
}
/**
* Injects the given CSS styles into the DOM.
*/
function injectStyleSheet(value) {
var tag = document.createElement('style');
tag.type = 'text/css';
if (tag.styleSheet) {
tag.styleSheet.cssText = value;
} else {
tag.appendChild(document.createTextNode(value));
}
document.getElementsByTagName('head')[0].appendChild(tag);
}
/**
* Converts various color input formats to an {r:0,g:0,b:0} object.
*
* @param {String} color The string representation of a color,
* the following formats are supported:
* - #000
* - #000000
* - rgb(0,0,0)
*/
function colorToRgb(color) {
var hex3 = color.match(/^#([0-9a-f]{3})$/i);
if (hex3 && hex3[1]) {
hex3 = hex3[1];
return {
r: parseInt(hex3.charAt(0), 16) * 0x11,
g: parseInt(hex3.charAt(1), 16) * 0x11,
b: parseInt(hex3.charAt(2), 16) * 0x11
};
}
var hex6 = color.match(/^#([0-9a-f]{6})$/i);
if (hex6 && hex6[1]) {
hex6 = hex6[1];
return {
r: parseInt(hex6.substr(0, 2), 16),
g: parseInt(hex6.substr(2, 2), 16),
b: parseInt(hex6.substr(4, 2), 16)
};
}
var rgb = color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
if (rgb) {
return {
r: parseInt(rgb[1], 10),
g: parseInt(rgb[2], 10),
b: parseInt(rgb[3], 10)
};
}
var rgba = color.match(/^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\,\s*([\d]+|[\d]*.[\d]+)\s*\)$/i);
if (rgba) {
return {
r: parseInt(rgba[1], 10),
g: parseInt(rgba[2], 10),
b: parseInt(rgba[3], 10),
a: parseFloat(rgba[4])
};
}
return null;
}
/**
* Calculates brightness on a scale of 0-255.
*
* @param color See colorStringToRgb for supported formats.
*/
function colorBrightness(color) {
if (typeof color === 'string') color = colorToRgb(color);
if (color) {
return (color.r * 299 + color.g * 587 + color.b * 114) / 1000;
}
return null;
}
/**
* Retrieves the height of the given element by looking
* at the position and height of its immediate children.
*/
function getAbsoluteHeight(element) {
var height = 0;
if (element) {
var absoluteChildren = 0;
toArray(element.childNodes).forEach(function (child) {
if (typeof child.offsetTop === 'number' && child.style) {
// Count # of abs children
if (window.getComputedStyle(child).position === 'absolute') {
absoluteChildren += 1;
}
height = Math.max(height, child.offsetTop + child.offsetHeight);
}
});
// If there are no absolute children, use offsetHeight
if (absoluteChildren === 0) {
height = element.offsetHeight;
}
}
return height;
}
/**
* Returns the remaining height within the parent of the
* target element.
*
* remaining height = [ configured parent height ] - [ current parent height ]
*/
function getRemainingHeight(element, height) {
height = height || 0;
if (element) {
var newHeight, oldHeight = element.style.height;
// Change the .stretch element height to 0 in order find the height of all
// the other elements
element.style.height = '0px';
newHeight = height - element.parentNode.offsetHeight;
// Restore the old height, just in case
element.style.height = oldHeight + 'px';
return newHeight;
}
return height;
}
/**
* Checks if this instance is being used to print a PDF.
*/
function isPrintingPDF() {
return (/print-pdf/gi).test(window.location.search);
}
/**
* Hides the address bar if we're on a mobile device.
*/
function hideAddressBar() {
if (config.hideAddressBar && isMobileDevice) {
// Events that should trigger the address bar to hide
window.addEventListener('load', removeAddressBar, false);
window.addEventListener('orientationchange', removeAddressBar, false);
}
}
/**
* Causes the address bar to hide on mobile devices,
* more vertical space ftw.
*/
function removeAddressBar() {
setTimeout(function () {
window.scrollTo(0, 1);
}, 10);
}
/**
* Dispatches an event of the specified type from the
* reveal DOM element.
*/
function dispatchEvent(type, args) {
var event = document.createEvent('HTMLEvents', 1, 2);
event.initEvent(type, true, true);
extend(event, args);
dom.wrapper.dispatchEvent(event);
// If we're in an iframe, post each reveal.js event to the
// parent window. Used by the notes plugin
if (config.postMessageEvents && window.parent !== window.self) {
window.parent.postMessage(JSON.stringify({
namespace: 'reveal',
eventName: type,
state: getState()
}), '*');
}
}
/**
* Wrap all links in 3D goodness.
*/
function enableRollingLinks() {
if (features.transforms3d && !('msPerspective' in document.body.style)) {
var anchors = dom.wrapper.querySelectorAll(SLIDES_SELECTOR + ' a');
for (var i = 0, len = anchors.length; i < len; i++) {
var anchor = anchors[i];
if (anchor.textContent && !anchor.querySelector('*') && (!anchor.className || !anchor.classList.contains(anchor, 'roll'))) {
var span = document.createElement('span');
span.setAttribute('data-title', anchor.text);
span.innerHTML = anchor.innerHTML;
anchor.classList.add('roll');
anchor.innerHTML = '';
anchor.appendChild(span);
}
}
}
}
/**
* Unwrap all 3D links.
*/
function disableRollingLinks() {
var anchors = dom.wrapper.querySelectorAll(SLIDES_SELECTOR + ' a.roll');
for (var i = 0, len = anchors.length; i < len; i++) {
var anchor = anchors[i];
var span = anchor.querySelector('span');
if (span) {
anchor.classList.remove('roll');
anchor.innerHTML = span.innerHTML;
}
}
}
/**
* Bind preview frame links.
*/
function enablePreviewLinks(selector) {
var anchors = toArray(document.querySelectorAll(selector ? selector : 'a'));
anchors.forEach(function (element) {
if (/^(http|www)/gi.test(element.getAttribute('href'))) {
element.addEventListener('click', onPreviewLinkClicked, false);
}
});
}
/**
* Unbind preview frame links.
*/
function disablePreviewLinks() {
var anchors = toArray(document.querySelectorAll('a'));
anchors.forEach(function (element) {
if (/^(http|www)/gi.test(element.getAttribute('href'))) {
element.removeEventListener('click', onPreviewLinkClicked, false);
}
});
}
/**
* Opens a preview window for the target URL.
*/
function showPreview(url) {
closeOverlay();
dom.overlay = document.createElement('div');
dom.overlay.classList.add('overlay');
dom.overlay.classList.add('overlay-preview');
dom.wrapper.appendChild(dom.overlay);
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'<a class="external" href="' + url + '" target="_blank"><span class="icon"></span></a>',
'</header>',
'<div class="spinner"></div>',
'<div class="viewport">',
'<iframe src="' + url + '"></iframe>',
'</div>'
].join('');
dom.overlay.querySelector('iframe').addEventListener('load', function (event) {
dom.overlay.classList.add('loaded');
}, false);
dom.overlay.querySelector('.close').addEventListener('click', function (event) {
closeOverlay();
event.preventDefault();
}, false);
dom.overlay.querySelector('.external').addEventListener('click', function (event) {
closeOverlay();
}, false);
setTimeout(function () {
dom.overlay.classList.add('visible');
}, 1);
}
/**
* Opens a overlay window with help material.
*/
function showHelp() {
if (config.help) {
closeOverlay();
dom.overlay = document.createElement('div');
dom.overlay.classList.add('overlay');
dom.overlay.classList.add('overlay-help');
dom.wrapper.appendChild(dom.overlay);
var html = '<p class="title">Keyboard Shortcuts</p><br/>';
html += '<table><th>KEY</th><th>ACTION</th>';
for (var key in keyboardShortcuts) {
html += '<tr><td>' + key + '</td><td>' + keyboardShortcuts[key] + '</td></tr>';
}
html += '</table>';
dom.overlay.innerHTML = [
'<header>',
'<a class="close" href="#"><span class="icon"></span></a>',
'</header>',
'<div class="viewport">',
'<div class="viewport-inner">' + html + '</div>',
'</div>'
].join('');
dom.overlay.querySelector('.close').addEventListener('click', function (event) {
closeOverlay();
event.preventDefault();
}, false);
setTimeout(function () {
dom.overlay.classList.add('visible');
}, 1);
}
}
/**
* Closes any currently open overlay.
*/
function closeOverlay() {
if (dom.overlay) {
dom.overlay.parentNode.removeChild(dom.overlay);
dom.overlay = null;
}
}
/**
* Applies JavaScript-controlled layout rules to the
* presentation.
*/
function layout() {
if (dom.wrapper && !isPrintingPDF()) {
var size = getComputedSlideSize();
var slidePadding = 20; // TODO Dig this out of DOM
// Layout the contents of the slides
layoutSlideContents(config.width, config.height, slidePadding);
dom.slides.style.width = size.width + 'px';
dom.slides.style.height = size.height + 'px';
// Determine scale of content to fit within available space
scale = Math.min(size.presentationWidth / size.width, size.presentationHeight / size.height);
// Respect max/min scale settings
scale = Math.max(scale, config.minScale);
scale = Math.min(scale, config.maxScale);
// Don't apply any scaling styles if scale is 1
if (scale === 1) {
dom.slides.style.zoom = '';
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides({
layout: ''
});
} else {
// Use zoom to scale up in desktop Chrome so that content
// remains crisp. We don't use zoom to scale down since that
// can lead to shifts in text layout/line breaks.
if (scale > 1 && !isMobileDevice && /chrome/i.test(navigator.userAgent) && typeof dom.slides.style.zoom !== 'undefined') {
dom.slides.style.zoom = scale;
dom.slides.style.left = '';
dom.slides.style.top = '';
dom.slides.style.bottom = '';
dom.slides.style.right = '';
transformSlides({
layout: ''
});
}
// Apply scale transform as a fallback
else {
dom.slides.style.zoom = '';
dom.slides.style.left = '50%';
dom.slides.style.top = '50%';
dom.slides.style.bottom = 'auto';
dom.slides.style.right = 'auto';
transformSlides({
layout: 'translate(-50%, -50%) scale(' + scale + ')'
});
}
}
// Select all slides, vertical and horizontal
var slides = toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR));
for (var i = 0, len = slides.length; i < len; i++) {
var slide = slides[i];
// Don't bother updating invisible slides
if (slide.style.display === 'none') {
continue;
}
if (config.center || slide.classList.contains('center')) {
// Vertical stacks are not centred since their section
// children will be
if (slide.classList.contains('stack')) {
slide.style.top = 0;
} else {
slide.style.top = Math.max(((size.height - getAbsoluteHeight(slide)) / 2) - slidePadding, 0) + 'px';
}
} else {
slide.style.top = '';
}
}
updateProgress();
updateParallax();
}
}
/**
* Applies layout logic to the contents of all slides in
* the presentation.
*/
function layoutSlideContents(width, height, padding) {
// Handle sizing of elements with the 'stretch' class
toArray(dom.slides.querySelectorAll('section > .stretch')).forEach(function (element) {
// Determine how much vertical space we can use
var remainingHeight = getRemainingHeight(element, height);
// Consider the aspect ratio of media elements
if (/(img|video)/gi.test(element.nodeName)) {
var nw = element.naturalWidth || element.videoWidth,
nh = element.naturalHeight || element.videoHeight;
var es = Math.min(width / nw, remainingHeight / nh);
element.style.width = (nw * es) + 'px';
element.style.height = (nh * es) + 'px';
} else {
element.style.width = width + 'px';
element.style.height = remainingHeight + 'px';
}
});
}
/**
* Calculates the computed pixel size of our slides. These
* values are based on the width and height configuration
* options.
*/
function getComputedSlideSize(presentationWidth, presentationHeight) {
var size = {
// Slide size
width: config.width,
height: config.height,
// Presentation size
presentationWidth: presentationWidth || dom.wrapper.offsetWidth,
presentationHeight: presentationHeight || dom.wrapper.offsetHeight
};
// Reduce available space by margin
size.presentationWidth -= (size.presentationWidth * config.margin);
size.presentationHeight -= (size.presentationHeight * config.margin);
// Slide width may be a percentage of available width
if (typeof size.width === 'string' && /%$/.test(size.width)) {
size.width = parseInt(size.width, 10) / 100 * size.presentationWidth;
}
// Slide height may be a percentage of available height
if (typeof size.height === 'string' && /%$/.test(size.height)) {
size.height = parseInt(size.height, 10) / 100 * size.presentationHeight;
}
return size;
}
/**
* Stores the vertical index of a stack so that the same
* vertical slide can be selected when navigating to and
* from the stack.
*
* @param {HTMLElement} stack The vertical stack element
* @param {int} v Index to memorize
*/
function setPreviousVerticalIndex(stack, v) {
if (typeof stack === 'object' && typeof stack.setAttribute === 'function') {
stack.setAttribute('data-previous-indexv', v || 0);
}
}
/**
* Retrieves the vertical index which was stored using
* #setPreviousVerticalIndex() or 0 if no previous index
* exists.
*
* @param {HTMLElement} stack The vertical stack element
*/
function getPreviousVerticalIndex(stack) {
if (typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains('stack')) {
// Prefer manually defined start-indexv
var attributeName = stack.hasAttribute('data-start-indexv') ? 'data-start-indexv' : 'data-previous-indexv';
return parseInt(stack.getAttribute(attributeName) || 0, 10);
}
return 0;
}
/**
* Displays the overview of slides (quick nav) by scaling
* down and arranging all slide elements.
*/
function activateOverview() {
// Only proceed if enabled in config
if (config.overview && !isOverview()) {
overview = true;
dom.wrapper.classList.add('overview');
dom.wrapper.classList.remove('overview-deactivating');
if (features.overviewTransitions) {
setTimeout(function () {
dom.wrapper.classList.add('overview-animated');
}, 1);
}
// Don't auto-slide while in overview mode
cancelAutoSlide();
// Move the backgrounds element into the slide container to
// that the same scaling is applied
dom.slides.appendChild(dom.background);
// Clicking on an overview slide navigates to it
toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR)).forEach(function (slide) {
if (!slide.classList.contains('stack')) {
slide.addEventListener('click', onOverviewSlideClicked, true);
}
});
updateSlidesVisibility();
layoutOverview();
updateOverview();
layout();
// Notify observers of the overview showing
dispatchEvent('overviewshown', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
});
}
}
/**
* Uses CSS transforms to position all slides in a grid for
* display inside of the overview mode.
*/
function layoutOverview() {
var margin = 70;
var slideWidth = config.width + margin,
slideHeight = config.height + margin;
// Reverse in RTL mode
if (config.rtl) {
slideWidth = -slideWidth;
}
// Layout slides
toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)).forEach(function (hslide, h) {
hslide.setAttribute('data-index-h', h);
transformElement(hslide, 'translate3d(' + (h * slideWidth) + 'px, 0, 0)');
if (hslide.classList.contains('stack')) {
toArray(hslide.querySelectorAll('section')).forEach(function (vslide, v) {
vslide.setAttribute('data-index-h', h);
vslide.setAttribute('data-index-v', v);
transformElement(vslide, 'translate3d(0, ' + (v * slideHeight) + 'px, 0)');
});
}
});
// Layout slide backgrounds
toArray(dom.background.childNodes).forEach(function (hbackground, h) {
transformElement(hbackground, 'translate3d(' + (h * slideWidth) + 'px, 0, 0)');
toArray(hbackground.querySelectorAll('.slide-background')).forEach(function (vbackground, v) {
transformElement(vbackground, 'translate3d(0, ' + (v * slideHeight) + 'px, 0)');
});
});
}
/**
* Moves the overview viewport to the current slides.
* Called each time the current slide changes.
*/
function updateOverview() {
var margin = 70;
var slideWidth = config.width + margin,
slideHeight = config.height + margin;
// Reverse in RTL mode
if (config.rtl) {
slideWidth = -slideWidth;
}
transformSlides({
overview: [
'translateX(' + (-indexh * slideWidth) + 'px)',
'translateY(' + (-indexv * slideHeight) + 'px)',
'translateZ(' + (window.innerWidth < 400 ? -1000 : -2500) + 'px)'
].join(' ')
});
}
/**
* Exits the slide overview and enters the currently
* active slide.
*/
function deactivateOverview() {
// Only proceed if enabled in config
if (config.overview) {
overview = false;
dom.wrapper.classList.remove('overview');
dom.wrapper.classList.remove('overview-animated');
// Temporarily add a class so that transitions can do different things
// depending on whether they are exiting/entering overview, or just
// moving from slide to slide
dom.wrapper.classList.add('overview-deactivating');
setTimeout(function () {
dom.wrapper.classList.remove('overview-deactivating');
}, 1);
// Move the background element back out
dom.wrapper.appendChild(dom.background);
// Clean up changes made to slides
toArray(dom.wrapper.querySelectorAll(SLIDES_SELECTOR)).forEach(function (slide) {
transformElement(slide, '');
slide.removeEventListener('click', onOverviewSlideClicked, true);
});
// Clean up changes made to backgrounds
toArray(dom.background.querySelectorAll('.slide-background')).forEach(function (background) {
transformElement(background, '');
});
transformSlides({
overview: ''
});
slide(indexh, indexv);
layout();
cueAutoSlide();
// Notify observers of the overview hiding
dispatchEvent('overviewhidden', {
'indexh': indexh,
'indexv': indexv,
'currentSlide': currentSlide
});
}
}
/**
* Toggles the slide overview mode on and off.
*
* @param {Boolean} override Optional flag which overrides the
* toggle logic and forcibly sets the desired state. True means
* overview is open, false means it's closed.
*/
function toggleOverview(override) {
if (typeof override === 'boolean') {
override ? activateOverview() : deactivateOverview();
} else {
isOverview() ? deactivateOverview() : activateOverview();
}
}
/**
* Checks if the overview is currently active.
*
* @return {Boolean} true if the overview is active,
* false otherwise
*/
function isOverview() {
return overview;
}
/**
* Checks if the current or specified slide is vertical
* (nested within another slide).
*
* @param {HTMLElement} slide [optional] The slide to check
* orientation of
*/
function isVerticalSlide(slide) {
// Prefer slide argument, otherwise use current slide
slide = slide ? slide : currentSlide;
return slide && slide.parentNode && !!slide.parentNode.nodeName.match(/section/i);
}
/**
* Handling the fullscreen functionality via the fullscreen API
*
* @see http://fullscreen.spec.whatwg.org/
* @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
*/
function enterFullscreen() {
var element = document.body;
// Check which implementation is available
var requestMethod = element.requestFullScreen ||
element.webkitRequestFullscreen ||
element.webkitRequestFullScreen ||
element.mozRequestFullScreen ||
element.msRequestFullscreen;
if (requestMethod) {
requestMethod.apply(element);
}
}
/**
* Enters the paused mode which fades everything on screen to
* black.
*/
function pause() {
if (config.pause) {
var wasPaused = dom.wrapper.classList.contains('paused');
cancelAutoSlide();
dom.wrapper.classList.add('paused');
if (wasPaused === false) {
dispatchEvent('paused');
}
}
}
/**
* Exits from the paused mode.
*/
function resume() {
var wasPaused = dom.wrapper.classList.contains('paused');
dom.wrapper.classList.remove('paused');
cueAutoSlide();
if (wasPaused) {
dispatchEvent('resumed');
}
}
/**
* Toggles the paused mode on and off.
*/
function togglePause(override) {
if (typeof override === 'boolean') {
override ? pause() : resume();
} else {
isPaused() ? resume() : pause();
}
}
/**
* Checks if we are currently in the paused mode.
*/
function isPaused() {
return dom.wrapper.classList.contains('paused');
}
/**
* Toggles the auto slide mode on and off.
*
* @param {Boolean} override Optional flag which sets the desired state.
* True means autoplay starts, false means it stops.
*/
function toggleAutoSlide(override) {
if (typeof override === 'boolean') {
override ? resumeAutoSlide() : pauseAutoSlide();
} else {
autoSlidePaused ? resumeAutoSlide() : pauseAutoSlide();
}
}
/**
* Checks if the auto slide mode is currently on.
*/
function isAutoSliding() {
return !!(autoSlide && !autoSlidePaused);
}
/**
* Steps from the current point in the presentation to the
* slide which matches the specified horizontal and vertical
* indices.
*
* @param {int} h Horizontal index of the target slide
* @param {int} v Vertical index of the target slide
* @param {int} f Optional index of a fragment within the
* target slide to activate
* @param {int} o Optional origin for use in multimaster environments
*/
function slide(h, v, f, o) {
// Remember where we were at before
previousSlide = currentSlide;
// Query all horizontal slides in the deck
var horizontalSlides = dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR);
// If no vertical index is specified and the upcoming slide is a
// stack, resume at its previous vertical index
if (v === undefined && !isOverview()) {
v = getPreviousVerticalIndex(horizontalSlides[h]);
}
// If we were on a vertical stack, remember what vertical index
// it was on so we can resume at the same position when returning
if (previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains('stack')) {
setPreviousVerticalIndex(previousSlide.parentNode, indexv);
}
// Remember the state before this slide
var stateBefore = state.concat();
// Reset the state array
state.length = 0;
var indexhBefore = indexh || 0,
indexvBefore = indexv || 0;
// Activate and transition to the new slide
indexh = updateSlides(HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h);
indexv = updateSlides(VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v);
// Update the visibility of slides now that the indices have changed
updateSlidesVisibility();
layout();
// Apply the new state
stateLoop: for (var i = 0, len = state.length; i < len; i++) {
// Check if this state existed on the previous slide. If it
// did, we will avoid adding it repeatedly
for (var j = 0; j < stateBefore.length; j++) {
if (stateBefore[j] === state[i]) {
stateBefore.splice(j, 1);
continue stateLoop;
}
}
document.documentElement.classList.add(state[i]);
// Dispatch custom event matching the state's name
dispatchEvent(state[i]);
}
// Clean up the remains of the previous state
while (stateBefore.length) {
document.documentElement.classList.remove(stateBefore.pop());
}
// Update the overview if it's currently active
if (isOverview()) {
updateOverview();
}
// Find the current horizontal slide and any possible vertical slides
// within it
var currentHorizontalSlide = horizontalSlides[indexh],
currentVerticalSlides = currentHorizontalSlide.querySelectorAll('section');
// Store references to the previous and current slides
currentSlide = currentVerticalSlides[indexv] || currentHorizontalSlide;
// Show fragment, if specified
if (typeof f !== 'undefined') {
navigateFragment(f);
}
// Dispatch an event if the slide changed
var slideChanged = (indexh !== indexhBefore || indexv !== indexvBefore);
if (slideChanged) {
dispatchEvent('slidechanged', {
'indexh': indexh,
'indexv': indexv,
'previousSlide': previousSlide,
'currentSlide': currentSlide,
'origin': o
});
} else {
// Ensure that the previous slide is never the same as the current
previousSlide = null;
}
// Solves an edge case where the previous slide maintains the
// 'present' class when navigating between adjacent vertical
// stacks
if (previousSlide) {
previousSlide.classList.remove('present');
previousSlide.setAttribute('aria-hidden', 'true');
// Reset all slides upon navigate to home
// Issue: #285
if (dom.wrapper.querySelector(HOME_SLIDE_SELECTOR).classList.contains('present')) {
// Launch async task
setTimeout(function () {
var slides = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR + '.stack')),
i;
for (i in slides) {
if (slides[i]) {
// Reset stack
setPreviousVerticalIndex(slides[i], 0);
}
}
}, 0);
}
}
// Handle embedded content
if (slideChanged || !previousSlide) {
stopEmbeddedContent(previousSlide);
startEmbeddedContent(currentSlide);
}
// Announce the current slide contents, for screen readers
dom.statusDiv.textContent = currentSlide.textContent;
updateControls();
updateProgress();
updateBackground();
updateParallax();
updateSlideNumber();
updateNotes();
// Update the URL hash
writeURL();
cueAutoSlide();
}
/**
* Syncs the presentation with the current DOM. Useful
* when new slides or control elements are added or when
* the configuration has changed.
*/
function sync() {
// Subscribe to input
removeEventListeners();
addEventListeners();
// Force a layout to make sure the current config is accounted for
layout();
// Reflect the current autoSlide value
autoSlide = config.autoSlide;
// Start auto-sliding if it's enabled
cueAutoSlide();
// Re-create the slide backgrounds
createBackgrounds();
// Write the current hash to the URL
writeURL();
sortAllFragments();
updateControls();
updateProgress();
updateBackground(true);
updateSlideNumber();
updateSlidesVisibility();
updateNotes();
formatEmbeddedContent();
startEmbeddedContent(currentSlide);
if (isOverview()) {
layoutOverview();
}
}
/**
* Resets all vertical slides so that only the first
* is visible.
*/
function resetVerticalSlides() {
var horizontalSlides = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR));
horizontalSlides.forEach(function (horizontalSlide) {
var verticalSlides = toArray(horizontalSlide.querySelectorAll('section'));
verticalSlides.forEach(function (verticalSlide, y) {
if (y > 0) {
verticalSlide.classList.remove('present');
verticalSlide.classList.remove('past');
verticalSlide.classList.add('future');
verticalSlide.setAttribute('aria-hidden', 'true');
}
});
});
}
/**
* Sorts and formats all of fragments in the
* presentation.
*/
function sortAllFragments() {
var horizontalSlides = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR));
horizontalSlides.forEach(function (horizontalSlide) {
var verticalSlides = toArray(horizontalSlide.querySelectorAll('section'));
verticalSlides.forEach(function (verticalSlide, y) {
sortFragments(verticalSlide.querySelectorAll('.fragment'));
});
if (verticalSlides.length === 0) sortFragments(horizontalSlide.querySelectorAll('.fragment'));
});
}
/**
* Updates one dimension of slides by showing the slide
* with the specified index.
*
* @param {String} selector A CSS selector that will fetch
* the group of slides we are working with
* @param {Number} index The index of the slide that should be
* shown
*
* @return {Number} The index of the slide that is now shown,
* might differ from the passed in index if it was out of
* bounds.
*/
function updateSlides(selector, index) {
// Select all slides and convert the NodeList result to
// an array
var slides = toArray(dom.wrapper.querySelectorAll(selector)),
slidesLength = slides.length;
var printMode = isPrintingPDF();
if (slidesLength) {
// Should the index loop?
if (config.loop) {
index %= slidesLength;
if (index < 0) {
index = slidesLength + index;
}
}
// Enforce max and minimum index bounds
index = Math.max(Math.min(index, slidesLength - 1), 0);
for (var i = 0; i < slidesLength; i++) {
var element = slides[i];
var reverse = config.rtl && !isVerticalSlide(element);
element.classList.remove('past');
element.classList.remove('present');
element.classList.remove('future');
// http://www.w3.org/html/wg/drafts/html/master/editing.html#the-hidden-attribute
element.setAttribute('hidden', '');
element.setAttribute('aria-hidden', 'true');
// If this element contains vertical slides
if (element.querySelector('section')) {
element.classList.add('stack');
}
// If we're printing static slides, all slides are "present"
if (printMode) {
element.classList.add('present');
continue;
}
if (i < index) {
// Any element previous to index is given the 'past' class
element.classList.add(reverse ? 'future' : 'past');
if (config.fragments) {
var pastFragments = toArray(element.querySelectorAll('.fragment'));
// Show all fragments on prior slides
while (pastFragments.length) {
var pastFragment = pastFragments.pop();
pastFragment.classList.add('visible');
pastFragment.classList.remove('current-fragment');
}
}
} else if (i > index) {
// Any element subsequent to index is given the 'future' class
element.classList.add(reverse ? 'past' : 'future');
if (config.fragments) {
var futureFragments = toArray(element.querySelectorAll('.fragment.visible'));
// No fragments in future slides should be visible ahead of time
while (futureFragments.length) {
var futureFragment = futureFragments.pop();
futureFragment.classList.remove('visible');
futureFragment.classList.remove('current-fragment');
}
}
}
}
// Mark the current slide as present
slides[index].classList.add('present');
slides[index].removeAttribute('hidden');
slides[index].removeAttribute('aria-hidden');
// If this slide has a state associated with it, add it
// onto the current state of the deck
var slideState = slides[index].getAttribute('data-state');
if (slideState) {
state = state.concat(slideState.split(' '));
}
} else {
// Since there are no slides we can't be anywhere beyond the
// zeroth index
index = 0;
}
return index;
}
/**
* Optimization method; hide all slides that are far away
* from the present slide.
*/
function updateSlidesVisibility() {
// Select all slides and convert the NodeList result to
// an array
var horizontalSlides = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)),
horizontalSlidesLength = horizontalSlides.length,
distanceX,
distanceY;
if (horizontalSlidesLength && typeof indexh !== 'undefined') {
// The number of steps away from the present slide that will
// be visible
var viewDistance = isOverview() ? 10 : config.viewDistance;
// Limit view distance on weaker devices
if (isMobileDevice) {
viewDistance = isOverview() ? 6 : 2;
}
// All slides need to be visible when exporting to PDF
if (isPrintingPDF()) {
viewDistance = Number.MAX_VALUE;
}
for (var x = 0; x < horizontalSlidesLength; x++) {
var horizontalSlide = horizontalSlides[x];
var verticalSlides = toArray(horizontalSlide.querySelectorAll('section')),
verticalSlidesLength = verticalSlides.length;
// Determine how far away this slide is from the present
distanceX = Math.abs((indexh || 0) - x) || 0;
// If the presentation is looped, distance should measure
// 1 between the first and last slides
if (config.loop) {
distanceX = Math.abs(((indexh || 0) - x) % (horizontalSlidesLength - viewDistance)) || 0;
}
// Show the horizontal slide if it's within the view distance
if (distanceX < viewDistance) {
showSlide(horizontalSlide);
} else {
hideSlide(horizontalSlide);
}
if (verticalSlidesLength) {
var oy = getPreviousVerticalIndex(horizontalSlide);
for (var y = 0; y < verticalSlidesLength; y++) {
var verticalSlide = verticalSlides[y];
distanceY = x === (indexh || 0) ? Math.abs((indexv || 0) - y) : Math.abs(y - oy);
if (distanceX + distanceY < viewDistance) {
showSlide(verticalSlide);
} else {
hideSlide(verticalSlide);
}
}
}
}
}
}
/**
* Pick up notes from the current slide and display tham
* to the viewer.
*
* @see `showNotes` config value
*/
function updateNotes() {
if (config.showNotes && dom.speakerNotes && currentSlide && !isPrintingPDF()) {
dom.speakerNotes.innerHTML = getSlideNotes() || '';
}
}
/**
* Updates the progress bar to reflect the current slide.
*/
function updateProgress() {
// Update progress if enabled
if (config.progress && dom.progressbar) {
dom.progressbar.style.width = getProgress() * dom.wrapper.offsetWidth + 'px';
}
}
/**
* Updates the slide number div to reflect the current slide.
*
* The following slide number formats are available:
* "h.v": horizontal . vertical slide number (default)
* "h/v": horizontal / vertical slide number
* "c": flattened slide number
* "c/t": flattened slide number / total slides
*/
function updateSlideNumber() {
// Update slide number if enabled
if (config.slideNumber && dom.slideNumber) {
var value = [];
var format = 'h.v';
// Check if a custom number format is available
if (typeof config.slideNumber === 'string') {
format = config.slideNumber;
}
switch (format) {
case 'c':
value.push(getSlidePastCount() + 1);
break;
case 'c/t':
value.push(getSlidePastCount() + 1, '/', getTotalSlides());
break;
case 'h/v':
value.push(indexh + 1);
if (isVerticalSlide()) value.push('/', indexv + 1);
break;
default:
value.push(indexh + 1);
if (isVerticalSlide()) value.push('.', indexv + 1);
}
dom.slideNumber.innerHTML = formatSlideNumber(value[0], value[1], value[2]);
}
}
/**
* Applies HTML formatting to a slide number before it's
* written to the DOM.
*/
function formatSlideNumber(a, delimiter, b) {
if (typeof b === 'number' && !isNaN(b)) {
return '<span class="slide-number-a">' + a + '</span>' +
'<span class="slide-number-delimiter">' + delimiter + '</span>' +
'<span class="slide-number-b">' + b + '</span>';
} else {
return '<span class="slide-number-a">' + a + '</span>';
}
}
/**
* Updates the state of all control/navigation arrows.
*/
function updateControls() {
var routes = availableRoutes();
var fragments = availableFragments();
// Remove the 'enabled' class from all directions
dom.controlsLeft.concat(dom.controlsRight)
.concat(dom.controlsUp)
.concat(dom.controlsDown)
.concat(dom.controlsPrev)
.concat(dom.controlsNext).forEach(function (node) {
node.classList.remove('enabled');
node.classList.remove('fragmented');
});
// Add the 'enabled' class to the available routes
if (routes.left) dom.controlsLeft.forEach(function (el) {
el.classList.add('enabled');
});
if (routes.right) dom.controlsRight.forEach(function (el) {
el.classList.add('enabled');
});
if (routes.up) dom.controlsUp.forEach(function (el) {
el.classList.add('enabled');
});
if (routes.down) dom.controlsDown.forEach(function (el) {
el.classList.add('enabled');
});
// Prev/next buttons
if (routes.left || routes.up) dom.controlsPrev.forEach(function (el) {
el.classList.add('enabled');
});
if (routes.right || routes.down) dom.controlsNext.forEach(function (el) {
el.classList.add('enabled');
});
// Highlight fragment directions
if (currentSlide) {
// Always apply fragment decorator to prev/next buttons
if (fragments.prev) dom.controlsPrev.forEach(function (el) {
el.classList.add('fragmented', 'enabled');
});
if (fragments.next) dom.controlsNext.forEach(function (el) {
el.classList.add('fragmented', 'enabled');
});
// Apply fragment decorators to directional buttons based on
// what slide axis they are in
if (isVerticalSlide(currentSlide)) {
if (fragments.prev) dom.controlsUp.forEach(function (el) {
el.classList.add('fragmented', 'enabled');
});
if (fragments.next) dom.controlsDown.forEach(function (el) {
el.classList.add('fragmented', 'enabled');
});
} else {
if (fragments.prev) dom.controlsLeft.forEach(function (el) {
el.classList.add('fragmented', 'enabled');
});
if (fragments.next) dom.controlsRight.forEach(function (el) {
el.classList.add('fragmented', 'enabled');
});
}
}
}
/**
* Updates the background elements to reflect the current
* slide.
*
* @param {Boolean} includeAll If true, the backgrounds of
* all vertical slides (not just the present) will be updated.
*/
function updateBackground(includeAll) {
var currentBackground = null;
// Reverse past/future classes when in RTL mode
var horizontalPast = config.rtl ? 'future' : 'past',
horizontalFuture = config.rtl ? 'past' : 'future';
// Update the classes of all backgrounds to match the
// states of their slides (past/present/future)
toArray(dom.background.childNodes).forEach(function (backgroundh, h) {
backgroundh.classList.remove('past');
backgroundh.classList.remove('present');
backgroundh.classList.remove('future');
if (h < indexh) {
backgroundh.classList.add(horizontalPast);
} else if (h > indexh) {
backgroundh.classList.add(horizontalFuture);
} else {
backgroundh.classList.add('present');
// Store a reference to the current background element
currentBackground = backgroundh;
}
if (includeAll || h === indexh) {
toArray(backgroundh.querySelectorAll('.slide-background')).forEach(function (backgroundv, v) {
backgroundv.classList.remove('past');
backgroundv.classList.remove('present');
backgroundv.classList.remove('future');
if (v < indexv) {
backgroundv.classList.add('past');
} else if (v > indexv) {
backgroundv.classList.add('future');
} else {
backgroundv.classList.add('present');
// Only if this is the present horizontal and vertical slide
if (h === indexh) currentBackground = backgroundv;
}
});
}
});
// Stop any currently playing video background
if (previousBackground) {
var previousVideo = previousBackground.querySelector('video');
if (previousVideo) previousVideo.pause();
}
if (currentBackground) {
// Start video playback
var currentVideo = currentBackground.querySelector('video');
if (currentVideo) {
if (currentVideo.currentTime > 0) currentVideo.currentTime = 0;
currentVideo.play();
}
var backgroundImageURL = currentBackground.style.backgroundImage || '';
// Restart GIFs (doesn't work in Firefox)
if (/\.gif/i.test(backgroundImageURL)) {
currentBackground.style.backgroundImage = '';
window.getComputedStyle(currentBackground).opacity;
currentBackground.style.backgroundImage = backgroundImageURL;
}
// Don't transition between identical backgrounds. This
// prevents unwanted flicker.
var previousBackgroundHash = previousBackground ? previousBackground.getAttribute('data-background-hash') : null;
var currentBackgroundHash = currentBackground.getAttribute('data-background-hash');
if (currentBackgroundHash && currentBackgroundHash === previousBackgroundHash && currentBackground !== previousBackground) {
dom.background.classList.add('no-transition');
}
previousBackground = currentBackground;
}
// If there's a background brightness flag for this slide,
// bubble it to the .reveal container
if (currentSlide) {
['has-light-background', 'has-dark-background'].forEach(function (classToBubble) {
if (currentSlide.classList.contains(classToBubble)) {
dom.wrapper.classList.add(classToBubble);
} else {
dom.wrapper.classList.remove(classToBubble);
}
});
}
// Allow the first background to apply without transition
setTimeout(function () {
dom.background.classList.remove('no-transition');
}, 1);
}
/**
* Updates the position of the parallax background based
* on the current slide index.
*/
function updateParallax() {
if (config.parallaxBackgroundImage) {
var horizontalSlides = dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR),
verticalSlides = dom.wrapper.querySelectorAll(VERTICAL_SLIDES_SELECTOR);
var backgroundSize = dom.background.style.backgroundSize.split(' '),
backgroundWidth, backgroundHeight;
if (backgroundSize.length === 1) {
backgroundWidth = backgroundHeight = parseInt(backgroundSize[0], 10);
} else {
backgroundWidth = parseInt(backgroundSize[0], 10);
backgroundHeight = parseInt(backgroundSize[1], 10);
}
var slideWidth = dom.background.offsetWidth,
horizontalSlideCount = horizontalSlides.length,
horizontalOffsetMultiplier,
horizontalOffset;
if (typeof config.parallaxBackgroundHorizontal === 'number') {
horizontalOffsetMultiplier = config.parallaxBackgroundHorizontal;
} else {
horizontalOffsetMultiplier = (backgroundWidth - slideWidth) / (horizontalSlideCount - 1);
}
horizontalOffset = horizontalOffsetMultiplier * indexh * -1;
var slideHeight = dom.background.offsetHeight,
verticalSlideCount = verticalSlides.length,
verticalOffsetMultiplier,
verticalOffset;
if (typeof config.parallaxBackgroundVertical === 'number') {
verticalOffsetMultiplier = config.parallaxBackgroundVertical;
} else {
verticalOffsetMultiplier = (backgroundHeight - slideHeight) / (verticalSlideCount - 1);
}
verticalOffset = verticalSlideCount > 0 ? verticalOffsetMultiplier * indexv * 1 : 0;
dom.background.style.backgroundPosition = horizontalOffset + 'px ' + -verticalOffset + 'px';
}
}
/**
* Called when the given slide is within the configured view
* distance. Shows the slide element and loads any content
* that is set to load lazily (data-src).
*/
function showSlide(slide) {
// Show the slide element
slide.style.display = 'block';
// Media elements with data-src attributes
toArray(slide.querySelectorAll('img[data-src], video[data-src], audio[data-src]')).forEach(function (element) {
element.setAttribute('src', element.getAttribute('data-src'));
element.removeAttribute('data-src');
});
// Media elements with <source> children
toArray(slide.querySelectorAll('video, audio')).forEach(function (media) {
var sources = 0;
toArray(media.querySelectorAll('source[data-src]')).forEach(function (source) {
source.setAttribute('src', source.getAttribute('data-src'));
source.removeAttribute('data-src');
sources += 1;
});
// If we rewrote sources for this video/audio element, we need
// to manually tell it to load from its new origin
if (sources > 0) {
media.load();
}
});
// Show the corresponding background element
var indices = getIndices(slide);
var background = getSlideBackground(indices.h, indices.v);
if (background) {
background.style.display = 'block';
// If the background contains media, load it
if (background.hasAttribute('data-loaded') === false) {
background.setAttribute('data-loaded', 'true');
var backgroundImage = slide.getAttribute('data-background-image'),
backgroundVideo = slide.getAttribute('data-background-video'),
backgroundVideoLoop = slide.hasAttribute('data-background-video-loop'),
backgroundIframe = slide.getAttribute('data-background-iframe');
// Images
if (backgroundImage) {
background.style.backgroundImage = 'url(' + backgroundImage + ')';
}
// Videos
else if (backgroundVideo && !isSpeakerNotes()) {
var video = document.createElement('video');
if (backgroundVideoLoop) {
video.setAttribute('loop', '');
}
// Support comma separated lists of video sources
backgroundVideo.split(',').forEach(function (source) {
video.innerHTML += '<source src="' + source + '">';
});
background.appendChild(video);
}
// Iframes
else if (backgroundIframe) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', backgroundIframe);
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.maxHeight = '100%';
iframe.style.maxWidth = '100%';
background.appendChild(iframe);
}
}
}
}
/**
* Called when the given slide is moved outside of the
* configured view distance.
*/
function hideSlide(slide) {
// Hide the slide element
slide.style.display = 'none';
// Hide the corresponding background element
var indices = getIndices(slide);
var background = getSlideBackground(indices.h, indices.v);
if (background) {
background.style.display = 'none';
}
}
/**
* Determine what available routes there are for navigation.
*
* @return {Object} containing four booleans: left/right/up/down
*/
function availableRoutes() {
var horizontalSlides = dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR),
verticalSlides = dom.wrapper.querySelectorAll(VERTICAL_SLIDES_SELECTOR);
var routes = {
left: indexh > 0 || config.loop,
right: indexh < horizontalSlides.length - 1 || config.loop,
up: indexv > 0,
down: indexv < verticalSlides.length - 1
};
// reverse horizontal controls for rtl
if (config.rtl) {
var left = routes.left;
routes.left = routes.right;
routes.right = left;
}
return routes;
}
/**
* Returns an object describing the available fragment
* directions.
*
* @return {Object} two boolean properties: prev/next
*/
function availableFragments() {
if (currentSlide && config.fragments) {
var fragments = currentSlide.querySelectorAll('.fragment');
var hiddenFragments = currentSlide.querySelectorAll('.fragment:not(.visible)');
return {
prev: fragments.length - hiddenFragments.length > 0,
next: !!hiddenFragments.length
};
} else {
return {
prev: false,
next: false
};
}
}
/**
* Enforces origin-specific format rules for embedded media.
*/
function formatEmbeddedContent() {
var _appendParamToIframeSource = function (sourceAttribute, sourceURL, param) {
toArray(dom.slides.querySelectorAll('iframe[' + sourceAttribute + '*="' + sourceURL + '"]')).forEach(function (el) {
var src = el.getAttribute(sourceAttribute);
if (src && src.indexOf(param) === -1) {
el.setAttribute(sourceAttribute, src + (!/\?/.test(src) ? '?' : '&') + param);
}
});
};
// YouTube frames must include "?enablejsapi=1"
_appendParamToIframeSource('src', 'youtube.com/embed/', 'enablejsapi=1');
_appendParamToIframeSource('data-src', 'youtube.com/embed/', 'enablejsapi=1');
// Vimeo frames must include "?api=1"
_appendParamToIframeSource('src', 'player.vimeo.com/', 'api=1');
_appendParamToIframeSource('data-src', 'player.vimeo.com/', 'api=1');
}
/**
* Start playback of any embedded content inside of
* the targeted slide.
*/
function startEmbeddedContent(slide) {
if (slide && !isSpeakerNotes()) {
// Restart GIFs
toArray(slide.querySelectorAll('img[src$=".gif"]')).forEach(function (el) {
// Setting the same unchanged source like this was confirmed
// to work in Chrome, FF & Safari
el.setAttribute('src', el.getAttribute('src'));
});
// HTML5 media elements
toArray(slide.querySelectorAll('video, audio')).forEach(function (el) {
if (el.hasAttribute('data-autoplay') && typeof el.play === 'function') {
el.play();
}
});
// Normal iframes
toArray(slide.querySelectorAll('iframe[src]')).forEach(function (el) {
startEmbeddedIframe({
target: el
});
});
// Lazy loading iframes
toArray(slide.querySelectorAll('iframe[data-src]')).forEach(function (el) {
if (el.getAttribute('src') !== el.getAttribute('data-src')) {
el.removeEventListener('load', startEmbeddedIframe); // remove first to avoid dupes
el.addEventListener('load', startEmbeddedIframe);
el.setAttribute('src', el.getAttribute('data-src'));
}
});
}
}
/**
* "Starts" the content of an embedded iframe using the
* postmessage API.
*/
function startEmbeddedIframe(event) {
var iframe = event.target;
// YouTube postMessage API
if (/youtube\.com\/embed\//.test(iframe.getAttribute('src')) && iframe.hasAttribute('data-autoplay')) {
iframe.contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
// Vimeo postMessage API
else if (/player\.vimeo\.com\//.test(iframe.getAttribute('src')) && iframe.hasAttribute('data-autoplay')) {
iframe.contentWindow.postMessage('{"method":"play"}', '*');
}
// Generic postMessage API
else {
iframe.contentWindow.postMessage('slide:start', '*');
}
}
/**
* Stop playback of any embedded content inside of
* the targeted slide.
*/
function stopEmbeddedContent(slide) {
if (slide && slide.parentNode) {
// HTML5 media elements
toArray(slide.querySelectorAll('video, audio')).forEach(function (el) {
if (!el.hasAttribute('data-ignore') && typeof el.pause === 'function') {
el.pause();
}
});
// Generic postMessage API for non-lazy loaded iframes
toArray(slide.querySelectorAll('iframe')).forEach(function (el) {
el.contentWindow.postMessage('slide:stop', '*');
el.removeEventListener('load', startEmbeddedIframe);
});
// YouTube postMessage API
toArray(slide.querySelectorAll('iframe[src*="youtube.com/embed/"]')).forEach(function (el) {
if (!el.hasAttribute('data-ignore') && typeof el.contentWindow.postMessage === 'function') {
el.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
});
// Vimeo postMessage API
toArray(slide.querySelectorAll('iframe[src*="player.vimeo.com/"]')).forEach(function (el) {
if (!el.hasAttribute('data-ignore') && typeof el.contentWindow.postMessage === 'function') {
el.contentWindow.postMessage('{"method":"pause"}', '*');
}
});
// Lazy loading iframes
toArray(slide.querySelectorAll('iframe[data-src]')).forEach(function (el) {
// Only removing the src doesn't actually unload the frame
// in all browsers (Firefox) so we set it to blank first
el.setAttribute('src', 'about:blank');
el.removeAttribute('src');
});
}
}
/**
* Returns the number of past slides. This can be used as a global
* flattened index for slides.
*/
function getSlidePastCount() {
var horizontalSlides = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR));
// The number of past slides
var pastCount = 0;
// Step through all slides and count the past ones
mainLoop: for (var i = 0; i < horizontalSlides.length; i++) {
var horizontalSlide = horizontalSlides[i];
var verticalSlides = toArray(horizontalSlide.querySelectorAll('section'));
for (var j = 0; j < verticalSlides.length; j++) {
// Stop as soon as we arrive at the present
if (verticalSlides[j].classList.contains('present')) {
break mainLoop;
}
pastCount++;
}
// Stop as soon as we arrive at the present
if (horizontalSlide.classList.contains('present')) {
break;
}
// Don't count the wrapping section for vertical slides
if (horizontalSlide.classList.contains('stack') === false) {
pastCount++;
}
}
return pastCount;
}
/**
* Returns a value ranging from 0-1 that represents
* how far into the presentation we have navigated.
*/
function getProgress() {
// The number of past and total slides
var totalCount = getTotalSlides();
var pastCount = getSlidePastCount();
if (currentSlide) {
var allFragments = currentSlide.querySelectorAll('.fragment');
// If there are fragments in the current slide those should be
// accounted for in the progress.
if (allFragments.length > 0) {
var visibleFragments = currentSlide.querySelectorAll('.fragment.visible');
// This value represents how big a portion of the slide progress
// that is made up by its fragments (0-1)
var fragmentWeight = 0.9;
// Add fragment progress to the past slide count
pastCount += (visibleFragments.length / allFragments.length) * fragmentWeight;
}
}
return pastCount / (totalCount - 1);
}
/**
* Checks if this presentation is running inside of the
* speaker notes window.
*/
function isSpeakerNotes() {
return !!window.location.search.match(/receiver/gi);
}
/**
* Reads the current URL (hash) and navigates accordingly.
*/
function readURL() {
var hash = window.location.hash;
// Attempt to parse the hash as either an index or name
var bits = hash.slice(2).split('/'),
name = hash.replace(/#|\//gi, '');
// If the first bit is invalid and there is a name we can
// assume that this is a named link
if (isNaN(parseInt(bits[0], 10)) && name.length) {
var element;
// Ensure the named link is a valid HTML ID attribute
if (/^[a-zA-Z][\w:.-]*$/.test(name)) {
// Find the slide with the specified ID
element = document.getElementById(name);
}
if (element) {
// Find the position of the named slide and navigate to it
var indices = Reveal.getIndices(element);
slide(indices.h, indices.v);
}
// If the slide doesn't exist, navigate to the current slide
else {
slide(indexh || 0, indexv || 0);
}
} else {
// Read the index components of the hash
var h = parseInt(bits[0], 10) || 0,
v = parseInt(bits[1], 10) || 0;
if (h !== indexh || v !== indexv) {
slide(h, v);
}
}
}
/**
* Updates the page URL (hash) to reflect the current
* state.
*
* @param {Number} delay The time in ms to wait before
* writing the hash
*/
function writeURL(delay) {
if (config.history) {
// Make sure there's never more than one timeout running
clearTimeout(writeURLTimeout);
// If a delay is specified, timeout this call
if (typeof delay === 'number') {
writeURLTimeout = setTimeout(writeURL, delay);
} else if (currentSlide) {
var url = '/';
// Attempt to create a named link based on the slide's ID
var id = currentSlide.getAttribute('id');
if (id) {
id = id.replace(/[^a-zA-Z0-9\-\_\:\.]/g, '');
}
// If the current slide has an ID, use that as a named link
if (typeof id === 'string' && id.length) {
url = '/' + id;
}
// Otherwise use the /h/v index
else {
if (indexh > 0 || indexv > 0) url += indexh;
if (indexv > 0) url += '/' + indexv;
}
window.location.hash = url;
}
}
}
/**
* Retrieves the h/v location of the current, or specified,
* slide.
*
* @param {HTMLElement} slide If specified, the returned
* index will be for this slide rather than the currently
* active one
*
* @return {Object} { h: <int>, v: <int>, f: <int> }
*/
function getIndices(slide) {
// By default, return the current indices
var h = indexh,
v = indexv,
f;
// If a slide is specified, return the indices of that slide
if (slide) {
var isVertical = isVerticalSlide(slide);
var slideh = isVertical ? slide.parentNode : slide;
// Select all horizontal slides
var horizontalSlides = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR));
// Now that we know which the horizontal slide is, get its index
h = Math.max(horizontalSlides.indexOf(slideh), 0);
// Assume we're not vertical
v = undefined;
// If this is a vertical slide, grab the vertical index
if (isVertical) {
v = Math.max(toArray(slide.parentNode.querySelectorAll('section')).indexOf(slide), 0);
}
}
if (!slide && currentSlide) {
var hasFragments = currentSlide.querySelectorAll('.fragment').length > 0;
if (hasFragments) {
var currentFragment = currentSlide.querySelector('.current-fragment');
if (currentFragment && currentFragment.hasAttribute('data-fragment-index')) {
f = parseInt(currentFragment.getAttribute('data-fragment-index'), 10);
} else {
f = currentSlide.querySelectorAll('.fragment.visible').length - 1;
}
}
}
return {
h: h,
v: v,
f: f
};
}
/**
* Retrieves the total number of slides in this presentation.
*/
function getTotalSlides() {
return dom.wrapper.querySelectorAll(SLIDES_SELECTOR + ':not(.stack)').length;
}
/**
* Returns the slide element matching the specified index.
*/
function getSlide(x, y) {
var horizontalSlide = dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)[x];
var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll('section');
if (verticalSlides && verticalSlides.length && typeof y === 'number') {
return verticalSlides ? verticalSlides[y] : undefined;
}
return horizontalSlide;
}
/**
* Returns the background element for the given slide.
* All slides, even the ones with no background properties
* defined, have a background element so as long as the
* index is valid an element will be returned.
*/
function getSlideBackground(x, y) {
// When printing to PDF the slide backgrounds are nested
// inside of the slides
if (isPrintingPDF()) {
var slide = getSlide(x, y);
if (slide) {
var background = slide.querySelector('.slide-background');
if (background && background.parentNode === slide) {
return background;
}
}
return undefined;
}
var horizontalBackground = dom.wrapper.querySelectorAll('.backgrounds>.slide-background')[x];
var verticalBackgrounds = horizontalBackground && horizontalBackground.querySelectorAll('.slide-background');
if (verticalBackgrounds && verticalBackgrounds.length && typeof y === 'number') {
return verticalBackgrounds ? verticalBackgrounds[y] : undefined;
}
return horizontalBackground;
}
/**
* Retrieves the speaker notes from a slide. Notes can be
* defined in two ways:
* 1. As a data-notes attribute on the slide <section>
* 2. As an <aside class="notes"> inside of the slide
*/
function getSlideNotes(slide) {
// Default to the current slide
slide = slide || currentSlide;
// Notes can be specified via the data-notes attribute...
if (slide.hasAttribute('data-notes')) {
return slide.getAttribute('data-notes');
}
// ... or using an <aside class="notes"> element
var notesElement = slide.querySelector('aside.notes');
if (notesElement) {
return notesElement.innerHTML;
}
return null;
}
/**
* Retrieves the current state of the presentation as
* an object. This state can then be restored at any
* time.
*/
function getState() {
var indices = getIndices();
return {
indexh: indices.h,
indexv: indices.v,
indexf: indices.f,
paused: isPaused(),
overview: isOverview()
};
}
/**
* Restores the presentation to the given state.
*
* @param {Object} state As generated by getState()
*/
function setState(state) {
if (typeof state === 'object') {
slide(deserialize(state.indexh), deserialize(state.indexv), deserialize(state.indexf));
var pausedFlag = deserialize(state.paused),
overviewFlag = deserialize(state.overview);
if (typeof pausedFlag === 'boolean' && pausedFlag !== isPaused()) {
togglePause(pausedFlag);
}
if (typeof overviewFlag === 'boolean' && overviewFlag !== isOverview()) {
toggleOverview(overviewFlag);
}
}
}
/**
* Return a sorted fragments list, ordered by an increasing
* "data-fragment-index" attribute.
*
* Fragments will be revealed in the order that they are returned by
* this function, so you can use the index attributes to control the
* order of fragment appearance.
*
* To maintain a sensible default fragment order, fragments are presumed
* to be passed in document order. This function adds a "fragment-index"
* attribute to each node if such an attribute is not already present,
* and sets that attribute to an integer value which is the position of
* the fragment within the fragments list.
*/
function sortFragments(fragments) {
fragments = toArray(fragments);
var ordered = [],
unordered = [],
sorted = [];
// Group ordered and unordered elements
fragments.forEach(function (fragment, i) {
if (fragment.hasAttribute('data-fragment-index')) {
var index = parseInt(fragment.getAttribute('data-fragment-index'), 10);
if (!ordered[index]) {
ordered[index] = [];
}
ordered[index].push(fragment);
} else {
unordered.push([fragment]);
}
});
// Append fragments without explicit indices in their
// DOM order
ordered = ordered.concat(unordered);
// Manually count the index up per group to ensure there
// are no gaps
var index = 0;
// Push all fragments in their sorted order to an array,
// this flattens the groups
ordered.forEach(function (group) {
group.forEach(function (fragment) {
sorted.push(fragment);
fragment.setAttribute('data-fragment-index', index);
});
index++;
});
return sorted;
}
/**
* Navigate to the specified slide fragment.
*
* @param {Number} index The index of the fragment that
* should be shown, -1 means all are invisible
* @param {Number} offset Integer offset to apply to the
* fragment index
*
* @return {Boolean} true if a change was made in any
* fragments visibility as part of this call
*/
function navigateFragment(index, offset) {
if (currentSlide && config.fragments) {
var fragments = sortFragments(currentSlide.querySelectorAll('.fragment'));
if (fragments.length) {
// If no index is specified, find the current
if (typeof index !== 'number') {
var lastVisibleFragment = sortFragments(currentSlide.querySelectorAll('.fragment.visible')).pop();
if (lastVisibleFragment) {
index = parseInt(lastVisibleFragment.getAttribute('data-fragment-index') || 0, 10);
} else {
index = -1;
}
}
// If an offset is specified, apply it to the index
if (typeof offset === 'number') {
index += offset;
}
var fragmentsShown = [],
fragmentsHidden = [];
toArray(fragments).forEach(function (element, i) {
if (element.hasAttribute('data-fragment-index')) {
i = parseInt(element.getAttribute('data-fragment-index'), 10);
}
// Visible fragments
if (i <= index) {
if (!element.classList.contains('visible')) fragmentsShown.push(element);
element.classList.add('visible');
element.classList.remove('current-fragment');
// Announce the fragments one by one to the Screen Reader
dom.statusDiv.textContent = element.textContent;
if (i === index) {
element.classList.add('current-fragment');
}
}
// Hidden fragments
else {
if (element.classList.contains('visible')) fragmentsHidden.push(element);
element.classList.remove('visible');
element.classList.remove('current-fragment');
}
});
if (fragmentsHidden.length) {
dispatchEvent('fragmenthidden', {
fragment: fragmentsHidden[0],
fragments: fragmentsHidden
});
}
if (fragmentsShown.length) {
dispatchEvent('fragmentshown', {
fragment: fragmentsShown[0],
fragments: fragmentsShown
});
}
updateControls();
updateProgress();
return !!(fragmentsShown.length || fragmentsHidden.length);
}
}
return false;
}
/**
* Navigate to the next slide fragment.
*
* @return {Boolean} true if there was a next fragment,
* false otherwise
*/
function nextFragment() {
return navigateFragment(null, 1);
}
/**
* Navigate to the previous slide fragment.
*
* @return {Boolean} true if there was a previous fragment,
* false otherwise
*/
function previousFragment() {
return navigateFragment(null, -1);
}
/**
* Cues a new automated slide if enabled in the config.
*/
function cueAutoSlide() {
cancelAutoSlide();
if (currentSlide) {
var currentFragment = currentSlide.querySelector('.current-fragment');
var fragmentAutoSlide = currentFragment ? currentFragment.getAttribute('data-autoslide') : null;
var parentAutoSlide = currentSlide.parentNode ? currentSlide.parentNode.getAttribute('data-autoslide') : null;
var slideAutoSlide = currentSlide.getAttribute('data-autoslide');
// Pick value in the following priority order:
// 1. Current fragment's data-autoslide
// 2. Current slide's data-autoslide
// 3. Parent slide's data-autoslide
// 4. Global autoSlide setting
if (fragmentAutoSlide) {
autoSlide = parseInt(fragmentAutoSlide, 10);
} else if (slideAutoSlide) {
autoSlide = parseInt(slideAutoSlide, 10);
} else if (parentAutoSlide) {
autoSlide = parseInt(parentAutoSlide, 10);
} else {
autoSlide = config.autoSlide;
}
// If there are media elements with data-autoplay,
// automatically set the autoSlide duration to the
// length of that media. Not applicable if the slide
// is divided up into fragments.
if (currentSlide.querySelectorAll('.fragment').length === 0) {
toArray(currentSlide.querySelectorAll('video, audio')).forEach(function (el) {
if (el.hasAttribute('data-autoplay')) {
if (autoSlide && el.duration * 1000 > autoSlide) {
autoSlide = (el.duration * 1000) + 1000;
}
}
});
}
// Cue the next auto-slide if:
// - There is an autoSlide value
// - Auto-sliding isn't paused by the user
// - The presentation isn't paused
// - The overview isn't active
// - The presentation isn't over
if (autoSlide && !autoSlidePaused && !isPaused() && !isOverview() && (!Reveal.isLastSlide() || availableFragments().next || config.loop === true)) {
autoSlideTimeout = setTimeout(navigateNext, autoSlide);
autoSlideStartTime = Date.now();
}
if (autoSlidePlayer) {
autoSlidePlayer.setPlaying(autoSlideTimeout !== -1);
}
}
}
/**
* Cancels any ongoing request to auto-slide.
*/
function cancelAutoSlide() {
clearTimeout(autoSlideTimeout);
autoSlideTimeout = -1;
}
function pauseAutoSlide() {
if (autoSlide && !autoSlidePaused) {
autoSlidePaused = true;
dispatchEvent('autoslidepaused');
clearTimeout(autoSlideTimeout);
if (autoSlidePlayer) {
autoSlidePlayer.setPlaying(false);
}
}
}
function resumeAutoSlide() {
if (autoSlide && autoSlidePaused) {
autoSlidePaused = false;
dispatchEvent('autoslideresumed');
cueAutoSlide();
}
}
function navigateLeft() {
// Reverse for RTL
if (config.rtl) {
if ((isOverview() || nextFragment() === false) && availableRoutes().left) {
slide(indexh + 1);
}
}
// Normal navigation
else if ((isOverview() || previousFragment() === false) && availableRoutes().left) {
slide(indexh - 1);
}
}
function navigateRight() {
// Reverse for RTL
if (config.rtl) {
if ((isOverview() || previousFragment() === false) && availableRoutes().right) {
slide(indexh - 1);
}
}
// Normal navigation
else if ((isOverview() || nextFragment() === false) && availableRoutes().right) {
slide(indexh + 1);
}
}
function navigateUp() {
// Prioritize hiding fragments
if ((isOverview() || previousFragment() === false) && availableRoutes().up) {
slide(indexh, indexv - 1);
}
}
function navigateDown() {
// Prioritize revealing fragments
if ((isOverview() || nextFragment() === false) && availableRoutes().down) {
slide(indexh, indexv + 1);
}
}
/**
* Navigates backwards, prioritized in the following order:
* 1) Previous fragment
* 2) Previous vertical slide
* 3) Previous horizontal slide
*/
function navigatePrev() {
// Prioritize revealing fragments
if (previousFragment() === false) {
if (availableRoutes().up) {
navigateUp();
} else {
// Fetch the previous horizontal slide, if there is one
var previousSlide;
if (config.rtl) {
previousSlide = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR + '.future')).pop();
} else {
previousSlide = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR + '.past')).pop();
}
if (previousSlide) {
var v = (previousSlide.querySelectorAll('section').length - 1) || undefined;
var h = indexh - 1;
slide(h, v);
}
}
}
}
/**
* The reverse of #navigatePrev().
*/
function navigateNext() {
// Prioritize revealing fragments
if (nextFragment() === false) {
if (availableRoutes().down) {
navigateDown();
} else if (config.rtl) {
navigateLeft();
} else {
navigateRight();
}
}
// If auto-sliding is enabled we need to cue up
// another timeout
cueAutoSlide();
}
/**
* Checks if the target element prevents the triggering of
* swipe navigation.
*/
function isSwipePrevented(target) {
while (target && typeof target.hasAttribute === 'function') {
if (target.hasAttribute('data-prevent-swipe')) return true;
target = target.parentNode;
}
return false;
}
// --------------------------------------------------------------------//
// ----------------------------- EVENTS -------------------------------//
// --------------------------------------------------------------------//
/**
* Called by all event handlers that are based on user
* input.
*/
function onUserInput(event) {
if (config.autoSlideStoppable) {
pauseAutoSlide();
}
}
/**
* Handler for the document level 'keypress' event.
*/
function onDocumentKeyPress(event) {
// Check if the pressed key is question mark
if (event.shiftKey && event.charCode === 63) {
if (dom.overlay) {
closeOverlay();
} else {
showHelp(true);
}
}
}
/**
* Handler for the document level 'keydown' event.
*/
function onDocumentKeyDown(event) {
// If there's a condition specified and it returns false,
// ignore this event
if (typeof config.keyboardCondition === 'function' && config.keyboardCondition() === false) {
return true;
}
// Remember if auto-sliding was paused so we can toggle it
var autoSlideWasPaused = autoSlidePaused;
onUserInput(event);
// Check if there's a focused element that could be using
// the keyboard
var activeElementIsCE = document.activeElement && document.activeElement.contentEditable !== 'inherit';
var activeElementIsInput = document.activeElement && document.activeElement.tagName && /input|textarea/i.test(document.activeElement.tagName);
// Disregard the event if there's a focused element or a
// keyboard modifier key is present
if (activeElementIsCE || activeElementIsInput || (event.shiftKey && event.keyCode !== 32) || event.altKey || event.ctrlKey || event.metaKey) return;
// While paused only allow resume keyboard events; 'b', '.''
var resumeKeyCodes = [66, 190, 191];
var key;
// Custom key bindings for togglePause should be able to resume
if (typeof config.keyboard === 'object') {
for (key in config.keyboard) {
if (config.keyboard[key] === 'togglePause') {
resumeKeyCodes.push(parseInt(key, 10));
}
}
}
if (isPaused() && resumeKeyCodes.indexOf(event.keyCode) === -1) {
return false;
}
var triggered = false;
// 1. User defined key bindings
if (typeof config.keyboard === 'object') {
for (key in config.keyboard) {
// Check if this binding matches the pressed key
if (parseInt(key, 10) === event.keyCode) {
var value = config.keyboard[key];
// Callback function
if (typeof value === 'function') {
value.apply(null, [event]);
}
// String shortcuts to reveal.js API
else if (typeof value === 'string' && typeof Reveal[value] === 'function') {
Reveal[value].call();
}
triggered = true;
}
}
}
// 2. System defined key bindings
if (triggered === false) {
// Assume true and try to prove false
triggered = true;
switch (event.keyCode) {
// p, page up
case 80:
case 33:
navigatePrev();
break;
// n, page down
case 78:
case 34:
navigateNext();
break;
// h, left
case 72:
case 37:
navigateLeft();
break;
// l, right
case 76:
case 39:
navigateRight();
break;
// k, up
case 75:
case 38:
navigateUp();
break;
// j, down
case 74:
case 40:
navigateDown();
break;
// home
case 36:
slide(0);
break;
// end
case 35:
slide(Number.MAX_VALUE);
break;
// space
case 32:
isOverview() ? deactivateOverview() : event.shiftKey ? navigatePrev() : navigateNext();
break;
// return
case 13:
isOverview() ? deactivateOverview() : triggered = false;
break;
// two-spot, semicolon, b, period, Logitech presenter tools "black screen" button
case 58:
case 59:
case 66:
case 190:
case 191:
togglePause();
break;
// f
case 70:
enterFullscreen();
break;
// a
case 65:
if (config.autoSlideStoppable) toggleAutoSlide(autoSlideWasPaused);
break;
default:
triggered = false;
}
}
// If the input resulted in a triggered action we should prevent
// the browsers default behavior
if (triggered) {
event.preventDefault && event.preventDefault();
}
// ESC or O key
else if ((event.keyCode === 27 || event.keyCode === 79) && features.transforms3d) {
if (dom.overlay) {
closeOverlay();
} else {
toggleOverview();
}
event.preventDefault && event.preventDefault();
}
// If auto-sliding is enabled we need to cue up
// another timeout
cueAutoSlide();
}
/**
* Handler for the 'touchstart' event, enables support for
* swipe and pinch gestures.
*/
function onTouchStart(event) {
if (isSwipePrevented(event.target)) return true;
touch.startX = event.touches[0].clientX;
touch.startY = event.touches[0].clientY;
touch.startCount = event.touches.length;
// If there's two touches we need to memorize the distance
// between those two points to detect pinching
if (event.touches.length === 2 && config.overview) {
touch.startSpan = distanceBetween({
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
});
}
}
/**
* Handler for the 'touchmove' event.
*/
function onTouchMove(event) {
if (isSwipePrevented(event.target)) return true;
// Each touch should only trigger one action
if (!touch.captured) {
onUserInput(event);
var currentX = event.touches[0].clientX;
var currentY = event.touches[0].clientY;
// If the touch started with two points and still has
// two active touches; test for the pinch gesture
if (event.touches.length === 2 && touch.startCount === 2 && config.overview) {
// The current distance in pixels between the two touch points
var currentSpan = distanceBetween({
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
});
// If the span is larger than the desire amount we've got
// ourselves a pinch
if (Math.abs(touch.startSpan - currentSpan) > touch.threshold) {
touch.captured = true;
if (currentSpan < touch.startSpan) {
activateOverview();
} else {
deactivateOverview();
}
}
event.preventDefault();
}
// There was only one touch point, look for a swipe
else if (event.touches.length === 1 && touch.startCount !== 2) {
var deltaX = currentX - touch.startX,
deltaY = currentY - touch.startY;
if (deltaX > touch.threshold && Math.abs(deltaX) > Math.abs(deltaY)) {
touch.captured = true;
navigateLeft();
} else if (deltaX < -touch.threshold && Math.abs(deltaX) > Math.abs(deltaY)) {
touch.captured = true;
navigateRight();
} else if (deltaY > touch.threshold) {
touch.captured = true;
navigateUp();
} else if (deltaY < -touch.threshold) {
touch.captured = true;
navigateDown();
}
// If we're embedded, only block touch events if they have
// triggered an action
if (config.embedded) {
if (touch.captured || isVerticalSlide(currentSlide)) {
event.preventDefault();
}
}
// Not embedded? Block them all to avoid needless tossing
// around of the viewport in iOS
else {
event.preventDefault();
}
}
}
// There's a bug with swiping on some Android devices unless
// the default action is always prevented
else if (navigator.userAgent.match(/android/gi)) {
event.preventDefault();
}
}
/**
* Handler for the 'touchend' event.
*/
function onTouchEnd(event) {
touch.captured = false;
}
/**
* Convert pointer down to touch start.
*/
function onPointerDown(event) {
if (event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch") {
event.touches = [{
clientX: event.clientX,
clientY: event.clientY
}];
onTouchStart(event);
}
}
/**
* Convert pointer move to touch move.
*/
function onPointerMove(event) {
if (event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch") {
event.touches = [{
clientX: event.clientX,
clientY: event.clientY
}];
onTouchMove(event);
}
}
/**
* Convert pointer up to touch end.
*/
function onPointerUp(event) {
if (event.pointerType === event.MSPOINTER_TYPE_TOUCH || event.pointerType === "touch") {
event.touches = [{
clientX: event.clientX,
clientY: event.clientY
}];
onTouchEnd(event);
}
}
/**
* Handles mouse wheel scrolling, throttled to avoid skipping
* multiple slides.
*/
function onDocumentMouseScroll(event) {
if (Date.now() - lastMouseWheelStep > 600) {
lastMouseWheelStep = Date.now();
var delta = event.detail || -event.wheelDelta;
if (delta > 0) {
navigateNext();
} else {
navigatePrev();
}
}
}
/**
* Clicking on the progress bar results in a navigation to the
* closest approximate horizontal slide using this equation:
*
* ( clickX / presentationWidth ) * numberOfSlides
*/
function onProgressClicked(event) {
onUserInput(event);
event.preventDefault();
var slidesTotal = toArray(dom.wrapper.querySelectorAll(HORIZONTAL_SLIDES_SELECTOR)).length;
var slideIndex = Math.floor((event.clientX / dom.wrapper.offsetWidth) * slidesTotal);
if (config.rtl) {
slideIndex = slidesTotal - slideIndex;
}
slide(slideIndex);
}
/**
* Event handler for navigation control buttons.
*/
function onNavigateLeftClicked(event) {
event.preventDefault();
onUserInput();
navigateLeft();
}
function onNavigateRightClicked(event) {
event.preventDefault();
onUserInput();
navigateRight();
}
function onNavigateUpClicked(event) {
event.preventDefault();
onUserInput();
navigateUp();
}
function onNavigateDownClicked(event) {
event.preventDefault();
onUserInput();
navigateDown();
}
function onNavigatePrevClicked(event) {
event.preventDefault();
onUserInput();
navigatePrev();
}
function onNavigateNextClicked(event) {
event.preventDefault();
onUserInput();
navigateNext();
}
/**
* Handler for the window level 'hashchange' event.
*/
function onWindowHashChange(event) {
readURL();
}
/**
* Handler for the window level 'resize' event.
*/
function onWindowResize(event) {
layout();
}
/**
* Handle for the window level 'visibilitychange' event.
*/
function onPageVisibilityChange(event) {
var isHidden = document.webkitHidden ||
document.msHidden ||
document.hidden;
// If, after clicking a link or similar and we're coming back,
// focus the document.body to ensure we can use keyboard shortcuts
if (isHidden === false && document.activeElement !== document.body) {
// Not all elements support .blur() - SVGs among them.
if (typeof document.activeElement.blur === 'function') {
document.activeElement.blur();
}
document.body.focus();
}
}
/**
* Invoked when a slide is and we're in the overview.
*/
function onOverviewSlideClicked(event) {
// TODO There's a bug here where the event listeners are not
// removed after deactivating the overview.
if (eventsAreBound && isOverview()) {
event.preventDefault();
var element = event.target;
while (element && !element.nodeName.match(/section/gi)) {
element = element.parentNode;
}
if (element && !element.classList.contains('disabled')) {
deactivateOverview();
if (element.nodeName.match(/section/gi)) {
var h = parseInt(element.getAttribute('data-index-h'), 10),
v = parseInt(element.getAttribute('data-index-v'), 10);
slide(h, v);
}
}
}
}
/**
* Handles clicks on links that are set to preview in the
* iframe overlay.
*/
function onPreviewLinkClicked(event) {
if (event.currentTarget && event.currentTarget.hasAttribute('href')) {
var url = event.currentTarget.getAttribute('href');
if (url) {
showPreview(url);
event.preventDefault();
}
}
}
/**
* Handles click on the auto-sliding controls element.
*/
function onAutoSlidePlayerClick(event) {
// Replay
if (Reveal.isLastSlide() && config.loop === false) {
slide(0, 0);
resumeAutoSlide();
}
// Resume
else if (autoSlidePaused) {
resumeAutoSlide();
}
// Pause
else {
pauseAutoSlide();
}
}
// --------------------------------------------------------------------//
// ------------------------ PLAYBACK COMPONENT ------------------------//
// --------------------------------------------------------------------//
/**
* Constructor for the playback component, which displays
* play/pause/progress controls.
*
* @param {HTMLElement} container The component will append
* itself to this
* @param {Function} progressCheck A method which will be
* called frequently to get the current progress on a range
* of 0-1
*/
function Playback(container, progressCheck) {
// Cosmetics
this.diameter = 50;
this.thickness = 3;
// Flags if we are currently playing
this.playing = false;
// Current progress on a 0-1 range
this.progress = 0;
// Used to loop the animation smoothly
this.progressOffset = 1;
this.container = container;
this.progressCheck = progressCheck;
this.canvas = document.createElement('canvas');
this.canvas.className = 'playback';
this.canvas.width = this.diameter;
this.canvas.height = this.diameter;
this.context = this.canvas.getContext('2d');
this.container.appendChild(this.canvas);
this.render();
}
Playback.prototype.setPlaying = function (value) {
var wasPlaying = this.playing;
this.playing = value;
// Start repainting if we weren't already
if (!wasPlaying && this.playing) {
this.animate();
} else {
this.render();
}
};
Playback.prototype.animate = function () {
var progressBefore = this.progress;
this.progress = this.progressCheck();
// When we loop, offset the progress so that it eases
// smoothly rather than immediately resetting
if (progressBefore > 0.8 && this.progress < 0.2) {
this.progressOffset = this.progress;
}
this.render();
if (this.playing) {
features.requestAnimationFrameMethod.call(window, this.animate.bind(this));
}
};
/**
* Renders the current progress and playback state.
*/
Playback.prototype.render = function () {
var progress = this.playing ? this.progress : 0,
radius = (this.diameter / 2) - this.thickness,
x = this.diameter / 2,
y = this.diameter / 2,
iconSize = 14;
// Ease towards 1
this.progressOffset += (1 - this.progressOffset) * 0.1;
var endAngle = (-Math.PI / 2) + (progress * (Math.PI * 2));
var startAngle = (-Math.PI / 2) + (this.progressOffset * (Math.PI * 2));
this.context.save();
this.context.clearRect(0, 0, this.diameter, this.diameter);
// Solid background color
this.context.beginPath();
this.context.arc(x, y, radius + 2, 0, Math.PI * 2, false);
this.context.fillStyle = 'rgba( 0, 0, 0, 0.4 )';
this.context.fill();
// Draw progress track
this.context.beginPath();
this.context.arc(x, y, radius, 0, Math.PI * 2, false);
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#666';
this.context.stroke();
if (this.playing) {
// Draw progress on top of track
this.context.beginPath();
this.context.arc(x, y, radius, startAngle, endAngle, false);
this.context.lineWidth = this.thickness;
this.context.strokeStyle = '#fff';
this.context.stroke();
}
this.context.translate(x - (iconSize / 2), y - (iconSize / 2));
// Draw play/pause icons
if (this.playing) {
this.context.fillStyle = '#fff';
this.context.fillRect(0, 0, iconSize / 2 - 2, iconSize);
this.context.fillRect(iconSize / 2 + 2, 0, iconSize / 2 - 2, iconSize);
} else {
this.context.beginPath();
this.context.translate(2, 0);
this.context.moveTo(0, 0);
this.context.lineTo(iconSize - 2, iconSize / 2);
this.context.lineTo(0, iconSize);
this.context.fillStyle = '#fff';
this.context.fill();
}
this.context.restore();
};
Playback.prototype.on = function (type, listener) {
this.canvas.addEventListener(type, listener, false);
};
Playback.prototype.off = function (type, listener) {
this.canvas.removeEventListener(type, listener, false);
};
Playback.prototype.destroy = function () {
this.playing = false;
if (this.canvas.parentNode) {
this.container.removeChild(this.canvas);
}
};
// --------------------------------------------------------------------//
// ------------------------------- API --------------------------------//
// --------------------------------------------------------------------//
Reveal = {
initialize: initialize,
configure: configure,
sync: sync,
// Navigation methods
slide: slide,
left: navigateLeft,
right: navigateRight,
up: navigateUp,
down: navigateDown,
prev: navigatePrev,
next: navigateNext,
// Fragment methods
navigateFragment: navigateFragment,
prevFragment: previousFragment,
nextFragment: nextFragment,
// Deprecated aliases
navigateTo: slide,
navigateLeft: navigateLeft,
navigateRight: navigateRight,
navigateUp: navigateUp,
navigateDown: navigateDown,
navigatePrev: navigatePrev,
navigateNext: navigateNext,
// Forces an update in slide layout
layout: layout,
// Returns an object with the available routes as booleans (left/right/top/bottom)
availableRoutes: availableRoutes,
// Returns an object with the available fragments as booleans (prev/next)
availableFragments: availableFragments,
// Toggles the overview mode on/off
toggleOverview: toggleOverview,
// Toggles the "black screen" mode on/off
togglePause: togglePause,
// Toggles the auto slide mode on/off
toggleAutoSlide: toggleAutoSlide,
// State checks
isOverview: isOverview,
isPaused: isPaused,
isAutoSliding: isAutoSliding,
// Adds or removes all internal event listeners (such as keyboard)
addEventListeners: addEventListeners,
removeEventListeners: removeEventListeners,
// Facility for persisting and restoring the presentation state
getState: getState,
setState: setState,
// Presentation progress on range of 0-1
getProgress: getProgress,
// Returns the indices of the current, or specified, slide
getIndices: getIndices,
getTotalSlides: getTotalSlides,
// Returns the slide element at the specified index
getSlide: getSlide,
// Returns the slide background element at the specified index
getSlideBackground: getSlideBackground,
// Returns the speaker notes string for a slide, or null
getSlideNotes: getSlideNotes,
// Returns the previous slide element, may be null
getPreviousSlide: function () {
return previousSlide;
},
// Returns the current slide element
getCurrentSlide: function () {
return currentSlide;
},
// Returns the current scale of the presentation content
getScale: function () {
return scale;
},
// Returns the current configuration object
getConfig: function () {
return config;
},
// Helper method, retrieves query string as a key/value hash
getQueryHash: function () {
var query = {};
location.search.replace(/[A-Z0-9]+?=([\w\.%-]*)/gi, function (a) {
query[a.split('=').shift()] = a.split('=').pop();
});
// Basic deserialization
for (var i in query) {
var value = query[i];
query[i] = deserialize(unescape(value));
}
return query;
},
// Returns true if we're currently on the first slide
isFirstSlide: function () {
return (indexh === 0 && indexv === 0);
},
// Returns true if we're currently on the last slide
isLastSlide: function () {
if (currentSlide) {
// Does this slide has next a sibling?
if (currentSlide.nextElementSibling) return false;
// If it's vertical, does its parent have a next sibling?
if (isVerticalSlide(currentSlide) && currentSlide.parentNode.nextElementSibling) return false;
return true;
}
return false;
},
// Checks if reveal.js has been loaded and is ready for use
isReady: function () {
return loaded;
},
// Forward event binding to the reveal DOM element
addEventListener: function (type, listener, useCapture) {
if ('addEventListener' in window) {
(dom.wrapper || document.querySelector('.reveal')).addEventListener(type, listener, useCapture);
}
},
removeEventListener: function (type, listener, useCapture) {
if ('addEventListener' in window) {
(dom.wrapper || document.querySelector('.reveal')).removeEventListener(type, listener, useCapture);
}
},
// Programatically triggers a keyboard event
triggerKey: function (keyCode) {
onDocumentKeyDown({
keyCode: keyCode
});
}
};
return Reveal;
})); |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m13 10.17-2.5-2.5V1H13v9.17zM20 4h-2.5v7h-1V2H14v9.17l6 6V4zM9.5 3H7.01v1.18L9.5 6.67V3zm11.69 18.19L2.81 2.81 1.39 4.22 7 9.83v4.3l-3.32-1.9L2 13.88 9.68 22h9.54l.56.61 1.41-1.42z"
}), 'DoNotTouchSharp');
exports.default = _default; |
var path = require('path');
var rimraf = require('rimraf');
var fs = require('fs');
var async = require('async');
var exec = require('child_process').exec;
var TIMEOUT = 60000;
function expectFilesToExist(files, run) {
async.each(files, function(file, callback) {
fs.existsSync(path.join(process.cwd(), file)) ? callback() : callback("cannot find " + file);
}, function(err) {
expect(err).toBeNull();
run();
});
}
(function cleanDirs() {
async.each([
'test/basic/build',
'test/basic/bower_components',
'test/bootstrap/build',
'test/bootstrap/bower_components',
'test/full/build',
'test/full/bower_components',
'test/glob/build',
'test/glob/bower_components',
'test/ignore/build',
'test/ignore/bower_components',
'test/mapping/build',
'test/mapping/bower_components',
'test/multiDirGlob/build',
'test/multiDirGlob/bower_components',
'test/multiFolder/build',
'test/multiFolder/bower_components',
'test/multiMain/build',
'test/multiMain/bower_components',
'test/multiPath/build',
'test/multiPath/bower_components',
], function(file, callback) {
rimraf(path.join(process.cwd(), file), function() {
callback();
});
})
})();
describe("Bower Installer", function() {
it('Should pass basic', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/basic')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/basic/build/src/jquery/jquery.js',
'test/basic/build/src/jquery-ui/jquery-ui.js'
], run);
});
}, TIMEOUT);
it('Should remove bower_components directory', function(run) {
exec('node ../../bower-installer.js -r', {cwd: path.join(process.cwd(), 'test/basic')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/basic/build/src/jquery/jquery.js',
'test/basic/build/src/jquery-ui/jquery-ui.js'
], run);
expect(fs.existsSync(path.join(process.cwd(), 'bower_components'))).toBeFalsy();
});
}, TIMEOUT);
it('Should pass bootstrap', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/bootstrap')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/bootstrap/build/src/bootstrap/bootstrap.js',
'test/bootstrap/build/src/bootstrap/glyphicons-halflings-regular.eot',
'test/bootstrap/build/src/bootstrap/glyphicons-halflings-regular.woff',
'test/bootstrap/build/src/bootstrap/glyphicons-halflings-regular.ttf',
'test/bootstrap/build/src/bootstrap/glyphicons-halflings-regular.svg',
'test/bootstrap/build/src/bootstrap/bootstrap.css',
'test/bootstrap/build/src/jquery/jquery.js'
], run);
});
}, TIMEOUT);
it('Should pass full', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/full')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/full/build/src/backbone-nested/backbone-nested.js',
'test/full/build/src/backbone/backbone.js',
'test/full/build/src/buster-jquery-assertions/buster-jquery-assertions.js',
'test/full/build/src/buster.js/buster-test.css',
'test/full/build/src/datejs/date.js',
'test/full/build/src/jquery-mousewheel/jquery.mousewheel.js',
'test/full/build/src/jquery.jscrollpane/jquery.jscrollpane.js',
'test/full/build/src/jquery.jscrollpane/jquery.jscrollpane.css',
'test/full/build/src/jquery.transit/jquery.transit.js',
'test/full/build/src/json2/json2.js',
'test/full/build/src/requirejs-text/text.js',
'test/full/build/src/underscore.string/underscore.string.min.js',
'test/full/build/src/underscore/underscore.js',
'test/full/build/src/requirejs/require.js',
'test/full/build/src/buster.js/buster-test.js',
'test/full/build/src/jquery/jquery.js',
'test/full/build/src/d3/d3.js',
'test/full/build/src/jquery-ui/jquery-ui.js',
'test/full/build/src/speak.js/speakGenerator.js',
], run);
});
}, TIMEOUT);
it('Should pass glob', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/glob')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/glob/build/src/datejs/date-af-ZA.js',
'test/glob/build/src/datejs/date-ar-AE.js',
'test/glob/build/src/datejs/date-ar-BH.js',
'test/glob/build/src/datejs/date-ar-DZ.js',
'test/glob/build/src/datejs/date-ar-EG.js',
'test/glob/build/src/datejs/date-ar-IQ.js',
'test/glob/build/src/datejs/date-ar-JO.js',
'test/glob/build/src/datejs/date-ar-KW.js',
'test/glob/build/src/datejs/date-ar-LB.js',
'test/glob/build/src/datejs/date-uz-Cyrl-UZ.js',
'test/glob/build/src/datejs/date-uz-Latn-UZ.js',
'test/glob/build/src/datejs/date-vi-VN.js',
'test/glob/build/src/datejs/date-xh-ZA.js',
'test/glob/build/src/datejs/date-zh-CN.js',
'test/glob/build/src/datejs/date-zh-HK.js',
'test/glob/build/src/datejs/date-zh-MO.js',
'test/glob/build/src/datejs/date-zh-SG.js',
'test/glob/build/src/datejs/date-zh-TW.js',
'test/glob/build/src/datejs/date-zu-ZA.js',
'test/glob/build/src/datejs/date.js'
], run);
});
}, TIMEOUT);
it('Should pass ignore', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/ignore')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/ignore/build/src/ember-model/ember-model.js',
'test/ignore/build/src/jquery/jquery.js'
], run);
});
}, TIMEOUT);
it('Should pass mapping', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/mapping')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/mapping/build/src/ember-bootstrap/ember-bootstrap.js',
'test/mapping/build/src/ember-easyForm/subdirectory/ember-easyForm.js',
'test/mapping/build/src/jquery/jquery.js',
'test/mapping/build/src/jquery-ui/jquery-ui.js'
], run);
});
}, TIMEOUT);
it('Should pass multiDirGlob', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/multiDirGlob')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
"test/multiDirGlob/build/src/bootstrap/css/bootstrap-theme.css",
"test/multiDirGlob/build/src/bootstrap/css/bootstrap-theme.css.map",
"test/multiDirGlob/build/src/bootstrap/css/bootstrap-theme.min.css",
"test/multiDirGlob/build/src/bootstrap/fonts/glyphicons-halflings-regular.eot",
"test/multiDirGlob/build/src/bootstrap/fonts/glyphicons-halflings-regular.svg",
"test/multiDirGlob/build/src/bootstrap/fonts/glyphicons-halflings-regular.ttf",
"test/multiDirGlob/build/src/bootstrap/fonts/glyphicons-halflings-regular.woff",
"test/multiDirGlob/build/src/bootstrap/js/bootstrap.min.js",
"test/multiDirGlob/build/src/bootstrap/js/bootstrap.js",
"test/multiDirGlob/build/src/bootstrap/css/bootstrap.css",
"test/multiDirGlob/build/src/bootstrap/css/bootstrap.min.css",
"test/multiDirGlob/build/src/jquery/jquery.js",
"test/multiDirGlob/build/src/bootstrap/css/bootstrap.css.map"
], run);
});
}, TIMEOUT);
it('Should install multiFolder', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/multiFolder')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/multiFolder/build/src-prod/index.js',
'test/multiFolder/build/src-test/index.js'
], run);
});
}, TIMEOUT);
it('Should pass multiMain', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/multiMain')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/multiMain/build/src/datejs/date.js'
], run);
});
}, TIMEOUT);
it('Should pass multiPath', function(run) {
exec('node ../../bower-installer.js', {cwd: path.join(process.cwd(), 'test/multiPath')}, function(err, stdout, stderr) {
expect(err).toBeNull();
expectFilesToExist([
'test/multiPath/build/src/buster-jquery-assertions/buster-jquery-assertions.js',
'test/multiPath/build/css/buster.js/buster-test.css',
'test/multiPath/build/src/buster.js/buster-test.js'
], run);
});
}, TIMEOUT);
});
|
/*jshint undef:false, strict:false*/ // Note: to avoid having to write QUnit.module, etc
module('promptForm', {
setup: function () {
this.sinon = sinon.sandbox.create();
$('<div id="form"><input id="name" /></div>').appendTo('#qunit-fixture');
},
teardown: function () {
this.sinon.restore();
detectLeaks();
}
});
test('construction', function () {
// given
this.sinon.stub(window, 'AutoComplete', function () {
this.focus = sinon.spy();
});
// when
var form = new window.PromptForm('#form', {
listUrl: '/someUrl'
});
// then
ok(form, 'created');
equal(window.AutoComplete.callCount, 1, 'AutoComplete called...');
var call = window.AutoComplete.firstCall;
var args = call.args;
var autoComplete = call.thisValue;
ok(args[0].is('#name'), '... on the right element');
deepEqual(args[1], {listUrl: '/someUrl'}, '... with the right options');
ok(autoComplete.focus.called, 'focus changed');
});
|
var t = {
tem: 20,
temUp: function() {
this.tem++;
},
temDown: function() {
this.tem--;
}
};
$(function() {
$('#increase').on('click', function() {
t.temUp();
update();
});
$('#decrease').on('click', function() {
t.temDown();
update();
});
});
function update() {
var elTem = document.getElementById('temperature');
elTem.textContent = t.tem;
}; |
var conf = require('../conf.js'),
log = require('../log.js');
var engine = require('engine'),
resMan = require('../resource_manager.js');
var errors = require('../errors.js');
var Bounds = require('./bounds.js');
Sheet.instances = 0;
Sheet.MISSED_SIDE = 50;
/* TODO: rename to Static and take optional function as source? */
/**
* @class anm.Sheet
*
* Sheet class represent both single image and sprite-sheet. It stores
* active region, and if its bounds are equal to image size (and they are,
* by default), then the source is treated as a single image. This active region
* may be changed dynamically during the animation, and this gives the effect of
* a spite-sheet.
*
* See {@link anm.Element#image Element.image()}
*
* @constructor
*
* @param {String} src image/spritesheet URL
* @param {Function} [f] callback to perform when image will be received
* @param {anm.Sheet} f.this sheet instance
* @param {Image} f.img corresponding DOM Image element
* @param {Number} [start_region] an id for initial region
*/
function Sheet(src, callback, start_region) {
this.id = Sheet.instances++;
this.src = src;
this._dimen = /*dimen ||*/ [0, 0];
this.regions = [ [ 0, 0, 1, 1 ] ]; // for image, sheet contains just one image
this.regions_f = null;
// this.aliases = {}; // map of names to regions (or regions ranges)
/* use state property for region num? or conform with state jumps/positions */
/* TODO: rename region to frame */
this.cur_region = start_region || 0; // current region may be changed with modifier
this.ready = false;
this.wasError = false;
this._image = null;
this._callback = callback;
this._thumbnail = false; // internal flag, used to load a player thumbnail
}
var https = engine.isHttps;
/**
* @private @method load
*/
Sheet.prototype.load = function(uid, player, callback, errback) {
callback = callback || this._callback;
if (this._image) throw errors.element('Image already loaded', uid); // just skip loading?
var me = this;
if (!me.src) {
log.error('Empty source URL for image');
me.ready = true; me.wasError = true;
if (errback) errback.call(me, 'Empty source');
return;
}
resMan.loadOrGet(uid, me.src,
function(notify_success, notify_error, notify_progress) { // loader
var src = engine.checkMediaUrl(me.src);
if (!me._thumbnail && conf.doNotLoadImages) {
notify_error('Loading images is turned off');
return; }
var img = new Image();
var props = engine.getAnmProps(img);
img.onload = img.onreadystatechange = function() {
if (props.ready) return;
if (this.readyState && (this.readyState !== 'complete')) {
notify_error(this.readyState);
}
props.ready = true; // this flag is to check later if request succeeded
// this flag is browser internal
img.isReady = true; /* FIXME: use 'image.complete' and
'...' (network exist) combination,
'complete' fails on Firefox */
notify_success(img);
};
img.onerror = notify_error;
img.addEventListener('error', notify_error, false);
try { img.src = src; }
catch(e) { notify_error(e); }
},
function(image) { // oncomplete
me._image = image;
me._dimen = [ image.width, image.height ];
me.ready = true; // this flag is for users of the Sheet class
if (callback) callback.call(me, image);
},
function(err) { log.error(err.srcElement || err.path, err.message || err);
me.ready = true;
me.wasError = true;
var doThrow = true;
if (errback) { doThrow = !errback.call(me, err); };
if (doThrow) { throw errors.element(err ? err.message : 'Unknown', elm); } });
};
/**
* @private @method updateRegion
*/
Sheet.prototype.updateRegion = function() {
if (this.cur_region < 0) return;
var region;
if (this.region_f) { region = this.region_f(this.cur_region); }
else {
var r = this.regions[this.cur_region],
d = this._dimen;
region = [ r[0] * d[0], r[1] * d[1],
r[2] * d[0], r[3] * d[1] ];
}
this.region = region;
};
/**
* @private @method apply
*/
Sheet.prototype.apply = function(ctx/*, fill, stroke, shadow*/) {
if (!this.ready) return;
if (this.wasError) { this.applyMissed(ctx); return; }
this.updateRegion();
var region = this.region;
ctx.drawImage(this._image, region[0], region[1],
region[2], region[3], 0, 0, region[2], region[3]);
};
/**
* @private @method applyMissed
*
* If there was an error in process of receiving an image, the "missing" image is
* displayed, this method draws it in context.
*/
Sheet.prototype.applyMissed = function(ctx) {
ctx.save();
ctx.strokeStyle = '#900';
ctx.lineWidth = 1;
ctx.beginPath();
var side = Sheet.MISSED_SIDE;
ctx.moveTo(0, 0);
ctx.lineTo(side, 0);
ctx.lineTo(0, side);
ctx.lineTo(side, side);
ctx.lineTo(0, 0);
ctx.lineTo(0, side);
ctx.lineTo(side, 0);
ctx.lineTo(side, side);
ctx.stroke();
ctx.restore();
};
Sheet.MISSED_BOUNDS = new Bounds(0, 0, Sheet.MISSED_SIDE, Sheet.MISSED_SIDE);
/**
* @method bounds
*
* Get image bounds
*
* @return anm.Bounds bounds
*/
Sheet.prototype.bounds = function() {
if (this.wasError) return Sheet.MISSED_BOUNDS;
// TODO: when using current_region, bounds will depend on that region
if (!this.ready) return Bounds.NONE;
if(!this.region) {
this.updateRegion();
}
var r = this.region;
return new Bounds(0, 0, r[2], r[3]);
};
/**
* @method inside
*
* Checks if point is inside the image. _Does no test for bounds_, the point is
* assumed to be already inside of the bounds, so check `image.bounds().inside(pt)`
* before calling this method manually.
*
* @param {Object} pt point to check
* @param {Number} pt.x
* @param {Number} pt.y
* @return {Boolean} is point inside
*/
Sheet.prototype.inside = function(pt) {
return true; // if point is inside of the bounds, point is considered to be
// inside the image shape
};
/**
* @method clone
*
* Clone this image
*
* @return anm.Sheet clone
*/
Sheet.prototype.clone = function() {
// FIXME: fix for sprite-sheet
return new Sheet(this.src);
};
Sheet.prototype.invalidate = function() {
};
Sheet.prototype.reset = function() { };
Sheet.prototype.dispose = function() {
};
// TODO: Bring back Sprite-animator
// https://github.com/Animatron/player/blob/3903d59c7653ec6a0dcc578d6193e6bdece4a3a0/src/builder.js#L213
// https://github.com/Animatron/player/blob/3903d59c7653ec6a0dcc578d6193e6bdece4a3a0/src/builder.js#L926
module.exports = Sheet;
|
/**
* Imports
*/
import test from 'tape'
import CreatePlaylist from '.'
/**
* <Create Playlist/> tests
*/
test('<CreatePlaylist/> should work', t => {
})
|
var net = require('net'),
dgram = require('dgram');
dgram.createSocket("udp4").bind(5340, function () {
net.createServer().listen(5341);
});
|
const LOG_LEVEL = {
Debug: 'DEBUG',
Info: 'INFO',
Warning: 'WARNING',
Error: 'ERROR',
};
export default LOG_LEVEL;
|
exports.type = "BinaryExpression";
exports.call = function(node, ctx, execute) {
return ctx.operate(node.operator, node.left, node.right);
}; |
//>>built
define(["dojo/_base/kernel","dojo/_base/declare","./_base"],function(f,d,e){return d("dojox.geo.openlayers.Feature",null,{constructor:function(){this._layer=null;this._coordSys=e.EPSG4326},getCoordinateSystem:function(){return this._coordSys},setCoordinateSystem:function(a){this._coordSys=a},getLayer:function(){return this._layer},_setLayer:function(a){this._layer=a},render:function(){},remove:function(){},_getLocalXY:function(a){var d=a.x;a=a.y;var b=this.getLayer(),c=b.olLayer.map.getResolution(),
b=b.olLayer.getExtent();return[d/c+-b.left/c,b.top/c-a/c]}})}); |
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M22 5H2v14h20V5zM9 6c1.65 0 3 1.35 3 3s-1.35 3-3 3-3-1.35-3-3 1.35-3 3-3zm6 12H3v-1.41C3 14.08 6.97 13 9 13s6 1.08 6 3.58V18zm2.85-4h1.64L21 16l-1.99 1.99c-1.31-.98-2.28-2.38-2.73-3.99-.18-.64-.28-1.31-.28-2s.1-1.36.28-2c.45-1.62 1.42-3.01 2.73-3.99L21 8l-1.51 2h-1.64c-.22.63-.35 1.3-.35 2s.13 1.37.35 2z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M2 21h20c1.1 0 1.99-.9 1.99-2L24 5c0-1.1-.9-2-2-2H2C.9 3 0 3.9 0 5v14c0 1.1.9 2 2 2zM2 5h20v14H2V5zm17.49 5L21 8l-1.99-1.99c-1.31.98-2.28 2.37-2.73 3.99-.18.64-.28 1.31-.28 2s.1 1.36.28 2c.45 1.61 1.42 3.01 2.73 3.99L21 16l-1.51-2h-1.64c-.22-.63-.35-1.3-.35-2s.13-1.37.35-2h1.64zM9 12c1.65 0 3-1.35 3-3s-1.35-3-3-3-3 1.35-3 3 1.35 3 3 3zm0-4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 5c-2.03 0-6 1.08-6 3.58V18h12v-1.41C15 14.08 11.03 13 9 13zm-3.52 3c.74-.5 2.22-1 3.52-1s2.77.49 3.52 1H5.48z"
}, "1")], 'ContactPhoneTwoTone'); |
/*global define, Workspace*/
/*jslint white: true*/
/**
* Widget for viewing and modifying narrative share settings
* @author Michael Sneddon <mwsneddon@lbl.gov>, Bill Riehl <wjriehl@lbl.gov>
* @public
*/
define ([
'bluebird',
'kbwidget',
'bootstrap',
'jquery',
'narrativeConfig',
'kbaseAuthenticatedWidget',
'api/auth',
'util/string',
'select2'
], function (
Promise,
KBWidget,
bootstrap,
$,
Config,
kbaseAuthenticatedWidget,
Auth,
StringUtil
) {
'use strict';
return KBWidget({
name: 'kbaseNarrativeSharePanel',
parent : kbaseAuthenticatedWidget,
version: '1.0.0',
options: {
ws_url: Config.url('workspace'),
groups_url: Config.url('groups'),
loadingImage: Config.get('loading_gif'),
user_page_link: Config.url('profile_page'),
ws_name_or_id: null,
max_name_length: 35,
max_list_height: '250px',
add_user_input_width: '200px',
wsID: Config.get('workspaceId'),
},
ws: null, // workspace client
narrOwner: null,
$mainPanel: null,
$notificationPanel: null,
init: function (options) {
this._super(options);
this.$notificationPanel = $('<div>');
this.$elem.append(this.$notificationPanel);
this.$mainPanel = $('<div style="text-align:center">');
this.$elem.append(this.$mainPanel);
this.showWorking('loading narrative information');
if (!this.options.ws_name_or_id) {
//fail!
}
return this;
},
my_user_id: null,
orgList: null,
narrativeOrgList: null,
loggedInCallback: function (event, auth) {
this.ws = new Workspace(this.options.ws_url, auth);
this.authClient = Auth.make({url: Config.url('auth')});
this.my_user_id = auth.user_id;
const p1 = this.fetchOrgs(this.authClient.getAuthToken());
const p2 = this.fetchNarrativeOrgs(this.options.wsID, this.authClient.getAuthToken());
Promise.all([p1, p2]).then(() => {
this.refresh();
})
return this;
},
loggedOutCallback: function () {
this.ws = null;
this.authClient = null;
this.my_user_id = null;
this.orgList = null;
this.narrativeOrgList = null;
this.refresh();
return this;
},
/**
* fetch organizations that user is associated.
* @param {string} token authorization token
*/
fetchOrgs: function(token) {
var groupUrl = this.options.groups_url+'/member';
return fetch(groupUrl, {
method: "GET",
mode: "cors",
json: true,
headers:{
"Authorization": token,
"Content-Type": "application/json",
},
})
.then(response => response.json())
.then(response => {
this.orgList = response;
})
.catch(error => console.error('Error while fetching groups associated with the user:', error));
},
/**
* fetch organization info from id
* extract logo url and map it to org id with org name.
* @param {string} org org id
* @param {string} token auth token
* @param {Map} map empty map
*/
fetchOrgLogoUrl: function(org, token, map) {
map.set(org.id, [org.name])
var groupUrl = this.options.groups_url+"/group/"+org.id;
return fetch(groupUrl, {
method: "GET",
mode: "cors",
json: true,
headers:{
"Authorization": token,
"Content-Type": "application/json",
},
})
.then(response => response.json())
.then(response => {
let arr = map.get(org.id);
map.set(org.id, [arr, response.custom.logourl]);
this.narrativeOrgList = map;
})
.catch(error => console.error('Error while fetching group info:', error));
},
/**
* fetch organizations that workspace is associated.
* @param {int} wsID workspace id
* @param {string} token authorization token
*/
fetchNarrativeOrgs: function(wsID, token) {
var groupUrl = this.options.groups_url+'/group?resourcetype=workspace&resource='+wsID;
return fetch(groupUrl, {
method: "GET",
mode: "cors",
json: true,
headers:{
"Authorization": token,
"Content-Type": "application/json",
},
})
.then(response => response.json())
.then(response => {
let orgInfoMap = new Map();
return Promise.all(response.map((org) => this.fetchOrgLogoUrl(org, token, orgInfoMap)));
})
.catch(error => console.error('Error while fetching groups associated with the workspace:', error));
},
ws_info: null,
ws_permissions: null,
user_data: {},
all_users: null,
getInfoAndRender: function () {
var self = this;
if (!self.ws || !self.options.ws_name_or_id) {
return;
}
var wsIdentity = {};
if (self.options.ws_name_or_id) {
if (/^[1-9]\d*$/.test(self.options.ws_name_or_id)) {
wsIdentity.id = parseInt(self.options.ws_name_or_id);
} else {
wsIdentity.workspace = self.options.ws_name_or_id;
}
}
Promise.resolve(self.ws.get_workspace_info(wsIdentity))
.then(function (info) {
self.ws_info = info;
self.narrOwner = info[2];
return Promise.resolve(self.ws.get_permissions(wsIdentity));
})
.then(function (perm) {
self.ws_permissions = [];
self.user_data = {};
var usernameList = [ self.my_user_id ];
Object.keys(perm).forEach(function(u) {
if (u === '*') {
return;
}
self.ws_permissions.push([u, perm[u]]);
usernameList.push(u);
});
return self.authClient.getUserNames(self.authClient.getAuthToken(), usernameList);
})
.then(function (data) {
self.user_data = data;
})
.catch(function(error) {
console.error(error);
self.reportError(error);
})
.finally(function() {
self.render();
});
},
/*
WORKSPACE INFO
0: ws_id id
1: ws_name workspace
2: username owner
3: timestamp moddate,
4: int object
5: permission user_permission
6: permission globalread,
7: lock_status lockstat
8: usermeta metadata
*/
isPrivate: true, // set if this ws is private or public
render: function () {
var self = this;
if (!self.ws_info || !self.ws_permissions) {
return;
}
self.$mainPanel.empty();
var globalReadStatus = '<strong><span class="fa fa-lock" style="margin-right:10px"></span>Private</strong>';
var globalReadClass = 'alert alert-info';
self.isPrivate = true;
if (self.ws_info[6] === 'r') {
self.isPrivate = false;
globalReadClass = 'alert alert-success';
globalReadStatus = '<strong><span class="fa fa-unlock" style="margin-right:10px"></span>Public</strong>';
}
var $topDiv = $('<div>')
.addClass(globalReadClass)
.css({'text-align': 'center', 'padding': '10px', 'margin': '5px'})
.append(globalReadStatus);
self.$mainPanel.append($topDiv);
var $togglePublicPrivate = self.makePublicPrivateToggle($togglePublicPrivate).hide();
self.$mainPanel.append($togglePublicPrivate);
// meDiv
var $meDiv = $('<div>').css({'margin': '5px', 'margin-top': '20px'});
var status = 'You do not have access to this Narrative.';
var isAdmin = false;
var isOwner = false;
if (self.narrOwner === self.my_user_id) {
status = 'You can edit and share it with other users or request to add to an organization.';
isAdmin = true;
isOwner = true;
$togglePublicPrivate.show();
} else if (self.ws_info[5] === 'a') {
status = 'You can edit and share this Narrative, but you cannot request to add to and organization.';
isAdmin = true; // not really, but set this so we show sharing controls
$togglePublicPrivate.show();
} else if (self.ws_info[5] === 'w') {
status = 'You can edit this Narrative, but you cannot share it.';
} else if (self.ws_info[5] === 'r' || self.ws_info[6] === 'r') { // either you can read it, or it is globally readable
status = 'You can view this Narrative, but you cannot edit or share it.';
}
$meDiv.append($('<div>').css({'margin-top': '10px'}).append(status));
self.$mainPanel.append($meDiv);
/**
* Tabs to select share with users or org
* - $tab1 for sharing user
* - $tab2 for sharing with org
*/
var $tabDiv = $('<div class="tabs">').css({'margin': '0px 5px'});
// make divs for each tab.
var $tab1 = createTab('white', 'Users')
.css({'border-top-left-radius': '2px'});
$tab1.click(function(){
tabSwitch($(this), $tab2);
$shareWithOrgDiv.css('display', 'none');
$shareWithUserDiv.css('display', 'inherit');
});
$tabDiv.append($tab1);
var $tab2 = createTab('#d8d8d8', 'Orgs')
.css({'padding-bottom': '9px', 'border-bottom': '1px solid', 'border-top-right-radius': '2px'});
$tab2.click(function(){
tabSwitch($(this), $tab1);
$shareWithOrgDiv.css('display', 'inherit');
$shareWithUserDiv.css('display', 'none');
});
$tabDiv.append($tab2);
function createTab(color, text){
return $('<div class="shareTab">')
.css({'background-color': color, 'width': '50%', 'display': 'inline-block', 'padding': '10px', 'border': 'solid', 'border-width': '1px 1px 0px', 'cursor': 'pointer'})
.append(text);
}
function tabSwitch(tab, otherTab){
tab.css({'background-color': 'white', 'border-bottom': 'none', 'padding-bottom': '10px'});
otherTab.css({'background-color': '#d8d8d8', 'border-bottom': '1px solid', 'padding-bottom': '9px'});
}
self.$mainPanel.append($tabDiv);
// end of share tabs
/**
* Tab content div /$tabContent
* - share with user div /$shareWithUserDiv
* - share with org div /$shareWithOrgDiv
*/
var $tabContent = $('<div class="tab-content">')
.css({'border': 'solid', 'border-width': '0px 1px 1px 1px', 'border-radius': '0px 0px 2px 2px', 'padding': '15px', 'margin': '0px 5px'});
var $shareWithUserDiv = $('<div id="shareWUser" class="content">').css({'display': 'inherit'});
var $shareWithOrgDiv = $('<div id="shareWOrg" class="content">').css({'display': 'none'});
// Content of Share with Org (Request to add to Org) Div
if(isOwner) {
var $addOrgDiv = $('<div>').css({'margin-top': '10px'});
var $inputOrg = $('<select single data-placeholder="Associate with..." id="orgInput">')
.addClass('form-control kb-share-select')
.css("display", "inline");
$inputOrg.append('<option></option>'); // option is needed for placeholder to work.
var $applyOrgBtn = $('<button>')
.addClass('btn btn-primary disabled')
.append('Apply')
.css("margin-left", "10px")
.click(function() {
if (!$(this).hasClass('disabled')) {
var org = $inputOrg.select2('data');
var orgID = org[0]["id"];
self.requestAddNarrative(self.authClient.getAuthToken(), orgID);
}
});
self.orgSetupSelect2($inputOrg);
$addOrgDiv
.append($inputOrg)
.append($applyOrgBtn);
$inputOrg.on('select2:select', function() {
if ($inputOrg.select2('data').length > 0) {
$applyOrgBtn.removeClass('disabled');
}
});
$inputOrg.on('select2:unselect', function() {
if ($inputOrg.select2('data').length === 0) {
$applyOrgBtn.addClass('disabled');
}
});
$addOrgDiv.find('span.select2-selection--single')
.css({'min-height': '32px'});
// if there are orgs already associated with the narrative, add the org list.
if(this.narrativeOrgList){
var $narrativeOrgsDiv = $('<table>').css({'border': '1px solid rgb(170, 170, 170)', 'border-radius': '4px', 'text-align': 'left', 'width': '51%', 'padding': '10px', 'margin': 'auto', 'margin-top': '10px'});
this.narrativeOrgList.forEach((value, key, map) => {
let url = window.location.origin + "/#org/" + key;
let $href = $('<a>').attr("href", url);
let $logo = $('<img>').attr("src", value[1]).css({'width': '40', 'margin': '8px'});
$href.append($logo).append(value[0]);
let $tr = $('<tr>').css({'padding': '2px'}).append($href);
$narrativeOrgsDiv.append($tr);
})
}
$shareWithOrgDiv.append($addOrgDiv); // put addOrgDiv into shareWithOrgDiv
$shareWithOrgDiv.append($narrativeOrgsDiv); // put list of narrative div
} else {
$shareWithOrgDiv.append('<p style="margin-top: 18px;">You must be the owner to request to add this narrative.</p>');
} // end of if(isOwner)
// content of share with user div
if (isAdmin) {
var $addUsersDiv = $('<div>').css({'margin-top': '10px'});
var $input = $('<select multiple data-placeholder="Share with...">')
.addClass('form-control kb-share-select');
var $permSelect =
$('<select>')
.css({'width': '25%', 'display': 'inline-block'})
// TODO: pull-right is deprecated, use dropdown-menu-right when bootstrap updates
.append($('<option value="r">').append('View only'))
.append($('<option value="w">').append('Edit and save'))
.append($('<option value="a">').append('Edit, save, and share'));
var $applyBtn = $('<button>')
.addClass('btn btn-primary disabled')
.append('Apply')
.click(function() {
if (!$(this).hasClass('disabled')) {
var users = $input.select2('data');
var perm = $permSelect.val();
self.updateUserPermissions(users, perm);
}
});
$addUsersDiv.append($input)
.append($permSelect)
.append($applyBtn);
self.setupSelect2($input);
$permSelect.select2({
minimumResultsForSearch: Infinity
});
$input.on('select2:select', function() {
if ($input.select2('data').length > 0) {
$applyBtn.removeClass('disabled');
}
});
$input.on('select2:unselect', function() {
if ($input.select2('data').length === 0) {
$applyBtn.addClass('disabled');
}
});
// Silly Select2 has different height rules for multiple and single select.
$addUsersDiv.find('span.select2-selection--single')
.css({'min-height': '32px'});
$addUsersDiv.find('.select2-container')
.css({'margin-left': '5px', 'margin-right': '5px'});
$shareWithUserDiv.append($addUsersDiv);
} // end of if(isAdmin)
// add share with.., divs to tab content
$tabContent.append($shareWithUserDiv, $shareWithOrgDiv);
// add tab content to the main panel
self.$mainPanel.append($tabContent);
// end of Tab content divs
// div contains other users sharing the narrative
var $othersDiv = $('<div>').css({
'margin-top': '15px',
'max-height': self.options.max_list_height,
'overflow-y': 'auto',
'overflow-x': 'hidden',
'display': 'flex',
'justify-content': 'center'
});
var $tbl = $('<table>');
$othersDiv.append($tbl);
// sort
self.ws_permissions.sort(function (a, b) {
var getPermLevel = function(perm) {
switch (perm) {
case 'a':
return 1;
case 'w':
return 2;
case 'r':
return 3;
default:
return 0;
}
};
if (a[1] !== b[1]) { // based on privilege first
return getPermLevel(a[1]) - getPermLevel(b[1]);
} // then on user name
if (a[0] < b[0])
return -1;
if (a[0] > b[0])
return 1;
return 0;
});
// show all other users
for (var i = 0; i < self.ws_permissions.length; i++) {
if (self.ws_permissions[i][0] === self.my_user_id || self.ws_permissions[i][0] === '*') {
continue;
}
var $select;
var $removeBtn = null;
var thisUser = self.ws_permissions[i][0];
if (isAdmin && thisUser !== self.narrOwner) {
$select = $('<select>')
.addClass('form-control kb-share-user-permissions-dropdown')
.attr('user', thisUser)
.append($('<option>').val('r').append('can view'))
.append($('<option>').val('w').append('can edit'))
.append($('<option>').val('a').append('can edit/share'))
.val(self.ws_permissions[i][1])
.on('change', function () {
self.showWorking('updating permissions...');
self.updateUserPermissions([{id: $(this).attr('user')}], $(this).val());
});
$removeBtn = $('<span>')
.attr('user', thisUser)
.addClass('btn btn-xs btn-danger')
.append($('<span>')
.addClass('fa fa-times'))
.click(function() {
self.updateUserPermissions([{id: $(this).attr('user')}], 'n');
});
} else {
$select = $('<div>').addClass('form-control kb-share-user-permissions-dropdown');
if (thisUser === self.narrOwner) {
$select.append('owns this Narrative');
}
else if (self.ws_permissions[i][1] === 'w') {
$select.append('can edit');
}
else if (self.ws_permissions[i][1] === 'a') {
$select.append('can edit/share');
}
else {
$select.append('can view');
}
}
var user_display = self.renderUserIconAndName(self.ws_permissions[i][0], null, true);
var $userRow =
$('<tr>')
.append($('<td style="text-align:left">')
.append(user_display[0]))
.append($('<td style="text-align:left">').css({'padding': '4px', 'padding-top': '6px'})
.append(user_display[1]))
.append($('<td style="text-align:right">').append($select));
if ($removeBtn) {
$userRow.append($('<td style="text-align:left">').append($removeBtn));
}
$tbl.append($userRow);
}
$shareWithUserDiv.append($othersDiv);
},
/**
* Send request to add narrative to a organization.
* Returns either {"complete": true} or a Request with the additional field "complete" with a value of false.
* @param {string} token // authorization token
*/
requestAddNarrative: function(token, orgID){
var ws_id = this.ws_info[0];
var groupResourceUrl = this.options.groups_url+"/group/"+orgID+"/resource/workspace/"+ws_id;
fetch(groupResourceUrl, {
method: "POST",
mode: "cors",
json: true,
headers:{
"Authorization": token,
"Content-Type": "application/json",
}
})
.then(response => response.json())
.then(response => {
if(response.error) {
this.reportError(response);
}
})
.catch(error => {
console.error('Error while sending request to add narrative:', error)
if(error) {
this.reportError(error);
}
});
},
/**
* Updates user permissions to the current Narrative.
* userData: list of objects. This typically comes from Select2, so it has some baggage.
* We just need the 'id' property.
* newPerm: string, one of [a (all), w (write), r (read), n (none)].
* Gets applied to all users.
*/
updateUserPermissions: function(userData, newPerm) {
var users = [];
for (var i = 0; i < userData.length; i++) {
if (userData[i].id.trim() !== '') {
users.push(userData[i].id.trim());
}
}
if (users.length === 0) {
return;
}
this.showWorking('updating permissions...');
Promise.resolve(this.ws.set_permissions({
id: this.ws_info[0],
new_permission: newPerm,
users: users
}))
.catch(function(error) {
this.reportError(error);
})
.finally(function() {
this.refresh();
}.bind(this));
},
makePublicPrivateToggle: function () {
var commandStr = 'make public?';
var newPerm = 'r';
var self = this;
if (!self.isPrivate) {
commandStr = 'make private?';
newPerm = 'n';
}
return $('<a href="#">' + commandStr + '</a>')
.click(function (e) {
e.preventDefault();
self.showWorking('updating permissions...');
Promise.resolve(self.ws.set_global_permission({
id: self.ws_info[0],
new_permission: newPerm
}))
.catch(function(error) {
self.reportError(error);
})
.finally(function() {
self.refresh();
});
});
},
/* private method - note: if placeholder is empty, then users cannot cancel a selection*/
setupSelect2: function ($input) {
var self = this;
var noMatchesFoundStr = 'Search by Name or Username';
$.fn.select2.amd.require([
'select2/data/array',
'select2/utils'
], function(ArrayData, Utils) {
function CustomData ($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function(params, callback) {
var term = params.term || '';
term = term.trim();
if (term.length >= 2) {
Promise.resolve(self.authClient.searchUserNames(null, term))
.then(function(users) {
var results = [];
Object.keys(users).forEach(function(username) {
if (username !== self.my_user_id) {
results.push({
id: username,
text: users[username],
found: true
});
}
});
if (results.length === 0) {
results = [{
id: term,
text: term,
found: false
}];
}
callback({ results: results });
});
}
else {
callback({ results: [] });
}
};
$input.select2({
formatNoMatches: noMatchesFoundStr,
placeholder: function() {
return $(this).data('placeholder');
},
delay: 250,
width: '40%',
dataAdapter: CustomData,
minimumResultsForSearch: 0,
language: {
noResults: function () {
return noMatchesFoundStr;
}
},
templateSelection: function (object) {
if (object.found) {
var toShow = self.renderUserIconAndName(object.id, object.text);
return $('<span>')
.append(toShow[0])
.append(toShow[1].css({'white-space': 'normal'}))
.css({'width': '100%'});
}
return $('<b>' + object.text + '</b> (not found)');
},
templateResult: function (object) {
if (object.found) {
var toShow = self.renderUserIconAndName(object.id, object.text);
return $('<span>').append(toShow[0]).append(toShow[1]);
}
return $('<b>' + object.text + '</b> (not found)');
}
});
$input.trigger('change');
});
},
// setting up Select2 for inputOrg
orgSetupSelect2: function($inputOrg){
var self = this;
var orgList = self.orgList;
var orgData = [];
var noMatchedOrgFoundStr = 'Search by Organization name';
$.fn.select2.amd.require([
'select2/data/array',
'select2/utils'
], function (ArrayData, Utils) {
if(!orgList) return;
orgList.forEach(org=>{
orgData.push({"id": org.id, "text": org.name});
})
$inputOrg.select2({
formatNoMatches: noMatchedOrgFoundStr,
placeholder: function() {
return $(this).data('placeholder');
},
delay: 250,
width: '40%',
data: orgData,
minimumResultsForSearch: 0,
allowClear: true,
language: {
noResults: function () {
return noMatchedOrgFoundStr;
}
},
});
$inputOrg.trigger('change');
});
},
showWorking: function (message) {
this.$mainPanel.empty();
this.$mainPanel.append('<br><br><div style="text-align:center"><img src="' + this.options.loadingImage
+ '"><br>' + message + '</div>');
},
reportError: function (error) {
console.error(error);
this.$notificationPanel.append(
$('<div>').addClass('alert alert-danger alert-dismissible').attr('role', 'alert')
.append('<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>')
.append('<strong>Error: </strong> ' + error.error.message)
);
},
refresh: function () {
this.getInfoAndRender();
},
colors: [
'#F44336', //red
'#E91E63', //pink
'#9C27B0', //purple
'#673AB7', //deep purple
'#3F51B5', //indigo
'#2196F3', //blue
'#03A9F4', //light blue
'#00BCD4', //cyan
'#009688', //teal
'#4CAF50', //green
'#8BC34A', //lime green
'#FFC107', //amber
'#FF9800', //orange
'#FF5722', //deep orange
'#795548', //brown
'#9E9E9E', //grey
'#607D8B' //blue grey
],
renderUserIconAndName: function (username, realName, turnOnLink) {
var code = 0;
for (var i = 0; i < username.length; i++) {
code += username.charCodeAt(i);
}
var userColor = this.colors[ code % this.colors.length ];
var $span = $('<span>').addClass('fa fa-user').css({'color': userColor});
var userString = username;
if (username === this.my_user_id) {
userString = ' Me (' + username + ')';
} else if (realName) {
userString = ' ' + realName + ' (' + username + ')';
} else if (this.user_data[username]) {
userString = ' ' + this.user_data[username] + ' (' + username + ')';
}
var shortName = userString;
var isShortened = false;
if (userString.length > this.options.max_name_length) {
shortName = shortName.substring(0, this.options.max_name_length - 3) + '...';
isShortened = true;
}
var $name = $('<span>').css({'color': userColor, 'white-space': 'nowrap'}).append(StringUtil.escape(shortName));
if (isShortened) {
$name.tooltip({title: userString, placement: 'bottom'});
}
if (turnOnLink) {
$name = $('<a href="' + this.options.user_page_link + username + '" target="_blank">').append(
$('<span>').css({'color': userColor, 'white-space': 'nowrap'}).append(StringUtil.escape(shortName)));
}
return [$span, $name];
}
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:57f398c99d91daa92f5f3a3b02c6427638e0bd2d060f97be98260c831be95f03
size 11152
|
import Vue from 'vue'
import deepmerge from 'deepmerge'
import { mount } from 'avoriaz'
export default async (component, template, options = { propsData: {} }) => {
const wrapper = mount(component, deepmerge(options, {
slots: {
default: [template]
}
}))
await Vue.nextTick()
return Promise.resolve(wrapper)
}
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["exports", "foo"], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require("foo"));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.foo);
global.input = mod.exports;
}
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_exports, _foo) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
Object.defineProperty(_exports, "some exports", {
enumerable: true,
get: function () {
return _foo["some exports"];
}
});
});
|
// The default deployment object. createDeployment overwrites this.
var deployment = new Deployment({});
// The label used by the QRI to denote connections with public internet.
var publicInternetLabel = "public";
// Overwrite the deployment object with a new one.
function createDeployment(deploymentOpts) {
deployment = new Deployment(deploymentOpts);
return deployment;
}
function Deployment(deploymentOpts) {
this.maxPrice = deploymentOpts.maxPrice || 0;
this.namespace = deploymentOpts.namespace || "default-namespace";
this.adminACL = deploymentOpts.adminACL || [];
this.machines = [];
this.containers = {};
this.services = [];
this.connections = [];
this.placements = [];
this.invariants = [];
}
// key creates a string key for objects that container a _refID, namely Containers
// and Machines.
function key(obj) {
var keyObj = obj.clone();
keyObj._refID = "";
return JSON.stringify(keyObj);
}
// setQuiltIDs deterministically sets the id field of objects based on
// their attributes. The _refID field is required to differentiate between multiple
// references to the same object, and multiple instantiations with the exact
// same attributes.
function setQuiltIDs(objs) {
// The refIDs for each identical instance.
var refIDs = {};
objs.forEach(function(obj) {
var k = key(obj);
if (!refIDs[k]) {
refIDs[k] = [];
}
refIDs[k].push(obj._refID);
});
// If there are multiple references to the same object, there will be duplicate
// refIDs.
Object.keys(refIDs).forEach(function(k) {
refIDs[k] = _.uniq(refIDs[k]).sort();
});
objs.forEach(function(obj) {
var k = key(obj);
obj.id = hash(k + refIDs[k].indexOf(obj._refID));
});
}
// Convert the deployment to the QRI deployment format.
Deployment.prototype.toQuiltRepresentation = function() {
this.vet();
setQuiltIDs(this.machines);
var containers = [];
this.services.forEach(function(serv) {
serv.containers.forEach(function(c) {
containers.push(c);
});
});
setQuiltIDs(containers);
// Map from container ID to container.
var containerMap = {};
var services = [];
var connections = [];
var placements = [];
// For each service, convert the associated connections and placement rules.
// Also, aggregate all containers referenced by services.
this.services.forEach(function(service) {
connections = connections.concat(service.getQuiltConnections());
placements = placements.concat(service.getQuiltPlacements());
// Collect the containers IDs, and add them to the container map.
var ids = [];
service.containers.forEach(function(container) {
ids.push(container.id);
containerMap[container.id] = container;
});
services.push({
name: service.name,
ids: ids,
annotations: service.annotations
});
});
var containers = [];
Object.keys(containerMap).forEach(function(cid) {
containers.push(containerMap[cid]);
});
return {
machines: this.machines,
labels: services,
containers: containers,
connections: connections,
placements: placements,
invariants: this.invariants,
namespace: this.namespace,
adminACL: this.adminACL,
maxPrice: this.maxPrice
};
};
// Check if all referenced services in connections and placements are really deployed.
Deployment.prototype.vet = function() {
var labelMap = {};
this.services.forEach(function(service) {
labelMap[service.name] = true;
});
this.services.forEach(function(service) {
service.connections.forEach(function(conn) {
var to = conn.to.name;
if (!labelMap[to]) {
throw service.name + " has a connection to undeployed service: " + to;
}
});
var hasFloatingIp = false;
service.placements.forEach(function(plcm) {
if (plcm.floatingIp) {
hasFloatingIp = true;
}
var otherLabel = plcm.otherLabel;
if (otherLabel !== undefined && !labelMap[otherLabel]) {
throw service.name + " has a placement in terms of an " +
"undeployed service: " + otherLabel;
}
});
if (hasFloatingIp && service.incomingPublic.length
&& service.containers.length > 1) {
throw service.name + " has a floating IP and multiple containers. " +
"This is not yet supported."
}
});
};
// deploy adds an object, or list of objects, to the deployment.
// Deployable objects must implement the deploy(deployment) interface.
Deployment.prototype.deploy = function(toDeployList) {
if (toDeployList.constructor !== Array) {
toDeployList = [toDeployList];
}
var that = this;
toDeployList.forEach(function(toDeploy) {
if (!toDeploy.deploy) {
throw "only objects that implement \"deploy(deployment)\" can be deployed";
}
toDeploy.deploy(that);
});
};
Deployment.prototype.assert = function(rule, desired) {
this.invariants.push(new Assertion(rule, desired));
};
function Service(name, containers) {
this.name = uniqueLabelName(name);
this.containers = containers;
this.annotations = [];
this.placements = [];
this.connections = [];
this.outgoingPublic = [];
this.incomingPublic = [];
}
// Get the Quilt hostname that represents the entire service.
Service.prototype.hostname = function() {
return this.name + ".q";
};
// Get a list of Quilt hostnames that address the containers within the service.
Service.prototype.children = function() {
var i;
var res = [];
for (i = 1; i < this.containers.length + 1; i++) {
res.push(i + "." + this.name + ".q");
}
return res;
};
Service.prototype.annotate = function(annotation) {
this.annotations.push(annotation);
};
Service.prototype.canReach = function(target) {
if (target === publicInternet) {
return reachable(this.name, publicInternetLabel);
}
return reachable(this.name, target.name);
};
Service.prototype.canReachACL = function(target) {
return reachableACL(this.name, target.name);
};
Service.prototype.between = function(src, dst) {
return between(src.name, this.name, dst.name);
};
Service.prototype.neighborOf = function(target) {
return neighbor(this.name, target.name);
};
Service.prototype.deploy = function(deployment) {
deployment.services.push(this);
};
Service.prototype.connect = function(range, to) {
range = boxRange(range);
if (to === publicInternet) {
return this.connectToPublic(range);
}
this.connections.push(new Connection(range, to));
};
// publicInternet is an object that looks like another service that can be
// connected to or from. However, it is actually just syntactic sugar to hide
// the connectToPublic and connectFromPublic functions.
var publicInternet = {
connect: function(range, to) {
to.connectFromPublic(range);
},
canReach: function(to) {
return reachable(publicInternetLabel, to.name);
}
};
// Allow outbound traffic from the service to public internet.
Service.prototype.connectToPublic = function(range) {
range = boxRange(range);
if (range.min != range.max) {
throw "public internet cannot connect on port ranges";
}
this.outgoingPublic.push(range);
};
// Allow inbound traffic from public internet to the service.
Service.prototype.connectFromPublic = function(range) {
range = boxRange(range);
if (range.min != range.max) {
throw "public internet cannot connect on port ranges";
}
this.incomingPublic.push(range);
};
Service.prototype.place = function(rule) {
this.placements.push(rule);
};
Service.prototype.getQuiltConnections = function() {
var connections = [];
var that = this;
this.connections.forEach(function(conn) {
connections.push({
from: that.name,
to: conn.to.name,
minPort: conn.minPort,
maxPort: conn.maxPort
});
});
this.outgoingPublic.forEach(function(rng) {
connections.push({
from: that.name,
to: publicInternetLabel,
minPort: rng.min,
maxPort: rng.max
});
});
this.incomingPublic.forEach(function(rng) {
connections.push({
from: publicInternetLabel,
to: that.name,
minPort: rng.min,
maxPort: rng.max
});
});
return connections;
};
Service.prototype.getQuiltPlacements = function() {
var placements = [];
var that = this;
this.placements.forEach(function(placement) {
placements.push({
targetLabel: that.name,
exclusive: placement.exclusive,
otherLabel: placement.otherLabel || "",
provider: placement.provider || "",
size: placement.size || "",
region: placement.region || "",
floatingIp: placement.floatingIp || ""
});
});
return placements;
};
var labelNameCount = {};
function uniqueLabelName(name) {
if (!(name in labelNameCount)) {
labelNameCount[name] = 0;
}
var count = ++labelNameCount[name];
if (count == 1) {
return name;
}
return name + labelNameCount[name];
}
// Box raw integers into range.
function boxRange(x) {
if (x === undefined) {
return new Range(0, 0);
}
if (typeof x === "number") {
x = new Range(x, x);
}
return x;
}
function Machine(optionalArgs) {
this._refID = _.uniqueId();
this.provider = optionalArgs.provider || "";
this.role = optionalArgs.role || "";
this.region = optionalArgs.region || "";
this.size = optionalArgs.size || "";
this.floatingIp = optionalArgs.floatingIp || "";
this.diskSize = optionalArgs.diskSize || 0;
this.sshKeys = optionalArgs.sshKeys || [];
this.cpu = boxRange(optionalArgs.cpu);
this.ram = boxRange(optionalArgs.ram);
}
Machine.prototype.deploy = function(deployment) {
deployment.machines.push(this);
};
// Create a new machine with the same attributes.
Machine.prototype.clone = function() {
// _.clone only creates a shallow copy, so we must clone sshKeys ourselves.
var keyClone = _.clone(this.sshKeys);
var cloned = _.clone(this);
cloned.sshKeys = keyClone;
return new Machine(cloned);
};
Machine.prototype.withRole = function(role) {
var copy = this.clone();
copy.role = role;
return copy;
};
Machine.prototype.asWorker = function() {
return this.withRole("Worker");
};
Machine.prototype.asMaster = function() {
return this.withRole("Master");
};
// Create n new machines with the same attributes.
Machine.prototype.replicate = function(n) {
var i;
var res = [];
for (i = 0 ; i < n ; i++) {
res.push(this.clone());
}
return res;
};
function Container(image, command) {
// refID is used to distinguish deployments with multiple references to the
// same container, and deployments with multiple containers with the exact
// same attributes.
this._refID = _.uniqueId();
this.image = image;
this.command = command || [];
this.env = {};
}
// Create a new Container with the same attributes.
Container.prototype.clone = function() {
var cloned = new Container(this.image, _.clone(this.command));
cloned.env = _.clone(this.env);
return cloned;
};
// Create n new Containers with the same attributes.
Container.prototype.replicate = function(n) {
var i;
var res = [];
for (i = 0 ; i < n ; i++) {
res.push(this.clone());
}
return res;
};
Container.prototype.setEnv = function(key, val) {
this.env[key] = val;
};
Container.prototype.withEnv = function(env) {
var cloned = this.clone();
cloned.env = env;
return cloned;
};
var enough = { form: "enough" };
var between = invariantType("between");
var neighbor = invariantType("reachDirect");
var reachableACL = invariantType("reachACL");
var reachable = invariantType("reach");
function Assertion(invariant, desired) {
this.form = invariant.form;
this.nodes = invariant.nodes;
this.target = desired;
}
function invariantType(form) {
return function() {
// Convert the arguments object into a real array. We can't simply use
// Array.from because it isn't defined in Otto.
var nodes = [];
var i;
for (i = 0 ; i < arguments.length ; i++) {
nodes.push(arguments[i]);
}
return {
form: form,
nodes: nodes
};
};
}
function LabelRule(exclusive, otherService) {
this.exclusive = exclusive;
this.otherLabel = otherService.name;
}
function MachineRule(exclusive, optionalArgs) {
this.exclusive = exclusive;
if (optionalArgs.provider) {
this.provider = optionalArgs.provider;
}
if (optionalArgs.size) {
this.size = optionalArgs.size;
}
if (optionalArgs.region) {
this.region = optionalArgs.region;
}
if (optionalArgs.floatingIp) {
this.floatingIp = optionalArgs.floatingIp;
}
}
function Connection(ports, to) {
this.minPort = ports.min;
this.maxPort = ports.max;
this.to = to;
}
function Range(min, max) {
this.min = min;
this.max = max;
}
function Port(p) {
return new PortRange(p, p);
}
var PortRange = Range;
|
var assert = require('assert');
var extend = require('util')._extend;
var expect = require('chai').expect;
var SharedClass = require('../lib/shared-class');
var factory = require('./helpers/shared-objects-factory.js');
var RemoteObjects = require('../');
describe('SharedClass', function() {
var SomeClass;
beforeEach(function() { SomeClass = factory.createSharedClass(); });
describe('constructor', function() {
it('fills http.path from ctor.http', function() {
SomeClass.http = { path: '/foo' };
var sc = new SharedClass('some', SomeClass);
expect(sc.http.path).to.equal('/foo');
});
it('fills http.path using the name', function() {
var sc = new SharedClass('some', SomeClass);
expect(sc.http.path).to.equal('/some');
});
it('fills http.path using a normalized path', function() {
var sc = new SharedClass('SomeClass', SomeClass, { normalizeHttpPath: true });
expect(sc.http.path).to.equal('/some-class');
});
it('does not require a sharedConstructor', function() {
var myClass = {};
myClass.remoteNamespace = 'bar';
myClass.foo = function() {};
myClass.foo.shared = true;
var sc = new SharedClass(undefined, myClass);
var fns = sc.methods().map(getName);
expect(fns).to.contain('foo');
expect(sc.http).to.eql({ path: '/bar' });
});
});
describe('sharedClass.methods()', function() {
it('discovers remote methods', function() {
var sc = new SharedClass('some', SomeClass);
SomeClass.staticMethod = function() {};
SomeClass.staticMethod.shared = true;
SomeClass.prototype.instanceMethod = function() {};
SomeClass.prototype.instanceMethod.shared = true;
var fns = sc.methods().map(getFn);
expect(fns).to.contain(SomeClass.staticMethod);
expect(fns).to.contain(SomeClass.prototype.instanceMethod);
});
it('only discovers a function once with aliases', function() {
function MyClass() {}
var sc = new SharedClass('some', MyClass);
var fn = function() {};
fn.shared = true;
MyClass.a = fn;
MyClass.b = fn;
MyClass.prototype.a = fn;
MyClass.prototype.b = fn;
var methods = sc.methods();
var fns = methods.map(getFn);
expect(fns.length).to.equal(1);
expect(methods[0].aliases.sort()).to.eql(['a', 'b']);
});
it('discovers multiple functions correctly', function() {
function MyClass() {}
var sc = new SharedClass('some', MyClass);
MyClass.a = createSharedFn();
MyClass.b = createSharedFn();
MyClass.prototype.a = createSharedFn();
MyClass.prototype.b = createSharedFn();
var fns = sc.methods().map(getFn);
expect(fns.length).to.equal(4);
expect(fns).to.contain(MyClass.a);
expect(fns).to.contain(MyClass.b);
expect(fns).to.contain(MyClass.prototype.a);
expect(fns).to.contain(MyClass.prototype.b);
function createSharedFn() {
var fn = function() {};
fn.shared = true;
return fn;
}
});
it('should skip properties that are model classes', function() {
var sc = new SharedClass('some', SomeClass);
function MockModel1() {}
MockModel1.modelName = 'M1';
MockModel1.shared = true;
SomeClass.staticMethod = MockModel1;
function MockModel2() {}
MockModel2.modelName = 'M2';
MockModel2.shared = true;
SomeClass.prototype.instanceMethod = MockModel2;
var fns = sc.methods().map(getFn);
expect(fns).to.not.contain(SomeClass.staticMethod);
expect(fns).to.not.contain(SomeClass.prototype.instanceMethod);
});
});
describe('sharedClass.defineMethod(name, options)', function() {
it('defines a remote method', function() {
var sc = new SharedClass('SomeClass', SomeClass);
SomeClass.prototype.myMethod = function() {};
var METHOD_NAME = 'myMethod';
sc.defineMethod(METHOD_NAME, {
prototype: true
});
var methods = sc.methods().map(getName);
expect(methods).to.contain(METHOD_NAME);
});
it('should allow a shared class to resolve dynamically defined functions',
function(done) {
var MyClass = function() {};
var METHOD_NAME = 'dynFn';
process.nextTick(function() {
MyClass[METHOD_NAME] = function(str, cb) {
cb(null, str);
};
done();
});
var sharedClass = new SharedClass('MyClass', MyClass);
sharedClass.defineMethod(METHOD_NAME, {});
var methods = sharedClass.methods().map(getName);
expect(methods).to.contain(METHOD_NAME);
}
);
});
describe('sharedClass.resolve(resolver)', function() {
it('should allow sharedMethods to be resolved dynamically', function() {
function MyClass() {}
MyClass.obj = {
dyn: function(cb) {
cb();
}
};
var sharedClass = new SharedClass('MyClass', MyClass);
sharedClass.resolve(function(define) {
define('dyn', {}, MyClass.obj.dyn);
});
var methods = sharedClass.methods().map(getName);
expect(methods).to.contain('dyn');
});
});
describe('sharedClass.find()', function() {
var sc;
var sm;
beforeEach(function() {
sc = new SharedClass('SomeClass', SomeClass);
SomeClass.prototype.myMethod = function() {};
var METHOD_NAME = 'myMethod';
sm = sc.defineMethod(METHOD_NAME, {
prototype: true
});
});
it('finds sharedMethod for the given function', function() {
assert(sc.find(SomeClass.prototype.myMethod) === sm);
});
it('find sharedMethod by name', function() {
assert(sc.find('myMethod') === sm);
});
});
describe('remotes.addClass(sharedClass)', function() {
it('should make the class available', function() {
var CLASS_NAME = 'SomeClass';
var remotes = RemoteObjects.create();
var sharedClass = new SharedClass(CLASS_NAME, SomeClass);
remotes.addClass(sharedClass);
var classes = remotes.classes().map(getName);
expect(classes).to.contain(CLASS_NAME);
});
});
describe('sharedClass.disableMethod(methodName, isStatic)', function() {
var sc;
var sm;
var METHOD_NAME = 'testMethod';
var INST_METHOD_NAME = 'instTestMethod';
var DYN_METHOD_NAME = 'dynMethod';
beforeEach(function() {
sc = new SharedClass('SomeClass', SomeClass);
sm = sc.defineMethod(METHOD_NAME, {isStatic: true});
sm = sc.defineMethod(INST_METHOD_NAME, {isStatic: false});
sc.resolve(function(define) {
define(DYN_METHOD_NAME, {isStatic: true});
});
});
it('excludes disabled static methods from the method list', function() {
sc.disableMethod(METHOD_NAME, true);
var methods = sc.methods().map(getName);
expect(methods).to.not.contain(METHOD_NAME);
});
it('excludes disabled prototype methods from the method list', function() {
sc.disableMethod(INST_METHOD_NAME, false);
var methods = sc.methods().map(getName);
expect(methods).to.not.contain(INST_METHOD_NAME);
});
it('excludes disabled dynamic (resolved) methods from the method list', function() {
sc.disableMethod(DYN_METHOD_NAME, true);
var methods = sc.methods().map(getName);
expect(methods).to.not.contain(DYN_METHOD_NAME);
});
});
});
function getName(obj) {
return obj.name;
}
function getFn(obj) {
return obj.fn;
}
|
"use strict";
/**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var tsutils_1 = require("tsutils");
var ts = require("typescript");
var Lint = require("../index");
var Rule = /** @class */ (function (_super) {
tslib_1.__extends(Rule, _super);
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
/* tslint:enable:object-literal-sort-keys */
Rule.FAILURE_STRING = function (cbText) {
return "No need to wrap '" + cbText + "' in another function. Just use it directly.";
};
Rule.prototype.apply = function (sourceFile) {
return this.applyWithFunction(sourceFile, walk);
};
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "no-unnecessary-callback-wrapper",
description: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Replaces `x => f(x)` with just `f`.\n To catch more cases, enable `only-arrow-functions` and `arrow-return-shorthand` too."], ["\n Replaces \\`x => f(x)\\` with just \\`f\\`.\n To catch more cases, enable \\`only-arrow-functions\\` and \\`arrow-return-shorthand\\` too."]))),
optionsDescription: "Not configurable.",
options: null,
optionExamples: [true],
rationale: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n There's generally no reason to wrap a function with a callback wrapper if it's directly called anyway.\n Doing so creates extra inline lambdas that slow the runtime down.\n "], ["\n There's generally no reason to wrap a function with a callback wrapper if it's directly called anyway.\n Doing so creates extra inline lambdas that slow the runtime down.\n "]))),
type: "style",
typescriptOnly: false,
};
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
function walk(ctx) {
return ts.forEachChild(ctx.sourceFile, cb);
function cb(node) {
if (tsutils_1.isArrowFunction(node) && !tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.AsyncKeyword) &&
tsutils_1.isCallExpression(node.body) && tsutils_1.isIdentifier(node.body.expression) &&
isRedundantCallback(node.parameters, node.body.arguments, node.body.expression)) {
var start = node.getStart(ctx.sourceFile);
ctx.addFailure(start, node.end, Rule.FAILURE_STRING(node.body.expression.text), [
Lint.Replacement.deleteFromTo(start, node.body.getStart(ctx.sourceFile)),
Lint.Replacement.deleteFromTo(node.body.expression.end, node.end),
]);
}
else {
return ts.forEachChild(node, cb);
}
}
}
function isRedundantCallback(parameters, args, expression) {
if (parameters.length !== args.length) {
return false;
}
for (var i = 0; i < parameters.length; ++i) {
var _a = parameters[i], dotDotDotToken = _a.dotDotDotToken, name = _a.name;
var arg = args[i];
if (dotDotDotToken !== undefined) {
if (!tsutils_1.isSpreadElement(arg)) {
return false;
}
arg = arg.expression;
}
if (!tsutils_1.isIdentifier(name) || !tsutils_1.isIdentifier(arg) || name.text !== arg.text
// If the invoked expression is one of the parameters, bail.
|| expression.text === name.text) {
return false;
}
}
return true;
}
var templateObject_1, templateObject_2;
|
/*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react'
import { connect } from 'react-redux'
import { createSelector } from 'reselect'
import { IntlProvider } from 'react-intl'
import { makeSelectLocale } from './selectors'
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
)
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
}
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
)
function mapDispatchToProps(dispatch) {
return {
dispatch,
}
}
export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider)
|
version https://git-lfs.github.com/spec/v1
oid sha256:9194712ba9daed404de66614b857fd4428c3c696a4fa67a22c2791b916b2311e
size 6148
|
import path from 'path';
import express from 'express';
import https from 'https';
import fallback from 'express-history-api-fallback'
const webpack = require('webpack');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// Additional middleware which will set headers that we need on each request.
app.use(function(req, res, next) {
// Set permissive CORS header - this allows this server to be used only as
// an API server in conjunction with something like webpack-dev-server.
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Credentials', '*');
// Disable caching so we'll always get the latest comments.
res.setHeader('Cache-Control', 'no-cache');
next();
});
// api
var apiRouter = require('./api');
app.use('/api', apiRouter);
// webpack middle for hot reloading during development
const inProduction = process.env.NODE_ENV == 'production';
if (inProduction) {
// under production, node serve the bundle.js (in development, webpack-dev-server serve the bundle.js)
console.log('in production, node will serve the bundle');
const PATH_DIST = path.resolve(__dirname, '../../dist');
app.use(express.static(PATH_DIST));
} else {
console.log('in development, node only serve APIs, please make sure webpack dev server is running.');
}
// serve html regardless whether the middleware is enabled or not
app.use(express.static(path.resolve(__dirname, '../public/')));
app.use(fallback(path.resolve(__dirname, '../public/index.html'))); // when requested route does not exist here in express app, return this file; for react.js route when using history.
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get('port'));
});
|
// Nest: A location (node) connected to other Nests via Webs (edges) in the game that Spiders can converge on, regardless of owner.
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// Instead, you should only be reading its variables and calling its functions.
const client = require(`${__basedir}/joueur/client`);
const GameObject = require('./gameObject');
//<<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// any additional requires you want can be required here safely between creer runs
//<<-- /Creer-Merge: requires -->>
/**
* A location (node) connected to other Nests via Webs (edges) in the game that Spiders can converge on, regardless of owner.
* @extends Spiders.GameObject
* @memberof Spiders
*/
class Nest extends GameObject {
/**
* Initializes a Nest with basic logic as provided by the Creer code generator.
*
* Never use this directly. It is for internal Joueur use.
*/
constructor(...args) {
super(...args);
// The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has.
// default values for private member values
this.controllingPlayer = null;
this.spiders = [];
this.webs = [];
this.x = 0;
this.y = 0;
//<<-- Creer-Merge: init -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// any additional init logic you want can go here
//<<-- /Creer-Merge: init -->>
}
// Member variables
/**
* The Player that 'controls' this Nest as they have the most Spiders on this nest.
*
* @type {Spiders.Player}
*/
get controllingPlayer() {
return client.gameManager.getMemberValue(this, 'controllingPlayer');
}
set controllingPlayer(value) {
client.gameManager.setMemberValue(this, 'controllingPlayer', value);
}
/**
* All the Spiders currently located on this Nest.
*
* @type {Array.<Spiders.Spider>}
*/
get spiders() {
return client.gameManager.getMemberValue(this, 'spiders');
}
set spiders(value) {
client.gameManager.setMemberValue(this, 'spiders', value);
}
/**
* Webs that connect to this Nest.
*
* @type {Array.<Spiders.Web>}
*/
get webs() {
return client.gameManager.getMemberValue(this, 'webs');
}
set webs(value) {
client.gameManager.setMemberValue(this, 'webs', value);
}
/**
* The X coordinate of the Nest. Used for distance calculations.
*
* @type {number}
*/
get x() {
return client.gameManager.getMemberValue(this, 'x');
}
set x(value) {
client.gameManager.setMemberValue(this, 'x', value);
}
/**
* The Y coordinate of the Nest. Used for distance calculations.
*
* @type {number}
*/
get y() {
return client.gameManager.getMemberValue(this, 'y');
}
set y(value) {
client.gameManager.setMemberValue(this, 'y', value);
}
//<<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// any additional functions you want to add to this class can be preserved here
//<<-- /Creer-Merge: functions -->>
}
module.exports = Nest;
|
export const LS_ACCESS_TOKEN_KEY = 'gitment-comments-token'
export const LS_USER_KEY = 'gitment-user-info'
export const NOT_INITIALIZED_ERROR = new Error('Comments Not Initialized')
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define("webextension-polyfill", ["module"], factory);
} else if (typeof exports !== "undefined") {
factory(module);
} else {
var mod = {
exports: {}
};
factory(mod);
global.browser = mod.exports;
}
})(this, function (module) {
/* webextension-polyfill - v0.1.1 - Fri Apr 28 2017 00:28:16 */
/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
/* vim: set sts=2 sw=2 et tw=80: */
/* 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/. */
"use strict";
if (typeof browser === "undefined") {
// Wrapping the bulk of this polyfill in a one-time-use function is a minor
// optimization for Firefox. Since Spidermonkey does not fully parse the
// contents of a function until the first time it's called, and since it will
// never actually need to be called, this allows the polyfill to be included
// in Firefox nearly for free.
const wrapAPIs = () => {
// NOTE: apiMetadata is associated to the content of the api-metadata.json file
// at build time by replacing the following "include" with the content of the
// JSON file.
const apiMetadata = {
"alarms": {
"clear": {
"minArgs": 0,
"maxArgs": 1
},
"clearAll": {
"minArgs": 0,
"maxArgs": 0
},
"get": {
"minArgs": 0,
"maxArgs": 1
},
"getAll": {
"minArgs": 0,
"maxArgs": 0
}
},
"bookmarks": {
"create": {
"minArgs": 1,
"maxArgs": 1
},
"export": {
"minArgs": 0,
"maxArgs": 0
},
"get": {
"minArgs": 1,
"maxArgs": 1
},
"getChildren": {
"minArgs": 1,
"maxArgs": 1
},
"getRecent": {
"minArgs": 1,
"maxArgs": 1
},
"getTree": {
"minArgs": 0,
"maxArgs": 0
},
"getSubTree": {
"minArgs": 1,
"maxArgs": 1
},
"import": {
"minArgs": 0,
"maxArgs": 0
},
"move": {
"minArgs": 2,
"maxArgs": 2
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"removeTree": {
"minArgs": 1,
"maxArgs": 1
},
"search": {
"minArgs": 1,
"maxArgs": 1
},
"update": {
"minArgs": 2,
"maxArgs": 2
}
},
"browserAction": {
"getBadgeBackgroundColor": {
"minArgs": 1,
"maxArgs": 1
},
"getBadgeText": {
"minArgs": 1,
"maxArgs": 1
},
"getPopup": {
"minArgs": 1,
"maxArgs": 1
},
"getTitle": {
"minArgs": 1,
"maxArgs": 1
},
"setIcon": {
"minArgs": 1,
"maxArgs": 1
}
},
"commands": {
"getAll": {
"minArgs": 0,
"maxArgs": 0
}
},
"contextMenus": {
"update": {
"minArgs": 2,
"maxArgs": 2
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"removeAll": {
"minArgs": 0,
"maxArgs": 0
}
},
"cookies": {
"get": {
"minArgs": 1,
"maxArgs": 1
},
"getAll": {
"minArgs": 1,
"maxArgs": 1
},
"getAllCookieStores": {
"minArgs": 0,
"maxArgs": 0
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"set": {
"minArgs": 1,
"maxArgs": 1
}
},
"downloads": {
"download": {
"minArgs": 1,
"maxArgs": 1
},
"cancel": {
"minArgs": 1,
"maxArgs": 1
},
"erase": {
"minArgs": 1,
"maxArgs": 1
},
"getFileIcon": {
"minArgs": 1,
"maxArgs": 2
},
"open": {
"minArgs": 1,
"maxArgs": 1
},
"pause": {
"minArgs": 1,
"maxArgs": 1
},
"removeFile": {
"minArgs": 1,
"maxArgs": 1
},
"resume": {
"minArgs": 1,
"maxArgs": 1
},
"search": {
"minArgs": 1,
"maxArgs": 1
},
"show": {
"minArgs": 1,
"maxArgs": 1
}
},
"extension": {
"isAllowedFileSchemeAccess": {
"minArgs": 0,
"maxArgs": 0
},
"isAllowedIncognitoAccess": {
"minArgs": 0,
"maxArgs": 0
}
},
"history": {
"addUrl": {
"minArgs": 1,
"maxArgs": 1
},
"getVisits": {
"minArgs": 1,
"maxArgs": 1
},
"deleteAll": {
"minArgs": 0,
"maxArgs": 0
},
"deleteRange": {
"minArgs": 1,
"maxArgs": 1
},
"deleteUrl": {
"minArgs": 1,
"maxArgs": 1
},
"search": {
"minArgs": 1,
"maxArgs": 1
}
},
"i18n": {
"detectLanguage": {
"minArgs": 1,
"maxArgs": 1
},
"getAcceptLanguages": {
"minArgs": 0,
"maxArgs": 0
}
},
"idle": {
"queryState": {
"minArgs": 1,
"maxArgs": 1
}
},
"management": {
"get": {
"minArgs": 1,
"maxArgs": 1
},
"getAll": {
"minArgs": 0,
"maxArgs": 0
},
"getSelf": {
"minArgs": 0,
"maxArgs": 0
},
"uninstallSelf": {
"minArgs": 0,
"maxArgs": 1
}
},
"notifications": {
"clear": {
"minArgs": 1,
"maxArgs": 1
},
"create": {
"minArgs": 1,
"maxArgs": 2
},
"getAll": {
"minArgs": 0,
"maxArgs": 0
},
"getPermissionLevel": {
"minArgs": 0,
"maxArgs": 0
},
"update": {
"minArgs": 2,
"maxArgs": 2
}
},
"pageAction": {
"getPopup": {
"minArgs": 1,
"maxArgs": 1
},
"getTitle": {
"minArgs": 1,
"maxArgs": 1
},
"hide": {
"minArgs": 0,
"maxArgs": 0
},
"setIcon": {
"minArgs": 1,
"maxArgs": 1
},
"show": {
"minArgs": 0,
"maxArgs": 0
}
},
"runtime": {
"getBackgroundPage": {
"minArgs": 0,
"maxArgs": 0
},
"getBrowserInfo": {
"minArgs": 0,
"maxArgs": 0
},
"getPlatformInfo": {
"minArgs": 0,
"maxArgs": 0
},
"openOptionsPage": {
"minArgs": 0,
"maxArgs": 0
},
"requestUpdateCheck": {
"minArgs": 0,
"maxArgs": 0
},
"sendMessage": {
"minArgs": 1,
"maxArgs": 3
},
"sendNativeMessage": {
"minArgs": 2,
"maxArgs": 2
},
"setUninstallURL": {
"minArgs": 1,
"maxArgs": 1
}
},
"storage": {
"local": {
"clear": {
"minArgs": 0,
"maxArgs": 0
},
"get": {
"minArgs": 0,
"maxArgs": 1
},
"getBytesInUse": {
"minArgs": 0,
"maxArgs": 1
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"set": {
"minArgs": 1,
"maxArgs": 1
}
},
"managed": {
"get": {
"minArgs": 0,
"maxArgs": 1
},
"getBytesInUse": {
"minArgs": 0,
"maxArgs": 1
}
},
"sync": {
"clear": {
"minArgs": 0,
"maxArgs": 0
},
"get": {
"minArgs": 0,
"maxArgs": 1
},
"getBytesInUse": {
"minArgs": 0,
"maxArgs": 1
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"set": {
"minArgs": 1,
"maxArgs": 1
}
}
},
"tabs": {
"create": {
"minArgs": 1,
"maxArgs": 1
},
"captureVisibleTab": {
"minArgs": 0,
"maxArgs": 2
},
"detectLanguage": {
"minArgs": 0,
"maxArgs": 1
},
"duplicate": {
"minArgs": 1,
"maxArgs": 1
},
"executeScript": {
"minArgs": 1,
"maxArgs": 2
},
"get": {
"minArgs": 1,
"maxArgs": 1
},
"getCurrent": {
"minArgs": 0,
"maxArgs": 0
},
"getZoom": {
"minArgs": 0,
"maxArgs": 1
},
"getZoomSettings": {
"minArgs": 0,
"maxArgs": 1
},
"highlight": {
"minArgs": 1,
"maxArgs": 1
},
"insertCSS": {
"minArgs": 1,
"maxArgs": 2
},
"move": {
"minArgs": 2,
"maxArgs": 2
},
"reload": {
"minArgs": 0,
"maxArgs": 2
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"query": {
"minArgs": 1,
"maxArgs": 1
},
"removeCSS": {
"minArgs": 1,
"maxArgs": 2
},
"sendMessage": {
"minArgs": 2,
"maxArgs": 3
},
"setZoom": {
"minArgs": 1,
"maxArgs": 2
},
"setZoomSettings": {
"minArgs": 1,
"maxArgs": 2
},
"update": {
"minArgs": 1,
"maxArgs": 2
}
},
"webNavigation": {
"getAllFrames": {
"minArgs": 1,
"maxArgs": 1
},
"getFrame": {
"minArgs": 1,
"maxArgs": 1
}
},
"webRequest": {
"handlerBehaviorChanged": {
"minArgs": 0,
"maxArgs": 0
}
},
"windows": {
"create": {
"minArgs": 0,
"maxArgs": 1
},
"get": {
"minArgs": 1,
"maxArgs": 2
},
"getAll": {
"minArgs": 0,
"maxArgs": 1
},
"getCurrent": {
"minArgs": 0,
"maxArgs": 1
},
"getLastFocused": {
"minArgs": 0,
"maxArgs": 1
},
"remove": {
"minArgs": 1,
"maxArgs": 1
},
"update": {
"minArgs": 2,
"maxArgs": 2
}
}
};
if (Object.keys(apiMetadata).length === 0) {
throw new Error("api-metadata.json has not been included in browser-polyfill");
}
/**
* A WeakMap subclass which creates and stores a value for any key which does
* not exist when accessed, but behaves exactly as an ordinary WeakMap
* otherwise.
*
* @param {function} createItem
* A function which will be called in order to create the value for any
* key which does not exist, the first time it is accessed. The
* function receives, as its only argument, the key being created.
*/
class DefaultWeakMap extends WeakMap {
constructor(createItem, items = undefined) {
super(items);
this.createItem = createItem;
}
get(key) {
if (!this.has(key)) {
this.set(key, this.createItem(key));
}
return super.get(key);
}
}
/**
* Returns true if the given object is an object with a `then` method, and can
* therefore be assumed to behave as a Promise.
*
* @param {*} value The value to test.
* @returns {boolean} True if the value is thenable.
*/
const isThenable = value => {
return value && typeof value === "object" && typeof value.then === "function";
};
/**
* Creates and returns a function which, when called, will resolve or reject
* the given promise based on how it is called:
*
* - If, when called, `chrome.runtime.lastError` contains a non-null object,
* the promise is rejected with that value.
* - If the function is called with exactly one argument, the promise is
* resolved to that value.
* - Otherwise, the promise is resolved to an array containing all of the
* function's arguments.
*
* @param {object} promise
* An object containing the resolution and rejection functions of a
* promise.
* @param {function} promise.resolve
* The promise's resolution function.
* @param {function} promise.rejection
* The promise's rejection function.
*
* @returns {function}
* The generated callback function.
*/
const makeCallback = promise => {
return (...callbackArgs) => {
if (chrome.runtime.lastError) {
promise.reject(chrome.runtime.lastError);
} else if (callbackArgs.length === 1) {
promise.resolve(callbackArgs[0]);
} else {
promise.resolve(callbackArgs);
}
};
};
/**
* Creates a wrapper function for a method with the given name and metadata.
*
* @param {string} name
* The name of the method which is being wrapped.
* @param {object} metadata
* Metadata about the method being wrapped.
* @param {integer} metadata.minArgs
* The minimum number of arguments which must be passed to the
* function. If called with fewer than this number of arguments, the
* wrapper will raise an exception.
* @param {integer} metadata.maxArgs
* The maximum number of arguments which may be passed to the
* function. If called with more than this number of arguments, the
* wrapper will raise an exception.
*
* @returns {function(object, ...*)}
* The generated wrapper function.
*/
const wrapAsyncFunction = (name, metadata) => {
const pluralizeArguments = numArgs => numArgs == 1 ? "argument" : "arguments";
return function asyncFunctionWrapper(target, ...args) {
if (args.length < metadata.minArgs) {
throw new Error(`Expected at least ${metadata.minArgs} ${pluralizeArguments(metadata.minArgs)} for ${name}(), got ${args.length}`);
}
if (args.length > metadata.maxArgs) {
throw new Error(`Expected at most ${metadata.maxArgs} ${pluralizeArguments(metadata.maxArgs)} for ${name}(), got ${args.length}`);
}
return new Promise((resolve, reject) => {
target[name](...args, makeCallback({ resolve, reject }));
});
};
};
/**
* Wraps an existing method of the target object, so that calls to it are
* intercepted by the given wrapper function. The wrapper function receives,
* as its first argument, the original `target` object, followed by each of
* the arguments passed to the orginal method.
*
* @param {object} target
* The original target object that the wrapped method belongs to.
* @param {function} method
* The method being wrapped. This is used as the target of the Proxy
* object which is created to wrap the method.
* @param {function} wrapper
* The wrapper function which is called in place of a direct invocation
* of the wrapped method.
*
* @returns {Proxy<function>}
* A Proxy object for the given method, which invokes the given wrapper
* method in its place.
*/
const wrapMethod = (target, method, wrapper) => {
return new Proxy(method, {
apply(targetMethod, thisObj, args) {
return wrapper.call(thisObj, target, ...args);
}
});
};
let hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty);
/**
* Wraps an object in a Proxy which intercepts and wraps certain methods
* based on the given `wrappers` and `metadata` objects.
*
* @param {object} target
* The target object to wrap.
*
* @param {object} [wrappers = {}]
* An object tree containing wrapper functions for special cases. Any
* function present in this object tree is called in place of the
* method in the same location in the `target` object tree. These
* wrapper methods are invoked as described in {@see wrapMethod}.
*
* @param {object} [metadata = {}]
* An object tree containing metadata used to automatically generate
* Promise-based wrapper functions for asynchronous. Any function in
* the `target` object tree which has a corresponding metadata object
* in the same location in the `metadata` tree is replaced with an
* automatically-generated wrapper function, as described in
* {@see wrapAsyncFunction}
*
* @returns {Proxy<object>}
*/
const wrapObject = (target, wrappers = {}, metadata = {}) => {
let cache = Object.create(null);
let handlers = {
has(target, prop) {
return prop in target || prop in cache;
},
get(target, prop, receiver) {
if (prop in cache) {
return cache[prop];
}
if (!(prop in target)) {
return undefined;
}
let value = target[prop];
if (typeof value === "function") {
// This is a method on the underlying object. Check if we need to do
// any wrapping.
if (typeof wrappers[prop] === "function") {
// We have a special-case wrapper for this method.
value = wrapMethod(target, target[prop], wrappers[prop]);
} else if (hasOwnProperty(metadata, prop)) {
// This is an async method that we have metadata for. Create a
// Promise wrapper for it.
let wrapper = wrapAsyncFunction(prop, metadata[prop]);
value = wrapMethod(target, target[prop], wrapper);
} else {
// This is a method that we don't know or care about. Return the
// original method, bound to the underlying object.
value = value.bind(target);
}
} else if (typeof value === "object" && value !== null && (hasOwnProperty(wrappers, prop) || hasOwnProperty(metadata, prop))) {
// This is an object that we need to do some wrapping for the children
// of. Create a sub-object wrapper for it with the appropriate child
// metadata.
value = wrapObject(value, wrappers[prop], metadata[prop]);
} else {
// We don't need to do any wrapping for this property,
// so just forward all access to the underlying object.
Object.defineProperty(cache, prop, {
configurable: true,
enumerable: true,
get() {
return target[prop];
},
set(value) {
target[prop] = value;
}
});
return value;
}
cache[prop] = value;
return value;
},
set(target, prop, value, receiver) {
if (prop in cache) {
cache[prop] = value;
} else {
target[prop] = value;
}
return true;
},
defineProperty(target, prop, desc) {
return Reflect.defineProperty(cache, prop, desc);
},
deleteProperty(target, prop) {
return Reflect.deleteProperty(cache, prop);
}
};
return new Proxy(target, handlers);
};
/**
* Creates a set of wrapper functions for an event object, which handles
* wrapping of listener functions that those messages are passed.
*
* A single wrapper is created for each listener function, and stored in a
* map. Subsequent calls to `addListener`, `hasListener`, or `removeListener`
* retrieve the original wrapper, so that attempts to remove a
* previously-added listener work as expected.
*
* @param {DefaultWeakMap<function, function>} wrapperMap
* A DefaultWeakMap object which will create the appropriate wrapper
* for a given listener function when one does not exist, and retrieve
* an existing one when it does.
*
* @returns {object}
*/
const wrapEvent = wrapperMap => ({
addListener(target, listener, ...args) {
target.addListener(wrapperMap.get(listener), ...args);
},
hasListener(target, listener) {
return target.hasListener(wrapperMap.get(listener));
},
removeListener(target, listener) {
target.removeListener(wrapperMap.get(listener));
}
});
const onMessageWrappers = new DefaultWeakMap(listener => {
if (typeof listener !== "function") {
return listener;
}
/**
* Wraps a message listener function so that it may send responses based on
* its return value, rather than by returning a sentinel value and calling a
* callback. If the listener function returns a Promise, the response is
* sent when the promise either resolves or rejects.
*
* @param {*} message
* The message sent by the other end of the channel.
* @param {object} sender
* Details about the sender of the message.
* @param {function(*)} sendResponse
* A callback which, when called with an arbitrary argument, sends
* that value as a response.
* @returns {boolean}
* True if the wrapped listener returned a Promise, which will later
* yield a response. False otherwise.
*/
return function onMessage(message, sender, sendResponse) {
let result = listener(message, sender);
if (isThenable(result)) {
result.then(sendResponse, error => {
console.error(error);
sendResponse(error);
});
return true;
} else if (result !== undefined) {
sendResponse(result);
}
};
});
const staticWrappers = {
runtime: {
onMessage: wrapEvent(onMessageWrappers)
}
};
return wrapObject(chrome, staticWrappers, apiMetadata);
};
// The build process adds a UMD wrapper around this file, which makes the
// `module` variable available.
module.exports = wrapAPIs(); // eslint-disable-line no-undef
} else {
module.exports = browser; // eslint-disable-line no-undef
}
});
//# sourceMappingURL=browser-polyfill.js.map
|
var assert = require("chai").assert;
var request = require("supertest");
var server = require("../app");
var app;
describe('Server API Test Suite', function () {
before(function (done) {
this.timeout(15000);
app = server();
done();
});
// test case for checking if server is up
describe('Server Root API Test', function () {
it('should return Server running...', function (done) {
request(app)
.get("/")
.end(function (err, res) {
assert.isTrue(res.text === 'Server running...');
done();
});
});
});
// test case for validating ical url api
describe('/validate POST API Test Suite', function () {
it('should respond with 404 status code', function (done) {
request(app)
.post("/validate")
.send({'url': ''})
.end(function (err, res) {
assert.equal(404, JSON.parse(res.text).statusCode);
done();
});
});
it('res.statusCode should be 200', function (done) {
request(app)
.post("/validate")
.send({'url': 'http://www.google.com/calendar/ical/49jqotgq8bcgt06tj7040hk2mk%40group.calendar.google.com/public/basic.ics'})
.end(function (err, res) {
assert.equal(200, JSON.parse(res.text).statusCode);
done();
});
});
it('res.statusCode should be 500', function (done) {
request(app)
.post("/validate")
.send({'url': 'http://www.google.com/calendar/abc'})// some random url apart from valid .ics url
.end(function (err, res) {
assert.equal(500, JSON.parse(res.text).statusCode);
done();
});
});
});
// test case for fetching events from ical url
describe('/events POST API Test Suite', function () {
it('should respond with 404 status code and null events', function (done) {
request(app)
.post("/events")
.send({'url': ''})
.end(function (err, res) {
assert.equal(404, JSON.parse(res.text).statusCode);
assert.isNull(JSON.parse(res.text).events, "Events list should be an array");
done();
});
});
it('res.statusCode should be 200 and array of events', function (done) {
request(app)
.post("/events")
.send({'url': 'http://www.google.com/calendar/ical/49jqotgq8bcgt06tj7040hk2mk%40group.calendar.google.com/public/basic.ics'})
.end(function (err, res) {
assert.equal(200, JSON.parse(res.text).statusCode);
assert.isArray(JSON.parse(res.text).events, "Events list should be an array");
assert.isNumber(JSON.parse(res.text).totalEvents, "Total number of events should be a number");
done();
});
});
it('res.statusCode should be 500 and null events', function (done) {
request(app)
.post("/events")
.send({'url': 'http://www.google.com/calendar/abc'})// some random url apart from valid .ics url
.end(function (err, res) {
assert.equal(500, JSON.parse(res.text).statusCode);
assert.isNull(JSON.parse(res.text).events, "Events list should be an array");
done();
});
});
});
// test case for fetching single event with given index from ical url
describe('/event POST API Test Suite', function () {
it('should respond with 404 status code and null event', function (done) {
request(app)
.post("/event")
.send({'url': '','index': 1})
.end(function (err, res) {
assert.equal(404, JSON.parse(res.text).statusCode);
assert.isNull(JSON.parse(res.text).event, "Event should be an object");
done();
});
});
it('res.statusCode should be 200 and a single object of event', function (done) {
request(app)
.post("/event")
.send({
'url': 'http://www.google.com/calendar/ical/49jqotgq8bcgt06tj7040hk2mk%40group.calendar.google.com/public/basic.ics',
'index': 1
})
.end(function (err, res) {
assert.equal(200, JSON.parse(res.text).statusCode);
assert.isObject(JSON.parse(res.text).event, "Event should be an object");
done();
});
});
it('res.statusCode should be 500 and null event', function (done) {
request(app)
.post("/event")
.send({'url': 'http://www.google.com/calendar/abc','index': 1})// some random url apart from valid .ics url
.end(function (err, res) {
assert.equal(500, JSON.parse(res.text).statusCode);
assert.isNull(JSON.parse(res.text).event, "Event should be an object");
done();
});
});
});
}); |
// This code demonstrates making point and segment queries in a space.
//
// Take a look at update(), below for the calls to space.*Query.
var Query = function() {
Demo.call(this);
var space = this.space;
space.iterations = 5;
{ // add a fat segment
var mass = 1;
var length = 100;
var a = v(-length/2, 0), b = v(length/2, 0);
var body = space.addBody(new cp.Body(mass, cp.momentForSegment(mass, a, b)));
body.setPos(v(320, 340));
space.addShape(new cp.SegmentShape(body, a, b, 20));
}
{ // add a static segment
space.addShape(new cp.SegmentShape(space.staticBody, v(320, 540), v(620, 240), 0));
}
{ // add a pentagon
var mass = 1;
var NUM_VERTS = 5;
var verts = new Array(NUM_VERTS * 2);
for(var i=0; i<NUM_VERTS*2; i+=2){
var angle = -Math.PI*i/NUM_VERTS;
verts[i] = 30*Math.cos(angle);
verts[i+1] = 30*Math.sin(angle);
}
var body = space.addBody(new cp.Body(mass, cp.momentForPoly(mass, verts, v(0,0))));
body.setPos(v(350+60, 220+60));
space.addShape(new cp.PolyShape(body, verts, v(0,0)));
}
{ // add a circle
var mass = 1;
var r = 20;
var body = space.addBody(new cp.Body(mass, cp.momentForCircle(mass, 0, r, v(0,0))));
body.setPos(v(320+100, 240+120));
space.addShape(new cp.CircleShape(body, r, v(0,0)));
}
this.drawSegment = function(start, end, style) {
var ctx = this.ctx;
ctx.beginPath();
var startT = this.point2canvas(start);
var endT = this.point2canvas(end);
ctx.moveTo(startT.x, startT.y);
ctx.lineTo(endT.x, endT.y);
ctx.lineWidth = 1;
ctx.strokeStyle = style;
ctx.stroke();
};
this.drawBB = function(bb, fillStyle, strokeStyle) {
var ctx = this.ctx;
var p = this.point2canvas(v(bb.l, bb.t));
var width = this.scale * (bb.r - bb.l);
var height = this.scale * (bb.t - bb.b);
if(fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fillRect(p.x, p.y, width, height);
}
if(strokeStyle) {
ctx.strokeStyle = strokeStyle;
ctx.strokeRect(p.x, p.y, width, height);
}
};
};
Query.prototype = Object.create(Demo.prototype);
Query.prototype.draw = function() {
Demo.prototype.draw.apply(this);
var ctx = this.ctx;
var start = v(320, 240);
var end = this.mouse;
// Draw a green line from start to end.
this.drawSegment(start, end, 'green');
this.message = "Query: Dist(" + Math.floor(v.dist(start, end)) + ") Point " + v.str(end) + ", ";
var info = this.space.segmentQueryFirst(start, end, cp.ALL_LAYERS, cp.NO_GROUP);
if(info) {
var point = info.hitPoint(start, end);
// Draw red over the occluded part of the query
this.drawSegment(point, end, 'red');
// Draw a little blue surface normal
this.drawSegment(point, v.add(point, v.mult(info.n, 16)), 'blue');
// Draw a little red dot on the hit point.
//ChipmunkDebugDrawPoints(3, 1, &point, RGBAColor(1,0,0,1));
this.message += "Segment Query: Dist(" + Math.floor(info.hitDist(start, end)) + ") Normal " + v.str(info.n);
//messageCursor += sprintf(messageCursor, "Segment Query: Dist(%f) Normal%s", cpSegmentQueryHitDist(start, end, info), cpvstr(info.n));
} else {
this.message += "Segment Query: (None)";
}
var nearestInfo = this.space.nearestPointQueryNearest(this.mouse, 100, cp.ALL_LAYERS, cp.NO_GROUP);
if (nearestInfo) {
this.drawSegment(this.mouse, nearestInfo.p, "grey");
// Draw a red bounding box around the shape under the mouse.
if(nearestInfo.d < 0) this.drawBB(nearestInfo.shape.getBB(), null, 'red');
}
};
Query.prototype.update = function(){};
addDemo('Query', Query);
|
'use strict';
var convert = require('./convert'),
func = convert('bindAll', require('../bindAll'));
func.placeholder = require('./placeholder');
module.exports = func;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2JpbmRBbGwuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxJQUFJLFVBQVUsUUFBUSxXQUFSLENBQWQ7SUFDSSxPQUFPLFFBQVEsU0FBUixFQUFtQixRQUFRLFlBQVIsQ0FBbkIsQ0FEWDs7QUFHQSxLQUFLLFdBQUwsR0FBbUIsUUFBUSxlQUFSLENBQW5CO0FBQ0EsT0FBTyxPQUFQLEdBQWlCLElBQWpCIiwiZmlsZSI6ImJpbmRBbGwuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgY29udmVydCA9IHJlcXVpcmUoJy4vY29udmVydCcpLFxuICAgIGZ1bmMgPSBjb252ZXJ0KCdiaW5kQWxsJywgcmVxdWlyZSgnLi4vYmluZEFsbCcpKTtcblxuZnVuYy5wbGFjZWhvbGRlciA9IHJlcXVpcmUoJy4vcGxhY2Vob2xkZXInKTtcbm1vZHVsZS5leHBvcnRzID0gZnVuYztcbiJdfQ== |
version https://git-lfs.github.com/spec/v1
oid sha256:147bcc2621052074f5656b1166435690c7ea9c7b543f124e75520c5200b326ad
size 15563
|
import installQuasar from './install-quasar.js'
import lang from './lang.js'
import iconSet from './icon-set.js'
import * as components from './components.js'
import * as directives from './directives.js'
export * from './components.js'
export * from './directives.js'
export * from './plugins.js'
export * from './composables.js'
export * from './utils.js'
export const Quasar = {
version: __QUASAR_VERSION__,
install (app, opts, ssrContext) {
installQuasar(
app,
{ components, directives, ...opts },
ssrContext
)
},
lang,
iconSet
}
|
'use strict';
angular.module('demoApp', ['nya.bootstrap.select', 'pascalprecht.translate'])
.config(function($translateProvider, nyaBsConfigProvider) {
$translateProvider.translations('en', {
LANG: 'English',
NOTHING: 'Nothing Selected!'
});
$translateProvider.translations('jp', {
LANG: '日本語',
NOTHING: '未選択'
});
})
.controller('MainCtrl', function($scope, $translate){
$translate.use('en');
$scope.changeLocale = function(locale) {
$translate.use(locale);
};
$scope.options1 = [
'Alpha',
'Bravo',
'Charlie',
'Golf',
'Hotel',
'Juliet',
'Kilo',
'Lima'
];
});
|
/**
* Copyright 2015 aixigo AG
* Released under the MIT license.
* http://laxarjs.org/license
*/
var path = require( 'path' );
var grunt = require( 'grunt' );
var runTask = require( 'grunt-run-task' );
var expect = require( 'expect.js' );
var run = require( './lib/run-elsewhere' );
var spyOn = require( './lib/spy-on' );
describe( 'the laxar-configure task', function() {
'use strict';
var dir = {
fixtures: 'tasks/spec/fixtures',
expected: 'tasks/spec/expected',
actual: 'tmp'
};
var project = {
flow: 'application/flow/flow.json',
work: 'var/flows'
};
var paths = {
fixtures: {
flow: path.join( dir.fixtures, project.flow )
},
expected: {
result: path.join( dir.expected, project.work, 'my-flow/work/task-configuration.json' )
},
actual: {
flow: path.join( dir.actual, project.flow ),
result: path.join( dir.actual, project.work, 'my-flow/work/task-configuration.json' )
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////
describe( 'configured for a single flow', function() {
var taskConfig = {
options: {
base: dir.actual,
workDirectory: project.work,
flows: [
{ target: 'my-flow', src: project.flow }
]
}
};
////////////////////////////////////////////////////////////////////////////////////////////////////////
var configSpy;
before( function( done ) {
// remove result (from previous run or from fixture to another task).
if( grunt.file.exists( paths.actual.result ) ) {
grunt.file.delete( paths.actual.result );
}
configSpy = spyOn( runTask.grunt.config, 'set' );
run( 'laxar-configure', taskConfig, dir.actual, done );
} );
after( function() {
configSpy.reset();
} );
////////////////////////////////////////////////////////////////////////////////////////////////////////
it( 'writes task configuration for grunt-laxar building blocks to a file', function() {
expect( grunt.file.exists( paths.actual.result ) ).to.be( true );
} );
////////////////////////////////////////////////////////////////////////////////////////////////////////
[
'laxar-build-flow',
'laxar-artifacts',
'laxar-dependencies',
'laxar-configure-watch',
'laxar-resources',
'laxar-dist-flow',
'laxar-dist-css',
'laxar-dist-js'
].forEach( function( taskName ) {
it( 'configures the building block ' + taskName + ' at runtime', function() {
expect( configSpy.calls.filter( configures( taskName + '.my-flow' ) ) ).not.to.be.empty();
} );
} );
////////////////////////////////////////////////////////////////////////////////////////////////////////
[
'connect.laxar-develop.options.port',
'connect.laxar-test.options.port',
'connect.options.livereload',
'watch.options.livereload',
'karma.options.proxies./base'
].forEach( function( key ) {
it( 'configures the ' + key + ' at runtime', function() {
expect( configSpy.calls.filter( configures( key ) ) ).not.to.be.empty();
} );
} );
////////////////////////////////////////////////////////////////////////////////////////////////////////
it( 'generates the correct task configuration', function() {
var actual = grunt.file.readJSON( paths.actual.result );
var expected = grunt.file.readJSON( paths.expected.result );
expect( actual ).to.eql( expected );
} );
} );
///////////////////////////////////////////////////////////////////////////////////////////////////////////
function configures( task ) {
return function ( callargs ) {
return callargs[ 0 ] === task;
};
}
} );
|
/**
* @license
* Visual Blocks Editor
*
* Copyright 2012 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Image field. Used for pictures, icons, etc.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
goog.provide('Blockly.FieldImage');
goog.require('Blockly.Field');
goog.require('Blockly.utils');
goog.require('goog.math.Size');
/**
* Class for an image on a block.
* @param {string} src The URL of the image.
* @param {number} width Width of the image.
* @param {number} height Height of the image.
* @param {string=} opt_alt Optional alt text for when block is collapsed.
* @param {Function=} opt_onClick Optional function to be called when the image
* is clicked. If opt_onClick is defined, opt_alt must also be defined.
* @extends {Blockly.Field}
* @constructor
*/
Blockly.FieldImage = function(src, width, height, opt_alt, opt_onClick) {
this.sourceBlock_ = null;
// Ensure height and width are numbers. Strings are bad at math.
this.height_ = Number(height);
this.width_ = Number(width);
this.size_ = new goog.math.Size(this.width_,
this.height_ + 2 * Blockly.BlockSvg.INLINE_PADDING_Y);
this.text_ = opt_alt || '';
this.setValue(src);
if (typeof opt_onClick == 'function') {
this.clickHandler_ = opt_onClick;
}
};
goog.inherits(Blockly.FieldImage, Blockly.Field);
/**
* Construct a FieldImage from a JSON arg object,
* dereferencing any string table references.
* @param {!Object} options A JSON object with options (src, width, height, and
* alt).
* @returns {!Blockly.FieldImage} The new field instance.
* @package
* @nocollapse
*/
Blockly.FieldImage.fromJson = function(options) {
var src = Blockly.utils.replaceMessageReferences(options['src']);
var width = Number(Blockly.utils.replaceMessageReferences(options['width']));
var height =
Number(Blockly.utils.replaceMessageReferences(options['height']));
var alt = Blockly.utils.replaceMessageReferences(options['alt']);
return new Blockly.FieldImage(src, width, height, alt);
};
/**
* Editable fields are saved by the XML renderer, non-editable fields are not.
*/
Blockly.FieldImage.prototype.EDITABLE = false;
/**
* Install this image on a block.
*/
Blockly.FieldImage.prototype.init = function() {
if (this.fieldGroup_) {
// Image has already been initialized once.
return;
}
// Build the DOM.
/** @type {SVGElement} */
this.fieldGroup_ = Blockly.utils.createSvgElement('g', {}, null);
if (!this.visible_) {
this.fieldGroup_.style.display = 'none';
}
/** @type {SVGElement} */
this.imageElement_ = Blockly.utils.createSvgElement(
'image',
{
'height': this.height_ + 'px',
'width': this.width_ + 'px'
},
this.fieldGroup_);
this.setValue(this.src_);
this.sourceBlock_.getSvgRoot().appendChild(this.fieldGroup_);
// Configure the field to be transparent with respect to tooltips.
this.setTooltip(this.sourceBlock_);
Blockly.Tooltip.bindMouseEvents(this.imageElement_);
this.maybeAddClickHandler_();
};
/**
* Dispose of all DOM objects belonging to this text.
*/
Blockly.FieldImage.prototype.dispose = function() {
if (this.fieldGroup_) {
Blockly.utils.removeNode(this.fieldGroup_);
this.fieldGroup_ = null;
}
this.imageElement_ = null;
};
/**
* Bind events for a mouse down on the image, but only if a click handler has
* been defined.
* @private
*/
Blockly.FieldImage.prototype.maybeAddClickHandler_ = function() {
if (this.clickHandler_) {
this.mouseDownWrapper_ =
Blockly.bindEventWithChecks_(
this.fieldGroup_, 'mousedown', this, this.onMouseDown_);
}
};
/**
* Change the tooltip text for this field.
* @param {string|!Element} newTip Text for tooltip or a parent element to
* link to for its tooltip.
*/
Blockly.FieldImage.prototype.setTooltip = function(newTip) {
this.imageElement_.tooltip = newTip;
};
/**
* Get the source URL of this image.
* @return {string} Current text.
* @override
*/
Blockly.FieldImage.prototype.getValue = function() {
return this.src_;
};
/**
* Set the source URL of this image.
* @param {?string} src New source.
* @override
*/
Blockly.FieldImage.prototype.setValue = function(src) {
if (src === null) {
// No change if null.
return;
}
this.src_ = src;
if (this.imageElement_) {
this.imageElement_.setAttributeNS('http://www.w3.org/1999/xlink',
'xlink:href', src || '');
}
};
/**
* Set the alt text of this image.
* @param {?string} alt New alt text.
* @override
*/
Blockly.FieldImage.prototype.setText = function(alt) {
if (alt === null) {
// No change if null.
return;
}
this.text_ = alt;
};
/**
* Images are fixed width, no need to render.
* @private
*/
Blockly.FieldImage.prototype.render_ = function() {
// NOP
};
/**
* Images are fixed width, no need to render even if forced.
*/
Blockly.FieldImage.prototype.forceRerender = function() {
// NOP
};
/**
* Images are fixed width, no need to update.
* @private
*/
Blockly.FieldImage.prototype.updateWidth = function() {
// NOP
};
/**
* If field click is called, and click handler defined,
* call the handler.
*/
Blockly.FieldImage.prototype.showEditor_ = function() {
if (this.clickHandler_) {
this.clickHandler_(this);
}
};
Blockly.Field.register('field_image', Blockly.FieldImage);
|
import { assert } from 'chai';
import { State } from '../src';
describe('Immutability', () => {
it('Map', () => {
const innerStruct = {
lesson: 1,
module: 1,
};
const test = new State.Map({
id: 1,
name: 'John',
progress: innerStruct,
});
const result = test.get();
result.id = 10;
result.progress.lesson = 2;
result.name = 'Mark';
assert.deepEqual(test.get(), {
id: 1,
name: 'John',
progress: {
lesson: 1,
module: 1,
},
});
assert.deepEqual(result, {
id: 10,
name: 'Mark',
progress: {
lesson: 2,
module: 1,
},
});
assert.deepEqual(innerStruct, {
lesson: 1,
module: 1,
});
});
it('List', () => {
const test = new State.List(['one', 'two']);
const result = test.get();
result.push('three');
assert.deepEqual(test.get(), ['one', 'two']);
});
});
|
var io = require('socket.io').listen(4242);
io.set('log level', 1);
var Cube = require('./Cube');
var cubes = {};
io.sockets.on('connection', function (socket) {
// Envía la lista de cubos actual al nuevo jugador
for (var playerId in cubes) {
socket.emit('cubeUpdate', cubes[playerId]);
}
// Crea el nuevo cubo y lo envía a todos
var cube = new Cube (socket.id);
cubes[socket.id] = cube;
io.sockets.emit('cubeUpdate', cube);
socket.on('cubeUpdate', function (cubeData) {
var cube = cubes[socket.id];
if (cube !== undefined) cube.updateWithCubeData(cubeData);
socket.broadcast.emit('cubeUpdate', cube);
});
socket.on('disconnect', function () {
console.log(socket.id + " has disconnected from the server!");
delete cubes[socket.id];
io.sockets.emit('cubeDisconnect', socket.id);
});
}); |
axboot.promise = function () {
/**
* @Class axboot.promise
* @example
* ```js
* axboot.promise()
* .then(function (ok, fail, data) {
* $.ajax({
* url: "/api/v1/connections",
* callback: function (res) {
* ok(res); // data 로 전달
* },
* onError: function (res) {
* fail(res);
* }
* });
* })
* .then(function (ok, fail, data) {
* $.ajax({
* url: "/api/v1/login",
* data: data,
* callback: function (res) {
* ok(res);
* },
* onError: function (res) {
* fail(res);
* }
* });
* })
* .then(function (ok, fail, data) {
* console.log("success");
* })
* .catch(function (res) {
* alert(res.message);
* });
* ```
*/
const myClass = function () {
this.busy = false;
this.queue = [];
this.then = function (fn) {
this.queue.push(fn);
this.exec({});
return this;
};
this.exec = function (data) {
if (this.busy) return this;
var Q = this.queue.shift(),
self = this;
if (Q) {
this.busy = true;
try {
Q(
function (a) {
self.busy = false;
self.exec(a);
},
function (e) {
self._catch(e);
},
data || {}
);
}
catch (e) {
this._catch(e);
}
} else {
this.busy = false;
}
};
this.catch = function (fn) {
this._catch = fn;
};
};
return new myClass();
}; |
/**
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import { mount, shallow } from 'enzyme'; // eslint-disable-line import/no-extraneous-dependencies
/** Create the IntlProvider to retrieve context for wrapping around. */
function createIntlContext(messages, locale) {
const intlProvider = new IntlProvider({ messages, locale }, {});
const { intl } = intlProvider.getChildContext();
return intl;
}
/** When using React-Intl `injectIntl` on components, props.intl is required. */
function nodeWithIntlProp(node, messages = {}, locale = 'en') {
return React.cloneElement(node, { intl: createIntlContext(messages, locale) });
}
/**
* Create a shadow renderer that wraps a node with Intl provider context.
* @param {ReactComponent} node - Any React Component
* @param {Object} context
* @param {Object} messages - A map with keys (id) and messages (value)
* @param {string} locale - Locale string
*/
export function shallowWithIntl(node, { context } = {}, messages = {}, locale = 'en') {
return shallow(
nodeWithIntlProp(node),
{
context: Object.assign({}, context, { intl: createIntlContext(messages, locale) }),
}
);
}
/**
* Mount the node with Intl provider context.
* @param {Component} node - Any React Component
* @param {Object} context
* @param {Object} messages - A map with keys (id) and messages (value)
* @param {string} locale - Locale string
*/
export function mountWithIntl(node, { context, childContextTypes } = {}, messages = {}, locale = 'en') {
return mount(
nodeWithIntlProp(node),
{
context: Object.assign({}, context, { intl: createIntlContext(messages, locale) }),
childContextTypes: Object.assign({}, { intl: intlShape }, childContextTypes)
}
);
}
|
import React from 'react';
import './UserHeaderLoading.less';
const UserHeaderLoading = () =>
(<div className="UserHeaderLoading">
<div className="UserHeaderLoading__container">
<div className="ant-card-loading-block UserHeaderLoading__avatar" style={{ width: '100px', height: '100px' }} />
<div className="UserHeaderLoading__user">
<div className="ant-card-loading-block" style={{ width: '160px', height: '32px', marginBottom: 0, marginLeft: 0 }} />
<div className="ant-card-loading-block" style={{ width: '120px', height: '20px', marginLeft: 0 }} />
</div>
</div>
</div>);
export default UserHeaderLoading;
|
'use strict';
(function (angular) {
angular.module('seminarNotesPluginDesign')
.constant('TAG_NAMES', {
SEMINAR_INFO: 'seminarInfo',
SEMINAR_ITEMS: "seminarItems",
SEMINAR_BOOKMARKS: "seminarBookmarks"
})
.constant('STATUS_CODE', {
INSERTED: 'inserted',
UPDATED: 'updated',
NOT_FOUND: 'NOTFOUND',
UNDEFINED_DATA: 'UNDEFINED_DATA',
UNDEFINED_OPTIONS: 'UNDEFINED_OPTIONS',
UNDEFINED_ID: 'UNDEFINED_ID',
ITEM_ARRAY_FOUND: 'ITEM_ARRAY_FOUND',
NOT_ITEM_ARRAY: 'NOT_ITEM_ARRAY'
})
.constant('STATUS_MESSAGES', {
UNDEFINED_DATA: 'Undefined data provided',
UNDEFINED_OPTIONS: 'Undefined options provided',
UNDEFINED_ID: 'Undefined id provided',
NOT_ITEM_ARRAY: 'Array of Items not provided',
ITEM_ARRAY_FOUND: 'Array of Items provided'
})
.constant('LAYOUTS', {
itemListLayout: [
{name: "Item_List_1"},
{name: "Item_List_2"},
{name: "Item_List_3"},
{name: "Item_List_4"},
{name: "Item_List_5"}
]
});
})(window.angular); |
describe('Set the `data-eq-state` attribute based on the element width and its CSS styling', function () {
var elem = document.createElement('div'),
body = document.querySelector('body'),
style = document.createElement('style'),
head = document.querySelector('head'),
sizes = [],
css,
result;
body.appendChild(elem);
elem.setAttribute('id', 'foo');
head.appendChild(style);
style.type = 'text/css';
function random(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
beforeEach(function () {
// Generate Sizes
sizes.push(random(50, 400));
sizes.push(random(405, 600));
sizes.push(random(605, 900));
// Remove State and Width
elem.removeAttribute('data-eq-state');
body.style.width = '0px';
style.innerHTML = '';
// Set new sizes
css = 'html:before { display: none; content: "#foo"; }';
css += '#foo:before { display: none; ';
css += 'content: "small: ' + sizes[0] + ', medium: ' + sizes[1] + ', large: ' + sizes[2] + '"; }';
style.appendChild(document.createTextNode(css));
// Reset result
result = null;
});
//////////////////////////////
// No Sizes
//////////////////////////////
it('should have no state if its width is smaller than smallest size', function () {
body.style.width = (sizes[0] - 1) + 'px';
eqjs.refreshNodes();
eqjs.query(undefined, function () {
result = elem.getAttribute('data-eq-state');
expect(result).toBe(null);
});
});
//////////////////////////////
// Small Sizes
//////////////////////////////
it('should be `small` when its width is equal to its smallest size', function () {
body.style.width = (sizes[0]) + 'px';
eqjs.refreshNodes();
eqjs.query(undefined, function () {
result = elem.getAttribute('data-eq-state');
expect(result).toBe('small');
});
});
it('should be `small` when its width is larger to its smallest size but smaller than its `medium` size', function () {
body.style.width = (sizes[0] + 1) + 'px';
eqjs.refreshNodes();
eqjs.query(undefined, function () {
result = elem.getAttribute('data-eq-state');
expect(result).toBe('small');
});
});
//////////////////////////////
// Medium Sizes
//////////////////////////////
it('should be `small medium` when its width is equal to its smallest size', function () {
body.style.width = (sizes[1]) + 'px';
eqjs.refreshNodes();
eqjs.query(undefined, function () {
result = elem.getAttribute('data-eq-state');
expect(result).toBe('small medium');
});
});
it('should be `small medium` when its width is larger to its medium size but smaller than its `larger` size', function () {
body.style.width = (sizes[1] + 1) + 'px';
eqjs.refreshNodes();
eqjs.query(undefined, function () {
result = elem.getAttribute('data-eq-state');
expect(result).toBe('small medium');
});
});
//////////////////////////////
// Large Sizes
//////////////////////////////
it('should be `small medium large` when its width is equal to its largest size', function () {
body.style.width = (sizes[2]) + 'px';
eqjs.refreshNodes();
eqjs.query(undefined, function () {
result = elem.getAttribute('data-eq-state');
expect(result).toBe('small medium large');
});
});
it('should be `small medium large` when its width is larger to its largest size', function () {
body.style.width = (sizes[2] + 1) + 'px';
eqjs.refreshNodes();
eqjs.query(undefined, function () {
result = elem.getAttribute('data-eq-state');
expect(result).toBe('small medium large');
});
});
});
|
/**
* JQueryUI widget for a block of text with many words to tag
* Version: 1.1.9
*
* Widget should be attached the the div containing the words to which a sense must be given.
*
* Options:
*
* menus : jQuery element hosting the menus that correspond to the words
* wordsContent: string with possible values {text|tile} which indicate how the words
* will be displayed in the "menus" element. When using the "tile" option,
* the useToolTip option should be "false". (default: "text")
* senseMenuOptions: sense menu options. May include options for OWL carousel.
* useToolTip: Boolean indicating whether the tooltip widget should be used
* to display the tagged senses. (default: true)
* hideUntaggable: some words can be identified as untaggable when the menu is generated
* by the backend. Those elements can be hidden using this option.
* (default: false)
* sensesel : Callback when a sense selection is made for one word. The event data is:
* - $selTile - selected sense tile - .idl-tile-container
* - $prevTile - previously selected sense tile or undefined if none
* - $text - text element for which a sense was selected
* - selStart - start offset of the word for new sense assigned to the text
* - selEnd - end offset for new sense
* - prevStart - start offset of the previous sense
* - prevEnd - end offset of the previous sense
* - allset - indicates that all words are tagged
* If the callback returns true, the text is updated with the word of the
* sense selected. If it returns false, the text is unchanged.
*
* createsel : Callback when user wishes to create a new sense. The event data is:
* - $selTile - selected create sense tile - .idl-tile-container
* - $prevTile - previously selected sense tile or undefined if none
* - $text - text element for which a sense creation is requested
*
* beforeOpen: Callback before menu is opened
* afterClose: Callback after menu is closed
*
* Important classes
* idl-menu-word - class assigned to all words for which a menu is available
* idl-untagged - initial state for all .idl-menu-word. Removed when a sense becomes available for it
* idl-tagged - added to .idl-menu-word when a sense is selected for it or available from initial conditions
* idl-mantagged - added to .idl-menu-word when a sense is manually selected for it
* idl-active - added to .idl-menu-word when a sense menu is open for it
* idl-def-show-icon - background-image of which is used to set the icon of show definition buttons.
* idl-def-hide-icon - background-image of which is used to set the icon of hide definition buttons.
*
* Available for use under the MIT License (http://en.wikipedia.org/wiki/MIT_License)
*
* Copyright (c) 2014 by Idilia
*
* 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.
*/
if (typeof Object.create !== "function") {
Object.create = function (obj) {
function F() {}
F.prototype = obj;
return new F();
};
}
(function ($, window, document) {
/* Prevents the installed html click handler from closing the menu. This flag is true
* only momentarily and in two distinct scenarios:
* 1.the html click handler is installed on a click event that will be seen by the
* handler but the menu must not be closed.
* 2.the closeOnSelect option uses this flag to stop the html handler from closing
* the menu when a sense card is selected. */
var _doNotClose = false;
/* Tracking which (if any) Word menu is currently opened */
var _openedWord = null;
/* Reference counting of global html click handler. Handler is installed on transition
* from 0 to 1, and removed when back down to 0. Reference count will go up to 2 when
* a word menu is opened while a sibling menu is already opened. */
var _bodyClickEnabledCount = 0;
/**
* An object that is created for each word with an associated sense menu.
* It manages its sense menu and informs listeners when a sense is selected.
*/
var Word = {
/**
* Initialize with arguments:
* options : control options: useToolTip
* $text: the jquery element to tag (has class
*/
init: function (options, $text, $menu) {
var base = this;
base.$elem = $text; /* jquery element holding the text word to tag */
base.$menu = $menu; /* jquery element holding the menu */
base.options = $.extend({}, base.$elem.data(), options);
base.tfOff = parseInt(base.$elem.data("off"), 10); /* tf offset of this menu */
base.endOff = base.tfOff + 1; /* assume a length 1 until a tile is selected */
base.$tile = null; /* sense tile currently selected */
base.menuW = null; /* menu widget of type idilia.senseMenu */
base._create();
},
/**
* Handle sense selection.
* event : { $prevTile:, $selTile: }
* $prevTile and $selTile are the jQuery tile container elements
*/
select: function(event) {
var base = this;
/* Add to given event data spanning information and the impacted text element */
event.$text = base.$elem;
event.selStart = base.tfOff;
base.endOff = event.selEnd = base.tfOff + parseInt(event.$selTile.data("len") || "1", 10);
if (event.$prevTile) {
event.prevStart = base.tfOff;
event.prevEnd = base.tfOff + parseInt(event.$prevTile.data("len") || "1", 10);
}
base.$tile = event.$selTile;
/* Update the attributes of the text element */
var fsk = event.$selTile.data('fsk');
base.$elem.
data("fsk", fsk).
addClass("idl-tagged idl-mantagged").
removeClass("idl-untagged");
/* Fire custom event to have the tagging menu update siblings */
base.$elem.parent().trigger( "tm_itl_sensesel", event);
/* Inform a listener of the selection. Listener can prevent
* default operation of updating the text. */
var upd = true; /* should set to options - default should be to use the skToLemma */
if (typeof base.options.sensesel === "function") {
upd = base.options.sensesel.call(this, event);
}
if (upd) {
if (base.options.wordsContent === "tile") {
base.$elem[0].innerHTML = event.$selTile[0].outerHTML;
base.$elem.senseCard({
lgcc: base.options.senseMenuOptions.lgcc,
deleted: function() {
base._deletedWordTileEH($(this));
}
});
}
else {
// Assemble the surface words for spanned spans
var $currS = base.$elem;
var text = "";
do {
text += $currS.data("tok") || $currS.text();
$currS = $currS.next();
} while ($currS.length && (!$currS.data("off") || $currS.data("off") < base.endOff));
base.$elem.text(text.trim().replace(/ /g, '_'));
}
}
/* And close the menu */
if (base.options.closeOnSelect) {
base.close();
}
},
/**
* Public method to remove the sense selection
*/
deselect : function () {
var base = this;
base.$elem.
addClass("idl-untagged").
removeClass("idl-tagged idl-mantagged").
removeData("fsk");
base.endOff = base.tfOff + 1;
var data = {
'selStart' : base.tfOff,
'selEnd' : base.tfOff + 1
};
if (base.$tile) {
data.prevStart = base.tfOff;
data.prevEnd = base.tfOff + parseInt(base.$tile.data("len") || "1", 10);
}
base.$elem.parent().trigger( "tm_itl_sensesel", data);
/* Inform a listener of the selection. Listener can prevent
* default operation of updating the text. */
var upd = true;
if (typeof base.options.sensedesel === "function") {
upd = base.options.sensedesel.call(this, event) !== false;
}
if (upd) {
base.$elem.text(base.$elem.data('tok'));
}
},
/**
* Public method for a client to mark a sense as selected
* @param $tile jquery element of the tile to select. It has class .idl-tile-container
*/
setSelected: function($tile) {
this.menuW.select($tile);
},
/**
* Public method to retrieve the selected tile
*/
selected: function() {
return this.menuW.selected();
},
/**
* Public method to set the view of the embedded sense menu (grid, carousel)
* @param view Value is 'grid' to set grid mode where all the tiles are visible or 'carousel'
* to present the tiles in a slider.
*/
setView: function(view) {
this.menuW.setView(view);
},
/**
* Public function to indicate if multiple tiles in a menu
* @return true when the menu has multiple tiles
*/
polysemous : function () {
return this.$menu.find('.idl-tile-container').length > 1;
},
/**
* Public function with the start offset of this Word within
* the text.
*/
startOffset : function () {
return this.tfOff;
},
/**
* Public function with the end offset of the sense selected
* for this word. Is > 1 when the sense selected spans multiple Word.
*/
endOffset : function () {
return this.endOff;
},
_bodyClickHandler: function(event) {
if ($(event.target).closest(".idl-sensemenu").length > 0) {
return;
}
if (!_doNotClose && _openedWord) {
_openedWord.close();
}
_doNotClose = false;
},
_monitorBodyClicks : function(enable) {
var base = this;
if (!base.options.closeOnOutsideClick)
return;
if (enable)
{
if (_bodyClickEnabledCount === 0) {
$(document.body).on("click", base._bodyClickHandler);
}
_bodyClickEnabledCount++;
}
else
{
--_bodyClickEnabledCount;
if (_bodyClickEnabledCount === 0) {
$(document.body).off("click", base._bodyClickHandler);
}
}
},
/**
* Public method to open the menu
*/
open: function() {
var base = this;
if (base.$elem.is(':visible')) {
if (typeof base.options.beforeOpen === "function") {
base.options.beforeOpen(this);
}
base._monitorBodyClicks(true);
if (_openedWord) {
_openedWord.close();
}
if (base.options.useToolTip) {
base._popover({show:false});
}
base.menuW.open();
base.$elem.addClass("idl-active");
_openedWord = base;
_doNotClose = true;
}
},
/**
* Public method to close the menu
*/
close: function() {
if (_openedWord == this)
{
var base = this;
base._monitorBodyClicks(false);
_openedWord = null;
base.menuW.close();
base.$elem.removeClass("idl-active");
if (typeof base.options.afterClose === "function") {
base.options.afterClose(this);
}
}
},
/**
* Public method to cleanup
*/
destroy: function() {
var base = this;
base.menuW.destroy();
if (base.options.useToolTip) {
base._popover({show:false});
}
},
/**
* popover state and content handling
* parms, object with potentially two fields:
* bool show: showing or hiding
* string content: content to use for the popover
* */
_popover: function(parms) {
var base = this;
if (parms.hasOwnProperty("show")) {
base.showingPopup = parms.show;
}
var e = base.$elem;
e.popover('destroy');
if (base.showingPopup && parms.content)
{
e.popover({
content: parms.content,
container: false,
html: true,
placement: "auto",
delay: 500,
trigger: 'hover',
animation: false});
e.popover('show');
}
},
/** Constructor */
_create: function() {
var base = this;
if (base.options.wordsContent === "tile") {
base._setWordTile();
}
/* Create the menu with the HTML fragment. */
base.menuW = base.$menu.senseMenu($.extend({}, base.options.senseMenuOptions, {
/* Add a handler when a sense is selected. */
sensesel: function (event) {
base.select(event);
},
/* Add a handler when a create sense action is selected. */
createsel: function (event) {
event.$text = base.$elem;
base.options.createsel(event);
if (base.options.closeOnSelect) {
base.close();
}
}
})).data("senseMenu");
base.$elem.on({
/** handler when the text/tile is clicked.
* Open this word's menu if more than one card or close when opened.
*/
"click" : function (event) {
if (base.$elem.hasClass("idl-active")) {
base.close();
} else {
base.open();
}
}
});
/** Initialize as untagged */
base.$elem.addClass("idl-untagged");
},
/**
* Private function to set a menu tile when displaying tiles instead of the word itself
* Updates base.$tile and base.$elem's html
*/
_setWordTile : function () {
var base = this;
var $tile = base.$menu.find(".idl-sensesel").first(); /* selected tile */
if ($tile.length === 0) {
$tile = base.$menu.find(".idl-tile-container[data-grp]").first(); /* first tile part of a group, excluding others */
}
if ($tile.length === 0) {
$tile = base.$menu.find(".idl-tile-other");
}
if ($tile.length === 0) {
$tile = base.$menu.find(".idl-tile-any");
}
if ($tile.length === 0) {
// If showing tiles and there is no sense, synthesize one
$tile = $('<div class="idl-tile-container idl-menu-sensecard idl-sensesel idl-tile-text idl-tmplt-menu_image_v3" data-grp="1"><div class="idl-sensetile"><div class="idl-tile-sum"><h1>' + base.$elem.data("tok") + '</h1></div><div class="idl-def"><p>Any sense (no known meaning).</p></div></div></div>');
}
base.$tile = $tile;
base.$elem[0].innerHTML = $tile[0].outerHTML; /* set the tile idl-menu-word content to the tile */
},
/**
* Private event handler for the word tile being deleted.
* This is called when displaying tiles for the current sense value
* and the tile is deleted. Remove it from the menu and replace with first tile.
* @param $card jquery element for the card deleted in the language graph customer center
*/
_deletedWordTileEH : function ($card) {
var base = this;
/* Remove the card from the menu that corresponds to this sensekey */
var fsk=$card.data("fsk");
var sel=".idl-tile-container[data-fsk='" + fsk + "']";
base.$menu.find(sel).remove();
/* Replace the tile */
base._setWordTile();
},
/** Private function to return the lemma in a sensekey */
_skToLemma : function (sk) {
var base = this;
var slPos = sk.lastIndexOf('/');
if (slPos != -1) {
sk = sk.substr(0, slPos);
}
return sk.replace(/_/g, ' ');
}
};
/**
* An object created to handle the visibility of the gap between words that
* have a sense menu. This gap can be a space or a word without any sense info.
* Becomes invisible when a sense spanning it is selected. visible otherwise.
*/
var Gap = {
init : function ($elem, tfOff, isWord) {
var base = this;
base.$elem = $elem; /* text element of the gap */
base.tfOff = tfOff; /* for a space, offset after; for a dead word, start offset */
base.isWord = isWord; /* true when a dead word */
},
startOffset : function () {
return this.tfOff;
},
endOffset : function () {
return this.isWord ? this.tfOff + 1 : this.tfOff;
}
};
/**
* Main class.
* Creates Word and Gap objects for all the span elements on which it is
* attached. Notifies instantiator on sense selections and provides services
* for retrieving the sense information
*/
var TaggingMenu = {
init : function(options, el) {
var base = this;
base.$elem = $(el); /* element on which attached. Has class "idl-menu-words" */
base.options = $.extend({}, $.fn.taggingMenu.options, base.$elem.data(), options);
base.words = []; /* array of instantiated Word objects */
base.gaps = []; /* array of instantiated Gap objects */
base.sensecards = {}; /* a cache of sense cards requested */
base.tmplt = options.menus.children().first().data("tmplt");
base._create();
},
/* Public method to return the text */
text : function() {
var base = this;
var t = "";
base.$elem.children().each(function (idx, elem) {
$elem = $(elem);
if ($elem.is(':visible')) {
t += $elem.text();
}
});
return t;
},
/**
* Public method to return the tagged text as one string
* where the string contains the selected sensekey for each word.
*/
senses : function() {
var base = this;
var t = "";
base.$elem.children().each(function (idx, elem) {
$elem = $(elem);
if (($elem.css("display") == "inline") || $elem.hasClass("hidden")) {
if ($elem.hasClass("idl-tagged")) {
var fsk = $elem.data("fsk");
if (fsk) {
t += fsk;
return;
}
}
// no fsk - either an unknown word (use token) or a gap (use text)
t += $elem.data("tok") || $elem.text();
}
});
return t;
},
/**
* Public method to return the sense information
* Returns an array of objects with properties:
* start: integer, start offset of the sense
* len: integer, number of tokens spanned by the selected sense
* text: string, text spanned by the selected sense
* fsk: string, sensekey of the selected sense,
* spcAft: boolean, true when text of selected sense is followed by a space
*/
sensesAsObjects : function() {
var base = this;
var res = [];
var pathEnd = 0;
var text = '';
var sense;
var elements = base.$elem.children();
for (var i = 0, iEnd = elements.length; i < iEnd; ++i) {
var $e = $(elements[i]);
/* handle the words with a menu and tagging information */
if ($e.hasClass('idl-menu-word')) {
var w = base.words[$e.data("widx")];
if (w.tfOff === pathEnd) {
if (sense !== undefined) {
sense.text = text.trim();
res.push(sense);
text = '';
}
sense = {'start' : w.tfOff, 'len' : w.endOff - w.tfOff, 'spcAft' : false};
var fsk = $e.data('fsk');
if (fsk) {
sense.fsk = fsk;
}
pathEnd = w.endOff;
}
text += $e.data('tok');
} else {
var g = base.gaps[$e.data("gidx")];
if (g.isWord && g.tfOff === pathEnd) {
if (sense !== undefined ) {
sense.text = text.trim();
res.push(sense);
text = '';
}
sense = {'start' : g.tfOff, 'len' : 1, 'spcAft' : false};
pathEnd = g.endOffset();
} else if (!g.isWord && g.tfOff === pathEnd) {
if (sense !== undefined ) {
sense.spcAft = true;
}
}
text += $e.text();
}
}
sense.text = text.trim();
res.push(sense);
return res;
},
/**
* Public method to select the sense assigned to a word
* @param $word jQuery object with the word (.menu-word) to select
* @param $tile jQuery object with the sense tile (.idl-tile-container) to select
*/
select : function($word, $tile) {
var base = this;
var widx = $word.data("widx");
if (typeof widx !== 'undefined') {
base.words[widx].setSelected($tile);
}
},
/**
* Public method to deselect the sense assigned to a word.
* @param $word jQuery object with class .menu-word
*/
deselect : function ($word) {
var base = this;
var widx = $word.data("widx");
if (typeof widx !== 'undefined') {
base.words[widx].deselect();
}
},
/**
* Public method to deselect all senses
*/
deselectAll : function () {
this.words.forEach(function (word) { word.deselect(); });
},
/**
* Public method to close any opened menus
*/
close : function() {
this.words.forEach(function(word) { word.close(); });
},
/**
* Public method to cleanup
*/
destroy : function() {
this.words.forEach( function(word) { word.destroy(); } );
this.$elem.removeData("taggingMenu");
},
/** Private function to retrieve the sensecard shown in the tool tip */
_getSenseCard : function (word) {
var base = this;
/* Assemble request parameters depending on type of card */
var cacheKey;
var data = { tmplt : base.tmplt};
var fsk = word.$tile.data('fsk');
data.fsk = cacheKey = fsk;
/* Check if already in cache */
cacheKey = cacheKey.replace(/\W/g, '');
var html = base.sensecards[cacheKey];
if (html !== undefined) {
return html;
}
/* Make jsonp request to retrieve */
$.ajax({
data: data,
type: 'GET',
url: base.options.apiUrl + "sensecard.js",
dataType: 'jsonp'
}).done(function (data) {
var card = data.card;
base.sensecards[cacheKey] = card;
word._popover({content: card});
});
return '';
},
/** Constructor */
_create: function() {
var base = this;
/* Pass on the options to the Word adding our callback */
var wordOptions = $.extend({}, base.options, {
sensesel: function (event) {
event.allset = !base.$elem.children(".idl-untagged").is(':visible');
if (base.options.informOnOther &&
event.$selTile.hasClass("idl-tile-other")) {
window.setTimeout(base.notifyOnOther, 1000, base, event);
}
if (typeof base.options.sensesel === "function") {
return base.options.sensesel.call(this, event);
}
return true; /* allow to replace word with lemma */
}
});
if (base.options.wordsContent === "tile") {
/* if showing tiles, tooltips should not be used */
if (base.options.useToolTip) {
alert("TaggingMenu \"useToolTip\" option should be false when \"wordsContent\" option is \"tile\".");
}
} else {
base.$elem.addClass("idl-text-mode");
}
if (base.options.useToolTip) {
if (base.$elem.popover !== undefined) {
base.$elem.on("mouseenter mouseleave", ".idl-tagged", function(event) {
var e = $(this);
var word = base.words[e.data("widx")];
if (event.type === "mouseenter") {
var html = base._getSenseCard(word);
if (html !== "") {
word._popover({show: true, content: html});
} else {
word._popover({show: true});
}
}
else {
word._popover({show: false});
}
});
}
else {
alert("Using tooltip without popover defined. Set useToolTip to false in options.");
}
}
base.options.menus.on("click", ".idl-to-carousel, .idl-to-grid", function(e) {
var view = $(e.currentTarget).data("view");
base.words.forEach(function (word) {
word.setView(view);
});
e.stopPropagation();
});
/*
* On word sense selection updates next siblings
*/
base.$elem.on("tm_itl_sensesel", function(event, data) {
base._senseSelHdlr(data);
});
/* Find each spanned text element and create their managing Word instance */
var tfOff = -1;
base.$elem.children().each(function (idx, elem) {
var $elem = $(elem);
if ($elem.hasClass("idl-menu-word")) {
tfOff = parseInt($elem.data("off"), 10);
var w = Object.create(Word);
var $menu = base.options.menus.children('[data-off="' + tfOff + '"]');
w.init(wordOptions, $elem, $menu);
var widx = base.words.length;
$elem.data("widx", widx);
base.words[widx] = w;
} else {
var g = Object.create(Gap);
var tfOffAttr = $elem.data("off");
tfOff = tfOffAttr !== undefined ? parseInt(tfOffAttr, 10) : tfOff + 1;
g.init($elem, tfOff, tfOffAttr !== undefined);
if (base.options.hideUntaggable && $elem.text().trim().length) {
$elem.addClass("hidden");
}
var gidx = base.gaps.length;
$elem.data("gidx", gidx);
base.gaps[gidx] = g;
}
});
/* For each one that have a sense selected, inform that selected.
* This can't be done during creation because the menus listen to each other. */
for (var i = 0; i < base.words.length; ++i) {
var word = base.words[i];
var $selTile = word.selected();
if ($selTile) {
if (base.options.preselect === 'sa' ||
(base.options.preselect === 'mono' && !word.polysemous())) {
word.setSelected($selTile);
} else {
$selTile.removeClass("idl-sensesel");
}
}
else if (word.$elem.is(":visible") && word.$tile) {
word.setSelected(word.$tile);
}
}
},
/** Handler to show/hide text elements depending on sense selection */
_senseSelHdlr : function (data) {
var base = this;
var visEnd = data.selEnd; /* end offset of last element visible in path*/
var pathEnd = Math.max(data.selEnd, data.prevEnd); /* end of the path where we can stop */
/* Updates next siblings */
var elements = data.$text.nextAll();
for (var i = 0; i < elements.length; ++i) {
var $e = $(elements[i]);
/*
* Handle the gap:
* Visible when after the end of last visible word, hidden when underneath
*/
if (!$e.hasClass('idl-menu-word')) {
var gap = base.gaps[$e.data("gidx")];
var pathOff = gap.tfOff;
if (pathOff < visEnd) {
$e.hide();
} else {
$e.show();
visEnd = gap.endOffset();
}
continue;
}
/*
* Handle the word:
* Visible when starting after the end of the last visible word
* When enabling, move visible end to match end of word
*/
var word = base.words[$e.data("widx")];
var wordOff = word.startOffset();
var wordEnd = word.endOffset();
if (wordOff === pathEnd) {
break;
}
if (wordOff < visEnd) {
$e.hide();
} else {
visEnd = wordEnd;
if (base.options.wordsContent === "tile" && word.$tile) {
word.setSelected(word.$tile);
}
$e.show();
}
if (wordEnd > pathEnd) {
pathEnd = wordEnd;
}
}
},
/** Inform Idilia when a sense "other" is selected. */
notifyOnOther : function(base, event) {
$.get(base.options.apiUrl + 'other_sense.js', {
'text' : base.text(),
'word' : event.$text.text()
});
}
};
/** Add to jQuery namespace method to create a tagging menu with options */
$.fn.taggingMenu = function (options) {
return this.each(function () {
var $elem = $(this);
var sm = $elem.data("taggingMenu");
if (sm === undefined) {
sm = Object.create(TaggingMenu);
$elem.data("taggingMenu", sm);
}
sm.init(options, this);
});
};
/** Add to jQuery namespace the default tagging menu options */
$.fn.taggingMenu.options = {
menus: null, /* jQuery element that is hosting the menus for each word */
useToolTip: true, /* whether tagging menus use a tooltip widget to display gloss */
wordsContent: "text", /* whether tagging menus show text or tiles */
hideUntaggable: false, /* whether tagging menus should hide text which is not to be tagged */
informOnOther: true, /* Notify Idilia of sense selection with "other" sense */
closeOnSelect: true, /* Close menu on sense selection */
closeOnOutsideClick: true, /* Close menu when a click is outside the opened sense menu */
apiUrl: 'https://api.idilia.com/1/kb/', /* Service url to obtain the sensecards */
preselect: 'sa', /* Preselect the senses based on the output of Sense Analysis. Others are 'mono', 'none' */
senseMenuOptions : {}, /* Sense menu options. None given here to use the defaults */
sensesel: null, /* callback function when a sense is selected */
sensedesel: null, /* callback function when a sense is deselected */
createsel: null, /* callback function when a create sense is selected */
beforeOpen: null, /* callback function before a menu is opened */
afterClose: null /* callback function after a menu has been closed */
};
}(jQuery, window, document));
|
'use strict';
const { spy } = require('sinon');
const Promise = require('bluebird');
describe('Tag', () => {
const Tag = require('../../../lib/extend/tag');
const tag = new Tag();
it('register()', async () => {
const tag = new Tag();
tag.register('test', (args, content) => args.join(' '));
const result = await tag.render('{% test foo.bar | abcdef > fn(a, b, c) < fn() %}');
result.should.eql('foo.bar | abcdef > fn(a, b, c) < fn()');
});
it('register() - async', async () => {
const tag = new Tag();
tag.register('test', (args, content) => Promise.resolve(args.join(' ')), { async: true });
const result = await tag.render('{% test foo bar %}');
result.should.eql('foo bar');
});
it('register() - block', async () => {
const tag = new Tag();
tag.register('test', (args, content) => args.join(' ') + ' ' + content, true);
const str = [
'{% test foo bar %}',
'test content',
'{% endtest %}'
].join('\n');
const result = await tag.render(str);
result.should.eql('foo bar test content');
});
it('register() - async block', async () => {
const tag = new Tag();
tag.register('test', (args, content) => Promise.resolve(args.join(' ') + ' ' + content), { ends: true, async: true });
const str = [
'{% test foo bar %}',
'test content',
'{% endtest %}'
].join('\n');
const result = await tag.render(str);
result.should.eql('foo bar test content');
});
it('register() - nested test', async () => {
const tag = new Tag();
tag.register('test', (args, content) => content, true);
const str = [
'{% test %}',
'123456',
' {% raw %}',
' raw',
' {% endraw %}',
' {% test %}',
' test',
' {% endtest %}',
'789012',
'{% endtest %}'
].join('\n');
const result = await tag.render(str);
result.replace(/\s/g, '').should.eql('123456rawtest789012');
});
it('register() - nested async / async test', async () => {
const tag = new Tag();
tag.register('test', (args, content) => content, {ends: true, async: true});
tag.register('async', (args, content) => {
return Promise.resolve(args.join(' ') + ' ' + content);
}, { ends: true, async: true });
const str = [
'{% test %}',
'123456',
' {% async %}',
' async',
' {% endasync %}',
'789012',
'{% endtest %}'
].join('\n');
const result = await tag.render(str);
result.replace(/\s/g, '').should.eql('123456async789012');
});
it('register() - strip indention', async () => {
const tag = new Tag();
tag.register('test', (args, content) => content, true);
const str = [
'{% test %}',
' test content',
'{% endtest %}'
].join('\n');
const result = await tag.render(str);
result.should.eql('test content');
});
it('register() - async callback', async () => {
const tag = new Tag();
tag.register('test', (args, content, callback) => {
callback(null, args.join(' '));
}, { async: true });
const result = await tag.render('{% test foo bar %}');
result.should.eql('foo bar');
});
it('register() - name is required', () => {
should.throw(() => tag.register(), 'name is required');
});
it('register() - fn must be a function', () => {
should.throw(() => tag.register('test'), 'fn must be a function');
});
it('unregister()', () => {
const tag = new Tag();
tag.register('test', (args, content) => Promise.resolve(args.join(' ')), {async: true});
tag.unregister('test');
return tag.render('{% test foo bar %}')
.then(result => {
console.log(result);
throw new Error('should return error');
})
.catch(err => {
err.should.have.property('type', 'unknown block tag: test');
});
});
it('unregister() - name is required', () => {
should.throw(() => tag.unregister(), 'name is required');
});
it('render() - context', async () => {
const tag = new Tag();
tag.register('test', function() {
return this.foo;
});
const result = await tag.render('{% test %}', { foo: 'bar' });
result.should.eql('bar');
});
it('render() - callback', () => {
const tag = new Tag();
const callback = spy();
tag.register('test', () => 'foo');
return tag.render('{% test %}', callback()).then(result => {
result.should.eql('foo');
callback.calledOnce.should.be.true;
});
});
});
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M17.51 3.87 15.73 2.1 5.84 12l9.9 9.9 1.77-1.77L9.38 12l8.13-8.13z"
}), 'ArrowBackIosSharp'); |
'use strict';
/**
* Expose `Abstract`.
*/
module.exports = Abstract;
/**
* Initialize a new abstract sequence interpreter.
*/
function Abstract() {
}
Abstract.defineImplementedInterfaces(['danf:sequencing.sequenceInterpreter']);
Abstract.defineAsAbstract();
Abstract.defineDependency('_sequencesContainer', 'danf:sequencing.sequencesContainer');
Abstract.defineDependency('_logger', 'danf:sequencing.logger');
/**
* Sequences container.
*
* @var {danf:sequencing.sequencesContainer}
* @api public
*/
Object.defineProperty(Abstract.prototype, 'sequencesContainer', {
set: function(sequencesContainer) {
this._sequencesContainer = sequencesContainer
}
});
/**
* Logger.
*
* @var {danf:logging.logger}
* @api public
*/
Object.defineProperty(Abstract.prototype, 'logger', {
set: function(logger) {
this._logger = logger
}
});
/**
* @interface {danf:sequencing.sequenceInterpreter}
*/
Object.defineProperty(Abstract.prototype, 'order', {
get: function() { return this._order; }
});
/**
* @interface {danf:sequencing.sequenceInterpreter}
*/
Abstract.prototype.buildContext = function(context, definition) {
return context;
}
/**
* @interface {danf:sequencing.sequenceInterpreter}
*/
Abstract.prototype.interpret = function(sequence, definition, context) {
return sequence;
}
|
var glslifyBundle = require('glslify-bundle')
var staticModule = require('static-module')
var glslifyDeps = require('glslify-deps')
var glslResolve = require('glsl-resolve')
var through = require('through2')
var nodeResolve = require('resolve')
var extend = require('xtend')
var path = require('path')
var fs = require('fs')
module.exports = transform
module.exports.bundle = bundle
function transform(jsFilename, browserifyOpts) {
if (path.extname(jsFilename) === '.json') return through()
var streamHasErrored = false
// static-module is responsible for replacing any
// calls to glslify in your JavaScript with a string
// of our choosing – in this case, our bundled glslify
// shader source.
var sm = staticModule({
glslify: streamBundle
}, {
vars: {
__dirname: path.dirname(jsFilename),
__filename: jsFilename,
require: {
resolve: nodeResolve
}
},
varModules: { path: path }
})
return sm
function streamBundle(filename, opts) {
var stream = through()
if (typeof filename === 'object') {
if (streamHasErrored) return
streamHasErrored = true
setTimeout(function () {
return sm.emit('error', new Error(
'You supplied an object as glslify\'s first argument. As of ' +
'glslify@2.0.0, glslify expects a filename or shader: ' +
'see https://github.com/stackgl/glslify#migrating-from-glslify1-to-glslify2 for more information'
))
})
return
}
opts = extend({
basedir: path.dirname(jsFilename)
}, browserifyOpts || {}, opts || {})
var depper = bundle(filename, opts, function(err, source) {
if (err) return sm.emit('error', err)
stream.push(JSON.stringify(source))
stream.push(null)
})
//notify watchify that we have a new dependency
depper.on('file', function(file) {
sm.emit('file', file)
})
return stream
}
}
function bundle(filename, opts, done) {
opts = opts || {}
var defaultBase = opts.inline
? process.cwd()
: path.dirname(filename)
var base = path.resolve(opts.basedir || defaultBase)
var posts = []
var files = []
var depper = glslifyDeps({
cwd: base
})
// Extract and add our local transforms.
var transforms = opts.transform || []
depper.on('file', function(file) {
files.push(file)
})
transforms = Array.isArray(transforms) ? transforms : [transforms]
transforms.forEach(function(transform) {
transform = Array.isArray(transform) ? transform : [transform]
var name = transform[0]
var opts = transform[1] || {}
if (opts.post) {
posts.push({ name: name, opts: opts })
} else {
depper.transform(name, opts)
}
})
if (opts.inline) {
depper.inline(filename
, base
, addedDep)
} else {
filename = glslResolve.sync(filename, {
basedir: base
})
depper.add(filename, addedDep)
}
return depper
// Builds a dependency tree starting from the
// given `filename` using glslify-deps.
function addedDep(err, tree) {
if (err) return done(err)
try {
// Turn that dependency tree into a GLSL string,
// stringified for use in our JavaScript.
var source = glslifyBundle(tree)
} catch(e) {
return done(e)
}
// Finally, this applies our --post transforms
next()
function next() {
var tr = posts.shift()
if (!tr) return postDone()
var target = nodeResolve.sync(tr.name, {
basedir: path.dirname(filename)
})
var transform = require(target)
transform(null, source, {
post: true
}, function(err, data) {
if (err) throw err
if (data) source = data
next()
})
}
function postDone() {
done(null, source, opts.inline
? files.slice(1)
: files
)
}
}
}
|
/*
* File: app/store/storeTanque3Material.js
*
* This file was generated by Sencha Architect version 4.1.2.
* http://www.sencha.com/products/architect/
*
* This file requires use of the Ext JS 5.1.x library, under independent license.
* License of Sencha Architect does not include license for Ext JS 5.1.x. For more
* details see http://www.sencha.com/license or contact license@sencha.com.
*
* This file will be auto-generated each and everytime you save your project.
*
* Do NOT hand edit this file.
*/
Ext.define('hwtProUnidadesUsadas.store.storeTanque3Material', {
extend: 'Ext.data.Store',
requires: [
'hwtProUnidadesUsadas.model.modTanque3Material'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
storeId: 'storeTanque3Material',
model: 'hwtProUnidadesUsadas.model.modTanque3Material'
}, cfg)]);
}
}); |
define(['jquery'], function($) {
var SearchService = {};
var self = this;
this.requestDigest = null;
var GetRequestDigest = function() {
var dfd = $.Deferred();
if (self.requestDigest && self.requestDigest.expiresOn > (new Date())) {
return dfd.resolve();
} else {
$.ajax({
type: "POST",
url: _spPageContextInfo.webAbsoluteUrl + "/_api/contextinfo",
headers: {
"accept": "application/json;odata=verbose"
}
}).done(function(resp) {
var now = (new Date()).getTime();
self.requestDigest = resp.d.GetContextWebInformation;
self.requestDigest.expiresOn = now + (resp.d.GetContextWebInformation.FormDigestTimeoutSeconds * 1000) - 60000; // -60000 To prevent any calls to fail at all, by refreshing a minute before
dfd.resolve();
}).fail(function(err) {
console.log("Error fetching Request Digest. Some parts won't work.");
dfd.reject();
});
}
return dfd.promise();
};
SearchService.Query = function(query) {
var dfd = $.Deferred();
GetRequestDigest().then(function() {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/postquery",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": self.requestDigest.FormDigestValue
},
data: JSON.stringify(query)
}).done(function(data) {
dfd.resolve(data);
}).fail(function(err) {
dfd.reject(err);
});
}, function(err) {
dfd.reject(err);
});
return dfd.promise();
}
SearchService.GetManagedProperties = function(options) {
var dfd = $.Deferred();
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='contenttype:"+ options.ContentType+ "+ListId:" + options.ListId + "'",
type: "get",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
}
}).done(function(data) {
if (data.d.query.PrimaryQueryResult.RelevantResults.RowCount > 0) {
var oWorkId = null;
var firstItem = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results["0"].Cells.results;
for (var i = 0; i < firstItem.length; i++) {
if (firstItem[i].Key == "WorkId") {
oWorkId = firstItem[i];
break;
}
}
//Got workId now.
//secret sauce to get all properties back (https://blogs.technet.microsoft.com/searchguys/2013/12/10/how-to-find-all-managed-properties-of-a-document/)
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + oWorkId.Key + ":" + oWorkId.Value + "'&refiners='ManagedProperties(filter=600/0/*)'",
type: "get",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
}
}).done(function(data) {
if (data.d.query.PrimaryQueryResult == null || data.d.query.PrimaryQueryResult.RefinementResults == null) {
dfd.reject(new Error({
name: "RC Search Service Error",
message: "Error detected. Could not retrieve managed properties.",
htmlMessage: "The ManagedProperties property does not contain values. See https://github.com/wobba/SPO-Trigger-Reindex for more information on how to enable this feature.",
toString: function() {
return this.name + ": " + this.message + " " + this.htmlMessage;
}
}));
} else {
var refiners = data.d.query.PrimaryQueryResult.RefinementResults.Refiners.results["0"].Entries.results;
dfd.resolve(refiners);
}
}).fail(function(err) {
dfd.reject(err);
});
}
})
return dfd.promise();
}
return SearchService
})
|
d3.queue()
.defer(d3.csv, '../assets/data/community/wellbeing_survey_trend.csv')
.defer(d3.csv, '../assets/data/community/crime_rate_by_tract.csv')
.defer(d3.json, '../assets/json/nhv_tracts.json')
.await(initCommunity);
function initCommunity(error, safety, crime, json) {
if (error) throw error;
safety.forEach(function(d) {
d.value = +d.value;
});
crime.forEach(function(d) {
d.value = +d.value;
});
var safetyTrend = makeSafetyTrend(safety);
var violentMap = d3map();
d3.select('#violent-crime-map')
.datum(topojson.feature(json, json.objects.nhv_tracts))
.call(violentMap);
violentMap.color(crime.filter(function(d) { return d.type === 'violent'; }), choroscale)
.tip('d3-tip', d3.format('.2r'), false)
.legend(d3.format('.0f'), 20, 20);
var propertyMap = d3map();
d3.select('#property-crime-map')
.datum(topojson.feature(json, json.objects.nhv_tracts))
.call(propertyMap);
propertyMap.color(crime.filter(function(d) { return d.type === 'property'; }), choroscale)
.tip('d3-tip', d3.format('.2r'), false)
.legend(d3.format('.0f'), 20, 20);
d3.select(window).on('resize', function() {
safetyTrend = makeSafetyTrend(safety);
violentMap.draw();
propertyMap.draw();
redrawDots();
});
redrawDots();
}
function makeSafetyTrend(data) {
var margin = { top: 24, right: 32, bottom: 48, left: 32 };
var svg = d3.select('#safety-trend')
.select('svg')
.attr('width', '100%')
.attr('height', '100%')
.html('');
var chart = new dimple.chart(svg, data);
chart.setMargins(margin.left, margin.top, margin.right, margin.bottom);
var x = chart.addTimeAxis('x', 'year', '%Y', '%Y');
x.title = null;
var y = chart.addMeasureAxis('y', 'value');
y.tickFormat = '.0%';
y.ticks = 4;
chart.defaultColors = [ pink, dkblue ];
var line = chart.addSeries('name', dimple.plot.line);
line.lineMarkers = true;
chart.addLegend('80%', '8%', '10%', '20%', 'right', line);
chart.draw();
var tip = d3.tip()
.attr('class', 'd3-tip')
.html(trendGroupTip);
svg.selectAll('circle.dimple-marker')
.call(tip)
.on('mouseover', function(d) {
tip.show(d);
dotOver(this);
})
.on('mouseout', function(d) {
tip.hide(d);
dotOut(this);
})
.on('touchstart', function(d) {
d3.event.preventDefault();
tip.show(d);
dotOver(this);
});
return chart;
}
|
import _ from 'underscore';
import React from 'react';
import ThatContainer from './containers/Container';
import * as Actions from '../actions/actions';
import './App.css';
//import 'bootstrap/dist/css/bootstrap.css';
import './short.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
console.log("IndexComponent.js loading");
export default class IndexComponent extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
var self = this;
var store = self.props.store;
}
render() {
console.log('IndexComponent.render');
return (
<div>
<Navbar inverse fluid fixedTop>
<Grid>
<Navbar.Header>
<Navbar.Brand>
<a href="/">That App</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
</Grid>
</Navbar>
<div>
<Grid fluid={true}>
<ThatComponent />
</Grid>
</div>
</div>
)
}
}
|
import 'detects.js';
// my app logic
import 'analytics.js';
|
(function (webgl) {
/**
* A ShaderClosure connects a mesh-specific GLProgram with it's Xflow data
* @param {GLContext} context
* @constructor
*/
var AbstractShaderClosure = function(context) {
/**
* @private
* @type {GLProgramObject|null}
*/
this.program = null;
this.context = context;
/**
* A flag used by shadercomposer to sort out obsolete shaderclosures
* @type {boolean}
*/
this.obsolete = false;
this.id = "";
this.uniformCollection = {
envBase: {},
envOverride: null,
sysBase: null
};
/**
* Stores, if the underlying shader has semi-transparencies
* and thus needs to considered for alpha-blending
* @type {boolean}
*/
this.isTransparent = false;
/**
* The source of a shader
* @private
* @type {{vertex: string, fragment: string}}
*/
this.source = {
vertex: "",
fragment: ""
}
};
Object.defineProperties(AbstractShaderClosure.prototype, {
attributes: {
writeable: false,
get: function() {
return this.program ? this.program.attributes : {}
}
},
uniforms: {
writeable: false,
get: function() {
return this.program ? this.program.uniforms : {}
}
},
samplers: {
writeable: false,
get: function() {
return this.program ? this.program.samplers : {}
}
}
}
);
XML3D.createClass(AbstractShaderClosure, null, {
equals: function(that) {
return this.source.vertex === that.source.vertex && this.source.fragment === that.source.fragment;
},
hasTransparency: function() {
return this.isTransparent;
},
compile: function () {
if (!this.source.fragment || !this.source.vertex) {
XML3D.debug.logError("No source found for shader", this);
return;
}
var programObject = new XML3D.webgl.GLProgramObject(this.context.gl, this.source);
this.program = programObject;
this.id = programObject.id;
},
bind: function() {
this.program.bind();
},
unbind: function() {
this.program.unbind();
},
isValid: function() {
return this.program.isValid();
},
/**
* @param {Xflow.ComputeResult} xflowResult
*/
updateUniformsFromComputeResult: function (xflowResult) {
var map = xflowResult.getOutputMap();
var envBase = this.uniformCollection.envBase = {};
this.setDefaultUniforms(this.uniformCollection.envBase);
for(var name in map){
var value = webgl.getGLUniformValueFromXflowDataEntry(map[name], this.context);
envBase[name] = value;
}
var names = Object.keys(envBase);
this.setUniformVariables(names, null, this.uniformCollection);
this.isTransparent = this.getTransparencyFromInputData(map);
},
setUniformVariables: function(envNames, sysNames, uniformCollection){
this.program.setUniformVariables(envNames, sysNames, uniformCollection);
},
setSystemUniformVariables: function(sysNames, sysValues){
this.uniformCollection.sysBase = sysValues;
this.setUniformVariables(null, sysNames, this.uniformCollection);
},
changeUniformVariableOverride: function(prevOverride, newOverride){
var overrideNames = prevOverride ? Object.keys(prevOverride) : [];
if(newOverride) overrideNames.push.apply(overrideNames, Object.keys(newOverride));
this.uniformCollection.envOverride = newOverride;
this.setUniformVariables(overrideNames, null, this.uniformCollection);
}
});
webgl.AbstractShaderClosure = AbstractShaderClosure;
}(XML3D.webgl));
|
version https://git-lfs.github.com/spec/v1
oid sha256:89eabed79e37ca85192e16168ed72c258770b52bb20d3714f624abb0d6c3533b
size 2415
|
/**
* Methods for rendering a template.
*/
import _ from 'lodash';
import nunjucks from 'nunjucks';
import moment from 'moment';
import Url from '../url';
const TemplateErrorMessage = {
NO_TEMPLATE: 'template not found',
};
/**
* Render a template with given context variables.
* @param {Object} env Nunjucks instance;
* @param {string} template Template name, excluding the extension.
* @param {object} variables Object of variables to interpolate in the
* template.
* @return {string} Rendered template.
*/
export function renderTemplate(env, template, variables) {
if (!env) {
return '';
}
let result = '';
try {
result = env.render(`${template}.html`, variables);
} catch (e) {
if (e.message.includes(TemplateErrorMessage.NO_TEMPLATE)) {
// The message given from nunjucks looks like:
// Template render error: (/reptar/templates/page.html)
// Template render error: (/reptar/templates/page.html)
// Error: template not found: mistake.html
// This takes the multi line message and just grabs the last line.
const message = _.last(e.message.split('\n'))
.trim()
// Format the last line of `Error: template` to remove anything
// preceding our known error message. (Basically remove `Error: `)
.replace(
new RegExp(`.*${TemplateErrorMessage.NO_TEMPLATE}`),
TemplateErrorMessage.NO_TEMPLATE
);
// Re-throw formatted error message.
throw new Error(message);
} else {
throw e;
}
}
return result;
}
/**
* Render a string template with given context variables.
* @param {Object} env Nunjucks instance;
* @param {string} str Template string.
* @param {object} variables Object of variables to interpolate in the
* template.
* @return {string} Rendered template.
*/
export function renderTemplateString(env, str, variables) {
if (!env) {
return '';
}
return env.renderString(str, variables);
}
/**
* Allow adding custom filters to the template engine.
* @see {@link http://mozilla.github.io/nunjucks/api#custom-filters}
* @param {Object} env Nunjucks instance;
* @param {string} name Filter name.
* @param {Function} func Filter function.
* @param {boolean} async Whether the filter should be async.
*/
export function addTemplateFilter(env, name, func, async = false) {
env.addFilter(name, func, async);
}
/**
* Adds built in filters to template renderer.
* @param {Object} env Nunjucks instance;
* @param {Object} config Config instance.
*/
function addBuiltinFilters(env, config) {
function dateFilter(date, momentTemplate) {
if (date == null) {
return '';
}
return moment
.utc(date, config.get('file.dateFormat'))
.format(momentTemplate);
}
[
['date', dateFilter],
[
'groupbydate',
// Group items by formating their date via momentjs.
// Useful for creating archive pages:
// eslint-disable-next-line
// {% for date, files in collections.post.files | reverse | groupbydate('MMMM YYYY') %}
function groupbydate(data, momentTemplate, dateKey = 'date') {
return _.groupBy(data, datum =>
dateFilter(datum[dateKey], momentTemplate)
);
},
],
[
'slug',
function slug(str) {
return Url.slug(str);
},
],
[
'absolute_url',
function absoluteUrl(relativePath, basePath) {
let base = basePath || '';
const baseLength = base.length - 1;
base = base[baseLength] === '/' ? base.substr(0, baseLength) : base;
let input = relativePath || '';
const inputLength = input.length - 1;
if (input[inputLength] !== '/') {
input = `${input}/`;
}
if (input[0] !== '/') {
input = `/${input}`;
}
return base + input;
},
],
[
'limit',
function limit(arr, length) {
return arr.slice(0, length);
},
],
].forEach(filter => {
addTemplateFilter(env, ...filter);
});
}
/**
* Exposed method to configure template engine.
* @param {Object} options Options object with following properties:
* @param {Object} options.config Config object.
* @param {string|Array.<string>} options.paths Either an array of paths or a
* singular path that we can load templates from.
* @param {boolean} options.noCache Whether our template engine should cache
* its templates. Only set to true when in watch mode.
* @return {Object} Nunjucks instance.
*/
export function configureTemplateEngine({ config, paths, noCache = false }) {
const fileSystemLoader = new nunjucks.FileSystemLoader(paths, {
noCache,
});
const env = new nunjucks.Environment(fileSystemLoader, {
autoescape: false,
});
addBuiltinFilters(env, config);
return env;
}
|
import * as util from "../util";
export default class Logger {
constructor(file: File) {
this.filename = file.opts.filename;
this.file = file;
}
_buildMessage(msg: string): string {
var parts = this.filename;
if (msg) parts += `: ${msg}`;
return parts;
}
debug(msg: string) {
util.debug(this._buildMessage(msg));
}
deopt(node: Object, msg: string) {
util.debug(this._buildMessage(msg));
}
}
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
import {
buttonsType,
createEventTarget,
describeWithPointerEvent,
setPointerEvent,
} from '../testing-library';
let React;
let ReactFeatureFlags;
let ReactDOM;
let usePress;
function initializeModules(hasPointerEvents) {
jest.resetModules();
setPointerEvent(hasPointerEvents);
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.enableFlareAPI = true;
React = require('react');
ReactDOM = require('react-dom');
usePress = require('react-interactions/events/press').usePress;
}
const pointerTypesTable = [['mouse'], ['touch']];
describeWithPointerEvent('Press responder', hasPointerEvents => {
let container;
beforeEach(() => {
initializeModules(hasPointerEvents);
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
ReactDOM.render(null, container);
document.body.removeChild(container);
container = null;
});
describe('disabled', () => {
let onPressStart, onPressChange, onPressMove, onPressEnd, onPress, ref;
beforeEach(() => {
onPressStart = jest.fn();
onPressChange = jest.fn();
onPressMove = jest.fn();
onPressEnd = jest.fn();
onPress = jest.fn();
ref = React.createRef();
const Component = () => {
const listener = usePress({
disabled: true,
onPressStart,
onPressChange,
onPressMove,
onPressEnd,
onPress,
});
return <div ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
});
test('does not call callbacks for pointers', () => {
const target = createEventTarget(ref.current);
target.pointerdown();
target.pointerup();
expect(onPressStart).not.toBeCalled();
expect(onPressChange).not.toBeCalled();
expect(onPressMove).not.toBeCalled();
expect(onPressEnd).not.toBeCalled();
expect(onPress).not.toBeCalled();
});
test('does not call callbacks for keyboard', () => {
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter'});
target.keyup({key: 'Enter'});
expect(onPressStart).not.toBeCalled();
expect(onPressChange).not.toBeCalled();
expect(onPressMove).not.toBeCalled();
expect(onPressEnd).not.toBeCalled();
expect(onPress).not.toBeCalled();
});
});
describe('onPressStart', () => {
let onPressStart, ref;
beforeEach(() => {
onPressStart = jest.fn();
ref = React.createRef();
const Component = () => {
const listener = usePress({
onPressStart,
});
return <div ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
document.elementFromPoint = () => ref.current;
});
it.each(pointerTypesTable)(
'is called after pointer down: %s',
pointerType => {
const target = createEventTarget(ref.current);
target.pointerdown({pointerType});
expect(onPressStart).toHaveBeenCalledTimes(1);
expect(onPressStart).toHaveBeenCalledWith(
expect.objectContaining({pointerType, type: 'pressstart'}),
);
},
);
it('is called after middle-button pointer down', () => {
const target = createEventTarget(ref.current);
const pointerType = 'mouse';
target.pointerdown({buttons: buttonsType.auxiliary, pointerType});
target.pointerup({pointerType});
expect(onPressStart).toHaveBeenCalledTimes(1);
expect(onPressStart).toHaveBeenCalledWith(
expect.objectContaining({
buttons: buttonsType.auxiliary,
pointerType: 'mouse',
type: 'pressstart',
}),
);
});
it('ignores any events not caused by primary/middle-click or touch/pen contact', () => {
const target = createEventTarget(ref.current);
target.pointerdown({buttons: buttonsType.secondary});
target.pointerup({buttons: buttonsType.secondary});
target.pointerdown({buttons: buttonsType.eraser});
target.pointerup({buttons: buttonsType.eraser});
expect(onPressStart).toHaveBeenCalledTimes(0);
});
it('is called once after "keydown" events for Enter', () => {
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter'});
target.keydown({key: 'Enter'});
target.keydown({key: 'Enter'});
expect(onPressStart).toHaveBeenCalledTimes(1);
expect(onPressStart).toHaveBeenCalledWith(
expect.objectContaining({pointerType: 'keyboard', type: 'pressstart'}),
);
});
it('is called once after "keydown" events for Spacebar', () => {
const target = createEventTarget(ref.current);
const preventDefault = jest.fn();
target.keydown({key: ' ', preventDefault});
expect(preventDefault).toBeCalled();
target.keydown({key: ' ', preventDefault});
expect(onPressStart).toHaveBeenCalledTimes(1);
expect(onPressStart).toHaveBeenCalledWith(
expect.objectContaining({
pointerType: 'keyboard',
type: 'pressstart',
}),
);
});
it('is not called after "keydown" for other keys', () => {
const target = createEventTarget(ref.current);
target.keydown({key: 'a'});
expect(onPressStart).not.toBeCalled();
});
});
describe('onPressEnd', () => {
let onPressEnd, ref;
beforeEach(() => {
onPressEnd = jest.fn();
ref = React.createRef();
const Component = () => {
const listener = usePress({
onPressEnd,
});
return <div ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
document.elementFromPoint = () => ref.current;
});
it.each(pointerTypesTable)(
'is called after pointer up: %s',
pointerType => {
const target = createEventTarget(ref.current);
target.pointerdown({pointerType});
target.pointerup({pointerType});
expect(onPressEnd).toHaveBeenCalledTimes(1);
expect(onPressEnd).toHaveBeenCalledWith(
expect.objectContaining({pointerType, type: 'pressend'}),
);
},
);
it('is called after middle-button pointer up', () => {
const target = createEventTarget(ref.current);
target.pointerdown({
buttons: buttonsType.auxiliary,
pointerType: 'mouse',
});
target.pointerup({pointerType: 'mouse'});
expect(onPressEnd).toHaveBeenCalledTimes(1);
expect(onPressEnd).toHaveBeenCalledWith(
expect.objectContaining({
buttons: buttonsType.auxiliary,
pointerType: 'mouse',
type: 'pressend',
}),
);
});
it('is called after "keyup" event for Enter', () => {
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter'});
// click occurs before keyup
target.virtualclick();
target.keyup({key: 'Enter'});
expect(onPressEnd).toHaveBeenCalledTimes(1);
expect(onPressEnd).toHaveBeenCalledWith(
expect.objectContaining({pointerType: 'keyboard', type: 'pressend'}),
);
});
it('is called after "keyup" event for Spacebar', () => {
const target = createEventTarget(ref.current);
target.keydown({key: ' '});
target.keyup({key: ' '});
expect(onPressEnd).toHaveBeenCalledTimes(1);
expect(onPressEnd).toHaveBeenCalledWith(
expect.objectContaining({pointerType: 'keyboard', type: 'pressend'}),
);
});
it('is not called after "keyup" event for other keys', () => {
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter'});
target.keyup({key: 'a'});
expect(onPressEnd).not.toBeCalled();
});
it('is called with keyboard modifiers', () => {
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter'});
target.keyup({
key: 'Enter',
metaKey: true,
ctrlKey: true,
altKey: true,
shiftKey: true,
});
expect(onPressEnd).toHaveBeenCalledWith(
expect.objectContaining({
pointerType: 'keyboard',
type: 'pressend',
metaKey: true,
ctrlKey: true,
altKey: true,
shiftKey: true,
}),
);
});
});
describe('onPressChange', () => {
let onPressChange, ref;
beforeEach(() => {
onPressChange = jest.fn();
ref = React.createRef();
const Component = () => {
const listener = usePress({
onPressChange,
});
return <div ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
document.elementFromPoint = () => ref.current;
});
it.each(pointerTypesTable)(
'is called after pointer down and up: %s',
pointerType => {
const target = createEventTarget(ref.current);
target.pointerdown({pointerType});
expect(onPressChange).toHaveBeenCalledTimes(1);
expect(onPressChange).toHaveBeenCalledWith(true);
target.pointerup({pointerType});
expect(onPressChange).toHaveBeenCalledTimes(2);
expect(onPressChange).toHaveBeenCalledWith(false);
},
);
it('is called after valid "keydown" and "keyup" events', () => {
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter'});
expect(onPressChange).toHaveBeenCalledTimes(1);
expect(onPressChange).toHaveBeenCalledWith(true);
target.keyup({key: 'Enter'});
expect(onPressChange).toHaveBeenCalledTimes(2);
expect(onPressChange).toHaveBeenCalledWith(false);
});
});
describe('onPress', () => {
let onPress, ref;
beforeEach(() => {
onPress = jest.fn();
ref = React.createRef();
const Component = () => {
const listener = usePress({
onPress,
});
return <div ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
ref.current.getBoundingClientRect = () => ({
top: 0,
left: 0,
bottom: 100,
right: 100,
});
document.elementFromPoint = () => ref.current;
});
it.each(pointerTypesTable)(
'is called after pointer up: %s',
pointerType => {
const target = createEventTarget(ref.current);
target.pointerdown({pointerType});
target.pointerup({pointerType, x: 10, y: 10});
expect(onPress).toHaveBeenCalledTimes(1);
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({pointerType, type: 'press'}),
);
},
);
it('is not called after middle-button press', () => {
const target = createEventTarget(ref.current);
target.pointerdown({
buttons: buttonsType.auxiliary,
pointerType: 'mouse',
});
target.pointerup({pointerType: 'mouse'});
expect(onPress).not.toHaveBeenCalled();
});
it('is called after valid "keyup" event', () => {
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter'});
target.keyup({key: 'Enter'});
expect(onPress).toHaveBeenCalledTimes(1);
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({pointerType: 'keyboard', type: 'press'}),
);
});
it('is not called after invalid "keyup" event', () => {
const inputRef = React.createRef();
const Component = () => {
const listener = usePress({onPress});
return <input ref={inputRef} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
const target = createEventTarget(inputRef.current);
target.keydown({key: 'Enter'});
target.keyup({key: 'Enter'});
target.keydown({key: ' '});
target.keyup({key: ' '});
expect(onPress).not.toBeCalled();
});
it('is called with modifier keys', () => {
const target = createEventTarget(ref.current);
target.pointerdown({metaKey: true, pointerType: 'mouse'});
target.pointerup({metaKey: true, pointerType: 'mouse'});
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({
pointerType: 'mouse',
type: 'press',
metaKey: true,
}),
);
});
it('is called once after virtual screen reader "click" event', () => {
const target = createEventTarget(ref.current);
const preventDefault = jest.fn();
target.virtualclick({preventDefault});
expect(preventDefault).toBeCalled();
expect(onPress).toHaveBeenCalledTimes(1);
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({
pointerType: 'keyboard',
type: 'press',
}),
);
});
});
describe('onPressMove', () => {
let onPressMove, ref;
beforeEach(() => {
onPressMove = jest.fn();
ref = React.createRef();
const Component = () => {
const listener = usePress({
onPressMove,
});
return <div ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
ref.current.getBoundingClientRect = () => ({
top: 0,
left: 0,
bottom: 100,
right: 100,
});
document.elementFromPoint = () => ref.current;
});
it.each(pointerTypesTable)(
'is called after pointer move: %s',
pointerType => {
const node = ref.current;
const target = createEventTarget(node);
target.setBoundingClientRect({x: 0, y: 0, width: 100, height: 100});
target.pointerdown({pointerType});
target.pointermove({pointerType, x: 10, y: 10});
target.pointermove({pointerType, x: 20, y: 20});
expect(onPressMove).toHaveBeenCalledTimes(2);
expect(onPressMove).toHaveBeenCalledWith(
expect.objectContaining({pointerType, type: 'pressmove'}),
);
},
);
it('is not called if pointer move occurs during keyboard press', () => {
const target = createEventTarget(ref.current);
target.setBoundingClientRect({x: 0, y: 0, width: 100, height: 100});
target.keydown({key: 'Enter'});
target.pointermove({
buttons: buttonsType.none,
pointerType: 'mouse',
x: 10,
y: 10,
});
expect(onPressMove).not.toBeCalled();
});
});
describe('link components', () => {
it('prevents native behavior by default', () => {
const onPress = jest.fn();
const preventDefault = jest.fn();
const ref = React.createRef();
const Component = () => {
const listener = usePress({onPress});
return <a href="#" ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
const target = createEventTarget(ref.current);
target.pointerdown();
target.pointerup({preventDefault});
expect(preventDefault).toBeCalled();
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({defaultPrevented: true}),
);
});
it('prevents native behaviour for keyboard events by default', () => {
const onPress = jest.fn();
const preventDefaultClick = jest.fn();
const preventDefaultKeyDown = jest.fn();
const ref = React.createRef();
const Component = () => {
const listener = usePress({onPress});
return <a href="#" ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter', preventDefault: preventDefaultKeyDown});
target.virtualclick({preventDefault: preventDefaultClick});
target.keyup({key: 'Enter'});
expect(preventDefaultKeyDown).toBeCalled();
expect(preventDefaultClick).toBeCalled();
expect(onPress).toHaveBeenCalledTimes(1);
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({defaultPrevented: true}),
);
});
it('deeply prevents native behaviour by default', () => {
const onPress = jest.fn();
const preventDefault = jest.fn();
const buttonRef = React.createRef();
const Component = () => {
const listener = usePress({onPress});
return (
<a href="#">
<button ref={buttonRef} DEPRECATED_flareListeners={listener} />
</a>
);
};
ReactDOM.render(<Component />, container);
const target = createEventTarget(buttonRef.current);
target.pointerdown();
target.pointerup({preventDefault});
expect(preventDefault).toBeCalled();
});
it('prevents native behaviour by default with nested elements', () => {
const onPress = jest.fn();
const preventDefault = jest.fn();
const ref = React.createRef();
const Component = () => {
const listener = usePress({onPress});
return (
<a href="#" DEPRECATED_flareListeners={listener}>
<div ref={ref} />
</a>
);
};
ReactDOM.render(<Component />, container);
const target = createEventTarget(ref.current);
target.pointerdown();
target.pointerup({preventDefault});
expect(preventDefault).toBeCalled();
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({defaultPrevented: true}),
);
});
it('uses native behaviour for interactions with modifier keys', () => {
const onPress = jest.fn();
const preventDefault = jest.fn();
const ref = React.createRef();
const Component = () => {
const listener = usePress({onPress});
return <a href="#" ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
['metaKey', 'ctrlKey', 'shiftKey'].forEach(modifierKey => {
const target = createEventTarget(ref.current);
target.pointerdown({[modifierKey]: true});
target.pointerup({[modifierKey]: true, preventDefault});
expect(preventDefault).not.toBeCalled();
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({defaultPrevented: false}),
);
});
});
it('uses native behaviour for pointer events if preventDefault is false', () => {
const onPress = jest.fn();
const preventDefault = jest.fn();
const ref = React.createRef();
const Component = () => {
const listener = usePress({onPress, preventDefault: false});
return <a href="#" ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
const target = createEventTarget(ref.current);
target.pointerdown();
target.pointerup({preventDefault});
expect(preventDefault).not.toBeCalled();
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({defaultPrevented: false}),
);
});
it('uses native behaviour for keyboard events if preventDefault is false', () => {
const onPress = jest.fn();
const preventDefault = jest.fn();
const ref = React.createRef();
const Component = () => {
const listener = usePress({onPress, preventDefault: false});
return <a href="#" ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
const target = createEventTarget(ref.current);
target.keydown({key: 'Enter'});
target.virtualclick({preventDefault});
target.keyup({key: 'Enter'});
expect(preventDefault).not.toBeCalled();
expect(onPress).toHaveBeenCalledTimes(1);
expect(onPress).toHaveBeenCalledWith(
expect.objectContaining({defaultPrevented: false}),
);
});
});
it('should not trigger an invariant in addRootEventTypes()', () => {
const ref = React.createRef();
const Component = () => {
const listener = usePress();
return <button ref={ref} DEPRECATED_flareListeners={listener} />;
};
ReactDOM.render(<Component />, container);
const target = createEventTarget(ref.current);
target.pointerdown();
target.pointermove();
target.pointerup();
target.pointerdown();
});
});
|
/**
* React App SDK (https://github.com/kriasoft/react-app)
*
* Copyright © 2015-present 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 from 'react';
import Layout from '../../components/Layout';
import s from './GetStarted.css';
import { title, html } from './GetStarted.md';
class AboutPage extends React.Component {
componentDidMount() {
document.title = title;
}
render() {
return (
<Layout className={s.content}>
<h1>{title}</h1>
<div dangerouslySetInnerHTML={{ __html: html }} />
</Layout>
);
}
}
export default AboutPage;
|
var pswpElement = document.querySelectorAll('.pswp')[0];
// build items array
var items = [{
src: 'https://placekitten.com/600/400',
w: 600,
h: 400
}, {
src: 'https://placekitten.com/1200/900',
w: 1200,
h: 900
}];
// define options (if needed)
var options = {
// optionName: 'option value'
// for example:
index: 0 // start at first slide
};
// Initializes and opens PhotoSwipe
var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
gallery.init(); |
/**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { PropTypes } from 'react';
import './Layout.scss';
import Navigation from '../Navigation';
function Layout({ children }) {
// {{ /* <Navigation /> */ }}
return (
<div className="Layout" onTouchStart={() => { window.hasTouch = true }}>
{children}
</div>
);
}
Layout.propTypes = {
children: PropTypes.element.isRequired,
};
export default Layout;
|
/**
* Created by King Lee on 15-3-3.
*/
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('announcement_230_000013', { title: 'Express' });
});
module.exports = router;
|
module.exports={A:{A:{"2":"K D G E A B hB"},B:{"1":"2 C d J M H I"},C:{"2":"2 eB DB F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b YB XB","194":"0 1 3 4 6 7 8 9 c e f g h i j k l m n o L q r s t u v w x y z HB GB BB CB FB"},D:{"2":"2 6 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n","322":"0 1 3 4 7 8 9 o L q r s t u v w x y z HB GB BB CB FB RB MB LB kB JB NB OB PB"},E:{"1":"5 D G E A B C TB UB VB WB p ZB","2":"F N K QB IB SB"},F:{"2":"5 E B C J M H I O P Q R S T U V W X Y Z a aB bB cB dB p AB fB","322":"0 1 6 b c e f g h i j k l m n o L q r s t u v w x y z"},G:{"1":"G KB lB mB nB oB pB qB rB sB tB","2":"IB gB EB iB jB"},H:{"2":"uB"},I:{"2":"4 DB F vB wB xB yB EB zB 0B"},J:{"2":"D A"},K:{"2":"5 A B C p AB","322":"L"},L:{"322":"JB"},M:{"2":"3"},N:{"2":"A B"},O:{"2":"1B"},P:{"2":"F 2B 3B 4B 5B 6B"},Q:{"2":"7B"},R:{"2":"8B"},S:{"194":"9B"}},B:1,C:"Video Tracks"};
|
/**
* Created by jszhou on 2017/3/27.
*/
/**
* 格式化日期为YYYY-MM-DD
* @param {Date} dateObject
* @return {string}
*/
function getFormatDate(dateObject) {
let year = dateObject.getFullYear();
let month = dateObject.getMonth() + 1 < 10 ? ('0' + (dateObject.getMonth() + 1)) : (dateObject.getMonth() + 1);
let date = dateObject.getDate() < 10 ? ('0' + dateObject.getDate()) : dateObject.getDate();
return year + '-' + month + '-' + date;
}
export default getFormatDate; |
import { connect } from 'react-redux';
import selectChapters from '../../store/selectors/chaptersSelector';
import selectActiveChapter from '../../store/selectors/activeChapterSelector';
import Chapters from './Chapters';
function mapStatetoProps(state) {
return {
chapters: selectChapters(state),
darkmode: state.application.darkmode,
activeChapter: selectActiveChapter(state),
chapterSelectToggled: false,
};
}
function mapDispatchToProps() {
return {};
}
export default connect(
mapStatetoProps,
mapDispatchToProps,
)(Chapters);
|
'use strict';
$(document).ready(function() {
Handlebars.registerHelper("debug", function(optionalValue) {
console.log("Current Context");
console.log("====================");
console.log(this);
if (optionalValue) {
console.log("Value");
console.log("====================");
console.log(optionalValue);
}
});
var App = {
start: function() {
this.dataProvider = new DataProvider();
this.router = Router(routes);
this.router.configure({
html5history: true
});
this.router.init();
},
user: {
id: 'ivan'
}
};
var routes = {
'/': function() {
var indexView = new IndexView(App);
indexView.fetchData().then(function(result) {
$('.page-layout').empty();
$('.page-layout').append(indexView.render(result.rows));
$('.link-to').on('click', function() {
App.router.setRoute($(this).data('href'));
return false;
});
});
},
'/create': function() {
var editView = new EditView(App);
$('.page-layout').empty();
$('.page-layout').append(editView.render({}));
},
'/:id/edit': function(id) {
var editView = new EditView(App);
editView.fetchData(id).then(function() {
editView.render();
});
},
};
App.start();
}); |
var template = require('lodash.template');
var reEscape = require('lodash._reescape');
var reEvaluate = require('lodash._reevaluate');
var reInterpolate = require('lodash._reinterpolate');
var forcedSettings = {
escape: reEscape,
evaluate: reEvaluate,
interpolate: reInterpolate
};
module.exports = function (tmpl, data) {
var fn = template(tmpl, forcedSettings);
var wrapped = function (o) {
if (typeof o === 'undefined' || typeof o.file === 'undefined') throw new Error('Failed to provide the current file as "file" to the template');
return fn(o);
};
return (data ? wrapped(data) : wrapped);
};
|
'use strict';
var React = require('react');
var mui = require('material-ui');
var SvgIcon = mui.SvgIcon;
var DeviceSignalCellularConnectedNoInternet2Bar = React.createClass({
displayName: 'DeviceSignalCellularConnectedNoInternet2Bar',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { 'fill-opacity': '.3', d: 'M22 8V2L2 22h16V8z' }),
React.createElement('path', { d: 'M14 22V10L2 22h12zm6-12v8h2v-8h-2zm0 12h2v-2h-2v2z' })
);
}
});
module.exports = DeviceSignalCellularConnectedNoInternet2Bar; |
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6z" /></g></React.Fragment>
, 'Brightness5Sharp');
|
let ExampleModule = require('../src/JavaScriptSkeleton.js');
describe("JavaScriptSkeleton", function () {
it("can greet the world", function () {
let em = new ExampleModule();
expect(em.hello()).toEqual("Hello friend.");
});
});
|
'use strict';
/* eslint-disable no-empty-function, no-unused-vars */
/**
* Every received message will be sent to all clients that are connected to the instance.
* Client A, B and C are connected to a WebSocket server instance with this plugin.
* When A sends a message then it will be sent to B and C, but not back to A.
* @constructor
* @struct
* @see {!PluginWorker}
* @param {!PluginContext} context
*/
function BroadcastPlugin(context) {
/**
* @param {!WebSocketMessage} message
* @param {!WebSocketConnection} myConnection
*/
this.onMessage = (message, myConnection) => {
const connections = context.instance.getConnections();
connections.forEach(connection => {
if (connection.id !== myConnection.id) {
context.log.debug('Sending message to ' + connection.id);
connection.send(message.data);
}
});
};
}
/**
* @param {?} data
* @param {PluginContext} context
* @param {CommandConfig} command
*/
function executeBroadcastCommand(data, context, command) {
const connections = context.instance.getConnections();
context.log.debug('Execute command: ' + command.name);
connections.forEach(connection => {
context.log.debug('Sending message to ' + connection.id);
connection.send(data);
});
return Promise.resolve({
message: `Data was send on instance "${context.instance.name}" to ${connections.length} connections`,
instanceName: context.instance.name,
connectionCount: connections.length
});
}
module.exports = {
name: 'broadcast',
description: 'Every received message will be sent to all connected clients.',
createWorker: context => new BroadcastPlugin(context),
commands: [
{
name: 'broadcast',
displayName: 'Broadcast',
description: 'Send a message to all connected clients',
execute: executeBroadcastCommand,
exampleData: {
message: 'Hello World'
}
}
]
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.