code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
'use strict';
module.exports = function (context) {
return {
CallExpression: function (node) {
if (node.callee.name === 'alert') {
context.report(node, 'testing custom rules.');
}
}
};
};
| inswave/websquare-lint | conf/rules_notuse/no-alert.js | JavaScript | mit | 204 |
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
function echo(msg) {
WScript.Echo(msg);
}
function guarded_call(func) {
try {
func();
} catch(e) {
echo("Exception: " + e.name + " : " + e.message);
}
}
function dump_args() {
var args = "";
for (var i = 0; i < arguments.length; i++) {
if (i > 0) {
args += ", ";
}
args += arguments[i];
}
echo("Called with this: " + typeof this + "[" + this + "], args: [" + args + "]");
}
// 1. If IsCallable(func) is false, throw TypeError
var noncallable = {
apply: Function.prototype.apply
};
echo("--- f is not callable ---");
guarded_call(function() {
noncallable.apply();
});
guarded_call(function() {
noncallable.apply({}, [1, 2, 3]);
});
// 2. If argArray is null or undefined, call func with an empty list of arguments
var o = {};
echo("\n--- f.apply(x) ---");
guarded_call(function() {
dump_args.apply(o);
});
echo("\n--- f.apply(x, null), f.apply(x, undefined) ---");
guarded_call(function() {
dump_args.apply(o, null);
});
guarded_call(function() {
dump_args.apply(o, undefined);
});
// 3. Type(argArray) is invalid
echo("\n--- f.apply(x, 123), f.apply(x, 'string'), f.apply(x, true) ---");
guarded_call(function() {
dump_args.apply(o, 123);
});
guarded_call(function() {
dump_args.apply(o, 'string');
});
guarded_call(function() {
dump_args.apply(o, true);
});
// 5, 7 argArray.length is invalid
echo("\n--- f.apply(x, obj), obj.length is null/undefined/NaN/string/OutOfRange ---");
guarded_call(function() {
dump_args.apply(o, {length: null});
});
guarded_call(function() {
dump_args.apply(o, {length: undefined});
});
guarded_call(function() {
dump_args.apply(o, {length: NaN});
});
guarded_call(function() {
dump_args.apply(o, {length: 'string'});
});
guarded_call(function() {
dump_args.apply(o, {length: 4294967295 + 1}); //UINT32_MAX + 1
});
guarded_call(function() {
dump_args.apply(o, {length: -1});
});
echo("\n--- f.apply(x, arr), arr.length is huge ---");
var huge_array_length = [];
huge_array_length.length = 2147483647; //INT32_MAX
guarded_call(function() {
dump_args.apply(o, huge_array_length);
});
echo("\n--- f.apply(x, obj), obj.length is huge ---");
guarded_call(function() {
dump_args.apply(o, {length: 4294967295}); //UINT32_MAX
});
// Normal usage -- argArray tests
echo("\n--- f.apply(x, arr) ---");
dump_args.apply(o, []);
dump_args.apply(o, [1]);
dump_args.apply(o, [2, 3, NaN, null, undefined, false, "hello", o]);
echo("\n--- f.apply(x, arr) arr.length increased ---");
var arr = [1, 2];
arr.length = 5;
dump_args.apply(o, arr);
echo("\n--- f.apply(x, arguments) ---");
function apply_arguments() {
dump_args.apply(o, arguments);
}
apply_arguments();
apply_arguments(1);
apply_arguments(2, 3, NaN, null, undefined, false, "hello", o);
echo("\n--- f.apply(x, obj) ---");
guarded_call(function() {
dump_args.apply(o, {
length: 0
});
});
guarded_call(function() {
dump_args.apply(o, {
length: 1,
"0": 1
});
});
guarded_call(function() {
dump_args.apply(o, {
length: 8,
"0": 2,
"1": 3,
"2": NaN,
"3": null,
"4": undefined,
"5": false,
"6": "hello",
"7": o
});
});
// Normal usage -- thisArg tests
function f1() {
this.x1 = "hello";
}
echo("\n--- f.apply(), f.apply(null), f.apply(undefined), global x1 should be changed ---");
f1.apply();
echo("global x1 : " + x1);
x1 = 0;
f1.apply(null);
echo("global x1 : " + x1);
x1 = 0;
f1.apply(undefined);
echo("global x1 : " + x1);
echo("\n--- f.apply(x), global x1 should NOT be changed ---");
var o = {};
x1 = 0;
f1.apply(o);
echo("global x1 : " + x1);
echo("o.x1 : " + o.x1);
// apply on non-objects -- test thisArg
function apply_non_object(func, doEcho) {
var echo_if = function(msg) {
if (doEcho) {
echo(msg);
}
};
guarded_call(function() {
echo_if(func.apply());
});
guarded_call(function() {
echo_if(func.apply(null));
});
guarded_call(function() {
echo_if(func.apply(undefined));
});
guarded_call(function() {
echo_if(func.apply(123));
});
guarded_call(function() {
echo_if(func.apply(true));
});
guarded_call(function() {
echo_if(func.apply("string"));
});
}
echo("\n--- f.apply(v), v is missing/null/undefined/123/true/'string' ---");
apply_non_object(dump_args);
//
// ES5: String.prototype.charCodeAt calls CheckObjectCoercible(thisArg). It should throw
// when thisArg is missing/null/undefined.
//
echo("\n--- f.apply(v), v is missing/null/undefined/123/true/'string', f: string.charCodeAt ---");
apply_non_object(String.prototype.charCodeAt, true);
echo("\n--- f.apply(v), v is missing/null/undefined/123/true/'string', f: string.charAt ---");
apply_non_object(String.prototype.charAt, true);
//
// Similarly, test thisArg behavior in Function.prototype.call
//
// call on non-objects -- test thisArg
function call_non_object(func, doEcho) {
var echo_if = function(msg) {
if (doEcho) {
echo(msg);
}
};
guarded_call(function() {
echo_if(func.call());
});
guarded_call(function() {
echo_if(func.call(null));
});
guarded_call(function() {
echo_if(func.call(undefined));
});
guarded_call(function() {
echo_if(func.call(123));
});
guarded_call(function() {
echo_if(func.call(true));
});
guarded_call(function() {
echo_if(func.call("string"));
});
}
echo("\n--- f.call(v), v is missing/null/undefined/123/true/'string' ---");
call_non_object(dump_args);
echo("\n--- f.call(v), v is missing/null/undefined/123/true/'string', f: string.charCodeAt ---");
call_non_object(String.prototype.charCodeAt, true);
echo("\n--- f.call(v), v is missing/null/undefined/123/true/'string', f: string.charAt ---");
call_non_object(String.prototype.charAt, true);
| Microsoft/ChakraCore | test/Function/apply3.js | JavaScript | mit | 6,608 |
/**
* Rooms
* Pokemon Showdown - http://pokemonshowdown.com/
*
* Every chat room and battle is a room, and what they do is done in
* rooms.js. There's also a global room which every user is in, and
* handles miscellaneous things like welcoming the user.
*
* @license MIT license
*/
const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000;
const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000;
const REPORT_USER_STATS_INTERVAL = 1000 * 60 * 10;
var fs = require('fs');
/* global Rooms: true */
var Rooms = module.exports = getRoom;
var rooms = Rooms.rooms = Object.create(null);
var Room = (function () {
function Room(roomid, title) {
this.id = roomid;
this.title = (title || roomid);
this.users = Object.create(null);
this.log = [];
this.bannedUsers = Object.create(null);
this.bannedIps = Object.create(null);
}
Room.prototype.title = "";
Room.prototype.type = 'chat';
Room.prototype.lastUpdate = 0;
Room.prototype.log = null;
Room.prototype.users = null;
Room.prototype.userCount = 0;
Room.prototype.send = function (message, errorArgument) {
if (errorArgument) throw new Error("Use Room#sendUser");
if (this.id !== 'lobby') message = '>' + this.id + '\n' + message;
Sockets.channelBroadcast(this.id, message);
};
Room.prototype.sendAuth = function (message) {
for (var i in this.users) {
var user = this.users[i];
if (user.connected && user.can('receiveauthmessages', null, this)) {
user.sendTo(this, message);
}
}
};
Room.prototype.sendUser = function (user, message) {
user.sendTo(this, message);
};
Room.prototype.add = function (message) {
if (typeof message !== 'string') throw new Error("Deprecated message type");
this.logEntry(message);
if (this.logTimes && message.substr(0, 3) === '|c|') {
message = '|c:|' + (~~(Date.now() / 1000)) + '|' + message.substr(3);
}
this.log.push(message);
};
Room.prototype.logEntry = function () {};
Room.prototype.addRaw = function (message) {
this.add('|raw|' + message);
};
Room.prototype.getLogSlice = function (amount) {
var log = this.log.slice(amount);
log.unshift('|:|' + (~~(Date.now() / 1000)));
return log;
};
Room.prototype.chat = function (user, message, connection) {
// Battle actions are actually just text commands that are handled in
// parseCommand(), which in turn often calls Simulator.prototype.sendFor().
// Sometimes the call to sendFor is done indirectly, by calling
// room.decision(), where room.constructor === BattleRoom.
message = CommandParser.parse(message, this, user, connection);
if (message) {
this.add('|c|' + user.getIdentity(this.id) + '|' + message);
}
this.update();
};
return Room;
})();
var GlobalRoom = (function () {
function GlobalRoom(roomid) {
this.id = roomid;
// init battle rooms
this.battleCount = 0;
this.searchers = [];
// Never do any other file IO synchronously
// but this is okay to prevent race conditions as we start up PS
this.lastBattle = 0;
try {
this.lastBattle = parseInt(fs.readFileSync('logs/lastbattle.txt')) || 0;
} catch (e) {} // file doesn't exist [yet]
this.chatRoomData = [];
try {
this.chatRoomData = JSON.parse(fs.readFileSync('config/chatrooms.json'));
if (!Array.isArray(this.chatRoomData)) this.chatRoomData = [];
} catch (e) {} // file doesn't exist [yet]
if (!this.chatRoomData.length) {
this.chatRoomData = [{
title: 'Lobby',
isOfficial: true,
autojoin: true
}, {
title: 'Staff',
isPrivate: true,
staffRoom: true,
staffAutojoin: true
}];
}
this.chatRooms = [];
this.autojoin = []; // rooms that users autojoin upon connecting
this.staffAutojoin = []; // rooms that staff autojoin upon connecting
for (var i = 0; i < this.chatRoomData.length; i++) {
if (!this.chatRoomData[i] || !this.chatRoomData[i].title) {
console.log('ERROR: Room number ' + i + ' has no data.');
continue;
}
var id = toId(this.chatRoomData[i].title);
console.log("NEW CHATROOM: " + id);
var room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]);
this.chatRooms.push(room);
if (room.autojoin) this.autojoin.push(id);
if (room.staffAutojoin) this.staffAutojoin.push(id);
}
// this function is complex in order to avoid several race conditions
var self = this;
this.writeNumRooms = (function () {
var writing = false;
var lastBattle; // last lastBattle to be written to file
var finishWriting = function () {
writing = false;
if (lastBattle < self.lastBattle) {
self.writeNumRooms();
}
};
return function () {
if (writing) return;
// batch writing lastbattle.txt for every 10 battles
if (lastBattle >= self.lastBattle) return;
lastBattle = self.lastBattle + 10;
writing = true;
fs.writeFile('logs/lastbattle.txt.0', '' + lastBattle, function () {
// rename is atomic on POSIX, but will throw an error on Windows
fs.rename('logs/lastbattle.txt.0', 'logs/lastbattle.txt', function (err) {
if (err) {
// This should only happen on Windows.
fs.writeFile('logs/lastbattle.txt', '' + lastBattle, finishWriting);
return;
}
finishWriting();
});
});
};
})();
this.writeChatRoomData = (function () {
var writing = false;
var writePending = false; // whether or not a new write is pending
var finishWriting = function () {
writing = false;
if (writePending) {
writePending = false;
self.writeChatRoomData();
}
};
return function () {
if (writing) {
writePending = true;
return;
}
writing = true;
var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]');
fs.writeFile('config/chatrooms.json.0', data, function () {
// rename is atomic on POSIX, but will throw an error on Windows
fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) {
if (err) {
// This should only happen on Windows.
fs.writeFile('config/chatrooms.json', data, finishWriting);
return;
}
finishWriting();
});
});
};
})();
// init users
this.users = {};
this.userCount = 0; // cache of `Object.size(this.users)`
this.maxUsers = 0;
this.maxUsersDate = 0;
this.reportUserStatsInterval = setInterval(
this.reportUserStats.bind(this),
REPORT_USER_STATS_INTERVAL
);
}
GlobalRoom.prototype.type = 'global';
GlobalRoom.prototype.formatListText = '|formats';
GlobalRoom.prototype.reportUserStats = function () {
if (this.maxUsersDate) {
LoginServer.request('updateuserstats', {
date: this.maxUsersDate,
users: this.maxUsers
}, function () {});
this.maxUsersDate = 0;
}
LoginServer.request('updateuserstats', {
date: Date.now(),
users: this.userCount
}, function () {});
};
GlobalRoom.prototype.getFormatListText = function () {
var formatListText = '|formats';
var curSection = '';
for (var i in Tools.data.Formats) {
var format = Tools.data.Formats[i];
if (!format.challengeShow && !format.searchShow) continue;
var section = format.section;
if (section === undefined) section = format.mod;
if (!section) section = '';
if (section !== curSection) {
curSection = section;
formatListText += '|,' + (format.column || 1) + '|' + section;
}
formatListText += '|' + format.name;
if (!format.challengeShow) formatListText += ',,';
else if (!format.searchShow) formatListText += ',';
if (format.team) formatListText += ',#';
}
return formatListText;
};
GlobalRoom.prototype.getRoomList = function (filter) {
var roomList = {};
var total = 0;
for (var i in Rooms.rooms) {
var room = Rooms.rooms[i];
if (!room || !room.active || room.isPrivate) continue;
if (filter && filter !== room.format && filter !== true) continue;
var roomData = {};
if (room.active && room.battle) {
if (room.battle.players[0]) roomData.p1 = room.battle.players[0].getIdentity();
if (room.battle.players[1]) roomData.p2 = room.battle.players[1].getIdentity();
}
if (!roomData.p1 || !roomData.p2) continue;
roomList[room.id] = roomData;
total++;
if (total >= 100) break;
}
return roomList;
};
GlobalRoom.prototype.getRooms = function () {
var roomsData = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount};
for (var i = 0; i < this.chatRooms.length; i++) {
var room = this.chatRooms[i];
if (!room) continue;
if (room.isPrivate) continue;
(room.isOfficial ? roomsData.official : roomsData.chat).push({
title: room.title,
desc: room.desc,
userCount: room.userCount
});
}
return roomsData;
};
GlobalRoom.prototype.cancelSearch = function (user) {
var success = false;
user.cancelChallengeTo();
for (var i = 0; i < this.searchers.length; i++) {
var search = this.searchers[i];
var searchUser = Users.get(search.userid);
if (!searchUser.connected) {
this.searchers.splice(i, 1);
i--;
continue;
}
if (searchUser === user) {
this.searchers.splice(i, 1);
i--;
if (!success) {
searchUser.send('|updatesearch|' + JSON.stringify({searching: false}));
success = true;
}
continue;
}
}
return success;
};
GlobalRoom.prototype.searchBattle = function (user, formatid) {
if (!user.connected) return;
formatid = toId(formatid);
user.prepBattle(formatid, 'search', null, this.finishSearchBattle.bind(this, user, formatid));
};
GlobalRoom.prototype.finishSearchBattle = function (user, formatid, result) {
if (!result) return;
// tell the user they've started searching
var newSearchData = {
format: formatid
};
user.send('|updatesearch|' + JSON.stringify({searching: newSearchData}));
// get the user's rating before actually starting to search
var newSearch = {
userid: user.userid,
formatid: formatid,
team: user.team,
rating: 1000,
time: new Date().getTime()
};
var self = this;
user.doWithMMR(formatid, function (mmr, error) {
if (error) {
user.popup("Connection to ladder server failed with error: " + error + "; please try again later");
return;
}
newSearch.rating = mmr;
self.addSearch(newSearch, user);
});
};
GlobalRoom.prototype.matchmakingOK = function (search1, search2, user1, user2) {
// users must be different
if (user1 === user2) return false;
// users must have different IPs
if (user1.latestIp === user2.latestIp) return false;
// users must not have been matched immediately previously
if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false;
// search must be within range
var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time - search2.time);
if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50;
searchRange += elapsed / 300; // +1 every .3 seconds
if (searchRange > 300) searchRange = 300;
if (Math.abs(search1.rating - search2.rating) > searchRange) return false;
user1.lastMatch = user2.userid;
user2.lastMatch = user1.userid;
return true;
};
GlobalRoom.prototype.addSearch = function (newSearch, user) {
if (!user.connected) return;
for (var i = 0; i < this.searchers.length; i++) {
var search = this.searchers[i];
var searchUser = Users.get(search.userid);
if (!searchUser || !searchUser.connected) {
this.searchers.splice(i, 1);
i--;
continue;
}
if (newSearch.formatid === search.formatid && searchUser === user) return; // only one search per format
if (newSearch.formatid === search.formatid && this.matchmakingOK(search, newSearch, searchUser, user)) {
this.cancelSearch(user, true);
this.cancelSearch(searchUser, true);
user.send('|updatesearch|' + JSON.stringify({searching: false}));
this.startBattle(searchUser, user, search.formatid, true, search.team, newSearch.team);
return;
}
}
this.searchers.push(newSearch);
};
GlobalRoom.prototype.send = function (message, user) {
if (user) {
user.sendTo(this, message);
} else {
Sockets.channelBroadcast(this.id, message);
}
};
GlobalRoom.prototype.sendAuth = function (message) {
for (var i in this.users) {
var user = this.users[i];
if (user.connected && user.can('receiveauthmessages', null, this)) {
user.sendTo(this, message);
}
}
};
GlobalRoom.prototype.add = function (message) {
if (rooms.lobby) rooms.lobby.add(message);
};
GlobalRoom.prototype.addRaw = function (message) {
if (rooms.lobby) rooms.lobby.addRaw(message);
};
GlobalRoom.prototype.addChatRoom = function (title) {
var id = toId(title);
if (rooms[id]) return false;
var chatRoomData = {
title: title
};
var room = Rooms.createChatRoom(id, title, chatRoomData);
this.chatRoomData.push(chatRoomData);
this.chatRooms.push(room);
this.writeChatRoomData();
return true;
};
GlobalRoom.prototype.deregisterChatRoom = function (id) {
id = toId(id);
var room = rooms[id];
if (!room) return false; // room doesn't exist
if (!room.chatRoomData) return false; // room isn't registered
// deregister from global chatRoomData
// looping from the end is a pretty trivial optimization, but the
// assumption is that more recently added rooms are more likely to
// be deleted
for (var i = this.chatRoomData.length - 1; i >= 0; i--) {
if (id === toId(this.chatRoomData[i].title)) {
this.chatRoomData.splice(i, 1);
this.writeChatRoomData();
break;
}
}
delete room.chatRoomData;
return true;
};
GlobalRoom.prototype.delistChatRoom = function (id) {
id = toId(id);
if (!rooms[id]) return false; // room doesn't exist
for (var i = this.chatRooms.length - 1; i >= 0; i--) {
if (id === this.chatRooms[i].id) {
this.chatRooms.splice(i, 1);
break;
}
}
};
GlobalRoom.prototype.removeChatRoom = function (id) {
id = toId(id);
var room = rooms[id];
if (!room) return false; // room doesn't exist
room.destroy();
return true;
};
GlobalRoom.prototype.autojoinRooms = function (user, connection) {
// we only autojoin regular rooms if the client requests it with /autojoin
// note that this restriction doesn't apply to staffAutojoin
for (var i = 0; i < this.autojoin.length; i++) {
user.joinRoom(this.autojoin[i], connection);
}
};
GlobalRoom.prototype.checkAutojoin = function (user, connection) {
if (user.isStaff) {
for (var i = 0; i < this.staffAutojoin.length; i++) {
user.joinRoom(this.staffAutojoin[i], connection);
}
}
};
GlobalRoom.prototype.onJoinConnection = function (user, connection) {
var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
connection.send(initdata + this.formatListText);
if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list
};
GlobalRoom.prototype.onJoin = function (user, connection, merging) {
if (!user) return false; // ???
if (this.users[user.userid]) return user;
this.users[user.userid] = user;
if (++this.userCount > this.maxUsers) {
this.maxUsers = this.userCount;
this.maxUsersDate = Date.now();
}
if (!merging) {
var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n';
connection.send(initdata + this.formatListText);
if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list
}
return user;
};
GlobalRoom.prototype.onRename = function (user, oldid, joining) {
delete this.users[oldid];
this.users[user.userid] = user;
return user;
};
GlobalRoom.prototype.onUpdateIdentity = function () {};
GlobalRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
delete this.users[user.userid];
--this.userCount;
this.cancelSearch(user, true);
};
GlobalRoom.prototype.startBattle = function (p1, p2, format, rated, p1team, p2team) {
var newRoom;
p1 = Users.get(p1);
p2 = Users.get(p2);
if (!p1 || !p2) {
// most likely, a user was banned during the battle start procedure
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
return;
}
if (p1 === p2) {
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
p1.popup("You can't battle your own account. Please use something like Private Browsing to battle yourself.");
return;
}
if (this.lockdown) {
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
p1.popup("The server is shutting down. Battles cannot be started at this time.");
p2.popup("The server is shutting down. Battles cannot be started at this time.");
return;
}
//console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid);
var i = this.lastBattle + 1;
var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, '');
while(rooms['battle-' + formaturlid + i]) {
i++;
}
this.lastBattle = i;
rooms.global.writeNumRooms();
newRoom = this.addRoom('battle-' + formaturlid + '-' + i, format, p1, p2, this.id, rated);
p1.joinRoom(newRoom);
p2.joinRoom(newRoom);
newRoom.joinBattle(p1, p1team);
newRoom.joinBattle(p2, p2team);
this.cancelSearch(p1, true);
this.cancelSearch(p2, true);
if (Config.reportbattles && rooms.lobby) {
rooms.lobby.add('|b|' + newRoom.id + '|' + p1.getIdentity() + '|' + p2.getIdentity());
}
if (Config.logladderip && rated) {
if (!this.ladderIpLog) {
this.ladderIpLog = fs.createWriteStream('logs/ladderip/ladderip.txt', {flags: 'a'});
}
this.ladderIpLog.write(p1.userid+': '+p1.latestIp+'\n');
this.ladderIpLog.write(p2.userid+': '+p2.latestIp+'\n');
}
return newRoom;
};
GlobalRoom.prototype.addRoom = function (room, format, p1, p2, parent, rated) {
room = Rooms.createBattle(room, format, p1, p2, parent, rated);
return room;
};
GlobalRoom.prototype.removeRoom = function (room) {};
GlobalRoom.prototype.chat = function (user, message, connection) {
if (rooms.lobby) return rooms.lobby.chat(user, message, connection);
message = CommandParser.parse(message, this, user, connection);
if (message) {
connection.sendPopup("You can't send messages directly to the server.");
}
};
return GlobalRoom;
})();
var BattleRoom = (function () {
function BattleRoom(roomid, format, p1, p2, parentid, rated) {
Room.call(this, roomid, "" + p1.name + " vs. " + p2.name);
this.modchat = (Config.battlemodchat || false);
format = '' + (format || '');
this.format = format;
this.auth = {};
//console.log("NEW BATTLE");
var formatid = toId(format);
if (rated && Tools.getFormat(formatid).rated !== false) {
rated = {
p1: p1.userid,
p2: p2.userid,
format: format
};
} else {
rated = false;
}
this.rated = rated;
this.battle = Simulator.create(this.id, format, rated, this);
this.parentid = parentid || '';
this.p1 = p1 || '';
this.p2 = p2 || '';
this.sideTicksLeft = [21, 21];
if (!rated) this.sideTicksLeft = [28, 28];
this.sideTurnTicks = [0, 0];
this.disconnectTickDiff = [0, 0];
if (Config.forcetimer) this.requestKickInactive(false);
}
BattleRoom.prototype = Object.create(Room.prototype);
BattleRoom.prototype.type = 'battle';
BattleRoom.prototype.resetTimer = null;
BattleRoom.prototype.resetUser = '';
BattleRoom.prototype.expireTimer = null;
BattleRoom.prototype.active = false;
BattleRoom.prototype.push = function (message) {
if (typeof message === 'string') {
this.log.push(message);
} else {
this.log = this.log.concat(message);
}
};
BattleRoom.prototype.win = function (winner) {
if (this.rated) {
var winnerid = toId(winner);
var rated = this.rated;
this.rated = false;
var p1score = 0.5;
if (winnerid === rated.p1) {
p1score = 1;
} else if (winnerid === rated.p2) {
p1score = 0;
}
var p1 = rated.p1;
if (Users.getExact(rated.p1)) p1 = Users.getExact(rated.p1).name;
var p2 = rated.p2;
if (Users.getExact(rated.p2)) p2 = Users.getExact(rated.p2).name;
//update.updates.push('[DEBUG] uri: ' + Config.loginserver + 'action.php?act=ladderupdate&serverid=' + Config.serverid + '&p1=' + encodeURIComponent(p1) + '&p2=' + encodeURIComponent(p2) + '&score=' + p1score + '&format=' + toId(rated.format) + '&servertoken=[token]');
if (!rated.p1 || !rated.p2) {
this.push('|raw|ERROR: Ladder not updated: a player does not exist');
} else {
winner = Users.get(winnerid);
if (winner && !winner.authenticated) {
this.sendUser(winner, '|askreg|' + winner.userid);
}
var p1rating, p2rating;
// update rankings
this.push('|raw|Ladder updating...');
var self = this;
LoginServer.request('ladderupdate', {
p1: p1,
p2: p2,
score: p1score,
format: toId(rated.format)
}, function (data, statusCode, error) {
if (!self.battle) {
console.log('room expired before ladder update was received');
return;
}
if (!data) {
self.addRaw('Ladder (probably) updated, but score could not be retrieved (' + error + ').');
// log the battle anyway
if (!Tools.getFormat(self.format).noLog) {
self.logBattle(p1score);
}
return;
} else if (data.errorip) {
self.addRaw("This server's request IP " + data.errorip + " is not a registered server.");
return;
} else {
try {
p1rating = data.p1rating;
p2rating = data.p2rating;
//self.add("Ladder updated.");
var oldacre = Math.round(data.p1rating.oldacre);
var acre = Math.round(data.p1rating.acre);
var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'winning' : (p1score < 0.01 ? 'losing' : 'tying'));
if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons;
self.addRaw(Tools.escapeHTML(p1) + '\'s rating: ' + oldacre + ' → <strong>' + acre + '</strong><br />(' + reasons + ')');
oldacre = Math.round(data.p2rating.oldacre);
acre = Math.round(data.p2rating.acre);
reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'losing' : (p1score < 0.01 ? 'winning' : 'tying'));
if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons;
self.addRaw(Tools.escapeHTML(p2) + '\'s rating: ' + oldacre + ' → <strong>' + acre + '</strong><br />(' + reasons + ')');
Users.get(p1).cacheMMR(rated.format, data.p1rating);
Users.get(p2).cacheMMR(rated.format, data.p2rating);
self.update();
} catch(e) {
self.addRaw('There was an error calculating rating changes.');
self.update();
}
if (!Tools.getFormat(self.format).noLog) {
self.logBattle(p1score, p1rating, p2rating);
}
}
});
}
}
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
this.update();
};
// logNum = 0 : spectator log
// logNum = 1, 2 : player log
// logNum = 3 : replay log
BattleRoom.prototype.getLog = function (logNum) {
var log = [];
for (var i = 0; i < this.log.length; ++i) {
var line = this.log[i];
if (line === '|split') {
log.push(this.log[i + logNum + 1]);
i += 4;
} else {
log.push(line);
}
}
return log;
};
BattleRoom.prototype.getLogForUser = function (user) {
var logNum = this.battle.getSlot(user) + 1;
if (logNum < 0) logNum = 0;
return this.getLog(logNum);
};
BattleRoom.prototype.update = function (excludeUser) {
if (this.log.length <= this.lastUpdate) return;
Sockets.subchannelBroadcast(this.id, '>' + this.id + '\n\n' + this.log.slice(this.lastUpdate).join('\n'));
this.lastUpdate = this.log.length;
// empty rooms time out after ten minutes
var hasUsers = false;
for (var i in this.users) {
hasUsers = true;
break;
}
if (!hasUsers) {
if (!this.expireTimer) {
this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_EMPTY_DEALLOCATE);
}
} else {
if (this.expireTimer) clearTimeout(this.expireTimer);
this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_INACTIVE_DEALLOCATE);
}
};
BattleRoom.prototype.logBattle = function (p1score, p1rating, p2rating) {
var logData = this.battle.logData;
logData.p1rating = p1rating;
logData.p2rating = p2rating;
logData.endType = this.battle.endType;
if (!p1rating) logData.ladderError = true;
logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage)
var date = new Date();
var logfolder = date.format('{yyyy}-{MM}');
var logsubfolder = date.format('{yyyy}-{MM}-{dd}');
var curpath = 'logs/' + logfolder;
var self = this;
fs.mkdir(curpath, '0755', function () {
var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, '');
curpath += '/' + tier;
fs.mkdir(curpath, '0755', function () {
curpath += '/' + logsubfolder;
fs.mkdir(curpath, '0755', function () {
fs.writeFile(curpath + '/' + self.id + '.log.json', JSON.stringify(logData));
});
});
}); // asychronicity
//console.log(JSON.stringify(logData));
};
BattleRoom.prototype.tryExpire = function () {
this.expire();
};
BattleRoom.prototype.getInactiveSide = function () {
if (this.battle.players[0] && !this.battle.players[1]) return 1;
if (this.battle.players[1] && !this.battle.players[0]) return 0;
return this.battle.inactiveSide;
};
BattleRoom.prototype.forfeit = function (user, message, side) {
if (!this.battle || this.battle.ended || !this.battle.started) return false;
if (!message) message = ' forfeited.';
if (side === undefined) {
if (user && user.userid === this.battle.playerids[0]) side = 0;
if (user && user.userid === this.battle.playerids[1]) side = 1;
}
if (side === undefined) return false;
var ids = ['p1', 'p2'];
var otherids = ['p2', 'p1'];
var name = 'Player ' + (side + 1);
if (user) {
name = user.name;
} else if (this.rated) {
name = this.rated[ids[side]];
}
this.add('|-message|' + name + message);
this.battle.endType = 'forfeit';
this.battle.send('win', otherids[side]);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
this.update();
return true;
};
BattleRoom.prototype.sendPlayer = function (num, message) {
var player = this.battle.getPlayer(num);
if (!player) return false;
this.sendUser(player, message);
};
BattleRoom.prototype.kickInactive = function () {
clearTimeout(this.resetTimer);
this.resetTimer = null;
if (!this.battle || this.battle.ended || !this.battle.started) return false;
var inactiveSide = this.getInactiveSide();
var ticksLeft = [0, 0];
if (inactiveSide !== 1) {
// side 0 is inactive
this.sideTurnTicks[0]--;
this.sideTicksLeft[0]--;
}
if (inactiveSide !== 0) {
// side 1 is inactive
this.sideTurnTicks[1]--;
this.sideTicksLeft[1]--;
}
ticksLeft[0] = Math.min(this.sideTurnTicks[0], this.sideTicksLeft[0]);
ticksLeft[1] = Math.min(this.sideTurnTicks[1], this.sideTicksLeft[1]);
if (ticksLeft[0] && ticksLeft[1]) {
if (inactiveSide === 0 || inactiveSide === 1) {
// one side is inactive
var inactiveTicksLeft = ticksLeft[inactiveSide];
var inactiveUser = this.battle.getPlayer(inactiveSide);
if (inactiveTicksLeft % 3 === 0 || inactiveTicksLeft <= 4) {
this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' has ' + (inactiveTicksLeft * 10) + ' seconds left.');
}
} else {
// both sides are inactive
var inactiveUser0 = this.battle.getPlayer(0);
if (inactiveUser0 && (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4)) {
this.sendUser(inactiveUser0, '|inactive|' + inactiveUser0.name + ' has ' + (ticksLeft[0] * 10) + ' seconds left.');
}
var inactiveUser1 = this.battle.getPlayer(1);
if (inactiveUser1 && (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4)) {
this.sendUser(inactiveUser1, '|inactive|' + inactiveUser1.name + ' has ' + (ticksLeft[1] * 10) + ' seconds left.');
}
}
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000);
return;
}
if (inactiveSide < 0) {
if (ticksLeft[0]) inactiveSide = 1;
else if (ticksLeft[1]) inactiveSide = 0;
}
this.forfeit(this.battle.getPlayer(inactiveSide), ' lost due to inactivity.', inactiveSide);
this.resetUser = '';
};
BattleRoom.prototype.requestKickInactive = function (user, force) {
if (this.resetTimer) {
if (user) this.sendUser(user, '|inactive|The inactivity timer is already counting down.');
return false;
}
if (user) {
if (!force && this.battle.getSlot(user) < 0) return false;
this.resetUser = user.userid;
this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by ' + user.name + ')');
} else if (user === false) {
this.resetUser = '~';
this.add('|inactive|Battle timer is ON: inactive players will automatically lose when time\'s up.');
}
// a tick is 10 seconds
var maxTicksLeft = 15; // 2 minutes 30 seconds
if (!this.battle.p1 || !this.battle.p2) {
// if a player has left, don't wait longer than 6 ticks (1 minute)
maxTicksLeft = 6;
}
if (!this.rated) maxTicksLeft = 30;
this.sideTurnTicks = [maxTicksLeft, maxTicksLeft];
var inactiveSide = this.getInactiveSide();
if (inactiveSide < 0) {
// add 10 seconds to bank if they're below 160 seconds
if (this.sideTicksLeft[0] < 16) this.sideTicksLeft[0]++;
if (this.sideTicksLeft[1] < 16) this.sideTicksLeft[1]++;
}
this.sideTicksLeft[0]++;
this.sideTicksLeft[1]++;
if (inactiveSide !== 1) {
// side 0 is inactive
var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft);
this.sendPlayer(0, '|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.');
}
if (inactiveSide !== 0) {
// side 1 is inactive
var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft);
this.sendPlayer(1, '|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.');
}
this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000);
return true;
};
BattleRoom.prototype.nextInactive = function () {
if (this.resetTimer) {
this.update();
clearTimeout(this.resetTimer);
this.resetTimer = null;
this.requestKickInactive();
}
};
BattleRoom.prototype.stopKickInactive = function (user, force) {
if (!force && user && user.userid !== this.resetUser) return false;
if (this.resetTimer) {
clearTimeout(this.resetTimer);
this.resetTimer = null;
this.send('|inactiveoff|Battle timer is now OFF.');
return true;
}
return false;
};
BattleRoom.prototype.kickInactiveUpdate = function () {
if (!this.rated) return false;
if (this.resetTimer) {
var inactiveSide = this.getInactiveSide();
var changed = false;
if ((!this.battle.p1 || !this.battle.p2) && !this.disconnectTickDiff[0] && !this.disconnectTickDiff[1]) {
if ((!this.battle.p1 && inactiveSide === 0) || (!this.battle.p2 && inactiveSide === 1)) {
var inactiveUser = this.battle.getPlayer(inactiveSide);
if (!this.battle.p1 && inactiveSide === 0 && this.sideTurnTicks[0] > 7) {
this.disconnectTickDiff[0] = this.sideTurnTicks[0] - 7;
this.sideTurnTicks[0] = 7;
changed = true;
} else if (!this.battle.p2 && inactiveSide === 1 && this.sideTurnTicks[1] > 7) {
this.disconnectTickDiff[1] = this.sideTurnTicks[1] - 7;
this.sideTurnTicks[1] = 7;
changed = true;
}
if (changed) {
this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' disconnected and has a minute to reconnect!');
return true;
}
}
} else if (this.battle.p1 && this.battle.p2) {
// Only one of the following conditions should happen, but do
// them both since you never know...
if (this.disconnectTickDiff[0]) {
this.sideTurnTicks[0] = this.sideTurnTicks[0] + this.disconnectTickDiff[0];
this.disconnectTickDiff[0] = 0;
changed = 0;
}
if (this.disconnectTickDiff[1]) {
this.sideTurnTicks[1] = this.sideTurnTicks[1] + this.disconnectTickDiff[1];
this.disconnectTickDiff[1] = 0;
changed = 1;
}
if (changed !== false) {
var user = this.battle.getPlayer(changed);
this.send('|inactive|' + (user ? user.name : 'Player ' + (changed + 1)) + ' reconnected and has ' + (this.sideTurnTicks[changed] * 10) + ' seconds left!');
return true;
}
}
}
return false;
};
BattleRoom.prototype.decision = function (user, choice, data) {
this.battle.sendFor(user, choice, data);
if (this.active !== this.battle.active) {
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
}
this.update();
};
// This function is only called when the room is not empty.
// Joining an empty room calls this.join() below instead.
BattleRoom.prototype.onJoinConnection = function (user, connection) {
this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'));
// this handles joining a battle in which a user is a participant,
// where the user has already identified before attempting to join
// the battle
this.battle.resendRequest(user);
};
BattleRoom.prototype.onJoin = function (user, connection) {
if (!user) return false;
if (this.users[user.userid]) return user;
if (user.named) {
this.add('|join|' + user.name);
this.update();
}
this.users[user.userid] = user;
this.userCount++;
this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'));
return user;
};
BattleRoom.prototype.onRename = function (user, oldid, joining) {
if (joining) {
this.add('|join|' + user.name);
}
var resend = joining || !this.battle.playerTable[oldid];
if (this.battle.playerTable[oldid]) {
if (this.rated) {
this.add('|message|' + user.name + ' forfeited by changing their name.');
this.battle.lose(oldid);
this.battle.leave(oldid);
resend = false;
} else {
this.battle.rename();
}
}
delete this.users[oldid];
this.users[user.userid] = user;
this.update();
if (resend) {
// this handles a named user renaming themselves into a user in the
// battle (i.e. by using /nick)
this.battle.resendRequest(user);
}
return user;
};
BattleRoom.prototype.onUpdateIdentity = function () {};
BattleRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
if (user.battles[this.id]) {
this.battle.leave(user);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
} else if (!user.named) {
delete this.users[user.userid];
return;
}
delete this.users[user.userid];
this.userCount--;
this.add('|leave|' + user.name);
if (Object.isEmpty(this.users)) {
rooms.global.battleCount += 0 - (this.active ? 1 : 0);
this.active = false;
}
this.update();
this.kickInactiveUpdate();
};
BattleRoom.prototype.joinBattle = function (user, team) {
var slot;
if (this.rated) {
if (this.rated.p1 === user.userid) {
slot = 0;
} else if (this.rated.p2 === user.userid) {
slot = 1;
} else {
user.popup("This is a rated battle; your username must be " + this.rated.p1 + " or " + this.rated.p2 + " to join.");
return false;
}
}
if (this.battle.active) {
user.popup("This battle already has two players.");
return false;
}
this.auth[user.userid] = '\u2605';
this.battle.join(user, slot, team);
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
if (this.active) {
this.title = "" + this.battle.p1 + " vs. " + this.battle.p2;
this.send('|title|' + this.title);
}
this.update();
this.kickInactiveUpdate();
};
BattleRoom.prototype.leaveBattle = function (user) {
if (!user) return false; // ...
if (user.battles[this.id]) {
this.battle.leave(user);
} else {
return false;
}
this.auth[user.userid] = '+';
rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0);
this.active = this.battle.active;
this.update();
this.kickInactiveUpdate();
return true;
};
BattleRoom.prototype.expire = function () {
this.send('|expire|');
this.destroy();
};
BattleRoom.prototype.destroy = function () {
// deallocate ourself
// remove references to ourself
for (var i in this.users) {
this.users[i].leaveRoom(this);
delete this.users[i];
}
this.users = null;
rooms.global.removeRoom(this.id);
// deallocate children and get rid of references to them
if (this.battle) {
this.battle.destroy();
}
this.battle = null;
if (this.resetTimer) {
clearTimeout(this.resetTimer);
}
this.resetTimer = null;
// get rid of some possibly-circular references
delete rooms[this.id];
};
return BattleRoom;
})();
var ChatRoom = (function () {
function ChatRoom(roomid, title, options) {
Room.call(this, roomid, title);
if (options) {
this.chatRoomData = options;
Object.merge(this, options);
}
this.logTimes = true;
this.logFile = null;
this.logFilename = '';
this.destroyingLog = false;
if (!this.modchat) this.modchat = (Config.chatmodchat || false);
if (Config.logchat) {
this.rollLogFile(true);
this.logEntry = function (entry, date) {
var timestamp = (new Date()).format('{HH}:{mm}:{ss} ');
this.logFile.write(timestamp + entry + '\n');
};
this.logEntry('NEW CHATROOM: ' + this.id);
if (Config.loguserstats) {
setInterval(this.logUserStats.bind(this), Config.loguserstats);
}
}
if (Config.reportjoinsperiod) {
this.userList = this.getUserList();
this.reportJoinsQueue = [];
}
}
ChatRoom.prototype = Object.create(Room.prototype);
ChatRoom.prototype.type = 'chat';
ChatRoom.prototype.reportRecentJoins = function () {
delete this.reportJoinsInterval;
if (this.reportJoinsQueue.length === 0) {
// nothing to report
return;
}
if (Config.reportjoinsperiod) {
this.userList = this.getUserList();
}
this.send(this.reportJoinsQueue.join('\n'));
this.reportJoinsQueue.length = 0;
};
ChatRoom.prototype.rollLogFile = function (sync) {
var mkdir = sync ? function (path, mode, callback) {
try {
fs.mkdirSync(path, mode);
} catch (e) {} // directory already exists
callback();
} : fs.mkdir;
var date = new Date();
var basepath = 'logs/chat/' + this.id + '/';
var self = this;
mkdir(basepath, '0755', function () {
var path = date.format('{yyyy}-{MM}');
mkdir(basepath + path, '0755', function () {
if (self.destroyingLog) return;
path += '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt';
if (path !== self.logFilename) {
self.logFilename = path;
if (self.logFile) self.logFile.destroySoon();
self.logFile = fs.createWriteStream(basepath + path, {flags: 'a'});
// Create a symlink to today's lobby log.
// These operations need to be synchronous, but it's okay
// because this code is only executed once every 24 hours.
var link0 = basepath + 'today.txt.0';
try {
fs.unlinkSync(link0);
} catch (e) {} // file doesn't exist
try {
fs.symlinkSync(path, link0); // `basepath` intentionally not included
try {
fs.renameSync(link0, basepath + 'today.txt');
} catch (e) {} // OS doesn't support atomic rename
} catch (e) {} // OS doesn't support symlinks
}
var timestamp = +date;
date.advance('1 hour').reset('minutes').advance('1 second');
setTimeout(self.rollLogFile.bind(self), +date - timestamp);
});
});
};
ChatRoom.prototype.destroyLog = function (initialCallback, finalCallback) {
this.destroyingLog = true;
initialCallback();
if (this.logFile) {
this.logEntry = function () { };
this.logFile.on('close', finalCallback);
this.logFile.destroySoon();
} else {
finalCallback();
}
};
ChatRoom.prototype.logUserStats = function () {
var total = 0;
var guests = 0;
var groups = {};
Config.groupsranking.forEach(function (group) {
groups[group] = 0;
});
for (var i in this.users) {
var user = this.users[i];
++total;
if (!user.named) {
++guests;
}
++groups[user.group];
}
var entry = '|userstats|total:' + total + '|guests:' + guests;
for (var i in groups) {
entry += '|' + i + ':' + groups[i];
}
this.logEntry(entry);
};
ChatRoom.prototype.getUserList = function () {
var buffer = '';
var counter = 0;
for (var i in this.users) {
if (!this.users[i].named) {
continue;
}
counter++;
buffer += ',' + this.users[i].getIdentity(this.id);
}
var msg = '|users|' + counter + buffer;
return msg;
};
ChatRoom.prototype.reportJoin = function (entry) {
if (Config.reportjoinsperiod) {
if (!this.reportJoinsInterval) {
this.reportJoinsInterval = setTimeout(
this.reportRecentJoins.bind(this), Config.reportjoinsperiod
);
}
this.reportJoinsQueue.push(entry);
} else {
this.send(entry);
}
this.logEntry(entry);
};
ChatRoom.prototype.update = function () {
if (this.log.length <= this.lastUpdate) return;
var entries = this.log.slice(this.lastUpdate);
if (this.reportJoinsQueue && this.reportJoinsQueue.length) {
clearTimeout(this.reportJoinsInterval);
delete this.reportJoinsInterval;
Array.prototype.unshift.apply(entries, this.reportJoinsQueue);
this.reportJoinsQueue.length = 0;
this.userList = this.getUserList();
}
var update = entries.join('\n');
if (this.log.length > 100) {
this.log.splice(0, this.log.length - 100);
}
this.lastUpdate = this.log.length;
this.send(update);
};
ChatRoom.prototype.getIntroMessage = function () {
var html = this.introMessage || '';
if (this.modchat) {
if (html) html += '<br /><br />';
html += '<div class="broadcast-red">';
html += 'Must be rank ' + this.modchat + ' or higher to talk right now.';
html += '</div>';
}
if (html) return '\n|raw|<div class="infobox">' + html + '</div>';
return '';
};
ChatRoom.prototype.onJoinConnection = function (user, connection) {
var userList = this.userList ? this.userList : this.getUserList();
this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-25).join('\n') + this.getIntroMessage());
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user, connection);
}
};
ChatRoom.prototype.onJoin = function (user, connection, merging) {
if (!user) return false; // ???
if (this.users[user.userid]) return user;
if (user.named && Config.reportjoins) {
this.add('|j|' + user.getIdentity(this.id));
this.update();
} else if (user.named) {
var entry = '|J|' + user.getIdentity(this.id);
this.reportJoin(entry);
}
this.users[user.userid] = user;
this.userCount++;
if (!merging) {
var userList = this.userList ? this.userList : this.getUserList();
this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-100).join('\n') + this.getIntroMessage());
}
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user, connection);
}
return user;
};
ChatRoom.prototype.onRename = function (user, oldid, joining) {
delete this.users[oldid];
if (this.bannedUsers && (user.userid in this.bannedUsers || user.autoconfirmed in this.bannedUsers)) {
this.bannedUsers[oldid] = true;
for (var ip in user.ips) this.bannedIps[ip] = true;
user.leaveRoom(this);
var alts = user.getAlts();
for (var i = 0; i < alts.length; ++i) {
this.bannedUsers[toId(alts[i])] = true;
Users.getExact(alts[i]).leaveRoom(this);
}
return;
}
this.users[user.userid] = user;
var entry;
if (joining) {
if (Config.reportjoins) {
entry = '|j|' + user.getIdentity(this.id);
} else {
entry = '|J|' + user.getIdentity(this.id);
}
} else if (!user.named) {
entry = '|L| ' + oldid;
} else {
entry = '|N|' + user.getIdentity(this.id) + '|' + oldid;
}
if (Config.reportjoins) {
this.add(entry);
} else {
this.reportJoin(entry);
}
if (global.Tournaments && Tournaments.get(this.id)) {
Tournaments.get(this.id).updateFor(user);
}
return user;
};
/**
* onRename, but without a userid change
*/
ChatRoom.prototype.onUpdateIdentity = function (user) {
if (user && user.connected && user.named) {
if (!this.users[user.userid]) return false;
var entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid;
this.reportJoin(entry);
}
};
ChatRoom.prototype.onLeave = function (user) {
if (!user) return; // ...
delete this.users[user.userid];
this.userCount--;
if (user.named && Config.reportjoins) {
this.add('|l|' + user.getIdentity(this.id));
} else if (user.named) {
var entry = '|L|' + user.getIdentity(this.id);
this.reportJoin(entry);
}
};
ChatRoom.prototype.destroy = function () {
// deallocate ourself
// remove references to ourself
for (var i in this.users) {
this.users[i].leaveRoom(this);
delete this.users[i];
}
this.users = null;
rooms.global.deregisterChatRoom(this.id);
rooms.global.delistChatRoom(this.id);
// get rid of some possibly-circular references
delete rooms[this.id];
};
return ChatRoom;
})();
// to make sure you don't get null returned, pass the second argument
function getRoom(roomid, fallback) {
if (roomid && roomid.id) return roomid;
if (!roomid) roomid = 'default';
if (!rooms[roomid] && fallback) {
return rooms.global;
}
return rooms[roomid];
}
Rooms.get = getRoom;
Rooms.createBattle = function (roomid, format, p1, p2, parent, rated) {
if (roomid && roomid.id) return roomid;
if (!p1 || !p2) return false;
if (!roomid) roomid = 'default';
if (!rooms[roomid]) {
// console.log("NEW BATTLE ROOM: " + roomid);
ResourceMonitor.countBattle(p1.latestIp, p1.name);
ResourceMonitor.countBattle(p2.latestIp, p2.name);
rooms[roomid] = new BattleRoom(roomid, format, p1, p2, parent, rated);
}
return rooms[roomid];
};
Rooms.createChatRoom = function (roomid, title, data) {
var room;
if ((room = rooms[roomid])) return room;
room = rooms[roomid] = new ChatRoom(roomid, title, data);
return room;
};
console.log("NEW GLOBAL: global");
rooms.global = new GlobalRoom('global');
Rooms.GlobalRoom = GlobalRoom;
Rooms.BattleRoom = BattleRoom;
Rooms.ChatRoom = ChatRoom;
Rooms.global = rooms.global;
Rooms.lobby = rooms.lobby;
| Nineage/Showdown-Boilerplate | rooms.js | JavaScript | mit | 46,612 |
/**
* Copyright (c) 2008-2011 The Open Planning Project
*
* Published under the BSD license.
* See https://github.com/opengeo/gxp/raw/master/license.txt for the full text
* of the license.
*/
/**
* @requires plugins/ZoomToExtent.js
*/
/** api: (define)
* module = gxp.plugins
* class = ZoomToSelectedFeatures
*/
/** api: (extends)
* plugins/ZoomToExtent.js
*/
Ext.namespace("gxp.plugins");
/** api: constructor
* .. class:: ZoomToSelectedFeatures(config)
*
* Plugin for zooming to the extent of selected features
*/
gxp.plugins.ZoomToSelectedFeatures = Ext.extend(gxp.plugins.ZoomToExtent, {
/** api: ptype = gxp_zoomtoselectedfeatures */
ptype: "gxp_zoomtoselectedfeatures",
/** api: config[menuText]
* ``String``
* Text for zoom menu item (i18n).
*/
menuText: "Zoom to selected features",
/** api: config[tooltip]
* ``String``
* Text for zoom action tooltip (i18n).
*/
tooltip: "Zoom to selected features",
/** api: config[featureManager]
* ``String`` id of the :class:`gxp.plugins.FeatureManager` to look for
* selected features
*/
/** api: config[closest]
* ``Boolean`` Find the zoom level that most closely fits the specified
* extent. Note that this may result in a zoom that does not exactly
* contain the entire extent. Default is false.
*/
closest: false,
/** private: property[iconCls]
*/
iconCls: "gxp-icon-zoom-to",
/** private: method[extent]
*/
extent: function() {
var layer = this.target.tools[this.featureManager].featureLayer;
var bounds, geom, extent, features = layer.selectedFeatures;
for (var i=features.length-1; i>=0; --i) {
geom = features[i].geometry;
if (geom) {
extent = geom.getBounds();
if (bounds) {
bounds.extend(extent);
} else {
bounds = extent.clone();
}
}
};
return bounds;
},
/** api: method[addActions]
*/
addActions: function() {
var actions = gxp.plugins.ZoomToSelectedFeatures.superclass.addActions.apply(this, arguments);
actions[0].disable();
var layer = this.target.tools[this.featureManager].featureLayer;
layer.events.on({
"featureselected": function() {
actions[0].isDisabled() && actions[0].enable();
},
"featureunselected": function() {
layer.selectedFeatures.length == 0 && actions[0].disable();
}
});
return actions;
}
});
Ext.preg(gxp.plugins.ZoomToSelectedFeatures.prototype.ptype, gxp.plugins.ZoomToSelectedFeatures);
| flavour/porto | static/scripts/gis/gxp/plugins/ZoomToSelectedFeatures.js | JavaScript | mit | 2,820 |
version https://git-lfs.github.com/spec/v1
oid sha256:7076c06d1c5b0c8a10633ae2837be365f999203218d8484d9c4dd3bcb53c7e95
size 49060
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.7.3/calendar/calendar-coverage.js | JavaScript | mit | 130 |
'use strict';
var React = require('react');
var PureRenderMixin = require('react-addons-pure-render-mixin');
var SvgIcon = require('../../svg-icon');
var SocialPages = React.createClass({
displayName: 'SocialPages',
mixins: [PureRenderMixin],
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M3 5v6h5L7 7l4 1V3H5c-1.1 0-2 .9-2 2zm5 8H3v6c0 1.1.9 2 2 2h6v-5l-4 1 1-4zm9 4l-4-1v5h6c1.1 0 2-.9 2-2v-6h-5l1 4zm2-14h-6v5l4-1-1 4h5V5c0-1.1-.9-2-2-2z' })
);
}
});
module.exports = SocialPages; | dominikgar/flask-search-engine | node_modules/material-ui/lib/svg-icons/social/pages.js | JavaScript | mit | 588 |
import $ from 'jquery';
import ParsleyUI from '../../src/parsley/ui';
import Parsley from '../../src/parsley';
describe('ParsleyUI', () => {
before(() => {
Parsley.setLocale('en');
});
it('should create proper errors container when needed', () => {
$('body').append('<input type="text" id="element" data-parsley-required />');
var parsleyField = $('#element').psly();
expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(0);
parsleyField.validate();
expect($('#element').attr('data-parsley-id')).to.be(parsleyField.__id__);
expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(1);
expect($('ul#parsley-id-' + parsleyField.__id__).hasClass('parsley-errors-list')).to.be(true);
});
it('should handle errors-container option', () => {
$('body').append(
'<form id="element">' +
'<input id="field1" type="text" required data-parsley-errors-container="#container" />' +
'<div id="container"></div>' +
'<div id="container2"></div>' +
'</form>');
$('#element').psly().validate();
expect($('#container .parsley-errors-list').length).to.be(1);
$('#element').psly().destroy();
$('#field1').removeAttr('data-parsley-errors-container');
$('#element').psly({
errorsContainer: function (ins) {
expect(ins).to.be($('#field1').psly());
expect(this).to.be($('#field1').psly());
return $('#container2');
}
}).validate();
expect($('#container2 .parsley-errors-list').length).to.be(1);
});
it('should handle wrong errors-container option', () => {
$('body').append('<input type="text" id="element" data-parsley-errors-container="#donotexist" required/>');
var parsley = $('#element').psly();
expectWarning(() => {
parsley.validate();
});
});
it('should not add success class on a field without constraints', () => {
$('body').append('<input type="text" id="element" />');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('#element').hasClass('parsley-error')).to.be(false);
expect($('#element').hasClass('parsley-success')).to.be(false);
});
it('should not add success class on an empty optional field', () => {
$('body').append('<input type="number" id="element" />');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('#element').hasClass('parsley-error')).to.be(false);
expect($('#element').hasClass('parsley-success')).to.be(false);
});
var checkType = (type, html, fillValue) => {
it(`should add proper parsley class on success or failure (${type})`, () => {
$('body').append(`<form id="element"><section>${html}</section></form>`);
let form = $('#element').parsley();
let $inputHolder = $('#element section').children().first();
form.validate();
expect($inputHolder.attr('class')).to.be('parsley-error');
expect($('.parsley-errors-list').parent().prop("tagName")).to.be('SECTION');
// Fill and revalidate:
fillValue($inputHolder);
form.validate();
expect($inputHolder.attr('class')).to.be('parsley-success');
});
};
let callVal = $input => $input.val('foo');
checkType('text', '<input type="text" required/>', callVal);
checkType('select', '<select multiple required><option value="foo">foo</option>', callVal);
let callProp = $fieldset => $fieldset.find('input').prop('checked', true);
checkType('radio', '<fieldset><input type="radio" name="foo" required /></fieldset>', callProp);
checkType('checkbox', '<fieldset><input type="checkbox" name="foo" required /></fieldset>', callProp);
it('should handle class-handler option', () => {
$('body').append(
'<form id="element">' +
'<input id="field1" type="email" data-parsley-class-handler="#field2" required />' +
'<div id="field2"></div>' +
'<div id="field3"></div>' +
'</form>');
$('#element').psly().validate();
expect($('#field2').hasClass('parsley-error')).to.be(true);
$('#element').psly().destroy();
$('#field1').removeAttr('data-parsley-class-handler');
$('#element').psly({
classHandler: function (ins) {
expect(ins).to.be($('#field1').parsley());
expect(this).to.be($('#field1').parsley());
return $('#field3');
}
}).validate();
expect($('#field3').hasClass('parsley-error')).to.be(true);
});
it('should show higher priority error message by default', () => {
$('body').append('<input type="email" id="element" required />');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('#element').hasClass('parsley-error')).to.be(true);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true);
$('#element').val('foo').psly().validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true);
});
it('should show all errors message if priority enabled set to false', () => {
$('body').append('<input type="email" id="element" required data-parsley-priority-enabled="false"/>');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(2);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').eq(0).hasClass('parsley-required')).to.be(true);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').eq(1).hasClass('parsley-type')).to.be(true);
$('#element').val('foo').psly().validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true);
});
it('should show custom error message by validator', () => {
$('body').append('<input type="email" id="element" required data-parsley-required-message="foo" data-parsley-type-message="bar"/>');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('foo');
$('#element').val('foo').psly().validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('bar');
});
it('should show custom error message with variabilized parameters', () => {
$('body').append('<input type="text" id="element" value="bar" data-parsley-minlength="7" data-parsley-minlength-message="foo %s bar"/>');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('foo 7 bar');
});
it('should show custom error message for whole field', () => {
$('body').append('<input type="email" id="element" required data-parsley-error-message="baz"/>');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('baz');
$('#element').val('foo').psly().validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('baz');
$('#element').val('foo@bar.baz').psly().validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
});
it('should display no error message if diabled', () => {
$('body').append('<input type="email" id="element" required data-parsley-errors-messages-disabled />');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
expect($('#element').hasClass('parsley-error')).to.be(true);
});
it('should handle simple triggers (change, focus...)', () => {
$('body').append('<input type="email" id="element" required data-parsley-trigger="change" />');
var parsleyField = $('#element').psly();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
$('#element').trigger($.Event('change'));
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
});
it('should allow customization of triggers after first error', () => {
$('body').append('<input type="email" id="element" required data-parsley-trigger-after-failure="focusout" />');
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
$('#element').val('a@example.com');
$('#element').trigger('input');
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
$('#element').trigger('focusout');
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
});
it('should auto bind error trigger on select field error (input=text)', () => {
$('body').append('<input type="email" id="element" required />');
var parsleyField = $('#element').psly();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true);
$('#element').val('foo').trigger('input');
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(true);
});
it('should auto bind error trigger on select field error (select)', () => {
$('body').append('<select id="element" required>' +
'<option value="">Choose</option>' +
'<option value="foo">foo</option>' +
'<option value="bar">bar</option>' +
'</select>');
var parsleyField = $('#element').psly();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-required')).to.be(true);
$('#element [option="foo"]').attr('selected', 'selected');
$('#element').trigger($.Event('change'));
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').hasClass('parsley-type')).to.be(false);
});
it('should handle complex triggers (keyup, keypress...)', () => {
$('body').append('<input type="email" id="element" required data-parsley-trigger="keyup" />');
var parsleyField = $('#element').psly();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
$('#element').val('foo').trigger($.Event('keyup'));
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
$('#element').val('foob').trigger($.Event('keyup'));
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
});
it('should handle trigger keyup threshold validation', () => {
$('body').append('<input type="email" id="element" data-parsley-validation-threshold="7" required data-parsley-trigger="keyup" />');
var parsleyField = $('#element').psly();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
$('#element').val('a@b.com').trigger('keyup');
expect($('#element').hasClass('success')).to.be(false);
$('#element').val('aa@b.com').trigger('keyup');
expect($('#element').hasClass('parsley-success')).to.be(true);
$('#element').val('@b.com').trigger('keyup');
expect($('#element').hasClass('parsley-success')).to.be(false);
});
it('should handle UI disabling', () => {
$('body').append('<input type="email" id="element" data-parsley-ui-enabled="false" required data-parsley-trigger="keyup" />');
var parsleyField = $('#element').psly();
expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(0);
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__).length).to.be(0);
});
it('should add novalidate on form elem', () => {
$('body').append(
'<form id="element" data-parsley-trigger="change">' +
'<input id="field1" type="text" data-parsley-required="true" />' +
'<div id="field2"></div>' +
'<textarea id="field3" data-parsley-notblank="true"></textarea>' +
'</form>');
var parsleyForm = $('#element').parsley();
expect($('#element').attr('novalidate')).not.to.be(undefined);
});
it('should test the no-focus option', () => {
$('body').append(
'<form id="element" data-parsley-focus="first">' +
'<input id="field1" type="text" data-parsley-required="true" data-parsley-no-focus />' +
'<input id="field2" data-parsley-required />' +
'</form>');
$('#element').parsley().validate();
expect($('#element').parsley()._focusedField.attr('id')).to.be('field2');
$('#field2').val('foo');
$('#element').psly().validate();
expect($('#element').parsley()._focusedField).to.be(null);
$('#field1').removeAttr('data-parsley-no-focus');
$('#element').psly().validate();
expect($('#element').parsley()._focusedField.attr('id')).to.be('field1');
$('#element').attr('data-parsley-focus', 'last');
$('#element').psly().validate();
expect($('#element').parsley()._focusedField.attr('id')).to.be('field1');
$('#field2').val('');
$('#element').psly().validate();
expect($('#element').parsley()._focusedField.attr('id')).to.be('field2');
});
it('should test the manual add / update / remove error', () => {
$('body').append('<input type="text" id="element" />');
var parsleyField = $('#element').parsley();
parsleyField.removeError('non-existent');
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
expect($('#element').hasClass('parsley-error')).to.be(false);
expectWarning(() => {
window.ParsleyUI.addError(parsleyField, 'foo', 'bar');
});
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(1);
expect($('#element').hasClass('parsley-error')).to.be(true);
expect($('li.parsley-foo').length).to.be(1);
expect($('li.parsley-foo').text()).to.be('bar');
expectWarning(() => {
window.ParsleyUI.updateError(parsleyField, 'foo', 'baz');
});
expect($('li.parsley-foo').text()).to.be('baz');
expectWarning(() => {
window.ParsleyUI.removeError(parsleyField, 'foo');
});
expect($('#element').hasClass('parsley-error')).to.be(false);
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').length).to.be(0);
});
it('should have a getErrorsMessage() method', () => {
$('body').append('<input type="email" id="element" value="foo" data-parsley-minlength="5" />');
var parsleyInstance = $('#element').parsley();
parsleyInstance.validate();
expectWarning(() => {
window.ParsleyUI.getErrorsMessages(parsleyInstance);
});
expect(window.ParsleyUI.getErrorsMessages(parsleyInstance).length).to.be(1);
expect(window.ParsleyUI.getErrorsMessages(parsleyInstance)[0]).to.be('This value should be a valid email.');
$('#element').attr('data-parsley-priority-enabled', false);
parsleyInstance.validate();
expect(window.ParsleyUI.getErrorsMessages(parsleyInstance).length).to.be(2);
expect(window.ParsleyUI.getErrorsMessages(parsleyInstance)[0]).to.be('This value is too short. It should have 5 characters or more.');
});
it('should not have errors ul created for excluded fields', () => {
$('body').append('<div id="hidden"><input type="hidden" id="element" value="foo" data-parsley-minlength="5" /></div>');
var parsleyInstance = $('#element').parsley();
expect($('#hidden ul').length).to.be(0);
$('#hidden').remove();
});
it('should remove filled class from errors container when reseting', () => {
$('body').append('<input type="email" id="element" value="foo" data-parsley-minlength="5" />');
var parsleyInstance = $('#element').parsley();
parsleyInstance.validate();
parsleyInstance.reset();
expect($('ul#parsley-id-' + parsleyInstance.__id__).hasClass('filled')).to.be(false);
});
it('should re-bind error triggers after a reset (input=text)', () => {
$('body').append('<input type="text" id="element" required />');
var parsleyInstance = $('#element').parsley();
parsleyInstance.validate();
parsleyInstance.reset();
parsleyInstance.validate();
expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(1);
$('#element').val('foo').trigger('input');
expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(0);
});
it('should re-bind error triggers after a reset (select)', () => {
$('body').append('<select id="element" required>' +
'<option value="">Choose</option>' +
'<option value="foo">foo</option>' +
'<option value="bar">bar</option>' +
'</select>');
var parsleyInstance = $('#element').parsley();
parsleyInstance.validate();
parsleyInstance.reset();
parsleyInstance.validate();
expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(1);
$('#element option[value="foo"]').prop('selected', true);
$('#element').trigger('input');
expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(0);
});
it('should re-bind custom triggers after a reset', () => {
$('body').append('<input type="text" id="element" required data-parsley-trigger="focusout" />');
var parsleyInstance = $('#element').parsley();
parsleyInstance.validate();
parsleyInstance.reset();
$('#element').trigger('focusout');
expect($('ul#parsley-id-' + parsleyInstance.__id__ + ' li').length).to.be(1);
});
it('should handle custom error message for validators with compound names', () => {
$('body').append('<input type="text" value="1" id="element" data-parsley-custom-validator="2" data-parsley-custom-validator-message="custom-validator error"/>');
window.Parsley.addValidator('customValidator', (value, requirement) => {
return requirement === value;
}, 32);
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($('ul#parsley-id-' + parsleyField.__id__ + ' li').text()).to.be('custom-validator error');
window.Parsley.removeValidator('customValidator');
});
it('should handle custom error messages returned from custom validators', () => {
$('body').append('<input type="text" value="1" id="element" data-parsley-custom-validator="2" data-parsley-custom-validator-message="custom-validator error"/>');
window.Parsley.addValidator('customValidator', (value, requirement) => {
return $.Deferred().reject("Hey, this ain't good at all").promise();
}, 32);
var parsleyField = $('#element').psly();
parsleyField.validate();
expect($(`ul#parsley-id-${parsleyField.__id__} li`).text()).to.be("Hey, this ain't good at all");
window.Parsley.removeValidator('customValidator');
});
it('should run before events are fired', () => {
$('body').append('<input type="text" id="element" required/>');
var parsley = $('#element').parsley().on('field:validated', () => {
expect($('.parsley-errors-list')).to.have.length(1);
});
parsley.validate();
});
afterEach(() => {
$('#element, .parsley-errors-list').remove();
});
});
| geoffroygivry/CyclopsVFX-Polyphemus | static/polyphemus/assets/plugins/parsley/test/unit/ui.js | JavaScript | mit | 19,850 |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var is = require('@redux-saga/is');
var __chunk_1 = require('./chunk-5caa0f1a.js');
var __chunk_2 = require('./chunk-062c0282.js');
require('@babel/runtime/helpers/extends');
require('@redux-saga/symbols');
require('@redux-saga/delay-p');
var done = function done(value) {
return {
done: true,
value: value
};
};
var qEnd = {};
function safeName(patternOrChannel) {
if (is.channel(patternOrChannel)) {
return 'channel';
}
if (is.stringableFunc(patternOrChannel)) {
return String(patternOrChannel);
}
if (is.func(patternOrChannel)) {
return patternOrChannel.name;
}
return String(patternOrChannel);
}
function fsmIterator(fsm, startState, name) {
var stateUpdater,
errorState,
effect,
nextState = startState;
function next(arg, error) {
if (nextState === qEnd) {
return done(arg);
}
if (error && !errorState) {
nextState = qEnd;
throw error;
} else {
stateUpdater && stateUpdater(arg);
var currentState = error ? fsm[errorState](error) : fsm[nextState]();
nextState = currentState.nextState;
effect = currentState.effect;
stateUpdater = currentState.stateUpdater;
errorState = currentState.errorState;
return nextState === qEnd ? done(arg) : effect;
}
}
return __chunk_1.makeIterator(next, function (error) {
return next(null, error);
}, name);
}
function takeEvery(patternOrChannel, worker) {
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var yTake = {
done: false,
value: __chunk_2.take(patternOrChannel)
};
var yFork = function yFork(ac) {
return {
done: false,
value: __chunk_2.fork.apply(void 0, [worker].concat(args, [ac]))
};
};
var action,
setAction = function setAction(ac) {
return action = ac;
};
return fsmIterator({
q1: function q1() {
return {
nextState: 'q2',
effect: yTake,
stateUpdater: setAction
};
},
q2: function q2() {
return {
nextState: 'q1',
effect: yFork(action)
};
}
}, 'q1', "takeEvery(" + safeName(patternOrChannel) + ", " + worker.name + ")");
}
function takeLatest(patternOrChannel, worker) {
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var yTake = {
done: false,
value: __chunk_2.take(patternOrChannel)
};
var yFork = function yFork(ac) {
return {
done: false,
value: __chunk_2.fork.apply(void 0, [worker].concat(args, [ac]))
};
};
var yCancel = function yCancel(task) {
return {
done: false,
value: __chunk_2.cancel(task)
};
};
var task, action;
var setTask = function setTask(t) {
return task = t;
};
var setAction = function setAction(ac) {
return action = ac;
};
return fsmIterator({
q1: function q1() {
return {
nextState: 'q2',
effect: yTake,
stateUpdater: setAction
};
},
q2: function q2() {
return task ? {
nextState: 'q3',
effect: yCancel(task)
} : {
nextState: 'q1',
effect: yFork(action),
stateUpdater: setTask
};
},
q3: function q3() {
return {
nextState: 'q1',
effect: yFork(action),
stateUpdater: setTask
};
}
}, 'q1', "takeLatest(" + safeName(patternOrChannel) + ", " + worker.name + ")");
}
function takeLeading(patternOrChannel, worker) {
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var yTake = {
done: false,
value: __chunk_2.take(patternOrChannel)
};
var yCall = function yCall(ac) {
return {
done: false,
value: __chunk_2.call.apply(void 0, [worker].concat(args, [ac]))
};
};
var action;
var setAction = function setAction(ac) {
return action = ac;
};
return fsmIterator({
q1: function q1() {
return {
nextState: 'q2',
effect: yTake,
stateUpdater: setAction
};
},
q2: function q2() {
return {
nextState: 'q1',
effect: yCall(action)
};
}
}, 'q1', "takeLeading(" + safeName(patternOrChannel) + ", " + worker.name + ")");
}
function throttle(delayLength, pattern, worker) {
for (var _len = arguments.length, args = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
args[_key - 3] = arguments[_key];
}
var action, channel;
var yActionChannel = {
done: false,
value: __chunk_2.actionChannel(pattern, __chunk_2.sliding(1))
};
var yTake = function yTake() {
return {
done: false,
value: __chunk_2.take(channel)
};
};
var yFork = function yFork(ac) {
return {
done: false,
value: __chunk_2.fork.apply(void 0, [worker].concat(args, [ac]))
};
};
var yDelay = {
done: false,
value: __chunk_2.delay(delayLength)
};
var setAction = function setAction(ac) {
return action = ac;
};
var setChannel = function setChannel(ch) {
return channel = ch;
};
return fsmIterator({
q1: function q1() {
return {
nextState: 'q2',
effect: yActionChannel,
stateUpdater: setChannel
};
},
q2: function q2() {
return {
nextState: 'q3',
effect: yTake(),
stateUpdater: setAction
};
},
q3: function q3() {
return {
nextState: 'q4',
effect: yFork(action)
};
},
q4: function q4() {
return {
nextState: 'q2',
effect: yDelay
};
}
}, 'q1', "throttle(" + safeName(pattern) + ", " + worker.name + ")");
}
function retry(maxTries, delayLength, fn) {
var counter = maxTries;
for (var _len = arguments.length, args = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
args[_key - 3] = arguments[_key];
}
var yCall = {
done: false,
value: __chunk_2.call.apply(void 0, [fn].concat(args))
};
var yDelay = {
done: false,
value: __chunk_2.delay(delayLength)
};
return fsmIterator({
q1: function q1() {
return {
nextState: 'q2',
effect: yCall,
errorState: 'q10'
};
},
q2: function q2() {
return {
nextState: qEnd
};
},
q10: function q10(error) {
counter -= 1;
if (counter <= 0) {
throw error;
}
return {
nextState: 'q1',
effect: yDelay
};
}
}, 'q1', "retry(" + fn.name + ")");
}
function debounceHelper(delayLength, patternOrChannel, worker) {
for (var _len = arguments.length, args = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
args[_key - 3] = arguments[_key];
}
var action, raceOutput;
var yTake = {
done: false,
value: __chunk_2.take(patternOrChannel)
};
var yRace = {
done: false,
value: __chunk_2.race({
action: __chunk_2.take(patternOrChannel),
debounce: __chunk_2.delay(delayLength)
})
};
var yFork = function yFork(ac) {
return {
done: false,
value: __chunk_2.fork.apply(void 0, [worker].concat(args, [ac]))
};
};
var yNoop = function yNoop(value) {
return {
done: false,
value: value
};
};
var setAction = function setAction(ac) {
return action = ac;
};
var setRaceOutput = function setRaceOutput(ro) {
return raceOutput = ro;
};
return fsmIterator({
q1: function q1() {
return {
nextState: 'q2',
effect: yTake,
stateUpdater: setAction
};
},
q2: function q2() {
return {
nextState: 'q3',
effect: yRace,
stateUpdater: setRaceOutput
};
},
q3: function q3() {
return raceOutput.debounce ? {
nextState: 'q1',
effect: yFork(action)
} : {
nextState: 'q2',
effect: yNoop(raceOutput.action),
stateUpdater: setAction
};
}
}, 'q1', "debounce(" + safeName(patternOrChannel) + ", " + worker.name + ")");
}
var validateTakeEffect = function validateTakeEffect(fn, patternOrChannel, worker) {
__chunk_1.check(patternOrChannel, is.notUndef, fn.name + " requires a pattern or channel");
__chunk_1.check(worker, is.notUndef, fn.name + " requires a saga parameter");
};
function takeEvery$1(patternOrChannel, worker) {
{
validateTakeEffect(takeEvery$1, patternOrChannel, worker);
}
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
return __chunk_2.fork.apply(void 0, [takeEvery, patternOrChannel, worker].concat(args));
}
function takeLatest$1(patternOrChannel, worker) {
{
validateTakeEffect(takeLatest$1, patternOrChannel, worker);
}
for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
return __chunk_2.fork.apply(void 0, [takeLatest, patternOrChannel, worker].concat(args));
}
function takeLeading$1(patternOrChannel, worker) {
{
validateTakeEffect(takeLeading$1, patternOrChannel, worker);
}
for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
args[_key3 - 2] = arguments[_key3];
}
return __chunk_2.fork.apply(void 0, [takeLeading, patternOrChannel, worker].concat(args));
}
function throttle$1(ms, pattern, worker) {
{
__chunk_1.check(pattern, is.notUndef, 'throttle requires a pattern');
__chunk_1.check(worker, is.notUndef, 'throttle requires a saga parameter');
}
for (var _len4 = arguments.length, args = new Array(_len4 > 3 ? _len4 - 3 : 0), _key4 = 3; _key4 < _len4; _key4++) {
args[_key4 - 3] = arguments[_key4];
}
return __chunk_2.fork.apply(void 0, [throttle, ms, pattern, worker].concat(args));
}
function retry$1(maxTries, delayLength, worker) {
for (var _len5 = arguments.length, args = new Array(_len5 > 3 ? _len5 - 3 : 0), _key5 = 3; _key5 < _len5; _key5++) {
args[_key5 - 3] = arguments[_key5];
}
return __chunk_2.call.apply(void 0, [retry, maxTries, delayLength, worker].concat(args));
}
function debounce(delayLength, pattern, worker) {
for (var _len6 = arguments.length, args = new Array(_len6 > 3 ? _len6 - 3 : 0), _key6 = 3; _key6 < _len6; _key6++) {
args[_key6 - 3] = arguments[_key6];
}
return __chunk_2.fork.apply(void 0, [debounceHelper, delayLength, pattern, worker].concat(args));
}
exports.effectTypes = __chunk_2.effectTypes;
exports.take = __chunk_2.take;
exports.takeMaybe = __chunk_2.takeMaybe;
exports.put = __chunk_2.put;
exports.putResolve = __chunk_2.putResolve;
exports.all = __chunk_2.all;
exports.race = __chunk_2.race;
exports.call = __chunk_2.call;
exports.apply = __chunk_2.apply;
exports.cps = __chunk_2.cps;
exports.fork = __chunk_2.fork;
exports.spawn = __chunk_2.spawn;
exports.join = __chunk_2.join;
exports.cancel = __chunk_2.cancel;
exports.select = __chunk_2.select;
exports.actionChannel = __chunk_2.actionChannel;
exports.cancelled = __chunk_2.cancelled;
exports.flush = __chunk_2.flush;
exports.getContext = __chunk_2.getContext;
exports.setContext = __chunk_2.setContext;
exports.delay = __chunk_2.delay;
exports.debounce = debounce;
exports.retry = retry$1;
exports.takeEvery = takeEvery$1;
exports.takeLatest = takeLatest$1;
exports.takeLeading = takeLeading$1;
exports.throttle = throttle$1;
| extend1994/cdnjs | ajax/libs/redux-saga/1.0.0-beta.3/redux-saga-effects.dev.cjs.js | JavaScript | mit | 11,792 |
YUI.add("yuidoc-meta", function(Y) {
Y.YUIDoc = { meta: {
"classes": [
"Amplitude",
"AudioIn",
"Env",
"FFT",
"Noise",
"Oscillator",
"Pulse",
"SoundFile",
"p5.Element",
"p5.MediaElement",
"p5.dom",
"p5.sound"
],
"modules": [
"p5.dom",
"p5.sound"
],
"allModules": [
{
"displayName": "p5.dom",
"name": "p5.dom",
"description": "This is the p5.dom library."
},
{
"displayName": "p5.sound",
"name": "p5.sound",
"description": "p5.sound extends p5 with Web Audio functionality including audio input, playback, analysis and synthesis."
}
]
} };
}); | processing/p5.js-sound | docs/reference/api.js | JavaScript | mit | 784 |
/// <reference path="angular.d.ts" />
/// <reference path="angular-route.d.ts" />
/// <reference path="angular-sanitize.d.ts" />
/// <reference path="bootstrap.d.ts" />
/// <reference path="moment.d.ts" />
/// <reference path="moment-duration-format.d.ts" />
/// <reference path="d3.d.ts" />
/// <reference path="underscore.d.ts" />
var bosunApp = angular.module('bosunApp', [
'ngRoute',
'bosunControllers',
'mgcrea.ngStrap',
'ngSanitize',
'ui.ace',
]);
bosunApp.config(['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider, $locationProvider, $httpProvider) {
$locationProvider.html5Mode(true);
$routeProvider.
when('/', {
title: 'Dashboard',
templateUrl: 'partials/dashboard.html',
controller: 'DashboardCtrl'
}).
when('/items', {
title: 'Items',
templateUrl: 'partials/items.html',
controller: 'ItemsCtrl'
}).
when('/expr', {
title: 'Expression',
templateUrl: 'partials/expr.html',
controller: 'ExprCtrl'
}).
when('/graph', {
title: 'Graph',
templateUrl: 'partials/graph.html',
controller: 'GraphCtrl'
}).
when('/host', {
title: 'Host View',
templateUrl: 'partials/host.html',
controller: 'HostCtrl',
reloadOnSearch: false
}).
when('/silence', {
title: 'Silence',
templateUrl: 'partials/silence.html',
controller: 'SilenceCtrl'
}).
when('/config', {
title: 'Configuration',
templateUrl: 'partials/config.html',
controller: 'ConfigCtrl',
reloadOnSearch: false
}).
when('/action', {
title: 'Action',
templateUrl: 'partials/action.html',
controller: 'ActionCtrl'
}).
when('/history', {
title: 'Alert History',
templateUrl: 'partials/history.html',
controller: 'HistoryCtrl'
}).
when('/put', {
title: 'Data Entry',
templateUrl: 'partials/put.html',
controller: 'PutCtrl'
}).
when('/incident', {
title: 'Incident',
templateUrl: 'partials/incident.html',
controller: 'IncidentCtrl'
}).
otherwise({
redirectTo: '/'
});
$httpProvider.interceptors.push(function ($q) {
return {
'request': function (config) {
config.headers['X-Miniprofiler'] = 'true';
return config;
}
};
});
}]);
bosunApp.run(['$location', '$rootScope', function ($location, $rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
$rootScope.shortlink = false;
});
}]);
var bosunControllers = angular.module('bosunControllers', []);
bosunControllers.controller('BosunCtrl', ['$scope', '$route', '$http', '$q', '$rootScope', function ($scope, $route, $http, $q, $rootScope) {
$scope.$on('$routeChangeSuccess', function (event, current, previous) {
$scope.stop(true);
});
$scope.active = function (v) {
if (!$route.current) {
return null;
}
if ($route.current.loadedTemplateUrl == 'partials/' + v + '.html') {
return { active: true };
}
return null;
};
$scope.json = function (v) {
return JSON.stringify(v, null, ' ');
};
$scope.btoa = function (v) {
return encodeURIComponent(btoa(v));
};
$scope.encode = function (v) {
return encodeURIComponent(v);
};
$scope.req_from_m = function (m) {
var r = new Request();
var q = new Query();
q.metric = m;
r.queries.push(q);
return r;
};
$scope.panelClass = function (status, prefix) {
if (prefix === void 0) { prefix = "panel-"; }
switch (status) {
case "critical": return prefix + "danger";
case "unknown": return prefix + "info";
case "warning": return prefix + "warning";
case "normal": return prefix + "success";
case "error": return prefix + "danger";
default: return prefix + "default";
}
};
$scope.values = {};
$scope.setKey = function (key, value) {
if (value === undefined) {
delete $scope.values[key];
}
else {
$scope.values[key] = value;
}
};
$scope.getKey = function (key) {
return $scope.values[key];
};
var scheduleFilter;
$scope.refresh = function (filter) {
var d = $q.defer();
scheduleFilter = filter;
$scope.animate();
var p = $http.get('/api/alerts?filter=' + encodeURIComponent(filter || ""))
.success(function (data) {
$scope.schedule = data;
$scope.timeanddate = data.TimeAndDate;
d.resolve();
})
.error(function (err) {
d.reject(err);
});
p.finally($scope.stop);
return d.promise;
};
var sz = 30;
var orig = 700;
var light = '#4ba2d9';
var dark = '#1f5296';
var med = '#356eb6';
var mult = sz / orig;
var bgrad = 25 * mult;
var circles = [
[150, 150, dark],
[550, 150, dark],
[150, 550, light],
[550, 550, light],
];
var svg = d3.select('#logo')
.append('svg')
.attr('height', sz)
.attr('width', sz);
svg.selectAll('rect.bg')
.data([[0, light], [sz / 2, dark]])
.enter()
.append('rect')
.attr('class', 'bg')
.attr('width', sz)
.attr('height', sz / 2)
.attr('rx', bgrad)
.attr('ry', bgrad)
.attr('fill', function (d) { return d[1]; })
.attr('y', function (d) { return d[0]; });
svg.selectAll('path.diamond')
.data([150, 550])
.enter()
.append('path')
.attr('d', function (d) {
var s = 'M ' + d * mult + ' ' + 150 * mult;
var w = 200 * mult;
s += ' l ' + w + ' ' + w;
s += ' l ' + -w + ' ' + w;
s += ' l ' + -w + ' ' + -w + ' Z';
return s;
})
.attr('fill', med)
.attr('stroke', 'white')
.attr('stroke-width', 15 * mult);
svg.selectAll('rect.white')
.data([150, 350, 550])
.enter()
.append('rect')
.attr('class', 'white')
.attr('width', .5)
.attr('height', '100%')
.attr('fill', 'white')
.attr('x', function (d) { return d * mult; });
svg.selectAll('circle')
.data(circles)
.enter()
.append('circle')
.attr('cx', function (d) { return d[0] * mult; })
.attr('cy', function (d) { return d[1] * mult; })
.attr('r', 62.5 * mult)
.attr('fill', function (d) { return d[2]; })
.attr('stroke', 'white')
.attr('stroke-width', 25 * mult);
var transitionDuration = 750;
var animateCount = 0;
$scope.animate = function () {
animateCount++;
if (animateCount == 1) {
doAnimate();
}
};
function doAnimate() {
if (!animateCount) {
return;
}
d3.shuffle(circles);
svg.selectAll('circle')
.data(circles, function (d, i) { return i; })
.transition()
.duration(transitionDuration)
.attr('cx', function (d) { return d[0] * mult; })
.attr('cy', function (d) { return d[1] * mult; })
.attr('fill', function (d) { return d[2]; });
setTimeout(doAnimate, transitionDuration);
}
$scope.stop = function (all) {
if (all === void 0) { all = false; }
if (all) {
animateCount = 0;
}
else if (animateCount > 0) {
animateCount--;
}
};
var short = $('#shortlink')[0];
$scope.shorten = function () {
$http.get('/api/shorten').success(function (data) {
if (data.id) {
short.value = data.id;
$rootScope.shortlink = true;
setTimeout(function () {
short.setSelectionRange(0, data.id.length);
});
}
});
};
}]);
var tsdbDateFormat = 'YYYY/MM/DD-HH:mm:ss';
moment.defaultFormat = tsdbDateFormat;
moment.locale('en', {
relativeTime: {
future: "in %s",
past: "%s-ago",
s: "%ds",
m: "%dm",
mm: "%dm",
h: "%dh",
hh: "%dh",
d: "%dd",
dd: "%dd",
M: "%dn",
MM: "%dn",
y: "%dy",
yy: "%dy"
}
});
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ')
c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0)
return unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
function getUser() {
return readCookie('action-user');
}
function setUser(name) {
createCookie('action-user', name, 1000);
}
// from: http://stackoverflow.com/a/15267754/864236
bosunApp.filter('reverse', function () {
return function (items) {
if (!angular.isArray(items)) {
return [];
}
return items.slice().reverse();
};
});
bosunControllers.controller('ActionCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) {
var search = $location.search();
$scope.user = readCookie("action-user");
$scope.type = search.type;
$scope.notify = true;
$scope.msgValid = true;
$scope.message = "";
$scope.validateMsg = function () {
$scope.msgValid = (!$scope.notify) || ($scope.message != "");
};
if (search.key) {
var keys = search.key;
if (!angular.isArray(search.key)) {
keys = [search.key];
}
$location.search('key', null);
$scope.setKey('action-keys', keys);
}
else {
$scope.keys = $scope.getKey('action-keys');
}
$scope.submit = function () {
$scope.validateMsg();
if (!$scope.msgValid || ($scope.user == "")) {
return;
}
var data = {
Type: $scope.type,
User: $scope.user,
Message: $scope.message,
Keys: $scope.keys,
Notify: $scope.notify
};
createCookie("action-user", $scope.user, 1000);
$http.post('/api/action', data)
.success(function (data) {
$location.url('/');
})
.error(function (error) {
alert(error);
});
};
}]);
bosunControllers.controller('ConfigCtrl', ['$scope', '$http', '$location', '$route', '$timeout', '$sce', function ($scope, $http, $location, $route, $timeout, $sce) {
var search = $location.search();
$scope.fromDate = search.fromDate || '';
$scope.fromTime = search.fromTime || '';
$scope.toDate = search.toDate || '';
$scope.toTime = search.toTime || '';
$scope.intervals = +search.intervals || 5;
$scope.duration = +search.duration || null;
$scope.config_text = 'Loading config...';
$scope.selected_alert = search.alert || '';
$scope.email = search.email || '';
$scope.template_group = search.template_group || '';
$scope.items = parseItems();
$scope.tab = search.tab || 'results';
$scope.aceTheme = 'chrome';
$scope.aceMode = 'bosun';
var expr = search.expr;
function buildAlertFromExpr() {
if (!expr)
return;
var newAlertName = "test";
var idx = 1;
//find a unique alert name
while ($scope.items["alert"].indexOf(newAlertName) != -1 || $scope.items["template"].indexOf(newAlertName) != -1) {
newAlertName = "test" + idx;
idx++;
}
var text = '\n\ntemplate ' + newAlertName + ' {\n' +
' subject = {{.Last.Status}}: {{.Alert.Name}} on {{.Group.host}}\n' +
' body = `<p>Name: {{.Alert.Name}}\n' +
' <p>Tags:\n' +
' <table>\n' +
' {{range $k, $v := .Group}}\n' +
' <tr><td>{{$k}}</td><td>{{$v}}</td></tr>\n' +
' {{end}}\n' +
' </table>`\n' +
'}\n\n';
var expression = atob(expr);
var lines = expression.split("\n").map(function (l) { return l.trim(); });
lines[lines.length - 1] = "crit = " + lines[lines.length - 1];
expression = lines.join("\n ");
text += 'alert ' + newAlertName + ' {\n' +
' template = ' + newAlertName + '\n' +
' ' + expression + '\n' +
'}\n';
$scope.config_text += text;
$scope.items = parseItems();
$timeout(function () {
//can't scroll editor until after control is updated. Defer it.
$scope.scrollTo("alert", newAlertName);
});
}
function parseItems() {
var configText = $scope.config_text;
var re = /^\s*(alert|template|notification|lookup|macro)\s+([\w\-\.\$]+)\s*\{/gm;
var match;
var items = {};
items["alert"] = [];
items["template"] = [];
items["lookup"] = [];
items["notification"] = [];
items["macro"] = [];
while (match = re.exec(configText)) {
var type = match[1];
var name = match[2];
var list = items[type];
if (!list) {
list = [];
items[type] = list;
}
list.push(name);
}
return items;
}
$http.get('/api/config?hash=' + (search.hash || ''))
.success(function (data) {
$scope.config_text = data;
$scope.items = parseItems();
buildAlertFromExpr();
if (!$scope.selected_alert && $scope.items["alert"].length) {
$scope.selected_alert = $scope.items["alert"][0];
}
$timeout(function () {
//can't scroll editor until after control is updated. Defer it.
$scope.scrollTo("alert", $scope.selected_alert);
});
})
.error(function (data) {
$scope.validationResult = "Error fetching config: " + data;
});
$scope.reparse = function () {
$scope.items = parseItems();
};
var editor;
$scope.aceLoaded = function (_editor) {
editor = _editor;
$scope.editor = editor;
editor.getSession().setUseWrapMode(true);
editor.on("blur", function () {
$scope.$apply(function () {
$scope.items = parseItems();
});
});
};
var syntax = true;
$scope.aceToggleHighlight = function () {
if (syntax) {
editor.getSession().setMode();
syntax = false;
return;
}
syntax = true;
editor.getSession().setMode({
path: 'ace/mode/' + $scope.aceMode,
v: Date.now()
});
};
$scope.scrollTo = function (type, name) {
var searchRegex = new RegExp("^\\s*" + type + "\\s+" + name, "g");
editor.find(searchRegex, {
backwards: false,
wrap: true,
caseSensitive: false,
wholeWord: false,
regExp: true
});
if (type == "alert") {
$scope.selectAlert(name);
}
};
$scope.scrollToInterval = function (id) {
document.getElementById('time-' + id).scrollIntoView();
$scope.show($scope.sets[id]);
};
$scope.show = function (set) {
set.show = 'loading...';
$scope.animate();
var url = '/api/rule?' +
'alert=' + encodeURIComponent($scope.selected_alert) +
'&from=' + encodeURIComponent(set.Time);
$http.post(url, $scope.config_text)
.success(function (data) {
procResults(data);
set.Results = data.Sets[0].Results;
})
.error(function (error) {
$scope.error = error;
})
.finally(function () {
$scope.stop();
delete (set.show);
});
};
$scope.setInterval = function () {
var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime);
var to = moment.utc($scope.toDate + ' ' + $scope.toTime);
if (!from.isValid() || !to.isValid()) {
return;
}
var diff = from.diff(to);
if (!diff) {
return;
}
var intervals = +$scope.intervals;
if (intervals < 2) {
return;
}
diff /= 1000 * 60;
var d = Math.abs(Math.round(diff / intervals));
if (d < 1) {
d = 1;
}
$scope.duration = d;
};
$scope.setDuration = function () {
var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime);
var to = moment.utc($scope.toDate + ' ' + $scope.toTime);
if (!from.isValid() || !to.isValid()) {
return;
}
var diff = from.diff(to);
if (!diff) {
return;
}
var duration = +$scope.duration;
if (duration < 1) {
return;
}
$scope.intervals = Math.abs(Math.round(diff / duration / 1000 / 60));
};
$scope.selectAlert = function (alert) {
$scope.selected_alert = alert;
$location.search("alert", alert);
// Attempt to find `template = foo` in order to set up quick jump between template and alert
var searchRegex = new RegExp("^\\s*alert\\s+" + alert, "g");
var lines = $scope.config_text.split("\n");
$scope.quickJumpTarget = null;
for (var i = 0; i < lines.length; i++) {
if (searchRegex.test(lines[i])) {
for (var j = i + 1; j < lines.length; j++) {
// Close bracket at start of line means end of alert.
if (/^\s*\}/m.test(lines[j])) {
return;
}
var found = /^\s*template\s*=\s*([\w\-\.\$]+)/m.exec(lines[j]);
if (found) {
$scope.quickJumpTarget = "template " + found[1];
}
}
}
}
};
$scope.quickJump = function () {
var parts = $scope.quickJumpTarget.split(" ");
if (parts.length != 2) {
return;
}
$scope.scrollTo(parts[0], parts[1]);
if (parts[0] == "template" && $scope.selected_alert) {
$scope.quickJumpTarget = "alert " + $scope.selected_alert;
}
};
$scope.setTemplateGroup = function (group) {
var match = group.match(/{(.*)}/);
if (match) {
$scope.template_group = match[1];
}
};
var line_re = /test:(\d+)/;
$scope.validate = function () {
$http.post('/api/config_test', $scope.config_text)
.success(function (data) {
if (data == "") {
$scope.validationResult = "Valid";
$timeout(function () {
$scope.validationResult = "";
}, 2000);
}
else {
$scope.validationResult = data;
var m = data.match(line_re);
if (angular.isArray(m) && (m.length > 1)) {
editor.gotoLine(m[1]);
}
}
})
.error(function (error) {
$scope.validationResult = 'Error validating: ' + error;
});
};
$scope.test = function () {
$scope.error = '';
$scope.running = true;
$scope.warning = [];
$location.search('fromDate', $scope.fromDate || null);
$location.search('fromTime', $scope.fromTime || null);
$location.search('toDate', $scope.toDate || null);
$location.search('toTime', $scope.toTime || null);
$location.search('intervals', String($scope.intervals) || null);
$location.search('duration', String($scope.duration) || null);
$location.search('email', $scope.email || null);
$location.search('template_group', $scope.template_group || null);
$scope.animate();
var from = moment.utc($scope.fromDate + ' ' + $scope.fromTime);
var to = moment.utc($scope.toDate + ' ' + $scope.toTime);
if (!from.isValid()) {
from = to;
}
if (!to.isValid()) {
to = from;
}
if (!from.isValid() && !to.isValid()) {
from = to = moment.utc();
}
var diff = from.diff(to);
var intervals;
if (diff == 0) {
intervals = 1;
}
else if (Math.abs(diff) < 60 * 1000) {
intervals = 2;
}
else {
intervals = +$scope.intervals;
}
var url = '/api/rule?' +
'alert=' + encodeURIComponent($scope.selected_alert) +
'&from=' + encodeURIComponent(from.format()) +
'&to=' + encodeURIComponent(to.format()) +
'&intervals=' + encodeURIComponent(intervals) +
'&email=' + encodeURIComponent($scope.email) +
'&template_group=' + encodeURIComponent($scope.template_group);
$http.post(url, $scope.config_text)
.success(function (data) {
$scope.sets = data.Sets;
$scope.alert_history = data.AlertHistory;
if (data.Hash) {
$location.search('hash', data.Hash);
}
procResults(data);
})
.error(function (error) {
$scope.error = error;
})
.finally(function () {
$scope.running = false;
$scope.stop();
});
};
$scope.zws = function (v) {
return v.replace(/([,{}()])/g, '$1\u200b');
};
$scope.loadTimelinePanel = function (entry, v) {
if (v.doneLoading && !v.error) {
return;
}
v.error = null;
v.doneLoading = false;
var ak = entry.key;
var openBrack = ak.indexOf("{");
var closeBrack = ak.indexOf("}");
var alertName = ak.substr(0, openBrack);
var template = ak.substring(openBrack + 1, closeBrack);
var url = '/api/rule?' +
'alert=' + encodeURIComponent(alertName) +
'&from=' + encodeURIComponent(moment.utc(v.Time).format()) +
'&template_group=' + encodeURIComponent(template);
$http.post(url, $scope.config_text)
.success(function (data) {
v.subject = data.Subject;
v.body = $sce.trustAsHtml(data.Body);
})
.error(function (error) {
v.error = error;
})
.finally(function () {
v.doneLoading = true;
});
};
function procResults(data) {
$scope.subject = data.Subject;
$scope.body = $sce.trustAsHtml(data.Body);
$scope.data = JSON.stringify(data.Data, null, ' ');
$scope.error = data.Errors;
$scope.warning = data.Warnings;
}
$scope.downloadConfig = function () {
var blob = new Blob([$scope.config_text], { type: "text/plain;charset=utf-8" });
saveAs(blob, "bosun.conf");
};
return $scope;
}]);
bosunControllers.controller('DashboardCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {
var search = $location.search();
$scope.loading = 'Loading';
$scope.error = '';
$scope.filter = search.filter;
if (!$scope.filter) {
$scope.filter = readCookie("filter");
}
$location.search('filter', $scope.filter || null);
reload();
function reload() {
$scope.refresh($scope.filter).then(function () {
$scope.loading = '';
$scope.error = '';
}, function (err) {
$scope.loading = '';
$scope.error = 'Unable to fetch alerts: ' + err;
});
}
$scope.keydown = function ($event) {
if ($event.keyCode == 13) {
createCookie("filter", $scope.filter || "", 1000);
$location.search('filter', $scope.filter || null);
}
};
}]);
bosunApp.directive('tsResults', function () {
return {
templateUrl: '/partials/results.html',
link: function (scope, elem, attrs) {
scope.isSeries = function (v) {
return typeof (v) === 'object';
};
}
};
});
bosunApp.directive('tsComputations', function () {
return {
scope: {
computations: '=tsComputations',
time: '=',
header: '='
},
templateUrl: '/partials/computations.html',
link: function (scope, elem, attrs) {
if (scope.time) {
var m = moment.utc(scope.time);
scope.timeParam = "&date=" + encodeURIComponent(m.format("YYYY-MM-DD")) + "&time=" + encodeURIComponent(m.format("HH:mm"));
}
scope.btoa = function (v) {
return encodeURIComponent(btoa(v));
};
}
};
});
function fmtDuration(v) {
var diff = moment.duration(v, 'milliseconds');
var f;
if (Math.abs(v) < 60000) {
return diff.format('ss[s]');
}
return diff.format('d[d]hh[h]mm[m]ss[s]');
}
function fmtTime(v) {
var m = moment(v).utc();
var now = moment().utc();
var msdiff = now.diff(m);
var ago = '';
var inn = '';
if (msdiff >= 0) {
ago = ' ago';
}
else {
inn = 'in ';
}
return m.format() + ' (' + inn + fmtDuration(msdiff) + ago + ')';
}
function parseDuration(v) {
var pattern = /(\d+)(d|y|n|h|m|s)-ago/;
var m = pattern.exec(v);
return moment.duration(parseInt(m[1]), m[2].replace('n', 'M'));
}
bosunApp.directive("tsTime", function () {
return {
link: function (scope, elem, attrs) {
scope.$watch(attrs.tsTime, function (v) {
var m = moment(v).utc();
var text = fmtTime(v);
if (attrs.tsEndTime) {
var diff = moment(scope.$eval(attrs.tsEndTime)).diff(m);
var duration = fmtDuration(diff);
text += " for " + duration;
}
if (attrs.noLink) {
elem.text(text);
}
else {
var el = document.createElement('a');
el.text = text;
el.href = 'http://www.timeanddate.com/worldclock/converted.html?iso=';
el.href += m.format('YYYYMMDDTHHmm');
el.href += '&p1=0';
angular.forEach(scope.timeanddate, function (v, k) {
el.href += '&p' + (k + 2) + '=' + v;
});
elem.html(el);
}
});
}
};
});
bosunApp.directive("tsSince", function () {
return {
link: function (scope, elem, attrs) {
scope.$watch(attrs.tsSince, function (v) {
var m = moment(v).utc();
elem.text(m.fromNow());
});
}
};
});
bosunApp.directive("tooltip", function () {
return {
link: function (scope, elem, attrs) {
angular.element(elem[0]).tooltip({ placement: "bottom" });
}
};
});
bosunApp.directive('tsTab', function () {
return {
link: function (scope, elem, attrs) {
var ta = elem[0];
elem.keydown(function (evt) {
if (evt.ctrlKey) {
return;
}
// This is so shift-enter can be caught to run a rule when tsTab is called from
// the rule page
if (evt.keyCode == 13 && evt.shiftKey) {
return;
}
switch (evt.keyCode) {
case 9:
evt.preventDefault();
var v = ta.value;
var start = ta.selectionStart;
ta.value = v.substr(0, start) + "\t" + v.substr(start);
ta.selectionStart = ta.selectionEnd = start + 1;
return;
case 13:
if (ta.selectionStart != ta.selectionEnd) {
return;
}
evt.preventDefault();
var v = ta.value;
var start = ta.selectionStart;
var sub = v.substr(0, start);
var last = sub.lastIndexOf("\n") + 1;
for (var i = last; i < sub.length && /[ \t]/.test(sub[i]); i++)
;
var ws = sub.substr(last, i - last);
ta.value = v.substr(0, start) + "\n" + ws + v.substr(start);
ta.selectionStart = ta.selectionEnd = start + 1 + ws.length;
}
});
}
};
});
bosunApp.directive('tsresizable', function () {
return {
restrict: 'A',
scope: {
callback: '&onResize'
},
link: function postLink(scope, elem, attrs) {
elem.resizable();
elem.on('resizestop', function (evt, ui) {
if (scope.callback) {
scope.callback();
}
});
}
};
});
bosunApp.directive('tsTableSort', ['$timeout', function ($timeout) {
return {
link: function (scope, elem, attrs) {
$timeout(function () {
$(elem).tablesorter({
sortList: scope.$eval(attrs.tsTableSort)
});
});
}
};
}]);
bosunApp.directive('tsTimeLine', function () {
var tsdbFormat = d3.time.format.utc("%Y/%m/%d-%X");
function parseDate(s) {
return moment.utc(s).toDate();
}
var margin = {
top: 10,
right: 10,
bottom: 30,
left: 250
};
return {
link: function (scope, elem, attrs) {
scope.shown = {};
scope.collapse = function (i, entry, v) {
scope.shown[i] = !scope.shown[i];
if (scope.loadTimelinePanel && entry && scope.shown[i]) {
scope.loadTimelinePanel(entry, v);
}
};
scope.$watch('alert_history', update);
function update(history) {
if (!history) {
return;
}
var entries = d3.entries(history);
if (!entries.length) {
return;
}
entries.sort(function (a, b) {
return a.key.localeCompare(b.key);
});
scope.entries = entries;
var values = entries.map(function (v) { return v.value; });
var keys = entries.map(function (v) { return v.key; });
var barheight = 500 / values.length;
barheight = Math.min(barheight, 45);
barheight = Math.max(barheight, 15);
var svgHeight = values.length * barheight + margin.top + margin.bottom;
var height = svgHeight - margin.top - margin.bottom;
var svgWidth = elem.width();
var width = svgWidth - margin.left - margin.right;
var xScale = d3.time.scale.utc().range([0, width]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom');
elem.empty();
var svg = d3.select(elem[0])
.append('svg')
.attr('width', svgWidth)
.attr('height', svgHeight)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
svg.append('g')
.attr('class', 'x axis tl-axis')
.attr('transform', 'translate(0,' + height + ')');
xScale.domain([
d3.min(values, function (d) { return d3.min(d.History, function (c) { return parseDate(c.Time); }); }),
d3.max(values, function (d) { return d3.max(d.History, function (c) { return parseDate(c.EndTime); }); }),
]);
var legend = d3.select(elem[0])
.append('div')
.attr('class', 'tl-legend');
var time_legend = legend
.append('div')
.text(values[0].History[0].Time);
var alert_legend = legend
.append('div')
.text(keys[0]);
svg.select('.x.axis')
.transition()
.call(xAxis);
var chart = svg.append('g');
angular.forEach(entries, function (entry, i) {
chart.selectAll('.bars')
.data(entry.value.History)
.enter()
.append('rect')
.attr('class', function (d) { return 'tl-' + d.Status; })
.attr('x', function (d) { return xScale(parseDate(d.Time)); })
.attr('y', i * barheight)
.attr('height', barheight)
.attr('width', function (d) {
return xScale(parseDate(d.EndTime)) - xScale(parseDate(d.Time));
})
.on('mousemove.x', mousemove_x)
.on('mousemove.y', function (d) {
alert_legend.text(entry.key);
})
.on('click', function (d, j) {
var id = 'panel' + i + '-' + j;
scope.shown['group' + i] = true;
scope.shown[id] = true;
if (scope.loadTimelinePanel) {
scope.loadTimelinePanel(entry, d);
}
scope.$apply();
setTimeout(function () {
var e = $("#" + id);
if (!e) {
console.log('no', id, e);
return;
}
$('html, body').scrollTop(e.offset().top);
});
});
});
chart.selectAll('.labels')
.data(keys)
.enter()
.append('text')
.attr('text-anchor', 'end')
.attr('x', 0)
.attr('dx', '-.5em')
.attr('dy', '.25em')
.attr('y', function (d, i) { return (i + .5) * barheight; })
.text(function (d) { return d; });
chart.selectAll('.sep')
.data(values)
.enter()
.append('rect')
.attr('y', function (d, i) { return (i + 1) * barheight; })
.attr('height', 1)
.attr('x', 0)
.attr('width', width)
.on('mousemove.x', mousemove_x);
function mousemove_x() {
var x = xScale.invert(d3.mouse(this)[0]);
time_legend
.text(tsdbFormat(x));
}
}
;
}
};
});
var fmtUnits = ['', 'k', 'M', 'G', 'T', 'P', 'E'];
function nfmt(s, mult, suffix, opts) {
opts = opts || {};
var n = parseFloat(s);
if (isNaN(n) && typeof s === 'string') {
return s;
}
if (opts.round)
n = Math.round(n);
if (!n)
return suffix ? '0 ' + suffix : '0';
if (isNaN(n) || !isFinite(n))
return '-';
var a = Math.abs(n);
if (a >= 1) {
var number = Math.floor(Math.log(a) / Math.log(mult));
a /= Math.pow(mult, Math.floor(number));
if (fmtUnits[number]) {
suffix = fmtUnits[number] + suffix;
}
}
var r = a.toFixed(5);
if (a < 1e-5) {
r = a.toString();
}
var neg = n < 0 ? '-' : '';
return neg + (+r) + suffix;
}
bosunApp.filter('nfmt', function () {
return function (s) {
return nfmt(s, 1000, '', {});
};
});
bosunApp.filter('bytes', function () {
return function (s) {
return nfmt(s, 1024, 'B', { round: true });
};
});
bosunApp.filter('bits', function () {
return function (s) {
return nfmt(s, 1024, 'b', { round: true });
};
});
bosunApp.directive('elastic', [
'$timeout',
function ($timeout) {
return {
restrict: 'A',
link: function ($scope, element) {
$scope.initialHeight = $scope.initialHeight || element[0].style.height;
var resize = function () {
element[0].style.height = $scope.initialHeight;
element[0].style.height = "" + element[0].scrollHeight + "px";
};
element.on("input change", resize);
$timeout(resize, 0);
}
};
}
]);
bosunApp.directive('tsGraph', ['$window', 'nfmtFilter', function ($window, fmtfilter) {
var margin = {
top: 10,
right: 10,
bottom: 30,
left: 80
};
return {
scope: {
data: '=',
height: '=',
generator: '=',
brushStart: '=bstart',
brushEnd: '=bend',
enableBrush: '@',
max: '=',
min: '=',
normalize: '='
},
link: function (scope, elem, attrs) {
var valueIdx = 1;
if (scope.normalize) {
valueIdx = 2;
}
var svgHeight = +scope.height || 150;
var height = svgHeight - margin.top - margin.bottom;
var svgWidth;
var width;
var yScale = d3.scale.linear().range([height, 0]);
var xScale = d3.time.scale.utc();
var xAxis = d3.svg.axis()
.orient('bottom');
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.ticks(Math.min(10, height / 20))
.tickFormat(fmtfilter);
var line;
switch (scope.generator) {
case 'area':
line = d3.svg.area();
break;
default:
line = d3.svg.line();
}
var brush = d3.svg.brush()
.x(xScale)
.on('brush', brushed);
var top = d3.select(elem[0])
.append('svg')
.attr('height', svgHeight)
.attr('width', '100%');
var svg = top
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var defs = svg.append('defs')
.append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('height', height);
var chart = svg.append('g')
.attr('pointer-events', 'all')
.attr('clip-path', 'url(#clip)');
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')');
svg.append('g')
.attr('class', 'y axis');
var paths = chart.append('g');
chart.append('g')
.attr('class', 'x brush');
top.append('rect')
.style('opacity', 0)
.attr('x', 0)
.attr('y', 0)
.attr('height', height)
.attr('width', margin.left)
.style('cursor', 'pointer')
.on('click', yaxisToggle);
var legendTop = d3.select(elem[0]).append('div');
var xloc = legendTop.append('div');
xloc.style('float', 'left');
var brushText = legendTop.append('div');
brushText.style('float', 'right');
var legend = d3.select(elem[0]).append('div');
legend.style('clear', 'both');
var color = d3.scale.ordinal().range([
'#e41a1c',
'#377eb8',
'#4daf4a',
'#984ea3',
'#ff7f00',
'#a65628',
'#f781bf',
'#999999',
]);
var mousex = 0;
var mousey = 0;
var oldx = 0;
var hover = svg.append('g')
.attr('class', 'hover')
.style('pointer-events', 'none')
.style('display', 'none');
var hoverPoint = hover.append('svg:circle')
.attr('r', 5);
var hoverRect = hover.append('svg:rect')
.attr('fill', 'white');
var hoverText = hover.append('svg:text')
.style('font-size', '12px');
var focus = svg.append('g')
.attr('class', 'focus')
.style('pointer-events', 'none');
focus.append('line');
var yaxisZero = false;
function yaxisToggle() {
yaxisZero = !yaxisZero;
draw();
}
var drawLegend = _.throttle(function (normalizeIdx) {
var names = legend.selectAll('.series')
.data(scope.data, function (d) { return d.Name; });
names.enter()
.append('div')
.attr('class', 'series');
names.exit()
.remove();
var xi = xScale.invert(mousex);
xloc.text('Time: ' + fmtTime(xi));
var t = xi.getTime() / 1000;
var minDist = width + height;
var minName, minColor;
var minX, minY;
names
.each(function (d) {
var idx = bisect(d.Data, t);
if (idx >= d.Data.length) {
idx = d.Data.length - 1;
}
var e = d3.select(this);
var pt = d.Data[idx];
if (pt) {
e.attr('title', pt[normalizeIdx]);
e.text(d.Name + ': ' + fmtfilter(pt[1]));
var ptx = xScale(pt[0] * 1000);
var pty = yScale(pt[normalizeIdx]);
var ptd = Math.sqrt(Math.pow(ptx - mousex, 2) +
Math.pow(pty - mousey, 2));
if (ptd < minDist) {
minDist = ptd;
minX = ptx;
minY = pty;
minName = d.Name + ': ' + pt[1];
minColor = color(d.Name);
}
}
})
.style('color', function (d) { return color(d.Name); });
hover
.attr('transform', 'translate(' + minX + ',' + minY + ')');
hoverPoint.style('fill', minColor);
hoverText
.text(minName)
.style('fill', minColor);
var isRight = minX > width / 2;
var isBottom = minY > height / 2;
hoverText
.attr('x', isRight ? -5 : 5)
.attr('y', isBottom ? -8 : 15)
.attr('text-anchor', isRight ? 'end' : 'start');
var node = hoverText.node();
var bb = node.getBBox();
hoverRect
.attr('x', bb.x - 1)
.attr('y', bb.y - 1)
.attr('height', bb.height + 2)
.attr('width', bb.width + 2);
var x = mousex;
if (x > width) {
x = 0;
}
focus.select('line')
.attr('x1', x)
.attr('x2', x)
.attr('y1', 0)
.attr('y2', height);
if (extentStart) {
var s = extentStart;
if (extentEnd != extentStart) {
s += ' - ' + extentEnd;
s += ' (' + extentDiff + ')';
}
brushText.text(s);
}
}, 50);
scope.$watch('data', update);
var w = angular.element($window);
scope.$watch(function () {
return w.width();
}, resize, true);
w.bind('resize', function () {
scope.$apply();
});
function resize() {
svgWidth = elem.width();
if (svgWidth <= 0) {
return;
}
width = svgWidth - margin.left - margin.right;
xScale.range([0, width]);
xAxis.scale(xScale);
if (!mousex) {
mousex = width + 1;
}
svg.attr('width', svgWidth);
defs.attr('width', width);
xAxis.ticks(width / 60);
draw();
}
var oldx = 0;
var bisect = d3.bisector(function (d) { return d[0]; }).left;
function update(v) {
if (!angular.isArray(v) || v.length == 0) {
return;
}
resize();
}
function draw() {
if (!scope.data) {
return;
}
if (scope.normalize) {
valueIdx = 2;
}
function mousemove() {
var pt = d3.mouse(this);
mousex = pt[0];
mousey = pt[1];
drawLegend(valueIdx);
}
scope.data.map(function (data, i) {
var max = d3.max(data.Data, function (d) { return d[1]; });
data.Data.map(function (d, j) {
d.push(d[1] / max * 100 || 0);
});
});
line.y(function (d) { return yScale(d[valueIdx]); });
line.x(function (d) { return xScale(d[0] * 1000); });
var xdomain = [
d3.min(scope.data, function (d) { return d3.min(d.Data, function (c) { return c[0]; }); }) * 1000,
d3.max(scope.data, function (d) { return d3.max(d.Data, function (c) { return c[0]; }); }) * 1000,
];
if (!oldx) {
oldx = xdomain[1];
}
xScale.domain(xdomain);
var ymin = d3.min(scope.data, function (d) { return d3.min(d.Data, function (c) { return c[1]; }); });
var ymax = d3.max(scope.data, function (d) { return d3.max(d.Data, function (c) { return c[valueIdx]; }); });
var diff = (ymax - ymin) / 50;
if (!diff) {
diff = 1;
}
ymin -= diff;
ymax += diff;
if (yaxisZero) {
if (ymin > 0) {
ymin = 0;
}
else if (ymax < 0) {
ymax = 0;
}
}
var ydomain = [ymin, ymax];
if (angular.isNumber(scope.min)) {
ydomain[0] = +scope.min;
}
if (angular.isNumber(scope.max)) {
ydomain[valueIdx] = +scope.max;
}
yScale.domain(ydomain);
if (scope.generator == 'area') {
line.y0(yScale(0));
}
svg.select('.x.axis')
.transition()
.call(xAxis);
svg.select('.y.axis')
.transition()
.call(yAxis);
svg.append('text')
.attr("class", "ylabel")
.attr("transform", "rotate(-90)")
.attr("y", -margin.left)
.attr("x", -(height / 2))
.attr("dy", "1em")
.text(_.uniq(scope.data.map(function (v) { return v.Unit; })).join("; "));
var queries = paths.selectAll('.line')
.data(scope.data, function (d) { return d.Name; });
switch (scope.generator) {
case 'area':
queries.enter()
.append('path')
.attr('stroke', function (d) { return color(d.Name); })
.attr('class', 'line')
.style('fill', function (d) { return color(d.Name); });
break;
default:
queries.enter()
.append('path')
.attr('stroke', function (d) { return color(d.Name); })
.attr('class', 'line');
}
queries.exit()
.remove();
queries
.attr('d', function (d) { return line(d.Data); })
.attr('transform', null)
.transition()
.ease('linear')
.attr('transform', 'translate(' + (xScale(oldx) - xScale(xdomain[1])) + ')');
chart.select('.x.brush')
.call(brush)
.selectAll('rect')
.attr('height', height)
.on('mouseover', function () {
hover.style('display', 'block');
})
.on('mouseout', function () {
hover.style('display', 'none');
})
.on('mousemove', mousemove);
chart.select('.x.brush .extent')
.style('stroke', '#fff')
.style('fill-opacity', '.125')
.style('shape-rendering', 'crispEdges');
oldx = xdomain[1];
drawLegend(valueIdx);
}
;
var extentStart;
var extentEnd;
var extentDiff;
function brushed() {
var extent = brush.extent();
extentStart = datefmt(extent[0]);
extentEnd = datefmt(extent[1]);
extentDiff = fmtDuration(moment(extent[1]).diff(moment(extent[0])));
drawLegend(valueIdx);
if (scope.enableBrush && extentEnd != extentStart) {
scope.brushStart = extentStart;
scope.brushEnd = extentEnd;
scope.$apply();
}
}
var mfmt = 'YYYY/MM/DD-HH:mm:ss';
function datefmt(d) {
return moment(d).utc().format(mfmt);
}
}
};
}]);
bosunControllers.controller('ExprCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) {
var search = $location.search();
var current;
try {
current = atob(search.expr);
}
catch (e) {
current = '';
}
if (!current) {
$location.search('expr', btoa('avg(q("avg:rate:os.cpu{host=*bosun*}", "5m", "")) > 80'));
return;
}
$scope.date = search.date || '';
$scope.time = search.time || '';
$scope.expr = current;
$scope.running = current;
$scope.tab = search.tab || 'results';
$scope.animate();
$http.post('/api/expr?' +
'date=' + encodeURIComponent($scope.date) +
'&time=' + encodeURIComponent($scope.time), current)
.success(function (data) {
$scope.result = data.Results;
$scope.queries = data.Queries;
$scope.result_type = data.Type;
if (data.Type == 'series') {
$scope.svg_url = '/api/egraph/' + btoa(current) + '.svg?now=' + Math.floor(Date.now() / 1000);
$scope.graph = toChart(data.Results);
}
$scope.running = '';
})
.error(function (error) {
$scope.error = error;
$scope.running = '';
})
.finally(function () {
$scope.stop();
});
$scope.set = function () {
$location.search('expr', btoa($scope.expr));
$location.search('date', $scope.date || null);
$location.search('time', $scope.time || null);
$route.reload();
};
function toChart(res) {
var graph = [];
angular.forEach(res, function (d, idx) {
var data = [];
angular.forEach(d.Value, function (val, ts) {
data.push([+ts, val]);
});
if (data.length == 0) {
return;
}
var name = '{';
angular.forEach(d.Group, function (tagv, tagk) {
if (name.length > 1) {
name += ',';
}
name += tagk + '=' + tagv;
});
name += '}';
var series = {
Data: data,
Name: name
};
graph[idx] = series;
});
return graph;
}
$scope.keydown = function ($event) {
if ($event.shiftKey && $event.keyCode == 13) {
$scope.set();
}
};
}]);
var TagSet = (function () {
function TagSet() {
}
return TagSet;
})();
var TagV = (function () {
function TagV() {
}
return TagV;
})();
var RateOptions = (function () {
function RateOptions() {
}
return RateOptions;
})();
var Query = (function () {
function Query(q) {
this.aggregator = q && q.aggregator || 'sum';
this.metric = q && q.metric || '';
this.rate = q && q.rate || false;
this.rateOptions = q && q.rateOptions || new RateOptions;
if (q && !q.derivative) {
// back compute derivative from q
if (!this.rate) {
this.derivative = 'gauge';
}
else if (this.rateOptions.counter) {
this.derivative = 'counter';
}
else {
this.derivative = 'rate';
}
}
else {
this.derivative = q && q.derivative || 'auto';
}
this.ds = q && q.ds || '';
this.dstime = q && q.dstime || '';
this.tags = q && q.tags || new TagSet;
this.setDs();
this.setDerivative();
}
Query.prototype.setDs = function () {
if (this.dstime && this.ds) {
this.downsample = this.dstime + '-' + this.ds;
}
else {
this.downsample = '';
}
};
Query.prototype.setDerivative = function () {
var max = this.rateOptions.counterMax;
this.rate = false;
this.rateOptions = new RateOptions();
switch (this.derivative) {
case "rate":
this.rate = true;
break;
case "counter":
this.rate = true;
this.rateOptions.counter = true;
this.rateOptions.counterMax = max;
this.rateOptions.resetValue = 1;
break;
case "gauge":
this.rate = false;
break;
}
};
return Query;
})();
var Request = (function () {
function Request() {
this.start = '1h-ago';
this.queries = [];
}
Request.prototype.prune = function () {
var _this = this;
for (var i = 0; i < this.queries.length; i++) {
angular.forEach(this.queries[i], function (v, k) {
var qi = _this.queries[i];
switch (typeof v) {
case "string":
if (!v) {
delete qi[k];
}
break;
case "boolean":
if (!v) {
delete qi[k];
}
break;
case "object":
if (Object.keys(v).length == 0) {
delete qi[k];
}
break;
}
});
}
};
return Request;
})();
var graphRefresh;
bosunControllers.controller('GraphCtrl', ['$scope', '$http', '$location', '$route', '$timeout', function ($scope, $http, $location, $route, $timeout) {
$scope.aggregators = ["sum", "min", "max", "avg", "dev", "zimsum", "mimmin", "minmax"];
$scope.dsaggregators = ["", "sum", "min", "max", "avg", "dev", "zimsum", "mimmin", "minmax"];
$scope.rate_options = ["auto", "gauge", "counter", "rate"];
$scope.canAuto = {};
var search = $location.search();
var j = search.json;
if (search.b64) {
j = atob(search.b64);
}
var request = j ? JSON.parse(j) : new Request;
$scope.index = parseInt($location.hash()) || 0;
$scope.tagvs = [];
$scope.sorted_tagks = [];
$scope.query_p = [];
angular.forEach(request.queries, function (q, i) {
$scope.query_p[i] = new Query(q);
});
$scope.start = request.start;
$scope.end = request.end;
$scope.autods = search.autods != 'false';
$scope.refresh = search.refresh == 'true';
$scope.normalize = search.normalize == 'true';
if (search.min) {
$scope.min = +search.min;
}
if (search.max) {
$scope.max = +search.max;
}
var duration_map = {
"s": "s",
"m": "m",
"h": "h",
"d": "d",
"w": "w",
"n": "M",
"y": "y"
};
var isRel = /^(\d+)(\w)-ago$/;
function RelToAbs(m) {
return moment().utc().subtract(parseFloat(m[1]), duration_map[m[2]]).format();
}
function AbsToRel(s) {
//Not strict parsing of the time format. For example, just "2014" will be valid
var t = moment.utc(s, moment.defaultFormat).fromNow();
return t;
}
function SwapTime(s) {
if (!s) {
return moment().utc().format();
}
var m = isRel.exec(s);
if (m) {
return RelToAbs(m);
}
return AbsToRel(s);
}
$scope.SwitchTimes = function () {
$scope.start = SwapTime($scope.start);
$scope.end = SwapTime($scope.end);
};
$scope.AddTab = function () {
$scope.index = $scope.query_p.length;
$scope.query_p.push(new Query);
};
$scope.setIndex = function (i) {
$scope.index = i;
};
$scope.GetTagKByMetric = function (index) {
$scope.tagvs[index] = new TagV;
var metric = $scope.query_p[index].metric;
if (!metric) {
$scope.canAuto[metric] = true;
return;
}
$http.get('/api/tagk/' + metric)
.success(function (data) {
var q = $scope.query_p[index];
var tags = new TagSet;
q.metric_tags = {};
for (var i = 0; i < data.length; i++) {
var d = data[i];
q.metric_tags[d] = true;
if (q.tags) {
tags[d] = q.tags[d];
}
if (!tags[d]) {
tags[d] = '';
}
GetTagVs(d, index);
}
angular.forEach(q.tags, function (val, key) {
if (val) {
tags[key] = val;
}
});
q.tags = tags;
// Make sure host is always the first tag.
$scope.sorted_tagks[index] = Object.keys(tags);
$scope.sorted_tagks[index].sort(function (a, b) {
if (a == 'host') {
return -1;
}
else if (b == 'host') {
return 1;
}
return a.localeCompare(b);
});
})
.error(function (error) {
$scope.error = 'Unable to fetch metrics: ' + error;
});
$http.get('/api/metadata/get?metric=' + metric)
.success(function (data) {
var canAuto = false;
angular.forEach(data, function (val) {
if (val.Metric == metric && val.Name == 'rate') {
canAuto = true;
}
});
$scope.canAuto[metric] = canAuto;
})
.error(function (err) {
$scope.error = err;
});
};
if ($scope.query_p.length == 0) {
$scope.AddTab();
}
$http.get('/api/metric')
.success(function (data) {
$scope.metrics = data;
})
.error(function (error) {
$scope.error = 'Unable to fetch metrics: ' + error;
});
function GetTagVs(k, index) {
$http.get('/api/tagv/' + k + '/' + $scope.query_p[index].metric)
.success(function (data) {
data.sort();
$scope.tagvs[index][k] = data;
})
.error(function (error) {
$scope.error = 'Unable to fetch metrics: ' + error;
});
}
function getRequest() {
request = new Request;
request.start = $scope.start;
request.end = $scope.end;
angular.forEach($scope.query_p, function (p) {
if (!p.metric) {
return;
}
var q = new Query(p);
var tags = q.tags;
q.tags = new TagSet;
angular.forEach(tags, function (v, k) {
if (v && k) {
q.tags[k] = v;
}
});
request.queries.push(q);
});
return request;
}
$scope.Query = function () {
var r = getRequest();
angular.forEach($scope.query_p, function (q, index) {
var m = q.metric_tags;
if (!m) {
return;
}
angular.forEach(q.tags, function (key, tag) {
if (m[tag]) {
return;
}
delete r.queries[index].tags[tag];
});
});
r.prune();
$location.search('b64', btoa(JSON.stringify(r)));
$location.search('autods', $scope.autods ? undefined : 'false');
$location.search('refresh', $scope.refresh ? 'true' : undefined);
$location.search('normalize', $scope.normalize ? 'true' : undefined);
var min = angular.isNumber($scope.min) ? $scope.min.toString() : null;
var max = angular.isNumber($scope.max) ? $scope.max.toString() : null;
$location.search('min', min);
$location.search('max', max);
$route.reload();
};
request = getRequest();
if (!request.queries.length) {
return;
}
var autods = $scope.autods ? '&autods=' + $('#chart').width() : '';
function getMetricMeta(metric) {
$http.get('/api/metadata/metrics?metric=' + encodeURIComponent(metric))
.success(function (data) {
if (Object.keys(data).length == 1) {
$scope.meta[metric] = data[metric];
}
})
.error(function (error) {
console.log("Error getting metadata for metric " + metric);
});
}
function get(noRunning) {
$timeout.cancel(graphRefresh);
if (!noRunning) {
$scope.running = 'Running';
}
var autorate = '';
$scope.meta = {};
for (var i = 0; i < request.queries.length; i++) {
if (request.queries[i].derivative == 'auto') {
autorate += '&autorate=' + i;
}
getMetricMeta(request.queries[i].metric);
}
var min = angular.isNumber($scope.min) ? '&min=' + encodeURIComponent($scope.min.toString()) : '';
var max = angular.isNumber($scope.max) ? '&max=' + encodeURIComponent($scope.max.toString()) : '';
$scope.animate();
$scope.queryTime = '';
if (request.end && !isRel.exec(request.end)) {
var t = moment.utc(request.end, moment.defaultFormat);
$scope.queryTime = '&date=' + t.format('YYYY-MM-DD');
$scope.queryTime += '&time=' + t.format('HH:mm');
}
$http.get('/api/graph?' + 'b64=' + encodeURIComponent(btoa(JSON.stringify(request))) + autods + autorate + min + max)
.success(function (data) {
$scope.result = data.Series;
if (!$scope.result) {
$scope.warning = 'No Results';
}
else {
$scope.warning = '';
}
$scope.queries = data.Queries;
$scope.running = '';
$scope.error = '';
var u = $location.absUrl();
u = u.substr(0, u.indexOf('?')) + '?';
u += 'b64=' + search.b64 + autods + autorate + min + max;
$scope.url = u;
})
.error(function (error) {
$scope.error = error;
$scope.running = '';
})
.finally(function () {
$scope.stop();
if ($scope.refresh) {
graphRefresh = $timeout(function () { get(true); }, 5000);
}
;
});
}
;
get(false);
}]);
bosunApp.directive('tsPopup', function () {
return {
restrict: 'E',
scope: {
url: '='
},
template: '<button class="btn btn-default" data-html="true" data-placement="bottom">embed</button>',
link: function (scope, elem, attrs) {
var button = $('button', elem);
scope.$watch(attrs.url, function (url) {
if (!url) {
return;
}
var text = '<input type="text" onClick="this.select();" readonly="readonly" value="<a href="' + url + '"><img src="' + url + '&.png=png"></a>">';
button.popover({
content: text
});
});
}
};
});
bosunApp.directive('tsAlertHistory', function () {
return {
templateUrl: '/partials/alerthistory.html'
};
});
bosunControllers.controller('HistoryCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) {
var search = $location.search();
var keys = {};
if (angular.isArray(search.key)) {
angular.forEach(search.key, function (v) {
keys[v] = true;
});
}
else {
keys[search.key] = true;
}
var params = Object.keys(keys).map(function (v) { return 'ak=' + encodeURIComponent(v); }).join('&');
$http.get('/api/status?' + params)
.success(function (data) {
var selected_alerts = {};
angular.forEach(data, function (v, ak) {
if (!keys[ak]) {
return;
}
v.History.map(function (h) { h.Time = moment.utc(h.Time); });
angular.forEach(v.History, function (h, i) {
if (i + 1 < v.History.length) {
h.EndTime = v.History[i + 1].Time;
}
else {
h.EndTime = moment.utc();
}
});
selected_alerts[ak] = {
History: v.History.reverse()
};
});
if (Object.keys(selected_alerts).length > 0) {
$scope.alert_history = selected_alerts;
}
else {
$scope.error = 'No Matching Alerts Found';
}
})
.error(function (err) {
$scope.error = err;
});
}]);
bosunControllers.controller('HostCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) {
var search = $location.search();
$scope.host = search.host;
$scope.time = search.time;
$scope.tab = search.tab || "stats";
$scope.idata = [];
$scope.fsdata = [];
$scope.metrics = [];
var currentURL = $location.url();
$scope.mlink = function (m) {
var r = new Request();
var q = new Query();
q.metric = m;
q.tags = { 'host': $scope.host };
r.queries.push(q);
return r;
};
$scope.setTab = function (t) {
$location.search('tab', t);
$scope.tab = t;
};
$http.get('/api/metric/host/' + $scope.host)
.success(function (data) {
$scope.metrics = data || [];
});
var start = moment().utc().subtract(parseDuration($scope.time));
function parseDuration(v) {
var pattern = /(\d+)(d|y|n|h|m|s)-ago/;
var m = pattern.exec(v);
return moment.duration(parseInt(m[1]), m[2].replace('n', 'M'));
}
$http.get('/api/metadata/get?tagk=host&tagv=' + encodeURIComponent($scope.host))
.success(function (data) {
$scope.metadata = _.filter(data, function (i) {
return moment.utc(i.Time) > start;
});
});
var autods = '&autods=100';
var cpu_r = new Request();
cpu_r.start = $scope.time;
cpu_r.queries = [
new Query({
metric: 'os.cpu',
derivative: 'counter',
tags: { host: $scope.host }
})
];
$http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(cpu_r)) + autods)
.success(function (data) {
if (!data.Series) {
return;
}
data.Series[0].Name = 'Percent Used';
$scope.cpu = data.Series;
});
var mem_r = new Request();
mem_r.start = $scope.time;
mem_r.queries.push(new Query({
metric: "os.mem.total",
tags: { host: $scope.host }
}));
mem_r.queries.push(new Query({
metric: "os.mem.used",
tags: { host: $scope.host }
}));
$http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(mem_r)) + autods)
.success(function (data) {
if (!data.Series) {
return;
}
data.Series[1].Name = "Used";
$scope.mem_total = Math.max.apply(null, data.Series[0].Data.map(function (d) { return d[1]; }));
$scope.mem = [data.Series[1]];
});
$http.get('/api/tagv/iface/os.net.bytes?host=' + $scope.host)
.success(function (data) {
angular.forEach(data, function (i, idx) {
$scope.idata[idx] = {
Name: i
};
});
function next(idx) {
var idata = $scope.idata[idx];
if (!idata || currentURL != $location.url()) {
return;
}
var net_bytes_r = new Request();
net_bytes_r.start = $scope.time;
net_bytes_r.queries = [
new Query({
metric: "os.net.bytes",
rate: true,
rateOptions: { counter: true, resetValue: 1 },
tags: { host: $scope.host, iface: idata.Name, direction: "*" }
})
];
$http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(net_bytes_r)) + autods)
.success(function (data) {
if (!data.Series) {
return;
}
angular.forEach(data.Series, function (d) {
d.Data = d.Data.map(function (dp) { return [dp[0], dp[1] * 8]; });
if (d.Name.indexOf("direction=out") != -1) {
d.Data = d.Data.map(function (dp) { return [dp[0], dp[1] * -1]; });
d.Name = "out";
}
else {
d.Name = "in";
}
});
$scope.idata[idx].Data = data.Series;
})
.finally(function () {
next(idx + 1);
});
}
next(0);
});
$http.get('/api/tagv/disk/os.disk.fs.space_total?host=' + $scope.host)
.success(function (data) {
angular.forEach(data, function (i, idx) {
if (i == '/dev/shm') {
return;
}
var fs_r = new Request();
fs_r.start = $scope.time;
fs_r.queries.push(new Query({
metric: "os.disk.fs.space_total",
tags: { host: $scope.host, disk: i }
}));
fs_r.queries.push(new Query({
metric: "os.disk.fs.space_used",
tags: { host: $scope.host, disk: i }
}));
$scope.fsdata[idx] = {
Name: i
};
$http.get('/api/graph?' + 'json=' + encodeURIComponent(JSON.stringify(fs_r)) + autods)
.success(function (data) {
if (!data.Series) {
return;
}
data.Series[1].Name = 'Used';
var total = Math.max.apply(null, data.Series[0].Data.map(function (d) { return d[1]; }));
var c_val = data.Series[1].Data.slice(-1)[0][1];
var percent_used = c_val / total * 100;
$scope.fsdata[idx].total = total;
$scope.fsdata[idx].c_val = c_val;
$scope.fsdata[idx].percent_used = percent_used;
$scope.fsdata[idx].Data = [data.Series[1]];
});
});
});
}]);
bosunControllers.controller('IncidentCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) {
var search = $location.search();
var id = search.id;
if (!id) {
$scope.error = "must supply incident id as query parameter";
return;
}
$http.get('/api/incidents/events?id=' + id)
.success(function (data) {
$scope.incident = data.Incident;
$scope.events = data.Events;
$scope.actions = data.Actions;
})
.error(function (err) {
$scope.error = err;
});
}]);
bosunControllers.controller('ItemsCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/api/metric')
.success(function (data) {
$scope.metrics = data;
})
.error(function (error) {
$scope.status = 'Unable to fetch metrics: ' + error;
});
$http.get('/api/tagv/host?since=default')
.success(function (data) {
$scope.hosts = data;
})
.error(function (error) {
$scope.status = 'Unable to fetch hosts: ' + error;
});
}]);
var Tag = (function () {
function Tag() {
}
return Tag;
})();
var DP = (function () {
function DP() {
}
return DP;
})();
bosunControllers.controller('PutCtrl', ['$scope', '$http', '$route', function ($scope, $http, $route) {
$scope.tags = [new Tag];
var dp = new DP;
dp.k = moment().utc().format();
$scope.dps = [dp];
$http.get('/api/metric')
.success(function (data) {
$scope.metrics = data;
})
.error(function (error) {
$scope.error = 'Unable to fetch metrics: ' + error;
});
$scope.Submit = function () {
var data = [];
var tags = {};
angular.forEach($scope.tags, function (v, k) {
if (v.k || v.v) {
tags[v.k] = v.v;
}
});
angular.forEach($scope.dps, function (v, k) {
if (v.k && v.v) {
var ts = parseInt(moment.utc(v.k, tsdbDateFormat).format('X'));
data.push({
metric: $scope.metric,
timestamp: ts,
value: parseFloat(v.v),
tags: tags
});
}
});
$scope.running = 'submitting data...';
$scope.success = '';
$scope.error = '';
$http.post('/api/put', data)
.success(function () {
$scope.running = '';
$scope.success = 'Data Submitted';
})
.error(function (error) {
$scope.running = '';
$scope.error = error.error.message;
});
};
$scope.AddTag = function () {
var last = $scope.tags[$scope.tags.length - 1];
if (last.k && last.v) {
$scope.tags.push(new Tag);
}
};
$scope.AddDP = function () {
var last = $scope.dps[$scope.dps.length - 1];
if (last.k && last.v) {
var dp = new DP;
dp.k = moment.utc(last.k, tsdbDateFormat).add(15, 'seconds').format();
$scope.dps.push(dp);
}
};
$scope.GetTagKByMetric = function () {
$http.get('/api/tagk/' + $scope.metric)
.success(function (data) {
if (!angular.isArray(data)) {
return;
}
$scope.tags = [new Tag];
for (var i = 0; i < data.length; i++) {
var t = new Tag;
t.k = data[i];
$scope.tags.push(t);
}
})
.error(function (error) {
$scope.error = 'Unable to fetch metrics: ' + error;
});
};
}]);
bosunControllers.controller('SilenceCtrl', ['$scope', '$http', '$location', '$route', function ($scope, $http, $location, $route) {
var search = $location.search();
$scope.start = search.start;
$scope.end = search.end;
$scope.duration = search.duration;
$scope.alert = search.alert;
$scope.hosts = search.hosts;
$scope.tags = search.tags;
$scope.edit = search.edit;
$scope.forget = search.forget;
$scope.user = getUser();
$scope.message = search.message;
if (!$scope.end && !$scope.duration) {
$scope.duration = '1h';
}
function filter(data, startBefore, startAfter, endAfter, endBefore, limit) {
var ret = {};
var count = 0;
_.each(data, function (v, name) {
if (limit && count >= limit) {
return;
}
var s = moment(v.Start).utc();
var e = moment(v.End).utc();
if (startBefore && s > startBefore) {
return;
}
if (startAfter && s < startAfter) {
return;
}
if (endAfter && e < endAfter) {
return;
}
if (endBefore && e > endBefore) {
return;
}
ret[name] = v;
});
return ret;
}
function get() {
$http.get('/api/silence/get')
.success(function (data) {
$scope.silences = [];
var now = moment.utc();
$scope.silences.push({
name: 'Active',
silences: filter(data, now, null, now, null, 0)
});
$scope.silences.push({
name: 'Upcoming',
silences: filter(data, null, now, null, null, 0)
});
$scope.silences.push({
name: 'Past',
silences: filter(data, null, null, null, now, 25)
});
})
.error(function (error) {
$scope.error = error;
});
}
get();
function getData() {
var tags = ($scope.tags || '').split(',');
if ($scope.hosts) {
tags.push('host=' + $scope.hosts.split(/[ ,|]+/).join('|'));
}
tags = tags.filter(function (v) { return v != ""; });
var data = {
start: $scope.start,
end: $scope.end,
duration: $scope.duration,
alert: $scope.alert,
tags: tags.join(','),
edit: $scope.edit,
forget: $scope.forget ? 'true' : null,
user: $scope.user,
message: $scope.message
};
return data;
}
var any = search.start || search.end || search.duration || search.alert || search.hosts || search.tags || search.forget;
var state = getData();
$scope.change = function () {
$scope.disableConfirm = true;
};
if (any) {
$scope.error = null;
$http.post('/api/silence/set', state)
.success(function (data) {
if (!data) {
data = { '(none)': false };
}
$scope.testSilences = data;
})
.error(function (error) {
$scope.error = error;
});
}
$scope.test = function () {
setUser($scope.user);
$location.search('start', $scope.start || null);
$location.search('end', $scope.end || null);
$location.search('duration', $scope.duration || null);
$location.search('alert', $scope.alert || null);
$location.search('hosts', $scope.hosts || null);
$location.search('tags', $scope.tags || null);
$location.search('forget', $scope.forget || null);
$location.search('message', $scope.message || null);
$route.reload();
};
$scope.confirm = function () {
$scope.error = null;
$scope.testSilences = null;
state.confirm = 'true';
$http.post('/api/silence/set', state)
.error(function (error) {
$scope.error = error;
})
.finally(get);
};
$scope.clear = function (id) {
if (!window.confirm('Clear this silence?')) {
return;
}
$scope.error = null;
$http.post('/api/silence/clear?id=' + id, {})
.error(function (error) {
$scope.error = error;
})
.finally(get);
};
$scope.time = function (v) {
var m = moment(v).utc();
return m.format();
};
}]);
bosunApp.directive('tsAckGroup', ['$location', function ($location) {
return {
scope: {
ack: '=',
groups: '=tsAckGroup',
schedule: '=',
timeanddate: '='
},
templateUrl: '/partials/ackgroup.html',
link: function (scope, elem, attrs) {
scope.canAckSelected = scope.ack == 'Needs Acknowledgement';
scope.panelClass = scope.$parent.panelClass;
scope.btoa = scope.$parent.btoa;
scope.encode = scope.$parent.encode;
scope.shown = {};
scope.collapse = function (i) {
scope.shown[i] = !scope.shown[i];
};
scope.click = function ($event, idx) {
scope.collapse(idx);
if ($event.shiftKey && scope.schedule.checkIdx != undefined) {
var checked = scope.groups[scope.schedule.checkIdx].checked;
var start = Math.min(idx, scope.schedule.checkIdx);
var end = Math.max(idx, scope.schedule.checkIdx);
for (var i = start; i <= end; i++) {
if (i == idx) {
continue;
}
scope.groups[i].checked = checked;
}
}
scope.schedule.checkIdx = idx;
scope.update();
};
scope.select = function (checked) {
for (var i = 0; i < scope.groups.length; i++) {
scope.groups[i].checked = checked;
}
scope.update();
};
scope.update = function () {
scope.canCloseSelected = true;
scope.canForgetSelected = true;
scope.anySelected = false;
for (var i = 0; i < scope.groups.length; i++) {
var g = scope.groups[i];
if (!g.checked) {
continue;
}
scope.anySelected = true;
if (g.Active && g.Status != 'unknown' && g.Status != 'error') {
scope.canCloseSelected = false;
}
if (g.Status != 'unknown') {
scope.canForgetSelected = false;
}
}
};
scope.multiaction = function (type) {
var keys = [];
angular.forEach(scope.groups, function (group) {
if (!group.checked) {
return;
}
if (group.AlertKey) {
keys.push(group.AlertKey);
}
angular.forEach(group.Children, function (child) {
keys.push(child.AlertKey);
});
});
scope.$parent.setKey("action-keys", keys);
$location.path("action");
$location.search("type", type);
};
scope.history = function () {
var url = '/history?';
angular.forEach(scope.groups, function (group) {
if (!group.checked) {
return;
}
if (group.AlertKey) {
url += '&key=' + encodeURIComponent(group.AlertKey);
}
angular.forEach(group.Children, function (child) {
url += '&key=' + encodeURIComponent(child.AlertKey);
});
});
return url;
};
}
};
}]);
bosunApp.directive('tsState', ['$sce', '$http', function ($sce, $http) {
return {
templateUrl: '/partials/alertstate.html',
link: function (scope, elem, attrs) {
scope.name = scope.child.AlertKey;
scope.state = scope.child.State;
scope.action = function (type) {
var key = encodeURIComponent(scope.name);
return '/action?type=' + type + '&key=' + key;
};
var loadedBody = false;
scope.toggle = function () {
scope.show = !scope.show;
if (scope.show && !loadedBody) {
scope.state.Body = "loading...";
loadedBody = true;
$http.get('/api/status?ak=' + scope.child.AlertKey)
.success(function (data) {
var body = data[scope.child.AlertKey].Body;
scope.state.Body = $sce.trustAsHtml(body);
})
.error(function (err) {
scope.state.Body = "Error loading template body: " + err;
});
}
};
scope.zws = function (v) {
if (!v) {
return '';
}
return v.replace(/([,{}()])/g, '$1\u200b');
};
scope.state.Touched = moment(scope.state.Touched).utc();
angular.forEach(scope.state.History, function (v, k) {
v.Time = moment(v.Time).utc();
});
scope.state.last = scope.state.History[scope.state.History.length - 1];
if (scope.state.Actions && scope.state.Actions.length > 0) {
scope.state.LastAction = scope.state.Actions[0];
}
scope.state.RuleUrl = '/config?' +
'alert=' + encodeURIComponent(scope.state.Alert) +
'&fromDate=' + encodeURIComponent(scope.state.last.Time.format("YYYY-MM-DD")) +
'&fromTime=' + encodeURIComponent(scope.state.last.Time.format("HH:mm"));
var groups = [];
angular.forEach(scope.state.Group, function (v, k) {
groups.push(k + "=" + v);
});
if (groups.length > 0) {
scope.state.RuleUrl += '&template_group=' + encodeURIComponent(groups.join(','));
}
scope.state.Body = $sce.trustAsHtml(scope.state.Body);
}
};
}]);
bosunApp.directive('tsAck', function () {
return {
restrict: 'E',
templateUrl: '/partials/ack.html'
};
});
bosunApp.directive('tsClose', function () {
return {
restrict: 'E',
templateUrl: '/partials/close.html'
};
});
bosunApp.directive('tsForget', function () {
return {
restrict: 'E',
templateUrl: '/partials/forget.html'
};
});
| dimamedvedev/bosun | cmd/bosun/web/static/js/bosun.js | JavaScript | mit | 97,399 |
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import Typography from '../Typography';
import withStyles from '../styles/withStyles';
import FormControlContext, { useFormControl } from '../FormControl/FormControlContext';
export var styles = {
/* Styles applied to the root element. */
root: {
display: 'flex',
height: '0.01em',
// Fix IE 11 flexbox alignment. To remove at some point.
maxHeight: '2em',
alignItems: 'center',
whiteSpace: 'nowrap'
},
/* Styles applied to the root element if `variant="filled"`. */
filled: {
'&$positionStart:not($hiddenLabel)': {
marginTop: 16
}
},
/* Styles applied to the root element if `position="start"`. */
positionStart: {
marginRight: 8
},
/* Styles applied to the root element if `position="end"`. */
positionEnd: {
marginLeft: 8
},
/* Styles applied to the root element if `disablePointerEvents=true`. */
disablePointerEvents: {
pointerEvents: 'none'
},
/* Styles applied if the adornment is used inside <FormControl hiddenLabel />. */
hiddenLabel: {},
/* Styles applied if the adornment is used inside <FormControl margin="dense" />. */
marginDense: {}
};
var InputAdornment = /*#__PURE__*/React.forwardRef(function InputAdornment(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$component = props.component,
Component = _props$component === void 0 ? 'div' : _props$component,
_props$disablePointer = props.disablePointerEvents,
disablePointerEvents = _props$disablePointer === void 0 ? false : _props$disablePointer,
_props$disableTypogra = props.disableTypography,
disableTypography = _props$disableTypogra === void 0 ? false : _props$disableTypogra,
position = props.position,
variantProp = props.variant,
other = _objectWithoutProperties(props, ["children", "classes", "className", "component", "disablePointerEvents", "disableTypography", "position", "variant"]);
var muiFormControl = useFormControl() || {};
var variant = variantProp;
if (variantProp && muiFormControl.variant) {
if (process.env.NODE_ENV !== 'production') {
if (variantProp === muiFormControl.variant) {
console.error('Material-UI: The `InputAdornment` variant infers the variant prop ' + 'you do not have to provide one.');
}
}
}
if (muiFormControl && !variant) {
variant = muiFormControl.variant;
}
return /*#__PURE__*/React.createElement(FormControlContext.Provider, {
value: null
}, /*#__PURE__*/React.createElement(Component, _extends({
className: clsx(classes.root, className, disablePointerEvents && classes.disablePointerEvents, muiFormControl.hiddenLabel && classes.hiddenLabel, variant === 'filled' && classes.filled, {
'start': classes.positionStart,
'end': classes.positionEnd
}[position], muiFormControl.margin === 'dense' && classes.marginDense),
ref: ref
}, other), typeof children === 'string' && !disableTypography ? /*#__PURE__*/React.createElement(Typography, {
color: "textSecondary"
}, children) : children));
});
process.env.NODE_ENV !== "production" ? InputAdornment.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component, normally an `IconButton` or string.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a HTML element or a component.
*/
component: PropTypes.elementType,
/**
* Disable pointer events on the root.
* This allows for the content of the adornment to focus the input on click.
* @default false
*/
disablePointerEvents: PropTypes.bool,
/**
* If children is a string then disable wrapping in a Typography component.
* @default false
*/
disableTypography: PropTypes.bool,
/**
* The position this adornment should appear relative to the `Input`.
*/
position: PropTypes.oneOf(['end', 'start']),
/**
* The variant to use.
* Note: If you are using the `TextField` component or the `FormControl` component
* you do not have to set this manually.
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
export default withStyles(styles, {
name: 'MuiInputAdornment'
})(InputAdornment); | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.9/esm/InputAdornment/InputAdornment.js | JavaScript | mit | 4,948 |
/*jshint eqeqeq:false */
/*global jQuery, define */
(function( factory ) {
"use strict";
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./grid.base"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
"use strict";
//module begin
$.extend($.jgrid,{
focusableElementsList : [
'>a[href]',
'>button:not([disabled])',
'>area[href]',
'>input:not([disabled])',
'>select:not([disabled])',
'>textarea:not([disabled])',
'>iframe',
'>object',
'>embed',
'>*[tabindex]',
'>*[contenteditable]'
]
});
$.jgrid.extend({
ariaBodyGrid : function ( p ) {
var o = $.extend({
onEnterCell : null
}, p || {});
return this.each(function (){
var $t = this,
getstyle = $.jgrid.getMethod("getStyleUI"),
highlight = getstyle($t.p.styleUI+'.common','highlight', true);
// basic functions
function isValidCell(row, col) {
return (
!isNaN(row) &&
!isNaN(col) &&
row >= 0 &&
col >= 0 &&
$t.rows.length &&
row < $t.rows.length &&
col < $t.p.colModel.length
);
};
function getNextCell( dirX, dirY) {
var row = $t.p.iRow + dirY; // set the default one when initialize grid
var col = $t.p.iCol + dirX; // set the default .................
var rowCount = $t.rows.length;
var isLeftRight = dirX !== 0;
if (!rowCount) {
return false;
}
var colCount = $t.p.colModel.length;
if (isLeftRight) {
if (col < 0 && row >= 2) {
col = colCount - 1;
row--;
}
if (col >= colCount) {
col = 0;
row++;
}
}
if (!isLeftRight) {
if (row < 1) {
col--;
row = rowCount - 1;
if ($t.rows[row] && col >= 0 && !$t.rows[row].cells[col]) {
// Sometimes the bottom row is not completely filled in. In this case,
// jump to the next filled in cell.
row--;
}
}
else if (row >= rowCount || !$t.rows[row].cells[col]) {
row = 1;
col++;
}
}
if (isValidCell(row, col)) {
return {
row: row,
col: col
};
} else if (isValidCell($t.p.iRow, $t.p.iCol)) {
return {
row: $t.p.iRow,
col: $t.p.iCol
};
} else {
return false;
}
}
function getNextVisibleCell(dirX, dirY) {
var nextCell = getNextCell( dirX, dirY);
if (!nextCell) {
return false;
}
while ( $($t.rows[nextCell.row].cells[nextCell.col]).is(":hidden") ) {
$t.p.iRow = nextCell.row;
$t.p.iCol = nextCell.col;
nextCell = getNextCell(dirX, dirY);
if ($t.p.iRow === nextCell.row && $t.p.iCol === nextCell.col) {
// There are no more cells to try if getNextCell returns the current cell
return false;
}
}
if( dirY !== 0 ) {
$($t).jqGrid('setSelection', $t.rows[nextCell.row].id, false, null, false);
}
return nextCell;
}
function movePage ( dir ) {
var curpage = $t.p.page, last =$t.p.lastpage;
curpage = curpage + dir;
if( curpage <= 0) {
curpage = 1;
}
if( curpage > last ) {
curpage = last;
}
if( $t.p.page === curpage ) {
return;
}
$t.p.page = curpage;
$t.grid.populate();
}
var focusableElementsSelector = $.jgrid.focusableElementsList.join();
function hasFocusableChild( el) {
return $(focusableElementsSelector, el)[0];
}
$($t).removeAttr("tabindex");
$($t).on('jqGridAfterGridComplete.setAriaGrid', function( e ) {
//var grid = e.target;
$("tbody:first>tr:not(.jqgfirstrow)>td:not(:hidden, :has("+focusableElementsSelector+"))", $t).attr("tabindex", -1);
$("tbody:first>tr:not(.jqgfirstrow)", $t).removeAttr("tabindex");
if($t.p.iRow !== undefined && $t.p.iCol !== undefined) {
if($t.rows[$t.p.iRow]) {
$($t.rows[$t.p.iRow].cells[$t.p.iCol])
.attr('tabindex', 0)
.focus( function() { $(this).addClass(highlight);})
.blur( function () { $(this).removeClass(highlight);});
}
}
});
$t.p.iRow = 1;
$t.p.iCol = $.jgrid.getFirstVisibleCol( $t );
var focusRow=0, focusCol=0; // set the dafualt one
$($t).on('keydown', function(e) {
if($t.p.navigationDisabled && $t.p.navigationDisabled === true) {
return;
}
var key = e.which || e.keyCode, nextCell;
switch(key) {
case (38) :
nextCell = getNextVisibleCell(0, -1);
focusRow = nextCell.row;
focusCol = nextCell.col;
e.preventDefault();
break;
case (40) :
nextCell = getNextVisibleCell(0, 1);
focusRow = nextCell.row;
focusCol = nextCell.col;
e.preventDefault();
break;
case (37) :
nextCell = getNextVisibleCell(-1, 0);
focusRow = nextCell.row;
focusCol = nextCell.col;
e.preventDefault();
break;
case (39) :
nextCell = getNextVisibleCell(1, 0);
focusRow = nextCell.row;
focusCol = nextCell.col;
e.preventDefault();
break;
case 36 : // HOME
if(e.ctrlKey) {
focusRow = 1;
} else {
focusRow = $t.p.iRow;
}
focusCol = 0;
e.preventDefault();
break;
case 35 : //END
if(e.ctrlKey) {
focusRow = $t.rows.length - 1;
} else {
focusRow = $t.p.iRow;
}
focusCol = $t.p.colModel.length - 1;
e.preventDefault();
break;
case 33 : // PAGEUP
movePage( -1 );
focusCol = $t.p.iCol;
focusRow = $t.p.iRow;
e.preventDefault();
break;
case 34 : // PAGEDOWN
movePage( 1 );
focusCol = $t.p.iCol;
focusRow = $t.p.iRow;
if(focusRow > $t.rows.length-1) {
focusRow = $t.rows.length-1;
$t.p.iRow = $t.rows.length-1;
}
e.preventDefault();
break;
case 13 : //Enter
if( $.isFunction( o.onEnterCell )) {
o.onEnterCell.call( $t, $t.rows[$t.p.iRow].id ,$t.p.iRow, $t.p.iCol, e);
e.preventDefault();
}
return;
default:
return;
}
$($t).jqGrid("focusBodyCell", focusRow, focusCol, getstyle, highlight);
});
$($t).on('jqGridBeforeSelectRow.ariaGridClick',function() {
return false;
});
$($t).on('jqGridCellSelect.ariaGridClick', function(el1, id, status,tdhtml, e) {
var el = e.target;
if($t.p.iRow > 0 && $t.p.iCol >=0) {
$($t.rows[$t.p.iRow].cells[$t.p.iCol]).attr("tabindex", -1);
}
if($(el).is("td") || $(el).is("th")) {
$t.p.iCol = el.cellIndex;
} else {
return;
}
var row = $(el).closest("tr.jqgrow");
$t.p.iRow = row[0].rowIndex;
$(el).attr("tabindex", 0)
.addClass(highlight)
.focus()
.blur(function(){$(this).removeClass(highlight);});
});
});
},
focusBodyCell : function(focusRow, focusCol, _s, _h) {
return this.each(function (){
var $t = this,
getstyle = !_s ? $.jgrid.getMethod("getStyleUI") : _s,
highlight = !_h ? getstyle($t.p.styleUI+'.common','highlight', true) : _h,
focusableElementsSelector = $.jgrid.focusableElementsList.join(),
fe;
function hasFocusableChild( el) {
return $(focusableElementsSelector, el)[0];
}
if(focusRow !== undefined && focusCol !== undefined) {
if (!isNaN($t.p.iRow) && !isNaN($t.p.iCol) && $t.p.iCol >= 0) {
fe = hasFocusableChild($t.rows[$t.p.iRow].cells[$t.p.iCol]);
if( fe ) {
$(fe).attr('tabindex', -1);
} else {
$($t.rows[$t.p.iRow].cells[$t.p.iCol]).attr('tabindex', -1);
}
}
} else {
focusRow = $t.p.iRow;
focusCol = $t.p.iCol;
}
focusRow = parseInt(focusRow, 10);
focusCol = parseInt(focusCol, 10);
if(focusRow > 0 && focusCol >=0) {
fe = hasFocusableChild($t.rows[focusRow].cells[focusCol]);
if( fe ) {
$(fe).attr('tabindex', 0)
.addClass(highlight)
.focus()
.blur( function () { $(this).removeClass(highlight); });
} else {
$($t.rows[focusRow].cells[focusCol])
.attr('tabindex', 0)
.addClass(highlight)
.focus()
.blur(function () { $(this).removeClass(highlight); });
}
$t.p.iRow = focusRow;
$t.p.iCol = focusCol;
}
});
},
resetAriaBody : function() {
return this.each(function(){
var $t = this;
$($t).attr("tabindex","0")
.off('keydown')
.off('jqGridBeforeSelectRow.ariaGridClick')
.off('jqGridCellSelect.ariaGridClick')
.off('jqGridAfterGridComplete.setAriaGrid');
var focusableElementsSelector = $.jgrid.focusableElementsList.join();
$("tbody:first>tr:not(.jqgfirstrow)>td:not(:hidden, :has("+focusableElementsSelector+"))", $t).removeAttr("tabindex").off("focus");
$("tbody:first>tr:not(.jqgfirstrow)", $t).attr("tabindex", -1);
});
},
ariaHeaderGrid : function() {
return this.each(function (){
var $t = this,
getstyle = $.jgrid.getMethod("getStyleUI"),
highlight = getstyle($t.p.styleUI+'.common','highlight', true),
htable = $(".ui-jqgrid-hbox>table:first", "#gbox_"+$t.p.id);
$('tr.ui-jqgrid-labels', htable).on("keydown", function(e) {
var currindex = $t.p.selHeadInd;
var key = e.which || e.keyCode;
var len = $t.grid.headers.length;
switch (key) {
case 37: // left
if(currindex-1 >= 0) {
currindex--;
while( $($t.grid.headers[currindex].el).is(':hidden') && currindex-1 >= 0) {
currindex--;
if(currindex < 0) {
break;
}
}
if(currindex >= 0) {
$($t.grid.headers[currindex].el).focus();
$($t.grid.headers[$t.p.selHeadInd].el).attr("tabindex", "-1");
$t.p.selHeadInd = currindex;
e.preventDefault();
}
}
break;
case 39: // right
if(currindex+1 < len) {
currindex++;
while( $($t.grid.headers[currindex].el).is(':hidden') && currindex+1 <len) {
currindex++;
if( currindex > len-1) {
break;
}
}
if( currindex < len) {
$($t.grid.headers[currindex].el).focus();
$($t.grid.headers[$t.p.selHeadInd].el).attr("tabindex", "-1");
$t.p.selHeadInd = currindex;
e.preventDefault();
}
}
break;
case 13: // enter
$("div:first",$t.grid.headers[currindex].el).trigger('click');
e.preventDefault();
break;
default:
return;
}
});
$('tr.ui-jqgrid-labels>th:not(:hidden)', htable).attr("tabindex", -1).focus(function(){
$(this).addClass(highlight).attr("tabindex", "0");
}).blur(function(){
$(this).removeClass(highlight);
});
$t.p.selHeadInd = $.jgrid.getFirstVisibleCol( $t );
$($t.grid.headers[$t.p.selHeadInd].el).attr("tabindex","0");
});
},
focusHeaderCell : function( index) {
return this.each( function(){
var $t = this;
if(index === undefined) {
index = $t.p.selHeadInd;
}
if(index >= 0 && index < $t.p.colModel.length) {
$($t.grid.headers[$t.p.selHeadInd].el).attr("tabindex", "-1");
$($t.grid.headers[index].el).focus();
$t.p.selHeadInd = index;
}
});
},
resetAriaHeader : function() {
return this.each(function(){
var htable = $(".ui-jqgrid-hbox>table:first", "#gbox_" + this.p.id);
$('tr.ui-jqgrid-labels', htable).off("keydown");
$('tr.ui-jqgrid-labels>th:not(:hidden)', htable).removeAttr("tabindex").off("focus blur");
});
},
ariaPagerGrid : function () {
return this.each( function(){
var $t = this,
getstyle = $.jgrid.getMethod("getStyleUI"),
highlight = getstyle($t.p.styleUI+'.common','highlight', true),
disabled = "."+getstyle($t.p.styleUI+'.common','disabled', true),
cels = $(".ui-pg-button",$t.p.pager),
len = cels.length;
cels.attr("tabindex","-1").focus(function(){
$(this).addClass(highlight);
}).blur(function(){
$(this).removeClass(highlight);
});
$t.p.navIndex = 0;
setTimeout( function() { // make another decision here
var navIndex = cels.not(disabled).first().attr("tabindex", "0");
$t.p.navIndex = navIndex[0].cellIndex ? navIndex[0].cellIndex-1 : 0;
}, 100);
$("table.ui-pager-table tr:first", $t.p.pager).on("keydown", function(e) {
var key = e.which || e.keyCode;
var indexa = $t.p.navIndex;//currindex;
switch (key) {
case 37: // left
if(indexa-1 >= 0) {
indexa--;
while( $(cels[indexa]).is(disabled) && indexa-1 >= 0) {
indexa--;
if(indexa < 0) {
break;
}
}
if(indexa >= 0) {
$(cels[$t.p.navIndex]).attr("tabindex","-1");
$(cels[indexa]).attr("tabindex","0").focus();
$t.p.navIndex = indexa;
}
e.preventDefault();
}
break;
case 39: // right
if(indexa+1 < len) {
indexa++;
while( $(cels[indexa]).is(disabled) && indexa+1 < len + 1) {
indexa++;
if( indexa > len-1) {
break;
}
}
if( indexa < len) {
$(cels[$t.p.navIndex]).attr("tabindex","-1");
$(cels[indexa]).attr("tabindex","0").focus();
$t.p.navIndex = indexa;
}
e.preventDefault();
}
break;
case 13: // enter
$(cels[indexa]).trigger('click');
e.preventDefault();
break;
default:
return;
}
});
});
},
focusPagerCell : function( index) {
return this.each( function(){
var $t = this,
cels = $(".ui-pg-button",$t.p.pager),
len = cels.length;
if(index === undefined) {
index = $t.p.navIndex;
}
if(index >= 0 && index < len) {
$(cels[$t.p.navIndex]).attr("tabindex","-1");
$(cels[index]).attr("tabindex","0").focus();
$t.p.navIndex = index;
}
});
},
resetAriaPager : function() {
return this.each(function(){
$(".ui-pg-button",this.p.pager).removeAttr("tabindex").off("focus");;
$("table.ui-pager-table tr:first", this.p.pager).off("keydown");
});
},
setAriaGrid : function ( p ) {
var o = $.extend({
header : true,
body : true,
pager : true,
onEnterCell : null
}, p || {});
return this.each(function(){
if( o.header ) {
$(this).jqGrid('ariaHeaderGrid');
}
if( o.body ) {
$(this).jqGrid('ariaBodyGrid', {onEnterCell : o.onEnterCell});
}
if( o.pager ) {
$(this).jqGrid('ariaPagerGrid');
}
});
},
resetAriaGrid : function( p ) {
var o = $.extend({
header : true,
body : true,
pager : true
}, p || {});
return this.each(function(){
var $t = this;
if( o.body ) {
$($t).jqGrid('resetAriaBody');
}
if( o.header ) {
$($t).jqGrid('resetAriaHeader');
}
if( o.pager ) {
$($t).jqGrid('resetAriaPager');
}
});
}
// end aria grid
});
//module end
}));
| cdnjs/cdnjs | ajax/libs/jqgrid/5.5.3/js/grid.aria.js | JavaScript | mit | 14,585 |
'use strict';
var re = /\|/;
module.exports = function() {
if( typeof re.split !== 'function' ) return false;
return re.split( 'bar|foo' )[1] === 'foo';
};
| tracyapps/chad | node_modules/grunt-contrib-imagemin/node_modules/imagemin/node_modules/imagemin-pngquant/node_modules/pngquant-bin/node_modules/bin-build/node_modules/decompress/node_modules/vinyl-fs/node_modules/glob-stream/node_modules/unique-stream/node_modules/es6-set/node_modules/es5-ext/reg-exp/#/split/is-implemented.js | JavaScript | gpl-2.0 | 160 |
/**
* Ext.ux.grid.GridFilters v0.2.7
**/
Ext.namespace("Ext.ux.grid");
Ext.ux.grid.GridFilters = function(config){
this.filters = new Ext.util.MixedCollection();
this.filters.getKey = function(o){return o ? o.dataIndex : null};
for(var i=0, len=config.filters.length; i<len; i++)
this.addFilter(config.filters[i]);
this.deferredUpdate = new Ext.util.DelayedTask(this.reload, this);
delete config.filters;
Ext.apply(this, config);
};
Ext.extend(Ext.ux.grid.GridFilters, Ext.util.Observable, {
/**
* @cfg {Integer} updateBuffer
* Number of milisecond to defer store updates since the last filter change.
*/
updateBuffer: 500,
/**
* @cfg {String} paramPrefix
* The url parameter prefix for the filters.
*/
paramPrefix: 'filter',
/**
* @cfg {String} fitlerCls
* The css class to be applied to column headers that active filters. Defaults to 'ux-filterd-column'
*/
filterCls: 'ux-filtered-column',
/**
* @cfg {Boolean} local
* True to use Ext.data.Store filter functions instead of server side filtering.
*/
local: false,
/**
* @cfg {Boolean} autoReload
* True to automagicly reload the datasource when a filter change happens.
*/
autoReload: true,
/**
* @cfg {String} stateId
* Name of the Ext.data.Store value to be used to store state information.
*/
stateId: undefined,
/**
* @cfg {Boolean} showMenu
* True to show the filter menus
*/
showMenu: true,
menuFilterText: 'Filters',
init: function(grid){
if(grid instanceof Ext.grid.GridPanel){
this.grid = grid;
this.store = this.grid.getStore();
if(this.local){
this.store.on('load', function(store){
store.filterBy(this.getRecordFilter());
}, this);
} else {
this.store.on('beforeload', this.onBeforeLoad, this);
}
this.grid.filters = this;
this.grid.addEvents({"filterupdate": true});
grid.on("render", this.onRender, this);
grid.on("beforestaterestore", this.applyState, this);
grid.on("beforestatesave", this.saveState, this);
} else if(grid instanceof Ext.PagingToolbar){
this.toolbar = grid;
}
},
/** private **/
applyState: function(grid, state){
this.suspendStateStore = true;
this.clearFilters();
if(state.filters)
for(var key in state.filters){
var filter = this.filters.get(key);
if(filter){
filter.setValue(state.filters[key]);
filter.setActive(true);
}
}
this.deferredUpdate.cancel();
if(this.local)
this.reload();
this.suspendStateStore = false;
},
/** private **/
saveState: function(grid, state){
var filters = {};
this.filters.each(function(filter){
if(filter.active)
filters[filter.dataIndex] = filter.getValue();
});
return state.filters = filters;
},
/** private **/
onRender: function(){
var hmenu;
if(this.showMenu){
hmenu = this.grid.getView().hmenu;
this.sep = hmenu.addSeparator();
this.menu = hmenu.add(new Ext.menu.CheckItem({
text: this.menuFilterText,
menu: new Ext.menu.Menu()
}));
this.menu.on('checkchange', this.onCheckChange, this);
this.menu.on('beforecheckchange', this.onBeforeCheck, this);
hmenu.on('beforeshow', this.onMenu, this);
}
this.grid.getView().on("refresh", this.onRefresh, this);
this.updateColumnHeadings(this.grid.getView());
},
/** private **/
onMenu: function(filterMenu){
var filter = this.getMenuFilter();
if(filter){
this.menu.menu = filter.menu;
this.menu.setChecked(filter.active, false);
}
this.menu.setVisible(filter !== undefined);
this.sep.setVisible(filter !== undefined);
},
/** private **/
onCheckChange: function(item, value){
this.getMenuFilter().setActive(value);
},
/** private **/
onBeforeCheck: function(check, value){
return !value || this.getMenuFilter().isActivatable();
},
/** private **/
onStateChange: function(event, filter){
if(event == "serialize") return;
if(filter == this.getMenuFilter())
this.menu.setChecked(filter.active, false);
if(this.autoReload || this.local)
this.deferredUpdate.delay(this.updateBuffer);
var view = this.grid.getView();
this.updateColumnHeadings(view);
this.grid.saveState();
this.grid.fireEvent('filterupdate', this, filter);
},
/** private **/
onBeforeLoad: function(store, options){
options.params = options.params || {};
this.cleanParams(options.params);
var params = this.buildQuery(this.getFilterData());
Ext.apply(options.params, params);
},
/** private **/
onRefresh: function(view){
this.updateColumnHeadings(view);
},
/** private **/
getMenuFilter: function(){
var view = this.grid.getView();
if(!view || view.hdCtxIndex === undefined)
return null;
return this.filters.get(
view.cm.config[view.hdCtxIndex].dataIndex);
},
/** private **/
updateColumnHeadings: function(view){
if(!view || !view.mainHd) return;
var hds = view.mainHd.select('td').removeClass(this.filterCls);
for(var i=0, len=view.cm.config.length; i<len; i++){
var filter = this.getFilter(view.cm.config[i].dataIndex);
if(filter && filter.active)
hds.item(i).addClass(this.filterCls);
}
},
/** private **/
reload: function(){
if(this.local){
this.grid.store.clearFilter(true);
this.grid.store.filterBy(this.getRecordFilter());
} else {
this.deferredUpdate.cancel();
var store = this.grid.store;
if(this.toolbar){
var start = this.toolbar.paramNames.start;
if(store.lastOptions && store.lastOptions.params && store.lastOptions.params[start])
store.lastOptions.params[start] = 0;
}
store.reload();
}
},
/**
* Method factory that generates a record validator for the filters active at the time
* of invokation.
*
* @private
*/
getRecordFilter: function(){
var f = [];
this.filters.each(function(filter){
if(filter.active) f.push(filter);
});
var len = f.length;
return function(record){
for(var i=0; i<len; i++)
if(!f[i].validateRecord(record))
return false;
return true;
};
},
/**
* Adds a filter to the collection.
*
* @param {Object/Ext.ux.grid.filter.Filter} config A filter configuration or a filter object.
*
* @return {Ext.ux.grid.filter.Filter} The existing or newly created filter object.
*/
addFilter: function(config){
var filter = config.menu ? config :
new (this.getFilterClass(config.type))(config);
this.filters.add(filter);
Ext.util.Observable.capture(filter, this.onStateChange, this);
return filter;
},
/**
* Returns a filter for the given dataIndex, if on exists.
*
* @param {String} dataIndex The dataIndex of the desired filter object.
*
* @return {Ext.ux.grid.filter.Filter}
*/
getFilter: function(dataIndex){
return this.filters.get(dataIndex);
},
/**
* Turns all filters off. This does not clear the configuration information.
*/
clearFilters: function(){
this.filters.each(function(filter){
filter.setActive(false);
});
},
/** private **/
getFilterData: function(){
var filters = [],
fields = this.grid.getStore().fields;
this.filters.each(function(f){
if(f.active){
var d = [].concat(f.serialize());
for(var i=0, len=d.length; i<len; i++)
filters.push({
field: f.dataIndex,
data: d[i]
});
}
});
return filters;
},
/**
* Function to take structured filter data and 'flatten' it into query parameteres. The default function
* will produce a query string of the form:
* filters[0][field]=dataIndex&filters[0][data][param1]=param&filters[0][data][param2]=param...
*
* @param {Array} filters A collection of objects representing active filters and their configuration.
* Each element will take the form of {field: dataIndex, data: filterConf}. dataIndex is not assured
* to be unique as any one filter may be a composite of more basic filters for the same dataIndex.
*
* @return {Object} Query keys and values
*/
buildQuery: function(filters){
var p = {};
for(var i=0, len=filters.length; i<len; i++){
var f = filters[i];
var root = [this.paramPrefix, '[', i, ']'].join('');
p[root + '[field]'] = f.field;
var dataPrefix = root + '[data]';
for(var key in f.data)
p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
}
return p;
},
/**
* Removes filter related query parameters from the provided object.
*
* @param {Object} p Query parameters that may contain filter related fields.
*/
cleanParams: function(p){
var regex = new RegExp("^" + this.paramPrefix + "\[[0-9]+\]");
for(var key in p)
if(regex.test(key))
delete p[key];
},
/**
* Function for locating filter classes, overwrite this with your favorite
* loader to provide dynamic filter loading.
*
* @param {String} type The type of filter to load.
*
* @return {Class}
*/
getFilterClass: function(type){
return Ext.ux.grid.filter[type.substr(0, 1).toUpperCase() + type.substr(1) + 'Filter'];
}
}); | bundocba/unitedworld | components/com_ose_cpu/extjs/grid/GridFilters.js | JavaScript | gpl-2.0 | 9,021 |
var ManageIssueTypePage = new Ext.Panel({
id : 'ezTrack_Manage_IssueType_Page',
layout : 'fit',
autoScroll : true,
items: [
ManageIssueTypePanelEvent
]
});
| chusiang/ezScrum_Ubuntu | WebContent/javascript/ezTrackPage/ManageIssueType.js | JavaScript | gpl-2.0 | 177 |
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
cc._txtLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadTxt(realUrl, cb);
}
};
cc.loader.register(["txt", "xml", "vsh", "fsh", "atlas"], cc._txtLoader);
cc._jsonLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadJson(realUrl, cb);
}
};
cc.loader.register(["json", "ExportJson"], cc._jsonLoader);
cc._jsLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadJs(realUrl, cb);
}
};
cc.loader.register(["js"], cc._jsLoader);
cc._imgLoader = {
load : function(realUrl, url, res, cb){
cc.loader.cache[url] = cc.loader.loadImg(realUrl, function(err, img){
if(err)
return cb(err);
cc.textureCache.handleLoadedTexture(url);
cb(null, img);
});
}
};
cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico", "tiff", "webp"], cc._imgLoader);
cc._serverImgLoader = {
load : function(realUrl, url, res, cb){
cc.loader.cache[url] = cc.loader.loadImg(res.src, function(err, img){
if(err)
return cb(err);
cc.textureCache.handleLoadedTexture(url);
cb(null, img);
});
}
};
cc.loader.register(["serverImg"], cc._serverImgLoader);
cc._plistLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadTxt(realUrl, function(err, txt){
if(err)
return cb(err);
cb(null, cc.plistParser.parse(txt));
});
}
};
cc.loader.register(["plist"], cc._plistLoader);
cc._fontLoader = {
TYPE : {
".eot" : "embedded-opentype",
".ttf" : "truetype",
".ttc" : "truetype",
".woff" : "woff",
".svg" : "svg"
},
_loadFont : function(name, srcs, type){
var doc = document, path = cc.path, TYPE = this.TYPE, fontStyle = document.createElement("style");
fontStyle.type = "text/css";
doc.body.appendChild(fontStyle);
var fontStr = "";
if(isNaN(name - 0))
fontStr += "@font-face { font-family:" + name + "; src:";
else
fontStr += "@font-face { font-family:'" + name + "'; src:";
if(srcs instanceof Array){
for(var i = 0, li = srcs.length; i < li; i++){
var src = srcs[i];
type = path.extname(src).toLowerCase();
fontStr += "url('" + srcs[i] + "') format('" + TYPE[type] + "')";
fontStr += (i === li - 1) ? ";" : ",";
}
}else{
type = type.toLowerCase();
fontStr += "url('" + srcs + "') format('" + TYPE[type] + "');";
}
fontStyle.textContent += fontStr + "}";
//<div style="font-family: PressStart;">.</div>
var preloadDiv = document.createElement("div");
var _divStyle = preloadDiv.style;
_divStyle.fontFamily = name;
preloadDiv.innerHTML = ".";
_divStyle.position = "absolute";
_divStyle.left = "-100px";
_divStyle.top = "-100px";
doc.body.appendChild(preloadDiv);
},
load : function(realUrl, url, res, cb){
var self = this;
var type = res.type, name = res.name, srcs = res.srcs;
if(cc.isString(res)){
type = cc.path.extname(res);
name = cc.path.basename(res, type);
self._loadFont(name, res, type);
}else{
self._loadFont(name, srcs);
}
if(document.fonts){
document.fonts.load("1em " + name).then(function(){
cb(null, true);
}, function(err){
cb(err);
});
}else{
cb(null, true);
}
}
};
cc.loader.register(["font", "eot", "ttf", "woff", "svg", "ttc"], cc._fontLoader);
cc._binaryLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadBinary(realUrl, cb);
}
};
cc._csbLoader = {
load: function(realUrl, url, res, cb){
cc.loader.loadCsb(realUrl, cb);
}
};
cc.loader.register(["csb"], cc._csbLoader);
| zero5566/super_mahjong | mahjong/test/super_mahjong/frameworks/cocos2d-html5/cocos2d/core/platform/CCLoaders.js | JavaScript | gpl-2.0 | 5,370 |
/*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.data.QueryReadStore"]){
dojo._hasResource["dojox.data.QueryReadStore"]=true;
dojo.provide("dojox.data.QueryReadStore");
dojo.require("dojo.string");
dojo.require("dojo.data.util.sorter");
dojo.declare("dojox.data.QueryReadStore",null,{url:"",requestMethod:"get",_className:"dojox.data.QueryReadStore",_items:[],_lastServerQuery:null,_numRows:-1,lastRequestHash:null,doClientPaging:false,doClientSorting:false,_itemsByIdentity:null,_identifier:null,_features:{"dojo.data.api.Read":true,"dojo.data.api.Identity":true},_labelAttr:"label",constructor:function(_1){
dojo.mixin(this,_1);
},getValue:function(_2,_3,_4){
this._assertIsItem(_2);
if(!dojo.isString(_3)){
throw new Error(this._className+".getValue(): Invalid attribute, string expected!");
}
if(!this.hasAttribute(_2,_3)){
if(_4){
return _4;
}
}
return _2.i[_3];
},getValues:function(_5,_6){
this._assertIsItem(_5);
var _7=[];
if(this.hasAttribute(_5,_6)){
_7.push(_5.i[_6]);
}
return _7;
},getAttributes:function(_8){
this._assertIsItem(_8);
var _9=[];
for(var i in _8.i){
_9.push(i);
}
return _9;
},hasAttribute:function(_b,_c){
return this.isItem(_b)&&typeof _b.i[_c]!="undefined";
},containsValue:function(_d,_e,_f){
var _10=this.getValues(_d,_e);
var len=_10.length;
for(var i=0;i<len;i++){
if(_10[i]==_f){
return true;
}
}
return false;
},isItem:function(_13){
if(_13){
return typeof _13.r!="undefined"&&_13.r==this;
}
return false;
},isItemLoaded:function(_14){
return this.isItem(_14);
},loadItem:function(_15){
if(this.isItemLoaded(_15.item)){
return;
}
},fetch:function(_16){
_16=_16||{};
if(!_16.store){
_16.store=this;
}
var _17=this;
var _18=function(_19,_1a){
if(_1a.onError){
var _1b=_1a.scope||dojo.global;
_1a.onError.call(_1b,_19,_1a);
}
};
var _1c=function(_1d,_1e,_1f){
var _20=_1e.abort||null;
var _21=false;
var _22=_1e.start?_1e.start:0;
if(_17.doClientPaging==false){
_22=0;
}
var _23=_1e.count?(_22+_1e.count):_1d.length;
_1e.abort=function(){
_21=true;
if(_20){
_20.call(_1e);
}
};
var _24=_1e.scope||dojo.global;
if(!_1e.store){
_1e.store=_17;
}
if(_1e.onBegin){
_1e.onBegin.call(_24,_1f,_1e);
}
if(_1e.sort&&_17.doClientSorting){
_1d.sort(dojo.data.util.sorter.createSortFunction(_1e.sort,_17));
}
if(_1e.onItem){
for(var i=_22;(i<_1d.length)&&(i<_23);++i){
var _26=_1d[i];
if(!_21){
_1e.onItem.call(_24,_26,_1e);
}
}
}
if(_1e.onComplete&&!_21){
var _27=null;
if(!_1e.onItem){
_27=_1d.slice(_22,_23);
}
_1e.onComplete.call(_24,_27,_1e);
}
};
this._fetchItems(_16,_1c,_18);
return _16;
},getFeatures:function(){
return this._features;
},close:function(_28){
},getLabel:function(_29){
if(this._labelAttr&&this.isItem(_29)){
return this.getValue(_29,this._labelAttr);
}
return undefined;
},getLabelAttributes:function(_2a){
if(this._labelAttr){
return [this._labelAttr];
}
return null;
},_xhrFetchHandler:function(_2b,_2c,_2d,_2e){
_2b=this._filterResponse(_2b);
if(_2b.label){
this._labelAttr=_2b.label;
}
var _2f=_2b.numRows||-1;
this._items=[];
dojo.forEach(_2b.items,function(e){
this._items.push({i:e,r:this});
},this);
var _31=_2b.identifier;
this._itemsByIdentity={};
if(_31){
this._identifier=_31;
var i;
for(i=0;i<this._items.length;++i){
var _33=this._items[i].i;
var _34=_33[_31];
if(!this._itemsByIdentity[_34]){
this._itemsByIdentity[_34]=_33;
}else{
throw new Error(this._className+": The json data as specified by: ["+this.url+"] is malformed. Items within the list have identifier: ["+_31+"]. Value collided: ["+_34+"]");
}
}
}else{
this._identifier=Number;
for(i=0;i<this._items.length;++i){
this._items[i].n=i;
}
}
_2f=this._numRows=(_2f===-1)?this._items.length:_2f;
_2d(this._items,_2c,_2f);
this._numRows=_2f;
},_fetchItems:function(_35,_36,_37){
var _38=_35.serverQuery||_35.query||{};
if(!this.doClientPaging){
_38.start=_35.start||0;
if(_35.count){
_38.count=_35.count;
}
}
if(!this.doClientSorting){
if(_35.sort){
var _39=_35.sort[0];
if(_39&&_39.attribute){
var _3a=_39.attribute;
if(_39.descending){
_3a="-"+_3a;
}
_38.sort=_3a;
}
}
}
if(this.doClientPaging&&this._lastServerQuery!==null&&dojo.toJson(_38)==dojo.toJson(this._lastServerQuery)){
this._numRows=(this._numRows===-1)?this._items.length:this._numRows;
_36(this._items,_35,this._numRows);
}else{
var _3b=this.requestMethod.toLowerCase()=="post"?dojo.xhrPost:dojo.xhrGet;
var _3c=_3b({url:this.url,handleAs:"json-comment-optional",content:_38});
_3c.addCallback(dojo.hitch(this,function(_3d){
this._xhrFetchHandler(_3d,_35,_36,_37);
}));
_3c.addErrback(function(_3e){
_37(_3e,_35);
});
this.lastRequestHash=new Date().getTime()+"-"+String(Math.random()).substring(2);
this._lastServerQuery=dojo.mixin({},_38);
}
},_filterResponse:function(_3f){
return _3f;
},_assertIsItem:function(_40){
if(!this.isItem(_40)){
throw new Error(this._className+": Invalid item argument.");
}
},_assertIsAttribute:function(_41){
if(typeof _41!=="string"){
throw new Error(this._className+": Invalid attribute argument ('"+_41+"').");
}
},fetchItemByIdentity:function(_42){
if(this._itemsByIdentity){
var _43=this._itemsByIdentity[_42.identity];
if(!(_43===undefined)){
if(_42.onItem){
var _44=_42.scope?_42.scope:dojo.global;
_42.onItem.call(_44,{i:_43,r:this});
}
return;
}
}
var _45=function(_46,_47){
var _48=_42.scope?_42.scope:dojo.global;
if(_42.onError){
_42.onError.call(_48,_46);
}
};
var _49=function(_4a,_4b){
var _4c=_42.scope?_42.scope:dojo.global;
try{
var _4d=null;
if(_4a&&_4a.length==1){
_4d=_4a[0];
}
if(_42.onItem){
_42.onItem.call(_4c,_4d);
}
}
catch(error){
if(_42.onError){
_42.onError.call(_4c,error);
}
}
};
var _4e={serverQuery:{id:_42.identity}};
this._fetchItems(_4e,_49,_45);
},getIdentity:function(_4f){
var _50=null;
if(this._identifier===Number){
_50=_4f.n;
}else{
_50=_4f.i[this._identifier];
}
return _50;
},getIdentityAttributes:function(_51){
return [this._identifier];
}});
}
| sguazt/dcsj-sharegrid-portal | web/resources/scripts/dojo/dojox/data/QueryReadStore.js | JavaScript | gpl-3.0 | 5,990 |
/** @jsx jsx */
import React from "react";
import PropTypes from "prop-types";
import moment from "moment";
import { css, jsx } from "@emotion/core";
import { withTheme } from "emotion-theming";
import constants from "../../../constants";
import { RegularText } from "../../atoms/typography";
const DatetimeFieldResponse = props => {
return (
<RegularText
css={css`
margin: 8px 0 16px 0;
`}
>
{moment(props.value).format(
props.fieldConfig.display_format ||
constants.DEFAULT_DATE_DISPLAY_FORMAT,
)}
</RegularText>
);
};
DatetimeFieldResponse.propTypes = {
fieldConfig: PropTypes.object.isRequired,
value: PropTypes.string.isRequired,
theme: PropTypes.object.isRequired,
};
export default withTheme(DatetimeFieldResponse);
| smartercleanup/duwamish | src/base/static/components/form-fields/types/datetime-field-response.js | JavaScript | gpl-3.0 | 800 |
/* Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo
* -----------------------------------------------------------
*
* The DHTML Calendar, version 1.0 "It is happening again"
*
* Details and latest version at:
* www.dynarch.com/projects/calendar
*
* This script is developed by Dynarch.com. Visit us at www.dynarch.com.
*
* This script is distributed under the GNU Lesser General Public License.
* Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
*/
// $Id: calendar.js,v 1.1 2010/05/21 13:49:25 a.zahner Exp $
/** The Calendar object constructor. */
Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {
// member variables
this.activeDiv = null;
this.currentDateEl = null;
this.getDateStatus = null;
this.getDateToolTip = null;
this.getDateText = null;
this.timeout = null;
this.onSelected = onSelected || null;
this.onClose = onClose || null;
this.dragging = false;
this.hidden = false;
this.minYear = 1970;
this.maxYear = 2050;
this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
this.isPopup = true;
this.weekNumbers = true;
this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
this.showsOtherMonths = false;
this.dateStr = dateStr;
this.ar_days = null;
this.showsTime = false;
this.time24 = true;
this.yearStep = 2;
this.hiliteToday = true;
this.multiple = null;
// HTML elements
this.table = null;
this.element = null;
this.tbody = null;
this.firstdayname = null;
// Combo boxes
this.monthsCombo = null;
this.yearsCombo = null;
this.hilitedMonth = null;
this.activeMonth = null;
this.hilitedYear = null;
this.activeYear = null;
// Information
this.dateClicked = false;
// one-time initializations
if (typeof Calendar._SDN == "undefined") {
// table of short day names
if (typeof Calendar._SDN_len == "undefined")
Calendar._SDN_len = 3;
var ar = new Array();
for (var i = 8; i > 0;) {
ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
}
Calendar._SDN = ar;
// table of short month names
if (typeof Calendar._SMN_len == "undefined")
Calendar._SMN_len = 3;
ar = new Array();
for (var i = 12; i > 0;) {
ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
}
Calendar._SMN = ar;
}
};
// ** constants
/// "static", needed for event handlers.
Calendar._C = null;
/// detect a special case of "web browser"
Calendar.is_ie = ( /msie/i.test(navigator.userAgent) &&
!/opera/i.test(navigator.userAgent) );
Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );
/// detect Opera browser
Calendar.is_opera = /opera/i.test(navigator.userAgent);
/// detect KHTML-based browsers
Calendar.is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);
// BEGIN: UTILITY FUNCTIONS; beware that these might be moved into a separate
// library, at some point.
Calendar.getAbsolutePos = function(el) {
var SL = 0, ST = 0;
var is_div = /^div$/i.test(el.tagName);
if (is_div && el.scrollLeft)
SL = el.scrollLeft;
if (is_div && el.scrollTop)
ST = el.scrollTop;
var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
if (el.offsetParent) {
var tmp = this.getAbsolutePos(el.offsetParent);
r.x += tmp.x;
r.y += tmp.y;
}
return r;
};
Calendar.isRelated = function (el, evt) {
var related = evt.relatedTarget;
if (!related) {
var type = evt.type;
if (type == "mouseover") {
related = evt.fromElement;
} else if (type == "mouseout") {
related = evt.toElement;
}
}
while (related) {
if (related == el) {
return true;
}
related = related.parentNode;
}
return false;
};
Calendar.removeClass = function(el, className) {
if (!(el && el.className)) {
return;
}
var cls = el.className.split(" ");
var ar = new Array();
for (var i = cls.length; i > 0;) {
if (cls[--i] != className) {
ar[ar.length] = cls[i];
}
}
el.className = ar.join(" ");
};
Calendar.addClass = function(el, className) {
Calendar.removeClass(el, className);
el.className += " " + className;
};
// FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
Calendar.getElement = function(ev) {
var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
while (f.nodeType != 1 || /^div$/i.test(f.tagName))
f = f.parentNode;
return f;
};
Calendar.getTargetElement = function(ev) {
var f = Calendar.is_ie ? window.event.srcElement : ev.target;
while (f.nodeType != 1)
f = f.parentNode;
return f;
};
Calendar.stopEvent = function(ev) {
ev || (ev = window.event);
if (Calendar.is_ie) {
ev.cancelBubble = true;
ev.returnValue = false;
} else {
ev.preventDefault();
ev.stopPropagation();
}
return false;
};
Calendar.addEvent = function(el, evname, func) {
if (el.attachEvent) { // IE
el.attachEvent("on" + evname, func);
} else if (el.addEventListener) { // Gecko / W3C
el.addEventListener(evname, func, true);
} else {
el["on" + evname] = func;
}
};
Calendar.removeEvent = function(el, evname, func) {
if (el.detachEvent) { // IE
el.detachEvent("on" + evname, func);
} else if (el.removeEventListener) { // Gecko / W3C
el.removeEventListener(evname, func, true);
} else {
el["on" + evname] = null;
}
};
Calendar.createElement = function(type, parent) {
var el = null;
if (document.createElementNS) {
// use the XHTML namespace; IE won't normally get here unless
// _they_ "fix" the DOM2 implementation.
el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
} else {
el = document.createElement(type);
}
if (typeof parent != "undefined") {
parent.appendChild(el);
}
return el;
};
// END: UTILITY FUNCTIONS
// BEGIN: CALENDAR STATIC FUNCTIONS
/** Internal -- adds a set of events to make some element behave like a button. */
Calendar._add_evs = function(el) {
with (Calendar) {
addEvent(el, "mouseover", dayMouseOver);
addEvent(el, "mousedown", dayMouseDown);
addEvent(el, "mouseout", dayMouseOut);
addEvent(el, "click", function(event){
event=event||window.event;
Calendar.stopEvent(event);
});
if (is_ie) {
addEvent(el, "dblclick", dayMouseDblClick);
el.setAttribute("unselectable", true);
}
}
};
Calendar.findMonth = function(el) {
if (typeof el.month != "undefined") {
return el;
} else if (typeof el.parentNode.month != "undefined") {
return el.parentNode;
}
return null;
};
Calendar.findYear = function(el) {
if (typeof el.year != "undefined") {
return el;
} else if (typeof el.parentNode.year != "undefined") {
return el.parentNode;
}
return null;
};
Calendar.showMonthsCombo = function () {
var cal = Calendar._C;
if (!cal) {
return false;
}
var cal = cal;
var cd = cal.activeDiv;
var mc = cal.monthsCombo;
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
if (cal.activeMonth) {
Calendar.removeClass(cal.activeMonth, "active");
}
var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
Calendar.addClass(mon, "active");
cal.activeMonth = mon;
var s = mc.style;
s.display = "block";
if (cd.navtype < 0)
s.left = cd.offsetLeft + "px";
else {
var mcw = mc.offsetWidth;
if (typeof mcw == "undefined")
// Konqueror brain-dead techniques
mcw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
};
Calendar.showYearsCombo = function (fwd) {
var cal = Calendar._C;
if (!cal) {
return false;
}
var cal = cal;
var cd = cal.activeDiv;
var yc = cal.yearsCombo;
if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
if (cal.activeYear) {
Calendar.removeClass(cal.activeYear, "active");
}
cal.activeYear = null;
var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
var yr = yc.firstChild;
var show = false;
for (var i = 12; i > 0; --i) {
if (Y >= cal.minYear && Y <= cal.maxYear) {
yr.innerHTML = Y;
yr.year = Y;
yr.style.display = "block";
show = true;
} else {
yr.style.display = "none";
}
yr = yr.nextSibling;
Y += fwd ? cal.yearStep : -cal.yearStep;
}
if (show) {
var s = yc.style;
s.display = "block";
if (cd.navtype < 0)
s.left = cd.offsetLeft + "px";
else {
var ycw = yc.offsetWidth;
if (typeof ycw == "undefined")
// Konqueror brain-dead techniques
ycw = 50;
s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
}
s.top = (cd.offsetTop + cd.offsetHeight) + "px";
}
};
// event handlers
Calendar.tableMouseUp = function(ev) {
var cal = Calendar._C;
if (!cal) {
return false;
}
if (cal.timeout) {
clearTimeout(cal.timeout);
}
var el = cal.activeDiv;
if (!el) {
return false;
}
var target = Calendar.getTargetElement(ev);
ev || (ev = window.event);
Calendar.removeClass(el, "active");
if (target == el || target.parentNode == el) {
Calendar.cellClick(el, ev);
}
var mon = Calendar.findMonth(target);
var date = null;
if (mon) {
date = new Date(cal.date);
if (mon.month != date.getMonth()) {
date.setMonth(mon.month);
cal.setDate(date);
cal.dateClicked = false;
cal.callHandler();
}
} else {
var year = Calendar.findYear(target);
if (year) {
date = new Date(cal.date);
if (year.year != date.getFullYear()) {
date.setFullYear(year.year);
cal.setDate(date);
cal.dateClicked = false;
cal.callHandler();
}
}
}
with (Calendar) {
removeEvent(document, "mouseup", tableMouseUp);
removeEvent(document, "mouseover", tableMouseOver);
removeEvent(document, "mousemove", tableMouseOver);
cal._hideCombos();
_C = null;
return stopEvent(ev);
}
};
Calendar.tableMouseOver = function (ev) {
var cal = Calendar._C;
if (!cal) {
return;
}
var el = cal.activeDiv;
var target = Calendar.getTargetElement(ev);
if (target == el || target.parentNode == el) {
Calendar.addClass(el, "hilite active");
Calendar.addClass(el.parentNode, "rowhilite");
} else {
if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
Calendar.removeClass(el, "active");
Calendar.removeClass(el, "hilite");
Calendar.removeClass(el.parentNode, "rowhilite");
}
ev || (ev = window.event);
if (el.navtype == 50 && target != el) {
var pos = Calendar.getAbsolutePos(el);
var w = el.offsetWidth;
var x = ev.clientX;
var dx;
var decrease = true;
if (x > pos.x + w) {
dx = x - pos.x - w;
decrease = false;
} else
dx = pos.x - x;
if (dx < 0) dx = 0;
var range = el._range;
var current = el._current;
var count = Math.floor(dx / 10) % range.length;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
while (count-- > 0)
if (decrease) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
}
var mon = Calendar.findMonth(target);
if (mon) {
if (mon.month != cal.date.getMonth()) {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
Calendar.addClass(mon, "hilite");
cal.hilitedMonth = mon;
} else if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
} else {
if (cal.hilitedMonth) {
Calendar.removeClass(cal.hilitedMonth, "hilite");
}
var year = Calendar.findYear(target);
if (year) {
if (year.year != cal.date.getFullYear()) {
if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
Calendar.addClass(year, "hilite");
cal.hilitedYear = year;
} else if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
} else if (cal.hilitedYear) {
Calendar.removeClass(cal.hilitedYear, "hilite");
}
}
return Calendar.stopEvent(ev);
};
Calendar.tableMouseDown = function (ev) {
if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
return Calendar.stopEvent(ev);
}
};
Calendar.calDragIt = function (ev) {
var cal = Calendar._C;
if (!(cal && cal.dragging)) {
return false;
}
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posX = ev.pageX;
posY = ev.pageY;
}
cal.hideShowCovered();
var st = cal.element.style;
st.left = (posX - cal.xOffs) + "px";
st.top = (posY - cal.yOffs) + "px";
return Calendar.stopEvent(ev);
};
Calendar.calDragEnd = function (ev) {
var cal = Calendar._C;
if (!cal) {
return false;
}
cal.dragging = false;
with (Calendar) {
removeEvent(document, "mousemove", calDragIt);
removeEvent(document, "mouseup", calDragEnd);
tableMouseUp(ev);
}
cal.hideShowCovered();
};
Calendar.dayMouseDown = function(ev) {
var el = Calendar.getElement(ev);
if (el.disabled) {
return false;
}
var cal = el.calendar;
cal.activeDiv = el;
Calendar._C = cal;
if (el.navtype != 300) with (Calendar) {
if (el.navtype == 50) {
el._current = el.innerHTML;
addEvent(document, "mousemove", tableMouseOver);
} else
addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
addClass(el, "hilite active");
addEvent(document, "mouseup", tableMouseUp);
} else if (cal.isPopup) {
cal._dragStart(ev);
}
if (el.navtype == -1 || el.navtype == 1) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
} else if (el.navtype == -2 || el.navtype == 2) {
if (cal.timeout) clearTimeout(cal.timeout);
cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
} else {
cal.timeout = null;
}
return Calendar.stopEvent(ev);
};
Calendar.dayMouseDblClick = function(ev) {
Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
if (Calendar.is_ie) {
document.selection.empty();
}
};
Calendar.dayMouseOver = function(ev) {
var el = Calendar.getElement(ev);
if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
return false;
}
if (el.ttip) {
if (el.ttip.substr(0, 1) == "_") {
el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
}
el.calendar.tooltips.innerHTML = el.ttip;
}
if (el.navtype != 300) {
Calendar.addClass(el, "hilite");
if (el.caldate) {
Calendar.addClass(el.parentNode, "rowhilite");
}
}
return Calendar.stopEvent(ev);
};
Calendar.dayMouseOut = function(ev) {
with (Calendar) {
var el = getElement(ev);
if (isRelated(el, ev) || _C || el.disabled)
return false;
removeClass(el, "hilite");
if (el.caldate)
removeClass(el.parentNode, "rowhilite");
if (el.calendar)
el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
return stopEvent(ev);
}
};
/**
* A generic "click" handler :) handles all types of buttons defined in this
* calendar.
*/
Calendar.cellClick = function(el, ev) {
var cal = el.calendar;
var closing = false;
var newdate = false;
var date = null;
if (typeof el.navtype == "undefined") {
if (cal.currentDateEl) {
Calendar.removeClass(cal.currentDateEl, "selected");
Calendar.addClass(el, "selected");
closing = (cal.currentDateEl == el);
if (!closing) {
cal.currentDateEl = el;
}
}
cal.date.setDateOnly(el.caldate);
date = cal.date;
var other_month = !(cal.dateClicked = !el.otherMonth);
if (!other_month && !cal.currentDateEl)
cal._toggleMultipleDate(new Date(date));
else
newdate = !el.disabled;
// a date was clicked
if (other_month)
cal._init(cal.firstDayOfWeek, date);
} else {
if (el.navtype == 200) {
Calendar.removeClass(el, "hilite");
cal.callCloseHandler();
return;
}
date = new Date(cal.date);
if (el.navtype == 0)
date.setDateOnly(new Date()); // TODAY
// unless "today" was clicked, we assume no date was clicked so
// the selected handler will know not to close the calenar when
// in single-click mode.
// cal.dateClicked = (el.navtype == 0);
cal.dateClicked = false;
var year = date.getFullYear();
var mon = date.getMonth();
function setMonth(m) {
var day = date.getDate();
var max = date.getMonthDays(m);
if (day > max) {
date.setDate(max);
}
date.setMonth(m);
};
switch (el.navtype) {
case 400:
Calendar.removeClass(el, "hilite");
var text = Calendar._TT["ABOUT"];
if (typeof text != "undefined") {
text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
} else {
// FIXME: this should be removed as soon as lang files get updated!
text = "Help and about box text is not translated into this language.\n" +
"If you know this language and you feel generous please update\n" +
"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution ;-)\n\n" +
"Thank you!\n" +
"http://dynarch.com/mishoo/calendar.epl\n";
}
alert(text);
return;
case -2:
if (year > cal.minYear) {
date.setFullYear(year - 1);
}
break;
case -1:
if (mon > 0) {
setMonth(mon - 1);
} else if (year-- > cal.minYear) {
date.setFullYear(year);
setMonth(11);
}
break;
case 1:
if (mon < 11) {
setMonth(mon + 1);
} else if (year < cal.maxYear) {
date.setFullYear(year + 1);
setMonth(0);
}
break;
case 2:
if (year < cal.maxYear) {
date.setFullYear(year + 1);
}
break;
case 100:
cal.setFirstDayOfWeek(el.fdow);
return;
case 50:
var range = el._range;
var current = el.innerHTML;
for (var i = range.length; --i >= 0;)
if (range[i] == current)
break;
if (ev && ev.shiftKey) {
if (--i < 0)
i = range.length - 1;
} else if ( ++i >= range.length )
i = 0;
var newval = range[i];
el.innerHTML = newval;
cal.onUpdateTime();
return;
case 0:
// TODAY will bring us here
if ((typeof cal.getDateStatus == "function") &&
cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
return false;
}
break;
}
if (!date.equalsTo(cal.date)) {
cal.setDate(date);
newdate = true;
} else if (el.navtype == 0)
newdate = closing = true;
}
if (newdate) {
ev && cal.callHandler();
}
if (closing) {
Calendar.removeClass(el, "hilite");
ev && cal.callCloseHandler();
}
};
// END: CALENDAR STATIC FUNCTIONS
// BEGIN: CALENDAR OBJECT FUNCTIONS
/**
* This function creates the calendar inside the given parent. If _par is
* null than it creates a popup calendar inside the BODY element. If _par is
* an element, be it BODY, then it creates a non-popup calendar (still
* hidden). Some properties need to be set before calling this function.
*/
Calendar.prototype.create = function (_par) {
var parent = null;
if (! _par) {
// default parent is the document body, in which case we create
// a popup calendar.
parent = document.getElementsByTagName("body")[0];
this.isPopup = true;
} else {
parent = _par;
this.isPopup = false;
}
this.date = this.dateStr ? new Date(this.dateStr) : new Date();
var table = Calendar.createElement("table");
this.table = table;
table.cellSpacing = 0;
table.cellPadding = 0;
table.calendar = this;
Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);
var div = Calendar.createElement("div");
this.element = div;
div.className = "calendar";
if (this.isPopup) {
div.style.position = "absolute";
div.style.display = "none";
}
div.appendChild(table);
var thead = Calendar.createElement("thead", table);
var cell = null;
var row = null;
var cal = this;
var hh = function (text, cs, navtype) {
cell = Calendar.createElement("td", row);
cell.colSpan = cs;
cell.className = "button";
if (navtype != 0 && Math.abs(navtype) <= 2)
cell.className += " nav";
Calendar._add_evs(cell);
cell.calendar = cal;
cell.navtype = navtype;
cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
return cell;
};
row = Calendar.createElement("tr", thead);
var title_length = 6;
(this.isPopup) && --title_length;
(this.weekNumbers) && ++title_length;
hh("?", 1, 400).ttip = Calendar._TT["INFO"];
this.title = hh("", title_length, 300);
this.title.className = "title";
if (this.isPopup) {
this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
this.title.style.cursor = "move";
hh("×", 1, 200).ttip = Calendar._TT["CLOSE"];
}
row = Calendar.createElement("tr", thead);
row.className = "headrow";
this._nav_py = hh("«", 1, -2);
this._nav_py.ttip = Calendar._TT["PREV_YEAR"];
this._nav_pm = hh("‹", 1, -1);
this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];
this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
this._nav_now.ttip = Calendar._TT["GO_TODAY"];
this._nav_nm = hh("›", 1, 1);
this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];
this._nav_ny = hh("»", 1, 2);
this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
// day names
row = Calendar.createElement("tr", thead);
row.className = "daynames";
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
cell.className = "name wn";
cell.innerHTML = Calendar._TT["WK"];
}
for (var i = 7; i > 0; --i) {
cell = Calendar.createElement("td", row);
if (!i) {
cell.navtype = 100;
cell.calendar = this;
Calendar._add_evs(cell);
}
}
this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
this._displayWeekdays();
var tbody = Calendar.createElement("tbody", table);
this.tbody = tbody;
for (i = 6; i > 0; --i) {
row = Calendar.createElement("tr", tbody);
if (this.weekNumbers) {
cell = Calendar.createElement("td", row);
}
for (var j = 7; j > 0; --j) {
cell = Calendar.createElement("td", row);
cell.calendar = this;
Calendar._add_evs(cell);
}
}
if (this.showsTime) {
row = Calendar.createElement("tr", tbody);
row.className = "time";
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
cell.innerHTML = Calendar._TT["TIME"] || " ";
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = this.weekNumbers ? 4 : 3;
(function(){
function makeTimePart(className, init, range_start, range_end) {
var part = Calendar.createElement("span", cell);
part.className = className;
part.innerHTML = init;
part.calendar = cal;
part.ttip = Calendar._TT["TIME_PART"];
part.navtype = 50;
part._range = [];
if (typeof range_start != "number")
part._range = range_start;
else {
for (var i = range_start; i <= range_end; ++i) {
var txt;
if (i < 10 && range_end >= 10) txt = '0' + i;
else txt = '' + i;
part._range[part._range.length] = txt;
}
}
Calendar._add_evs(part);
return part;
};
var hrs = cal.date.getHours();
var mins = cal.date.getMinutes();
var t12 = !cal.time24;
var pm = (hrs > 12);
if (t12 && pm) hrs -= 12;
var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
var span = Calendar.createElement("span", cell);
span.innerHTML = ":";
span.className = "colon";
var M = makeTimePart("minute", mins, 0, 59);
var AP = null;
cell = Calendar.createElement("td", row);
cell.className = "time";
cell.colSpan = 2;
if (t12)
AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
else
cell.innerHTML = " ";
cal.onSetTime = function() {
var pm, hrs = this.date.getHours(),
mins = this.date.getMinutes();
if (t12) {
pm = (hrs >= 12);
if (pm) hrs -= 12;
if (hrs == 0) hrs = 12;
AP.innerHTML = pm ? "pm" : "am";
}
H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
};
cal.onUpdateTime = function() {
var date = this.date;
var h = parseInt(H.innerHTML, 10);
if (t12) {
if (/pm/i.test(AP.innerHTML) && h < 12)
h += 12;
else if (/am/i.test(AP.innerHTML) && h == 12)
h = 0;
}
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
date.setHours(h);
date.setMinutes(parseInt(M.innerHTML, 10));
date.setFullYear(y);
date.setMonth(m);
date.setDate(d);
this.dateClicked = false;
this.callHandler();
};
})();
} else {
this.onSetTime = this.onUpdateTime = function() {};
}
var tfoot = Calendar.createElement("tfoot", table);
row = Calendar.createElement("tr", tfoot);
row.className = "footrow";
cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
cell.className = "ttip";
if (this.isPopup) {
cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
cell.style.cursor = "move";
}
this.tooltips = cell;
div = Calendar.createElement("div", this.element);
this.monthsCombo = div;
div.className = "combo";
for (i = 0; i < Calendar._MN.length; ++i) {
var mn = Calendar.createElement("div");
mn.className = Calendar.is_ie ? "label-IEfix" : "label";
mn.month = i;
mn.innerHTML = Calendar._SMN[i];
div.appendChild(mn);
}
div = Calendar.createElement("div", this.element);
this.yearsCombo = div;
div.className = "combo";
for (i = 12; i > 0; --i) {
var yr = Calendar.createElement("div");
yr.className = Calendar.is_ie ? "label-IEfix" : "label";
div.appendChild(yr);
}
this._init(this.firstDayOfWeek, this.date);
parent.appendChild(this.element);
};
/** keyboard navigation, only for popup calendars */
Calendar._keyEvent = function(ev) {
var cal = window._dynarch_popupCalendar;
if (!cal || cal.multiple)
return false;
(Calendar.is_ie) && (ev = window.event);
var act = (Calendar.is_ie || ev.type == "keypress"),
K = ev.keyCode;
if (ev.ctrlKey) {
switch (K) {
case 37: // KEY left
act && Calendar.cellClick(cal._nav_pm);
break;
case 38: // KEY up
act && Calendar.cellClick(cal._nav_py);
break;
case 39: // KEY right
act && Calendar.cellClick(cal._nav_nm);
break;
case 40: // KEY down
act && Calendar.cellClick(cal._nav_ny);
break;
default:
return false;
}
} else switch (K) {
case 32: // KEY space (now)
Calendar.cellClick(cal._nav_now);
break;
case 27: // KEY esc
act && cal.callCloseHandler();
break;
case 37: // KEY left
case 38: // KEY up
case 39: // KEY right
case 40: // KEY down
if (act) {
var prev, x, y, ne, el, step;
prev = K == 37 || K == 38;
step = (K == 37 || K == 39) ? 1 : 7;
function setVars() {
el = cal.currentDateEl;
var p = el.pos;
x = p & 15;
y = p >> 4;
ne = cal.ar_days[y][x];
};setVars();
function prevMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() - step);
cal.setDate(date);
};
function nextMonth() {
var date = new Date(cal.date);
date.setDate(date.getDate() + step);
cal.setDate(date);
};
while (1) {
switch (K) {
case 37: // KEY left
if (--x >= 0)
ne = cal.ar_days[y][x];
else {
x = 6;
K = 38;
continue;
}
break;
case 38: // KEY up
if (--y >= 0)
ne = cal.ar_days[y][x];
else {
prevMonth();
setVars();
}
break;
case 39: // KEY right
if (++x < 7)
ne = cal.ar_days[y][x];
else {
x = 0;
K = 40;
continue;
}
break;
case 40: // KEY down
if (++y < cal.ar_days.length)
ne = cal.ar_days[y][x];
else {
nextMonth();
setVars();
}
break;
}
break;
}
if (ne) {
if (!ne.disabled)
Calendar.cellClick(ne);
else if (prev)
prevMonth();
else
nextMonth();
}
}
break;
case 13: // KEY enter
if (act)
Calendar.cellClick(cal.currentDateEl, ev);
break;
default:
return false;
}
return Calendar.stopEvent(ev);
};
/**
* (RE)Initializes the calendar to the given date and firstDayOfWeek
*/
Calendar.prototype._init = function (firstDayOfWeek, date) {
var today = new Date(),
TY = today.getFullYear(),
TM = today.getMonth(),
TD = today.getDate();
this.table.style.visibility = "hidden";
var year = date.getFullYear();
if (year < this.minYear) {
year = this.minYear;
date.setFullYear(year);
} else if (year > this.maxYear) {
year = this.maxYear;
date.setFullYear(year);
}
this.firstDayOfWeek = firstDayOfWeek;
this.date = new Date(date);
var month = date.getMonth();
var mday = date.getDate();
var no_days = date.getMonthDays();
// calendar voodoo for computing the first day that would actually be
// displayed in the calendar, even if it's from the previous month.
// WARNING: this is magic. ;-)
date.setDate(1);
var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
if (day1 < 0)
day1 += 7;
date.setDate(-day1);
date.setDate(date.getDate() + 1);
var row = this.tbody.firstChild;
var MN = Calendar._SMN[month];
var ar_days = this.ar_days = new Array();
var weekend = Calendar._TT["WEEKEND"];
var dates = this.multiple ? (this.datesCells = {}) : null;
for (var i = 0; i < 6; ++i, row = row.nextSibling) {
var cell = row.firstChild;
if (this.weekNumbers) {
cell.className = "day wn";
cell.innerHTML = date.getWeekNumber();
cell = cell.nextSibling;
}
row.className = "daysrow";
var hasdays = false, iday, dpos = ar_days[i] = [];
for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
iday = date.getDate();
var wday = date.getDay();
cell.className = "day";
cell.pos = i << 4 | j;
dpos[j] = cell;
var current_month = (date.getMonth() == month);
if (!current_month) {
if (this.showsOtherMonths) {
cell.className += " othermonth";
cell.otherMonth = true;
} else {
cell.className = "emptycell";
cell.innerHTML = " ";
cell.disabled = true;
continue;
}
} else {
cell.otherMonth = false;
hasdays = true;
}
cell.disabled = false;
cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
if (dates)
dates[date.print("%Y%m%d")] = cell;
if (this.getDateStatus) {
var status = this.getDateStatus(date, year, month, iday);
if (this.getDateToolTip) {
var toolTip = this.getDateToolTip(date, year, month, iday);
if (toolTip)
cell.title = toolTip;
}
if (status === true) {
cell.className += " disabled";
cell.disabled = true;
} else {
if (/disabled/i.test(status))
cell.disabled = true;
cell.className += " " + status;
}
}
if (!cell.disabled) {
cell.caldate = new Date(date);
cell.ttip = "_";
if (!this.multiple && current_month
&& iday == mday && this.hiliteToday) {
cell.className += " selected";
this.currentDateEl = cell;
}
if (date.getFullYear() == TY &&
date.getMonth() == TM &&
iday == TD) {
cell.className += " today";
cell.ttip += Calendar._TT["PART_TODAY"];
}
if (weekend.indexOf(wday.toString()) != -1)
cell.className += cell.otherMonth ? " oweekend" : " weekend";
}
}
if (!(hasdays || this.showsOtherMonths))
row.className = "emptyrow";
}
this.title.innerHTML = Calendar._MN[month] + ", " + year;
this.onSetTime();
this.table.style.visibility = "visible";
this._initMultipleDates();
// PROFILE
// this.tooltips.innerHTML = "Generated in " + ((new Date()) - today) + " ms";
};
Calendar.prototype._initMultipleDates = function() {
if (this.multiple) {
for (var i in this.multiple) {
var cell = this.datesCells[i];
var d = this.multiple[i];
if (!d)
continue;
if (cell)
cell.className += " selected";
}
}
};
Calendar.prototype._toggleMultipleDate = function(date) {
if (this.multiple) {
var ds = date.print("%Y%m%d");
var cell = this.datesCells[ds];
if (cell) {
var d = this.multiple[ds];
if (!d) {
Calendar.addClass(cell, "selected");
this.multiple[ds] = date;
} else {
Calendar.removeClass(cell, "selected");
delete this.multiple[ds];
}
}
}
};
Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
this.getDateToolTip = unaryFunction;
};
/**
* Calls _init function above for going to a certain date (but only if the
* date is different than the currently selected one).
*/
Calendar.prototype.setDate = function (date) {
if (!date.equalsTo(this.date)) {
this._init(this.firstDayOfWeek, date);
}
};
/**
* Refreshes the calendar. Useful if the "disabledHandler" function is
* dynamic, meaning that the list of disabled date can change at runtime.
* Just * call this function if you think that the list of disabled dates
* should * change.
*/
Calendar.prototype.refresh = function () {
this._init(this.firstDayOfWeek, this.date);
};
/** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
this._init(firstDayOfWeek, this.date);
this._displayWeekdays();
};
/**
* Allows customization of what dates are enabled. The "unaryFunction"
* parameter must be a function object that receives the date (as a JS Date
* object) and returns a boolean value. If the returned value is true then
* the passed date will be marked as disabled.
*/
Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
this.getDateStatus = unaryFunction;
};
/** Customization of allowed year range for the calendar. */
Calendar.prototype.setRange = function (a, z) {
this.minYear = a;
this.maxYear = z;
};
/** Calls the first user handler (selectedHandler). */
Calendar.prototype.callHandler = function () {
if (this.onSelected) {
this.onSelected(this, this.date.print(this.dateFormat));
}
};
/** Calls the second user handler (closeHandler). */
Calendar.prototype.callCloseHandler = function () {
if (this.onClose) {
this.onClose(this);
}
this.hideShowCovered();
};
/** Removes the calendar object from the DOM tree and destroys it. */
Calendar.prototype.destroy = function () {
var el = this.element.parentNode;
el.removeChild(this.element);
Calendar._C = null;
window._dynarch_popupCalendar = null;
};
/**
* Moves the calendar element to a different section in the DOM tree (changes
* its parent).
*/
Calendar.prototype.reparent = function (new_parent) {
var el = this.element;
el.parentNode.removeChild(el);
new_parent.appendChild(el);
};
// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown. If the click was outside the open
// calendar this function closes it.
Calendar._checkCalendar = function(ev) {
var calendar = window._dynarch_popupCalendar;
if (!calendar) {
return false;
}
var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
for (; el != null && el != calendar.element; el = el.parentNode);
if (el == null) {
// calls closeHandler which should hide the calendar.
window._dynarch_popupCalendar.callCloseHandler();
return Calendar.stopEvent(ev);
}
};
/** Shows the calendar. */
Calendar.prototype.show = function () {
var rows = this.table.getElementsByTagName("tr");
for (var i = rows.length; i > 0;) {
var row = rows[--i];
Calendar.removeClass(row, "rowhilite");
var cells = row.getElementsByTagName("td");
for (var j = cells.length; j > 0;) {
var cell = cells[--j];
Calendar.removeClass(cell, "hilite");
Calendar.removeClass(cell, "active");
}
}
this.element.style.display = "block";
this.hidden = false;
if (this.isPopup) {
window._dynarch_popupCalendar = this;
Calendar.addEvent(document, "keydown", Calendar._keyEvent);
Calendar.addEvent(document, "keypress", Calendar._keyEvent);
Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
}
this.hideShowCovered();
};
/**
* Hides the calendar. Also removes any "hilite" from the class of any TD
* element.
*/
Calendar.prototype.hide = function () {
if (this.isPopup) {
Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
}
this.element.style.display = "none";
this.hidden = true;
this.hideShowCovered();
};
/**
* Shows the calendar at a given absolute position (beware that, depending on
* the calendar element style -- position property -- this might be relative
* to the parent's containing rectangle).
*/
Calendar.prototype.showAt = function (x, y) {
var s = this.element.style;
s.left = x + "px";
s.top = y + "px";
this.show();
};
/** Shows the calendar near a given element. */
Calendar.prototype.showAtElement = function (el, opts) {
var self = this;
var p = Calendar.getAbsolutePos(el);
if (!opts || typeof opts != "string") {
this.showAt(p.x, p.y + el.offsetHeight);
return true;
}
function fixPosition(box) {
if (box.x < 0)
box.x = 0;
if (box.y < 0)
box.y = 0;
var cp = document.createElement("div");
var s = cp.style;
s.position = "absolute";
s.right = s.bottom = s.width = s.height = "0px";
document.body.appendChild(cp);
var br = Calendar.getAbsolutePos(cp);
document.body.removeChild(cp);
if (Calendar.is_ie) {
br.y += document.body.scrollTop;
br.x += document.body.scrollLeft;
} else {
br.y += window.scrollY;
br.x += window.scrollX;
}
var tmp = box.x + box.width - br.x;
if (tmp > 0) box.x -= tmp;
tmp = box.y + box.height - br.y;
if (tmp > 0) box.y -= tmp;
};
this.element.style.display = "block";
Calendar.continuation_for_the_fucking_khtml_browser = function() {
var w = self.element.offsetWidth;
var h = self.element.offsetHeight;
self.element.style.display = "none";
var valign = opts.substr(0, 1);
var halign = "l";
if (opts.length > 1) {
halign = opts.substr(1, 1);
}
// vertical alignment
switch (valign) {
case "T": p.y -= h; break;
case "B": p.y += el.offsetHeight; break;
case "C": p.y += (el.offsetHeight - h) / 2; break;
case "t": p.y += el.offsetHeight - h; break;
case "b": break; // already there
}
// horizontal alignment
switch (halign) {
case "L": p.x -= w; break;
case "R": p.x += el.offsetWidth; break;
case "C": p.x += (el.offsetWidth - w) / 2; break;
case "l": p.x += el.offsetWidth - w; break;
case "r": break; // already there
}
p.width = w;
p.height = h + 40;
self.monthsCombo.style.display = "none";
fixPosition(p);
self.showAt(p.x, p.y);
};
if (Calendar.is_khtml)
setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
else
Calendar.continuation_for_the_fucking_khtml_browser();
};
/** Customizes the date format. */
Calendar.prototype.setDateFormat = function (str) {
this.dateFormat = str;
};
/** Customizes the tooltip date format. */
Calendar.prototype.setTtDateFormat = function (str) {
this.ttDateFormat = str;
};
/**
* Tries to identify the date represented in a string. If successful it also
* calls this.setDate which moves the calendar to the given date.
*/
Calendar.prototype.parseDate = function(str, fmt) {
if (!fmt)
fmt = this.dateFormat;
this.setDate(Date.parseDate(str, fmt));
};
Calendar.prototype.hideShowCovered = function () {
if (!Calendar.is_ie && !Calendar.is_opera)
return;
function getVisib(obj){
var value = obj.style.visibility;
if (!value) {
if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
if (!Calendar.is_khtml)
value = document.defaultView.
getComputedStyle(obj, "").getPropertyValue("visibility");
else
value = '';
} else if (obj.currentStyle) { // IE
value = obj.currentStyle.visibility;
} else
value = '';
}
return value;
};
var tags = new Array("applet", "iframe", "select");
var el = this.element;
var p = Calendar.getAbsolutePos(el);
var EX1 = p.x;
var EX2 = el.offsetWidth + EX1;
var EY1 = p.y;
var EY2 = el.offsetHeight + EY1;
for (var k = tags.length; k > 0; ) {
var ar = document.getElementsByTagName(tags[--k]);
var cc = null;
for (var i = ar.length; i > 0;) {
cc = ar[--i];
p = Calendar.getAbsolutePos(cc);
var CX1 = p.x;
var CX2 = cc.offsetWidth + CX1;
var CY1 = p.y;
var CY2 = cc.offsetHeight + CY1;
if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = cc.__msh_save_visibility;
} else {
if (!cc.__msh_save_visibility) {
cc.__msh_save_visibility = getVisib(cc);
}
cc.style.visibility = "hidden";
}
}
}
};
/** Internal function; it displays the bar with the names of the weekday. */
Calendar.prototype._displayWeekdays = function () {
var fdow = this.firstDayOfWeek;
var cell = this.firstdayname;
var weekend = Calendar._TT["WEEKEND"];
for (var i = 0; i < 7; ++i) {
cell.className = "day name";
var realday = (i + fdow) % 7;
if (i) {
cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
cell.navtype = 100;
cell.calendar = this;
cell.fdow = realday;
Calendar._add_evs(cell);
}
if (weekend.indexOf(realday.toString()) != -1) {
Calendar.addClass(cell, "weekend");
}
cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
cell = cell.nextSibling;
}
};
/** Internal function. Hides all combo boxes that might be displayed. */
Calendar.prototype._hideCombos = function () {
this.monthsCombo.style.display = "none";
this.yearsCombo.style.display = "none";
};
/** Internal function. Starts dragging the element. */
Calendar.prototype._dragStart = function (ev) {
if (this.dragging) {
return;
}
this.dragging = true;
var posX;
var posY;
if (Calendar.is_ie) {
posY = window.event.clientY + document.body.scrollTop;
posX = window.event.clientX + document.body.scrollLeft;
} else {
posY = ev.clientY + window.scrollY;
posX = ev.clientX + window.scrollX;
}
var st = this.element.style;
this.xOffs = posX - parseInt(st.left);
this.yOffs = posY - parseInt(st.top);
with (Calendar) {
addEvent(document, "mousemove", calDragIt);
addEvent(document, "mouseup", calDragEnd);
}
};
// BEGIN: DATE OBJECT PATCHES
/** Adds the number of days array to the Date object. */
Date._MD = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
/** Constants used for time computations */
Date.SECOND = 1000 /* milliseconds */;
Date.MINUTE = 60 * Date.SECOND;
Date.HOUR = 60 * Date.MINUTE;
Date.DAY = 24 * Date.HOUR;
Date.WEEK = 7 * Date.DAY;
Date.parseDate = function(str, fmt) {
var today = new Date();
var y = 0;
var m = -1;
var d = 0;
var a = str.split(/\W+/);
var b = fmt.match(/%./g);
var i = 0, j = 0;
var hr = 0;
var min = 0;
for (i = 0; i < a.length; ++i) {
if (!a[i])
continue;
switch (b[i]) {
case "%d":
case "%e":
d = parseInt(a[i], 10);
break;
case "%m":
m = parseInt(a[i], 10) - 1;
break;
case "%Y":
case "%y":
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
break;
case "%b":
case "%B":
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
}
break;
case "%H":
case "%I":
case "%k":
case "%l":
hr = parseInt(a[i], 10);
break;
case "%P":
case "%p":
if (/pm/i.test(a[i]) && hr < 12)
hr += 12;
else if (/am/i.test(a[i]) && hr >= 12)
hr -= 12;
break;
case "%M":
min = parseInt(a[i], 10);
break;
}
}
if (isNaN(y)) y = today.getFullYear();
if (isNaN(m)) m = today.getMonth();
if (isNaN(d)) d = today.getDate();
if (isNaN(hr)) hr = today.getHours();
if (isNaN(min)) min = today.getMinutes();
if (y != 0 && m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
y = 0; m = -1; d = 0;
for (i = 0; i < a.length; ++i) {
if (a[i].search(/[a-zA-Z]+/) != -1) {
var t = -1;
for (j = 0; j < 12; ++j) {
if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
}
if (t != -1) {
if (m != -1) {
d = m+1;
}
m = t;
}
} else if (parseInt(a[i], 10) <= 12 && m == -1) {
m = a[i]-1;
} else if (parseInt(a[i], 10) > 31 && y == 0) {
y = parseInt(a[i], 10);
(y < 100) && (y += (y > 29) ? 1900 : 2000);
} else if (d == 0) {
d = a[i];
}
}
if (y == 0)
y = today.getFullYear();
if (m != -1 && d != 0)
return new Date(y, m, d, hr, min, 0);
return today;
};
/** Returns the number of days in the current month */
Date.prototype.getMonthDays = function(month) {
var year = this.getFullYear();
if (typeof month == "undefined") {
month = this.getMonth();
}
if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
return 29;
} else {
return Date._MD[month];
}
};
/** Returns the number of day in the year. */
Date.prototype.getDayOfYear = function() {
var now = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var then = new Date(this.getFullYear(), 0, 0, 0, 0, 0);
var time = now - then;
return Math.floor(time / Date.DAY);
};
/** Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function() {
var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
var DoW = d.getDay();
d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
var ms = d.valueOf(); // GMT
d.setMonth(0);
d.setDate(4); // Thu in Week 1
return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};
/** Checks date and time equality */
Date.prototype.equalsTo = function(date) {
return ((this.getFullYear() == date.getFullYear()) &&
(this.getMonth() == date.getMonth()) &&
(this.getDate() == date.getDate()) &&
(this.getHours() == date.getHours()) &&
(this.getMinutes() == date.getMinutes()));
};
/** Set only the year, month, date parts (keep existing time) */
Date.prototype.setDateOnly = function(date) {
var tmp = new Date(date);
this.setDate(1);
this.setFullYear(tmp.getFullYear());
this.setMonth(tmp.getMonth());
this.setDate(tmp.getDate());
};
/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
var m = this.getMonth();
var d = this.getDate();
var y = this.getFullYear();
var wn = this.getWeekNumber();
var w = this.getDay();
var s = {};
var hr = this.getHours();
var pm = (hr >= 12);
var ir = (pm) ? (hr - 12) : hr;
var dy = this.getDayOfYear();
if (ir == 0)
ir = 12;
var min = this.getMinutes();
var sec = this.getSeconds();
s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
s["%A"] = Calendar._DN[w]; // full weekday name
s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
s["%B"] = Calendar._MN[m]; // full month name
// FIXME: %c : preferred date and time representation for the current locale
s["%C"] = 1 + Math.floor(y / 100); // the century number
s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
s["%e"] = d; // the day of the month (range 1 to 31)
// FIXME: %D : american date style: %m/%d/%y
// FIXME: %E, %F, %G, %g, %h (man strftime)
s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
s["%k"] = hr; // hour, range 0 to 23 (24h format)
s["%l"] = ir; // hour, range 1 to 12 (12h format)
s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
s["%n"] = "\n"; // a newline character
s["%p"] = pm ? "PM" : "AM";
s["%P"] = pm ? "pm" : "am";
// FIXME: %r : the time in am/pm notation %I:%M:%S %p
// FIXME: %R : the time in 24-hour notation %H:%M
s["%s"] = Math.floor(this.getTime() / 1000);
s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
s["%t"] = "\t"; // a tab character
// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
s["%u"] = w + 1; // the day of the week (range 1 to 7, 1 = MON)
s["%w"] = w; // the day of the week (range 0 to 6, 0 = SUN)
// FIXME: %x : preferred date representation for the current locale without the time
// FIXME: %X : preferred time representation for the current locale without the date
s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
s["%Y"] = y; // year with the century
s["%%"] = "%"; // a literal '%' character
var re = /%./g;
if (!Calendar.is_ie5 && !Calendar.is_khtml)
return str.replace(re, function (par) { return s[par] || par; });
var a = str.match(re);
for (var i = 0; i < a.length; i++) {
var tmp = s[a[i]];
if (tmp) {
re = new RegExp(a[i], 'g');
str = str.replace(re, tmp);
}
}
return str;
};
Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
Date.prototype.setFullYear = function(y) {
var d = new Date(this);
d.__msh_oldSetFullYear(y);
if (d.getMonth() != this.getMonth())
this.setDate(28);
this.__msh_oldSetFullYear(y);
};
// END: DATE OBJECT PATCHES
// global object that remembers the calendar
window._dynarch_popupCalendar = null;
| gallardo/alkacon-oamp | com.alkacon.opencms.v8.formgenerator/resources/system/modules/com.alkacon.opencms.v8.formgenerator/resources/grid/grid/calendar/calendar.js | JavaScript | gpl-3.0 | 49,345 |
/* Authors:
* Endi Sukma Dewata <edewata@redhat.com>
*
* Copyright (C) 2010 Red Hat
* see file 'COPYING' for use and warranty information
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
define([
'./ipa',
'./jquery',
'./phases',
'./reg',
'./rpc',
'./text',
'./details',
'./search',
'./association',
'./entity'],
function(IPA, $, phases, reg, rpc, text) {
IPA.rule_details_widget = function(spec) {
spec = spec || {};
var that = IPA.composite_widget(spec);
that.radio_name = spec.radio_name;
that.options = spec.options || [];
that.tables = spec.tables || [];
that.columns = spec.columns;
that.note = spec.note;
that.init = function() {
that.enable_radio = IPA.rule_radio_widget({
name: that.radio_name,
options: that.options,
entity: that.entity,
css_class: 'rule-enable-radio',
note: that.note
});
that.widgets.add_widget(that.enable_radio);
that.enable_radio.value_changed.attach(that.on_enable_radio_changed);
};
that.on_enable_radio_changed = function() {
var value = that.enable_radio.save();
if(value.length > 0) {
var enabled = ('' === value[0]);
for (var i=0; i<that.tables.length; i++) {
var table = that.tables[i];
var table_widget = that.widgets.get_widget(table.name);
table_widget.set_enabled(enabled);
}
}
};
that.init();
return that;
};
/**
* Rule radio widget
*
* Intended to be used especially by rule widget.
*
* @class IPA.rule_radio_widget
* @extends IPA.radio_widget
*/
IPA.rule_radio_widget = function(spec) {
spec = spec || {};
var that = IPA.radio_widget(spec);
/**
* The text from note will be displayed after radio buttons.
*/
that.note = spec.note || '';
/** @inheritDoc */
that.create = function(container) {
var param_info = IPA.get_entity_param(that.entity.name, that.name);
var title = param_info ? param_info.doc : that.name;
container.append(document.createTextNode(title + ': '));
that.widget_create(container);
that.owb_create(container);
if (that.undo) {
that.create_undo(container);
}
if (that.note) {
$('<div />', {
text: text.get(that.note),
'class': 'rule-radio-note'
}).appendTo(container);
}
};
return that;
};
IPA.rule_association_table_widget = function(spec) {
spec = spec || {};
spec.footer = spec.footer === undefined ? false : spec.footer;
var that = IPA.association_table_widget(spec);
that.external = spec.external;
that.setup_column = function(column, div, record) {
var suppress_link = false;
if (that.external) {
suppress_link = record[that.external] === 'true';
}
column.setup(div, record, suppress_link);
};
that.create_columns = function() {
if (!that.columns.length) {
that.association_table_widget_create_columns();
if (that.external) {
that.create_column({
name: that.external,
label: '@i18n:objects.sudorule.external',
entity: that.other_entity,
formatter: 'boolean',
width: '200px'
});
}
}
};
that.create_add_dialog = function() {
var entity_label = that.entity.metadata.label_singular;
var pkey = that.facet.get_pkey();
var other_entity_label = that.other_entity.metadata.label;
var title = that.add_title;
title = title.replace('${entity}', entity_label);
title = title.replace('${primary_key}', pkey);
title = title.replace('${other_entity}', other_entity_label);
var exclude = that.values;
if (that.external) {
exclude = [];
for (var i=0; i<that.values.length; i++) {
exclude.push(that.values[i][that.name]);
}
}
return IPA.rule_association_adder_dialog({
title: title,
pkey: pkey,
other_entity: that.other_entity,
attribute_member: that.attribute_member,
entity: that.entity,
external: that.external,
exclude: exclude
});
};
return that;
};
IPA.rule_association_table_field = function(spec) {
spec = spec || {};
var that = IPA.association_table_field(spec);
that.external = spec.external;
that.set_values_external = function(values, external) {
for (var i=0; i<values.length; i++) {
var record = values[i];
if (typeof record !== 'object') {
record = {};
record[that.param] = values[i];
}
record[that.external] = external;
values[i] = record;
}
};
that.load = function(data) {
that.values = that.adapter.load(data);
if (that.external) {
that.set_values_external(that.values, '');
var external_values = that.adapter.load(data, that.external, []);
that.set_values_external(external_values, 'true');
$.merge(that.values, external_values);
}
that.widget.update(that.values);
that.widget.unselect_all();
};
that.get_update_info = function() {
var update_info = IPA.update_info_builder.new_update_info();
//association_table_widget performs basic add and remove operation
//immediately. Rule association field test if its enabled and if not it
//performs delete operation.
if (!that.widget.enabled) {
var values = that.widget.save();
if (values.length > 0) { //no need to delete if has no values
var command = rpc.command({
entity: that.entity.name,
method: that.widget.remove_method,
args: that.facet.get_pkeys()
});
command.set_option(that.widget.other_entity.name, values);
update_info.append_command(command, that.priority);
}
}
return update_info;
};
return that;
};
IPA.rule_association_adder_dialog = function(spec) {
spec = spec || {};
var that = IPA.association_adder_dialog(spec);
that.external = spec.external;
that.add = function() {
var rows = that.available_table.remove_selected_rows();
that.selected_table.add_rows(rows);
if (that.external) {
var pkey_name = that.other_entity.metadata.primary_key;
var value = that.external_field.val();
if (!value) return;
var record = {};
record[pkey_name] = value;
that.selected_table.add_record(record);
that.external_field.val('');
}
};
return that;
};
phases.on('registration', function() {
var w = reg.widget;
var f = reg.field;
w.register('rule_association_table', IPA.rule_association_table_widget);
f.register('rule_association_table', IPA.rule_association_table_field);
});
return {};
});
| apophys/freeipa | install/ui/src/freeipa/rule.js | JavaScript | gpl-3.0 | 7,989 |
var search = require('./helpers/search'),
authoring = require('./helpers/pages').authoring,
monitoring = require('./helpers/monitoring');
describe('package', () => {
beforeEach(() => {
monitoring.openMonitoring();
});
it('increment package version', () => {
monitoring.actionOnItem('Edit', 3, 0);
// Add item to current package.
monitoring.actionOnItemSubmenu('Add to current', 'main', 2, 0);
// Save package
authoring.save();
// Check version number.
authoring.showVersions();
expect(element.all(by.repeater('version in versions')).count()).toBe(2);
authoring.showVersions(); // close version panel
});
it('add to current package removed', () => {
monitoring.actionOnItem('Edit', 3, 0);
monitoring.actionOnItemSubmenu('Add to current', 'main', 2, 0);
// Open menu.
var menu = monitoring.openItemMenu(2, 0);
var header = menu.element(by.partialLinkText('Add to current'));
expect(header.isPresent()).toBeFalsy();
// Close menu.
menu.element(by.css('.dropdown__menu-close')).click();
});
it('reorder group package items', () => {
monitoring.actionOnItem('Edit', 3, 0);
monitoring.actionOnItemSubmenu('Add to current', 'main', 2, 0);
monitoring.actionOnItemSubmenu('Add to current', 'story', 3, 2);
// Reorder item on package
authoring.moveToGroup('MAIN', 0, 'STORY', 0);
expect(authoring.getGroupItems('MAIN').count()).toBe(0);
expect(authoring.getGroupItems('STORY').count()).toBe(2);
});
it('create package from multiple items', () => {
monitoring.selectItem(2, 0);
monitoring.selectItem(2, 1);
monitoring.createPackageFromItems();
expect(authoring.getGroupItems('MAIN').count()).toBe(2);
});
it('create package by combining an item with open item', () => {
monitoring.openAction(2, 1);
browser.sleep(500);
monitoring.actionOnItem('Combine with current', 3, 0);
expect(authoring.getGroupItems('MAIN').count()).toBe(2);
});
it('add multiple items to package', () => {
monitoring.actionOnItem('Edit', 3, 0);
monitoring.selectItem(2, 0);
monitoring.selectItem(3, 1);
monitoring.multiActionDropdown().click();
monitoring.addToCurrentMultipleItems();
expect(authoring.getGroupItems('MAIN').count()).toBe(2);
});
it('create package from published item', () => {
expect(monitoring.getTextItem(2, 0)).toBe('item5');
monitoring.actionOnItem('Edit', 2, 0);
authoring.writeText('some text');
authoring.save();
authoring.publish();
monitoring.showSearch();
search.setListView();
search.showCustomSearch();
search.toggleSearchTabs('filters');
search.toggleByType('text');
expect(search.getTextItem(0)).toBe('item5');
search.actionOnItem('Create package', 0);
expect(authoring.getGroupItems('MAIN').count()).toBe(1);
});
xit('can preview package in a package', () => {
monitoring.actionOnItem('Edit', 3, 0);
monitoring.actionOnItemSubmenu('Add to current', 'main', 3, 1);
authoring.save();
authoring.close();
monitoring.previewAction(3, 0);
// There is no preview in preview, SD-3319
});
});
| darconny/superdesk-client-core | spec/package_spec.js | JavaScript | agpl-3.0 | 3,433 |
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'removeformat', 'ja', {
toolbar: 'フォーマット削除'
});
| phamtuanchip/mailfilter | resources/src/main/webapp/ckeditor/plugins/removeformat/lang/ja.js | JavaScript | lgpl-3.0 | 239 |
$(document).ready(function () {
$("#bSort").hide();
$("#bShare").hide();
var movieCache = new Array();
//var movieRatingCache = new Array();
var isDebugMode = false;
var webSocketAddress, imdbServletUrl, treeUrl, sortUrl, shareServletUrl, sharedDataUrl;
if (isDebugMode) {
webSocketAddress = "ws://localhost:8080/RankixSocket";
} else {
webSocketAddress = "ws://theapache64.xyz:8080/rankix/RankixSocket";
}
imdbServletUrl = "/rankix/imdbServlet";
treeUrl = "/rankix/Tree";
sortUrl = "/rankix/sortServlet";
shareServletUrl = "/rankix/shareServlet";
sharedDataUrl = "/rankix/shared/";
var sharedLink = null;
var isWorking = true;
function showProgressBar() {
$("#divProgress").css({'display': 'block'});
$("#divProgress").slideDown(2000);
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function hideProgress() {
$("#divProgress").slideUp(2000);
}
function consoleData(data) {
$("#console_data").prepend('<p>' + data + '</p>');
}
webSocket = new WebSocket(webSocketAddress);
consoleData("CONNECTING...");
$("#bRankix").removeClass("btn-primary").addClass("btn-disabled");
webSocket.onopen = function (evt) {
hideProgress();
freeApp();
consoleData("CONNECTED TO SOCKET :)");
};
//Checking if the intent is to access shared data
var params = window.location.search;
var key = getParameterByName('key');
if (key.length == 10) {
postProgress(70, "Loading shared data... ")
//Valid key
$.ajax({
url: sharedDataUrl + key,
type: "get",
success: function (response) {
hideProgress();
if (response.error) {
alert(response.message);
} else {
$("div#results").html(response.data);
}
},
error: function (xhr) {
console.log(xhr);
consoleData("Error " + xhr.data);
consoleData("Error " + xhr.data);
}
});
}
$("#bShare").click(function () {
if (sharedLink == null) {
var shareData = $("#results").html();
postProgress(70, "Sharing... This may take some time.")
$.ajax({
url: shareServletUrl,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress here
postProgress(percentComplete, "Saving result...");
}
}, false);
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
postProgress(percentComplete, "Downloading shared link...");
}
}, false);
return xhr;
},
type: "post",
data: {share_data: shareData},
success: function (response) {
console.log(response);
hideProgress();
if (response.error) {
consoleData("Error :" + response.message);
} else {
sharedLink = response.shared_data_url;
window.prompt("Shared! Press Control+C to copy the link", sharedLink);
consoleData(response.shared_data_url);
}
},
error: function (xhr) {
console.log(xhr);
}
});
} else {
window.prompt("Press Control + C to copy the shareable link.", sharedLink);
}
});
$("#bSort").click(function () {
sharedLink = null;
var resultHtml = $("#results").html();
$.ajax({
url: sortUrl,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress here
postProgress(percentComplete, "Sorting (UP)...");
}
}, false);
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
postProgress(percentComplete, "Sorting (DOWN)...");
}
}, false);
return xhr;
},
type: "post",
data: {results: resultHtml},
success: function (response) {
postProgress(100, "Finished");
hideProgress();
console.log(response);
if (!response.error) {
$("#bSort").fadeOut(1000);
$("#bShare").fadeIn(1000);
$("#results").html(response.results);
} else {
alert(response.message);
}
},
error: function (xhr) {
hideProgress();
console.log(xhr);
consoleData("Error while " + xhr.data);
}
});
});
function postProgress(perc, sentance) {
if (perc == 100) {
$("#pbProgress")
.removeClass("progress-bar-info progress-bar-striped active")
.addClass("progress-bar-success")
.attr('aria-valuenow', 100)
.css({width: "100%"})
.html("Finished (100%)");
} else if (perc == 10) {
$("#pbProgress")
.removeClass("progress-bar-success")
.addClass("progress-bar-info progress-bar-striped active")
.attr('aria-valuenow', 10)
.css({width: "10%"})
.html("Initializing...");
} else {
$("#pbProgress")
.attr('aria-valuenow', perc)
.css({width: perc + "%"})
.html(sentance);
}
}
function freezeApp() {
isWorking = true;
$("#bRankix").removeClass("btn-primary").addClass("btn-disabled");
}
function freeApp() {
isWorking = false;
$("#bRankix").addClass("btn-primary").removeClass("btn-disabled");
}
$("#bRankix").click(function () {
if (isWorking) {
consoleData("Work in progress...")
return;
}
sharedLink = null;
$("#bSort").hide();
$("#bShare").hide();
var movieCache = new Array();
//TODO: X
//var movieRatingCache = new Array();
postProgress(20, "Contacting TREE Manager...");
if (webSocket == null || webSocket.readyState != 1) {
consoleData("Reopening new socket...");
webSocket = new WebSocket(webSocketAddress);
isWorking = false;
}
var treeData = $("#taTree").val();
function showError(errorReason) {
$("div#results").prepend('<p r="0" class="text-danger"><strong>Error: </strong>' + errorReason + '</p>\n');
}
if (treeData.trim().length == 0) {
alert("Tree data can't be empty!");
} else {
showProgressBar();
freezeApp();
$.ajax({
url: treeUrl,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress here
postProgress(percentComplete, "Scanning tree ...");
}
}, false);
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
postProgress(percentComplete, "Downloading scan result...");
}
}, false);
return xhr;
},
type: "post",
data: {tree: treeData},
success: function (data) {
postProgress(100, "Tree scan completed, please wait...")
if (data.error) {
postProgress(0, "");
hideProgress();
freeApp();
showError(data.message);
consoleData(data.message);
} else {
$("#pbProgress")
.removeClass("progress-bar-success")
.addClass("progress-bar-info progress-bar-striped active");
var movieNameAndId = [];
/*{
"ignored_element_count":14,
"total_elements_found":18,
"rankixed_file_count":0,
"movie_file_count":4}*/
var totalElementsCount = data.total_elements_found;
var rankixedFileCount = data.rankixed_file_count;
var ignoredFileCount = data.ignored_element_count;
var fineFileCount = data.movie_file_count;
var date = new Date();
var startTime = date.getTime();
consoleData("---------------------------------");
consoleData("Requested at " + date.toLocaleTimeString());
consoleData("Total elements count: " + totalElementsCount);
consoleData("Rankixed file count: " + rankixedFileCount);
consoleData("Ignored file count: " + ignoredFileCount);
consoleData("Fine file count: " + fineFileCount);
if (fineFileCount == 0) {
freeApp();
showError("No fine file found!");
return;
}
$("div#results").html("");
function handleData(data) {
var movieName = movieNameAndId[data.id];
console.log(data);
function addResult(fontSize, movieName, imdbId, imdbRating) {
$("div#results").prepend('<p r="' + imdbRating + '" data-toggle="modal" data-target="#myModal" class="movieRow" id="' + imdbId + '" style="font-size:' + fontSize + 'px;">' + movieName + '<small class="text-muted"> has ' + imdbRating + '</small></p>\n');
}
if (!data.error) {
var fontSize = data.data * 5;
addResult(fontSize, movieName, data.imdb_id, data.data);
} else {
console.log('Data is ' + data.message);
var myRegexp = /^Invalid movie name (.+)$/;
var match = myRegexp.exec(data.message);
movieName = match[1];
$("div#results").prepend('<p r="0" class="text-danger"><strong>' + movieName + '</strong> has no rating</p>\n');
}
var scoreCount = $("#results p").length;
var perc = (scoreCount / movieNameAndId.length ) * 100;
postProgress(perc, parseInt(perc) + "%");
if (perc == 100) {
$("#bSort").fadeIn(1000);
$("#bShare").fadeIn(1000);
var finishTime = new Date().getTime();
consoleData("Took " + Math.round(((finishTime - startTime) / 1000)) + "s");
consoleData("---------------------------------");
freeApp();
/*
//SORTING REMOVED
$("div#results p").sort(function (a, b) {
console.log(a.id + " " + b.id);
return parseFloat(a.id) > parseFloat(b.id);
}).each(function(){
var elem = $(this);
elem.remove();
$(elem).prependTo("div#results");
});*/
}
}
data.results.forEach(function (obj) {
movieNameAndId[obj.id] = obj.name;
webSocket.send(JSON.stringify(obj));
/*
//Cacheing concept must be improved
if (obj.id in movieRatingCache) {
consoleData("Downloading from cache : " + obj.name);
handleData(movieRatingCache[obj.id]);
} else {
}*/
});
webSocket.onmessage = function (evt) {
var data = JSON.parse(evt.data);
//Adding to cache
//movieRatingCache[data.id] = data;
handleData(data);
};
webSocket.onclose = function (evt) {
consoleData("Socket closed");
freeApp();
$("div#results").prepend("<p r='0' class='text-info'>SOCKET Closed</p>\n");
};
webSocket.onerror = function (evt) {
freeApp();
$("div#results").prepend("<p r='0' class='text-danger'>" + evt.data + "</p>\n");
};
}
},
error: function () {
hideProgress();
freeApp();
showError("Network error occured, Please check your connection! ");
}
});
}
});
$('div#results').on('click', 'p.movieRow', function () {
var id = $(this).attr('id');
//Set loading
$("h4.modal-title").html("Loading...");
$("div.modal-body").hide();
$("#imgPoster").html("");
if (id in movieCache) {
consoleData("Data available in cache for " + movieCache[id].name);
showMovieDetailedDialog(movieCache[id]);
} else {
//Not available in cache so download
$.ajax({
url: imdbServletUrl,
type: "get",
data: {imdbId: id},
success: function (data) {
movieCache[id] = data;
consoleData("Movie loaded " + data.name);
showMovieDetailedDialog(data);
},
error: function (xhr) {
$("#bDismissDialog").click();
consoleData("Error occurred!");
}
});
}
function showMovieDetailedDialog(data) {
var img = $('<img />').load(function () {
$("#imgPoster").html("");
$("#imgPoster").append(img);
}).error(function () {
consoleData("Failed to load image");
}).attr('src', data.poster_url);
$("b#bRating").text(data.rating);
$("b#bGender").text(data.gender);
$("p#pPlot").text(data.plot);
$("h4.modal-title").text(data.name);
$("div.modal-body").slideDown(500);
}
});
}); | axefox/Rankix | server/web/js/code.js | JavaScript | apache-2.0 | 17,897 |
/* Copyright 2021 Mozilla Foundation
*
* 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.
*/
import { PDFPageViewBuffer } from "../../web/base_viewer.js";
describe("BaseViewer", function () {
describe("PDFPageViewBuffer", function () {
function createViewsMap(startId, endId) {
const map = new Map();
for (let id = startId; id <= endId; id++) {
map.set(id, {
id,
destroy: () => {},
});
}
return map;
}
it("handles `push` correctly", function () {
const buffer = new PDFPageViewBuffer(3);
const viewsMap = createViewsMap(1, 5),
iterator = viewsMap.values();
for (let i = 0; i < 3; i++) {
const view = iterator.next().value;
buffer.push(view);
}
// Ensure that the correct views are inserted.
expect([...buffer]).toEqual([
viewsMap.get(1),
viewsMap.get(2),
viewsMap.get(3),
]);
for (let i = 3; i < 5; i++) {
const view = iterator.next().value;
buffer.push(view);
}
// Ensure that the correct views are evicted.
expect([...buffer]).toEqual([
viewsMap.get(3),
viewsMap.get(4),
viewsMap.get(5),
]);
});
it("handles `resize` correctly", function () {
const buffer = new PDFPageViewBuffer(5);
const viewsMap = createViewsMap(1, 5),
iterator = viewsMap.values();
for (let i = 0; i < 5; i++) {
const view = iterator.next().value;
buffer.push(view);
}
// Ensure that keeping the size constant won't evict any views.
buffer.resize(5);
expect([...buffer]).toEqual([
viewsMap.get(1),
viewsMap.get(2),
viewsMap.get(3),
viewsMap.get(4),
viewsMap.get(5),
]);
// Ensure that increasing the size won't evict any views.
buffer.resize(10);
expect([...buffer]).toEqual([
viewsMap.get(1),
viewsMap.get(2),
viewsMap.get(3),
viewsMap.get(4),
viewsMap.get(5),
]);
// Ensure that decreasing the size will evict the correct views.
buffer.resize(3);
expect([...buffer]).toEqual([
viewsMap.get(3),
viewsMap.get(4),
viewsMap.get(5),
]);
});
it("handles `resize` correctly, with `idsToKeep` provided", function () {
const buffer = new PDFPageViewBuffer(5);
const viewsMap = createViewsMap(1, 5),
iterator = viewsMap.values();
for (let i = 0; i < 5; i++) {
const view = iterator.next().value;
buffer.push(view);
}
// Ensure that keeping the size constant won't evict any views,
// while re-ordering them correctly.
buffer.resize(5, new Set([1, 2]));
expect([...buffer]).toEqual([
viewsMap.get(3),
viewsMap.get(4),
viewsMap.get(5),
viewsMap.get(1),
viewsMap.get(2),
]);
// Ensure that increasing the size won't evict any views,
// while re-ordering them correctly.
buffer.resize(10, new Set([3, 4, 5]));
expect([...buffer]).toEqual([
viewsMap.get(1),
viewsMap.get(2),
viewsMap.get(3),
viewsMap.get(4),
viewsMap.get(5),
]);
// Ensure that decreasing the size will evict the correct views,
// while re-ordering the remaining ones correctly.
buffer.resize(3, new Set([1, 2, 5]));
expect([...buffer]).toEqual([
viewsMap.get(1),
viewsMap.get(2),
viewsMap.get(5),
]);
});
it("handles `has` correctly", function () {
const buffer = new PDFPageViewBuffer(3);
const viewsMap = createViewsMap(1, 2),
iterator = viewsMap.values();
for (let i = 0; i < 1; i++) {
const view = iterator.next().value;
buffer.push(view);
}
expect(buffer.has(viewsMap.get(1))).toEqual(true);
expect(buffer.has(viewsMap.get(2))).toEqual(false);
});
});
});
| mozilla/pdf.js | test/unit/base_viewer_spec.js | JavaScript | apache-2.0 | 4,511 |
dojo.provide("dijit.form.HorizontalRule");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.declare("dijit.form.HorizontalRule", [dijit._Widget, dijit._Templated],
{
// summary:
// Hash marks for `dijit.form.HorizontalSlider`
templateString: '<div class="dijitRuleContainer dijitRuleContainerH"></div>',
// count: Integer
// Number of hash marks to generate
count: 3,
// container: String
// For HorizontalSlider, this is either "topDecoration" or "bottomDecoration",
// and indicates whether this rule goes above or below the slider.
container: "containerNode",
// ruleStyle: String
// CSS style to apply to individual hash marks
ruleStyle: "",
_positionPrefix: '<div class="dijitRuleMark dijitRuleMarkH" style="left:',
_positionSuffix: '%;',
_suffix: '"></div>',
_genHTML: function(pos, ndx){
return this._positionPrefix + pos + this._positionSuffix + this.ruleStyle + this._suffix;
},
// _isHorizontal: [protected extension] Boolean
// VerticalRule will override this...
_isHorizontal: true,
postCreate: function(){
var innerHTML;
if(this.count==1){
innerHTML = this._genHTML(50, 0);
}else{
var i;
var interval = 100 / (this.count-1);
if(!this._isHorizontal || this.isLeftToRight()){
innerHTML = this._genHTML(0, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(interval*i, i);
}
innerHTML += this._genHTML(100, this.count-1);
}else{
innerHTML = this._genHTML(100, 0);
for(i=1; i < this.count-1; i++){
innerHTML += this._genHTML(100-interval*i, i);
}
innerHTML += this._genHTML(0, this.count-1);
}
}
this.domNode.innerHTML = innerHTML;
}
});
| feklee/rotogame | source/dojo-release-1.3.0-src/dijit/form/HorizontalRule.js | JavaScript | apache-2.0 | 1,692 |
/* */
"format cjs";
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [comparer] Used to determine whether the objects are equal.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
| cfraz89/moonrock-js-starter | jspm_packages/npm/rx@2.5.3/src/core/linq/observable/groupby.js | JavaScript | apache-2.0 | 1,147 |
/* */
"format cjs";
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
| cfraz89/moonrock-js-starter | jspm_packages/npm/rx@2.5.3/src/core/linq/observable/_observabletimertimespan.js | JavaScript | apache-2.0 | 299 |
function CreateUiSlider(args) {
var instanceSlider = Titanium.UI.createSlider({
height:"auto",
width:"auto",
//top:100,
min:0, //Minimum value for the slider (needed for Android)
max:10 //Maximum value for the slider (needed for Android)
});
if(args.min){
instanceSlider.min = args.min;
}
if(args.max){
instanceSlider.max = args.max;
}
return instanceSlider;
};
exports.CreateUiSlider = CreateUiSlider; | andi2/03_main | Resources/ui/components/uiSlider.js | JavaScript | apache-2.0 | 540 |
import {buildUrl} from '#ads/google/a4a/shared/url-builder';
import {dict} from '#core/types/object';
import {Services} from '#service';
/**
* A fake ad network integration that is mainly used for testing
* and demo purposes. This implementation gets stripped out in compiled
* production code.
* @implements {./ad-network-config.AdNetworkConfigDef}
* @visibleForTesting
*/
export class PingNetworkConfig {
/**
* @param {!Element} autoAmpAdsElement
*/
constructor(autoAmpAdsElement) {
this.autoAmpAdsElement_ = autoAmpAdsElement;
}
/** @override */
isEnabled() {
return true;
}
/** @override */
isResponsiveEnabled() {
return true;
}
/** @override */
getConfigUrl() {
return buildUrl(
'//lh3.googleusercontent.com/' +
'pSECrJ82R7-AqeBCOEPGPM9iG9OEIQ_QXcbubWIOdkY=w400-h300-no-n',
{},
4096
);
}
/** @override */
getAttributes() {
return dict({
'type': '_ping_',
});
}
/** @override */
getDefaultAdConstraints() {
const viewportHeight = Services.viewportForDoc(
this.autoAmpAdsElement_
).getSize().height;
return {
initialMinSpacing: viewportHeight,
subsequentMinSpacing: [
{adCount: 3, spacing: viewportHeight * 2},
{adCount: 6, spacing: viewportHeight * 3},
],
maxAdCount: 8,
};
}
/** @override */
getSizing() {
return {};
}
}
| jpettitt/amphtml | extensions/amp-auto-ads/0.1/ping-network-config.js | JavaScript | apache-2.0 | 1,416 |
// Generated by CoffeeScript 1.9.3
(function() {
var CONNECTION_STRING_NAMED_INSTANCE, CONNECTION_STRING_PORT, DECLARATIONS, EMPTY_BUFFER, ISOLATION_LEVEL, Pool, TYPES, UDT, castParameter, createColumns, declare, isolationLevelDeclaration, msnodesql, ref, util, valueCorrection,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
Pool = require('generic-pool').Pool;
msnodesql = require('msnodesql');
util = require('util');
ref = require('./datatypes'), TYPES = ref.TYPES, declare = ref.declare;
UDT = require('./udt').PARSERS;
ISOLATION_LEVEL = require('./isolationlevel');
DECLARATIONS = require('./datatypes').DECLARATIONS;
EMPTY_BUFFER = new Buffer(0);
CONNECTION_STRING_PORT = 'Driver={SQL Server Native Client 11.0};Server={#{server},#{port}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};';
CONNECTION_STRING_NAMED_INSTANCE = 'Driver={SQL Server Native Client 11.0};Server={#{server}\\#{instance}};Database={#{database}};Uid={#{user}};Pwd={#{password}};Trusted_Connection={#{trusted}};';
/*
@ignore
*/
castParameter = function(value, type) {
if (value == null) {
if (type === TYPES.Binary || type === TYPES.VarBinary || type === TYPES.Image) {
return EMPTY_BUFFER;
}
return null;
}
switch (type) {
case TYPES.VarChar:
case TYPES.NVarChar:
case TYPES.Char:
case TYPES.NChar:
case TYPES.Xml:
case TYPES.Text:
case TYPES.NText:
if (typeof value !== 'string' && !(value instanceof String)) {
value = value.toString();
}
break;
case TYPES.Int:
case TYPES.TinyInt:
case TYPES.BigInt:
case TYPES.SmallInt:
if (typeof value !== 'number' && !(value instanceof Number)) {
value = parseInt(value);
if (isNaN(value)) {
value = null;
}
}
break;
case TYPES.Float:
case TYPES.Real:
case TYPES.Decimal:
case TYPES.Numeric:
case TYPES.SmallMoney:
case TYPES.Money:
if (typeof value !== 'number' && !(value instanceof Number)) {
value = parseFloat(value);
if (isNaN(value)) {
value = null;
}
}
break;
case TYPES.Bit:
if (typeof value !== 'boolean' && !(value instanceof Boolean)) {
value = Boolean(value);
}
break;
case TYPES.DateTime:
case TYPES.SmallDateTime:
case TYPES.DateTimeOffset:
case TYPES.Date:
if (!(value instanceof Date)) {
value = new Date(value);
}
break;
case TYPES.Binary:
case TYPES.VarBinary:
case TYPES.Image:
if (!(value instanceof Buffer)) {
value = new Buffer(value.toString());
}
}
return value;
};
/*
@ignore
*/
createColumns = function(metadata) {
var column, i, index, len, out;
out = {};
for (index = i = 0, len = metadata.length; i < len; index = ++i) {
column = metadata[index];
out[column.name] = {
index: index,
name: column.name,
length: column.size,
type: DECLARATIONS[column.sqlType]
};
if (column.udtType != null) {
out[column.name].udt = {
name: column.udtType
};
if (DECLARATIONS[column.udtType]) {
out[column.name].type = DECLARATIONS[column.udtType];
}
}
}
return out;
};
/*
@ignore
*/
isolationLevelDeclaration = function(type) {
switch (type) {
case ISOLATION_LEVEL.READ_UNCOMMITTED:
return "READ UNCOMMITTED";
case ISOLATION_LEVEL.READ_COMMITTED:
return "READ COMMITTED";
case ISOLATION_LEVEL.REPEATABLE_READ:
return "REPEATABLE READ";
case ISOLATION_LEVEL.SERIALIZABLE:
return "SERIALIZABLE";
case ISOLATION_LEVEL.SNAPSHOT:
return "SNAPSHOT";
default:
throw new TransactionError("Invalid isolation level.");
}
};
/*
@ignore
*/
valueCorrection = function(value, metadata) {
if (metadata.sqlType === 'time' && (value != null)) {
value.setFullYear(1970);
return value;
} else if (metadata.sqlType === 'udt' && (value != null)) {
if (UDT[metadata.udtType]) {
return UDT[metadata.udtType](value);
} else {
return value;
}
} else {
return value;
}
};
/*
@ignore
*/
module.exports = function(Connection, Transaction, Request, ConnectionError, TransactionError, RequestError) {
var MsnodesqlConnection, MsnodesqlRequest, MsnodesqlTransaction;
MsnodesqlConnection = (function(superClass) {
extend(MsnodesqlConnection, superClass);
function MsnodesqlConnection() {
return MsnodesqlConnection.__super__.constructor.apply(this, arguments);
}
MsnodesqlConnection.prototype.pool = null;
MsnodesqlConnection.prototype.connect = function(config, callback) {
var cfg, cfg_pool, defaultConnectionString, key, ref1, ref2, value;
defaultConnectionString = CONNECTION_STRING_PORT;
if (config.options.instanceName != null) {
defaultConnectionString = CONNECTION_STRING_NAMED_INSTANCE;
}
cfg = {
connectionString: (ref1 = config.connectionString) != null ? ref1 : defaultConnectionString
};
cfg.connectionString = cfg.connectionString.replace(new RegExp('#{([^}]*)}', 'g'), function(p) {
var key, ref2;
key = p.substr(2, p.length - 3);
if (key === 'instance') {
return config.options.instanceName;
} else if (key === 'trusted') {
if (config.options.trustedConnection) {
return 'Yes';
} else {
return 'No';
}
} else {
return (ref2 = config[key]) != null ? ref2 : '';
}
});
cfg_pool = {
name: 'mssql',
max: 10,
min: 0,
idleTimeoutMillis: 30000,
create: (function(_this) {
return function(callback) {
return msnodesql.open(cfg.connectionString, function(err, c) {
if (err) {
err = ConnectionError(err);
}
if (err) {
return callback(err, null);
}
return callback(null, c);
});
};
})(this),
validate: function(c) {
return c != null;
},
destroy: function(c) {
return c != null ? c.close() : void 0;
}
};
if (config.pool) {
ref2 = config.pool;
for (key in ref2) {
value = ref2[key];
cfg_pool[key] = value;
}
}
this.pool = Pool(cfg_pool, cfg);
return this.pool.acquire((function(_this) {
return function(err, connection) {
if (err && !(err instanceof Error)) {
err = new Error(err);
}
if (err) {
_this.pool.drain(function() {
var ref3;
if ((ref3 = _this.pool) != null) {
ref3.destroyAllNow();
}
return _this.pool = null;
});
} else {
_this.pool.release(connection);
}
return callback(err);
};
})(this));
};
MsnodesqlConnection.prototype.close = function(callback) {
if (!this.pool) {
return callback(null);
}
return this.pool.drain((function(_this) {
return function() {
var ref1;
if ((ref1 = _this.pool) != null) {
ref1.destroyAllNow();
}
_this.pool = null;
return callback(null);
};
})(this));
};
return MsnodesqlConnection;
})(Connection);
MsnodesqlTransaction = (function(superClass) {
extend(MsnodesqlTransaction, superClass);
function MsnodesqlTransaction() {
return MsnodesqlTransaction.__super__.constructor.apply(this, arguments);
}
MsnodesqlTransaction.prototype.begin = function(callback) {
return this.connection.pool.acquire((function(_this) {
return function(err, connection) {
if (err) {
return callback(err);
}
_this._pooledConnection = connection;
return _this.request().query("set transaction isolation level " + (isolationLevelDeclaration(_this.isolationLevel)) + ";begin tran;", callback);
};
})(this));
};
MsnodesqlTransaction.prototype.commit = function(callback) {
this._dedicatedConnection = this._pooledConnection;
return this.request().query('commit tran', (function(_this) {
return function(err) {
_this.connection.pool.release(_this._pooledConnection);
_this._dedicateConnection = null;
_this._pooledConnection = null;
return callback(err);
};
})(this));
};
MsnodesqlTransaction.prototype.rollback = function(callback) {
this._dedicatedConnection = this._pooledConnection;
return this.request().query('rollback tran', (function(_this) {
return function(err) {
_this.connection.pool.release(_this._pooledConnection);
_this._dedicateConnection = null;
_this._pooledConnection = null;
return callback(err);
};
})(this));
};
return MsnodesqlTransaction;
})(Transaction);
MsnodesqlRequest = (function(superClass) {
extend(MsnodesqlRequest, superClass);
function MsnodesqlRequest() {
return MsnodesqlRequest.__super__.constructor.apply(this, arguments);
}
MsnodesqlRequest.prototype.batch = function(batch, callback) {
return MsnodesqlRequest.prototype.query.call(this, batch, callback);
};
MsnodesqlRequest.prototype.bulk = function(table, callback) {
return process.nextTick(function() {
return callback(RequestError("Bulk insert is not supported in 'msnodesql' driver.", 'ENOTSUPP'));
});
};
MsnodesqlRequest.prototype.query = function(command, callback) {
var columns, handleOutput, input, name, output, param, recordset, recordsets, row, sets, started;
if (this.verbose && !this.nested) {
this._log("---------- sql query ----------\n query: " + command);
}
if (command.length === 0) {
return process.nextTick(function() {
var elapsed;
if (this.verbose && !this.nested) {
this._log("---------- response -----------");
elapsed = Date.now() - started;
this._log(" duration: " + elapsed + "ms");
this._log("---------- completed ----------");
}
return typeof callback === "function" ? callback(null, this.multiple || this.nested ? [] : null) : void 0;
});
}
row = null;
columns = null;
recordset = null;
recordsets = [];
started = Date.now();
handleOutput = false;
if (!this.nested) {
input = (function() {
var ref1, results;
ref1 = this.parameters;
results = [];
for (name in ref1) {
param = ref1[name];
results.push("@" + param.name + " " + (declare(param.type, param)));
}
return results;
}).call(this);
sets = (function() {
var ref1, results;
ref1 = this.parameters;
results = [];
for (name in ref1) {
param = ref1[name];
if (param.io === 1) {
results.push("set @" + param.name + "=?");
}
}
return results;
}).call(this);
output = (function() {
var ref1, results;
ref1 = this.parameters;
results = [];
for (name in ref1) {
param = ref1[name];
if (param.io === 2) {
results.push("@" + param.name + " as '" + param.name + "'");
}
}
return results;
}).call(this);
if (input.length) {
command = "declare " + (input.join(',')) + ";" + (sets.join(';')) + ";" + command + ";";
}
if (output.length) {
command += "select " + (output.join(',')) + ";";
handleOutput = true;
}
}
return this._acquire((function(_this) {
return function(err, connection) {
var req;
if (!err) {
req = connection.queryRaw(command, (function() {
var ref1, results;
ref1 = this.parameters;
results = [];
for (name in ref1) {
param = ref1[name];
if (param.io === 1) {
results.push(castParameter(param.value, param.type));
}
}
return results;
}).call(_this));
if (_this.verbose && !_this.nested) {
_this._log("---------- response -----------");
}
req.on('meta', function(metadata) {
if (row) {
if (_this.verbose) {
_this._log(util.inspect(row));
_this._log("---------- --------------------");
}
if (row["___return___"] == null) {
if (_this.stream) {
_this.emit('row', row);
}
}
}
row = null;
columns = metadata;
recordset = [];
Object.defineProperty(recordset, 'columns', {
enumerable: false,
value: createColumns(metadata)
});
if (_this.stream) {
if (recordset.columns["___return___"] == null) {
return _this.emit('recordset', recordset.columns);
}
} else {
return recordsets.push(recordset);
}
});
req.on('row', function(rownumber) {
if (row) {
if (_this.verbose) {
_this._log(util.inspect(row));
_this._log("---------- --------------------");
}
if (row["___return___"] == null) {
if (_this.stream) {
_this.emit('row', row);
}
}
}
row = {};
if (!_this.stream) {
return recordset.push(row);
}
});
req.on('column', function(idx, data, more) {
var exi;
data = valueCorrection(data, columns[idx]);
exi = row[columns[idx].name];
if (exi != null) {
if (exi instanceof Array) {
return exi.push(data);
} else {
return row[columns[idx].name] = [exi, data];
}
} else {
return row[columns[idx].name] = data;
}
});
req.once('error', function(err) {
var e, elapsed;
e = RequestError(err);
if (/^\[Microsoft\]\[SQL Server Native Client 11\.0\]\[SQL Server\](.*)$/.exec(err.message)) {
e.message = RegExp.$1;
}
e.number = err.code;
e.code = 'EREQUEST';
if (_this.verbose && !_this.nested) {
elapsed = Date.now() - started;
_this._log(" error: " + err);
_this._log(" duration: " + elapsed + "ms");
_this._log("---------- completed ----------");
}
_this._release(connection);
return typeof callback === "function" ? callback(e) : void 0;
});
return req.once('done', function() {
var elapsed, last, ref1, ref2;
if (!_this.nested) {
if (row) {
if (_this.verbose) {
_this._log(util.inspect(row));
_this._log("---------- --------------------");
}
if (row["___return___"] == null) {
if (_this.stream) {
_this.emit('row', row);
}
}
}
if (handleOutput) {
last = (ref1 = recordsets.pop()) != null ? ref1[0] : void 0;
ref2 = _this.parameters;
for (name in ref2) {
param = ref2[name];
if (!(param.io === 2)) {
continue;
}
param.value = last[param.name];
if (_this.verbose) {
_this._log(" output: @" + param.name + ", " + param.type.declaration + ", " + param.value);
}
}
}
if (_this.verbose) {
elapsed = Date.now() - started;
_this._log(" duration: " + elapsed + "ms");
_this._log("---------- completed ----------");
}
}
_this._release(connection);
if (_this.stream) {
return callback(null, _this.nested ? row : null);
} else {
return typeof callback === "function" ? callback(null, _this.multiple || _this.nested ? recordsets : recordsets[0]) : void 0;
}
});
} else {
if (connection) {
_this._release(connection);
}
return typeof callback === "function" ? callback(err) : void 0;
}
};
})(this));
};
MsnodesqlRequest.prototype.execute = function(procedure, callback) {
var cmd, name, param, ref1, spp, started;
if (this.verbose) {
this._log("---------- sql execute --------\n proc: " + procedure);
}
started = Date.now();
cmd = "declare " + (['@___return___ int'].concat((function() {
var ref1, results;
ref1 = this.parameters;
results = [];
for (name in ref1) {
param = ref1[name];
if (param.io === 2) {
results.push("@" + param.name + " " + (declare(param.type, param)));
}
}
return results;
}).call(this)).join(', ')) + ";";
cmd += "exec @___return___ = " + procedure + " ";
spp = [];
ref1 = this.parameters;
for (name in ref1) {
param = ref1[name];
if (this.verbose) {
this._log(" " + (param.io === 1 ? " input" : "output") + ": @" + param.name + ", " + param.type.declaration + ", " + param.value);
}
if (param.io === 2) {
spp.push("@" + param.name + "=@" + param.name + " output");
} else {
spp.push("@" + param.name + "=?");
}
}
cmd += (spp.join(', ')) + ";";
cmd += "select " + (['@___return___ as \'___return___\''].concat((function() {
var ref2, results;
ref2 = this.parameters;
results = [];
for (name in ref2) {
param = ref2[name];
if (param.io === 2) {
results.push("@" + param.name + " as '" + param.name + "'");
}
}
return results;
}).call(this)).join(', ')) + ";";
if (this.verbose) {
this._log("---------- response -----------");
}
this.nested = true;
return MsnodesqlRequest.prototype.query.call(this, cmd, (function(_this) {
return function(err, recordsets) {
var elapsed, last, ref2, ref3, returnValue;
_this.nested = false;
if (err) {
if (_this.verbose) {
elapsed = Date.now() - started;
_this._log(" error: " + err);
_this._log(" duration: " + elapsed + "ms");
_this._log("---------- completed ----------");
}
return typeof callback === "function" ? callback(err) : void 0;
} else {
if (_this.stream) {
last = recordsets;
} else {
last = (ref2 = recordsets.pop()) != null ? ref2[0] : void 0;
}
if (last && (last.___return___ != null)) {
returnValue = last.___return___;
ref3 = _this.parameters;
for (name in ref3) {
param = ref3[name];
if (!(param.io === 2)) {
continue;
}
param.value = last[param.name];
if (_this.verbose) {
_this._log(" output: @" + param.name + ", " + param.type.declaration + ", " + param.value);
}
}
}
if (_this.verbose) {
elapsed = Date.now() - started;
_this._log(" return: " + returnValue);
_this._log(" duration: " + elapsed + "ms");
_this._log("---------- completed ----------");
}
if (_this.stream) {
return callback(null, null, returnValue);
} else {
recordsets.returnValue = returnValue;
return typeof callback === "function" ? callback(null, recordsets, returnValue) : void 0;
}
}
};
})(this));
};
/*
Cancel currently executed request.
*/
MsnodesqlRequest.prototype.cancel = function() {
return false;
};
return MsnodesqlRequest;
})(Request);
return {
Connection: MsnodesqlConnection,
Transaction: MsnodesqlTransaction,
Request: MsnodesqlRequest,
fix: function() {}
};
};
}).call(this);
| erkankoc1221647/MyGrade | node_modules/mssql/lib/msnodesql.js | JavaScript | apache-2.0 | 23,012 |
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.uk');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Додати коментар";
Blockly.Msg.CANNOT_DELETE_VARIABLE_PROCEDURE = "Can't delete the variable '%1' because it's part of the definition of the function '%2'"; // untranslated
Blockly.Msg.CHANGE_VALUE_TITLE = "Змінити значення:";
Blockly.Msg.CLEAN_UP = "Вирівняти блоки";
Blockly.Msg.COLLAPSE_ALL = "Згорнути блоки";
Blockly.Msg.COLLAPSE_BLOCK = "Згорнути блок";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "колір 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "колір 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/";
Blockly.Msg.COLOUR_BLEND_RATIO = "співвідношення";
Blockly.Msg.COLOUR_BLEND_TITLE = "змішати";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Змішує два кольори разом у вказаному співвідношені (0.0 - 1.0).";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://uk.wikipedia.org/wiki/Колір";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Вибрати колір з палітри.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "випадковий колір";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Вибрати колір навмання.";
Blockly.Msg.COLOUR_RGB_BLUE = "синій";
Blockly.Msg.COLOUR_RGB_GREEN = "зелений";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html";
Blockly.Msg.COLOUR_RGB_RED = "червоний";
Blockly.Msg.COLOUR_RGB_TITLE = "колір з";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Створити колір зі вказаними рівнями червоного, зеленого та синього. Усі значення мають бути від 0 до 100.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "перервати цикл";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "продовжити з наступної ітерації циклу";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Перервати виконання циклу.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Пропустити залишок цього циклу і перейти до виконання наступної ітерації.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Попередження: цей блок може бути використаний тільки в межах циклу.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated
Blockly.Msg.CONTROLS_FOREACH_TITLE = "для кожного елемента %1 у списку %2";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Для кожного елемента в списку змінна '%1' отримує значення елемента, а потім виконуються певні дії.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg.CONTROLS_FOR_TITLE = "рахувати з %1 від %2 до %3 через %4";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Наявна змінна \"%1\" набуває значень від початкового до кінцевого, враховуючи заданий інтервал, і виконуються вказані блоки.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Додайте умову до блока 'якщо'.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Додати остаточну, всеосяжну умову до блоку 'якщо'.";
Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Додайте, вилучіть або змініть порядок секцій, щоб переналаштувати цей блок 'якщо'.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "інакше";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "інакше якщо";
Blockly.Msg.CONTROLS_IF_MSG_IF = "якщо";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Якщо значення істинне, то виконати певні дії.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Якщо значення істинне, то виконується перший блок операторів. В іншому випадку виконується другий блок операторів.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Якщо перше значення істинне, то виконується перший блок операторів. В іншому випадку, якщо друге значення істина, то виконується другий блок операторів.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Якщо перше значення істинне, то виконується перший блок операторів. В іншому випадку, якщо друге значення істинне, то виконується другий блок операторів. Якщо жодне із значень не є істинним, то виконується останній блок операторів.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://uk.wikipedia.org/wiki/Цикл_(програмування)#.D0.A6.D0.B8.D0.BA.D0.BB_.D0.B7_.D0.BB.D1.96.D1.87.D0.B8.D0.BB.D1.8C.D0.BD.D0.B8.D0.BA.D0.BE.D0.BC";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "виконати";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "повторити %1 разів";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Виконати певні дії декілька разів.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "повторювати, доки не";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "повторювати поки";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Поки значення хибне, виконувати певні дії.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Поки значення істинне, виконувати певні дії.";
Blockly.Msg.DELETE_ALL_BLOCKS = "Вилучити всі блоки %1?";
Blockly.Msg.DELETE_BLOCK = "Видалити блок";
Blockly.Msg.DELETE_VARIABLE = "Вилучити змінну '%1'";
Blockly.Msg.DELETE_VARIABLE_CONFIRMATION = "Вилучити %1 використання змінної '%2'?";
Blockly.Msg.DELETE_X_BLOCKS = "Видалити %1 блоків";
Blockly.Msg.DISABLE_BLOCK = "Вимкнути блок";
Blockly.Msg.DUPLICATE_BLOCK = "Дублювати";
Blockly.Msg.ENABLE_BLOCK = "Увімкнути блок";
Blockly.Msg.EXPAND_ALL = "Розгорнути блоки";
Blockly.Msg.EXPAND_BLOCK = "Розгорнути блок";
Blockly.Msg.EXTERNAL_INPUTS = "Зовнішні входи";
Blockly.Msg.HELP = "Довідка";
Blockly.Msg.INLINE_INPUTS = "Вбудовані входи";
Blockly.Msg.IOS_CANCEL = "Cancel"; // untranslated
Blockly.Msg.IOS_ERROR = "Error"; // untranslated
Blockly.Msg.IOS_OK = "OK"; // untranslated
Blockly.Msg.IOS_PROCEDURES_ADD_INPUT = "+ Add Input"; // untranslated
Blockly.Msg.IOS_PROCEDURES_ALLOW_STATEMENTS = "Allow statements"; // untranslated
Blockly.Msg.IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR = "This function has duplicate inputs."; // untranslated
Blockly.Msg.IOS_PROCEDURES_INPUTS = "INPUTS"; // untranslated
Blockly.Msg.IOS_VARIABLES_ADD_BUTTON = "Add"; // untranslated
Blockly.Msg.IOS_VARIABLES_ADD_VARIABLE = "+ Add Variable"; // untranslated
Blockly.Msg.IOS_VARIABLES_DELETE_BUTTON = "Delete"; // untranslated
Blockly.Msg.IOS_VARIABLES_EMPTY_NAME_ERROR = "You can't use an empty variable name."; // untranslated
Blockly.Msg.IOS_VARIABLES_RENAME_BUTTON = "Rename"; // untranslated
Blockly.Msg.IOS_VARIABLES_VARIABLE_NAME = "Variable name"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list";
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "створити порожній список";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Повертає список, довжиною 0, що не містить записів даних";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "список";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Додайте, вилучіть або змініть порядок секцій для переналаштування блока списку.";
Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "створити список з";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Додати елемент до списку.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Створює список з будь-якою кількістю елементів.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "перший";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# з кінця";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#";
Blockly.Msg.LISTS_GET_INDEX_GET = "отримати";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "отримати і вилучити";
Blockly.Msg.LISTS_GET_INDEX_LAST = "останній";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "випадковий";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "вилучити";
Blockly.Msg.LISTS_GET_INDEX_TAIL = "-ий.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Повертає перший елемент списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM = "Повертає елемент у заданій позиції у списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Повертає останній елемент списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Повертає випадковий елемент списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Видаляє і повертає перший елемент списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM = "Видаляє і повертає елемент у заданій позиції у списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Видаляє і повертає останній елемент списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Видаляє і повертає випадковий елемент списоку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Вилучає перший елемент списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM = "Вилучає зі списку елемент у вказаній позиції.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Вилучає останній елемент списку.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Вилучає випадковий елемент списку.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "до # з кінця";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "до #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "до останнього";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "отримати вкладений список з першого";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "отримати вкладений список від # з кінця";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "отримати вкладений список з #";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = "символу.";
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Створює копію вказаної частини списку.";
Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP = "%1 - це останній елемент.";
Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP = "%1 - це перший елемент.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "знайти перше входження елемента";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "знайти останнє входження елемента";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Повертає індекс першого/останнього входження елемента у списку. Повертає %1, якщо елемент не знайдено.";
Blockly.Msg.LISTS_INLIST = "у списку";
Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 є порожнім";
Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "Повертає істину, якщо список порожній.";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg.LISTS_LENGTH_TITLE = "довжина %1";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Повертає довжину списку.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_REPEAT_TITLE = "створити список з елемента %1 повтореного %2 разів";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Створює список, що складається з заданого значення повтореного задану кількість разів.";
Blockly.Msg.LISTS_REVERSE_HELPURL = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated
Blockly.Msg.LISTS_REVERSE_MESSAGE0 = "reverse %1"; // untranslated
Blockly.Msg.LISTS_REVERSE_TOOLTIP = "Reverse a copy of a list."; // untranslated
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "як";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "вставити в";
Blockly.Msg.LISTS_SET_INDEX_SET = "встановити";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Вставляє елемент на початок списку.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM = "Вставка елемента у вказану позицію списку.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Додає елемент у кінці списку.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Випадковим чином вставляє елемент у список.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Задає перший елемент списку.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM = "Задає елемент списку у вказаній позиції.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Задає останній елемент списку.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Задає випадковий елемент у списку.";
Blockly.Msg.LISTS_SORT_HELPURL = "https://github.com/google/blockly/wiki/Lists#sorting-a-list";
Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = "за зростанням";
Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = "за спаданням";
Blockly.Msg.LISTS_SORT_TITLE = "сортувати %3 %1 %2";
Blockly.Msg.LISTS_SORT_TOOLTIP = "Сортувати копію списку.";
Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = "за абеткою, ігноруючи регістр";
Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = "як числа";
Blockly.Msg.LISTS_SORT_TYPE_TEXT = "за абеткою";
Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated
Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "зробити з тексту список";
Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "зробити зі списку текст";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Злити список текстів у єдиний текст, відокремивши розділювачами.";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Поділити текст на список текстів, розриваючи на кожному розділювачі.";
Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "з розділювачем";
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "хибність";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Повертає значення істина або хибність.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "істина";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://uk.wikipedia.org/wiki/Нерівність";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Повертає істину, якщо обидва входи рівні один одному.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Повертає істину, якщо перше вхідне значення більше, ніж друге.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Повертає істину, якщо перше вхідне значення більше або дорівнює другому.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Повертає істину, якщо перше вхідне значення менше, ніж друге.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Повертає істину, якщо перше вхідне значення менше або дорівнює другому.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Повертає істину, якщо обидва входи не дорівнюють один одному.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "не %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Повертає істину, якщо вхідне значення хибне. Повертає хибність, якщо вхідне значення істинне.";
Blockly.Msg.LOGIC_NULL = "ніщо";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type";
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Повертає ніщо.";
Blockly.Msg.LOGIC_OPERATION_AND = "та";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "або";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Повертає істину, якщо обидва входи істинні.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Повертає істину, якщо принаймні один з входів істинний.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "тест";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:";
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "якщо хибність";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "якщо істина";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Перевіряє умову в 'тест'. Якщо умова істинна, то повертає значення 'якщо істина'; в іншому випадку повертає значення 'якщо хибність'.";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; // untranslated
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://uk.wikipedia.org/wiki/Арифметика";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Повертає суму двох чисел.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Повертає частку двох чисел.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Повертає різницю двох чисел.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Повертає добуток двох чисел.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Повертає перше число, піднесене до степеня, вираженого другим числом.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter";
Blockly.Msg.MATH_CHANGE_TITLE = "змінити %1 на %2";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Додати число до змінної '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://uk.wikipedia.org/wiki/Математична_константа";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Повертає одну з поширених констант: π (3.141...), e (2.718...), φ (1,618...), sqrt(2) (1.414...), sqrt(½) (0.707...) або ∞ (нескінченність).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "обмежити %1 від %2 до %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Обмежує число вказаними межами (включно).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; // untranslated
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "ділиться на";
Blockly.Msg.MATH_IS_EVEN = "парне";
Blockly.Msg.MATH_IS_NEGATIVE = "від'ємне";
Blockly.Msg.MATH_IS_ODD = "непарне";
Blockly.Msg.MATH_IS_POSITIVE = "додатне";
Blockly.Msg.MATH_IS_PRIME = "просте";
Blockly.Msg.MATH_IS_TOOLTIP = "Перевіряє, чи число парне, непарне, просте, ціле, додатне, від'ємне або чи воно ділиться на певне число без остачі. Повертає істину або хибність.";
Blockly.Msg.MATH_IS_WHOLE = "ціле";
Blockly.Msg.MATH_MODULO_HELPURL = "https://uk.wikipedia.org/wiki/Ділення_з_остачею";
Blockly.Msg.MATH_MODULO_TITLE = "остача від %1 ÷ %2";
Blockly.Msg.MATH_MODULO_TOOLTIP = "Повертає остачу від ділення двох чисел.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; // untranslated
Blockly.Msg.MATH_NUMBER_HELPURL = "https://uk.wikipedia.org/wiki/Число";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Число.";
Blockly.Msg.MATH_ONLIST_HELPURL = "http://www.mapleprimes.com/questions/100441-Applying-Function-To-List-Of-Numbers";
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "середнє списку";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "максимум списку";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "медіана списку";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "мінімум списку";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "моди списку";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "випадковий елемент списку";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "стандартне відхилення списку";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "сума списку";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Повертає середнє (арифметичне) числових значень у списку.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Повертає найбільше число у списку.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Повертає медіану списку.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Повертає найменше число у списку.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Повертає перелік найпоширеніших елементів у списку.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Повертає випадковий елемент зі списку.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Повертає стандартне відхилення списку.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Повертає суму всіх чисел у списку.";
Blockly.Msg.MATH_POWER_SYMBOL = "^"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://uk.wikipedia.org/wiki/Генерація_випадкових_чисел";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "випадковий дріб";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Повертає випадковий дріб від 0,0 (включно) та 1.0 (не включно).";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://uk.wikipedia.org/wiki/Генерація_випадкових_чисел";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "випадкове ціле число від %1 до %2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Повертає випадкове ціле число між двома заданими межами включно.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://uk.wikipedia.org/wiki/Округлення";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "округлити";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "округлити до меншого";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "округлити до більшого";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Округлення числа до більшого або до меншого.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://uk.wikipedia.org/wiki/Квадратний_корінь";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "модуль";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "квадратний корінь";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Повертає модуль числа.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Повертає e у степені.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Повертає натуральний логарифм числа.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Повертає десятковий логарифм числа.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Повертає протилежне число.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Повертає 10 у степені.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Повертає квадратний корінь з числа.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; // untranslated
Blockly.Msg.MATH_TRIG_ACOS = "acos"; // untranslated
Blockly.Msg.MATH_TRIG_ASIN = "asin"; // untranslated
Blockly.Msg.MATH_TRIG_ATAN = "atan"; // untranslated
Blockly.Msg.MATH_TRIG_COS = "cos"; // untranslated
Blockly.Msg.MATH_TRIG_HELPURL = "https://uk.wikipedia.org/wiki/Тригонометричні_функції";
Blockly.Msg.MATH_TRIG_SIN = "sin"; // untranslated
Blockly.Msg.MATH_TRIG_TAN = "tan"; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Повертає арккосинус числа.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Повертає арксинус числа.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Повертає арктангенс числа.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Повертає косинус кута в градусах (не в радіанах).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Повертає синус кута в градусах (не в радіанах).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Повертає тангенс кута в градусах (не в радіанах).";
Blockly.Msg.NEW_VARIABLE = "Створити змінну...";
Blockly.Msg.NEW_VARIABLE_TITLE = "Нова назва змінної:";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = "-ий.";
Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "дозволити дії";
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "з:";
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://uk.wikipedia.org/wiki/Підпрограма";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Запустити користувацьку функцію \"%1\".";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://uk.wikipedia.org/wiki/Підпрограма";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Запустити користувацьку функцію \"%1\" і використати її вивід.";
Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "з:";
Blockly.Msg.PROCEDURES_CREATE_DO = "Створити \"%1\"";
Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = "Опишіть цю функцію...";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = "блок тексту";
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://uk.wikipedia.org/wiki/Підпрограма";
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "щось зробити";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "до";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Створює функцію без виводу.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://uk.wikipedia.org/wiki/Підпрограма";
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "повернути";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Створює функцію з виводом.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Увага: ця функція має дубльовані параметри.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Підсвітити визначення функції";
Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Якщо значення істинне, то повернути друге значення.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Попередження: цей блок може використовуватися лише в межах визначення функції.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "назва входу:";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Додати до функції вхідні параметри.";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "входи";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Додайте, вилучіть або змініть порядок вхідних параметрів для цієї функції.";
Blockly.Msg.REDO = "Повторити";
Blockly.Msg.REMOVE_COMMENT = "Видалити коментар";
Blockly.Msg.RENAME_VARIABLE = "Перейменувати змінну...";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Перейменувати усі змінні \"%1\" до:";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "додати текст";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TO = "до";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Додати деякий текст до змінної '%1'.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "до нижнього регістру";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "Великі Перші Букви";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "до ВЕРХНЬОГО регістру";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "В іншому випадку повертає копію тексту.";
Blockly.Msg.TEXT_CHARAT_FIRST = "отримати перший символ";
Blockly.Msg.TEXT_CHARAT_FROM_END = "отримати символ # з кінця";
Blockly.Msg.TEXT_CHARAT_FROM_START = "отримати символ #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage%2Fref%2Farsubex.htm";
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "у тексті";
Blockly.Msg.TEXT_CHARAT_LAST = "отримати останній символ";
Blockly.Msg.TEXT_CHARAT_RANDOM = "отримати випадковий символ";
Blockly.Msg.TEXT_CHARAT_TAIL = "-ий.";
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Повертає символ у зазначеній позиції.";
Blockly.Msg.TEXT_COUNT_HELPURL = "https://github.com/google/blockly/wiki/Text#counting-substrings"; // untranslated
Blockly.Msg.TEXT_COUNT_MESSAGE0 = "count %1 in %2"; // untranslated
Blockly.Msg.TEXT_COUNT_TOOLTIP = "Count how many times some text occurs within some other text."; // untranslated
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Додати елемент до тексту.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "приєднати";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Додайте, вилучіть або змініть порядок секцій для переналаштування текстового блоку.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "до символу # з кінця";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "до символу #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "до останнього символу";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "у тексті";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "отримати підрядок від першого символу";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "отримати підрядок від символу # з кінця";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "отримати підрядок від символу #";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = "-ого.";
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Повертає заданий фрагмент тексту.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "у тексті";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "знайти перше входження тексту";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "знайти останнє входження тексту";
Blockly.Msg.TEXT_INDEXOF_TAIL = ".";
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Повертає індекс першого/останнього входження першого тексту в другий. Повертає %1, якщо текст не знайдено.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 є порожнім";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Повертає істину, якщо вказаний текст порожній.";
Blockly.Msg.TEXT_JOIN_HELPURL = "http://www.chemie.fu-berlin.de/chemnet/use/info/make/make_8.html";
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "створити текст з";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Створити фрагмент тексту шляхом з'єднування будь-якого числа елементів.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "довжина %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Повертає число символів (включно з пропусками) у даному тексті.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "друк %1";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Надрукувати заданий текст, числа або інші значення.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Запитати у користувача число.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Запитати у користувача деякий текст.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "запит числа з повідомленням";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "запит тексту з повідомленням";
Blockly.Msg.TEXT_REPLACE_HELPURL = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated
Blockly.Msg.TEXT_REPLACE_MESSAGE0 = "replace %1 with %2 in %3"; // untranslated
Blockly.Msg.TEXT_REPLACE_TOOLTIP = "Replace all occurances of some text within some other text."; // untranslated
Blockly.Msg.TEXT_REVERSE_HELPURL = "https://github.com/google/blockly/wiki/Text#reversing-text"; // untranslated
Blockly.Msg.TEXT_REVERSE_MESSAGE0 = "reverse %1"; // untranslated
Blockly.Msg.TEXT_REVERSE_TOOLTIP = "Reverses the order of the characters in the text."; // untranslated
Blockly.Msg.TEXT_TEXT_HELPURL = "https://uk.wikipedia.org/wiki/Рядок_(програмування)";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Символ, слово або рядок тексту.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "вилучити крайні пропуски з обох кінців";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "вилучити пропуски з лівого боку";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "вилучити пропуски з правого боку";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Повертає копію тексту з вилученими пропусками з одного або обох кінців.";
Blockly.Msg.TODAY = "Сьогодні";
Blockly.Msg.UNDO = "Скасувати";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "елемент";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Створити 'встановити %1'";
Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Повертає значення цієї змінної.";
Blockly.Msg.VARIABLES_SET = "встановити %1 до %2";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Створити 'отримати %1'";
Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Задає цю змінну рівною входу.";
Blockly.Msg.VARIABLE_ALREADY_EXISTS = "Змінна з назвою '%1' вже існує.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT;
Blockly.Msg.MATH_HUE = "230";
Blockly.Msg.LOOPS_HUE = "120";
Blockly.Msg.LISTS_HUE = "260";
Blockly.Msg.LOGIC_HUE = "210";
Blockly.Msg.VARIABLES_HUE = "330";
Blockly.Msg.TEXTS_HUE = "160";
Blockly.Msg.PROCEDURES_HUE = "290";
Blockly.Msg.COLOUR_HUE = "20"; | lzairdking/blockly | msg/js/uk.js | JavaScript | apache-2.0 | 39,947 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.6-2-8
description: >
Object.defineProperty - argument 'P' is a number that converts to
a string (value is -0)
---*/
var obj = {};
Object.defineProperty(obj, -0, {});
assert(obj.hasOwnProperty("0"), 'obj.hasOwnProperty("0") !== true');
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/Object/defineProperty/15.2.3.6-2-8.js | JavaScript | bsd-2-clause | 401 |
// Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-module-namespace-exotic-objects-isextensible
description: The [[IsExtensible]] internal method returns `false`
flags: [module]
---*/
import * as ns from './is-extensible.js';
assert.sameValue(Object.isExtensible(ns), false);
| sebastienros/jint | Jint.Tests.Test262/test/language/module-code/namespace/internals/is-extensible.js | JavaScript | bsd-2-clause | 381 |
// -*- coding: utf-8 -*-
// Copyright (C) 2014 Yusuke Suzuki <utatane.tea@gmail.com>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import { expect } from 'chai';
import { parse } from '../third_party/esprima';
import { analyze } from '..';
describe('ES6 block scope', function() {
it('let is materialized in ES6 block scope#1', function() {
const ast = parse(`
{
let i = 20;
i;
}
`);
const scopeManager = analyze(ast, {ecmaVersion: 6});
expect(scopeManager.scopes).to.have.length(2); // Program and BlcokStatement scope.
let scope = scopeManager.scopes[0];
expect(scope.type).to.be.equal('global');
expect(scope.variables).to.have.length(0); // No variable in Program scope.
scope = scopeManager.scopes[1];
expect(scope.type).to.be.equal('block');
expect(scope.variables).to.have.length(1); // `i` in block scope.
expect(scope.variables[0].name).to.be.equal('i');
expect(scope.references).to.have.length(2);
expect(scope.references[0].identifier.name).to.be.equal('i');
expect(scope.references[1].identifier.name).to.be.equal('i');
});
it('let is materialized in ES6 block scope#2', function() {
const ast = parse(`
{
let i = 20;
var i = 20;
i;
}
`);
const scopeManager = analyze(ast, {ecmaVersion: 6});
expect(scopeManager.scopes).to.have.length(2); // Program and BlcokStatement scope.
let scope = scopeManager.scopes[0];
expect(scope.type).to.be.equal('global');
expect(scope.variables).to.have.length(1); // No variable in Program scope.
expect(scope.variables[0].name).to.be.equal('i');
scope = scopeManager.scopes[1];
expect(scope.type).to.be.equal('block');
expect(scope.variables).to.have.length(1); // `i` in block scope.
expect(scope.variables[0].name).to.be.equal('i');
expect(scope.references).to.have.length(3);
expect(scope.references[0].identifier.name).to.be.equal('i');
expect(scope.references[1].identifier.name).to.be.equal('i');
expect(scope.references[2].identifier.name).to.be.equal('i');
});
it('function delaration is materialized in ES6 block scope', function() {
const ast = parse(`
{
function test() {
}
test();
}
`);
const scopeManager = analyze(ast, {ecmaVersion: 6});
expect(scopeManager.scopes).to.have.length(3);
let scope = scopeManager.scopes[0];
expect(scope.type).to.be.equal('global');
expect(scope.variables).to.have.length(0);
scope = scopeManager.scopes[1];
expect(scope.type).to.be.equal('block');
expect(scope.variables).to.have.length(1);
expect(scope.variables[0].name).to.be.equal('test');
expect(scope.references).to.have.length(1);
expect(scope.references[0].identifier.name).to.be.equal('test');
scope = scopeManager.scopes[2];
expect(scope.type).to.be.equal('function');
expect(scope.variables).to.have.length(1);
expect(scope.variables[0].name).to.be.equal('arguments');
expect(scope.references).to.have.length(0);
});
it('let is not hoistable#1', function() {
const ast = parse(`
var i = 42; (1)
{
i; // (2) ReferenceError at runtime.
let i = 20; // (2)
i; // (2)
}
`);
const scopeManager = analyze(ast, {ecmaVersion: 6});
expect(scopeManager.scopes).to.have.length(2);
const globalScope = scopeManager.scopes[0];
expect(globalScope.type).to.be.equal('global');
expect(globalScope.variables).to.have.length(1);
expect(globalScope.variables[0].name).to.be.equal('i');
expect(globalScope.references).to.have.length(1);
const scope = scopeManager.scopes[1];
expect(scope.type).to.be.equal('block');
expect(scope.variables).to.have.length(1);
expect(scope.variables[0].name).to.be.equal('i');
expect(scope.references).to.have.length(3);
expect(scope.references[0].resolved).to.be.equal(scope.variables[0]);
expect(scope.references[1].resolved).to.be.equal(scope.variables[0]);
expect(scope.references[2].resolved).to.be.equal(scope.variables[0]);
});
it('let is not hoistable#2', function() {
const ast = parse(`
(function () {
var i = 42; // (1)
i; // (1)
{
i; // (3)
{
i; // (2)
let i = 20; // (2)
i; // (2)
}
let i = 30; // (3)
i; // (3)
}
i; // (1)
}());
`);
const scopeManager = analyze(ast, {ecmaVersion: 6});
expect(scopeManager.scopes).to.have.length(4);
const globalScope = scopeManager.scopes[0];
expect(globalScope.type).to.be.equal('global');
expect(globalScope.variables).to.have.length(0);
expect(globalScope.references).to.have.length(0);
let scope = scopeManager.scopes[1];
expect(scope.type).to.be.equal('function');
expect(scope.variables).to.have.length(2);
expect(scope.variables[0].name).to.be.equal('arguments');
expect(scope.variables[1].name).to.be.equal('i');
const v1 = scope.variables[1];
expect(scope.references).to.have.length(3);
expect(scope.references[0].resolved).to.be.equal(v1);
expect(scope.references[1].resolved).to.be.equal(v1);
expect(scope.references[2].resolved).to.be.equal(v1);
scope = scopeManager.scopes[2];
expect(scope.type).to.be.equal('block');
expect(scope.variables).to.have.length(1);
expect(scope.variables[0].name).to.be.equal('i');
const v3 = scope.variables[0];
expect(scope.references).to.have.length(3);
expect(scope.references[0].resolved).to.be.equal(v3);
expect(scope.references[1].resolved).to.be.equal(v3);
expect(scope.references[2].resolved).to.be.equal(v3);
scope = scopeManager.scopes[3];
expect(scope.type).to.be.equal('block');
expect(scope.variables).to.have.length(1);
expect(scope.variables[0].name).to.be.equal('i');
const v2 = scope.variables[0];
expect(scope.references).to.have.length(3);
expect(scope.references[0].resolved).to.be.equal(v2);
expect(scope.references[1].resolved).to.be.equal(v2);
expect(scope.references[2].resolved).to.be.equal(v2);
});
});
// vim: set sw=4 ts=4 et tw=80 :
| mysticatea/escope | test/es6-block-scope.js | JavaScript | bsd-2-clause | 8,227 |
// Copyright 2015 Microsoft Corporation. All rights reserved.
// This code is governed by the license found in the LICENSE file.
/*---
description: Math.acosh(1) returns +0
es6id: 20.2.2.3
info: |
Math.acosh ( x )
- If x is 1, the result is +0.
---*/
assert.sameValue(Math.acosh(+1), 0, "Math.acosh should produce 0 for +1");
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/Math/acosh/arg-is-one.js | JavaScript | bsd-2-clause | 333 |
// Copyright (C) 2017 Josh Wolfe. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: Bitwise AND for BigInt values
esid: sec-bitwise-op
info: |
BitwiseOp(op, x, y)
1. Let result be 0.
2. Let shift be 0.
3. Repeat, until (x = 0 or x = -1) and (y = 0 or y = -1),
a. Let xDigit be x modulo 2.
b. Let yDigit be y modulo 2.
c. Let result be result + 2**shift * op(xDigit, yDigit)
d. Let shift be shift + 1.
e. Let x be (x - xDigit) / 2.
f. Let y be (y - yDigit) / 2.
4. If op(x modulo 2, y modulo 2) ≠ 0,
a. Let result be result - 2**shift. NOTE: This extends the sign.
5. Return result.
features: [BigInt]
---*/
assert.sameValue(0b00n & 0b00n, 0b00n, "0b00n & 0b00n === 0b00n");
assert.sameValue(0b00n & 0b01n, 0b00n, "0b00n & 0b01n === 0b00n");
assert.sameValue(0b01n & 0b00n, 0b00n, "0b01n & 0b00n === 0b00n");
assert.sameValue(0b00n & 0b10n, 0b00n, "0b00n & 0b10n === 0b00n");
assert.sameValue(0b10n & 0b00n, 0b00n, "0b10n & 0b00n === 0b00n");
assert.sameValue(0b00n & 0b11n, 0b00n, "0b00n & 0b11n === 0b00n");
assert.sameValue(0b11n & 0b00n, 0b00n, "0b11n & 0b00n === 0b00n");
assert.sameValue(0b01n & 0b01n, 0b01n, "0b01n & 0b01n === 0b01n");
assert.sameValue(0b01n & 0b10n, 0b00n, "0b01n & 0b10n === 0b00n");
assert.sameValue(0b10n & 0b01n, 0b00n, "0b10n & 0b01n === 0b00n");
assert.sameValue(0b01n & 0b11n, 0b01n, "0b01n & 0b11n === 0b01n");
assert.sameValue(0b11n & 0b01n, 0b01n, "0b11n & 0b01n === 0b01n");
assert.sameValue(0b10n & 0b10n, 0b10n, "0b10n & 0b10n === 0b10n");
assert.sameValue(0b10n & 0b11n, 0b10n, "0b10n & 0b11n === 0b10n");
assert.sameValue(0b11n & 0b10n, 0b10n, "0b11n & 0b10n === 0b10n");
assert.sameValue(0xffffffffn & 0n, 0n, "0xffffffffn & 0n === 0n");
assert.sameValue(0n & 0xffffffffn, 0n, "0n & 0xffffffffn === 0n");
assert.sameValue(0xffffffffn & 0xffffffffn, 0xffffffffn, "0xffffffffn & 0xffffffffn === 0xffffffffn");
assert.sameValue(0xffffffffffffffffn & 0n, 0n, "0xffffffffffffffffn & 0n === 0n");
assert.sameValue(0n & 0xffffffffffffffffn, 0n, "0n & 0xffffffffffffffffn === 0n");
assert.sameValue(0xffffffffffffffffn & 0xffffffffn, 0xffffffffn, "0xffffffffffffffffn & 0xffffffffn === 0xffffffffn");
assert.sameValue(0xffffffffn & 0xffffffffffffffffn, 0xffffffffn, "0xffffffffn & 0xffffffffffffffffn === 0xffffffffn");
assert.sameValue(
0xffffffffffffffffn & 0xffffffffffffffffn, 0xffffffffffffffffn,
"0xffffffffffffffffn & 0xffffffffffffffffn === 0xffffffffffffffffn");
assert.sameValue(
0xbf2ed51ff75d380fd3be813ec6185780n & 0x4aabef2324cedff5387f1f65n, 0x42092803008e813400181700n,
"0xbf2ed51ff75d380fd3be813ec6185780n & 0x4aabef2324cedff5387f1f65n === 0x42092803008e813400181700n");
assert.sameValue(
0x4aabef2324cedff5387f1f65n & 0xbf2ed51ff75d380fd3be813ec6185780n, 0x42092803008e813400181700n,
"0x4aabef2324cedff5387f1f65n & 0xbf2ed51ff75d380fd3be813ec6185780n === 0x42092803008e813400181700n");
assert.sameValue(0n & -1n, 0n, "0n & -1n === 0n");
assert.sameValue(-1n & 0n, 0n, "-1n & 0n === 0n");
assert.sameValue(0n & -2n, 0n, "0n & -2n === 0n");
assert.sameValue(-2n & 0n, 0n, "-2n & 0n === 0n");
assert.sameValue(1n & -2n, 0n, "1n & -2n === 0n");
assert.sameValue(-2n & 1n, 0n, "-2n & 1n === 0n");
assert.sameValue(2n & -2n, 2n, "2n & -2n === 2n");
assert.sameValue(-2n & 2n, 2n, "-2n & 2n === 2n");
assert.sameValue(2n & -3n, 0n, "2n & -3n === 0n");
assert.sameValue(-3n & 2n, 0n, "-3n & 2n === 0n");
assert.sameValue(-1n & -2n, -2n, "-1n & -2n === -2n");
assert.sameValue(-2n & -1n, -2n, "-2n & -1n === -2n");
assert.sameValue(-2n & -2n, -2n, "-2n & -2n === -2n");
assert.sameValue(-2n & -3n, -4n, "-2n & -3n === -4n");
assert.sameValue(-3n & -2n, -4n, "-3n & -2n === -4n");
assert.sameValue(0xffffffffn & -1n, 0xffffffffn, "0xffffffffn & -1n === 0xffffffffn");
assert.sameValue(-1n & 0xffffffffn, 0xffffffffn, "-1n & 0xffffffffn === 0xffffffffn");
assert.sameValue(0xffffffffffffffffn & -1n, 0xffffffffffffffffn, "0xffffffffffffffffn & -1n === 0xffffffffffffffffn");
assert.sameValue(-1n & 0xffffffffffffffffn, 0xffffffffffffffffn, "-1n & 0xffffffffffffffffn === 0xffffffffffffffffn");
assert.sameValue(
0xbf2ed51ff75d380fd3be813ec6185780n & -0x4aabef2324cedff5387f1f65n, 0xbf2ed51fb554100cd330000ac6004080n,
"0xbf2ed51ff75d380fd3be813ec6185780n & -0x4aabef2324cedff5387f1f65n === 0xbf2ed51fb554100cd330000ac6004080n");
assert.sameValue(
-0x4aabef2324cedff5387f1f65n & 0xbf2ed51ff75d380fd3be813ec6185780n, 0xbf2ed51fb554100cd330000ac6004080n,
"-0x4aabef2324cedff5387f1f65n & 0xbf2ed51ff75d380fd3be813ec6185780n === 0xbf2ed51fb554100cd330000ac6004080n");
assert.sameValue(
-0xbf2ed51ff75d380fd3be813ec6185780n & 0x4aabef2324cedff5387f1f65n, 0x8a2c72024405ec138670800n,
"-0xbf2ed51ff75d380fd3be813ec6185780n & 0x4aabef2324cedff5387f1f65n === 0x8a2c72024405ec138670800n");
assert.sameValue(
0x4aabef2324cedff5387f1f65n & -0xbf2ed51ff75d380fd3be813ec6185780n, 0x8a2c72024405ec138670800n,
"0x4aabef2324cedff5387f1f65n & -0xbf2ed51ff75d380fd3be813ec6185780n === 0x8a2c72024405ec138670800n");
assert.sameValue(
-0xbf2ed51ff75d380fd3be813ec6185780n & -0x4aabef2324cedff5387f1f65n, -0xbf2ed51fffffff2ff7fedffffe7f5f80n,
"-0xbf2ed51ff75d380fd3be813ec6185780n & -0x4aabef2324cedff5387f1f65n === -0xbf2ed51fffffff2ff7fedffffe7f5f80n");
assert.sameValue(
-0x4aabef2324cedff5387f1f65n & -0xbf2ed51ff75d380fd3be813ec6185780n, -0xbf2ed51fffffff2ff7fedffffe7f5f80n,
"-0x4aabef2324cedff5387f1f65n & -0xbf2ed51ff75d380fd3be813ec6185780n === -0xbf2ed51fffffff2ff7fedffffe7f5f80n");
assert.sameValue(-0xffffffffn & 0n, 0n, "-0xffffffffn & 0n === 0n");
assert.sameValue(0n & -0xffffffffn, 0n, "0n & -0xffffffffn === 0n");
assert.sameValue(
-0xffffffffffffffffn & 0x10000000000000000n, 0x10000000000000000n,
"-0xffffffffffffffffn & 0x10000000000000000n === 0x10000000000000000n");
assert.sameValue(
0x10000000000000000n & -0xffffffffffffffffn, 0x10000000000000000n,
"0x10000000000000000n & -0xffffffffffffffffn === 0x10000000000000000n");
assert.sameValue(
-0xffffffffffffffffffffffffn & 0x10000000000000000n, 0n,
"-0xffffffffffffffffffffffffn & 0x10000000000000000n === 0n");
assert.sameValue(
0x10000000000000000n & -0xffffffffffffffffffffffffn, 0n,
"0x10000000000000000n & -0xffffffffffffffffffffffffn === 0n");
| sebastienros/jint | Jint.Tests.Test262/test/language/expressions/bitwise-and/bigint.js | JavaScript | bsd-2-clause | 6,299 |
/**
* Use `Polymer.IronValidatableBehavior` to implement an element that validates user input.
*
* ### Accessiblity
*
* Changing the `invalid` property, either manually or by calling `validate()` will update the
* `aria-invalid` attribute.
*
* @demo demo/index.html
* @polymerBehavior
*/
Polymer.IronValidatableBehavior = {
properties: {
/**
* Namespace for this validator.
*/
validatorType: {
type: String,
value: 'validator'
},
/**
* Name of the validator to use.
*/
validator: {
type: String
},
/**
* True if the last call to `validate` is invalid.
*/
invalid: {
notify: true,
reflectToAttribute: true,
type: Boolean,
value: false
},
_validatorMeta: {
type: Object
}
},
observers: [
'_invalidChanged(invalid)'
],
get _validator() {
return this._validatorMeta && this._validatorMeta.byKey(this.validator);
},
ready: function() {
this._validatorMeta = new Polymer.IronMeta({type: this.validatorType});
},
_invalidChanged: function() {
if (this.invalid) {
this.setAttribute('aria-invalid', 'true');
} else {
this.removeAttribute('aria-invalid');
}
},
/**
* @return {boolean} True if the validator `validator` exists.
*/
hasValidator: function() {
return this._validator != null;
},
/**
* @param {Object} values Passed to the validator's `validate()` function.
* @return {boolean} True if `values` is valid.
*/
validate: function(values) {
var valid = this._validator && this._validator.validate(values);
this.invalid = !valid;
return valid;
}
};
| TheTypoMaster/chromium-crosswalk | third_party/polymer/v1_0/components-chromium/iron-validatable-behavior/iron-validatable-behavior-extracted.js | JavaScript | bsd-3-clause | 1,835 |
/*! VelocityJS.org (1.2.1). (C) 2014 Julian Shapiro. MIT @license: en.wikipedia.org/wiki/MIT_License */
/*************************
Velocity jQuery Shim
*************************/
/*! VelocityJS.org jQuery Shim (1.0.1). (C) 2014 The jQuery Foundation. MIT @license: en.wikipedia.org/wiki/MIT_License. */
/* This file contains the jQuery functions that Velocity relies on, thereby removing Velocity's dependency on a full copy of jQuery, and allowing it to work in any environment. */
/* These shimmed functions are only used if jQuery isn't present. If both this shim and jQuery are loaded, Velocity defaults to jQuery proper. */
/* Browser support: Using this shim instead of jQuery proper removes support for IE8. */
;(function (window) {
/***************
Setup
***************/
/* If jQuery is already loaded, there's no point in loading this shim. */
if (window.jQuery) {
return;
}
/* jQuery base. */
var $ = function (selector, context) {
return new $.fn.init(selector, context);
};
/********************
Private Methods
********************/
/* jQuery */
$.isWindow = function (obj) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
};
/* jQuery */
$.type = function (obj) {
if (obj == null) {
return obj + "";
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[toString.call(obj)] || "object" :
typeof obj;
};
/* jQuery */
$.isArray = Array.isArray || function (obj) {
return $.type(obj) === "array";
};
/* jQuery */
function isArraylike (obj) {
var length = obj.length,
type = $.type(obj);
if (type === "function" || $.isWindow(obj)) {
return false;
}
if (obj.nodeType === 1 && length) {
return true;
}
return type === "array" || length === 0 || typeof length === "number" && length > 0 && (length - 1) in obj;
}
/***************
$ Methods
***************/
/* jQuery: Support removed for IE<9. */
$.isPlainObject = function (obj) {
var key;
if (!obj || $.type(obj) !== "object" || obj.nodeType || $.isWindow(obj)) {
return false;
}
try {
if (obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
return false;
}
for (key in obj) {}
return key === undefined || hasOwn.call(obj, key);
};
/* jQuery */
$.each = function(obj, callback, args) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike(obj);
if (args) {
if (isArray) {
for (; i < length; i++) {
value = callback.apply(obj[i], args);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.apply(obj[i], args);
if (value === false) {
break;
}
}
}
} else {
if (isArray) {
for (; i < length; i++) {
value = callback.call(obj[i], i, obj[i]);
if (value === false) {
break;
}
}
} else {
for (i in obj) {
value = callback.call(obj[i], i, obj[i]);
if (value === false) {
break;
}
}
}
}
return obj;
};
/* Custom */
$.data = function (node, key, value) {
/* $.getData() */
if (value === undefined) {
var id = node[$.expando],
store = id && cache[id];
if (key === undefined) {
return store;
} else if (store) {
if (key in store) {
return store[key];
}
}
/* $.setData() */
} else if (key !== undefined) {
var id = node[$.expando] || (node[$.expando] = ++$.uuid);
cache[id] = cache[id] || {};
cache[id][key] = value;
return value;
}
};
/* Custom */
$.removeData = function (node, keys) {
var id = node[$.expando],
store = id && cache[id];
if (store) {
$.each(keys, function(_, key) {
delete store[key];
});
}
};
/* jQuery */
$.extend = function () {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
if (typeof target === "boolean") {
deep = target;
target = arguments[i] || {};
i++;
}
if (typeof target !== "object" && $.type(target) !== "function") {
target = {};
}
if (i === length) {
target = this;
i--;
}
for (; i < length; i++) {
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) {
continue;
}
if (deep && copy && ($.isPlainObject(copy) || (copyIsArray = $.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && $.isArray(src) ? src : [];
} else {
clone = src && $.isPlainObject(src) ? src : {};
}
target[name] = $.extend(deep, clone, copy);
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
/* jQuery 1.4.3 */
$.queue = function (elem, type, data) {
function $makeArray (arr, results) {
var ret = results || [];
if (arr != null) {
if (isArraylike(Object(arr))) {
/* $.merge */
(function(first, second) {
var len = +second.length,
j = 0,
i = first.length;
while (j < len) {
first[i++] = second[j++];
}
if (len !== len) {
while (second[j] !== undefined) {
first[i++] = second[j++];
}
}
first.length = i;
return first;
})(ret, typeof arr === "string" ? [arr] : arr);
} else {
[].push.call(ret, arr);
}
}
return ret;
}
if (!elem) {
return;
}
type = (type || "fx") + "queue";
var q = $.data(elem, type);
if (!data) {
return q || [];
}
if (!q || $.isArray(data)) {
q = $.data(elem, type, $makeArray(data));
} else {
q.push(data);
}
return q;
};
/* jQuery 1.4.3 */
$.dequeue = function (elems, type) {
/* Custom: Embed element iteration. */
$.each(elems.nodeType ? [ elems ] : elems, function(i, elem) {
type = type || "fx";
var queue = $.queue(elem, type),
fn = queue.shift();
if (fn === "inprogress") {
fn = queue.shift();
}
if (fn) {
if (type === "fx") {
queue.unshift("inprogress");
}
fn.call(elem, function() {
$.dequeue(elem, type);
});
}
});
};
/******************
$.fn Methods
******************/
/* jQuery */
$.fn = $.prototype = {
init: function (selector) {
/* Just return the element wrapped inside an array; don't proceed with the actual jQuery node wrapping process. */
if (selector.nodeType) {
this[0] = selector;
return this;
} else {
throw new Error("Not a DOM node.");
}
},
offset: function () {
/* jQuery altered code: Dropped disconnected DOM node checking. */
var box = this[0].getBoundingClientRect ? this[0].getBoundingClientRect() : { top: 0, left: 0 };
return {
top: box.top + (window.pageYOffset || document.scrollTop || 0) - (document.clientTop || 0),
left: box.left + (window.pageXOffset || document.scrollLeft || 0) - (document.clientLeft || 0)
};
},
position: function () {
/* jQuery */
function offsetParent() {
var offsetParent = this.offsetParent || document;
while (offsetParent && (!offsetParent.nodeType.toLowerCase === "html" && offsetParent.style.position === "static")) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document;
}
/* Zepto */
var elem = this[0],
offsetParent = offsetParent.apply(elem),
offset = this.offset(),
parentOffset = /^(?:body|html)$/i.test(offsetParent.nodeName) ? { top: 0, left: 0 } : $(offsetParent).offset()
offset.top -= parseFloat(elem.style.marginTop) || 0;
offset.left -= parseFloat(elem.style.marginLeft) || 0;
if (offsetParent.style) {
parentOffset.top += parseFloat(offsetParent.style.borderTopWidth) || 0
parentOffset.left += parseFloat(offsetParent.style.borderLeftWidth) || 0
}
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
}
};
/**********************
Private Variables
**********************/
/* For $.data() */
var cache = {};
$.expando = "velocity" + (new Date().getTime());
$.uuid = 0;
/* For $.queue() */
var class2type = {},
hasOwn = class2type.hasOwnProperty,
toString = class2type.toString;
var types = "Boolean Number String Function Array Date RegExp Object Error".split(" ");
for (var i = 0; i < types.length; i++) {
class2type["[object " + types[i] + "]"] = types[i].toLowerCase();
}
/* Makes $(node) possible, without having to call init. */
$.fn.init.prototype = $.fn;
/* Globalize Velocity onto the window, and assign its Utilities property. */
window.Velocity = { Utilities: $ };
})(window);
/******************
Velocity.js
******************/
;(function (factory) {
/* CommonJS module. */
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = factory();
/* AMD module. */
} else if (typeof define === "function" && define.amd) {
define(factory);
/* Browser globals. */
} else {
factory();
}
}(function() {
return function (global, window, document, undefined) {
/***************
Summary
***************/
/*
- CSS: CSS stack that works independently from the rest of Velocity.
- animate(): Core animation method that iterates over the targeted elements and queues the incoming call onto each element individually.
- Pre-Queueing: Prepare the element for animation by instantiating its data cache and processing the call's options.
- Queueing: The logic that runs once the call has reached its point of execution in the element's $.queue() stack.
Most logic is placed here to avoid risking it becoming stale (if the element's properties have changed).
- Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container.
- tick(): The single requestAnimationFrame loop responsible for tweening all in-progress calls.
- completeCall(): Handles the cleanup process for each Velocity call.
*/
/*********************
Helper Functions
*********************/
/* IE detection. Gist: https://gist.github.com/julianshapiro/9098609 */
var IE = (function() {
if (document.documentMode) {
return document.documentMode;
} else {
for (var i = 7; i > 4; i--) {
var div = document.createElement("div");
div.innerHTML = "<!--[if IE " + i + "]><span></span><![endif]-->";
if (div.getElementsByTagName("span").length) {
div = null;
return i;
}
}
}
return undefined;
})();
/* rAF shim. Gist: https://gist.github.com/julianshapiro/9497513 */
var rAFShim = (function() {
var timeLast = 0;
return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
var timeCurrent = (new Date()).getTime(),
timeDelta;
/* Dynamically set delay on a per-tick basis to match 60fps. */
/* Technique by Erik Moller. MIT license: https://gist.github.com/paulirish/1579671 */
timeDelta = Math.max(0, 16 - (timeCurrent - timeLast));
timeLast = timeCurrent + timeDelta;
return setTimeout(function() { callback(timeCurrent + timeDelta); }, timeDelta);
};
})();
/* Array compacting. Copyright Lo-Dash. MIT License: https://github.com/lodash/lodash/blob/master/LICENSE.txt */
function compactSparseArray (array) {
var index = -1,
length = array ? array.length : 0,
result = [];
while (++index < length) {
var value = array[index];
if (value) {
result.push(value);
}
}
return result;
}
function sanitizeElements (elements) {
/* Unwrap jQuery/Zepto objects. */
if (Type.isWrapped(elements)) {
elements = [].slice.call(elements);
/* Wrap a single element in an array so that $.each() can iterate with the element instead of its node's children. */
} else if (Type.isNode(elements)) {
elements = [ elements ];
}
return elements;
}
var Type = {
isString: function (variable) {
return (typeof variable === "string");
},
isArray: Array.isArray || function (variable) {
return Object.prototype.toString.call(variable) === "[object Array]";
},
isFunction: function (variable) {
return Object.prototype.toString.call(variable) === "[object Function]";
},
isNode: function (variable) {
return variable && variable.nodeType;
},
/* Copyright Martin Bohm. MIT License: https://gist.github.com/Tomalak/818a78a226a0738eaade */
isNodeList: function (variable) {
return typeof variable === "object" &&
/^\[object (HTMLCollection|NodeList|Object)\]$/.test(Object.prototype.toString.call(variable)) &&
variable.length !== undefined &&
(variable.length === 0 || (typeof variable[0] === "object" && variable[0].nodeType > 0));
},
/* Determine if variable is a wrapped jQuery or Zepto element. */
isWrapped: function (variable) {
return variable && (variable.jquery || (window.Zepto && window.Zepto.zepto.isZ(variable)));
},
isSVG: function (variable) {
return window.SVGElement && (variable instanceof window.SVGElement);
},
isEmptyObject: function (variable) {
for (var name in variable) {
return false;
}
return true;
}
};
/*****************
Dependencies
*****************/
var $,
isJQuery = false;
if (global.fn && global.fn.jquery) {
$ = global;
isJQuery = true;
} else {
$ = window.Velocity.Utilities;
}
if (IE <= 8 && !isJQuery) {
throw new Error("Velocity: IE8 and below require jQuery to be loaded before Velocity.");
} else if (IE <= 7) {
/* Revert to jQuery's $.animate(), and lose Velocity's extra features. */
jQuery.fn.velocity = jQuery.fn.animate;
/* Now that $.fn.velocity is aliased, abort this Velocity declaration. */
return;
}
/*****************
Constants
*****************/
var DURATION_DEFAULT = 400,
EASING_DEFAULT = "swing";
/*************
State
*************/
var Velocity = {
/* Container for page-wide Velocity state data. */
State: {
/* Detect mobile devices to determine if mobileHA should be turned on. */
isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
/* The mobileHA option's behavior changes on older Android devices (Gingerbread, versions 2.3.3-2.3.7). */
isAndroid: /Android/i.test(navigator.userAgent),
isGingerbread: /Android 2\.3\.[3-7]/i.test(navigator.userAgent),
isChrome: window.chrome,
isFirefox: /Firefox/i.test(navigator.userAgent),
/* Create a cached element for re-use when checking for CSS property prefixes. */
prefixElement: document.createElement("div"),
/* Cache every prefix match to avoid repeating lookups. */
prefixMatches: {},
/* Cache the anchor used for animating window scrolling. */
scrollAnchor: null,
/* Cache the browser-specific property names associated with the scroll anchor. */
scrollPropertyLeft: null,
scrollPropertyTop: null,
/* Keep track of whether our RAF tick is running. */
isTicking: false,
/* Container for every in-progress call to Velocity. */
calls: []
},
/* Velocity's custom CSS stack. Made global for unit testing. */
CSS: { /* Defined below. */ },
/* A shim of the jQuery utility functions used by Velocity -- provided by Velocity's optional jQuery shim. */
Utilities: $,
/* Container for the user's custom animation redirects that are referenced by name in place of the properties map argument. */
Redirects: { /* Manually registered by the user. */ },
Easings: { /* Defined below. */ },
/* Attempt to use ES6 Promises by default. Users can override this with a third-party promises library. */
Promise: window.Promise,
/* Velocity option defaults, which can be overriden by the user. */
defaults: {
queue: "",
duration: DURATION_DEFAULT,
easing: EASING_DEFAULT,
begin: undefined,
complete: undefined,
progress: undefined,
display: undefined,
visibility: undefined,
loop: false,
delay: false,
mobileHA: true,
/* Advanced: Set to false to prevent property values from being cached between consecutive Velocity-initiated chain calls. */
_cacheValues: true
},
/* A design goal of Velocity is to cache data wherever possible in order to avoid DOM requerying. Accordingly, each element has a data cache. */
init: function (element) {
$.data(element, "velocity", {
/* Store whether this is an SVG element, since its properties are retrieved and updated differently than standard HTML elements. */
isSVG: Type.isSVG(element),
/* Keep track of whether the element is currently being animated by Velocity.
This is used to ensure that property values are not transferred between non-consecutive (stale) calls. */
isAnimating: false,
/* A reference to the element's live computedStyle object. Learn more here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */
computedStyle: null,
/* Tween data is cached for each animation on the element so that data can be passed across calls --
in particular, end values are used as subsequent start values in consecutive Velocity calls. */
tweensContainer: null,
/* The full root property values of each CSS hook being animated on this element are cached so that:
1) Concurrently-animating hooks sharing the same root can have their root values' merged into one while tweening.
2) Post-hook-injection root values can be transferred over to consecutively chained Velocity calls as starting root values. */
rootPropertyValueCache: {},
/* A cache for transform updates, which must be manually flushed via CSS.flushTransformCache(). */
transformCache: {}
});
},
/* A parallel to jQuery's $.css(), used for getting/setting Velocity's hooked CSS properties. */
hook: null, /* Defined below. */
/* Velocity-wide animation time remapping for testing purposes. */
mock: false,
version: { major: 1, minor: 2, patch: 1 },
/* Set to 1 or 2 (most verbose) to output debug info to console. */
debug: false
};
/* Retrieve the appropriate scroll anchor and property name for the browser: https://developer.mozilla.org/en-US/docs/Web/API/Window.scrollY */
if (window.pageYOffset !== undefined) {
Velocity.State.scrollAnchor = window;
Velocity.State.scrollPropertyLeft = "pageXOffset";
Velocity.State.scrollPropertyTop = "pageYOffset";
} else {
Velocity.State.scrollAnchor = document.documentElement || document.body.parentNode || document.body;
Velocity.State.scrollPropertyLeft = "scrollLeft";
Velocity.State.scrollPropertyTop = "scrollTop";
}
/* Shorthand alias for jQuery's $.data() utility. */
function Data (element) {
/* Hardcode a reference to the plugin name. */
var response = $.data(element, "velocity");
/* jQuery <=1.4.2 returns null instead of undefined when no match is found. We normalize this behavior. */
return response === null ? undefined : response;
};
/**************
Easing
**************/
/* Step easing generator. */
function generateStep (steps) {
return function (p) {
return Math.round(p * steps) * (1 / steps);
};
}
/* Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License */
function generateBezier (mX1, mY1, mX2, mY2) {
var NEWTON_ITERATIONS = 4,
NEWTON_MIN_SLOPE = 0.001,
SUBDIVISION_PRECISION = 0.0000001,
SUBDIVISION_MAX_ITERATIONS = 10,
kSplineTableSize = 11,
kSampleStepSize = 1.0 / (kSplineTableSize - 1.0),
float32ArraySupported = "Float32Array" in window;
/* Must contain four arguments. */
if (arguments.length !== 4) {
return false;
}
/* Arguments must be numbers. */
for (var i = 0; i < 4; ++i) {
if (typeof arguments[i] !== "number" || isNaN(arguments[i]) || !isFinite(arguments[i])) {
return false;
}
}
/* X values must be in the [0, 1] range. */
mX1 = Math.min(mX1, 1);
mX2 = Math.min(mX2, 1);
mX1 = Math.max(mX1, 0);
mX2 = Math.max(mX2, 0);
var mSampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
function A (aA1, aA2) { return 1.0 - 3.0 * aA2 + 3.0 * aA1; }
function B (aA1, aA2) { return 3.0 * aA2 - 6.0 * aA1; }
function C (aA1) { return 3.0 * aA1; }
function calcBezier (aT, aA1, aA2) {
return ((A(aA1, aA2)*aT + B(aA1, aA2))*aT + C(aA1))*aT;
}
function getSlope (aT, aA1, aA2) {
return 3.0 * A(aA1, aA2)*aT*aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
}
function newtonRaphsonIterate (aX, aGuessT) {
for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
var currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0.0) return aGuessT;
var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
function calcSampleValues () {
for (var i = 0; i < kSplineTableSize; ++i) {
mSampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
}
function binarySubdivide (aX, aA, aB) {
var currentX, currentT, i = 0;
do {
currentT = aA + (aB - aA) / 2.0;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0.0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
}
function getTForX (aX) {
var intervalStart = 0.0,
currentSample = 1,
lastSample = kSplineTableSize - 1;
for (; currentSample != lastSample && mSampleValues[currentSample] <= aX; ++currentSample) {
intervalStart += kSampleStepSize;
}
--currentSample;
var dist = (aX - mSampleValues[currentSample]) / (mSampleValues[currentSample+1] - mSampleValues[currentSample]),
guessForT = intervalStart + dist * kSampleStepSize,
initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT);
} else if (initialSlope == 0.0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize);
}
}
var _precomputed = false;
function precompute() {
_precomputed = true;
if (mX1 != mY1 || mX2 != mY2) calcSampleValues();
}
var f = function (aX) {
if (!_precomputed) precompute();
if (mX1 === mY1 && mX2 === mY2) return aX;
if (aX === 0) return 0;
if (aX === 1) return 1;
return calcBezier(getTForX(aX), mY1, mY2);
};
f.getControlPoints = function() { return [{ x: mX1, y: mY1 }, { x: mX2, y: mY2 }]; };
var str = "generateBezier(" + [mX1, mY1, mX2, mY2] + ")";
f.toString = function () { return str; };
return f;
}
/* Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License */
/* Given a tension, friction, and duration, a simulation at 60FPS will first run without a defined duration in order to calculate the full path. A second pass
then adjusts the time delta -- using the relation between actual time and duration -- to calculate the path for the duration-constrained animation. */
var generateSpringRK4 = (function () {
function springAccelerationForState (state) {
return (-state.tension * state.x) - (state.friction * state.v);
}
function springEvaluateStateWithDerivative (initialState, dt, derivative) {
var state = {
x: initialState.x + derivative.dx * dt,
v: initialState.v + derivative.dv * dt,
tension: initialState.tension,
friction: initialState.friction
};
return { dx: state.v, dv: springAccelerationForState(state) };
}
function springIntegrateState (state, dt) {
var a = {
dx: state.v,
dv: springAccelerationForState(state)
},
b = springEvaluateStateWithDerivative(state, dt * 0.5, a),
c = springEvaluateStateWithDerivative(state, dt * 0.5, b),
d = springEvaluateStateWithDerivative(state, dt, c),
dxdt = 1.0 / 6.0 * (a.dx + 2.0 * (b.dx + c.dx) + d.dx),
dvdt = 1.0 / 6.0 * (a.dv + 2.0 * (b.dv + c.dv) + d.dv);
state.x = state.x + dxdt * dt;
state.v = state.v + dvdt * dt;
return state;
}
return function springRK4Factory (tension, friction, duration) {
var initState = {
x: -1,
v: 0,
tension: null,
friction: null
},
path = [0],
time_lapsed = 0,
tolerance = 1 / 10000,
DT = 16 / 1000,
have_duration, dt, last_state;
tension = parseFloat(tension) || 500;
friction = parseFloat(friction) || 20;
duration = duration || null;
initState.tension = tension;
initState.friction = friction;
have_duration = duration !== null;
/* Calculate the actual time it takes for this animation to complete with the provided conditions. */
if (have_duration) {
/* Run the simulation without a duration. */
time_lapsed = springRK4Factory(tension, friction);
/* Compute the adjusted time delta. */
dt = time_lapsed / duration * DT;
} else {
dt = DT;
}
while (true) {
/* Next/step function .*/
last_state = springIntegrateState(last_state || initState, dt);
/* Store the position. */
path.push(1 + last_state.x);
time_lapsed += 16;
/* If the change threshold is reached, break. */
if (!(Math.abs(last_state.x) > tolerance && Math.abs(last_state.v) > tolerance)) {
break;
}
}
/* If duration is not defined, return the actual time required for completing this animation. Otherwise, return a closure that holds the
computed path and returns a snapshot of the position according to a given percentComplete. */
return !have_duration ? time_lapsed : function(percentComplete) { return path[ (percentComplete * (path.length - 1)) | 0 ]; };
};
}());
/* jQuery easings. */
Velocity.Easings = {
linear: function(p) { return p; },
swing: function(p) { return 0.5 - Math.cos( p * Math.PI ) / 2 },
/* Bonus "spring" easing, which is a less exaggerated version of easeInOutElastic. */
spring: function(p) { return 1 - (Math.cos(p * 4.5 * Math.PI) * Math.exp(-p * 6)); }
};
/* CSS3 and Robert Penner easings. */
$.each(
[
[ "ease", [ 0.25, 0.1, 0.25, 1.0 ] ],
[ "ease-in", [ 0.42, 0.0, 1.00, 1.0 ] ],
[ "ease-out", [ 0.00, 0.0, 0.58, 1.0 ] ],
[ "ease-in-out", [ 0.42, 0.0, 0.58, 1.0 ] ],
[ "easeInSine", [ 0.47, 0, 0.745, 0.715 ] ],
[ "easeOutSine", [ 0.39, 0.575, 0.565, 1 ] ],
[ "easeInOutSine", [ 0.445, 0.05, 0.55, 0.95 ] ],
[ "easeInQuad", [ 0.55, 0.085, 0.68, 0.53 ] ],
[ "easeOutQuad", [ 0.25, 0.46, 0.45, 0.94 ] ],
[ "easeInOutQuad", [ 0.455, 0.03, 0.515, 0.955 ] ],
[ "easeInCubic", [ 0.55, 0.055, 0.675, 0.19 ] ],
[ "easeOutCubic", [ 0.215, 0.61, 0.355, 1 ] ],
[ "easeInOutCubic", [ 0.645, 0.045, 0.355, 1 ] ],
[ "easeInQuart", [ 0.895, 0.03, 0.685, 0.22 ] ],
[ "easeOutQuart", [ 0.165, 0.84, 0.44, 1 ] ],
[ "easeInOutQuart", [ 0.77, 0, 0.175, 1 ] ],
[ "easeInQuint", [ 0.755, 0.05, 0.855, 0.06 ] ],
[ "easeOutQuint", [ 0.23, 1, 0.32, 1 ] ],
[ "easeInOutQuint", [ 0.86, 0, 0.07, 1 ] ],
[ "easeInExpo", [ 0.95, 0.05, 0.795, 0.035 ] ],
[ "easeOutExpo", [ 0.19, 1, 0.22, 1 ] ],
[ "easeInOutExpo", [ 1, 0, 0, 1 ] ],
[ "easeInCirc", [ 0.6, 0.04, 0.98, 0.335 ] ],
[ "easeOutCirc", [ 0.075, 0.82, 0.165, 1 ] ],
[ "easeInOutCirc", [ 0.785, 0.135, 0.15, 0.86 ] ]
], function(i, easingArray) {
Velocity.Easings[easingArray[0]] = generateBezier.apply(null, easingArray[1]);
});
/* Determine the appropriate easing type given an easing input. */
function getEasing(value, duration) {
var easing = value;
/* The easing option can either be a string that references a pre-registered easing,
or it can be a two-/four-item array of integers to be converted into a bezier/spring function. */
if (Type.isString(value)) {
/* Ensure that the easing has been assigned to jQuery's Velocity.Easings object. */
if (!Velocity.Easings[value]) {
easing = false;
}
} else if (Type.isArray(value) && value.length === 1) {
easing = generateStep.apply(null, value);
} else if (Type.isArray(value) && value.length === 2) {
/* springRK4 must be passed the animation's duration. */
/* Note: If the springRK4 array contains non-numbers, generateSpringRK4() returns an easing
function generated with default tension and friction values. */
easing = generateSpringRK4.apply(null, value.concat([ duration ]));
} else if (Type.isArray(value) && value.length === 4) {
/* Note: If the bezier array contains non-numbers, generateBezier() returns false. */
easing = generateBezier.apply(null, value);
} else {
easing = false;
}
/* Revert to the Velocity-wide default easing type, or fall back to "swing" (which is also jQuery's default)
if the Velocity-wide default has been incorrectly modified. */
if (easing === false) {
if (Velocity.Easings[Velocity.defaults.easing]) {
easing = Velocity.defaults.easing;
} else {
easing = EASING_DEFAULT;
}
}
return easing;
}
/*****************
CSS Stack
*****************/
/* The CSS object is a highly condensed and performant CSS stack that fully replaces jQuery's.
It handles the validation, getting, and setting of both standard CSS properties and CSS property hooks. */
/* Note: A "CSS" shorthand is aliased so that our code is easier to read. */
var CSS = Velocity.CSS = {
/*************
RegEx
*************/
RegEx: {
isHex: /^#([A-f\d]{3}){1,2}$/i,
/* Unwrap a property value's surrounding text, e.g. "rgba(4, 3, 2, 1)" ==> "4, 3, 2, 1" and "rect(4px 3px 2px 1px)" ==> "4px 3px 2px 1px". */
valueUnwrap: /^[A-z]+\((.*)\)$/i,
wrappedValueAlreadyExtracted: /[0-9.]+ [0-9.]+ [0-9.]+( [0-9.]+)?/,
/* Split a multi-value property into an array of subvalues, e.g. "rgba(4, 3, 2, 1) 4px 3px 2px 1px" ==> [ "rgba(4, 3, 2, 1)", "4px", "3px", "2px", "1px" ]. */
valueSplit: /([A-z]+\(.+\))|(([A-z0-9#-.]+?)(?=\s|$))/ig
},
/************
Lists
************/
Lists: {
colors: [ "fill", "stroke", "stopColor", "color", "backgroundColor", "borderColor", "borderTopColor", "borderRightColor", "borderBottomColor", "borderLeftColor", "outlineColor" ],
transformsBase: [ "translateX", "translateY", "scale", "scaleX", "scaleY", "skewX", "skewY", "rotateZ" ],
transforms3D: [ "transformPerspective", "translateZ", "scaleZ", "rotateX", "rotateY" ]
},
/************
Hooks
************/
/* Hooks allow a subproperty (e.g. "boxShadowBlur") of a compound-value CSS property
(e.g. "boxShadow: X Y Blur Spread Color") to be animated as if it were a discrete property. */
/* Note: Beyond enabling fine-grained property animation, hooking is necessary since Velocity only
tweens properties with single numeric values; unlike CSS transitions, Velocity does not interpolate compound-values. */
Hooks: {
/********************
Registration
********************/
/* Templates are a concise way of indicating which subproperties must be individually registered for each compound-value CSS property. */
/* Each template consists of the compound-value's base name, its constituent subproperty names, and those subproperties' default values. */
templates: {
"textShadow": [ "Color X Y Blur", "black 0px 0px 0px" ],
"boxShadow": [ "Color X Y Blur Spread", "black 0px 0px 0px 0px" ],
"clip": [ "Top Right Bottom Left", "0px 0px 0px 0px" ],
"backgroundPosition": [ "X Y", "0% 0%" ],
"transformOrigin": [ "X Y Z", "50% 50% 0px" ],
"perspectiveOrigin": [ "X Y", "50% 50%" ]
},
/* A "registered" hook is one that has been converted from its template form into a live,
tweenable property. It contains data to associate it with its root property. */
registered: {
/* Note: A registered hook looks like this ==> textShadowBlur: [ "textShadow", 3 ],
which consists of the subproperty's name, the associated root property's name,
and the subproperty's position in the root's value. */
},
/* Convert the templates into individual hooks then append them to the registered object above. */
register: function () {
/* Color hooks registration: Colors are defaulted to white -- as opposed to black -- since colors that are
currently set to "transparent" default to their respective template below when color-animated,
and white is typically a closer match to transparent than black is. An exception is made for text ("color"),
which is almost always set closer to black than white. */
for (var i = 0; i < CSS.Lists.colors.length; i++) {
var rgbComponents = (CSS.Lists.colors[i] === "color") ? "0 0 0 1" : "255 255 255 1";
CSS.Hooks.templates[CSS.Lists.colors[i]] = [ "Red Green Blue Alpha", rgbComponents ];
}
var rootProperty,
hookTemplate,
hookNames;
/* In IE, color values inside compound-value properties are positioned at the end the value instead of at the beginning.
Thus, we re-arrange the templates accordingly. */
if (IE) {
for (rootProperty in CSS.Hooks.templates) {
hookTemplate = CSS.Hooks.templates[rootProperty];
hookNames = hookTemplate[0].split(" ");
var defaultValues = hookTemplate[1].match(CSS.RegEx.valueSplit);
if (hookNames[0] === "Color") {
/* Reposition both the hook's name and its default value to the end of their respective strings. */
hookNames.push(hookNames.shift());
defaultValues.push(defaultValues.shift());
/* Replace the existing template for the hook's root property. */
CSS.Hooks.templates[rootProperty] = [ hookNames.join(" "), defaultValues.join(" ") ];
}
}
}
/* Hook registration. */
for (rootProperty in CSS.Hooks.templates) {
hookTemplate = CSS.Hooks.templates[rootProperty];
hookNames = hookTemplate[0].split(" ");
for (var i in hookNames) {
var fullHookName = rootProperty + hookNames[i],
hookPosition = i;
/* For each hook, register its full name (e.g. textShadowBlur) with its root property (e.g. textShadow)
and the hook's position in its template's default value string. */
CSS.Hooks.registered[fullHookName] = [ rootProperty, hookPosition ];
}
}
},
/*****************************
Injection and Extraction
*****************************/
/* Look up the root property associated with the hook (e.g. return "textShadow" for "textShadowBlur"). */
/* Since a hook cannot be set directly (the browser won't recognize it), style updating for hooks is routed through the hook's root property. */
getRoot: function (property) {
var hookData = CSS.Hooks.registered[property];
if (hookData) {
return hookData[0];
} else {
/* If there was no hook match, return the property name untouched. */
return property;
}
},
/* Convert any rootPropertyValue, null or otherwise, into a space-delimited list of hook values so that
the targeted hook can be injected or extracted at its standard position. */
cleanRootPropertyValue: function(rootProperty, rootPropertyValue) {
/* If the rootPropertyValue is wrapped with "rgb()", "clip()", etc., remove the wrapping to normalize the value before manipulation. */
if (CSS.RegEx.valueUnwrap.test(rootPropertyValue)) {
rootPropertyValue = rootPropertyValue.match(CSS.RegEx.valueUnwrap)[1];
}
/* If rootPropertyValue is a CSS null-value (from which there's inherently no hook value to extract),
default to the root's default value as defined in CSS.Hooks.templates. */
/* Note: CSS null-values include "none", "auto", and "transparent". They must be converted into their
zero-values (e.g. textShadow: "none" ==> textShadow: "0px 0px 0px black") for hook manipulation to proceed. */
if (CSS.Values.isCSSNullValue(rootPropertyValue)) {
rootPropertyValue = CSS.Hooks.templates[rootProperty][1];
}
return rootPropertyValue;
},
/* Extracted the hook's value from its root property's value. This is used to get the starting value of an animating hook. */
extractValue: function (fullHookName, rootPropertyValue) {
var hookData = CSS.Hooks.registered[fullHookName];
if (hookData) {
var hookRoot = hookData[0],
hookPosition = hookData[1];
rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);
/* Split rootPropertyValue into its constituent hook values then grab the desired hook at its standard position. */
return rootPropertyValue.toString().match(CSS.RegEx.valueSplit)[hookPosition];
} else {
/* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */
return rootPropertyValue;
}
},
/* Inject the hook's value into its root property's value. This is used to piece back together the root property
once Velocity has updated one of its individually hooked values through tweening. */
injectValue: function (fullHookName, hookValue, rootPropertyValue) {
var hookData = CSS.Hooks.registered[fullHookName];
if (hookData) {
var hookRoot = hookData[0],
hookPosition = hookData[1],
rootPropertyValueParts,
rootPropertyValueUpdated;
rootPropertyValue = CSS.Hooks.cleanRootPropertyValue(hookRoot, rootPropertyValue);
/* Split rootPropertyValue into its individual hook values, replace the targeted value with hookValue,
then reconstruct the rootPropertyValue string. */
rootPropertyValueParts = rootPropertyValue.toString().match(CSS.RegEx.valueSplit);
rootPropertyValueParts[hookPosition] = hookValue;
rootPropertyValueUpdated = rootPropertyValueParts.join(" ");
return rootPropertyValueUpdated;
} else {
/* If the provided fullHookName isn't a registered hook, return the rootPropertyValue that was passed in. */
return rootPropertyValue;
}
}
},
/*******************
Normalizations
*******************/
/* Normalizations standardize CSS property manipulation by pollyfilling browser-specific implementations (e.g. opacity)
and reformatting special properties (e.g. clip, rgba) to look like standard ones. */
Normalizations: {
/* Normalizations are passed a normalization target (either the property's name, its extracted value, or its injected value),
the targeted element (which may need to be queried), and the targeted property value. */
registered: {
clip: function (type, element, propertyValue) {
switch (type) {
case "name":
return "clip";
/* Clip needs to be unwrapped and stripped of its commas during extraction. */
case "extract":
var extracted;
/* If Velocity also extracted this value, skip extraction. */
if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {
extracted = propertyValue;
} else {
/* Remove the "rect()" wrapper. */
extracted = propertyValue.toString().match(CSS.RegEx.valueUnwrap);
/* Strip off commas. */
extracted = extracted ? extracted[1].replace(/,(\s+)?/g, " ") : propertyValue;
}
return extracted;
/* Clip needs to be re-wrapped during injection. */
case "inject":
return "rect(" + propertyValue + ")";
}
},
blur: function(type, element, propertyValue) {
switch (type) {
case "name":
return Velocity.State.isFirefox ? "filter" : "-webkit-filter";
case "extract":
var extracted = parseFloat(propertyValue);
/* If extracted is NaN, meaning the value isn't already extracted. */
if (!(extracted || extracted === 0)) {
var blurComponent = propertyValue.toString().match(/blur\(([0-9]+[A-z]+)\)/i);
/* If the filter string had a blur component, return just the blur value and unit type. */
if (blurComponent) {
extracted = blurComponent[1];
/* If the component doesn't exist, default blur to 0. */
} else {
extracted = 0;
}
}
return extracted;
/* Blur needs to be re-wrapped during injection. */
case "inject":
/* For the blur effect to be fully de-applied, it needs to be set to "none" instead of 0. */
if (!parseFloat(propertyValue)) {
return "none";
} else {
return "blur(" + propertyValue + ")";
}
}
},
/* <=IE8 do not support the standard opacity property. They use filter:alpha(opacity=INT) instead. */
opacity: function (type, element, propertyValue) {
if (IE <= 8) {
switch (type) {
case "name":
return "filter";
case "extract":
/* <=IE8 return a "filter" value of "alpha(opacity=\d{1,3})".
Extract the value and convert it to a decimal value to match the standard CSS opacity property's formatting. */
var extracted = propertyValue.toString().match(/alpha\(opacity=(.*)\)/i);
if (extracted) {
/* Convert to decimal value. */
propertyValue = extracted[1] / 100;
} else {
/* When extracting opacity, default to 1 since a null value means opacity hasn't been set. */
propertyValue = 1;
}
return propertyValue;
case "inject":
/* Opacified elements are required to have their zoom property set to a non-zero value. */
element.style.zoom = 1;
/* Setting the filter property on elements with certain font property combinations can result in a
highly unappealing ultra-bolding effect. There's no way to remedy this throughout a tween, but dropping the
value altogether (when opacity hits 1) at leasts ensures that the glitch is gone post-tweening. */
if (parseFloat(propertyValue) >= 1) {
return "";
} else {
/* As per the filter property's spec, convert the decimal value to a whole number and wrap the value. */
return "alpha(opacity=" + parseInt(parseFloat(propertyValue) * 100, 10) + ")";
}
}
/* With all other browsers, normalization is not required; return the same values that were passed in. */
} else {
switch (type) {
case "name":
return "opacity";
case "extract":
return propertyValue;
case "inject":
return propertyValue;
}
}
}
},
/*****************************
Batched Registrations
*****************************/
/* Note: Batched normalizations extend the CSS.Normalizations.registered object. */
register: function () {
/*****************
Transforms
*****************/
/* Transforms are the subproperties contained by the CSS "transform" property. Transforms must undergo normalization
so that they can be referenced in a properties map by their individual names. */
/* Note: When transforms are "set", they are actually assigned to a per-element transformCache. When all transform
setting is complete complete, CSS.flushTransformCache() must be manually called to flush the values to the DOM.
Transform setting is batched in this way to improve performance: the transform style only needs to be updated
once when multiple transform subproperties are being animated simultaneously. */
/* Note: IE9 and Android Gingerbread have support for 2D -- but not 3D -- transforms. Since animating unsupported
transform properties results in the browser ignoring the *entire* transform string, we prevent these 3D values
from being normalized for these browsers so that tweening skips these properties altogether
(since it will ignore them as being unsupported by the browser.) */
if (!(IE <= 9) && !Velocity.State.isGingerbread) {
/* Note: Since the standalone CSS "perspective" property and the CSS transform "perspective" subproperty
share the same name, the latter is given a unique token within Velocity: "transformPerspective". */
CSS.Lists.transformsBase = CSS.Lists.transformsBase.concat(CSS.Lists.transforms3D);
}
for (var i = 0; i < CSS.Lists.transformsBase.length; i++) {
/* Wrap the dynamically generated normalization function in a new scope so that transformName's value is
paired with its respective function. (Otherwise, all functions would take the final for loop's transformName.) */
(function() {
var transformName = CSS.Lists.transformsBase[i];
CSS.Normalizations.registered[transformName] = function (type, element, propertyValue) {
switch (type) {
/* The normalized property name is the parent "transform" property -- the property that is actually set in CSS. */
case "name":
return "transform";
/* Transform values are cached onto a per-element transformCache object. */
case "extract":
/* If this transform has yet to be assigned a value, return its null value. */
if (Data(element) === undefined || Data(element).transformCache[transformName] === undefined) {
/* Scale CSS.Lists.transformsBase default to 1 whereas all other transform properties default to 0. */
return /^scale/i.test(transformName) ? 1 : 0;
/* When transform values are set, they are wrapped in parentheses as per the CSS spec.
Thus, when extracting their values (for tween calculations), we strip off the parentheses. */
} else {
return Data(element).transformCache[transformName].replace(/[()]/g, "");
}
case "inject":
var invalid = false;
/* If an individual transform property contains an unsupported unit type, the browser ignores the *entire* transform property.
Thus, protect users from themselves by skipping setting for transform values supplied with invalid unit types. */
/* Switch on the base transform type; ignore the axis by removing the last letter from the transform's name. */
switch (transformName.substr(0, transformName.length - 1)) {
/* Whitelist unit types for each transform. */
case "translate":
invalid = !/(%|px|em|rem|vw|vh|\d)$/i.test(propertyValue);
break;
/* Since an axis-free "scale" property is supported as well, a little hack is used here to detect it by chopping off its last letter. */
case "scal":
case "scale":
/* Chrome on Android has a bug in which scaled elements blur if their initial scale
value is below 1 (which can happen with forcefeeding). Thus, we detect a yet-unset scale property
and ensure that its first value is always 1. More info: http://stackoverflow.com/questions/10417890/css3-animations-with-transform-causes-blurred-elements-on-webkit/10417962#10417962 */
if (Velocity.State.isAndroid && Data(element).transformCache[transformName] === undefined && propertyValue < 1) {
propertyValue = 1;
}
invalid = !/(\d)$/i.test(propertyValue);
break;
case "skew":
invalid = !/(deg|\d)$/i.test(propertyValue);
break;
case "rotate":
invalid = !/(deg|\d)$/i.test(propertyValue);
break;
}
if (!invalid) {
/* As per the CSS spec, wrap the value in parentheses. */
Data(element).transformCache[transformName] = "(" + propertyValue + ")";
}
/* Although the value is set on the transformCache object, return the newly-updated value for the calling code to process as normal. */
return Data(element).transformCache[transformName];
}
};
})();
}
/*************
Colors
*************/
/* Since Velocity only animates a single numeric value per property, color animation is achieved by hooking the individual RGBA components of CSS color properties.
Accordingly, color values must be normalized (e.g. "#ff0000", "red", and "rgb(255, 0, 0)" ==> "255 0 0 1") so that their components can be injected/extracted by CSS.Hooks logic. */
for (var i = 0; i < CSS.Lists.colors.length; i++) {
/* Wrap the dynamically generated normalization function in a new scope so that colorName's value is paired with its respective function.
(Otherwise, all functions would take the final for loop's colorName.) */
(function () {
var colorName = CSS.Lists.colors[i];
/* Note: In IE<=8, which support rgb but not rgba, color properties are reverted to rgb by stripping off the alpha component. */
CSS.Normalizations.registered[colorName] = function(type, element, propertyValue) {
switch (type) {
case "name":
return colorName;
/* Convert all color values into the rgb format. (Old IE can return hex values and color names instead of rgb/rgba.) */
case "extract":
var extracted;
/* If the color is already in its hookable form (e.g. "255 255 255 1") due to having been previously extracted, skip extraction. */
if (CSS.RegEx.wrappedValueAlreadyExtracted.test(propertyValue)) {
extracted = propertyValue;
} else {
var converted,
colorNames = {
black: "rgb(0, 0, 0)",
blue: "rgb(0, 0, 255)",
gray: "rgb(128, 128, 128)",
green: "rgb(0, 128, 0)",
red: "rgb(255, 0, 0)",
white: "rgb(255, 255, 255)"
};
/* Convert color names to rgb. */
if (/^[A-z]+$/i.test(propertyValue)) {
if (colorNames[propertyValue] !== undefined) {
converted = colorNames[propertyValue]
} else {
/* If an unmatched color name is provided, default to black. */
converted = colorNames.black;
}
/* Convert hex values to rgb. */
} else if (CSS.RegEx.isHex.test(propertyValue)) {
converted = "rgb(" + CSS.Values.hexToRgb(propertyValue).join(" ") + ")";
/* If the provided color doesn't match any of the accepted color formats, default to black. */
} else if (!(/^rgba?\(/i.test(propertyValue))) {
converted = colorNames.black;
}
/* Remove the surrounding "rgb/rgba()" string then replace commas with spaces and strip
repeated spaces (in case the value included spaces to begin with). */
extracted = (converted || propertyValue).toString().match(CSS.RegEx.valueUnwrap)[1].replace(/,(\s+)?/g, " ");
}
/* So long as this isn't <=IE8, add a fourth (alpha) component if it's missing and default it to 1 (visible). */
if (!(IE <= 8) && extracted.split(" ").length === 3) {
extracted += " 1";
}
return extracted;
case "inject":
/* If this is IE<=8 and an alpha component exists, strip it off. */
if (IE <= 8) {
if (propertyValue.split(" ").length === 4) {
propertyValue = propertyValue.split(/\s+/).slice(0, 3).join(" ");
}
/* Otherwise, add a fourth (alpha) component if it's missing and default it to 1 (visible). */
} else if (propertyValue.split(" ").length === 3) {
propertyValue += " 1";
}
/* Re-insert the browser-appropriate wrapper("rgb/rgba()"), insert commas, and strip off decimal units
on all values but the fourth (R, G, and B only accept whole numbers). */
return (IE <= 8 ? "rgb" : "rgba") + "(" + propertyValue.replace(/\s+/g, ",").replace(/\.(\d)+(?=,)/g, "") + ")";
}
};
})();
}
}
},
/************************
CSS Property Names
************************/
Names: {
/* Camelcase a property name into its JavaScript notation (e.g. "background-color" ==> "backgroundColor").
Camelcasing is used to normalize property names between and across calls. */
camelCase: function (property) {
return property.replace(/-(\w)/g, function (match, subMatch) {
return subMatch.toUpperCase();
});
},
/* For SVG elements, some properties (namely, dimensional ones) are GET/SET via the element's HTML attributes (instead of via CSS styles). */
SVGAttribute: function (property) {
var SVGAttributes = "width|height|x|y|cx|cy|r|rx|ry|x1|x2|y1|y2";
/* Certain browsers require an SVG transform to be applied as an attribute. (Otherwise, application via CSS is preferable due to 3D support.) */
if (IE || (Velocity.State.isAndroid && !Velocity.State.isChrome)) {
SVGAttributes += "|transform";
}
return new RegExp("^(" + SVGAttributes + ")$", "i").test(property);
},
/* Determine whether a property should be set with a vendor prefix. */
/* If a prefixed version of the property exists, return it. Otherwise, return the original property name.
If the property is not at all supported by the browser, return a false flag. */
prefixCheck: function (property) {
/* If this property has already been checked, return the cached value. */
if (Velocity.State.prefixMatches[property]) {
return [ Velocity.State.prefixMatches[property], true ];
} else {
var vendors = [ "", "Webkit", "Moz", "ms", "O" ];
for (var i = 0, vendorsLength = vendors.length; i < vendorsLength; i++) {
var propertyPrefixed;
if (i === 0) {
propertyPrefixed = property;
} else {
/* Capitalize the first letter of the property to conform to JavaScript vendor prefix notation (e.g. webkitFilter). */
propertyPrefixed = vendors[i] + property.replace(/^\w/, function(match) { return match.toUpperCase(); });
}
/* Check if the browser supports this property as prefixed. */
if (Type.isString(Velocity.State.prefixElement.style[propertyPrefixed])) {
/* Cache the match. */
Velocity.State.prefixMatches[property] = propertyPrefixed;
return [ propertyPrefixed, true ];
}
}
/* If the browser doesn't support this property in any form, include a false flag so that the caller can decide how to proceed. */
return [ property, false ];
}
}
},
/************************
CSS Property Values
************************/
Values: {
/* Hex to RGB conversion. Copyright Tim Down: http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb */
hexToRgb: function (hex) {
var shortformRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i,
longformRegex = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i,
rgbParts;
hex = hex.replace(shortformRegex, function (m, r, g, b) {
return r + r + g + g + b + b;
});
rgbParts = longformRegex.exec(hex);
return rgbParts ? [ parseInt(rgbParts[1], 16), parseInt(rgbParts[2], 16), parseInt(rgbParts[3], 16) ] : [ 0, 0, 0 ];
},
isCSSNullValue: function (value) {
/* The browser defaults CSS values that have not been set to either 0 or one of several possible null-value strings.
Thus, we check for both falsiness and these special strings. */
/* Null-value checking is performed to default the special strings to 0 (for the sake of tweening) or their hook
templates as defined as CSS.Hooks (for the sake of hook injection/extraction). */
/* Note: Chrome returns "rgba(0, 0, 0, 0)" for an undefined color whereas IE returns "transparent". */
return (value == 0 || /^(none|auto|transparent|(rgba\(0, ?0, ?0, ?0\)))$/i.test(value));
},
/* Retrieve a property's default unit type. Used for assigning a unit type when one is not supplied by the user. */
getUnitType: function (property) {
if (/^(rotate|skew)/i.test(property)) {
return "deg";
} else if (/(^(scale|scaleX|scaleY|scaleZ|alpha|flexGrow|flexHeight|zIndex|fontWeight)$)|((opacity|red|green|blue|alpha)$)/i.test(property)) {
/* The above properties are unitless. */
return "";
} else {
/* Default to px for all other properties. */
return "px";
}
},
/* HTML elements default to an associated display type when they're not set to display:none. */
/* Note: This function is used for correctly setting the non-"none" display value in certain Velocity redirects, such as fadeIn/Out. */
getDisplayType: function (element) {
var tagName = element && element.tagName.toString().toLowerCase();
if (/^(b|big|i|small|tt|abbr|acronym|cite|code|dfn|em|kbd|strong|samp|var|a|bdo|br|img|map|object|q|script|span|sub|sup|button|input|label|select|textarea)$/i.test(tagName)) {
return "inline";
} else if (/^(li)$/i.test(tagName)) {
return "list-item";
} else if (/^(tr)$/i.test(tagName)) {
return "table-row";
} else if (/^(table)$/i.test(tagName)) {
return "table";
} else if (/^(tbody)$/i.test(tagName)) {
return "table-row-group";
/* Default to "block" when no match is found. */
} else {
return "block";
}
},
/* The class add/remove functions are used to temporarily apply a "velocity-animating" class to elements while they're animating. */
addClass: function (element, className) {
if (element.classList) {
element.classList.add(className);
} else {
element.className += (element.className.length ? " " : "") + className;
}
},
removeClass: function (element, className) {
if (element.classList) {
element.classList.remove(className);
} else {
element.className = element.className.toString().replace(new RegExp("(^|\\s)" + className.split(" ").join("|") + "(\\s|$)", "gi"), " ");
}
}
},
/****************************
Style Getting & Setting
****************************/
/* The singular getPropertyValue, which routes the logic for all normalizations, hooks, and standard CSS properties. */
getPropertyValue: function (element, property, rootPropertyValue, forceStyleLookup) {
/* Get an element's computed property value. */
/* Note: Retrieving the value of a CSS property cannot simply be performed by checking an element's
style attribute (which only reflects user-defined values). Instead, the browser must be queried for a property's
*computed* value. You can read more about getComputedStyle here: https://developer.mozilla.org/en/docs/Web/API/window.getComputedStyle */
function computePropertyValue (element, property) {
/* When box-sizing isn't set to border-box, height and width style values are incorrectly computed when an
element's scrollbars are visible (which expands the element's dimensions). Thus, we defer to the more accurate
offsetHeight/Width property, which includes the total dimensions for interior, border, padding, and scrollbar.
We subtract border and padding to get the sum of interior + scrollbar. */
var computedValue = 0;
/* IE<=8 doesn't support window.getComputedStyle, thus we defer to jQuery, which has an extensive array
of hacks to accurately retrieve IE8 property values. Re-implementing that logic here is not worth bloating the
codebase for a dying browser. The performance repercussions of using jQuery here are minimal since
Velocity is optimized to rarely (and sometimes never) query the DOM. Further, the $.css() codepath isn't that slow. */
if (IE <= 8) {
computedValue = $.css(element, property); /* GET */
/* All other browsers support getComputedStyle. The returned live object reference is cached onto its
associated element so that it does not need to be refetched upon every GET. */
} else {
/* Browsers do not return height and width values for elements that are set to display:"none". Thus, we temporarily
toggle display to the element type's default value. */
var toggleDisplay = false;
if (/^(width|height)$/.test(property) && CSS.getPropertyValue(element, "display") === 0) {
toggleDisplay = true;
CSS.setPropertyValue(element, "display", CSS.Values.getDisplayType(element));
}
function revertDisplay () {
if (toggleDisplay) {
CSS.setPropertyValue(element, "display", "none");
}
}
if (!forceStyleLookup) {
if (property === "height" && CSS.getPropertyValue(element, "boxSizing").toString().toLowerCase() !== "border-box") {
var contentBoxHeight = element.offsetHeight - (parseFloat(CSS.getPropertyValue(element, "borderTopWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "borderBottomWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingTop")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingBottom")) || 0);
revertDisplay();
return contentBoxHeight;
} else if (property === "width" && CSS.getPropertyValue(element, "boxSizing").toString().toLowerCase() !== "border-box") {
var contentBoxWidth = element.offsetWidth - (parseFloat(CSS.getPropertyValue(element, "borderLeftWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "borderRightWidth")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingLeft")) || 0) - (parseFloat(CSS.getPropertyValue(element, "paddingRight")) || 0);
revertDisplay();
return contentBoxWidth;
}
}
var computedStyle;
/* For elements that Velocity hasn't been called on directly (e.g. when Velocity queries the DOM on behalf
of a parent of an element its animating), perform a direct getComputedStyle lookup since the object isn't cached. */
if (Data(element) === undefined) {
computedStyle = window.getComputedStyle(element, null); /* GET */
/* If the computedStyle object has yet to be cached, do so now. */
} else if (!Data(element).computedStyle) {
computedStyle = Data(element).computedStyle = window.getComputedStyle(element, null); /* GET */
/* If computedStyle is cached, use it. */
} else {
computedStyle = Data(element).computedStyle;
}
/* IE and Firefox do not return a value for the generic borderColor -- they only return individual values for each border side's color.
Also, in all browsers, when border colors aren't all the same, a compound value is returned that Velocity isn't setup to parse.
So, as a polyfill for querying individual border side colors, we just return the top border's color and animate all borders from that value. */
if (property === "borderColor") {
property = "borderTopColor";
}
/* IE9 has a bug in which the "filter" property must be accessed from computedStyle using the getPropertyValue method
instead of a direct property lookup. The getPropertyValue method is slower than a direct lookup, which is why we avoid it by default. */
if (IE === 9 && property === "filter") {
computedValue = computedStyle.getPropertyValue(property); /* GET */
} else {
computedValue = computedStyle[property];
}
/* Fall back to the property's style value (if defined) when computedValue returns nothing,
which can happen when the element hasn't been painted. */
if (computedValue === "" || computedValue === null) {
computedValue = element.style[property];
}
revertDisplay();
}
/* For top, right, bottom, and left (TRBL) values that are set to "auto" on elements of "fixed" or "absolute" position,
defer to jQuery for converting "auto" to a numeric value. (For elements with a "static" or "relative" position, "auto" has the same
effect as being set to 0, so no conversion is necessary.) */
/* An example of why numeric conversion is necessary: When an element with "position:absolute" has an untouched "left"
property, which reverts to "auto", left's value is 0 relative to its parent element, but is often non-zero relative
to its *containing* (not parent) element, which is the nearest "position:relative" ancestor or the viewport (and always the viewport in the case of "position:fixed"). */
if (computedValue === "auto" && /^(top|right|bottom|left)$/i.test(property)) {
var position = computePropertyValue(element, "position"); /* GET */
/* For absolute positioning, jQuery's $.position() only returns values for top and left;
right and bottom will have their "auto" value reverted to 0. */
/* Note: A jQuery object must be created here since jQuery doesn't have a low-level alias for $.position().
Not a big deal since we're currently in a GET batch anyway. */
if (position === "fixed" || (position === "absolute" && /top|left/i.test(property))) {
/* Note: jQuery strips the pixel unit from its returned values; we re-add it here to conform with computePropertyValue's behavior. */
computedValue = $(element).position()[property] + "px"; /* GET */
}
}
return computedValue;
}
var propertyValue;
/* If this is a hooked property (e.g. "clipLeft" instead of the root property of "clip"),
extract the hook's value from a normalized rootPropertyValue using CSS.Hooks.extractValue(). */
if (CSS.Hooks.registered[property]) {
var hook = property,
hookRoot = CSS.Hooks.getRoot(hook);
/* If a cached rootPropertyValue wasn't passed in (which Velocity always attempts to do in order to avoid requerying the DOM),
query the DOM for the root property's value. */
if (rootPropertyValue === undefined) {
/* Since the browser is now being directly queried, use the official post-prefixing property name for this lookup. */
rootPropertyValue = CSS.getPropertyValue(element, CSS.Names.prefixCheck(hookRoot)[0]); /* GET */
}
/* If this root has a normalization registered, peform the associated normalization extraction. */
if (CSS.Normalizations.registered[hookRoot]) {
rootPropertyValue = CSS.Normalizations.registered[hookRoot]("extract", element, rootPropertyValue);
}
/* Extract the hook's value. */
propertyValue = CSS.Hooks.extractValue(hook, rootPropertyValue);
/* If this is a normalized property (e.g. "opacity" becomes "filter" in <=IE8) or "translateX" becomes "transform"),
normalize the property's name and value, and handle the special case of transforms. */
/* Note: Normalizing a property is mutually exclusive from hooking a property since hook-extracted values are strictly
numerical and therefore do not require normalization extraction. */
} else if (CSS.Normalizations.registered[property]) {
var normalizedPropertyName,
normalizedPropertyValue;
normalizedPropertyName = CSS.Normalizations.registered[property]("name", element);
/* Transform values are calculated via normalization extraction (see below), which checks against the element's transformCache.
At no point do transform GETs ever actually query the DOM; initial stylesheet values are never processed.
This is because parsing 3D transform matrices is not always accurate and would bloat our codebase;
thus, normalization extraction defaults initial transform values to their zero-values (e.g. 1 for scaleX and 0 for translateX). */
if (normalizedPropertyName !== "transform") {
normalizedPropertyValue = computePropertyValue(element, CSS.Names.prefixCheck(normalizedPropertyName)[0]); /* GET */
/* If the value is a CSS null-value and this property has a hook template, use that zero-value template so that hooks can be extracted from it. */
if (CSS.Values.isCSSNullValue(normalizedPropertyValue) && CSS.Hooks.templates[property]) {
normalizedPropertyValue = CSS.Hooks.templates[property][1];
}
}
propertyValue = CSS.Normalizations.registered[property]("extract", element, normalizedPropertyValue);
}
/* If a (numeric) value wasn't produced via hook extraction or normalization, query the DOM. */
if (!/^[\d-]/.test(propertyValue)) {
/* For SVG elements, dimensional properties (which SVGAttribute() detects) are tweened via
their HTML attribute values instead of their CSS style values. */
if (Data(element) && Data(element).isSVG && CSS.Names.SVGAttribute(property)) {
/* Since the height/width attribute values must be set manually, they don't reflect computed values.
Thus, we use use getBBox() to ensure we always get values for elements with undefined height/width attributes. */
if (/^(height|width)$/i.test(property)) {
/* Firefox throws an error if .getBBox() is called on an SVG that isn't attached to the DOM. */
try {
propertyValue = element.getBBox()[property];
} catch (error) {
propertyValue = 0;
}
/* Otherwise, access the attribute value directly. */
} else {
propertyValue = element.getAttribute(property);
}
} else {
propertyValue = computePropertyValue(element, CSS.Names.prefixCheck(property)[0]); /* GET */
}
}
/* Since property lookups are for animation purposes (which entails computing the numeric delta between start and end values),
convert CSS null-values to an integer of value 0. */
if (CSS.Values.isCSSNullValue(propertyValue)) {
propertyValue = 0;
}
if (Velocity.debug >= 2) console.log("Get " + property + ": " + propertyValue);
return propertyValue;
},
/* The singular setPropertyValue, which routes the logic for all normalizations, hooks, and standard CSS properties. */
setPropertyValue: function(element, property, propertyValue, rootPropertyValue, scrollData) {
var propertyName = property;
/* In order to be subjected to call options and element queueing, scroll animation is routed through Velocity as if it were a standard CSS property. */
if (property === "scroll") {
/* If a container option is present, scroll the container instead of the browser window. */
if (scrollData.container) {
scrollData.container["scroll" + scrollData.direction] = propertyValue;
/* Otherwise, Velocity defaults to scrolling the browser window. */
} else {
if (scrollData.direction === "Left") {
window.scrollTo(propertyValue, scrollData.alternateValue);
} else {
window.scrollTo(scrollData.alternateValue, propertyValue);
}
}
} else {
/* Transforms (translateX, rotateZ, etc.) are applied to a per-element transformCache object, which is manually flushed via flushTransformCache().
Thus, for now, we merely cache transforms being SET. */
if (CSS.Normalizations.registered[property] && CSS.Normalizations.registered[property]("name", element) === "transform") {
/* Perform a normalization injection. */
/* Note: The normalization logic handles the transformCache updating. */
CSS.Normalizations.registered[property]("inject", element, propertyValue);
propertyName = "transform";
propertyValue = Data(element).transformCache[property];
} else {
/* Inject hooks. */
if (CSS.Hooks.registered[property]) {
var hookName = property,
hookRoot = CSS.Hooks.getRoot(property);
/* If a cached rootPropertyValue was not provided, query the DOM for the hookRoot's current value. */
rootPropertyValue = rootPropertyValue || CSS.getPropertyValue(element, hookRoot); /* GET */
propertyValue = CSS.Hooks.injectValue(hookName, propertyValue, rootPropertyValue);
property = hookRoot;
}
/* Normalize names and values. */
if (CSS.Normalizations.registered[property]) {
propertyValue = CSS.Normalizations.registered[property]("inject", element, propertyValue);
property = CSS.Normalizations.registered[property]("name", element);
}
/* Assign the appropriate vendor prefix before performing an official style update. */
propertyName = CSS.Names.prefixCheck(property)[0];
/* A try/catch is used for IE<=8, which throws an error when "invalid" CSS values are set, e.g. a negative width.
Try/catch is avoided for other browsers since it incurs a performance overhead. */
if (IE <= 8) {
try {
element.style[propertyName] = propertyValue;
} catch (error) { if (Velocity.debug) console.log("Browser does not support [" + propertyValue + "] for [" + propertyName + "]"); }
/* SVG elements have their dimensional properties (width, height, x, y, cx, etc.) applied directly as attributes instead of as styles. */
/* Note: IE8 does not support SVG elements, so it's okay that we skip it for SVG animation. */
} else if (Data(element) && Data(element).isSVG && CSS.Names.SVGAttribute(property)) {
/* Note: For SVG attributes, vendor-prefixed property names are never used. */
/* Note: Not all CSS properties can be animated via attributes, but the browser won't throw an error for unsupported properties. */
element.setAttribute(property, propertyValue);
} else {
element.style[propertyName] = propertyValue;
}
if (Velocity.debug >= 2) console.log("Set " + property + " (" + propertyName + "): " + propertyValue);
}
}
/* Return the normalized property name and value in case the caller wants to know how these values were modified before being applied to the DOM. */
return [ propertyName, propertyValue ];
},
/* To increase performance by batching transform updates into a single SET, transforms are not directly applied to an element until flushTransformCache() is called. */
/* Note: Velocity applies transform properties in the same order that they are chronogically introduced to the element's CSS styles. */
flushTransformCache: function(element) {
var transformString = "";
/* Certain browsers require that SVG transforms be applied as an attribute. However, the SVG transform attribute takes a modified version of CSS's transform string
(units are dropped and, except for skewX/Y, subproperties are merged into their master property -- e.g. scaleX and scaleY are merged into scale(X Y). */
if ((IE || (Velocity.State.isAndroid && !Velocity.State.isChrome)) && Data(element).isSVG) {
/* Since transform values are stored in their parentheses-wrapped form, we use a helper function to strip out their numeric values.
Further, SVG transform properties only take unitless (representing pixels) values, so it's okay that parseFloat() strips the unit suffixed to the float value. */
function getTransformFloat (transformProperty) {
return parseFloat(CSS.getPropertyValue(element, transformProperty));
}
/* Create an object to organize all the transforms that we'll apply to the SVG element. To keep the logic simple,
we process *all* transform properties -- even those that may not be explicitly applied (since they default to their zero-values anyway). */
var SVGTransforms = {
translate: [ getTransformFloat("translateX"), getTransformFloat("translateY") ],
skewX: [ getTransformFloat("skewX") ], skewY: [ getTransformFloat("skewY") ],
/* If the scale property is set (non-1), use that value for the scaleX and scaleY values
(this behavior mimics the result of animating all these properties at once on HTML elements). */
scale: getTransformFloat("scale") !== 1 ? [ getTransformFloat("scale"), getTransformFloat("scale") ] : [ getTransformFloat("scaleX"), getTransformFloat("scaleY") ],
/* Note: SVG's rotate transform takes three values: rotation degrees followed by the X and Y values
defining the rotation's origin point. We ignore the origin values (default them to 0). */
rotate: [ getTransformFloat("rotateZ"), 0, 0 ]
};
/* Iterate through the transform properties in the user-defined property map order.
(This mimics the behavior of non-SVG transform animation.) */
$.each(Data(element).transformCache, function(transformName) {
/* Except for with skewX/Y, revert the axis-specific transform subproperties to their axis-free master
properties so that they match up with SVG's accepted transform properties. */
if (/^translate/i.test(transformName)) {
transformName = "translate";
} else if (/^scale/i.test(transformName)) {
transformName = "scale";
} else if (/^rotate/i.test(transformName)) {
transformName = "rotate";
}
/* Check that we haven't yet deleted the property from the SVGTransforms container. */
if (SVGTransforms[transformName]) {
/* Append the transform property in the SVG-supported transform format. As per the spec, surround the space-delimited values in parentheses. */
transformString += transformName + "(" + SVGTransforms[transformName].join(" ") + ")" + " ";
/* After processing an SVG transform property, delete it from the SVGTransforms container so we don't
re-insert the same master property if we encounter another one of its axis-specific properties. */
delete SVGTransforms[transformName];
}
});
} else {
var transformValue,
perspective;
/* Transform properties are stored as members of the transformCache object. Concatenate all the members into a string. */
$.each(Data(element).transformCache, function(transformName) {
transformValue = Data(element).transformCache[transformName];
/* Transform's perspective subproperty must be set first in order to take effect. Store it temporarily. */
if (transformName === "transformPerspective") {
perspective = transformValue;
return true;
}
/* IE9 only supports one rotation type, rotateZ, which it refers to as "rotate". */
if (IE === 9 && transformName === "rotateZ") {
transformName = "rotate";
}
transformString += transformName + transformValue + " ";
});
/* If present, set the perspective subproperty first. */
if (perspective) {
transformString = "perspective" + perspective + " " + transformString;
}
}
CSS.setPropertyValue(element, "transform", transformString);
}
};
/* Register hooks and normalizations. */
CSS.Hooks.register();
CSS.Normalizations.register();
/* Allow hook setting in the same fashion as jQuery's $.css(). */
Velocity.hook = function (elements, arg2, arg3) {
var value = undefined;
elements = sanitizeElements(elements);
$.each(elements, function(i, element) {
/* Initialize Velocity's per-element data cache if this element hasn't previously been animated. */
if (Data(element) === undefined) {
Velocity.init(element);
}
/* Get property value. If an element set was passed in, only return the value for the first element. */
if (arg3 === undefined) {
if (value === undefined) {
value = Velocity.CSS.getPropertyValue(element, arg2);
}
/* Set property value. */
} else {
/* sPV returns an array of the normalized propertyName/propertyValue pair used to update the DOM. */
var adjustedSet = Velocity.CSS.setPropertyValue(element, arg2, arg3);
/* Transform properties don't automatically set. They have to be flushed to the DOM. */
if (adjustedSet[0] === "transform") {
Velocity.CSS.flushTransformCache(element);
}
value = adjustedSet;
}
});
return value;
};
/*****************
Animation
*****************/
var animate = function() {
/******************
Call Chain
******************/
/* Logic for determining what to return to the call stack when exiting out of Velocity. */
function getChain () {
/* If we are using the utility function, attempt to return this call's promise. If no promise library was detected,
default to null instead of returning the targeted elements so that utility function's return value is standardized. */
if (isUtility) {
return promiseData.promise || null;
/* Otherwise, if we're using $.fn, return the jQuery-/Zepto-wrapped element set. */
} else {
return elementsWrapped;
}
}
/*************************
Arguments Assignment
*************************/
/* To allow for expressive CoffeeScript code, Velocity supports an alternative syntax in which "elements" (or "e"), "properties" (or "p"), and "options" (or "o")
objects are defined on a container object that's passed in as Velocity's sole argument. */
/* Note: Some browsers automatically populate arguments with a "properties" object. We detect it by checking for its default "names" property. */
var syntacticSugar = (arguments[0] && (arguments[0].p || (($.isPlainObject(arguments[0].properties) && !arguments[0].properties.names) || Type.isString(arguments[0].properties)))),
/* Whether Velocity was called via the utility function (as opposed to on a jQuery/Zepto object). */
isUtility,
/* When Velocity is called via the utility function ($.Velocity()/Velocity()), elements are explicitly
passed in as the first parameter. Thus, argument positioning varies. We normalize them here. */
elementsWrapped,
argumentIndex;
var elements,
propertiesMap,
options;
/* Detect jQuery/Zepto elements being animated via the $.fn method. */
if (Type.isWrapped(this)) {
isUtility = false;
argumentIndex = 0;
elements = this;
elementsWrapped = this;
/* Otherwise, raw elements are being animated via the utility function. */
} else {
isUtility = true;
argumentIndex = 1;
elements = syntacticSugar ? (arguments[0].elements || arguments[0].e) : arguments[0];
}
elements = sanitizeElements(elements);
if (!elements) {
return;
}
if (syntacticSugar) {
propertiesMap = arguments[0].properties || arguments[0].p;
options = arguments[0].options || arguments[0].o;
} else {
propertiesMap = arguments[argumentIndex];
options = arguments[argumentIndex + 1];
}
/* The length of the element set (in the form of a nodeList or an array of elements) is defaulted to 1 in case a
single raw DOM element is passed in (which doesn't contain a length property). */
var elementsLength = elements.length,
elementsIndex = 0;
/***************************
Argument Overloading
***************************/
/* Support is included for jQuery's argument overloading: $.animate(propertyMap [, duration] [, easing] [, complete]).
Overloading is detected by checking for the absence of an object being passed into options. */
/* Note: The stop and finish actions do not accept animation options, and are therefore excluded from this check. */
if (!/^(stop|finish)$/i.test(propertiesMap) && !$.isPlainObject(options)) {
/* The utility function shifts all arguments one position to the right, so we adjust for that offset. */
var startingArgumentPosition = argumentIndex + 1;
options = {};
/* Iterate through all options arguments */
for (var i = startingArgumentPosition; i < arguments.length; i++) {
/* Treat a number as a duration. Parse it out. */
/* Note: The following RegEx will return true if passed an array with a number as its first item.
Thus, arrays are skipped from this check. */
if (!Type.isArray(arguments[i]) && (/^(fast|normal|slow)$/i.test(arguments[i]) || /^\d/.test(arguments[i]))) {
options.duration = arguments[i];
/* Treat strings and arrays as easings. */
} else if (Type.isString(arguments[i]) || Type.isArray(arguments[i])) {
options.easing = arguments[i];
/* Treat a function as a complete callback. */
} else if (Type.isFunction(arguments[i])) {
options.complete = arguments[i];
}
}
}
/***************
Promises
***************/
var promiseData = {
promise: null,
resolver: null,
rejecter: null
};
/* If this call was made via the utility function (which is the default method of invocation when jQuery/Zepto are not being used), and if
promise support was detected, create a promise object for this call and store references to its resolver and rejecter methods. The resolve
method is used when a call completes naturally or is prematurely stopped by the user. In both cases, completeCall() handles the associated
call cleanup and promise resolving logic. The reject method is used when an invalid set of arguments is passed into a Velocity call. */
/* Note: Velocity employs a call-based queueing architecture, which means that stopping an animating element actually stops the full call that
triggered it -- not that one element exclusively. Similarly, there is one promise per call, and all elements targeted by a Velocity call are
grouped together for the purposes of resolving and rejecting a promise. */
if (isUtility && Velocity.Promise) {
promiseData.promise = new Velocity.Promise(function (resolve, reject) {
promiseData.resolver = resolve;
promiseData.rejecter = reject;
});
}
/*********************
Action Detection
*********************/
/* Velocity's behavior is categorized into "actions": Elements can either be specially scrolled into view,
or they can be started, stopped, or reversed. If a literal or referenced properties map is passed in as Velocity's
first argument, the associated action is "start". Alternatively, "scroll", "reverse", or "stop" can be passed in instead of a properties map. */
var action;
switch (propertiesMap) {
case "scroll":
action = "scroll";
break;
case "reverse":
action = "reverse";
break;
case "finish":
case "stop":
/*******************
Action: Stop
*******************/
/* Clear the currently-active delay on each targeted element. */
$.each(elements, function(i, element) {
if (Data(element) && Data(element).delayTimer) {
/* Stop the timer from triggering its cached next() function. */
clearTimeout(Data(element).delayTimer.setTimeout);
/* Manually call the next() function so that the subsequent queue items can progress. */
if (Data(element).delayTimer.next) {
Data(element).delayTimer.next();
}
delete Data(element).delayTimer;
}
});
var callsToStop = [];
/* When the stop action is triggered, the elements' currently active call is immediately stopped. The active call might have
been applied to multiple elements, in which case all of the call's elements will be stopped. When an element
is stopped, the next item in its animation queue is immediately triggered. */
/* An additional argument may be passed in to clear an element's remaining queued calls. Either true (which defaults to the "fx" queue)
or a custom queue string can be passed in. */
/* Note: The stop command runs prior to Velocity's Queueing phase since its behavior is intended to take effect *immediately*,
regardless of the element's current queue state. */
/* Iterate through every active call. */
$.each(Velocity.State.calls, function(i, activeCall) {
/* Inactive calls are set to false by the logic inside completeCall(). Skip them. */
if (activeCall) {
/* Iterate through the active call's targeted elements. */
$.each(activeCall[1], function(k, activeElement) {
/* If true was passed in as a secondary argument, clear absolutely all calls on this element. Otherwise, only
clear calls associated with the relevant queue. */
/* Call stopping logic works as follows:
- options === true --> stop current default queue calls (and queue:false calls), including remaining queued ones.
- options === undefined --> stop current queue:"" call and all queue:false calls.
- options === false --> stop only queue:false calls.
- options === "custom" --> stop current queue:"custom" call, including remaining queued ones (there is no functionality to only clear the currently-running queue:"custom" call). */
var queueName = (options === undefined) ? "" : options;
if (queueName !== true && (activeCall[2].queue !== queueName) && !(options === undefined && activeCall[2].queue === false)) {
return true;
}
/* Iterate through the calls targeted by the stop command. */
$.each(elements, function(l, element) {
/* Check that this call was applied to the target element. */
if (element === activeElement) {
/* Optionally clear the remaining queued calls. */
if (options === true || Type.isString(options)) {
/* Iterate through the items in the element's queue. */
$.each($.queue(element, Type.isString(options) ? options : ""), function(_, item) {
/* The queue array can contain an "inprogress" string, which we skip. */
if (Type.isFunction(item)) {
/* Pass the item's callback a flag indicating that we want to abort from the queue call.
(Specifically, the queue will resolve the call's associated promise then abort.) */
item(null, true);
}
});
/* Clearing the $.queue() array is achieved by resetting it to []. */
$.queue(element, Type.isString(options) ? options : "", []);
}
if (propertiesMap === "stop") {
/* Since "reverse" uses cached start values (the previous call's endValues), these values must be
changed to reflect the final value that the elements were actually tweened to. */
/* Note: If only queue:false animations are currently running on an element, it won't have a tweensContainer
object. Also, queue:false animations can't be reversed. */
if (Data(element) && Data(element).tweensContainer && queueName !== false) {
$.each(Data(element).tweensContainer, function(m, activeTween) {
activeTween.endValue = activeTween.currentValue;
});
}
callsToStop.push(i);
} else if (propertiesMap === "finish") {
/* To get active tweens to finish immediately, we forcefully shorten their durations to 1ms so that
they finish upon the next rAf tick then proceed with normal call completion logic. */
activeCall[2].duration = 1;
}
}
});
});
}
});
/* Prematurely call completeCall() on each matched active call. Pass an additional flag for "stop" to indicate
that the complete callback and display:none setting should be skipped since we're completing prematurely. */
if (propertiesMap === "stop") {
$.each(callsToStop, function(i, j) {
completeCall(j, true);
});
if (promiseData.promise) {
/* Immediately resolve the promise associated with this stop call since stop runs synchronously. */
promiseData.resolver(elements);
}
}
/* Since we're stopping, and not proceeding with queueing, exit out of Velocity. */
return getChain();
default:
/* Treat a non-empty plain object as a literal properties map. */
if ($.isPlainObject(propertiesMap) && !Type.isEmptyObject(propertiesMap)) {
action = "start";
/****************
Redirects
****************/
/* Check if a string matches a registered redirect (see Redirects above). */
} else if (Type.isString(propertiesMap) && Velocity.Redirects[propertiesMap]) {
var opts = $.extend({}, options),
durationOriginal = opts.duration,
delayOriginal = opts.delay || 0;
/* If the backwards option was passed in, reverse the element set so that elements animate from the last to the first. */
if (opts.backwards === true) {
elements = $.extend(true, [], elements).reverse();
}
/* Individually trigger the redirect for each element in the set to prevent users from having to handle iteration logic in their redirect. */
$.each(elements, function(elementIndex, element) {
/* If the stagger option was passed in, successively delay each element by the stagger value (in ms). Retain the original delay value. */
if (parseFloat(opts.stagger)) {
opts.delay = delayOriginal + (parseFloat(opts.stagger) * elementIndex);
} else if (Type.isFunction(opts.stagger)) {
opts.delay = delayOriginal + opts.stagger.call(element, elementIndex, elementsLength);
}
/* If the drag option was passed in, successively increase/decrease (depending on the presense of opts.backwards)
the duration of each element's animation, using floors to prevent producing very short durations. */
if (opts.drag) {
/* Default the duration of UI pack effects (callouts and transitions) to 1000ms instead of the usual default duration of 400ms. */
opts.duration = parseFloat(durationOriginal) || (/^(callout|transition)/.test(propertiesMap) ? 1000 : DURATION_DEFAULT);
/* For each element, take the greater duration of: A) animation completion percentage relative to the original duration,
B) 75% of the original duration, or C) a 200ms fallback (in case duration is already set to a low value).
The end result is a baseline of 75% of the redirect's duration that increases/decreases as the end of the element set is approached. */
opts.duration = Math.max(opts.duration * (opts.backwards ? 1 - elementIndex/elementsLength : (elementIndex + 1) / elementsLength), opts.duration * 0.75, 200);
}
/* Pass in the call's opts object so that the redirect can optionally extend it. It defaults to an empty object instead of null to
reduce the opts checking logic required inside the redirect. */
Velocity.Redirects[propertiesMap].call(element, element, opts || {}, elementIndex, elementsLength, elements, promiseData.promise ? promiseData : undefined);
});
/* Since the animation logic resides within the redirect's own code, abort the remainder of this call.
(The performance overhead up to this point is virtually non-existant.) */
/* Note: The jQuery call chain is kept intact by returning the complete element set. */
return getChain();
} else {
var abortError = "Velocity: First argument (" + propertiesMap + ") was not a property map, a known action, or a registered redirect. Aborting.";
if (promiseData.promise) {
promiseData.rejecter(new Error(abortError));
} else {
console.log(abortError);
}
return getChain();
}
}
/**************************
Call-Wide Variables
**************************/
/* A container for CSS unit conversion ratios (e.g. %, rem, and em ==> px) that is used to cache ratios across all elements
being animated in a single Velocity call. Calculating unit ratios necessitates DOM querying and updating, and is therefore
avoided (via caching) wherever possible. This container is call-wide instead of page-wide to avoid the risk of using stale
conversion metrics across Velocity animations that are not immediately consecutively chained. */
var callUnitConversionData = {
lastParent: null,
lastPosition: null,
lastFontSize: null,
lastPercentToPxWidth: null,
lastPercentToPxHeight: null,
lastEmToPx: null,
remToPx: null,
vwToPx: null,
vhToPx: null
};
/* A container for all the ensuing tween data and metadata associated with this call. This container gets pushed to the page-wide
Velocity.State.calls array that is processed during animation ticking. */
var call = [];
/************************
Element Processing
************************/
/* Element processing consists of three parts -- data processing that cannot go stale and data processing that *can* go stale (i.e. third-party style modifications):
1) Pre-Queueing: Element-wide variables, including the element's data storage, are instantiated. Call options are prepared. If triggered, the Stop action is executed.
2) Queueing: The logic that runs once this call has reached its point of execution in the element's $.queue() stack. Most logic is placed here to avoid risking it becoming stale.
3) Pushing: Consolidation of the tween data followed by its push onto the global in-progress calls container.
*/
function processElement () {
/*************************
Part I: Pre-Queueing
*************************/
/***************************
Element-Wide Variables
***************************/
var element = this,
/* The runtime opts object is the extension of the current call's options and Velocity's page-wide option defaults. */
opts = $.extend({}, Velocity.defaults, options),
/* A container for the processed data associated with each property in the propertyMap.
(Each property in the map produces its own "tween".) */
tweensContainer = {},
elementUnitConversionData;
/******************
Element Init
******************/
if (Data(element) === undefined) {
Velocity.init(element);
}
/******************
Option: Delay
******************/
/* Since queue:false doesn't respect the item's existing queue, we avoid injecting its delay here (it's set later on). */
/* Note: Velocity rolls its own delay function since jQuery doesn't have a utility alias for $.fn.delay()
(and thus requires jQuery element creation, which we avoid since its overhead includes DOM querying). */
if (parseFloat(opts.delay) && opts.queue !== false) {
$.queue(element, opts.queue, function(next) {
/* This is a flag used to indicate to the upcoming completeCall() function that this queue entry was initiated by Velocity. See completeCall() for further details. */
Velocity.velocityQueueEntryFlag = true;
/* The ensuing queue item (which is assigned to the "next" argument that $.queue() automatically passes in) will be triggered after a setTimeout delay.
The setTimeout is stored so that it can be subjected to clearTimeout() if this animation is prematurely stopped via Velocity's "stop" command. */
Data(element).delayTimer = {
setTimeout: setTimeout(next, parseFloat(opts.delay)),
next: next
};
});
}
/*********************
Option: Duration
*********************/
/* Support for jQuery's named durations. */
switch (opts.duration.toString().toLowerCase()) {
case "fast":
opts.duration = 200;
break;
case "normal":
opts.duration = DURATION_DEFAULT;
break;
case "slow":
opts.duration = 600;
break;
default:
/* Remove the potential "ms" suffix and default to 1 if the user is attempting to set a duration of 0 (in order to produce an immediate style change). */
opts.duration = parseFloat(opts.duration) || 1;
}
/************************
Global Option: Mock
************************/
if (Velocity.mock !== false) {
/* In mock mode, all animations are forced to 1ms so that they occur immediately upon the next rAF tick.
Alternatively, a multiplier can be passed in to time remap all delays and durations. */
if (Velocity.mock === true) {
opts.duration = opts.delay = 1;
} else {
opts.duration *= parseFloat(Velocity.mock) || 1;
opts.delay *= parseFloat(Velocity.mock) || 1;
}
}
/*******************
Option: Easing
*******************/
opts.easing = getEasing(opts.easing, opts.duration);
/**********************
Option: Callbacks
**********************/
/* Callbacks must functions. Otherwise, default to null. */
if (opts.begin && !Type.isFunction(opts.begin)) {
opts.begin = null;
}
if (opts.progress && !Type.isFunction(opts.progress)) {
opts.progress = null;
}
if (opts.complete && !Type.isFunction(opts.complete)) {
opts.complete = null;
}
/*********************************
Option: Display & Visibility
*********************************/
/* Refer to Velocity's documentation (VelocityJS.org/#displayAndVisibility) for a description of the display and visibility options' behavior. */
/* Note: We strictly check for undefined instead of falsiness because display accepts an empty string value. */
if (opts.display !== undefined && opts.display !== null) {
opts.display = opts.display.toString().toLowerCase();
/* Users can pass in a special "auto" value to instruct Velocity to set the element to its default display value. */
if (opts.display === "auto") {
opts.display = Velocity.CSS.Values.getDisplayType(element);
}
}
if (opts.visibility !== undefined && opts.visibility !== null) {
opts.visibility = opts.visibility.toString().toLowerCase();
}
/**********************
Option: mobileHA
**********************/
/* When set to true, and if this is a mobile device, mobileHA automatically enables hardware acceleration (via a null transform hack)
on animating elements. HA is removed from the element at the completion of its animation. */
/* Note: Android Gingerbread doesn't support HA. If a null transform hack (mobileHA) is in fact set, it will prevent other tranform subproperties from taking effect. */
/* Note: You can read more about the use of mobileHA in Velocity's documentation: VelocityJS.org/#mobileHA. */
opts.mobileHA = (opts.mobileHA && Velocity.State.isMobile && !Velocity.State.isGingerbread);
/***********************
Part II: Queueing
***********************/
/* When a set of elements is targeted by a Velocity call, the set is broken up and each element has the current Velocity call individually queued onto it.
In this way, each element's existing queue is respected; some elements may already be animating and accordingly should not have this current Velocity call triggered immediately. */
/* In each queue, tween data is processed for each animating property then pushed onto the call-wide calls array. When the last element in the set has had its tweens processed,
the call array is pushed to Velocity.State.calls for live processing by the requestAnimationFrame tick. */
function buildQueue (next) {
/*******************
Option: Begin
*******************/
/* The begin callback is fired once per call -- not once per elemenet -- and is passed the full raw DOM element set as both its context and its first argument. */
if (opts.begin && elementsIndex === 0) {
/* We throw callbacks in a setTimeout so that thrown errors don't halt the execution of Velocity itself. */
try {
opts.begin.call(elements, elements);
} catch (error) {
setTimeout(function() { throw error; }, 1);
}
}
/*****************************************
Tween Data Construction (for Scroll)
*****************************************/
/* Note: In order to be subjected to chaining and animation options, scroll's tweening is routed through Velocity as if it were a standard CSS property animation. */
if (action === "scroll") {
/* The scroll action uniquely takes an optional "offset" option -- specified in pixels -- that offsets the targeted scroll position. */
var scrollDirection = (/^x$/i.test(opts.axis) ? "Left" : "Top"),
scrollOffset = parseFloat(opts.offset) || 0,
scrollPositionCurrent,
scrollPositionCurrentAlternate,
scrollPositionEnd;
/* Scroll also uniquely takes an optional "container" option, which indicates the parent element that should be scrolled --
as opposed to the browser window itself. This is useful for scrolling toward an element that's inside an overflowing parent element. */
if (opts.container) {
/* Ensure that either a jQuery object or a raw DOM element was passed in. */
if (Type.isWrapped(opts.container) || Type.isNode(opts.container)) {
/* Extract the raw DOM element from the jQuery wrapper. */
opts.container = opts.container[0] || opts.container;
/* Note: Unlike other properties in Velocity, the browser's scroll position is never cached since it so frequently changes
(due to the user's natural interaction with the page). */
scrollPositionCurrent = opts.container["scroll" + scrollDirection]; /* GET */
/* $.position() values are relative to the container's currently viewable area (without taking into account the container's true dimensions
-- say, for example, if the container was not overflowing). Thus, the scroll end value is the sum of the child element's position *and*
the scroll container's current scroll position. */
scrollPositionEnd = (scrollPositionCurrent + $(element).position()[scrollDirection.toLowerCase()]) + scrollOffset; /* GET */
/* If a value other than a jQuery object or a raw DOM element was passed in, default to null so that this option is ignored. */
} else {
opts.container = null;
}
} else {
/* If the window itself is being scrolled -- not a containing element -- perform a live scroll position lookup using
the appropriate cached property names (which differ based on browser type). */
scrollPositionCurrent = Velocity.State.scrollAnchor[Velocity.State["scrollProperty" + scrollDirection]]; /* GET */
/* When scrolling the browser window, cache the alternate axis's current value since window.scrollTo() doesn't let us change only one value at a time. */
scrollPositionCurrentAlternate = Velocity.State.scrollAnchor[Velocity.State["scrollProperty" + (scrollDirection === "Left" ? "Top" : "Left")]]; /* GET */
/* Unlike $.position(), $.offset() values are relative to the browser window's true dimensions -- not merely its currently viewable area --
and therefore end values do not need to be compounded onto current values. */
scrollPositionEnd = $(element).offset()[scrollDirection.toLowerCase()] + scrollOffset; /* GET */
}
/* Since there's only one format that scroll's associated tweensContainer can take, we create it manually. */
tweensContainer = {
scroll: {
rootPropertyValue: false,
startValue: scrollPositionCurrent,
currentValue: scrollPositionCurrent,
endValue: scrollPositionEnd,
unitType: "",
easing: opts.easing,
scrollData: {
container: opts.container,
direction: scrollDirection,
alternateValue: scrollPositionCurrentAlternate
}
},
element: element
};
if (Velocity.debug) console.log("tweensContainer (scroll): ", tweensContainer.scroll, element);
/******************************************
Tween Data Construction (for Reverse)
******************************************/
/* Reverse acts like a "start" action in that a property map is animated toward. The only difference is
that the property map used for reverse is the inverse of the map used in the previous call. Thus, we manipulate
the previous call to construct our new map: use the previous map's end values as our new map's start values. Copy over all other data. */
/* Note: Reverse can be directly called via the "reverse" parameter, or it can be indirectly triggered via the loop option. (Loops are composed of multiple reverses.) */
/* Note: Reverse calls do not need to be consecutively chained onto a currently-animating element in order to operate on cached values;
there is no harm to reverse being called on a potentially stale data cache since reverse's behavior is simply defined
as reverting to the element's values as they were prior to the previous *Velocity* call. */
} else if (action === "reverse") {
/* Abort if there is no prior animation data to reverse to. */
if (!Data(element).tweensContainer) {
/* Dequeue the element so that this queue entry releases itself immediately, allowing subsequent queue entries to run. */
$.dequeue(element, opts.queue);
return;
} else {
/*********************
Options Parsing
*********************/
/* If the element was hidden via the display option in the previous call,
revert display to "auto" prior to reversal so that the element is visible again. */
if (Data(element).opts.display === "none") {
Data(element).opts.display = "auto";
}
if (Data(element).opts.visibility === "hidden") {
Data(element).opts.visibility = "visible";
}
/* If the loop option was set in the previous call, disable it so that "reverse" calls aren't recursively generated.
Further, remove the previous call's callback options; typically, users do not want these to be refired. */
Data(element).opts.loop = false;
Data(element).opts.begin = null;
Data(element).opts.complete = null;
/* Since we're extending an opts object that has already been extended with the defaults options object,
we remove non-explicitly-defined properties that are auto-assigned values. */
if (!options.easing) {
delete opts.easing;
}
if (!options.duration) {
delete opts.duration;
}
/* The opts object used for reversal is an extension of the options object optionally passed into this
reverse call plus the options used in the previous Velocity call. */
opts = $.extend({}, Data(element).opts, opts);
/*************************************
Tweens Container Reconstruction
*************************************/
/* Create a deepy copy (indicated via the true flag) of the previous call's tweensContainer. */
var lastTweensContainer = $.extend(true, {}, Data(element).tweensContainer);
/* Manipulate the previous tweensContainer by replacing its end values and currentValues with its start values. */
for (var lastTween in lastTweensContainer) {
/* In addition to tween data, tweensContainers contain an element property that we ignore here. */
if (lastTween !== "element") {
var lastStartValue = lastTweensContainer[lastTween].startValue;
lastTweensContainer[lastTween].startValue = lastTweensContainer[lastTween].currentValue = lastTweensContainer[lastTween].endValue;
lastTweensContainer[lastTween].endValue = lastStartValue;
/* Easing is the only option that embeds into the individual tween data (since it can be defined on a per-property basis).
Accordingly, every property's easing value must be updated when an options object is passed in with a reverse call.
The side effect of this extensibility is that all per-property easing values are forcefully reset to the new value. */
if (!Type.isEmptyObject(options)) {
lastTweensContainer[lastTween].easing = opts.easing;
}
if (Velocity.debug) console.log("reverse tweensContainer (" + lastTween + "): " + JSON.stringify(lastTweensContainer[lastTween]), element);
}
}
tweensContainer = lastTweensContainer;
}
/*****************************************
Tween Data Construction (for Start)
*****************************************/
} else if (action === "start") {
/*************************
Value Transferring
*************************/
/* If this queue entry follows a previous Velocity-initiated queue entry *and* if this entry was created
while the element was in the process of being animated by Velocity, then this current call is safe to use
the end values from the prior call as its start values. Velocity attempts to perform this value transfer
process whenever possible in order to avoid requerying the DOM. */
/* If values aren't transferred from a prior call and start values were not forcefed by the user (more on this below),
then the DOM is queried for the element's current values as a last resort. */
/* Note: Conversely, animation reversal (and looping) *always* perform inter-call value transfers; they never requery the DOM. */
var lastTweensContainer;
/* The per-element isAnimating flag is used to indicate whether it's safe (i.e. the data isn't stale)
to transfer over end values to use as start values. If it's set to true and there is a previous
Velocity call to pull values from, do so. */
if (Data(element).tweensContainer && Data(element).isAnimating === true) {
lastTweensContainer = Data(element).tweensContainer;
}
/***************************
Tween Data Calculation
***************************/
/* This function parses property data and defaults endValue, easing, and startValue as appropriate. */
/* Property map values can either take the form of 1) a single value representing the end value,
or 2) an array in the form of [ endValue, [, easing] [, startValue] ].
The optional third parameter is a forcefed startValue to be used instead of querying the DOM for
the element's current value. Read Velocity's docmentation to learn more about forcefeeding: VelocityJS.org/#forcefeeding */
function parsePropertyValue (valueData, skipResolvingEasing) {
var endValue = undefined,
easing = undefined,
startValue = undefined;
/* Handle the array format, which can be structured as one of three potential overloads:
A) [ endValue, easing, startValue ], B) [ endValue, easing ], or C) [ endValue, startValue ] */
if (Type.isArray(valueData)) {
/* endValue is always the first item in the array. Don't bother validating endValue's value now
since the ensuing property cycling logic does that. */
endValue = valueData[0];
/* Two-item array format: If the second item is a number, function, or hex string, treat it as a
start value since easings can only be non-hex strings or arrays. */
if ((!Type.isArray(valueData[1]) && /^[\d-]/.test(valueData[1])) || Type.isFunction(valueData[1]) || CSS.RegEx.isHex.test(valueData[1])) {
startValue = valueData[1];
/* Two or three-item array: If the second item is a non-hex string or an array, treat it as an easing. */
} else if ((Type.isString(valueData[1]) && !CSS.RegEx.isHex.test(valueData[1])) || Type.isArray(valueData[1])) {
easing = skipResolvingEasing ? valueData[1] : getEasing(valueData[1], opts.duration);
/* Don't bother validating startValue's value now since the ensuing property cycling logic inherently does that. */
if (valueData[2] !== undefined) {
startValue = valueData[2];
}
}
/* Handle the single-value format. */
} else {
endValue = valueData;
}
/* Default to the call's easing if a per-property easing type was not defined. */
if (!skipResolvingEasing) {
easing = easing || opts.easing;
}
/* If functions were passed in as values, pass the function the current element as its context,
plus the element's index and the element set's size as arguments. Then, assign the returned value. */
if (Type.isFunction(endValue)) {
endValue = endValue.call(element, elementsIndex, elementsLength);
}
if (Type.isFunction(startValue)) {
startValue = startValue.call(element, elementsIndex, elementsLength);
}
/* Allow startValue to be left as undefined to indicate to the ensuing code that its value was not forcefed. */
return [ endValue || 0, easing, startValue ];
}
/* Cycle through each property in the map, looking for shorthand color properties (e.g. "color" as opposed to "colorRed"). Inject the corresponding
colorRed, colorGreen, and colorBlue RGB component tweens into the propertiesMap (which Velocity understands) and remove the shorthand property. */
$.each(propertiesMap, function(property, value) {
/* Find shorthand color properties that have been passed a hex string. */
if (RegExp("^" + CSS.Lists.colors.join("$|^") + "$").test(property)) {
/* Parse the value data for each shorthand. */
var valueData = parsePropertyValue(value, true),
endValue = valueData[0],
easing = valueData[1],
startValue = valueData[2];
if (CSS.RegEx.isHex.test(endValue)) {
/* Convert the hex strings into their RGB component arrays. */
var colorComponents = [ "Red", "Green", "Blue" ],
endValueRGB = CSS.Values.hexToRgb(endValue),
startValueRGB = startValue ? CSS.Values.hexToRgb(startValue) : undefined;
/* Inject the RGB component tweens into propertiesMap. */
for (var i = 0; i < colorComponents.length; i++) {
var dataArray = [ endValueRGB[i] ];
if (easing) {
dataArray.push(easing);
}
if (startValueRGB !== undefined) {
dataArray.push(startValueRGB[i]);
}
propertiesMap[property + colorComponents[i]] = dataArray;
}
/* Remove the intermediary shorthand property entry now that we've processed it. */
delete propertiesMap[property];
}
}
});
/* Create a tween out of each property, and append its associated data to tweensContainer. */
for (var property in propertiesMap) {
/**************************
Start Value Sourcing
**************************/
/* Parse out endValue, easing, and startValue from the property's data. */
var valueData = parsePropertyValue(propertiesMap[property]),
endValue = valueData[0],
easing = valueData[1],
startValue = valueData[2];
/* Now that the original property name's format has been used for the parsePropertyValue() lookup above,
we force the property to its camelCase styling to normalize it for manipulation. */
property = CSS.Names.camelCase(property);
/* In case this property is a hook, there are circumstances where we will intend to work on the hook's root property and not the hooked subproperty. */
var rootProperty = CSS.Hooks.getRoot(property),
rootPropertyValue = false;
/* Other than for the dummy tween property, properties that are not supported by the browser (and do not have an associated normalization) will
inherently produce no style changes when set, so they are skipped in order to decrease animation tick overhead.
Property support is determined via prefixCheck(), which returns a false flag when no supported is detected. */
/* Note: Since SVG elements have some of their properties directly applied as HTML attributes,
there is no way to check for their explicit browser support, and so we skip skip this check for them. */
if (!Data(element).isSVG && rootProperty !== "tween" && CSS.Names.prefixCheck(rootProperty)[1] === false && CSS.Normalizations.registered[rootProperty] === undefined) {
if (Velocity.debug) console.log("Skipping [" + rootProperty + "] due to a lack of browser support.");
continue;
}
/* If the display option is being set to a non-"none" (e.g. "block") and opacity (filter on IE<=8) is being
animated to an endValue of non-zero, the user's intention is to fade in from invisible, thus we forcefeed opacity
a startValue of 0 if its startValue hasn't already been sourced by value transferring or prior forcefeeding. */
if (((opts.display !== undefined && opts.display !== null && opts.display !== "none") || (opts.visibility !== undefined && opts.visibility !== "hidden")) && /opacity|filter/.test(property) && !startValue && endValue !== 0) {
startValue = 0;
}
/* If values have been transferred from the previous Velocity call, extract the endValue and rootPropertyValue
for all of the current call's properties that were *also* animated in the previous call. */
/* Note: Value transferring can optionally be disabled by the user via the _cacheValues option. */
if (opts._cacheValues && lastTweensContainer && lastTweensContainer[property]) {
if (startValue === undefined) {
startValue = lastTweensContainer[property].endValue + lastTweensContainer[property].unitType;
}
/* The previous call's rootPropertyValue is extracted from the element's data cache since that's the
instance of rootPropertyValue that gets freshly updated by the tweening process, whereas the rootPropertyValue
attached to the incoming lastTweensContainer is equal to the root property's value prior to any tweening. */
rootPropertyValue = Data(element).rootPropertyValueCache[rootProperty];
/* If values were not transferred from a previous Velocity call, query the DOM as needed. */
} else {
/* Handle hooked properties. */
if (CSS.Hooks.registered[property]) {
if (startValue === undefined) {
rootPropertyValue = CSS.getPropertyValue(element, rootProperty); /* GET */
/* Note: The following getPropertyValue() call does not actually trigger a DOM query;
getPropertyValue() will extract the hook from rootPropertyValue. */
startValue = CSS.getPropertyValue(element, property, rootPropertyValue);
/* If startValue is already defined via forcefeeding, do not query the DOM for the root property's value;
just grab rootProperty's zero-value template from CSS.Hooks. This overwrites the element's actual
root property value (if one is set), but this is acceptable since the primary reason users forcefeed is
to avoid DOM queries, and thus we likewise avoid querying the DOM for the root property's value. */
} else {
/* Grab this hook's zero-value template, e.g. "0px 0px 0px black". */
rootPropertyValue = CSS.Hooks.templates[rootProperty][1];
}
/* Handle non-hooked properties that haven't already been defined via forcefeeding. */
} else if (startValue === undefined) {
startValue = CSS.getPropertyValue(element, property); /* GET */
}
}
/**************************
Value Data Extraction
**************************/
var separatedValue,
endValueUnitType,
startValueUnitType,
operator = false;
/* Separates a property value into its numeric value and its unit type. */
function separateValue (property, value) {
var unitType,
numericValue;
numericValue = (value || "0")
.toString()
.toLowerCase()
/* Match the unit type at the end of the value. */
.replace(/[%A-z]+$/, function(match) {
/* Grab the unit type. */
unitType = match;
/* Strip the unit type off of value. */
return "";
});
/* If no unit type was supplied, assign one that is appropriate for this property (e.g. "deg" for rotateZ or "px" for width). */
if (!unitType) {
unitType = CSS.Values.getUnitType(property);
}
return [ numericValue, unitType ];
}
/* Separate startValue. */
separatedValue = separateValue(property, startValue);
startValue = separatedValue[0];
startValueUnitType = separatedValue[1];
/* Separate endValue, and extract a value operator (e.g. "+=", "-=") if one exists. */
separatedValue = separateValue(property, endValue);
endValue = separatedValue[0].replace(/^([+-\/*])=/, function(match, subMatch) {
operator = subMatch;
/* Strip the operator off of the value. */
return "";
});
endValueUnitType = separatedValue[1];
/* Parse float values from endValue and startValue. Default to 0 if NaN is returned. */
startValue = parseFloat(startValue) || 0;
endValue = parseFloat(endValue) || 0;
/***************************************
Property-Specific Value Conversion
***************************************/
/* Custom support for properties that don't actually accept the % unit type, but where pollyfilling is trivial and relatively foolproof. */
if (endValueUnitType === "%") {
/* A %-value fontSize/lineHeight is relative to the parent's fontSize (as opposed to the parent's dimensions),
which is identical to the em unit's behavior, so we piggyback off of that. */
if (/^(fontSize|lineHeight)$/.test(property)) {
/* Convert % into an em decimal value. */
endValue = endValue / 100;
endValueUnitType = "em";
/* For scaleX and scaleY, convert the value into its decimal format and strip off the unit type. */
} else if (/^scale/.test(property)) {
endValue = endValue / 100;
endValueUnitType = "";
/* For RGB components, take the defined percentage of 255 and strip off the unit type. */
} else if (/(Red|Green|Blue)$/i.test(property)) {
endValue = (endValue / 100) * 255;
endValueUnitType = "";
}
}
/***************************
Unit Ratio Calculation
***************************/
/* When queried, the browser returns (most) CSS property values in pixels. Therefore, if an endValue with a unit type of
%, em, or rem is animated toward, startValue must be converted from pixels into the same unit type as endValue in order
for value manipulation logic (increment/decrement) to proceed. Further, if the startValue was forcefed or transferred
from a previous call, startValue may also not be in pixels. Unit conversion logic therefore consists of two steps:
1) Calculating the ratio of %/em/rem/vh/vw relative to pixels
2) Converting startValue into the same unit of measurement as endValue based on these ratios. */
/* Unit conversion ratios are calculated by inserting a sibling node next to the target node, copying over its position property,
setting values with the target unit type then comparing the returned pixel value. */
/* Note: Even if only one of these unit types is being animated, all unit ratios are calculated at once since the overhead
of batching the SETs and GETs together upfront outweights the potential overhead
of layout thrashing caused by re-querying for uncalculated ratios for subsequently-processed properties. */
/* Todo: Shift this logic into the calls' first tick instance so that it's synced with RAF. */
function calculateUnitRatios () {
/************************
Same Ratio Checks
************************/
/* The properties below are used to determine whether the element differs sufficiently from this call's
previously iterated element to also differ in its unit conversion ratios. If the properties match up with those
of the prior element, the prior element's conversion ratios are used. Like most optimizations in Velocity,
this is done to minimize DOM querying. */
var sameRatioIndicators = {
myParent: element.parentNode || document.body, /* GET */
position: CSS.getPropertyValue(element, "position"), /* GET */
fontSize: CSS.getPropertyValue(element, "fontSize") /* GET */
},
/* Determine if the same % ratio can be used. % is based on the element's position value and its parent's width and height dimensions. */
samePercentRatio = ((sameRatioIndicators.position === callUnitConversionData.lastPosition) && (sameRatioIndicators.myParent === callUnitConversionData.lastParent)),
/* Determine if the same em ratio can be used. em is relative to the element's fontSize. */
sameEmRatio = (sameRatioIndicators.fontSize === callUnitConversionData.lastFontSize);
/* Store these ratio indicators call-wide for the next element to compare against. */
callUnitConversionData.lastParent = sameRatioIndicators.myParent;
callUnitConversionData.lastPosition = sameRatioIndicators.position;
callUnitConversionData.lastFontSize = sameRatioIndicators.fontSize;
/***************************
Element-Specific Units
***************************/
/* Note: IE8 rounds to the nearest pixel when returning CSS values, thus we perform conversions using a measurement
of 100 (instead of 1) to give our ratios a precision of at least 2 decimal values. */
var measurement = 100,
unitRatios = {};
if (!sameEmRatio || !samePercentRatio) {
var dummy = Data(element).isSVG ? document.createElementNS("http://www.w3.org/2000/svg", "rect") : document.createElement("div");
Velocity.init(dummy);
sameRatioIndicators.myParent.appendChild(dummy);
/* To accurately and consistently calculate conversion ratios, the element's cascaded overflow and box-sizing are stripped.
Similarly, since width/height can be artificially constrained by their min-/max- equivalents, these are controlled for as well. */
/* Note: Overflow must be also be controlled for per-axis since the overflow property overwrites its per-axis values. */
$.each([ "overflow", "overflowX", "overflowY" ], function(i, property) {
Velocity.CSS.setPropertyValue(dummy, property, "hidden");
});
Velocity.CSS.setPropertyValue(dummy, "position", sameRatioIndicators.position);
Velocity.CSS.setPropertyValue(dummy, "fontSize", sameRatioIndicators.fontSize);
Velocity.CSS.setPropertyValue(dummy, "boxSizing", "content-box");
/* width and height act as our proxy properties for measuring the horizontal and vertical % ratios. */
$.each([ "minWidth", "maxWidth", "width", "minHeight", "maxHeight", "height" ], function(i, property) {
Velocity.CSS.setPropertyValue(dummy, property, measurement + "%");
});
/* paddingLeft arbitrarily acts as our proxy property for the em ratio. */
Velocity.CSS.setPropertyValue(dummy, "paddingLeft", measurement + "em");
/* Divide the returned value by the measurement to get the ratio between 1% and 1px. Default to 1 since working with 0 can produce Infinite. */
unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth = (parseFloat(CSS.getPropertyValue(dummy, "width", null, true)) || 1) / measurement; /* GET */
unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight = (parseFloat(CSS.getPropertyValue(dummy, "height", null, true)) || 1) / measurement; /* GET */
unitRatios.emToPx = callUnitConversionData.lastEmToPx = (parseFloat(CSS.getPropertyValue(dummy, "paddingLeft")) || 1) / measurement; /* GET */
sameRatioIndicators.myParent.removeChild(dummy);
} else {
unitRatios.emToPx = callUnitConversionData.lastEmToPx;
unitRatios.percentToPxWidth = callUnitConversionData.lastPercentToPxWidth;
unitRatios.percentToPxHeight = callUnitConversionData.lastPercentToPxHeight;
}
/***************************
Element-Agnostic Units
***************************/
/* Whereas % and em ratios are determined on a per-element basis, the rem unit only needs to be checked
once per call since it's exclusively dependant upon document.body's fontSize. If this is the first time
that calculateUnitRatios() is being run during this call, remToPx will still be set to its default value of null,
so we calculate it now. */
if (callUnitConversionData.remToPx === null) {
/* Default to browsers' default fontSize of 16px in the case of 0. */
callUnitConversionData.remToPx = parseFloat(CSS.getPropertyValue(document.body, "fontSize")) || 16; /* GET */
}
/* Similarly, viewport units are %-relative to the window's inner dimensions. */
if (callUnitConversionData.vwToPx === null) {
callUnitConversionData.vwToPx = parseFloat(window.innerWidth) / 100; /* GET */
callUnitConversionData.vhToPx = parseFloat(window.innerHeight) / 100; /* GET */
}
unitRatios.remToPx = callUnitConversionData.remToPx;
unitRatios.vwToPx = callUnitConversionData.vwToPx;
unitRatios.vhToPx = callUnitConversionData.vhToPx;
if (Velocity.debug >= 1) console.log("Unit ratios: " + JSON.stringify(unitRatios), element);
return unitRatios;
}
/********************
Unit Conversion
********************/
/* The * and / operators, which are not passed in with an associated unit, inherently use startValue's unit. Skip value and unit conversion. */
if (/[\/*]/.test(operator)) {
endValueUnitType = startValueUnitType;
/* If startValue and endValue differ in unit type, convert startValue into the same unit type as endValue so that if endValueUnitType
is a relative unit (%, em, rem), the values set during tweening will continue to be accurately relative even if the metrics they depend
on are dynamically changing during the course of the animation. Conversely, if we always normalized into px and used px for setting values, the px ratio
would become stale if the original unit being animated toward was relative and the underlying metrics change during the animation. */
/* Since 0 is 0 in any unit type, no conversion is necessary when startValue is 0 -- we just start at 0 with endValueUnitType. */
} else if ((startValueUnitType !== endValueUnitType) && startValue !== 0) {
/* Unit conversion is also skipped when endValue is 0, but *startValueUnitType* must be used for tween values to remain accurate. */
/* Note: Skipping unit conversion here means that if endValueUnitType was originally a relative unit, the animation won't relatively
match the underlying metrics if they change, but this is acceptable since we're animating toward invisibility instead of toward visibility,
which remains past the point of the animation's completion. */
if (endValue === 0) {
endValueUnitType = startValueUnitType;
} else {
/* By this point, we cannot avoid unit conversion (it's undesirable since it causes layout thrashing).
If we haven't already, we trigger calculateUnitRatios(), which runs once per element per call. */
elementUnitConversionData = elementUnitConversionData || calculateUnitRatios();
/* The following RegEx matches CSS properties that have their % values measured relative to the x-axis. */
/* Note: W3C spec mandates that all of margin and padding's properties (even top and bottom) are %-relative to the *width* of the parent element. */
var axis = (/margin|padding|left|right|width|text|word|letter/i.test(property) || /X$/.test(property) || property === "x") ? "x" : "y";
/* In order to avoid generating n^2 bespoke conversion functions, unit conversion is a two-step process:
1) Convert startValue into pixels. 2) Convert this new pixel value into endValue's unit type. */
switch (startValueUnitType) {
case "%":
/* Note: translateX and translateY are the only properties that are %-relative to an element's own dimensions -- not its parent's dimensions.
Velocity does not include a special conversion process to account for this behavior. Therefore, animating translateX/Y from a % value
to a non-% value will produce an incorrect start value. Fortunately, this sort of cross-unit conversion is rarely done by users in practice. */
startValue *= (axis === "x" ? elementUnitConversionData.percentToPxWidth : elementUnitConversionData.percentToPxHeight);
break;
case "px":
/* px acts as our midpoint in the unit conversion process; do nothing. */
break;
default:
startValue *= elementUnitConversionData[startValueUnitType + "ToPx"];
}
/* Invert the px ratios to convert into to the target unit. */
switch (endValueUnitType) {
case "%":
startValue *= 1 / (axis === "x" ? elementUnitConversionData.percentToPxWidth : elementUnitConversionData.percentToPxHeight);
break;
case "px":
/* startValue is already in px, do nothing; we're done. */
break;
default:
startValue *= 1 / elementUnitConversionData[endValueUnitType + "ToPx"];
}
}
}
/*********************
Relative Values
*********************/
/* Operator logic must be performed last since it requires unit-normalized start and end values. */
/* Note: Relative *percent values* do not behave how most people think; while one would expect "+=50%"
to increase the property 1.5x its current value, it in fact increases the percent units in absolute terms:
50 points is added on top of the current % value. */
switch (operator) {
case "+":
endValue = startValue + endValue;
break;
case "-":
endValue = startValue - endValue;
break;
case "*":
endValue = startValue * endValue;
break;
case "/":
endValue = startValue / endValue;
break;
}
/**************************
tweensContainer Push
**************************/
/* Construct the per-property tween object, and push it to the element's tweensContainer. */
tweensContainer[property] = {
rootPropertyValue: rootPropertyValue,
startValue: startValue,
currentValue: startValue,
endValue: endValue,
unitType: endValueUnitType,
easing: easing
};
if (Velocity.debug) console.log("tweensContainer (" + property + "): " + JSON.stringify(tweensContainer[property]), element);
}
/* Along with its property data, store a reference to the element itself onto tweensContainer. */
tweensContainer.element = element;
}
/*****************
Call Push
*****************/
/* Note: tweensContainer can be empty if all of the properties in this call's property map were skipped due to not
being supported by the browser. The element property is used for checking that the tweensContainer has been appended to. */
if (tweensContainer.element) {
/* Apply the "velocity-animating" indicator class. */
CSS.Values.addClass(element, "velocity-animating");
/* The call array houses the tweensContainers for each element being animated in the current call. */
call.push(tweensContainer);
/* Store the tweensContainer and options if we're working on the default effects queue, so that they can be used by the reverse command. */
if (opts.queue === "") {
Data(element).tweensContainer = tweensContainer;
Data(element).opts = opts;
}
/* Switch on the element's animating flag. */
Data(element).isAnimating = true;
/* Once the final element in this call's element set has been processed, push the call array onto
Velocity.State.calls for the animation tick to immediately begin processing. */
if (elementsIndex === elementsLength - 1) {
/* Add the current call plus its associated metadata (the element set and the call's options) onto the global call container.
Anything on this call container is subjected to tick() processing. */
Velocity.State.calls.push([ call, elements, opts, null, promiseData.resolver ]);
/* If the animation tick isn't running, start it. (Velocity shuts it off when there are no active calls to process.) */
if (Velocity.State.isTicking === false) {
Velocity.State.isTicking = true;
/* Start the tick loop. */
tick();
}
} else {
elementsIndex++;
}
}
}
/* When the queue option is set to false, the call skips the element's queue and fires immediately. */
if (opts.queue === false) {
/* Since this buildQueue call doesn't respect the element's existing queue (which is where a delay option would have been appended),
we manually inject the delay property here with an explicit setTimeout. */
if (opts.delay) {
setTimeout(buildQueue, opts.delay);
} else {
buildQueue();
}
/* Otherwise, the call undergoes element queueing as normal. */
/* Note: To interoperate with jQuery, Velocity uses jQuery's own $.queue() stack for queuing logic. */
} else {
$.queue(element, opts.queue, function(next, clearQueue) {
/* If the clearQueue flag was passed in by the stop command, resolve this call's promise. (Promises can only be resolved once,
so it's fine if this is repeatedly triggered for each element in the associated call.) */
if (clearQueue === true) {
if (promiseData.promise) {
promiseData.resolver(elements);
}
/* Do not continue with animation queueing. */
return true;
}
/* This flag indicates to the upcoming completeCall() function that this queue entry was initiated by Velocity.
See completeCall() for further details. */
Velocity.velocityQueueEntryFlag = true;
buildQueue(next);
});
}
/*********************
Auto-Dequeuing
*********************/
/* As per jQuery's $.queue() behavior, to fire the first non-custom-queue entry on an element, the element
must be dequeued if its queue stack consists *solely* of the current call. (This can be determined by checking
for the "inprogress" item that jQuery prepends to active queue stack arrays.) Regardless, whenever the element's
queue is further appended with additional items -- including $.delay()'s or even $.animate() calls, the queue's
first entry is automatically fired. This behavior contrasts that of custom queues, which never auto-fire. */
/* Note: When an element set is being subjected to a non-parallel Velocity call, the animation will not begin until
each one of the elements in the set has reached the end of its individually pre-existing queue chain. */
/* Note: Unfortunately, most people don't fully grasp jQuery's powerful, yet quirky, $.queue() function.
Lean more here: http://stackoverflow.com/questions/1058158/can-somebody-explain-jquery-queue-to-me */
if ((opts.queue === "" || opts.queue === "fx") && $.queue(element)[0] !== "inprogress") {
$.dequeue(element);
}
}
/**************************
Element Set Iteration
**************************/
/* If the "nodeType" property exists on the elements variable, we're animating a single element.
Place it in an array so that $.each() can iterate over it. */
$.each(elements, function(i, element) {
/* Ensure each element in a set has a nodeType (is a real element) to avoid throwing errors. */
if (Type.isNode(element)) {
processElement.call(element);
}
});
/******************
Option: Loop
******************/
/* The loop option accepts an integer indicating how many times the element should loop between the values in the
current call's properties map and the element's property values prior to this call. */
/* Note: The loop option's logic is performed here -- after element processing -- because the current call needs
to undergo its queue insertion prior to the loop option generating its series of constituent "reverse" calls,
which chain after the current call. Two reverse calls (two "alternations") constitute one loop. */
var opts = $.extend({}, Velocity.defaults, options),
reverseCallsCount;
opts.loop = parseInt(opts.loop);
reverseCallsCount = (opts.loop * 2) - 1;
if (opts.loop) {
/* Double the loop count to convert it into its appropriate number of "reverse" calls.
Subtract 1 from the resulting value since the current call is included in the total alternation count. */
for (var x = 0; x < reverseCallsCount; x++) {
/* Since the logic for the reverse action occurs inside Queueing and therefore this call's options object
isn't parsed until then as well, the current call's delay option must be explicitly passed into the reverse
call so that the delay logic that occurs inside *Pre-Queueing* can process it. */
var reverseOptions = {
delay: opts.delay,
progress: opts.progress
};
/* If a complete callback was passed into this call, transfer it to the loop redirect's final "reverse" call
so that it's triggered when the entire redirect is complete (and not when the very first animation is complete). */
if (x === reverseCallsCount - 1) {
reverseOptions.display = opts.display;
reverseOptions.visibility = opts.visibility;
reverseOptions.complete = opts.complete;
}
animate(elements, "reverse", reverseOptions);
}
}
/***************
Chaining
***************/
/* Return the elements back to the call chain, with wrapped elements taking precedence in case Velocity was called via the $.fn. extension. */
return getChain();
};
/* Turn Velocity into the animation function, extended with the pre-existing Velocity object. */
Velocity = $.extend(animate, Velocity);
/* For legacy support, also expose the literal animate method. */
Velocity.animate = animate;
/**************
Timing
**************/
/* Ticker function. */
var ticker = window.requestAnimationFrame || rAFShim;
/* Inactive browser tabs pause rAF, which results in all active animations immediately sprinting to their completion states when the tab refocuses.
To get around this, we dynamically switch rAF to setTimeout (which the browser *doesn't* pause) when the tab loses focus. We skip this for mobile
devices to avoid wasting battery power on inactive tabs. */
/* Note: Tab focus detection doesn't work on older versions of IE, but that's okay since they don't support rAF to begin with. */
if (!Velocity.State.isMobile && document.hidden !== undefined) {
document.addEventListener("visibilitychange", function() {
/* Reassign the rAF function (which the global tick() function uses) based on the tab's focus state. */
if (document.hidden) {
ticker = function(callback) {
/* The tick function needs a truthy first argument in order to pass its internal timestamp check. */
return setTimeout(function() { callback(true) }, 16);
};
/* The rAF loop has been paused by the browser, so we manually restart the tick. */
tick();
} else {
ticker = window.requestAnimationFrame || rAFShim;
}
});
}
/************
Tick
************/
/* Note: All calls to Velocity are pushed to the Velocity.State.calls array, which is fully iterated through upon each tick. */
function tick (timestamp) {
/* An empty timestamp argument indicates that this is the first tick occurence since ticking was turned on.
We leverage this metadata to fully ignore the first tick pass since RAF's initial pass is fired whenever
the browser's next tick sync time occurs, which results in the first elements subjected to Velocity
calls being animated out of sync with any elements animated immediately thereafter. In short, we ignore
the first RAF tick pass so that elements being immediately consecutively animated -- instead of simultaneously animated
by the same Velocity call -- are properly batched into the same initial RAF tick and consequently remain in sync thereafter. */
if (timestamp) {
/* We ignore RAF's high resolution timestamp since it can be significantly offset when the browser is
under high stress; we opt for choppiness over allowing the browser to drop huge chunks of frames. */
var timeCurrent = (new Date).getTime();
/********************
Call Iteration
********************/
var callsLength = Velocity.State.calls.length;
/* To speed up iterating over this array, it is compacted (falsey items -- calls that have completed -- are removed)
when its length has ballooned to a point that can impact tick performance. This only becomes necessary when animation
has been continuous with many elements over a long period of time; whenever all active calls are completed, completeCall() clears Velocity.State.calls. */
if (callsLength > 10000) {
Velocity.State.calls = compactSparseArray(Velocity.State.calls);
}
/* Iterate through each active call. */
for (var i = 0; i < callsLength; i++) {
/* When a Velocity call is completed, its Velocity.State.calls entry is set to false. Continue on to the next call. */
if (!Velocity.State.calls[i]) {
continue;
}
/************************
Call-Wide Variables
************************/
var callContainer = Velocity.State.calls[i],
call = callContainer[0],
opts = callContainer[2],
timeStart = callContainer[3],
firstTick = !!timeStart,
tweenDummyValue = null;
/* If timeStart is undefined, then this is the first time that this call has been processed by tick().
We assign timeStart now so that its value is as close to the real animation start time as possible.
(Conversely, had timeStart been defined when this call was added to Velocity.State.calls, the delay
between that time and now would cause the first few frames of the tween to be skipped since
percentComplete is calculated relative to timeStart.) */
/* Further, subtract 16ms (the approximate resolution of RAF) from the current time value so that the
first tick iteration isn't wasted by animating at 0% tween completion, which would produce the
same style value as the element's current value. */
if (!timeStart) {
timeStart = Velocity.State.calls[i][3] = timeCurrent - 16;
}
/* The tween's completion percentage is relative to the tween's start time, not the tween's start value
(which would result in unpredictable tween durations since JavaScript's timers are not particularly accurate).
Accordingly, we ensure that percentComplete does not exceed 1. */
var percentComplete = Math.min((timeCurrent - timeStart) / opts.duration, 1);
/**********************
Element Iteration
**********************/
/* For every call, iterate through each of the elements in its set. */
for (var j = 0, callLength = call.length; j < callLength; j++) {
var tweensContainer = call[j],
element = tweensContainer.element;
/* Check to see if this element has been deleted midway through the animation by checking for the
continued existence of its data cache. If it's gone, skip animating this element. */
if (!Data(element)) {
continue;
}
var transformPropertyExists = false;
/**********************************
Display & Visibility Toggling
**********************************/
/* If the display option is set to non-"none", set it upfront so that the element can become visible before tweening begins.
(Otherwise, display's "none" value is set in completeCall() once the animation has completed.) */
if (opts.display !== undefined && opts.display !== null && opts.display !== "none") {
if (opts.display === "flex") {
var flexValues = [ "-webkit-box", "-moz-box", "-ms-flexbox", "-webkit-flex" ];
$.each(flexValues, function(i, flexValue) {
CSS.setPropertyValue(element, "display", flexValue);
});
}
CSS.setPropertyValue(element, "display", opts.display);
}
/* Same goes with the visibility option, but its "none" equivalent is "hidden". */
if (opts.visibility !== undefined && opts.visibility !== "hidden") {
CSS.setPropertyValue(element, "visibility", opts.visibility);
}
/************************
Property Iteration
************************/
/* For every element, iterate through each property. */
for (var property in tweensContainer) {
/* Note: In addition to property tween data, tweensContainer contains a reference to its associated element. */
if (property !== "element") {
var tween = tweensContainer[property],
currentValue,
/* Easing can either be a pre-genereated function or a string that references a pre-registered easing
on the Velocity.Easings object. In either case, return the appropriate easing *function*. */
easing = Type.isString(tween.easing) ? Velocity.Easings[tween.easing] : tween.easing;
/******************************
Current Value Calculation
******************************/
/* If this is the last tick pass (if we've reached 100% completion for this tween),
ensure that currentValue is explicitly set to its target endValue so that it's not subjected to any rounding. */
if (percentComplete === 1) {
currentValue = tween.endValue;
/* Otherwise, calculate currentValue based on the current delta from startValue. */
} else {
var tweenDelta = tween.endValue - tween.startValue;
currentValue = tween.startValue + (tweenDelta * easing(percentComplete, opts, tweenDelta));
/* If no value change is occurring, don't proceed with DOM updating. */
if (!firstTick && (currentValue === tween.currentValue)) {
continue;
}
}
tween.currentValue = currentValue;
/* If we're tweening a fake 'tween' property in order to log transition values, update the one-per-call variable so that
it can be passed into the progress callback. */
if (property === "tween") {
tweenDummyValue = currentValue;
} else {
/******************
Hooks: Part I
******************/
/* For hooked properties, the newly-updated rootPropertyValueCache is cached onto the element so that it can be used
for subsequent hooks in this call that are associated with the same root property. If we didn't cache the updated
rootPropertyValue, each subsequent update to the root property in this tick pass would reset the previous hook's
updates to rootPropertyValue prior to injection. A nice performance byproduct of rootPropertyValue caching is that
subsequently chained animations using the same hookRoot but a different hook can use this cached rootPropertyValue. */
if (CSS.Hooks.registered[property]) {
var hookRoot = CSS.Hooks.getRoot(property),
rootPropertyValueCache = Data(element).rootPropertyValueCache[hookRoot];
if (rootPropertyValueCache) {
tween.rootPropertyValue = rootPropertyValueCache;
}
}
/*****************
DOM Update
*****************/
/* setPropertyValue() returns an array of the property name and property value post any normalization that may have been performed. */
/* Note: To solve an IE<=8 positioning bug, the unit type is dropped when setting a property value of 0. */
var adjustedSetData = CSS.setPropertyValue(element, /* SET */
property,
tween.currentValue + (parseFloat(currentValue) === 0 ? "" : tween.unitType),
tween.rootPropertyValue,
tween.scrollData);
/*******************
Hooks: Part II
*******************/
/* Now that we have the hook's updated rootPropertyValue (the post-processed value provided by adjustedSetData), cache it onto the element. */
if (CSS.Hooks.registered[property]) {
/* Since adjustedSetData contains normalized data ready for DOM updating, the rootPropertyValue needs to be re-extracted from its normalized form. ?? */
if (CSS.Normalizations.registered[hookRoot]) {
Data(element).rootPropertyValueCache[hookRoot] = CSS.Normalizations.registered[hookRoot]("extract", null, adjustedSetData[1]);
} else {
Data(element).rootPropertyValueCache[hookRoot] = adjustedSetData[1];
}
}
/***************
Transforms
***************/
/* Flag whether a transform property is being animated so that flushTransformCache() can be triggered once this tick pass is complete. */
if (adjustedSetData[0] === "transform") {
transformPropertyExists = true;
}
}
}
}
/****************
mobileHA
****************/
/* If mobileHA is enabled, set the translate3d transform to null to force hardware acceleration.
It's safe to override this property since Velocity doesn't actually support its animation (hooks are used in its place). */
if (opts.mobileHA) {
/* Don't set the null transform hack if we've already done so. */
if (Data(element).transformCache.translate3d === undefined) {
/* All entries on the transformCache object are later concatenated into a single transform string via flushTransformCache(). */
Data(element).transformCache.translate3d = "(0px, 0px, 0px)";
transformPropertyExists = true;
}
}
if (transformPropertyExists) {
CSS.flushTransformCache(element);
}
}
/* The non-"none" display value is only applied to an element once -- when its associated call is first ticked through.
Accordingly, it's set to false so that it isn't re-processed by this call in the next tick. */
if (opts.display !== undefined && opts.display !== "none") {
Velocity.State.calls[i][2].display = false;
}
if (opts.visibility !== undefined && opts.visibility !== "hidden") {
Velocity.State.calls[i][2].visibility = false;
}
/* Pass the elements and the timing data (percentComplete, msRemaining, timeStart, tweenDummyValue) into the progress callback. */
if (opts.progress) {
opts.progress.call(callContainer[1],
callContainer[1],
percentComplete,
Math.max(0, (timeStart + opts.duration) - timeCurrent),
timeStart,
tweenDummyValue);
}
/* If this call has finished tweening, pass its index to completeCall() to handle call cleanup. */
if (percentComplete === 1) {
completeCall(i);
}
}
}
/* Note: completeCall() sets the isTicking flag to false when the last call on Velocity.State.calls has completed. */
if (Velocity.State.isTicking) {
ticker(tick);
}
}
/**********************
Call Completion
**********************/
/* Note: Unlike tick(), which processes all active calls at once, call completion is handled on a per-call basis. */
function completeCall (callIndex, isStopped) {
/* Ensure the call exists. */
if (!Velocity.State.calls[callIndex]) {
return false;
}
/* Pull the metadata from the call. */
var call = Velocity.State.calls[callIndex][0],
elements = Velocity.State.calls[callIndex][1],
opts = Velocity.State.calls[callIndex][2],
resolver = Velocity.State.calls[callIndex][4];
var remainingCallsExist = false;
/*************************
Element Finalization
*************************/
for (var i = 0, callLength = call.length; i < callLength; i++) {
var element = call[i].element;
/* If the user set display to "none" (intending to hide the element), set it now that the animation has completed. */
/* Note: display:none isn't set when calls are manually stopped (via Velocity("stop"). */
/* Note: Display gets ignored with "reverse" calls and infinite loops, since this behavior would be undesirable. */
if (!isStopped && !opts.loop) {
if (opts.display === "none") {
CSS.setPropertyValue(element, "display", opts.display);
}
if (opts.visibility === "hidden") {
CSS.setPropertyValue(element, "visibility", opts.visibility);
}
}
/* If the element's queue is empty (if only the "inprogress" item is left at position 0) or if its queue is about to run
a non-Velocity-initiated entry, turn off the isAnimating flag. A non-Velocity-initiatied queue entry's logic might alter
an element's CSS values and thereby cause Velocity's cached value data to go stale. To detect if a queue entry was initiated by Velocity,
we check for the existence of our special Velocity.queueEntryFlag declaration, which minifiers won't rename since the flag
is assigned to jQuery's global $ object and thus exists out of Velocity's own scope. */
if (opts.loop !== true && ($.queue(element)[1] === undefined || !/\.velocityQueueEntryFlag/i.test($.queue(element)[1]))) {
/* The element may have been deleted. Ensure that its data cache still exists before acting on it. */
if (Data(element)) {
Data(element).isAnimating = false;
/* Clear the element's rootPropertyValueCache, which will become stale. */
Data(element).rootPropertyValueCache = {};
var transformHAPropertyExists = false;
/* If any 3D transform subproperty is at its default value (regardless of unit type), remove it. */
$.each(CSS.Lists.transforms3D, function(i, transformName) {
var defaultValue = /^scale/.test(transformName) ? 1 : 0,
currentValue = Data(element).transformCache[transformName];
if (Data(element).transformCache[transformName] !== undefined && new RegExp("^\\(" + defaultValue + "[^.]").test(currentValue)) {
transformHAPropertyExists = true;
delete Data(element).transformCache[transformName];
}
});
/* Mobile devices have hardware acceleration removed at the end of the animation in order to avoid hogging the GPU's memory. */
if (opts.mobileHA) {
transformHAPropertyExists = true;
delete Data(element).transformCache.translate3d;
}
/* Flush the subproperty removals to the DOM. */
if (transformHAPropertyExists) {
CSS.flushTransformCache(element);
}
/* Remove the "velocity-animating" indicator class. */
CSS.Values.removeClass(element, "velocity-animating");
}
}
/*********************
Option: Complete
*********************/
/* Complete is fired once per call (not once per element) and is passed the full raw DOM element set as both its context and its first argument. */
/* Note: Callbacks aren't fired when calls are manually stopped (via Velocity("stop"). */
if (!isStopped && opts.complete && !opts.loop && (i === callLength - 1)) {
/* We throw callbacks in a setTimeout so that thrown errors don't halt the execution of Velocity itself. */
try {
opts.complete.call(elements, elements);
} catch (error) {
setTimeout(function() { throw error; }, 1);
}
}
/**********************
Promise Resolving
**********************/
/* Note: Infinite loops don't return promises. */
if (resolver && opts.loop !== true) {
resolver(elements);
}
/****************************
Option: Loop (Infinite)
****************************/
if (opts.loop === true && !isStopped) {
/* If a rotateX/Y/Z property is being animated to 360 deg with loop:true, swap tween start/end values to enable
continuous iterative rotation looping. (Otherise, the element would just rotate back and forth.) */
$.each(Data(element).tweensContainer, function(propertyName, tweenContainer) {
if (/^rotate/.test(propertyName) && parseFloat(tweenContainer.endValue) === 360) {
tweenContainer.endValue = 0;
tweenContainer.startValue = 360;
}
if (/^backgroundPosition/.test(propertyName) && parseFloat(tweenContainer.endValue) === 100 && tweenContainer.unitType === "%") {
tweenContainer.endValue = 0;
tweenContainer.startValue = 100;
}
});
Velocity(element, "reverse", { loop: true, delay: opts.delay });
}
/***************
Dequeueing
***************/
/* Fire the next call in the queue so long as this call's queue wasn't set to false (to trigger a parallel animation),
which would have already caused the next call to fire. Note: Even if the end of the animation queue has been reached,
$.dequeue() must still be called in order to completely clear jQuery's animation queue. */
if (opts.queue !== false) {
$.dequeue(element, opts.queue);
}
}
/************************
Calls Array Cleanup
************************/
/* Since this call is complete, set it to false so that the rAF tick skips it. This array is later compacted via compactSparseArray().
(For performance reasons, the call is set to false instead of being deleted from the array: http://www.html5rocks.com/en/tutorials/speed/v8/) */
Velocity.State.calls[callIndex] = false;
/* Iterate through the calls array to determine if this was the final in-progress animation.
If so, set a flag to end ticking and clear the calls array. */
for (var j = 0, callsLength = Velocity.State.calls.length; j < callsLength; j++) {
if (Velocity.State.calls[j] !== false) {
remainingCallsExist = true;
break;
}
}
if (remainingCallsExist === false) {
/* tick() will detect this flag upon its next iteration and subsequently turn itself off. */
Velocity.State.isTicking = false;
/* Clear the calls array so that its length is reset. */
delete Velocity.State.calls;
Velocity.State.calls = [];
}
}
/******************
Frameworks
******************/
/* Both jQuery and Zepto allow their $.fn object to be extended to allow wrapped elements to be subjected to plugin calls.
If either framework is loaded, register a "velocity" extension pointing to Velocity's core animate() method. Velocity
also registers itself onto a global container (window.jQuery || window.Zepto || window) so that certain features are
accessible beyond just a per-element scope. This master object contains an .animate() method, which is later assigned to $.fn
(if jQuery or Zepto are present). Accordingly, Velocity can both act on wrapped DOM elements and stand alone for targeting raw DOM elements. */
global.Velocity = Velocity;
if (global !== window) {
/* Assign the element function to Velocity's core animate() method. */
global.fn.velocity = animate;
/* Assign the object function's defaults to Velocity's global defaults object. */
global.fn.velocity.defaults = Velocity.defaults;
}
/***********************
Packaged Redirects
***********************/
/* slideUp, slideDown */
$.each([ "Down", "Up" ], function(i, direction) {
Velocity.Redirects["slide" + direction] = function (element, options, elementsIndex, elementsSize, elements, promiseData) {
var opts = $.extend({}, options),
begin = opts.begin,
complete = opts.complete,
computedValues = { height: "", marginTop: "", marginBottom: "", paddingTop: "", paddingBottom: "" },
inlineValues = {};
if (opts.display === undefined) {
/* Show the element before slideDown begins and hide the element after slideUp completes. */
/* Note: Inline elements cannot have dimensions animated, so they're reverted to inline-block. */
opts.display = (direction === "Down" ? (Velocity.CSS.Values.getDisplayType(element) === "inline" ? "inline-block" : "block") : "none");
}
opts.begin = function() {
/* If the user passed in a begin callback, fire it now. */
begin && begin.call(elements, elements);
/* Cache the elements' original vertical dimensional property values so that we can animate back to them. */
for (var property in computedValues) {
inlineValues[property] = element.style[property];
/* For slideDown, use forcefeeding to animate all vertical properties from 0. For slideUp,
use forcefeeding to start from computed values and animate down to 0. */
var propertyValue = Velocity.CSS.getPropertyValue(element, property);
computedValues[property] = (direction === "Down") ? [ propertyValue, 0 ] : [ 0, propertyValue ];
}
/* Force vertical overflow content to clip so that sliding works as expected. */
inlineValues.overflow = element.style.overflow;
element.style.overflow = "hidden";
}
opts.complete = function() {
/* Reset element to its pre-slide inline values once its slide animation is complete. */
for (var property in inlineValues) {
element.style[property] = inlineValues[property];
}
/* If the user passed in a complete callback, fire it now. */
complete && complete.call(elements, elements);
promiseData && promiseData.resolver(elements);
};
Velocity(element, computedValues, opts);
};
});
/* fadeIn, fadeOut */
$.each([ "In", "Out" ], function(i, direction) {
Velocity.Redirects["fade" + direction] = function (element, options, elementsIndex, elementsSize, elements, promiseData) {
var opts = $.extend({}, options),
propertiesMap = { opacity: (direction === "In") ? 1 : 0 },
originalComplete = opts.complete;
/* Since redirects are triggered individually for each element in the animated set, avoid repeatedly triggering
callbacks by firing them only when the final element has been reached. */
if (elementsIndex !== elementsSize - 1) {
opts.complete = opts.begin = null;
} else {
opts.complete = function() {
if (originalComplete) {
originalComplete.call(elements, elements);
}
promiseData && promiseData.resolver(elements);
}
}
/* If a display was passed in, use it. Otherwise, default to "none" for fadeOut or the element-specific default for fadeIn. */
/* Note: We allow users to pass in "null" to skip display setting altogether. */
if (opts.display === undefined) {
opts.display = (direction === "In" ? "auto" : "none");
}
Velocity(this, propertiesMap, opts);
};
});
return Velocity;
}((window.jQuery || window.Zepto || window), window, document);
}));
/******************
Known Issues
******************/
/* The CSS spec mandates that the translateX/Y/Z transforms are %-relative to the element itself -- not its parent.
Velocity, however, doesn't make this distinction. Thus, converting to or from the % unit with these subproperties
will produce an inaccurate conversion value. The same issue exists with the cx/cy attributes of SVG circles and ellipses. */ | tpmanc/football | web/js/admin/vendor/bower/velocity/velocity.js | JavaScript | bsd-3-clause | 213,740 |
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var _callbacks = {};
var _next_reply_id = 0;
var postMessage = function(msg, callback) {
var reply_id = _next_reply_id;
_next_reply_id += 1;
_callbacks[reply_id] = callback;
msg.reply_id = reply_id.toString();
extension.postMessage(JSON.stringify(msg));
};
function checkPostError(msg, errorCallback) {
if (msg.error == tizen.WebAPIException.NO_ERROR)
return false;
if (errorCallback) {
var error = new tizen.WebAPIError(msg.error);
errorCallback(error);
}
return true;
}
extension.setMessageListener(function(json) {
var msg = JSON.parse(json);
if (msg.cmd == 'BondedDevice')
handleBondedDevice(msg);
else if (msg.cmd == 'DeviceFound')
handleDeviceFound(msg);
else if (msg.cmd == 'DiscoveryFinished')
handleDiscoveryFinished();
else if (msg.cmd == 'DeviceRemoved')
handleDeviceRemoved(msg.Address);
else if (msg.cmd == 'DeviceUpdated')
handleDeviceUpdated(msg);
else if (msg.cmd == 'AdapterUpdated')
handleAdapterUpdated(msg);
else if (msg.cmd == 'RFCOMMSocketAccept')
handleRFCOMMSocketAccept(msg);
else if (msg.cmd == 'SocketHasData')
handleSocketHasData(msg);
else if (msg.cmd == 'SocketClosed')
handleSocketClosed(msg);
else { // Then we are dealing with postMessage return.
var reply_id = msg.reply_id;
var callback = _callbacks[reply_id];
if (callback) {
delete msg.reply_id;
delete _callbacks[reply_id];
callback(msg);
} else {
// do not print error log when the postmessage was not initiated by JS
if (reply_id != '')
console.log('Invalid reply_id from Tizen Bluetooth: ' + reply_id);
}
}
});
function Adapter() {
this.found_devices = []; // Filled while a Discovering.
this.known_devices = []; // Keeps Managed and Found devices.
this.discovery_callbacks = {};
this.isReady = false;
this.service_handlers = [];
this.sockets = [];
this.change_listener = {};
this.health_apps = {};
this.health_channel_listener = {};
}
function validateAddress(address) {
if (typeof address !== 'string')
return false;
var regExp = /([\dA-F][\dA-F]:){5}[\dA-F][\dA-F]/i;
if (!address.match(regExp))
return false;
return true;
}
Adapter.prototype.checkServiceAvailability = function(errorCallback) {
if (adapter.isReady && defaultAdapter.powered)
return false;
if (errorCallback) {
var error = new tizen.WebAPIError(tizen.WebAPIException.SERVICE_NOT_AVAILABLE_ERR);
errorCallback(error);
}
return true;
};
Adapter.prototype.indexOfDevice = function(devices, address) {
for (var i = 0; i < devices.length; i++) {
if (devices[i].address == address)
return i;
}
return -1;
};
Adapter.prototype.addDevice = function(device, on_discovery) {
var new_device = false;
if (on_discovery) {
var index = this.indexOfDevice(this.found_devices, device.address);
if (index == -1) {
this.found_devices.push(device);
new_device = true;
} else {
this.found_devices[index] = device;
new_device = false;
}
}
var i = this.indexOfDevice(this.known_devices, device.address);
if (i == -1)
this.known_devices.push(device);
else
this.known_devices[i] = device;
return new_device;
};
Adapter.prototype.updateDevice = function(device) {
var index = this.indexOfDevice(this.known_devices, device.address);
if (index == -1)
this.known_devices.push(device);
else
this.known_devices[index]._updateProperties(device);
};
// This holds the adapter the Bluetooth backend is currently using.
// In BlueZ 4, for instance, this would represent the "default adapter".
// BlueZ 5 has no such concept, so this will hold the currently available
// adapter, which can be just the first one found.
var adapter = new Adapter();
var deepCopyDevices = function(devices) {
var copiedDevices = [];
for (var i = 0; i < devices.length; i++)
copiedDevices[i] = devices[i]._clone();
return copiedDevices;
};
var handleBondedDevice = function(msg) {
var device = new BluetoothDevice(msg);
adapter.addDevice(device, false);
};
var handleDeviceFound = function(msg) {
var device = new BluetoothDevice(msg);
var is_new = adapter.addDevice(device, msg.found_on_discovery);
// FIXME(jeez): we are not returning a deep copy so we can keep
// the devices up-to-date. We have to find a better way to handle this.
if (is_new && msg.found_on_discovery && adapter.discovery_callbacks.ondevicefound)
adapter.discovery_callbacks.ondevicefound(device);
};
var handleDiscoveryFinished = function() {
// FIXME(jeez): we are not returning a deep copy so we can keep
// the devices up-to-date. We have to find a better way to handle this.
if (typeof adapter.discovery_callbacks.onfinished === 'function')
adapter.discovery_callbacks.onfinished(adapter.found_devices);
adapter.found_devices = [];
adapter.discovery_callbacks = {};
};
var handleDeviceRemoved = function(address) {
var foundDevices = adapter.found_devices;
var knownDevices = adapter.known_devices;
for (var i = 0; i < foundDevices.length; i++) {
if (foundDevices[i].address === address) {
foundDevices.splice(i, 1);
break;
}
}
for (var i = 0; i < knownDevices.length; i++) {
if (knownDevices[i].address === address) {
knownDevices.splice(i, 1);
break;
}
}
if (adapter.discovery_callbacks.ondevicedisappeared)
adapter.discovery_callbacks.ondevicedisappeared(address);
};
var handleDeviceUpdated = function(msg) {
var device = new BluetoothDevice(msg);
adapter.updateDevice(device);
};
var handleAdapterUpdated = function(msg) {
var listener = adapter.change_listener;
if (msg.Name) {
_addConstProperty(defaultAdapter, 'name', msg.Name);
if (listener && listener.onnamechanged) {
adapter.change_listener.onnamechanged(msg.Name);
}
}
if (msg.Address)
_addConstProperty(defaultAdapter, 'address', msg.Address);
if (msg.Powered) {
var powered = (msg.Powered === 'true');
_addConstProperty(defaultAdapter, 'powered', powered);
if (listener && listener.onstatechanged) {
adapter.change_listener.onstatechanged(powered);
}
}
if (msg.Discoverable) {
var visibility = (msg.Discoverable === 'true');
if (defaultAdapter.visible !== visibility && listener && listener.onvisibilitychanged) {
adapter.change_listener.onvisibilitychanged(visibility);
}
_addConstProperty(defaultAdapter, 'visible', visibility);
}
defaultAdapter.isReady = true;
};
var handleRFCOMMSocketAccept = function(msg) {
for (var i in adapter.service_handlers) {
var server = adapter.service_handlers[i];
// FIXME(clecou) BlueZ4 backend compares rfcomm channel number but this parameter
// is not available in Tizen C API so we check socket fd.
// A better approach would be to adapt backends instances to have a single JSON protocol.
if (server.channel === msg.channel || server.server_fd === msg.socket_fd) {
var j = adapter.indexOfDevice(adapter.known_devices, msg.peer);
var peer = adapter.known_devices[j];
var socket = new BluetoothSocket(server.uuid, peer, msg);
adapter.sockets.push(socket);
_addConstProperty(server, 'isConnected', true);
if (server.onconnect && typeof server.onconnect === 'function')
server.onconnect(socket);
return;
}
}
};
var handleSocketHasData = function(msg) {
for (var i in adapter.sockets) {
var socket = adapter.sockets[i];
if (socket.socket_fd === msg.socket_fd) {
socket.data = msg.data;
if (socket.onmessage && typeof socket.onmessage === 'function')
socket.onmessage();
socket.data = [];
return;
}
}
};
var handleSocketClosed = function(msg) {
for (var i in adapter.sockets) {
var socket = adapter.sockets[i];
if (socket.socket_fd === msg.socket_fd) {
if (socket.onclose && typeof socket.onmessage === 'function')
socket.onclose();
return;
}
}
};
function _addConstProperty(obj, propertyKey, propertyValue) {
Object.defineProperty(obj, propertyKey, {
configurable: true,
writable: false,
value: propertyValue
});
}
exports.deviceMajor = {};
var deviceMajor = {
'MISC': { value: 0x00, configurable: false, writable: false },
'COMPUTER': { value: 0x01, configurable: false, writable: false },
'PHONE': { value: 0x02, configurable: false, writable: false },
'NETWORK': { value: 0x03, configurable: false, writable: false },
'AUDIO_VIDEO': { value: 0x04, configurable: false, writable: false },
'PERIPHERAL': { value: 0x05, configurable: false, writable: false },
'IMAGING': { value: 0x06, configurable: false, writable: false },
'WEARABLE': { value: 0x07, configurable: false, writable: false },
'TOY': { value: 0x08, configurable: false, writable: false },
'HEALTH': { value: 0x09, configurable: false, writable: false },
'UNCATEGORIZED': { value: 0x1F, configurable: false, writable: false }
};
Object.defineProperties(exports.deviceMajor, deviceMajor);
_addConstProperty(exports, 'deviceMajor', exports.deviceMajor);
exports.deviceMinor = {};
var deviceMinor = {
'COMPUTER_UNCATEGORIZED': { value: 0x00, configurable: false, writable: false },
'COMPUTER_DESKTOP': { value: 0x01, configurable: false, writable: false },
'COMPUTER_SERVER': { value: 0x02, configurable: false, writable: false },
'COMPUTER_LAPTOP': { value: 0x03, configurable: false, writable: false },
'COMPUTER_HANDHELD_PC_OR_PDA': { value: 0x04, configurable: false, writable: false },
'COMPUTER_PALM_PC_OR_PDA': { value: 0x05, configurable: false, writable: false },
'COMPUTER_WEARABLE': { value: 0x06, configurable: false, writable: false },
'PHONE_UNCATEGORIZED': { value: 0x00, configurable: false, writable: false },
'PHONE_CELLULAR': { value: 0x01, configurable: false, writable: false },
'PHONE_CORDLESS': { value: 0x02, configurable: false, writable: false },
'PHONE_SMARTPHONE': { value: 0x03, configurable: false, writable: false },
'PHONE_MODEM_OR_GATEWAY': { value: 0x04, configurable: false, writable: false },
'PHONE_ISDN': { value: 0x05, configurable: false, writable: false },
'AV_UNRECOGNIZED': { value: 0x00, configurable: false, writable: false },
'AV_WEARABLE_HEADSET': { value: 0x01, configurable: false, writable: false },
'AV_HANDSFREE': { value: 0x02, configurable: false, writable: false },
'AV_MICROPHONE': { value: 0x04, configurable: false, writable: false },
'AV_LOUDSPEAKER': { value: 0x05, configurable: false, writable: false },
'AV_HEADPHONES': { value: 0x06, configurable: false, writable: false },
'AV_PORTABLE_AUDIO': { value: 0x07, configurable: false, writable: false },
'AV_CAR_AUDIO': { value: 0x08, configurable: false, writable: false },
'AV_SETTOP_BOX': { value: 0x09, configurable: false, writable: false },
'AV_HIFI': { value: 0x0a, configurable: false, writable: false },
'AV_VCR': { value: 0x0b, configurable: false, writable: false },
'AV_VIDEO_CAMERA': { value: 0x0c, configurable: false, writable: false },
'AV_CAMCORDER': { value: 0x0d, configurable: false, writable: false },
'AV_MONITOR': { value: 0x0e, configurable: false, writable: false },
'AV_DISPLAY_AND_LOUDSPEAKER': { value: 0x0f, configurable: false, writable: false },
'AV_VIDEO_CONFERENCING': { value: 0x10, configurable: false, writable: false },
'AV_GAMING_TOY': { value: 0x12, configurable: false, writable: false },
'PERIPHERAL_UNCATEGORIZED': { value: 0, configurable: false, writable: false },
'PERIPHERAL_KEYBOARD': { value: 0x10, configurable: false, writable: false },
'PERIPHERAL_POINTING_DEVICE': { value: 0x20, configurable: false, writable: false },
'PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE': { value: 0x30, configurable: false, writable: false },
'PERIPHERAL_JOYSTICK': { value: 0x01, configurable: false, writable: false },
'PERIPHERAL_GAMEPAD': { value: 0x02, configurable: false, writable: false },
'PERIPHERAL_REMOTE_CONTROL': { value: 0x03, configurable: false, writable: false },
'PERIPHERAL_SENSING_DEVICE': { value: 0x04, configurable: false, writable: false },
'PERIPHERAL_DEGITIZER_TABLET': { value: 0x05, configurable: false, writable: false },
'PERIPHERAL_CARD_READER': { value: 0x06, configurable: false, writable: false },
'PERIPHERAL_DIGITAL_PEN': { value: 0x07, configurable: false, writable: false },
'PERIPHERAL_HANDHELD_SCANNER': { value: 0x08, configurable: false, writable: false },
'PERIPHERAL_HANDHELD_INPUT_DEVICE': { value: 0x09, configurable: false, writable: false },
'IMAGING_UNCATEGORIZED': { value: 0x00, configurable: false, writable: false },
'IMAGING_DISPLAY': { value: 0x04, configurable: false, writable: false },
'IMAGING_CAMERA': { value: 0x08, configurable: false, writable: false },
'IMAGING_SCANNER': { value: 0x10, configurable: false, writable: false },
'IMAGING_PRINTER': { value: 0x20, configurable: false, writable: false },
'WEARABLE_WRITST_WATCH': { value: 0x01, configurable: false, writable: false },
'WEARABLE_PAGER': { value: 0x02, configurable: false, writable: false },
'WEARABLE_JACKET': { value: 0x03, configurable: false, writable: false },
'WEARABLE_HELMET': { value: 0x04, configurable: false, writable: false },
'WEARABLE_GLASSES': { value: 0x05, configurable: false, writable: false },
'TOY_ROBOT': { value: 0x01, configurable: false, writable: false },
'TOY_VEHICLE': { value: 0x02, configurable: false, writable: false },
'TOY_DOLL': { value: 0x03, configurable: false, writable: false },
'TOY_CONTROLLER': { value: 0x04, configurable: false, writable: false },
'TOY_GAME': { value: 0x05, configurable: false, writable: false },
'HEALTH_UNDEFINED': { value: 0x00, configurable: false, writable: false },
'HEALTH_BLOOD_PRESSURE_MONITOR': { value: 0x01, configurable: false, writable: false },
'HEALTH_THERMOMETER': { value: 0x02, configurable: false, writable: false },
'HEALTH_WEIGHING_SCALE': { value: 0x03, configurable: false, writable: false },
'HEALTH_GLUCOSE_METER': { value: 0x04, configurable: false, writable: false },
'HEALTH_PULSE_OXIMETER': { value: 0x05, configurable: false, writable: false },
'HEALTH_PULSE_RATE_MONITOR': { value: 0x06, configurable: false, writable: false },
'HEALTH_DATA_DISPLAY': { value: 0x07, configurable: false, writable: false },
'HEALTH_STEP_COUNTER': { value: 0x08, configurable: false, writable: false },
'HEALTH_BODY_COMPOSITION_ANALYZER': { value: 0x09, configurable: false, writable: false },
'HEALTH_PEAK_FLOW_MONITOR': { value: 0x0a, configurable: false, writable: false },
'HEALTH_MEDICATION_MONITOR': { value: 0x0b, configurable: false, writable: false },
'HEALTH_KNEE_PROSTHESIS': { value: 0x0c, configurable: false, writable: false },
'HEALTH_ANKLE_PROSTHESIS': { value: 0x0d, configurable: false, writable: false }
};
Object.defineProperties(exports.deviceMinor, deviceMinor);
_addConstProperty(exports, 'deviceMinor', exports.deviceMinor);
exports.deviceService = {};
var deviceService = {
'LIMITED_DISCOVERABILITY': { value: 0x0001, configurable: false, writable: false },
'POSITIONING': { value: 0x0008, configurable: false, writable: false },
'NETWORKING': { value: 0x0010, configurable: false, writable: false },
'RENDERING': { value: 0x0020, configurable: false, writable: false },
'CAPTURING': { value: 0x0040, configurable: false, writable: false },
'OBJECT_TRANSFER': { value: 0x0080, configurable: false, writable: false },
'AUDIO': { value: 0x0100, configurable: false, writable: false },
'TELEPHONY': { value: 0x0200, configurable: false, writable: false },
'INFORMATION': { value: 0x0400, configurable: false, writable: false }
};
Object.defineProperties(exports.deviceService, deviceService);
_addConstProperty(exports, 'deviceService', exports.deviceService);
var defaultAdapter = new BluetoothAdapter();
exports.getDefaultAdapter = function() {
if (!defaultAdapter.name) {
var msg = { 'cmd': 'GetDefaultAdapter' };
var result = JSON.parse(extension.internal.sendSyncMessage(JSON.stringify(msg)));
if (result.error != tizen.WebAPIException.NO_ERROR) {
_addConstProperty(defaultAdapter, 'name', result.name);
_addConstProperty(defaultAdapter, 'address', result.address);
_addConstProperty(defaultAdapter, 'powered', result.powered);
_addConstProperty(defaultAdapter, 'visible', result.visible);
if (result.hasOwnProperty('address') && result.address != '')
adapter.isReady = true;
} else {
adapter.isReady = false;
throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR);
}
}
return defaultAdapter;
};
function BluetoothAdapter() {
_addConstProperty(this, 'name', '');
_addConstProperty(this, 'address', '00:00:00:00:00:00');
_addConstProperty(this, 'powered', false);
_addConstProperty(this, 'visible', false);
}
BluetoothAdapter.prototype.setName = function(name, successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('s?ff', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
if (name === defaultAdapter.name) {
if (successCallback)
successCallback();
return;
}
var msg = {
'cmd': 'SetAdapterProperty',
'property': 'Name',
'value': name
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
handleAdapterUpdated(result);
if (successCallback)
successCallback();
});
};
BluetoothAdapter.prototype.setPowered = function(state, successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('b?ff', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (state === defaultAdapter.powered) {
if (successCallback)
successCallback();
return;
}
var msg = {
'cmd': 'SetAdapterProperty',
'property': 'Powered',
'value': state
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
handleAdapterUpdated(result);
if (successCallback)
successCallback();
});
};
BluetoothAdapter.prototype.setVisible = function(mode, successCallback, errorCallback, timeout) {
if (!xwalk.utils.validateArguments('b?ffn', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
if (timeout === undefined || typeof timeout !== 'number' || timeout < 0)
timeout = 180; // According to tizen.bluetooth documentation.
var msg = {
'cmd': 'SetAdapterProperty',
'property': 'Discoverable',
'value': mode,
'timeout': timeout
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
handleAdapterUpdated(result);
if (successCallback)
successCallback();
});
};
BluetoothAdapter.prototype.discoverDevices = function(discoverySuccessCallback, errorCallback) {
if (!xwalk.utils.validateArguments('o?f', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (!xwalk.utils.validateObject(discoverySuccessCallback, 'ffff',
['onstarted', 'ondevicefound', 'ondevicedisappeared', 'onfinished'])) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var msg = {
'cmd': 'DiscoverDevices'
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
adapter.discovery_callbacks = discoverySuccessCallback;
if (discoverySuccessCallback && discoverySuccessCallback.onstarted)
discoverySuccessCallback.onstarted();
});
};
BluetoothAdapter.prototype.stopDiscovery = function(successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('?ff', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var msg = {
'cmd': 'StopDiscovery'
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
if (successCallback)
successCallback();
handleDiscoveryFinished();
});
};
BluetoothAdapter.prototype.getKnownDevices = function(deviceArraySuccessCallback, errorCallback) {
if (!xwalk.utils.validateArguments('f?f', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
// FIXME(jeez): we are not returning a deep copy so we can keep
// the devices up-to-date. We have to find a better way to handle this.
deviceArraySuccessCallback(adapter.known_devices);
};
BluetoothAdapter.prototype.getDevice = function(address, deviceSuccessCallback, errorCallback) {
if (!xwalk.utils.validateArguments('sf?f', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (!validateAddress(address)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var index = adapter.indexOfDevice(adapter.known_devices, address);
if (index == -1) {
var error = new tizen.WebAPIError(tizen.WebAPIException.NOT_FOUND_ERR);
errorCallback(error);
return;
}
deviceSuccessCallback(adapter.known_devices[index]);
};
BluetoothAdapter.prototype.createBonding = function(address, successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('sf?f', arguments)) {
throw new tizen.WebAPIError(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (!validateAddress(address)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var index = adapter.indexOfDevice(adapter.known_devices, address);
if (index == -1) {
var error = new tizen.WebAPIError(tizen.WebAPIException.NOT_FOUND_ERR);
if (errorCallback)
errorCallback(error);
return;
}
var msg = {
'cmd': 'CreateBonding',
'address': address
};
postMessage(msg, function(result) {
var cb_device;
if (checkPostError(result, errorCallback))
return;
if (successCallback) {
var known_devices = adapter.known_devices;
for (var i = 0; i < known_devices.length; i++) {
if (known_devices[i].address === address) {
cb_device = known_devices[i];
break;
}
}
// FIXME(clecou) Update known device state here when using C API Tizen backend
// BlueZ backends update the device state automatically when catching dbus signals.
// A better approach would be to adapt backends instances to have a single JSON protocol.
if (result.capi)
_addConstProperty(adapter.known_devices[i], 'isBonded', true);
successCallback(cb_device);
}
});
};
BluetoothAdapter.prototype.destroyBonding = function(address, successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('s?ff', arguments)) {
throw new tizen.WebAPIError(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
if (!validateAddress(address)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
var index = adapter.indexOfDevice(adapter.known_devices, address);
if (index == -1) {
var error = new tizen.WebAPIError(tizen.WebAPIException.NOT_FOUND_ERR);
if (errorCallback)
errorCallback(error);
return;
}
var msg = {
'cmd': 'DestroyBonding',
'address': address
};
postMessage(msg, function(result) {
var cb_device;
if (checkPostError(result, errorCallback))
return;
if (successCallback) {
var known_devices = adapter.known_devices;
for (var i = 0; i < known_devices.length; i++) {
if (known_devices[i].address === address) {
cb_device = known_devices[i];
break;
}
}
// FIXME(clecou) Update known device state here when using C API Tizen backend
// BlueZ backends update the device state automatically when catching dbus signals
// A better approach would be to adapt backends instances to have a single JSON protocol.
if (result.capi)
adapter.known_devices.splice(i, 1);
successCallback(cb_device);
}
});
};
BluetoothAdapter.prototype.registerRFCOMMServiceByUUID =
function(uuid, name, serviceSuccessCallback, errorCallback) {
if (!xwalk.utils.validateArguments('ssf?f', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var msg = {
'cmd': 'RFCOMMListen',
'uuid': uuid,
'name': name
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
var service = new BluetoothServiceHandler(uuid.toUpperCase(), name, result);
adapter.service_handlers.push(service);
if (serviceSuccessCallback) {
serviceSuccessCallback(service);
}
});
};
BluetoothAdapter.prototype.setChangeListener = function(listener) {
if (!xwalk.utils.validateArguments('o', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (!xwalk.utils.validateObject(listener, 'fff',
['onstatechanged', 'onnamechanged', 'onvisibilitychanged'])) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
adapter.change_listener = listener;
};
BluetoothAdapter.prototype.unsetChangeListener = function() {
adapter.change_listener = {};
};
function BluetoothProfileHandler(profileType) {
_addConstProperty(this, 'profileType', profileType);
}
function BluetoothHealthProfileHandler() {
BluetoothProfileHandler.call(this, 'HEALTH');
}
BluetoothHealthProfileHandler.prototype = Object.create(BluetoothProfileHandler.prototype);
BluetoothHealthProfileHandler.prototype.constructor = BluetoothHealthProfileHandler;
BluetoothAdapter.prototype.getBluetoothProfileHandler = function(profile_type) {
if (!xwalk.utils.validateArguments('s', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
return (profile_type === 'HEALTH') ? new BluetoothHealthProfileHandler() :
new BluetoothProfileHandler(profile_type);
};
var _deviceClassMask = {
'MINOR': 0x3F,
'MAJOR': 0x1F,
'SERVICE': 0x7F9
};
function BluetoothDevice(msg) {
if (!msg) {
_addConstProperty(this, 'name', '');
_addConstProperty(this, 'address', '');
_addConstProperty(this, 'deviceClass', new BluetoothClass());
_addConstProperty(this, 'isBonded', false);
_addConstProperty(this, 'isTrusted', false);
_addConstProperty(this, 'isConnected', false);
_addConstProperty(this, 'uuids', []);
return;
}
_addConstProperty(this, 'name', msg.Alias);
_addConstProperty(this, 'address', msg.Address);
_addConstProperty(this, 'deviceClass', new BluetoothClass());
_addConstProperty(this.deviceClass, 'minor', (msg.ClassMinor >> 2) & _deviceClassMask.MINOR);
_addConstProperty(this.deviceClass, 'major', msg.ClassMajor & _deviceClassMask.MAJOR);
_addConstProperty(this, 'isBonded', (msg.Paired == 'true'));
_addConstProperty(this, 'isTrusted', (msg.Trusted == 'true'));
_addConstProperty(this, 'isConnected', (msg.Connected == 'true'));
if (msg.UUIDs) {
var uuids_array = [];
if (typeof msg.UUIDs === 'string') {
// FIXME(clecou) BlueZ backend sends a string to convert it into an array
// A better approach would be to adapt backends instances to have a single JSON protocol.
uuids_array = msg.UUIDs.substring(msg.UUIDs.indexOf('[') + 1,
msg.UUIDs.indexOf(']')).split(',');
for (var i = 0; i < uuids_array.length; i++) {
uuids_array[i] = uuids_array[i].substring(2, uuids_array[i].length - 1);
}
} else {
// Tizen C API backend directly sends an array
uuids_array = msg.UUIDs;
for (var i = 0; i < msg.UUIDs.length; i++)
_addConstProperty(uuids_array, i.toString(), msg.UUIDs[i].toUpperCase());
}
_addConstProperty(this, 'uuids', uuids_array);
}
var services = (msg.ClassService >> 13) & _deviceClassMask.SERVICE;
var services_array = [];
var index = 0;
var SERVICE_CLASS_BITS_NUMBER = 11;
for (var i = 0; i < SERVICE_CLASS_BITS_NUMBER; i++) {
if ((services & (1 << i)) !== 0) {
_addConstProperty(services_array, index.toString(), (1 << i));
index++;
}
}
_addConstProperty(this.deviceClass, 'services', services_array);
}
BluetoothDevice.prototype.connectToServiceByUUID =
function(uuid, socketSuccessCallback, errorCallback) {
if (!xwalk.utils.validateArguments('sf?f', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var uuid_found = false;
for (var i = 0; i < this.uuids.length; i++) {
if (this.uuids[i] == uuid.toUpperCase()) {
uuid_found = true;
break;
}
}
if (uuid_found == false) {
var error = new tizen.WebAPIError(tizen.WebAPIException.NOT_FOUND_ERR);
errorCallback(error);
}
var msg = {
'cmd': 'ConnectToService',
'uuid': uuid,
'address' : this.address
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
var i = adapter.indexOfDevice(adapter.known_devices, result.peer);
var socket = new BluetoothSocket(result.uuid, adapter.known_devices[i], result);
adapter.sockets.push(socket);
socketSuccessCallback(socket);
});
};
BluetoothDevice.prototype._clone = function() {
var clone = new BluetoothDevice();
_addConstProperty(clone, 'name', this.name);
_addConstProperty(clone, 'address', this.address);
_addConstProperty(clone, 'deviceClass', this.deviceClass);
_addConstProperty(clone, 'isBonded', this.isBonded);
_addConstProperty(clone, 'isTrusted', this.isTrusted);
_addConstProperty(clone, 'isConnected', this.isConnected);
var uuids_array = [];
for (var i = 0; i < this.uuids.length; i++)
uuids_array[i] = this.uuids[i];
_addConstProperty(clone, 'uuids', uuids_array);
return clone;
};
BluetoothDevice.prototype._updateProperties = function(device) {
if (device.hasOwnProperty('name'))
_addConstProperty(this, 'name', device.name);
if (device.hasOwnProperty('address'))
_addConstProperty(this, 'address', device.address);
if (device.hasOwnProperty('deviceClass'))
_addConstProperty(this, 'deviceClass', device.deviceClass);
if (device.hasOwnProperty('isBonded'))
_addConstProperty(this, 'isBonded', device.isBonded);
if (device.hasOwnProperty('isTrusted'))
_addConstProperty(this, 'isTrusted', device.isTrusted);
if (device.hasOwnProperty('isConnected'))
_addConstProperty(this, 'isConnected', device.isConnected);
if (device.hasOwnProperty('uuids')) {
for (var i = 0; i < this.uuids.length; i++)
this.uuids[i] = device.uuids[i];
}
};
function BluetoothSocket(uuid, peer, msg) {
_addConstProperty(this, 'uuid', uuid);
_addConstProperty(this, 'peer', peer);
_addConstProperty(this, 'state', 'OPEN');
this.onclose = null;
this.onmessage = null;
this.data = [];
this.channel = 0;
this.socket_fd = 0;
if (msg) {
this.channel = msg.channel;
this.socket_fd = msg.socket_fd;
}
}
BluetoothSocket.prototype.writeData = function(data) {
// make sure that socket is connected and opened.
if (this.state == 'CLOSED') {
throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR);
return;
}
var msg = {
'cmd': 'SocketWriteData',
'data': data,
'socket_fd': this.socket_fd
};
var result = JSON.parse(extension.internal.sendSyncMessage(JSON.stringify(msg)));
return result.size;
};
BluetoothSocket.prototype.readData = function() {
return this.data;
};
BluetoothSocket.prototype.close = function() {
var msg = {
'cmd': 'CloseSocket',
'socket_fd': this.socket_fd
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback)) {
console.log('Can\'t close socket (' + this.socket_fd + ').');
throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR);
return;
}
// FIXME(clecou) Update socket object state only when using Tizen C API backend.
// BlueZ4 backend independently updates socket state based on a dbus callback mechanism.
// A better approach would be to adapt backends instances to have a single JSON protocol.
if (result.capi) {
for (var i in adapter.sockets) {
var socket = adapter.sockets[i];
if (socket.socket_fd === msg.socket_fd) {
if (socket.onclose && typeof socket.onmessage === 'function') {
_addConstProperty(adapter.sockets[i], 'state', 'CLOSED');
socket.onclose();
}
}
}
}
});
};
function BluetoothClass() {}
BluetoothClass.prototype.hasService = function(service) {
for (var i = 0; i < this.services.length; i++) {
if (this.services[i] === service)
return true;
}
return false;
};
function BluetoothServiceHandler(name, uuid, msg) {
_addConstProperty(this, 'name', name);
_addConstProperty(this, 'uuid', uuid);
_addConstProperty(this, 'isConnected', false);
this.onconnect = null;
if (msg) {
this.server_fd = msg.server_fd;
this.sdp_handle = msg.sdp_handle;
this.channel = msg.channel;
}
}
BluetoothServiceHandler.prototype.unregister = function(successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('?ff', arguments)) {
throw new tizen.WebAPIError(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
var msg = {
'cmd': 'UnregisterServer',
'server_fd': this.server_fd,
'sdp_handle': this.sdp_handle
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
for (var i in adapter.service_handlers) {
var service = adapter.service_handlers[i];
if (service.server_fd == result.socket_fd)
adapter.service_handlers.splice(i, 1);
}
if (successCallback)
successCallback();
});
};
function BluetoothHealthApplication(data_type, app_name, msg) {
_addConstProperty(this, 'dataType', data_type);
_addConstProperty(this, 'name', app_name);
this.onconnect = null;
if (msg)
this.app_id = msg.app_id;
}
BluetoothHealthApplication.prototype.unregister =
function(successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('?ff', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var msg = {
'cmd': 'UnregisterSinkApp',
'app_id': this.app_id
};
var app = this;
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
if (app.app_id)
delete adapter.health_apps[app.app_id];
if (successCallback)
successCallback();
});
};
BluetoothHealthProfileHandler.prototype.registerSinkApplication =
function(dataType, name, successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('nsf?f', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var msg = {
'cmd': 'RegisterSinkApp',
'datatype': dataType
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
if (successCallback) {
var application = new BluetoothHealthApplication(dataType, name, result);
adapter.health_apps[result.app_id] = application;
successCallback(application);
}
});
};
BluetoothHealthProfileHandler.prototype.connectToSource =
function(peer, application, successCallback, errorCallback) {
if (!xwalk.utils.validateArguments('oof?f', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (adapter.checkServiceAvailability(errorCallback))
return;
var msg = {
'cmd': 'ConnectToSource',
'address': peer.address,
'app_id': application.app_id
};
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
if (successCallback) {
var i = adapter.indexOfDevice(adapter.known_devices, result.address);
var channel = new BluetoothHealthChannel(adapter.known_devices[i],
adapter.health_apps[result.app_id], result);
successCallback(channel);
}
});
};
function BluetoothHealthChannel(device, application, msg) {
_addConstProperty(this, 'peer', device);
_addConstProperty(this, 'channelType', (msg.channel_type == 1) ? 'RELIABLE' : 'STREAMING');
_addConstProperty(this, 'application', application);
_addConstProperty(this, 'isConnected', (msg.connected == 'true'));
this.channel = msg.channel;
this.data = [];
}
BluetoothHealthChannel.prototype.close = function() {
if (adapter.checkServiceAvailability(errorCallback))
return;
var msg = {
'cmd': 'DisconnectSource',
'address': this.peer.address,
'channel': this.channel
};
var channel = this;
postMessage(msg, function(result) {
if (checkPostError(result, errorCallback))
return;
_addConstProperty(channel, 'isConnected', false);
if (adapter.health_channel_listener.onclose)
adapter.health_channel_listener.onclose();
});
};
BluetoothHealthChannel.prototype.sendData = function(data) {
if (adapter.checkServiceAvailability(errorCallback))
return;
if (!xwalk.utils.validateArguments('o', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
var msg = {
'cmd': 'SendHealthData',
'data': data,
'channel' : this.channel
};
postMessage(msg, function(result) {
if (result.error != tizen.WebAPIException.NO_ERROR) {
var error = new tizen.WebAPIError(tizen.WebAPIException.UNKNOWN_ERR);
return 0;
}
return result.size;
});
};
BluetoothHealthChannel.prototype.setListener = function(listener) {
if (!xwalk.utils.validateArguments('o', arguments)) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
if (!xwalk.utils.validateObject(listener, 'ff', ['onmessage', 'onclose'])) {
throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
}
adapter.health_channel_listener = listener;
};
BluetoothHealthChannel.prototype.unsetListener = function() {
adapter.health_channel_listener = {};
};
| pk-sam/tizen-extensions-crosswalk | src/bluetooth/bluetooth_api.js | JavaScript | bsd-3-clause | 39,100 |
/*
* Author: Zoltán Lajos Kis <zoltan.lajos.kis@ericsson.com>
*/
"use strict";
(function() {
var util = require('util');
var ofp = require('../ofp.js');
var offsets = ofp.offsets.ofp_action_tp_port;
module.exports = {
"unpack" : function(buffer, offset) {
var action = {
"header" : {"type" : 'OFPAT_SET_TP_DST'},
"body" : {}
};
var len = buffer.readUInt16BE(offset + offsets.len, true);
if (len != ofp.sizes.ofp_action_tp_port) {
return {
"error" : {
"desc" : util.format('%s action at offset %d has invalid length (%d).', action.header.type, offset, len),
"type" : 'OFPET_BAD_ACTION', "code" : 'OFPBAC_BAD_LEN'
}
}
}
action.body.tp_port = buffer.readUInt16BE(offset + offsets.tp_port, true);
return {
"action" : action,
"offset" : offset + len
}
}
}
})();
| gaberger/oflib-node | lib/ofp-1.0/actions/set-tp-dst.js | JavaScript | bsd-3-clause | 1,231 |
/*
* Author: Zoltán Lajos Kis <zoltan.lajos.kis@ericsson.com>
*/
"use strict";
module.exports.bin = [
0x00, 0x15, // type = 21
0x00, 0x08, // length = 8
0xff, 0xff, 0xff, 0x0ff, // queue_id = 0xffffffff
];
module.exports.obj = {
header : {type : 'OFPAT_SET_QUEUE'},
body : {queue_id : 0xffffffff}
};
module.exports.warnings = [];
| John-Lin/oflib-node | test/oflib-1.1/actions/set-queue-2.js | JavaScript | bsd-3-clause | 487 |
import React, { PureComponent } from 'react';
import { Animated, View, StyleSheet } from 'react-native';
var babelPluginFlowReactPropTypes_proptype_Style = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_Style || require('prop-types').any;
var babelPluginFlowReactPropTypes_proptype_NavigationScreenProp = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationScreenProp || require('prop-types').any;
var babelPluginFlowReactPropTypes_proptype_NavigationState = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationState || require('prop-types').any;
var babelPluginFlowReactPropTypes_proptype_NavigationAction = require('../../TypeDefinition').babelPluginFlowReactPropTypes_proptype_NavigationAction || require('prop-types').any;
var babelPluginFlowReactPropTypes_proptype_TabScene = require('./TabView').babelPluginFlowReactPropTypes_proptype_TabScene || require('prop-types').any;
export default class TabBarIcon extends PureComponent {
render() {
const {
position,
scene,
navigation,
activeTintColor,
inactiveTintColor,
style
} = this.props;
const { route, index } = scene;
const { routes } = navigation.state;
// Prepend '-1', so there are always at least 2 items in inputRange
const inputRange = [-1, ...routes.map((x, i) => i)];
const activeOpacity = position.interpolate({
inputRange,
outputRange: inputRange.map(i => i === index ? 1 : 0)
});
const inactiveOpacity = position.interpolate({
inputRange,
outputRange: inputRange.map(i => i === index ? 0 : 1)
});
// We render the icon twice at the same position on top of each other:
// active and inactive one, so we can fade between them.
return <View style={style}>
<Animated.View style={[styles.icon, { opacity: activeOpacity }]}>
{this.props.renderIcon({
route,
index,
focused: true,
tintColor: activeTintColor
})}
</Animated.View>
<Animated.View style={[styles.icon, { opacity: inactiveOpacity }]}>
{this.props.renderIcon({
route,
index,
focused: false,
tintColor: inactiveTintColor
})}
</Animated.View>
</View>;
}
}
TabBarIcon.propTypes = {
activeTintColor: require('prop-types').string.isRequired,
inactiveTintColor: require('prop-types').string.isRequired,
scene: babelPluginFlowReactPropTypes_proptype_TabScene,
position: require('prop-types').any.isRequired,
navigation: babelPluginFlowReactPropTypes_proptype_NavigationScreenProp,
renderIcon: require('prop-types').func.isRequired,
style: babelPluginFlowReactPropTypes_proptype_Style
};
TabBarIcon.propTypes = {
activeTintColor: require('prop-types').string.isRequired,
inactiveTintColor: require('prop-types').string.isRequired,
scene: babelPluginFlowReactPropTypes_proptype_TabScene,
position: require('prop-types').any.isRequired,
navigation: babelPluginFlowReactPropTypes_proptype_NavigationScreenProp,
renderIcon: require('prop-types').func.isRequired,
style: babelPluginFlowReactPropTypes_proptype_Style
};
const styles = StyleSheet.create({
icon: {
// We render the icon twice at the same position on top of each other:
// active and inactive one, so we can fade between them:
// Cover the whole iconContainer:
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
}
}); | gunaangs/Feedonymous | node_modules/react-navigation/lib-rn/views/TabView/TabBarIcon.js | JavaScript | mit | 3,575 |
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>group: exclude
define([
"require",
"./widgets/loader",
"./events/navigate",
"./navigation/path",
"./navigation/history",
"./navigation/navigator",
"./navigation/method",
"./transitions/handlers",
"./transitions/visuals",
"./animationComplete",
"./navigation",
"./degradeInputs",
"./widgets/page.dialog",
"./widgets/dialog",
"./widgets/collapsible",
"./widgets/collapsibleSet",
"./fieldContain",
"./grid",
"./widgets/navbar",
"./widgets/listview",
"./widgets/listview.autodividers",
"./widgets/listview.hidedividers",
"./nojs",
"./widgets/forms/checkboxradio",
"./widgets/forms/button",
"./widgets/forms/slider",
"./widgets/forms/slider.tooltip",
"./widgets/forms/flipswitch",
"./widgets/forms/rangeslider",
"./widgets/forms/textinput",
"./widgets/forms/clearButton",
"./widgets/forms/autogrow",
"./widgets/forms/select.custom",
"./widgets/forms/select",
"./buttonMarkup",
"./widgets/controlgroup",
"./links",
"./widgets/toolbar",
"./widgets/fixedToolbar",
"./widgets/fixedToolbar.workarounds",
"./widgets/popup",
"./widgets/popup.arrow",
"./widgets/panel",
"./widgets/table",
"./widgets/table.columntoggle",
"./widgets/table.reflow",
"./widgets/filterable",
"./widgets/filterable.backcompat",
"./widgets/tabs",
"./zoom",
"./zoom/iosorientationfix"
], function( require ) {
require( [ "./init" ], function() {} );
});
//>>excludeEnd("jqmBuildExclude");
| ericsteele/retrospec.js | test/input/projects/jquery-mobile/rev-1.4.5-2ef45a1/js/jquery.mobile.js | JavaScript | mit | 1,471 |
module.exports = {
name: 'basis.type',
test: [
require('./type/string.js'),
require('./type/number.js'),
require('./type/int.js'),
require('./type/enum.js'),
require('./type/array.js'),
require('./type/object.js'),
require('./type/date.js'),
{
name: 'definition of new types',
init: function(){
var basis = window.basis.createSandbox();
var type = basis.require('basis.type');
var catchWarnings = basis.require('./helpers/common.js').catchWarnings;
},
test: [
{
name: 'simple case',
test: function(){
var any = function(value){
return value;
};
type.defineType('Any', any);
assert(type.getTypeByName('Any') === any);
}
},
{
name: 'corner case',
test: function(){
var toStringType = type.getTypeByName('toString');
var warned = catchWarnings(function(){
toStringType({});
});
assert(warned);
assert(type.getTypeByNameIfDefined('toString') === undefined);
type.defineType('toString', basis.fn.$self);
var warnedAgain = catchWarnings(function(){
toStringType({});
});
assert(!warnedAgain);
assert(type.getTypeByNameIfDefined('toString') === basis.fn.$self);
}
},
{
name: 'deferred type definition',
test: function(){
var DeferredType = type.getTypeByName('DeferredType');
var warnedBefore = catchWarnings(function(){
assert(DeferredType('234.55') === undefined);
});
assert(warnedBefore);
type.defineType('DeferredType', type.int);
var warnedAfter = catchWarnings(function(){
assert(DeferredType('234.55') === 234);
});
assert(warnedAfter === false);
}
},
{
name: 'deffered type definition with specifying type host',
test: function(){
var typeHost = {};
var HostedType = type.getTypeByName('HostedType', typeHost, 'someType');
var warnedBefore = catchWarnings(function(){
assert(HostedType('234.55') === undefined);
});
assert(warnedBefore);
type.defineType('HostedType', type.number);
var warnedAfter = catchWarnings(function(){
assert(HostedType('234.55') === 234.55);
});
assert(warnedAfter === false);
assert(typeHost.someType === type.number);
}
},
{
name: 'double define',
test: function(){
var DoubleTypeA = type.defineType('DoubleType', type.string);
var DoubleTypeB;
var warned = catchWarnings(function(){
var DoubleTypeB = type.defineType('DoubleType', type.date);
});
assert(warned);
assert(type.getTypeByName('DoubleType') === type.date);
}
},
{
name: 'type definition with non string value',
test: function(){
var warned = catchWarnings(function(){
var Three = type.defineType(3, type.object);
});
assert(warned);
}
},
{
name: 'validation',
test: function(){
var StringType = type.getTypeByName('StringType');
var NumberType = type.getTypeByName('NumberType');
type.defineType('StringType', type.string);
var warned = catchWarnings(function(){
type.validate();
});
assert(warned);
type.defineType('NumberType', type.number);
var warnedAgain = catchWarnings(function(){
type.validate();
});
assert(!warnedAgain);
}
}
]
}
]
};
| fateevv/basisjs | test/spec/type.js | JavaScript | mit | 4,048 |
/* Slovenia +*/
/*global jQuery */
(function ($) {
$.ig = $.ig || {};
$.ig.regional = $.ig.regional || {};
if ($.datepicker && $.datepicker.regional) {
$.datepicker.regional['sl'] = {
closeText: 'Zapri',
prevText: '<Prejšnji',
nextText: 'Naslednji>',
currentText: 'Trenutni',
monthNames: ['Januar','Februar','Marec','April','Maj','Junij',
'Julij','Avgust','September','Oktober','November','December'],
monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun',
'Jul','Avg','Sep','Okt','Nov','Dec'],
dayNames: ['Nedelja','Ponedeljek','Torek','Sreda','Četrtek','Petek','Sobota'],
dayNamesShort: ['Ned','Pon','Tor','Sre','Čet','Pet','Sob'],
dayNamesMin: ['Ne','Po','To','Sr','Če','Pe','So'],
weekHeader: 'Teden',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
}
$.ig.regional.sl = {
monthNames: ['Januar', 'Februar', 'Marec', 'April', 'Maj', 'Junij', 'Julij', 'Avgust', 'September', 'Oktober', 'November', 'December'],
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun', 'Jul', 'Avg', 'Sep', 'Okt', 'Nov', 'Dec'],
dayNames: ['Nedelja', 'Ponedeljek', 'Torek', 'Sreda', 'Četrtek', 'Petek', 'Sobota'],
dayNamesShort: ['Ned', 'Pon', 'Tor', 'Sre', 'Čet', 'Pet', 'Sob'],
datePattern: 'd.M.yyyy',
dateLongPattern: 'd. MMMM yyyy',
dateTimePattern: 'd.M.yyyy HH:mm',
timePattern: 'HH:mm',
timeLongPattern: 'HH:mm:ss',
//
numericNegativePattern: '-n$',
numericDecimalSeparator: ',',
numericGroupSeparator: '.',
numericMaxDecimals: 2,
currencyPositivePattern: 'n $',
currencyNegativePattern: '-n $',
currencySymbol: '€',
currencyDecimalSeparator: ',',
currencyGroupSeparator: '.',
percentDecimalSeparator: ',',
percentGroupSeparator: '.'
};
if ($.ig.setRegionalDefault) {
$.ig.setRegionalDefault('sl');
}
})(jQuery); | ajbeaven/personal-finance-sample | PersonalFinance/Scripts/ig/modules/i18n/regional/infragistics.ui.regional-sl.js | JavaScript | mit | 1,974 |
const models = require('../../models');
const {i18n} = require('../../lib/common');
const errors = require('@tryghost/errors');
const urlUtils = require('../../../shared/url-utils');
const ALLOWED_INCLUDES = ['tags', 'authors', 'authors.roles'];
const UNSAFE_ATTRS = ['status', 'authors', 'visibility'];
module.exports = {
docName: 'pages',
browse: {
options: [
'include',
'filter',
'fields',
'formats',
'limit',
'order',
'page',
'debug',
'absolute_urls'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
},
formats: {
values: models.Post.allowedFormats
}
}
},
permissions: {
docName: 'posts',
unsafeAttrs: UNSAFE_ATTRS
},
query(frame) {
return models.Post.findPage(frame.options);
}
},
read: {
options: [
'include',
'fields',
'formats',
'debug',
'absolute_urls',
// NOTE: only for internal context
'forUpdate',
'transacting'
],
data: [
'id',
'slug',
'uuid'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
},
formats: {
values: models.Post.allowedFormats
}
}
},
permissions: {
docName: 'posts',
unsafeAttrs: UNSAFE_ATTRS
},
query(frame) {
return models.Post.findOne(frame.data, frame.options)
.then((model) => {
if (!model) {
throw new errors.NotFoundError({
message: i18n.t('errors.api.pages.pageNotFound')
});
}
return model;
});
}
},
add: {
statusCode: 201,
headers: {},
options: [
'include',
'source'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
},
source: {
values: ['html']
}
}
},
permissions: {
docName: 'posts',
unsafeAttrs: UNSAFE_ATTRS
},
query(frame) {
return models.Post.add(frame.data.pages[0], frame.options)
.then((model) => {
if (model.get('status') !== 'published') {
this.headers.cacheInvalidate = false;
} else {
this.headers.cacheInvalidate = true;
}
return model;
});
}
},
edit: {
headers: {},
options: [
'include',
'id',
'source',
// NOTE: only for internal context
'forUpdate',
'transacting'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
},
id: {
required: true
},
source: {
values: ['html']
}
}
},
permissions: {
docName: 'posts',
unsafeAttrs: UNSAFE_ATTRS
},
query(frame) {
return models.Post.edit(frame.data.pages[0], frame.options)
.then((model) => {
if (
model.get('status') === 'published' && model.wasChanged() ||
model.get('status') === 'draft' && model.previous('status') === 'published'
) {
this.headers.cacheInvalidate = true;
} else if (
model.get('status') === 'draft' && model.previous('status') !== 'published' ||
model.get('status') === 'scheduled' && model.wasChanged()
) {
this.headers.cacheInvalidate = {
value: urlUtils.urlFor({
relativeUrl: urlUtils.urlJoin('/p', model.get('uuid'), '/')
})
};
} else {
this.headers.cacheInvalidate = false;
}
return model;
});
}
},
destroy: {
statusCode: 204,
headers: {
cacheInvalidate: true
},
options: [
'include',
'id'
],
validation: {
options: {
include: {
values: ALLOWED_INCLUDES
},
id: {
required: true
}
}
},
permissions: {
docName: 'posts',
unsafeAttrs: UNSAFE_ATTRS
},
query(frame) {
frame.options.require = true;
return models.Post.destroy(frame.options)
.then(() => null)
.catch(models.Post.NotFoundError, () => {
return Promise.reject(new errors.NotFoundError({
message: i18n.t('errors.api.pages.pageNotFound')
}));
});
}
}
};
| e10/Ghost | core/server/api/v2/pages.js | JavaScript | mit | 5,771 |
'use strict';
module.exports = {
env: 'test'
};
| anishreddy202/ng2-scaffold | server/sdk/test/config.js | JavaScript | mit | 51 |
function trading_init(){
if (!this.trading){
//if (this.trading === undefined || this.trading === null){
this.trading = apiNewOwnedDC(this);
this.trading.label = 'Trading';
this.trading_create_escrow_bag();
this.trading.currants = 0;
}
var escrow = this.trading_get_escrow_bag();
if (!escrow){
this.trading_create_escrow_bag();
}
else if (escrow.capacity != 6 && escrow.countContents() == 0){
escrow.apiDelete();
this.trading_create_escrow_bag();
}
}
function trading_create_escrow_bag(){
// Create a new private storage bag for holding items in escrow
var it = apiNewItemStack('bag_escrow', 1);
it.label = 'Private Trading Storage';
this.apiAddHiddenStack(it);
this.trading.storage_tsid = it.tsid;
}
function trading_reset(){
this.trading_cancel_auto();
if (this.trading){
var escrow = this.trading_get_escrow_bag();
if (escrow){
var contents = escrow.getContents();
for (var i in contents){
if (contents[i]) contents[i].apiDelete();
}
}
}
}
function trading_delete(){
this.trading_cancel_auto();
if (this.trading){
var escrow = this.trading_get_escrow_bag();
if (escrow){
var contents = escrow.getContents();
for (var i in contents){
if (contents[i]) contents[i].apiDelete();
}
escrow.apiDelete();
delete this.trading.storage_tsid;
}
this.trading.apiDelete();
delete this.trading;
}
}
function trading_get_escrow_bag(){
return this.hiddenItems[this.trading.storage_tsid];
}
function trading_has_escrow_items(){
var escrow = this.trading_get_escrow_bag();
return escrow.countContents() > 0 ? true : false;
}
//
// Attempt to start a trade with player 'target_tsid'
//
function trading_request_start(target_tsid){
//log.info(this.tsid+' starting trade with '+target_tsid);
this.trading_init();
//
// Are we currently trading?
//
if (this['!is_trading']){
return {
ok: 0,
error: 'You are already trading with someone else. Finish that up first.'
};
}
//
// Is there stuff in our escrow bag?
//
if (this.trading_has_escrow_items()){
return {
ok: 0,
error: 'You have unsettled items from a previous trade. Make some room in your pack for them before attempting another trade.'
};
}
//
// Valid player?
//
if (target_tsid == this.tsid){
return {
ok: 0,
error: 'No trading with yourself.'
};
}
var target = getPlayer(target_tsid);
if (!target){
return {
ok: 0,
error: 'Not a valid target player.'
};
}
if (this.buddies_is_ignored_by(target) || this.buddies_is_ignoring(target)){
return {
ok: 0,
error: 'You are blocking or blocked by that player.'
};
}
if (!apiIsPlayerOnline(target_tsid)){
return {
ok: 0,
error: 'That player is not online.'
};
}
if (target.getProp('location').tsid != this.location.tsid){
return {
ok: 0,
error: "Oh come on, they're not even in the same location as you!"
};
}
//
// Are they currently trading?
//
if (target['!is_trading']){
target.sendOnlineActivity(this.label+' wanted to trade with you, but you are busy.');
return {
ok: 0,
error: 'That player is already trading with someone else. Please wait until they are done.'
};
}
//
// Is there stuff in their escrow bag?
//
if (target.trading_has_escrow_items()){
target.sendOnlineActivity(this.label+' wanted to trade with you, but you have an unsettled previous trade.');
return {
ok: 0,
error: 'That player is not available for trading right now.'
};
}
//
// PROCEED
//
target.trading_init();
this['!is_trading'] = target.tsid;
target['!is_trading'] = this.tsid;
target.apiSendMsgAsIs({
type: 'trade_start',
tsid: this.tsid
});
//
// Overlays
//
var anncx = {
type: 'pc_overlay',
duration: 0,
pc_tsid: this.tsid,
delta_x: 0,
delta_y: -110,
bubble: true,
width: 70,
height: 70,
swf_url: overlay_key_to_url('trading'),
uid: this.tsid+'_trading'
};
this.location.apiSendAnnouncementX(anncx, this);
anncx['pc_tsid'] = target.tsid;
anncx['uid'] = target.tsid+'_trading';
target.location.apiSendAnnouncementX(anncx, target);
return {
ok: 1
};
}
//
// Cancel an in-progress trade with 'target_tsid'
//
function trading_cancel(target_tsid){
//log.info(this.tsid+' canceling trade with '+target_tsid);
//
// Sanity check
//
if (!this['!is_trading'] || this['!is_trading'] != target_tsid){
return {
ok: 0,
error: 'You are not trading with that player.'
};
}
var target = getPlayer(target_tsid);
//
// Roll back the trade on us and the target
//
this.trading_rollback();
if (target['!is_trading'] == this.tsid){
target.trading_rollback();
}
//
// Overlays
//
this.location.apiSendMsgAsIsX({
type: 'overlay_cancel',
uid: this.tsid+'_trading'
}, this);
if (apiIsPlayerOnline(target_tsid) && target['!is_trading'] == this.tsid){
target.location.apiSendMsgAsIsX({
type: 'overlay_cancel',
uid: target.tsid+'_trading'
}, target);
}
//
// Tell the other player
//
if (apiIsPlayerOnline(target_tsid) && target['!is_trading'] == this.tsid){
target.apiSendMsgAsIs({
type: 'trade_cancel',
tsid: this.tsid
});
target.prompts_add({
txt : this.label+" canceled their trade with you.",
icon_buttons : false,
timeout : 10,
choices : [
{ value : 'ok', label : 'Oh well' }
]
});
}
delete this['!is_trading'];
if (target['!is_trading'] == this.tsid){
delete target['!is_trading'];
}
return {
ok: 1
};
}
function trading_rollback(){
//log.info(this.tsid+' rolling back trade');
//
// Refund all the in-progress items
//
var escrow = this.trading_get_escrow_bag();
if (escrow){
var returned = [];
var overflow = false;
var contents = escrow.getContents();
for (var i in contents){
if (contents[i]){
var restore = escrow.removeItemStackSlot(i);
var count = restore.count;
var remaining = this.addItemStack(restore);
if (remaining) overflow = true;
if (remaining != count){
returned.push(pluralize(count-remaining, restore.name_single, restore.name_plural));
}
}
}
if (overflow){
//log.info('trading_rollback overflow detected');
this.prompts_add({
txt : "Your magic rock is holding items from a previous trade for you. Make room in your pack to hold them.",
icon_buttons : false,
timeout : 30,
choices : [
{ value : 'ok', label : 'Very well' }
]
});
this.trading_reorder_escrow();
}
if (returned.length){
this.prompts_add({
txt : "Your "+pretty_list(returned, ' and ')+" "+(returned.length == 1 ? 'has' : 'have')+" been returned to you.",
icon_buttons : false,
timeout : 5,
choices : [
{ value : 'ok', label : 'OK' }
]
});
}
}
//
// Refund currants
//
if (this.trading.currants){
this.stats_add_currants(this.trading.currants);
this.trading.currants = 0;
}
delete this['!trade_accepted'];
}
//
// Cancel any in-progress trade
//
function trading_cancel_auto(){
//log.info(this.tsid+' canceling all trades');
if (this['!is_trading']) this.trading_cancel(this['!is_trading']);
}
//
// Add an item to the trade
//
function trading_add_item(target_tsid, itemstack_tsid, amount){
//log.info(this.tsid+' adding item '+itemstack_tsid+' to trade with '+target_tsid);
//
// Sanity check
//
if (!this['!is_trading'] || this['!is_trading'] != target_tsid){
return {
ok: 0,
error: 'You are not trading with that player.'
};
}
var target = getPlayer(target_tsid);
if (!apiIsPlayerOnline(target_tsid)){
return {
ok: 0,
error: 'That player is not online.'
};
}
//
// Get the item, put it in escrow
//
delete this['!trade_accepted'];
delete target['!trade_accepted'];
var ret = this.trading_add_item_do(itemstack_tsid, amount);
if (!ret['ok']){
return ret;
}
//
// Tell the other player
//
if (ret.item_class){
var rsp = {
type: 'trade_add_item',
tsid: this.tsid,
itemstack_class: ret.item_class,
amount: ret.count,
slot: ret.slot,
label: ret.label,
config: ret.config
};
if (ret.tool_state) rsp.tool_state = ret.tool_state;
target.apiSendMsgAsIs(rsp);
}
return {
ok: 1
};
}
function trading_add_item_do(itemstack_tsid, amount, destination_slot){
//log.info('trading_add_item_do '+itemstack_tsid+' ('+amount+')');
var item = this.removeItemStackTsid(itemstack_tsid, amount);
if (!item){
return {
ok: 0,
error: "That item is not in your possession."
};
}
var target = getPlayer(this['!is_trading']);
if (!item.has_parent('furniture_base') && target.isBagFull(item)){
target.sendOnlineActivity(this.label+' tried to offer some '+item.label+' for trade, but you cannot hold it.');
this.items_put_back(item);
return {
ok: 0,
error: "The other player cannot hold that item."
};
}
var item_class = item.class_tsid;
var have_count = this.countItemClass(item_class);
if (item.has_parent('furniture_base')){
have_count = this.furniture_get_bag().countItemClass(item_class);
}
// If this is a stack we split off from somewhere, we need to add it to the count
if (!item.container) have_count += item.count;
//log.info('trading_add_item_do have_count: '+have_count+', amount: '+amount);
if (have_count < amount){
this.items_put_back(item);
return {
ok: 0,
error: "You don't have enough of that item."
};
}
//
// Some things are untradeable -- check them here
//
if (item.is_bag && item.countContents() > 0){
this.items_put_back(item);
return {
ok: 0,
error: "You may not trade non-empty bags."
};
}
if (item.isSoulbound()){
this.items_put_back(item);
return {
ok: 0,
error: "That item is locked to you, and can't be traded."
};
}
var escrow = this.trading_get_escrow_bag();
var slots = {};
var contents = escrow.getContents();
for (var i in contents){
if (contents[i]){
slots[i] = contents[i].count;
}
}
var item_count = item.count;
var remaining = escrow.addItemStack(item, destination_slot);
if (remaining == item_count){
var restore = escrow.removeItemStackClass(item.class_tsid, remaining);
this.items_put_back(item);
this.addItemStack(restore);
return {
ok: 0,
error: "Oops! We couldn't place that item in escrow."
};
}
if (item_count < amount){
var still_need = amount - item_count;
do {
var stack = this.removeItemStackClass(item_class, still_need);
if (!stack){
return {
ok: 0,
error: "Oops! We couldn't place that item in escrow."
};
}
still_need -= stack.count;
remaining = escrow.addItemStack(stack);
if (remaining){
var restore = escrow.removeItemStackClass(item.class_tsid, remaining);
this.items_put_back(stack);
this.addItemStack(restore);
return {
ok: 0,
error: "Oops! We couldn't place that item in escrow."
};
}
} while (still_need > 0);
}
//
// Send changes
//
contents = escrow.getContents();
for (var i in contents){
if (contents[i]){
if (slots[i] && contents[i].count != slots[i]){
var rsp = {
type: 'trade_change_item',
tsid: this.tsid,
itemstack_class: contents[i].class_id,
amount: contents[i].count,
slot: i,
label: contents[i].label
};
if (contents[i].is_tool) rsp.tool_state = contents[i].get_tool_state();
target.apiSendMsgAsIs(rsp);
}
}
}
if (item.apiIsDeleted()){
//log.info('Stack was merged');
return {
ok: 1
};
}
var rsp = {
ok: 1,
item_class: item_class,
slot: intval(item.slot),
count: item.count,
label: item.label
};
if (item.is_tool) rsp.tool_state = item.get_tool_state();
// Config?
if (item.make_config){
rsp.config = item.make_config();
}
return rsp;
}
//
// Remove an item from the trade
//
function trading_remove_item(target_tsid, itemstack_tsid, amount){
//log.info(this.tsid+' removing item '+itemstack_tsid+' from trade with '+target_tsid);
//
// Sanity check
//
if (!this['!is_trading'] || this['!is_trading'] != target_tsid){
return {
ok: 0,
error: 'You are not trading with that player.'
};
}
var target = getPlayer(target_tsid);
if (!apiIsPlayerOnline(target_tsid)){
return {
ok: 0,
error: 'That player is not online.'
};
}
//
// Get the item from escrow
//
delete this['!trade_accepted'];
delete target['!trade_accepted'];
var ret = this.trading_remove_item_do(itemstack_tsid, amount);
if (!ret['ok']){
return ret;
}
//
// Tell the other player
//
target.apiSendMsgAsIs({
type: 'trade_remove_item',
tsid: this.tsid,
itemstack_class: ret.item_class,
amount: amount,
slot: ret.slot,
label: ret.label
});
return {
ok: 1
};
}
function trading_remove_item_do(itemstack_tsid, amount){
var escrow = this.trading_get_escrow_bag();
if (escrow.items[itemstack_tsid]){
var slot = escrow.items[itemstack_tsid].slot;
var item = escrow.removeItemStackTsid(itemstack_tsid, amount);
//log.info('trading_remove_item_do slot is '+slot);
}
else{
return {
ok: 0,
error: "That item is not in your escrow storage."
};
}
if (item.count != amount){
this.items_put_back(item);
return {
ok: 0,
error: "You don't have enough of that item in escrow."
};
}
var item_class = item.class_tsid;
var item_label = item.label;
var remaining = this.addItemStack(item);
if (remaining){
var restore = this.removeItemStackClass(item.class_tsid, remaining);
this.items_put_back(item);
escrow.addItemStack(restore);
return {
ok: 0,
error: "Oops! We couldn't place that item in your pack."
};
}
//
// Do we need to move everything around?
//
this.trading_reorder_escrow();
return {
ok: 1,
item_class: item_class,
slot: intval(slot),
label: item_label
};
}
//
// Move items around in the escrow bag in order to keep things in sequential slots
//
function trading_reorder_escrow(){
var escrow = this.trading_get_escrow_bag();
if (escrow.countContents()){
var escrow_contents = escrow.getContents();
for (var slot in escrow_contents){
if (!escrow_contents[slot]){
for (var i=intval(slot); i<escrow.capacity; i++){
if (escrow_contents[i+1]){
escrow.addItemStack(escrow.removeItemStackSlot(i+1), i);
}
}
break;
}
}
}
}
//
// Change the amount of an item to trage
//
function trading_change_item(target_tsid, itemstack_tsid, amount){
//log.info(this.tsid+' changing item '+itemstack_tsid+' to trade with '+target_tsid+' ('+amount+')');
//
// Sanity check
//
if (!this['!is_trading'] || this['!is_trading'] != target_tsid){
return {
ok: 0,
error: 'You are not trading with that player.'
};
}
var target = getPlayer(target_tsid);
if (!apiIsPlayerOnline(target_tsid)){
return {
ok: 0,
error: 'That player is not online.'
};
}
//
// Adjust counts
//
delete this['!trade_accepted'];
delete target['!trade_accepted'];
var escrow = this.trading_get_escrow_bag();
var contents = escrow.getAllContents();
var item = contents[itemstack_tsid];
if (!item){
return {
ok: 0,
error: "That item is not in your escrow storage."
};
}
//log.info('trading_change_item '+item.count+' != '+amount);
if (item.count != amount){
if (item.count < amount){
// We need an item from the pack to move
var pack_item = this.findFirst(item.class_id);
if (!pack_item){
return {
ok: 0,
error: "You don't have any more of that item."
};
}
//log.info('pack_item: '+pack_item.tsid);
//log.info('Adding '+(amount-item.count));
var ret = this.trading_add_item_do(pack_item.tsid, amount-item.count, item.slot);
amount = ret.count;
}
else{
//log.info('Removing '+(item.count-amount));
var ret = this.trading_remove_item_do(itemstack_tsid, item.count-amount);
}
if (!ret['ok']){
return ret;
}
//
// Tell the other player
//
if (ret.item_class){
//log.info('trade_change_item ---------------------- slot '+ret.slot+' = '+amount);
target.apiSendMsgAsIs({
type: 'trade_change_item',
tsid: this.tsid,
itemstack_class: ret.item_class,
amount: amount,
slot: ret.slot,
label: ret.label,
config: ret.config
});
}
}
return {
ok: 1
};
}
//
// Update the currants on the trade
//
function trading_update_currants(target_tsid, amount){
//log.info(this.tsid+' updating currants to '+amount+' on trade with '+target_tsid);
//
// Sanity check
//
if (!this['!is_trading'] || this['!is_trading'] != target_tsid){
return {
ok: 0,
error: 'You are not trading with that player.'
};
}
var target = getPlayer(target_tsid);
if (!apiIsPlayerOnline(target_tsid)){
return {
ok: 0,
error: 'That player is not online.'
};
}
//
// Put the currants in escrow
//
delete this['!trade_accepted'];
delete target['!trade_accepted'];
var amount_diff = amount - this.trading.currants;
//log.info('Currants diff of '+amount+' - '+this.trading.currants+' is '+amount_diff);
//log.info('Player currently has: '+this.stats.currants.value);
if (amount_diff != 0){
if (amount_diff < 0){
//log.info('Restoring '+Math.abs(amount_diff));
this.stats_add_currants(Math.abs(amount_diff));
}
else{
if (!this.stats_try_remove_currants(amount_diff, {type: 'trading', target: target_tsid})){
return {
ok: 0,
error: "You don't have enough currants for that."
};
}
}
this.trading.currants = amount;
//
// Tell the other player
//
target.apiSendMsgAsIs({
type: 'trade_currants',
tsid: this.tsid,
amount: this.trading.currants
});
}
return {
ok: 1
};
}
//
// Accept the trade
//
function trading_accept(target_tsid){
//log.info(this.tsid+' accepting trade with '+target_tsid);
//
// Sanity check
//
if (!this['!is_trading'] || this['!is_trading'] != target_tsid){
return {
ok: 0,
error: 'You are not trading with that player.'
};
}
var target = getPlayer(target_tsid);
if (!apiIsPlayerOnline(target_tsid)){
return {
ok: 0,
error: 'That player is not online.'
};
}
this['!trade_accepted'] = true;
//
// Tell the other player
//
target.apiSendMsgAsIs({
type: 'trade_accept',
tsid: this.tsid
});
//
// If both sides have accepted, then do it
//
if (target['!trade_accepted']){
var ret = this.trading_complete(target_tsid);
if (!ret['ok']){
return ret;
}
}
return {
ok: 1
};
}
//
// Unlock the trade
//
function trading_unlock(target_tsid){
//log.info(this.tsid+' unlocking trade with '+target_tsid);
//
// Sanity check
//
if (!this['!is_trading'] || this['!is_trading'] != target_tsid){
return {
ok: 0,
error: 'You are not trading with that player.'
};
}
var target = getPlayer(target_tsid);
if (!apiIsPlayerOnline(target_tsid)){
return {
ok: 0,
error: 'That player is not online.'
};
}
delete this['!trade_accepted'];
//
// Tell the other player
//
target.apiSendMsgAsIs({
type: 'trade_unlock',
tsid: this.tsid
});
return {
ok: 1
};
}
//
// Complete the trade
//
function trading_complete(target_tsid){
//log.info(this.tsid+' completing trade with '+target_tsid);
//
// Sanity check
//
if (!this['!is_trading'] || this['!is_trading'] != target_tsid){
return {
ok: 0,
error: 'You are not trading with that player.'
};
}
var target = getPlayer(target_tsid);
if (!apiIsPlayerOnline(target_tsid)){
return {
ok: 0,
error: 'That player is not online.'
};
}
//
// Have both sides accepted?
//
if (!this['!trade_accepted']){
return {
ok: 0,
error: 'You have not accepted this trade.'
};
}
if (!target['!trade_accepted']){
return {
ok: 0,
error: 'That player has not accepted this trade.'
};
}
//
// Perform the transfer
//
this.trading_transfer(target_tsid);
target.trading_transfer(this.tsid);
//
// Overlays
//
this.location.apiSendMsgAsIsX({
type: 'overlay_cancel',
uid: this.tsid+'_trading'
}, this);
target.location.apiSendMsgAsIsX({
type: 'overlay_cancel',
uid: target.tsid+'_trading'
}, target);
//
// Tell both players that we are done
//
this.apiSendMsgAsIs({
type: 'trade_complete',
tsid: target_tsid
});
target.apiSendMsgAsIs({
type: 'trade_complete',
tsid: this.tsid
});
//
// Cleanup and exit
//
delete this['!is_trading'];
delete target['!is_trading'];
delete this['!trade_accepted'];
delete target['!trade_accepted'];
return {
ok: 1
};
}
//
// Transfer items/currants from escrow to target_tsid.
// If something goes wrong, oh well!
//
function trading_transfer(target_tsid){
var target = getPlayer(target_tsid);
//
// Items!
//
var traded_something = false;
var escrow = this.trading_get_escrow_bag();
if (escrow){
var contents = escrow.getContents();
var overflow = false;
for (var i in contents){
if (contents[i]){
var item = escrow.removeItemStackSlot(i);
// Item callback
if (item.onTrade) item.onTrade(this, target);
var remaining = target.addItemStack(item);
if (remaining){
var target_escrow = target.trading_get_escrow_bag();
target_escrow.addItemStack(item);
overflow = true;
}
traded_something = true;
}
}
if (overflow){
target.prompts_add({
txt : "Some of the items you received in your trade with "+this.label+" did not fit in your pack. Your magic rock will hold them for you until you make room, and you cannot start another trade until you do so.",
icon_buttons : false,
timeout : 30,
choices : [
{ value : 'ok', label : 'Very well' }
]
});
}
}
//
// Currants!
//
if (this.trading.currants){
target.stats_add_currants(this.trading.currants, {'trade':this.tsid});
this.trading.currants = 0;
traded_something = true;
}
if (traded_something){
//
// Achievements
//
this.achievements_increment('players_traded', target_tsid);
target.achievements_increment('players_traded', this.tsid);
}
} | yelworc/eleven-gsjs | players/inc_trading.js | JavaScript | mit | 22,066 |
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
/**
* The tween class for Armature.
* @class
* @extends ccs.ProcessBase
*
* @property {ccs.ArmatureAnimation} animation - The animation
*/
ccs.Tween = ccs.ProcessBase.extend(/** @lends ccs.Tween# */{
_tweenData:null,
_to:null,
_from:null,
_between:null,
_movementBoneData:null,
_bone:null,
_frameTweenEasing:0,
_betweenDuration:0,
_totalDuration:0,
_toIndex:0,
_fromIndex:0,
_animation:null,
_passLastFrame:false,
/**
* Construction of ccs.Tween.
*/
ctor:function () {
ccs.ProcessBase.prototype.ctor.call(this);
this._frameTweenEasing = ccs.TweenType.linear;
},
/**
* initializes a ccs.Tween with a CCBone
* @param {ccs.Bone} bone
* @return {Boolean}
*/
init:function (bone) {
this._from = new ccs.FrameData();
this._between = new ccs.FrameData();
this._bone = bone;
this._tweenData = this._bone.getTweenData();
this._tweenData.displayIndex = -1;
this._animation = this._bone.getArmature() != null ?
this._bone.getArmature().getAnimation() :
null;
return true;
},
/**
* Plays the tween.
* @param {ccs.MovementBoneData} movementBoneData
* @param {Number} durationTo
* @param {Number} durationTween
* @param {Boolean} loop
* @param {ccs.TweenType} tweenEasing
*/
play:function (movementBoneData, durationTo, durationTween, loop, tweenEasing) {
ccs.ProcessBase.prototype.play.call(this, durationTo, durationTween, loop, tweenEasing);
this._loopType = (loop)?ccs.ANIMATION_TYPE_TO_LOOP_FRONT:ccs.ANIMATION_TYPE_NO_LOOP;
this._totalDuration = 0;
this._betweenDuration = 0;
this._fromIndex = this._toIndex = 0;
var difMovement = movementBoneData != this._movementBoneData;
this.setMovementBoneData(movementBoneData);
this._rawDuration = this._movementBoneData.duration;
var nextKeyFrame = this._movementBoneData.getFrameData(0);
this._tweenData.displayIndex = nextKeyFrame.displayIndex;
if (this._bone.getArmature().getArmatureData().dataVersion >= ccs.CONST_VERSION_COMBINED) {
ccs.TransformHelp.nodeSub(this._tweenData, this._bone.getBoneData());
this._tweenData.scaleX += 1;
this._tweenData.scaleY += 1;
}
if (this._rawDuration == 0) {
this._loopType = ccs.ANIMATION_TYPE_SINGLE_FRAME;
if (durationTo == 0)
this.setBetween(nextKeyFrame, nextKeyFrame);
else
this.setBetween(this._tweenData, nextKeyFrame);
this._frameTweenEasing = ccs.TweenType.linear;
}
else if (this._movementBoneData.frameList.length > 1) {
this._durationTween = durationTween * this._movementBoneData.scale;
if (loop && this._movementBoneData.delay != 0)
this.setBetween(this._tweenData, this.tweenNodeTo(this.updateFrameData(1 - this._movementBoneData.delay), this._between));
else {
if (!difMovement || durationTo == 0)
this.setBetween(nextKeyFrame, nextKeyFrame);
else
this.setBetween(this._tweenData, nextKeyFrame);
}
}
this.tweenNodeTo(0);
},
/**
* Goes to specified frame and plays frame.
* @param {Number} frameIndex
*/
gotoAndPlay: function (frameIndex) {
ccs.ProcessBase.prototype.gotoFrame.call(this, frameIndex);
this._totalDuration = 0;
this._betweenDuration = 0;
this._fromIndex = this._toIndex = 0;
this._isPlaying = true;
this._isComplete = this._isPause = false;
this._currentPercent = this._curFrameIndex / (this._rawDuration-1);
this._currentFrame = this._nextFrameIndex * this._currentPercent;
},
/**
* Goes to specified frame and pauses frame.
* @param {Number} frameIndex
*/
gotoAndPause: function (frameIndex) {
this.gotoAndPlay(frameIndex);
this.pause();
},
/**
* update will call this handler, you can handle your logic here
*/
updateHandler:function () {
var locCurrentPercent = this._currentPercent || 1;
var locLoopType = this._loopType;
if (locCurrentPercent >= 1) {
switch (locLoopType) {
case ccs.ANIMATION_TYPE_SINGLE_FRAME:
locCurrentPercent = 1;
this._isComplete = true;
this._isPlaying = false;
break;
case ccs.ANIMATION_TYPE_NO_LOOP:
locLoopType = ccs.ANIMATION_TYPE_MAX;
if (this._durationTween <= 0)
locCurrentPercent = 1;
else
locCurrentPercent = (locCurrentPercent - 1) * this._nextFrameIndex / this._durationTween;
if (locCurrentPercent >= 1) {
locCurrentPercent = 1;
this._isComplete = true;
this._isPlaying = false;
break;
} else {
this._nextFrameIndex = this._durationTween;
this._currentFrame = locCurrentPercent * this._nextFrameIndex;
this._totalDuration = 0;
this._betweenDuration = 0;
this._fromIndex = this._toIndex = 0;
break;
}
case ccs.ANIMATION_TYPE_TO_LOOP_FRONT:
locLoopType = ccs.ANIMATION_TYPE_LOOP_FRONT;
this._nextFrameIndex = this._durationTween > 0 ? this._durationTween : 1;
if (this._movementBoneData.delay != 0) {
this._currentFrame = (1 - this._movementBoneData.delay) * this._nextFrameIndex;
locCurrentPercent = this._currentFrame / this._nextFrameIndex;
} else {
locCurrentPercent = 0;
this._currentFrame = 0;
}
this._totalDuration = 0;
this._betweenDuration = 0;
this._fromIndex = this._toIndex = 0;
break;
case ccs.ANIMATION_TYPE_MAX:
locCurrentPercent = 1;
this._isComplete = true;
this._isPlaying = false;
break;
default:
this._currentFrame = ccs.fmodf(this._currentFrame, this._nextFrameIndex);
break;
}
}
if (locCurrentPercent < 1 && locLoopType < ccs.ANIMATION_TYPE_TO_LOOP_BACK)
locCurrentPercent = Math.sin(locCurrentPercent * cc.PI / 2);
this._currentPercent = locCurrentPercent;
this._loopType = locLoopType;
if (locLoopType > ccs.ANIMATION_TYPE_TO_LOOP_BACK)
locCurrentPercent = this.updateFrameData(locCurrentPercent);
if (this._frameTweenEasing != ccs.TweenType.tweenEasingMax)
this.tweenNodeTo(locCurrentPercent);
},
/**
* Calculate the between value of _from and _to, and give it to between frame data
* @param {ccs.FrameData} from
* @param {ccs.FrameData} to
* @param {Boolean} [limit=true]
*/
setBetween:function (from, to, limit) { //TODO set tweenColorTo to protected in v3.1
if(limit === undefined)
limit = true;
do {
if (from.displayIndex < 0 && to.displayIndex >= 0) {
this._from.copy(to);
this._between.subtract(to, to, limit);
break;
}
if (to.displayIndex < 0 && from.displayIndex >= 0) {
this._from.copy(from);
this._between.subtract(to, to, limit);
break;
}
this._from.copy(from);
this._between.subtract(from, to, limit);
} while (0);
if (!from.isTween){
this._tweenData.copy(from);
this._tweenData.isTween = true;
}
this.arriveKeyFrame(from);
},
/**
* Update display index and process the key frame event when arrived a key frame
* @param {ccs.FrameData} keyFrameData
*/
arriveKeyFrame:function (keyFrameData) { //TODO set tweenColorTo to protected in v3.1
if (keyFrameData) {
var locBone = this._bone;
var displayManager = locBone.getDisplayManager();
//! Change bone's display
var displayIndex = keyFrameData.displayIndex;
if (!displayManager.getForceChangeDisplay())
displayManager.changeDisplayWithIndex(displayIndex, false);
//! Update bone zorder, bone's zorder is determined by frame zorder and bone zorder
this._tweenData.zOrder = keyFrameData.zOrder;
locBone.updateZOrder();
//! Update blend type
this._bone.setBlendFunc(keyFrameData.blendFunc);
var childAramture = locBone.getChildArmature();
if (childAramture) {
if (keyFrameData.movement != "")
childAramture.getAnimation().play(keyFrameData.movement);
}
}
},
/**
* According to the percent to calculate current CCFrameData with tween effect
* @param {Number} percent
* @param {ccs.FrameData} [node]
* @return {ccs.FrameData}
*/
tweenNodeTo:function (percent, node) { //TODO set tweenColorTo to protected in v3.1
if (!node)
node = this._tweenData;
var locFrom = this._from;
var locBetween = this._between;
if (!locFrom.isTween)
percent = 0;
node.x = locFrom.x + percent * locBetween.x;
node.y = locFrom.y + percent * locBetween.y;
node.scaleX = locFrom.scaleX + percent * locBetween.scaleX;
node.scaleY = locFrom.scaleY + percent * locBetween.scaleY;
node.skewX = locFrom.skewX + percent * locBetween.skewX;
node.skewY = locFrom.skewY + percent * locBetween.skewY;
this._bone.setTransformDirty(true);
if (node && locBetween.isUseColorInfo)
this.tweenColorTo(percent, node);
return node;
},
/**
* According to the percent to calculate current color with tween effect
* @param {Number} percent
* @param {ccs.FrameData} node
*/
tweenColorTo:function(percent,node){ //TODO set tweenColorTo to protected in v3.1
var locFrom = this._from;
var locBetween = this._between;
node.a = locFrom.a + percent * locBetween.a;
node.r = locFrom.r + percent * locBetween.r;
node.g = locFrom.g + percent * locBetween.g;
node.b = locFrom.b + percent * locBetween.b;
this._bone.updateColor();
},
/**
* Calculate which frame arrived, and if current frame have event, then call the event listener
* @param {Number} currentPercent
* @return {Number}
*/
updateFrameData:function (currentPercent) { //TODO set tweenColorTo to protected in v3.1
if (currentPercent > 1 && this._movementBoneData.delay != 0)
currentPercent = ccs.fmodf(currentPercent,1);
var playedTime = (this._rawDuration-1) * currentPercent;
var from, to;
var locTotalDuration = this._totalDuration,locBetweenDuration = this._betweenDuration, locToIndex = this._toIndex;
// if play to current frame's front or back, then find current frame again
if (playedTime < locTotalDuration || playedTime >= locTotalDuration + locBetweenDuration) {
/*
* get frame length, if this._toIndex >= _length, then set this._toIndex to 0, start anew.
* this._toIndex is next index will play
*/
var frames = this._movementBoneData.frameList;
var length = frames.length;
if (playedTime < frames[0].frameID){
from = to = frames[0];
this.setBetween(from, to);
return this._currentPercent;
}
if (playedTime >= frames[length - 1].frameID) {
// If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on.
if (this._passLastFrame) {
from = to = frames[length - 1];
this.setBetween(from, to);
return this._currentPercent;
}
this._passLastFrame = true;
} else
this._passLastFrame = false;
do {
this._fromIndex = locToIndex;
from = frames[this._fromIndex];
locTotalDuration = from.frameID;
locToIndex = this._fromIndex + 1;
if (locToIndex >= length)
locToIndex = 0;
to = frames[locToIndex];
//! Guaranteed to trigger frame event
if(from.strEvent && !this._animation.isIgnoreFrameEvent())
this._animation.frameEvent(this._bone, from.strEvent,from.frameID, playedTime);
if (playedTime == from.frameID|| (this._passLastFrame && this._fromIndex == length-1))
break;
} while (playedTime < from.frameID || playedTime >= to.frameID);
locBetweenDuration = to.frameID - from.frameID;
this._frameTweenEasing = from.tweenEasing;
this.setBetween(from, to, false);
this._totalDuration = locTotalDuration;
this._betweenDuration = locBetweenDuration;
this._toIndex = locToIndex;
}
currentPercent = locBetweenDuration == 0 ? 0 : (playedTime - this._totalDuration) / this._betweenDuration;
/*
* if frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween.
*/
var tweenType = (this._frameTweenEasing != ccs.TweenType.linear) ? this._frameTweenEasing : this._tweenEasing;
if (tweenType != ccs.TweenType.tweenEasingMax && tweenType != ccs.TweenType.linear && !this._passLastFrame) {
currentPercent = ccs.TweenFunction.tweenTo(currentPercent, tweenType, this._from.easingParams);
}
return currentPercent;
},
/**
* Sets Armature animation to ccs.Tween.
* @param {ccs.ArmatureAnimation} animation
*/
setAnimation:function (animation) {
this._animation = animation;
},
/**
* Returns Armature animation of ccs.Tween.
* @return {ccs.ArmatureAnimation}
*/
getAnimation:function () {
return this._animation;
},
/**
* Sets movement bone data to ccs.Tween.
* @param data
*/
setMovementBoneData: function(data){
this._movementBoneData = data;
}
});
var _p = ccs.Tween.prototype;
// Extended properties
/** @expose */
_p.animation;
cc.defineGetterSetter(_p, "animation", _p.getAnimation, _p.setAnimation);
_p = null;
/**
* Allocates and initializes a ArmatureAnimation.
* @param {ccs.Bone} bone
* @return {ccs.Tween}
* @example
* // example
* var animation = ccs.ArmatureAnimation.create();
*/
ccs.Tween.create = function (bone) { //TODO it will be deprecated in v3.1
var tween = new ccs.Tween();
if (tween && tween.init(bone))
return tween;
return null;
};
| oneliojr/CityDefender | frameworks/cocos2d-html5/extensions/cocostudio/armature/animation/CCTween.js | JavaScript | mit | 16,987 |
var path = require('path');
var async = require('async');
module.exports = function(content) {
var cb = this.async();
var json = JSON.parse(content);
async.mapSeries(
json.imports,
function(url, callback) {
this.loadModule(url, function(err, source, map, module) {
if (err) {
return callback(err);
}
callback(null, this.exec(source, url));
}.bind(this))
}.bind(this),
function(err, results) {
if (err) {
return cb(err);
}
// Combine all the results into one object and return it
cb(null, 'module.exports = ' + JSON.stringify(results.reduce(function(prev, result) {
return Object.assign({}, prev, result);
}, json)));
}
);
}
| nkzawa/webpack | test/cases/loaders/issue-2299/loader/index.js | JavaScript | mit | 684 |
var THREEx = THREEx || {}
//////////////////////////////////////////////////////////////////////////////////
// Constructor //
//////////////////////////////////////////////////////////////////////////////////
/**
* create a dynamic texture with a underlying canvas
*
* @param {Number} width width of the canvas
* @param {Number} height height of the canvas
*/
THREEx.DynamicTexture = function(width, height){
var canvas = document.createElement( 'canvas' )
canvas.width = width
canvas.height = height
this.canvas = canvas
var context = canvas.getContext( '2d' )
this.context = context
var texture = new THREE.Texture(canvas)
this.texture = texture
}
//////////////////////////////////////////////////////////////////////////////////
// methods //
//////////////////////////////////////////////////////////////////////////////////
/**
* clear the canvas
*
* @param {String*} fillStyle the fillStyle to clear with, if not provided, fallback on .clearRect
* @return {THREEx.DynamicTexture} the object itself, for chained texture
*/
THREEx.DynamicTexture.prototype.clear = function(fillStyle){
// depends on fillStyle
if( fillStyle !== undefined ){
this.context.fillStyle = fillStyle
this.context.fillRect(0,0,this.canvas.width, this.canvas.height)
}else{
this.context.clearRect(0,0,this.canvas.width, this.canvas.height)
}
// make the texture as .needsUpdate
this.texture.needsUpdate = true;
// for chained API
return this;
}
/**
* draw text
*
* @param {String} text the text to display
* @param {Number|undefined} x if provided, it is the x where to draw, if not, the text is centered
* @param {Number} y the y where to draw the text
* @param {String*} fillStyle the fillStyle to clear with, if not provided, fallback on .clearRect
* @param {String*} contextFont the font to use
* @return {THREEx.DynamicTexture} the object itself, for chained texture
*/
THREEx.DynamicTexture.prototype.drawText = function(text, x, y, fillStyle, contextFont){
// set font if needed
if( contextFont !== undefined ) this.context.font = contextFont;
// if x isnt provided
if( x === undefined || x === null ){
var textSize = this.context.measureText(text);
x = (this.canvas.width - textSize.width) / 2;
}
// actually draw the text
this.context.fillStyle = fillStyle;
this.context.fillText(text, x, y);
// make the texture as .needsUpdate
this.texture.needsUpdate = true;
// for chained API
return this;
};
THREEx.DynamicTexture.prototype.drawTextCooked = function(text, options){
var context = this.context
var canvas = this.canvas
options = options || {}
var params = {
margin : options.margin !== undefined ? options.margin : 0.1,
lineHeight : options.lineHeight !== undefined ? options.lineHeight : 0.1,
align : options.align !== undefined ? options.align : 'left',
fillStyle : options.fillStyle !== undefined ? options.fillStyle : 'black',
}
context.save()
context.fillStyle = params.fillStyle;
var y = (params.lineHeight + params.margin)*canvas.height
while(text.length > 0 ){
// compute the text for specifically this line
var maxText = computeMaxTextLength(text)
// update the remaining text
text = text.substr(maxText.length)
// compute x based on params.align
var textSize = context.measureText(maxText);
if( params.align === 'left' ){
var x = params.margin*canvas.width
}else if( params.align === 'right' ){
var x = (1-params.margin)*canvas.width - textSize.width
}else if( params.align === 'center' ){
var x = (canvas.width - textSize.width) / 2;
}else console.assert( false )
// actually draw the text at the proper position
this.context.fillText(maxText, x, y);
// goto the next line
y += params.lineHeight*canvas.height
}
context.restore()
// make the texture as .needsUpdate
this.texture.needsUpdate = true;
// for chained API
return this;
function computeMaxTextLength(text){
var maxText = ''
var maxWidth = (1-params.margin*2)*canvas.width
while( maxText.length !== text.length ){
var textSize = context.measureText(maxText);
if( textSize.width > maxWidth ) break;
maxText += text.substr(maxText.length, 1)
}
return maxText
}
}
/**
* execute the drawImage on the internal context
* the arguments are the same the official context2d.drawImage
*/
THREEx.DynamicTexture.prototype.drawImage = function(/* same params as context2d.drawImage */){
// call the drawImage
this.context.drawImage.apply(this.context, arguments)
// make the texture as .needsUpdate
this.texture.needsUpdate = true;
// for chained API
return this;
}
| gvcm/CWAPP | vendor/dynamictexture.js | JavaScript | mit | 4,633 |
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var React = require('react');
var React__default = _interopDefault(React);
var mobx = require('mobx');
var reactNative = require('react-native');
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
// These functions can be stubbed out in specific environments
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x.default : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var reactIs_production_min = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports,"__esModule",{value:!0});
var b="function"===typeof Symbol&&Symbol.for,c=b?Symbol.for("react.element"):60103,d=b?Symbol.for("react.portal"):60106,e=b?Symbol.for("react.fragment"):60107,f=b?Symbol.for("react.strict_mode"):60108,g=b?Symbol.for("react.profiler"):60114,h=b?Symbol.for("react.provider"):60109,k=b?Symbol.for("react.context"):60110,l=b?Symbol.for("react.async_mode"):60111,m=b?Symbol.for("react.forward_ref"):60112,n=b?Symbol.for("react.placeholder"):60113;
function q(a){if("object"===typeof a&&null!==a){var p=a.$$typeof;switch(p){case c:switch(a=a.type,a){case l:case e:case g:case f:return a;default:switch(a=a&&a.$$typeof,a){case k:case m:case h:return a;default:return p}}case d:return p}}}exports.typeOf=q;exports.AsyncMode=l;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=m;exports.Fragment=e;exports.Profiler=g;exports.Portal=d;exports.StrictMode=f;
exports.isValidElementType=function(a){return "string"===typeof a||"function"===typeof a||a===e||a===l||a===g||a===f||a===n||"object"===typeof a&&null!==a&&("function"===typeof a.then||a.$$typeof===h||a.$$typeof===k||a.$$typeof===m)};exports.isAsyncMode=function(a){return q(a)===l};exports.isContextConsumer=function(a){return q(a)===k};exports.isContextProvider=function(a){return q(a)===h};exports.isElement=function(a){return "object"===typeof a&&null!==a&&a.$$typeof===c};
exports.isForwardRef=function(a){return q(a)===m};exports.isFragment=function(a){return q(a)===e};exports.isProfiler=function(a){return q(a)===g};exports.isPortal=function(a){return q(a)===d};exports.isStrictMode=function(a){return q(a)===f};
});
unwrapExports(reactIs_production_min);
var reactIs_production_min_1 = reactIs_production_min.typeOf;
var reactIs_production_min_2 = reactIs_production_min.AsyncMode;
var reactIs_production_min_3 = reactIs_production_min.ContextConsumer;
var reactIs_production_min_4 = reactIs_production_min.ContextProvider;
var reactIs_production_min_5 = reactIs_production_min.Element;
var reactIs_production_min_6 = reactIs_production_min.ForwardRef;
var reactIs_production_min_7 = reactIs_production_min.Fragment;
var reactIs_production_min_8 = reactIs_production_min.Profiler;
var reactIs_production_min_9 = reactIs_production_min.Portal;
var reactIs_production_min_10 = reactIs_production_min.StrictMode;
var reactIs_production_min_11 = reactIs_production_min.isValidElementType;
var reactIs_production_min_12 = reactIs_production_min.isAsyncMode;
var reactIs_production_min_13 = reactIs_production_min.isContextConsumer;
var reactIs_production_min_14 = reactIs_production_min.isContextProvider;
var reactIs_production_min_15 = reactIs_production_min.isElement;
var reactIs_production_min_16 = reactIs_production_min.isForwardRef;
var reactIs_production_min_17 = reactIs_production_min.isFragment;
var reactIs_production_min_18 = reactIs_production_min.isProfiler;
var reactIs_production_min_19 = reactIs_production_min.isPortal;
var reactIs_production_min_20 = reactIs_production_min.isStrictMode;
var reactIs = createCommonjsModule(function (module) {
{
module.exports = reactIs_production_min;
}
});
var _ReactIs$ForwardRef;
function _defineProperty$1(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
/**
* Copyright 2015, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var REACT_STATICS = {
childContextTypes: true,
contextTypes: true,
defaultProps: true,
displayName: true,
getDefaultProps: true,
getDerivedStateFromProps: true,
mixins: true,
propTypes: true,
type: true
};
var KNOWN_STATICS = {
name: true,
length: true,
prototype: true,
caller: true,
callee: true,
arguments: true,
arity: true
};
var TYPE_STATICS = _defineProperty$1({}, reactIs.ForwardRef, (_ReactIs$ForwardRef = {}, _defineProperty$1(_ReactIs$ForwardRef, '$$typeof', true), _defineProperty$1(_ReactIs$ForwardRef, 'render', true), _ReactIs$ForwardRef));
var defineProperty = Object.defineProperty;
var getOwnPropertyNames = Object.getOwnPropertyNames;
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var getPrototypeOf = Object.getPrototypeOf;
var objectPrototype = Object.prototype;
function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {
if (typeof sourceComponent !== 'string') {
// don't hoist over string (html) components
if (objectPrototype) {
var inheritedComponent = getPrototypeOf(sourceComponent);
if (inheritedComponent && inheritedComponent !== objectPrototype) {
hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);
}
}
var keys = getOwnPropertyNames(sourceComponent);
if (getOwnPropertySymbols) {
keys = keys.concat(getOwnPropertySymbols(sourceComponent));
}
var targetStatics = TYPE_STATICS[targetComponent['$$typeof']] || REACT_STATICS;
var sourceStatics = TYPE_STATICS[sourceComponent['$$typeof']] || REACT_STATICS;
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {
var descriptor = getOwnPropertyDescriptor(sourceComponent, key);
try {
// Avoid failures from read-only properties
defineProperty(targetComponent, key, descriptor);
} catch (e) {}
}
}
return targetComponent;
}
return targetComponent;
}
var hoistNonReactStatics_cjs = hoistNonReactStatics;
var EventEmitter =
/*#__PURE__*/
function () {
function EventEmitter() {
_classCallCheck(this, EventEmitter);
this.listeners = [];
}
_createClass(EventEmitter, [{
key: "on",
value: function on(cb) {
var _this = this;
this.listeners.push(cb);
return function () {
var index = _this.listeners.indexOf(cb);
if (index !== -1) _this.listeners.splice(index, 1);
};
}
}, {
key: "emit",
value: function emit(data) {
this.listeners.forEach(function (fn) {
return fn(data);
});
}
}]);
return EventEmitter;
}();
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location, propFullName) {
for (var _len = arguments.length, rest = new Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) {
rest[_key - 6] = arguments[_key];
}
return mobx.untracked(function () {
componentName = componentName || "<<anonymous>>";
propFullName = propFullName || propName;
if (props[propName] == null) {
if (isRequired) {
var actual = props[propName] === null ? "null" : "undefined";
return new Error("The " + location + " `" + propFullName + "` is marked as required " + "in `" + componentName + "`, but its value is `" + actual + "`.");
}
return null;
} else {
return validate.apply(void 0, [props, propName, componentName, location, propFullName].concat(rest));
}
});
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
} // Copied from React.PropTypes
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === "symbol") {
return true;
} // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue["@@toStringTag"] === "Symbol") {
return true;
} // Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === "function" && propValue instanceof Symbol) {
return true;
}
return false;
} // Copied from React.PropTypes
function getPropType(propValue) {
var propType = _typeof(propValue);
if (Array.isArray(propValue)) {
return "array";
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return "object";
}
if (isSymbol(propType, propValue)) {
return "symbol";
}
return propType;
} // This handles more types than `getPropType`. Only used for error messages.
// Copied from React.PropTypes
function getPreciseType(propValue) {
var propType = getPropType(propValue);
if (propType === "object") {
if (propValue instanceof Date) {
return "date";
} else if (propValue instanceof RegExp) {
return "regexp";
}
}
return propType;
}
function createObservableTypeCheckerCreator(allowNativeType, mobxType) {
return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {
return mobx.untracked(function () {
if (allowNativeType) {
if (getPropType(props[propName]) === mobxType.toLowerCase()) return null;
}
var mobxChecker;
switch (mobxType) {
case "Array":
mobxChecker = mobx.isObservableArray;
break;
case "Object":
mobxChecker = mobx.isObservableObject;
break;
case "Map":
mobxChecker = mobx.isObservableMap;
break;
default:
throw new Error("Unexpected mobxType: ".concat(mobxType));
}
var propValue = props[propName];
if (!mobxChecker(propValue)) {
var preciseType = getPreciseType(propValue);
var nativeTypeExpectationMessage = allowNativeType ? " or javascript `" + mobxType.toLowerCase() + "`" : "";
return new Error("Invalid prop `" + propFullName + "` of type `" + preciseType + "` supplied to" + " `" + componentName + "`, expected `mobx.Observable" + mobxType + "`" + nativeTypeExpectationMessage + ".");
}
return null;
});
});
}
function createObservableArrayOfTypeChecker(allowNativeType, typeChecker) {
return createChainableTypeChecker(function (props, propName, componentName, location, propFullName) {
for (var _len2 = arguments.length, rest = new Array(_len2 > 5 ? _len2 - 5 : 0), _key2 = 5; _key2 < _len2; _key2++) {
rest[_key2 - 5] = arguments[_key2];
}
return mobx.untracked(function () {
if (typeof typeChecker !== "function") {
return new Error("Property `" + propFullName + "` of component `" + componentName + "` has " + "invalid PropType notation.");
}
var error = createObservableTypeCheckerCreator(allowNativeType, "Array")(props, propName, componentName);
if (error instanceof Error) return error;
var propValue = props[propName];
for (var i = 0; i < propValue.length; i++) {
error = typeChecker.apply(void 0, [propValue, i, componentName, location, propFullName + "[" + i + "]"].concat(rest));
if (error instanceof Error) return error;
}
return null;
});
});
}
var observableArray = createObservableTypeCheckerCreator(false, "Array");
var observableArrayOf = createObservableArrayOfTypeChecker.bind(null, false);
var observableMap = createObservableTypeCheckerCreator(false, "Map");
var observableObject = createObservableTypeCheckerCreator(false, "Object");
var arrayOrObservableArray = createObservableTypeCheckerCreator(true, "Array");
var arrayOrObservableArrayOf = createObservableArrayOfTypeChecker.bind(null, true);
var objectOrObservableObject = createObservableTypeCheckerCreator(true, "Object");
var propTypes = /*#__PURE__*/Object.freeze({
observableArray: observableArray,
observableArrayOf: observableArrayOf,
observableMap: observableMap,
observableObject: observableObject,
arrayOrObservableArray: arrayOrObservableArray,
arrayOrObservableArrayOf: arrayOrObservableArrayOf,
objectOrObservableObject: objectOrObservableObject
});
function isStateless(component) {
// `function() {}` has prototype, but `() => {}` doesn't
// `() => {}` via Babel has prototype too.
return !(component.prototype && component.prototype.render);
}
var symbolId = 0;
function newSymbol(name) {
if (typeof Symbol === "function") {
return Symbol(name);
}
var symbol = "__$mobx-react ".concat(name, " (").concat(symbolId, ")");
symbolId++;
return symbol;
}
var mobxMixins = newSymbol("patchMixins");
var mobxPatchedDefinition = newSymbol("patchedDefinition");
function getMixins(target, methodName) {
var mixins = target[mobxMixins] = target[mobxMixins] || {};
var methodMixins = mixins[methodName] = mixins[methodName] || {};
methodMixins.locks = methodMixins.locks || 0;
methodMixins.methods = methodMixins.methods || [];
return methodMixins;
}
function wrapper(realMethod, mixins) {
var _this = this;
for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
// locks are used to ensure that mixins are invoked only once per invocation, even on recursive calls
mixins.locks++;
try {
var retVal;
if (realMethod !== undefined && realMethod !== null) {
retVal = realMethod.apply(this, args);
}
return retVal;
} finally {
mixins.locks--;
if (mixins.locks === 0) {
mixins.methods.forEach(function (mx) {
mx.apply(_this, args);
});
}
}
}
function wrapFunction(realMethod, mixins) {
var fn = function fn() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
wrapper.call.apply(wrapper, [this, realMethod, mixins].concat(args));
};
return fn;
}
function patch(target, methodName) {
var mixins = getMixins(target, methodName);
for (var _len3 = arguments.length, mixinMethods = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
mixinMethods[_key3 - 2] = arguments[_key3];
}
for (var _i = 0; _i < mixinMethods.length; _i++) {
var mixinMethod = mixinMethods[_i];
if (mixins.methods.indexOf(mixinMethod) < 0) {
mixins.methods.push(mixinMethod);
}
}
var oldDefinition = Object.getOwnPropertyDescriptor(target, methodName);
if (oldDefinition && oldDefinition[mobxPatchedDefinition]) {
// already patched definition, do not repatch
return;
}
var originalMethod = target[methodName];
var newDefinition = createDefinition(target, methodName, oldDefinition ? oldDefinition.enumerable : undefined, mixins, originalMethod);
Object.defineProperty(target, methodName, newDefinition);
}
function createDefinition(target, methodName, enumerable, mixins, originalMethod) {
var _ref;
var wrappedFunc = wrapFunction(originalMethod, mixins);
return _ref = {}, _defineProperty(_ref, mobxPatchedDefinition, true), _defineProperty(_ref, "get", function get() {
return wrappedFunc;
}), _defineProperty(_ref, "set", function set(value) {
if (this === target) {
wrappedFunc = wrapFunction(value, mixins);
} else {
// when it is an instance of the prototype/a child prototype patch that particular case again separately
// since we need to store separate values depending on wether it is the actual instance, the prototype, etc
// e.g. the method for super might not be the same as the method for the prototype which might be not the same
// as the method for the instance
var newDefinition = createDefinition(this, methodName, enumerable, mixins, value);
Object.defineProperty(this, methodName, newDefinition);
}
}), _defineProperty(_ref, "configurable", true), _defineProperty(_ref, "enumerable", enumerable), _ref;
}
var injectorContextTypes = {
mobxStores: objectOrObservableObject
};
Object.seal(injectorContextTypes);
var proxiedInjectorProps = {
contextTypes: {
get: function get() {
return injectorContextTypes;
},
set: function set(_) {
console.warn("Mobx Injector: you are trying to attach `contextTypes` on an component decorated with `inject` (or `observer`) HOC. Please specify the contextTypes on the wrapped component instead. It is accessible through the `wrappedComponent`");
},
configurable: true,
enumerable: false
},
isMobxInjector: {
value: true,
writable: true,
configurable: true,
enumerable: true
}
/**
* Store Injection
*/
};
function createStoreInjector(grabStoresFn, component, injectNames) {
var displayName = "inject-" + (component.displayName || component.name || component.constructor && component.constructor.name || "Unknown");
if (injectNames) displayName += "-with-" + injectNames;
var Injector =
/*#__PURE__*/
function (_Component) {
_inherits(Injector, _Component);
function Injector() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, Injector);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Injector)).call.apply(_getPrototypeOf2, [this].concat(args)));
_this.storeRef = function (instance) {
_this.wrappedInstance = instance;
};
return _this;
}
_createClass(Injector, [{
key: "render",
value: function render() {
// Optimization: it might be more efficient to apply the mapper function *outside* the render method
// (if the mapper is a function), that could avoid expensive(?) re-rendering of the injector component
// See this test: 'using a custom injector is not too reactive' in inject.js
var newProps = {};
for (var key in this.props) {
if (this.props.hasOwnProperty(key)) {
newProps[key] = this.props[key];
}
}
var additionalProps = grabStoresFn(this.context.mobxStores || {}, newProps, this.context) || {};
for (var _key2 in additionalProps) {
newProps[_key2] = additionalProps[_key2];
}
if (!isStateless(component)) {
newProps.ref = this.storeRef;
}
return React.createElement(component, newProps);
}
}]);
return Injector;
}(React.Component); // Static fields from component should be visible on the generated Injector
Injector.displayName = displayName;
hoistNonReactStatics_cjs(Injector, component);
Injector.wrappedComponent = component;
Object.defineProperties(Injector, proxiedInjectorProps);
return Injector;
}
function grabStoresByName(storeNames) {
return function (baseStores, nextProps) {
storeNames.forEach(function (storeName) {
if (storeName in nextProps // prefer props over stores
) return;
if (!(storeName in baseStores)) throw new Error("MobX injector: Store '" + storeName + "' is not available! Make sure it is provided by some Provider");
nextProps[storeName] = baseStores[storeName];
});
return nextProps;
};
}
/**
* higher order component that injects stores to a child.
* takes either a varargs list of strings, which are stores read from the context,
* or a function that manually maps the available stores from the context to props:
* storesToProps(mobxStores, props, context) => newProps
*/
function inject()
/* fn(stores, nextProps) or ...storeNames */
{
var grabStoresFn;
if (typeof arguments[0] === "function") {
grabStoresFn = arguments[0];
return function (componentClass) {
var injected = createStoreInjector(grabStoresFn, componentClass);
injected.isMobxInjector = false; // supress warning
// mark the Injector as observer, to make it react to expressions in `grabStoresFn`,
// see #111
injected = observer(injected);
injected.isMobxInjector = true; // restore warning
return injected;
};
} else {
var storeNames = [];
for (var i = 0; i < arguments.length; i++) {
storeNames[i] = arguments[i];
}
grabStoresFn = grabStoresByName(storeNames);
return function (componentClass) {
return createStoreInjector(grabStoresFn, componentClass, storeNames.join("-"));
};
}
}
var mobxAdminProperty = mobx.$mobx || "$mobx";
var mobxIsUnmounted = newSymbol("isUnmounted");
/**
* dev tool support
*/
var isDevtoolsEnabled = false;
var isUsingStaticRendering = false;
var warnedAboutObserverInjectDeprecation = false; // WeakMap<Node, Object>;
var componentByNodeRegistry = typeof WeakMap !== "undefined" ? new WeakMap() : undefined;
var renderReporter = new EventEmitter();
var skipRenderKey = newSymbol("skipRender");
var isForcingUpdateKey = newSymbol("isForcingUpdate");
/**
* Helper to set `prop` to `this` as non-enumerable (hidden prop)
* @param target
* @param prop
* @param value
*/
function setHiddenProp(target, prop, value) {
if (!Object.hasOwnProperty.call(target, prop)) {
Object.defineProperty(target, prop, {
enumerable: false,
configurable: true,
writable: true,
value: value
});
} else {
target[prop] = value;
}
}
function findDOMNode$1(component) {
return null;
}
function reportRendering(component) {
var node = findDOMNode$1(component);
if (node && componentByNodeRegistry) componentByNodeRegistry.set(node, component);
renderReporter.emit({
event: "render",
renderTime: component.__$mobRenderEnd - component.__$mobRenderStart,
totalTime: Date.now() - component.__$mobRenderStart,
component: component,
node: node
});
}
function trackComponents() {
if (typeof WeakMap === "undefined") throw new Error("[mobx-react] tracking components is not supported in this browser.");
if (!isDevtoolsEnabled) isDevtoolsEnabled = true;
}
function useStaticRendering(useStaticRendering) {
isUsingStaticRendering = useStaticRendering;
}
/**
* Errors reporter
*/
var errorsReporter = new EventEmitter();
/**
* Utilities
*/
function patch$1(target, funcName) {
patch(target, funcName, reactiveMixin[funcName]);
}
function shallowEqual(objA, objB) {
//From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
if (is(objA, objB)) return true;
if (_typeof(objA) !== "object" || objA === null || _typeof(objB) !== "object" || objB === null) {
return false;
}
var keysA = Object.keys(objA);
var keysB = Object.keys(objB);
if (keysA.length !== keysB.length) return false;
for (var i = 0; i < keysA.length; i++) {
if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
return false;
}
}
return true;
}
function is(x, y) {
// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function makeComponentReactive(render) {
var _this2 = this;
if (isUsingStaticRendering === true) return render.call(this);
function reactiveRender() {
var _this = this;
isRenderingPending = false;
var exception = undefined;
var rendering = undefined;
reaction.track(function () {
if (isDevtoolsEnabled) {
_this.__$mobRenderStart = Date.now();
}
try {
rendering = mobx._allowStateChanges(false, baseRender);
} catch (e) {
exception = e;
}
if (isDevtoolsEnabled) {
_this.__$mobRenderEnd = Date.now();
}
});
if (exception) {
errorsReporter.emit(exception);
throw exception;
}
return rendering;
} // Generate friendly name for debugging
var initialName = this.displayName || this.name || this.constructor && (this.constructor.displayName || this.constructor.name) || "<component>";
var rootNodeID = this._reactInternalInstance && this._reactInternalInstance._rootNodeID || this._reactInternalInstance && this._reactInternalInstance._debugID || this._reactInternalFiber && this._reactInternalFiber._debugID;
/**
* If props are shallowly modified, react will render anyway,
* so atom.reportChanged() should not result in yet another re-render
*/
setHiddenProp(this, skipRenderKey, false);
/**
* forceUpdate will re-assign this.props. We don't want that to cause a loop,
* so detect these changes
*/
setHiddenProp(this, isForcingUpdateKey, false); // wire up reactive render
var baseRender = render.bind(this);
var isRenderingPending = false;
var reaction = new mobx.Reaction("".concat(initialName, "#").concat(rootNodeID, ".render()"), function () {
if (!isRenderingPending) {
// N.B. Getting here *before mounting* means that a component constructor has side effects (see the relevant test in misc.js)
// This unidiomatic React usage but React will correctly warn about this so we continue as usual
// See #85 / Pull #44
isRenderingPending = true;
if (typeof _this2.componentWillReact === "function") _this2.componentWillReact(); // TODO: wrap in action?
if (_this2[mobxIsUnmounted] !== true) {
// If we are unmounted at this point, componentWillReact() had a side effect causing the component to unmounted
// TODO: remove this check? Then react will properly warn about the fact that this should not happen? See #73
// However, people also claim this migth happen during unit tests..
var hasError = true;
try {
setHiddenProp(_this2, isForcingUpdateKey, true);
if (!_this2[skipRenderKey]) React.Component.prototype.forceUpdate.call(_this2);
hasError = false;
} finally {
setHiddenProp(_this2, isForcingUpdateKey, false);
if (hasError) reaction.dispose();
}
}
}
});
reaction.reactComponent = this;
reactiveRender[mobxAdminProperty] = reaction;
this.render = reactiveRender;
return reactiveRender.call(this);
}
/**
* ReactiveMixin
*/
var reactiveMixin = {
componentWillUnmount: function componentWillUnmount() {
if (isUsingStaticRendering === true) return;
this.render[mobxAdminProperty] && this.render[mobxAdminProperty].dispose();
this[mobxIsUnmounted] = true;
if (isDevtoolsEnabled) {
var node = findDOMNode$1(this);
if (node && componentByNodeRegistry) {
componentByNodeRegistry.delete(node);
}
renderReporter.emit({
event: "destroy",
component: this,
node: node
});
}
},
componentDidMount: function componentDidMount() {
if (isDevtoolsEnabled) {
reportRendering(this);
}
},
componentDidUpdate: function componentDidUpdate() {
if (isDevtoolsEnabled) {
reportRendering(this);
}
},
shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) {
if (isUsingStaticRendering) {
console.warn("[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side.");
} // update on any state changes (as is the default)
if (this.state !== nextState) {
return true;
} // update if props are shallowly not equal, inspired by PureRenderMixin
// we could return just 'false' here, and avoid the `skipRender` checks etc
// however, it is nicer if lifecycle events are triggered like usually,
// so we return true here if props are shallowly modified.
return !shallowEqual(this.props, nextProps);
}
};
function makeObservableProp(target, propName) {
var valueHolderKey = newSymbol("reactProp_".concat(propName, "_valueHolder"));
var atomHolderKey = newSymbol("reactProp_".concat(propName, "_atomHolder"));
function getAtom() {
if (!this[atomHolderKey]) {
setHiddenProp(this, atomHolderKey, mobx.createAtom("reactive " + propName));
}
return this[atomHolderKey];
}
Object.defineProperty(target, propName, {
configurable: true,
enumerable: true,
get: function get() {
getAtom.call(this).reportObserved();
return this[valueHolderKey];
},
set: function set(v) {
if (!this[isForcingUpdateKey] && !shallowEqual(this[valueHolderKey], v)) {
setHiddenProp(this, valueHolderKey, v);
setHiddenProp(this, skipRenderKey, true);
getAtom.call(this).reportChanged();
setHiddenProp(this, skipRenderKey, false);
} else {
setHiddenProp(this, valueHolderKey, v);
}
}
});
}
/**
* Observer function / decorator
*/
function observer(arg1, arg2) {
if (typeof arg1 === "string") {
throw new Error("Store names should be provided as array");
}
if (Array.isArray(arg1)) {
// TODO: remove in next major
// component needs stores
if (!warnedAboutObserverInjectDeprecation) {
warnedAboutObserverInjectDeprecation = true;
console.warn('Mobx observer: Using observer to inject stores is deprecated since 4.0. Use `@inject("store1", "store2") @observer ComponentClass` or `inject("store1", "store2")(observer(componentClass))` instead of `@observer(["store1", "store2"]) ComponentClass`');
}
if (!arg2) {
// invoked as decorator
return function (componentClass) {
return observer(arg1, componentClass);
};
} else {
return inject.apply(null, arg1)(observer(arg2));
}
}
var componentClass = arg1;
if (componentClass.isMobxInjector === true) {
console.warn("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'");
}
if (componentClass.__proto__ === React.PureComponent) {
console.warn("Mobx observer: You are using 'observer' on React.PureComponent. These two achieve two opposite goals and should not be used together");
} // Stateless function component:
// If it is function but doesn't seem to be a react class constructor,
// wrap it to a react class automatically
if (typeof componentClass === "function" && (!componentClass.prototype || !componentClass.prototype.render) && !componentClass.isReactClass && !React.Component.isPrototypeOf(componentClass)) {
var _class, _temp;
var observerComponent = observer((_temp = _class =
/*#__PURE__*/
function (_Component) {
_inherits(_class, _Component);
function _class() {
_classCallCheck(this, _class);
return _possibleConstructorReturn(this, _getPrototypeOf(_class).apply(this, arguments));
}
_createClass(_class, [{
key: "render",
value: function render() {
return componentClass.call(this, this.props, this.context);
}
}]);
return _class;
}(React.Component), _class.displayName = componentClass.displayName || componentClass.name, _class.contextTypes = componentClass.contextTypes, _class.propTypes = componentClass.propTypes, _class.defaultProps = componentClass.defaultProps, _temp));
hoistNonReactStatics_cjs(observerComponent, componentClass);
return observerComponent;
}
if (!componentClass) {
throw new Error("Please pass a valid component to 'observer'");
}
var target = componentClass.prototype || componentClass;
mixinLifecycleEvents(target);
componentClass.isMobXReactObserver = true;
makeObservableProp(target, "props");
makeObservableProp(target, "state");
var baseRender = target.render;
target.render = function () {
return makeComponentReactive.call(this, baseRender);
};
return componentClass;
}
function mixinLifecycleEvents(target) {
["componentDidMount", "componentWillUnmount", "componentDidUpdate"].forEach(function (funcName) {
patch$1(target, funcName);
});
if (!target.shouldComponentUpdate) {
target.shouldComponentUpdate = reactiveMixin.shouldComponentUpdate;
} else {
if (target.shouldComponentUpdate !== reactiveMixin.shouldComponentUpdate) {
// TODO: make throw in next major
console.warn("Use `shouldComponentUpdate` in an `observer` based component breaks the behavior of `observer` and might lead to unexpected results. Manually implementing `sCU` should not be needed when using mobx-react.");
}
}
}
var Observer = observer(function (_ref) {
var children = _ref.children,
observerInject = _ref.inject,
render = _ref.render;
var component = children || render;
if (typeof component === "undefined") {
return null;
}
if (!observerInject) {
return component();
} // TODO: remove in next major
console.warn("<Observer inject=.../> is no longer supported. Please use inject on the enclosing component instead");
var InjectComponent = inject(observerInject)(component);
return React__default.createElement(InjectComponent, null);
});
Observer.displayName = "Observer";
var ObserverPropsCheck = function ObserverPropsCheck(props, key, componentName, location, propFullName) {
var extraKey = key === "children" ? "render" : "children";
if (typeof props[key] === "function" && typeof props[extraKey] === "function") {
return new Error("Invalid prop,do not use children and render in the same time in`" + componentName);
}
if (typeof props[key] === "function" || typeof props[extraKey] === "function") {
return;
}
return new Error("Invalid prop `" + propFullName + "` of type `" + _typeof(props[key]) + "` supplied to" + " `" + componentName + "`, expected `function`.");
};
Observer.propTypes = {
render: ObserverPropsCheck,
children: ObserverPropsCheck
};
/**
* 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.
*/
function componentWillMount() {
// Call this.constructor.gDSFP to support sub-classes.
var state = this.constructor.getDerivedStateFromProps(this.props, this.state);
if (state !== null && state !== undefined) {
this.setState(state);
}
}
function componentWillReceiveProps(nextProps) {
// Call this.constructor.gDSFP to support sub-classes.
// Use the setState() updater to ensure state isn't stale in certain edge cases.
function updater(prevState) {
var state = this.constructor.getDerivedStateFromProps(nextProps, prevState);
return state !== null && state !== undefined ? state : null;
}
// Binding "this" is important for shallow renderer support.
this.setState(updater.bind(this));
}
function componentWillUpdate(nextProps, nextState) {
try {
var prevProps = this.props;
var prevState = this.state;
this.props = nextProps;
this.state = nextState;
this.__reactInternalSnapshotFlag = true;
this.__reactInternalSnapshot = this.getSnapshotBeforeUpdate(
prevProps,
prevState
);
} finally {
this.props = prevProps;
this.state = prevState;
}
}
// React may warn about cWM/cWRP/cWU methods being deprecated.
// Add a flag to suppress these warnings for this special case.
componentWillMount.__suppressDeprecationWarning = true;
componentWillReceiveProps.__suppressDeprecationWarning = true;
componentWillUpdate.__suppressDeprecationWarning = true;
function polyfill(Component) {
var prototype = Component.prototype;
if (!prototype || !prototype.isReactComponent) {
throw new Error('Can only polyfill class components');
}
if (
typeof Component.getDerivedStateFromProps !== 'function' &&
typeof prototype.getSnapshotBeforeUpdate !== 'function'
) {
return Component;
}
// If new component APIs are defined, "unsafe" lifecycles won't be called.
// Error if any of these lifecycles are present,
// Because they would work differently between older and newer (16.3+) versions of React.
var foundWillMountName = null;
var foundWillReceivePropsName = null;
var foundWillUpdateName = null;
if (typeof prototype.componentWillMount === 'function') {
foundWillMountName = 'componentWillMount';
} else if (typeof prototype.UNSAFE_componentWillMount === 'function') {
foundWillMountName = 'UNSAFE_componentWillMount';
}
if (typeof prototype.componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'componentWillReceiveProps';
} else if (typeof prototype.UNSAFE_componentWillReceiveProps === 'function') {
foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
}
if (typeof prototype.componentWillUpdate === 'function') {
foundWillUpdateName = 'componentWillUpdate';
} else if (typeof prototype.UNSAFE_componentWillUpdate === 'function') {
foundWillUpdateName = 'UNSAFE_componentWillUpdate';
}
if (
foundWillMountName !== null ||
foundWillReceivePropsName !== null ||
foundWillUpdateName !== null
) {
var componentName = Component.displayName || Component.name;
var newApiName =
typeof Component.getDerivedStateFromProps === 'function'
? 'getDerivedStateFromProps()'
: 'getSnapshotBeforeUpdate()';
throw Error(
'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
componentName +
' uses ' +
newApiName +
' but also contains the following legacy lifecycles:' +
(foundWillMountName !== null ? '\n ' + foundWillMountName : '') +
(foundWillReceivePropsName !== null
? '\n ' + foundWillReceivePropsName
: '') +
(foundWillUpdateName !== null ? '\n ' + foundWillUpdateName : '') +
'\n\nThe above lifecycles should be removed. Learn more about this warning here:\n' +
'https://fb.me/react-async-component-lifecycle-hooks'
);
}
// React <= 16.2 does not support static getDerivedStateFromProps.
// As a workaround, use cWM and cWRP to invoke the new static lifecycle.
// Newer versions of React will ignore these lifecycles if gDSFP exists.
if (typeof Component.getDerivedStateFromProps === 'function') {
prototype.componentWillMount = componentWillMount;
prototype.componentWillReceiveProps = componentWillReceiveProps;
}
// React <= 16.2 does not support getSnapshotBeforeUpdate.
// As a workaround, use cWU to invoke the new lifecycle.
// Newer versions of React will ignore that lifecycle if gSBU exists.
if (typeof prototype.getSnapshotBeforeUpdate === 'function') {
if (typeof prototype.componentDidUpdate !== 'function') {
throw new Error(
'Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype'
);
}
prototype.componentWillUpdate = componentWillUpdate;
var componentDidUpdate = prototype.componentDidUpdate;
prototype.componentDidUpdate = function componentDidUpdatePolyfill(
prevProps,
prevState,
maybeSnapshot
) {
// 16.3+ will not execute our will-update method;
// It will pass a snapshot value to did-update though.
// Older versions will require our polyfilled will-update value.
// We need to handle both cases, but can't just check for the presence of "maybeSnapshot",
// Because for <= 15.x versions this might be a "prevContext" object.
// We also can't just check "__reactInternalSnapshot",
// Because get-snapshot might return a falsy value.
// So check for the explicit __reactInternalSnapshotFlag flag to determine behavior.
var snapshot = this.__reactInternalSnapshotFlag
? this.__reactInternalSnapshot
: maybeSnapshot;
componentDidUpdate.call(this, prevProps, prevState, snapshot);
};
}
return Component;
}
var specialReactKeys = {
children: true,
key: true,
ref: true
};
var Provider =
/*#__PURE__*/
function (_Component) {
_inherits(Provider, _Component);
function Provider(props, context) {
var _this;
_classCallCheck(this, Provider);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Provider).call(this, props, context));
_this.state = {};
copyStores(props, _this.state);
return _this;
}
_createClass(Provider, [{
key: "render",
value: function render() {
return React.Children.only(this.props.children);
}
}, {
key: "getChildContext",
value: function getChildContext() {
var stores = {}; // inherit stores
copyStores(this.context.mobxStores, stores); // add own stores
copyStores(this.props, stores);
return {
mobxStores: stores
};
}
}], [{
key: "getDerivedStateFromProps",
value: function getDerivedStateFromProps(nextProps, prevState) {
if (!nextProps) return null;
if (!prevState) return nextProps; // Maybe this warning is too aggressive?
if (Object.keys(nextProps).filter(validStoreName).length !== Object.keys(prevState).filter(validStoreName).length) console.warn("MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children");
if (!nextProps.suppressChangedStoreWarning) for (var key in nextProps) {
if (validStoreName(key) && prevState[key] !== nextProps[key]) console.warn("MobX Provider: Provided store '" + key + "' has changed. Please avoid replacing stores as the change might not propagate to all children");
}
return nextProps;
}
}]);
return Provider;
}(React.Component);
Provider.contextTypes = {
mobxStores: objectOrObservableObject
};
Provider.childContextTypes = {
mobxStores: objectOrObservableObject.isRequired
};
function copyStores(from, to) {
if (!from) return;
for (var key in from) {
if (validStoreName(key)) to[key] = from[key];
}
}
function validStoreName(key) {
return !specialReactKeys[key] && key !== "suppressChangedStoreWarning";
} // TODO: kill in next major
polyfill(Provider);
var storeKey = newSymbol("disposeOnUnmount");
function runDisposersOnWillUnmount() {
var _this = this;
if (!this[storeKey]) {
// when disposeOnUnmount is only set to some instances of a component it will still patch the prototype
return;
}
this[storeKey].forEach(function (propKeyOrFunction) {
var prop = typeof propKeyOrFunction === "string" ? _this[propKeyOrFunction] : propKeyOrFunction;
if (prop !== undefined && prop !== null) {
if (typeof prop !== "function") {
throw new Error("[mobx-react] disposeOnUnmount only works on functions such as disposers returned by reactions, autorun, etc.");
}
prop();
}
});
this[storeKey] = [];
}
function disposeOnUnmount(target, propertyKeyOrFunction) {
if (Array.isArray(propertyKeyOrFunction)) {
return propertyKeyOrFunction.map(function (fn) {
return disposeOnUnmount(target, fn);
});
}
if (!target instanceof React.Component) {
throw new Error("[mobx-react] disposeOnUnmount only works on class based React components.");
}
if (typeof propertyKeyOrFunction !== "string" && typeof propertyKeyOrFunction !== "function") {
throw new Error("[mobx-react] disposeOnUnmount only works if the parameter is either a property key or a function.");
} // add property key / function we want run (disposed) to the store
var componentWasAlreadyModified = !!target[storeKey];
var store = target[storeKey] || (target[storeKey] = []);
store.push(propertyKeyOrFunction); // tweak the component class componentWillUnmount if not done already
if (!componentWasAlreadyModified) {
patch(target, "componentWillUnmount", runDisposersOnWillUnmount);
} // return the disposer as is if invoked as a non decorator
if (typeof propertyKeyOrFunction !== "string") {
return propertyKeyOrFunction;
}
}
if (!React.Component) throw new Error("mobx-react requires React to be available");
if (!mobx.spy) throw new Error("mobx-react requires mobx to be available");
if (typeof reactNative.unstable_batchedUpdates === "function") mobx.configure({
reactionScheduler: reactNative.unstable_batchedUpdates
});
var onError = function onError(fn) {
return errorsReporter.on(fn);
};
if ((typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "undefined" ? "undefined" : _typeof(__MOBX_DEVTOOLS_GLOBAL_HOOK__)) === "object") {
var mobx$1 = {
spy: mobx.spy,
extras: {
getDebugName: mobx.getDebugName
}
};
var mobxReact = {
renderReporter: renderReporter,
componentByNodeRegistry: componentByNodeRegistry,
componentByNodeRegistery: componentByNodeRegistry,
trackComponents: trackComponents
};
__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobxReact(mobxReact, mobx$1);
}
exports.propTypes = propTypes;
exports.PropTypes = propTypes;
exports.onError = onError;
exports.observer = observer;
exports.Observer = Observer;
exports.renderReporter = renderReporter;
exports.componentByNodeRegistery = componentByNodeRegistry;
exports.componentByNodeRegistry = componentByNodeRegistry;
exports.trackComponents = trackComponents;
exports.useStaticRendering = useStaticRendering;
exports.Provider = Provider;
exports.inject = inject;
exports.disposeOnUnmount = disposeOnUnmount;
| sufuf3/cdnjs | ajax/libs/mobx-react/5.3.6/native.js | JavaScript | mit | 48,550 |
/*
This example renders a treemap using the built in
TreeDraw function.
*/
/**
* Create the actual tree.
* @return {mo.Tree}
*/
function makeTree(){
var tree = new mo.Tree();
var parent = new mo.Node('root', 'root');
var child1 = new mo.Node('c1', 'c1');
var child2 = new mo.Node('c2', 'c2');
tree.addNodeToTree(parent);
tree.addNodeToTree(child1, parent);
tree.addNodeToTree(child2, parent);
return tree;
}
function displayTree() {
var tree = makeTree();
var state = {};
// Since the methods are short, we will just define
// our init and cycle functions inline.
var g = new mo.Graphics({
'container': '#container',
'dimensions': {
width: 600,
height: 500
},
init: function() {
state.frame = new mo.Rectangle(20,20, 400, 400);
state.colorList = new mo.ColorList('Azure', 'blue', 'green');
state.weights = new mo.NumberList(2,6);
state.textColor = "black";
},
cycle: function() {
// Draw the treemap with the built in functionality
// this will also provide selection and zoom pan interaction
// for free.
mo.TreeDraw.drawTreemap(
state.frame,
tree,
state.colorList,
state.weights,
state.textColor,
null,
this
);
}
});
g.setAlphaRefresh(1);
g.setBackgroundColor("AntiqueWhite");
}
window.onload = function() {
displayTree();
};
| fmacias64/moebio_framework | examples/treemap/index.js | JavaScript | mit | 1,433 |
var icms = icms || {};
icms.subscriptions = (function ($) {
this.active_link = {};
this.onDocumentReady = function () {
this.setSubscribe();
$('.subscriber').on('click', function () {
icms.subscriptions.active_link = this;
icms.subscriptions.showLoader();
$.get($(this).attr('href'), $(this).data('target'), function(data){
icms.subscriptions.setResult(data);
}, 'json');
return false;
});
$('.subscribe_wrap > .count-subscribers').on('click', function () {
if(+$(this).text() === 0){
return false;
}
var list_title = $(this).attr('title');
$.get($(this).data('list_link'), {}, function(data){
icms.modal.openHtml(data.html, list_title);
}, 'json');
return false;
});
};
this.showLoader = function (){
$(icms.subscriptions.active_link).closest('.subscribe_wrap').find('.spinner').show();
};
this.hideLoader = function (){
$(icms.subscriptions.active_link).closest('.subscribe_wrap').find('.spinner').fadeOut();
};
this.setResult = function (data){
icms.subscriptions.hideLoader();
if(data.error){
alert('error'); return;
}
if(data.confirm_url){
icms.modal.openAjax(data.confirm_url, undefined, undefined, data.confirm_title); return;
}
if(data.confirm){
icms.modal.openHtml(data.confirm, data.confirm_title); return;
}
if(data.modal_close){
icms.modal.close();
}
if(data.success_text){
icms.modal.alert(data.success_text);
}
$(icms.subscriptions.active_link).data('issubscribe', data.is_subscribe);
icms.subscriptions.setSubscribe(icms.subscriptions.active_link);
$(icms.subscriptions.active_link).parent().find('.count-subscribers').html(data.count);
};
this.setSubscribe = function (link){
set = function (obj){
var is_subscribe = $(obj).data('issubscribe');
$('span', obj).html($(obj).data('text'+is_subscribe));
$(obj).attr('href', $(obj).data('link'+is_subscribe));
if(is_subscribe == 0){
$(obj).removeClass('unsubscribe').addClass('subscribe');
} else {
$(obj).removeClass('subscribe').addClass('unsubscribe');
}
};
if(link){
set(link); return;
}
$('.subscriber').each(function(indx){
set(this);
});
};
return this;
}).call(icms.subscriptions || {},jQuery);
function successSubscribe(form_data, result){
icms.subscriptions.setResult(result);
} | filinov/icms2 | templates/default/js/subscriptions.js | JavaScript | gpl-2.0 | 2,818 |
(function ($) {
/**
* Drag and drop table rows with field manipulation.
*
* Using the drupal_add_tabledrag() function, any table with weights or parent
* relationships may be made into draggable tables. Columns containing a field
* may optionally be hidden, providing a better user experience.
*
* Created tableDrag instances may be modified with custom behaviors by
* overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods.
* See blocks.js for an example of adding additional functionality to tableDrag.
*/
Drupal.behaviors.tableDrag = {
attach: function (context, settings) {
for (var base in settings.tableDrag) {
$('#' + base, context).once('tabledrag', function () {
// Create the new tableDrag instance. Save in the Drupal variable
// to allow other scripts access to the object.
Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]);
});
}
}
};
/**
* Constructor for the tableDrag object. Provides table and field manipulation.
*
* @param table
* DOM object for the table to be made draggable.
* @param tableSettings
* Settings for the table added via drupal_add_dragtable().
*/
Drupal.tableDrag = function (table, tableSettings) {
var self = this;
// Required object variables.
this.table = table;
this.tableSettings = tableSettings;
this.dragObject = null; // Used to hold information about a current drag operation.
this.rowObject = null; // Provides operations for row manipulation.
this.oldRowElement = null; // Remember the previous element.
this.oldY = 0; // Used to determine up or down direction from last mouse move.
this.changed = false; // Whether anything in the entire table has changed.
this.maxDepth = 0; // Maximum amount of allowed parenting.
this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table.
// Configure the scroll settings.
this.scrollSettings = { amount: 4, interval: 50, trigger: 70 };
this.scrollInterval = null;
this.scrollY = 0;
this.windowHeight = 0;
// Check this table's settings to see if there are parent relationships in
// this table. For efficiency, large sections of code can be skipped if we
// don't need to track horizontal movement and indentations.
this.indentEnabled = false;
for (var group in tableSettings) {
for (var n in tableSettings[group]) {
if (tableSettings[group][n].relationship == 'parent') {
this.indentEnabled = true;
}
if (tableSettings[group][n].limit > 0) {
this.maxDepth = tableSettings[group][n].limit;
}
}
}
if (this.indentEnabled) {
this.indentCount = 1; // Total width of indents, set in makeDraggable.
// Find the width of indentations to measure mouse movements against.
// Because the table doesn't need to start with any indentations, we
// manually append 2 indentations in the first draggable row, measure
// the offset, then remove.
var indent = Drupal.theme('tableDragIndentation');
var testRow = $('<tr/>').addClass('draggable').appendTo(table);
var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent);
this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft;
testRow.remove();
}
// Make each applicable row draggable.
// Match immediate children of the parent element to allow nesting.
$('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); });
// Add a link before the table for users to show or hide weight columns.
$(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>')
.attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.'))
.click(function () {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
self.hideColumns();
}
else {
self.showColumns();
}
return false;
})
.wrap('<div class="tabledrag-toggle-weight-wrapper"></div>')
.parent()
);
// Initialize the specified columns (for example, weight or parent columns)
// to show or hide according to user preference. This aids accessibility
// so that, e.g., screen reader users can choose to enter weight values and
// manipulate form elements directly, rather than using drag-and-drop..
self.initColumns();
// Add mouse bindings to the document. The self variable is passed along
// as event handlers do not have direct access to the tableDrag object.
$(document).bind('mousemove', function (event) { return self.dragRow(event, self); });
$(document).bind('mouseup', function (event) { return self.dropRow(event, self); });
};
/**
* Initialize columns containing form elements to be hidden by default,
* according to the settings for this tableDrag instance.
*
* Identify and mark each cell with a CSS class so we can easily toggle
* show/hide it. Finally, hide columns if user does not have a
* 'Drupal.tableDrag.showWeight' cookie.
*/
Drupal.tableDrag.prototype.initColumns = function () {
for (var group in this.tableSettings) {
// Find the first field in this group.
for (var d in this.tableSettings[group]) {
var field = $('.' + this.tableSettings[group][d].target + ':first', this.table);
if (field.size() && this.tableSettings[group][d].hidden) {
var hidden = this.tableSettings[group][d].hidden;
var cell = field.parents('td:first');
break;
}
}
// Mark the column containing this field so it can be hidden.
if (hidden && cell[0]) {
// Add 1 to our indexes. The nth-child selector is 1 based, not 0 based.
// Match immediate children of the parent element to allow nesting.
var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1;
$('> thead > tr, > tbody > tr, > tr', this.table).each(function () {
// Get the columnIndex and adjust for any colspans in this row.
var index = columnIndex;
var cells = $(this).children();
cells.each(function (n) {
if (n < index && this.colSpan && this.colSpan > 1) {
index -= this.colSpan - 1;
}
});
if (index > 0) {
cell = cells.filter(':nth-child(' + index + ')');
if (cell[0].colSpan && cell[0].colSpan > 1) {
// If this cell has a colspan, mark it so we can reduce the colspan.
cell.addClass('tabledrag-has-colspan');
}
else {
// Mark this cell so we can hide it.
cell.addClass('tabledrag-hide');
}
}
});
}
}
// Now hide cells and reduce colspans unless cookie indicates previous choice.
// Set a cookie if it is not already present.
if ($.cookie('Drupal.tableDrag.showWeight') === null) {
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
this.hideColumns();
}
// Check cookie value and show/hide weight columns accordingly.
else {
if ($.cookie('Drupal.tableDrag.showWeight') == 1) {
this.showColumns();
}
else {
this.hideColumns();
}
}
};
/**
* Hide the columns containing weight/parent form elements.
* Undo showColumns().
*/
Drupal.tableDrag.prototype.hideColumns = function () {
// Hide weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none');
// Show TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', '');
// Reduce the colspan of any effected multi-span columns.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan - 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Show row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 0, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
};
/**
* Show the columns containing weight/parent form elements
* Undo hideColumns().
*/
Drupal.tableDrag.prototype.showColumns = function () {
// Show weight/parent cells and headers.
$('.tabledrag-hide', 'table.tabledrag-processed').css('display', '');
// Hide TableDrag handles.
$('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none');
// Increase the colspan for any columns where it was previously reduced.
$('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () {
this.colSpan = this.colSpan + 1;
});
// Change link text.
$('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights'));
// Change cookie.
$.cookie('Drupal.tableDrag.showWeight', 1, {
path: Drupal.settings.basePath,
// The cookie expires in one year.
expires: 365
});
};
/**
* Find the target used within a particular row and group.
*/
Drupal.tableDrag.prototype.rowSettings = function (group, row) {
var field = $('.' + group, row);
for (var delta in this.tableSettings[group]) {
var targetClass = this.tableSettings[group][delta].target;
if (field.is('.' + targetClass)) {
// Return a copy of the row settings.
var rowSettings = {};
for (var n in this.tableSettings[group][delta]) {
rowSettings[n] = this.tableSettings[group][delta][n];
}
return rowSettings;
}
}
};
/**
* Take an item and add event handlers to make it become draggable.
*/
Drupal.tableDrag.prototype.makeDraggable = function (item) {
var self = this;
// Create the handle.
var handle = $('<a href="#" class="tabledrag-handle"><div class="handle"> </div></a>').attr('title', Drupal.t('Drag to re-order'));
// Insert the handle after indentations (if any).
if ($('td:first .indentation:last', item).length) {
$('td:first .indentation:last', item).after(handle);
// Update the total width of indentation in this entire table.
self.indentCount = Math.max($('.indentation', item).size(), self.indentCount);
}
else {
$('td:first', item).prepend(handle);
}
// Add hover action for the handle.
handle.hover(function () {
self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null;
}, function () {
self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null;
});
// Add the mousedown action for the handle.
handle.mousedown(function (event) {
// Create a new dragObject recording the event information.
self.dragObject = {};
self.dragObject.initMouseOffset = self.getMouseOffset(item, event);
self.dragObject.initMouseCoords = self.mouseCoords(event);
if (self.indentEnabled) {
self.dragObject.indentMousePos = self.dragObject.initMouseCoords;
}
// If there's a lingering row object from the keyboard, remove its focus.
if (self.rowObject) {
$('a.tabledrag-handle', self.rowObject.element).blur();
}
// Create a new rowObject for manipulation of this row.
self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true);
// Save the position of the table.
self.table.topY = $(self.table).offset().top;
self.table.bottomY = self.table.topY + self.table.offsetHeight;
// Add classes to the handle and row.
$(this).addClass('tabledrag-handle-hover');
$(item).addClass('drag');
// Set the document to use the move cursor during drag.
$('body').addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'none');
}
// Hack for Konqueror, prevent the blur handler from firing.
// Konqueror always gives links focus, even after returning false on mousedown.
self.safeBlur = false;
// Call optional placeholder function.
self.onDrag();
return false;
});
// Prevent the anchor tag from jumping us to the top of the page.
handle.click(function () {
return false;
});
// Similar to the hover event, add a class when the handle is focused.
handle.focus(function () {
$(this).addClass('tabledrag-handle-hover');
self.safeBlur = true;
});
// Remove the handle class on blur and fire the same function as a mouseup.
handle.blur(function (event) {
$(this).removeClass('tabledrag-handle-hover');
if (self.rowObject && self.safeBlur) {
self.dropRow(event, self);
}
});
// Add arrow-key support to the handle.
handle.keydown(function (event) {
// If a rowObject doesn't yet exist and this isn't the tab key.
if (event.keyCode != 9 && !self.rowObject) {
self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true);
}
var keyChange = false;
switch (event.keyCode) {
case 37: // Left arrow.
case 63234: // Safari left arrow.
keyChange = true;
self.rowObject.indent(-1 * self.rtl);
break;
case 38: // Up arrow.
case 63232: // Safari up arrow.
var previousRow = $(self.rowObject.element).prev('tr').get(0);
while (previousRow && $(previousRow).is(':hidden')) {
previousRow = $(previousRow).prev('tr').get(0);
}
if (previousRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'up';
keyChange = true;
if ($(item).is('.tabledrag-root')) {
// Swap with the previous top-level row.
var groupHeight = 0;
while (previousRow && $('.indentation', previousRow).size()) {
previousRow = $(previousRow).prev('tr').get(0);
groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight;
}
if (previousRow) {
self.rowObject.swap('before', previousRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, -groupHeight);
}
}
else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) {
// Swap with the previous row (unless previous row is the first one
// and undraggable).
self.rowObject.swap('before', previousRow);
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, -parseInt(item.offsetHeight, 10));
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
case 39: // Right arrow.
case 63235: // Safari right arrow.
keyChange = true;
self.rowObject.indent(1 * self.rtl);
break;
case 40: // Down arrow.
case 63233: // Safari down arrow.
var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0);
while (nextRow && $(nextRow).is(':hidden')) {
nextRow = $(nextRow).next('tr').get(0);
}
if (nextRow) {
self.safeBlur = false; // Do not allow the onBlur cleanup.
self.rowObject.direction = 'down';
keyChange = true;
if ($(item).is('.tabledrag-root')) {
// Swap with the next group (necessarily a top-level one).
var groupHeight = 0;
nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false);
if (nextGroup) {
$(nextGroup.group).each(function () {
groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight;
});
nextGroupRow = $(nextGroup.group).filter(':last').get(0);
self.rowObject.swap('after', nextGroupRow);
// No need to check for indentation, 0 is the only valid one.
window.scrollBy(0, parseInt(groupHeight, 10));
}
}
else {
// Swap with the next row.
self.rowObject.swap('after', nextRow);
self.rowObject.interval = null;
self.rowObject.indent(0);
window.scrollBy(0, parseInt(item.offsetHeight, 10));
}
handle.get(0).focus(); // Regain focus after the DOM manipulation.
}
break;
}
if (self.rowObject && self.rowObject.changed == true) {
$(item).addClass('drag');
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
self.oldRowElement = item;
self.restripeTable();
self.onDrag();
}
// Returning false if we have an arrow key to prevent scrolling.
if (keyChange) {
return false;
}
});
// Compatibility addition, return false on keypress to prevent unwanted scrolling.
// IE and Safari will suppress scrolling on keydown, but all other browsers
// need to return false on keypress. http://www.quirksmode.org/js/keys.html
handle.keypress(function (event) {
switch (event.keyCode) {
case 37: // Left arrow.
case 38: // Up arrow.
case 39: // Right arrow.
case 40: // Down arrow.
return false;
}
});
};
/**
* Mousemove event handler, bound to document.
*/
Drupal.tableDrag.prototype.dragRow = function (event, self) {
if (self.dragObject) {
self.currentMouseCoords = self.mouseCoords(event);
var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y;
var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x;
// Check for row swapping and vertical scrolling.
if (y != self.oldY) {
self.rowObject.direction = y > self.oldY ? 'down' : 'up';
self.oldY = y; // Update the old value.
// Check if the window should be scrolled (and how fast).
var scrollAmount = self.checkScroll(self.currentMouseCoords.y);
// Stop any current scrolling.
clearInterval(self.scrollInterval);
// Continue scrolling if the mouse has moved in the scroll direction.
if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') {
self.setScroll(scrollAmount);
}
// If we have a valid target, perform the swap and restripe the table.
var currentRow = self.findDropTargetRow(x, y);
if (currentRow) {
if (self.rowObject.direction == 'down') {
self.rowObject.swap('after', currentRow, self);
}
else {
self.rowObject.swap('before', currentRow, self);
}
self.restripeTable();
}
}
// Similar to row swapping, handle indentations.
if (self.indentEnabled) {
var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x;
// Set the number of indentations the mouse has been moved left or right.
var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl);
// Indent the row with our estimated diff, which may be further
// restricted according to the rows around this row.
var indentChange = self.rowObject.indent(indentDiff);
// Update table and mouse indentations.
self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl;
self.indentCount = Math.max(self.indentCount, self.rowObject.indents);
}
return false;
}
};
/**
* Mouseup event handler, bound to document.
* Blur event handler, bound to drag handle for keyboard support.
*/
Drupal.tableDrag.prototype.dropRow = function (event, self) {
// Drop row functionality shared between mouseup and blur events.
if (self.rowObject != null) {
var droppedRow = self.rowObject.element;
// The row is already in the right place so we just release it.
if (self.rowObject.changed == true) {
// Update the fields in the dropped row.
self.updateFields(droppedRow);
// If a setting exists for affecting the entire group, update all the
// fields in the entire dragged group.
for (var group in self.tableSettings) {
var rowSettings = self.rowSettings(group, droppedRow);
if (rowSettings.relationship == 'group') {
for (var n in self.rowObject.children) {
self.updateField(self.rowObject.children[n], group);
}
}
}
self.rowObject.markChanged();
if (self.changed == false) {
$(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow');
self.changed = true;
}
}
if (self.indentEnabled) {
self.rowObject.removeIndentClasses();
}
if (self.oldRowElement) {
$(self.oldRowElement).removeClass('drag-previous');
}
$(droppedRow).removeClass('drag').addClass('drag-previous');
self.oldRowElement = droppedRow;
self.onDrop();
self.rowObject = null;
}
// Functionality specific only to mouseup event.
if (self.dragObject != null) {
$('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover');
self.dragObject = null;
$('body').removeClass('drag');
clearInterval(self.scrollInterval);
// Hack for IE6 that flickers uncontrollably if select lists are moved.
if (navigator.userAgent.indexOf('MSIE 6.') != -1) {
$('select', this.table).css('display', 'block');
}
}
};
/**
* Get the mouse coordinates from the event (allowing for browser differences).
*/
Drupal.tableDrag.prototype.mouseCoords = function (event) {
if (event.pageX || event.pageY) {
return { x: event.pageX, y: event.pageY };
}
return {
x: event.clientX + document.body.scrollLeft - document.body.clientLeft,
y: event.clientY + document.body.scrollTop - document.body.clientTop
};
};
/**
* Given a target element and a mouse event, get the mouse offset from that
* element. To do this we need the element's position and the mouse position.
*/
Drupal.tableDrag.prototype.getMouseOffset = function (target, event) {
var docPos = $(target).offset();
var mousePos = this.mouseCoords(event);
return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top };
};
/**
* Find the row the mouse is currently over. This row is then taken and swapped
* with the one being dragged.
*
* @param x
* The x coordinate of the mouse on the page (not the screen).
* @param y
* The y coordinate of the mouse on the page (not the screen).
*/
Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) {
var rows = $(this.table.tBodies[0].rows).not(':hidden');
for (var n = 0; n < rows.length; n++) {
var row = rows[n];
var indentDiff = 0;
var rowY = $(row).offset().top;
// Because Safari does not report offsetHeight on table rows, but does on
// table cells, grab the firstChild of the row and use that instead.
// http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari.
if (row.offsetHeight == 0) {
var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2;
}
// Other browsers.
else {
var rowHeight = parseInt(row.offsetHeight, 10) / 2;
}
// Because we always insert before, we need to offset the height a bit.
if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) {
if (this.indentEnabled) {
// Check that this row is not a child of the row being dragged.
for (var n in this.rowObject.group) {
if (this.rowObject.group[n] == row) {
return null;
}
}
}
else {
// Do not allow a row to be swapped with itself.
if (row == this.rowObject.element) {
return null;
}
}
// Check that swapping with this row is allowed.
if (!this.rowObject.isValidSwap(row)) {
return null;
}
// We may have found the row the mouse just passed over, but it doesn't
// take into account hidden rows. Skip backwards until we find a draggable
// row.
while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) {
row = $(row).prev('tr').get(0);
}
return row;
}
}
return null;
};
/**
* After the row is dropped, update the table fields according to the settings
* set for this table.
*
* @param changedRow
* DOM object for the row that was just dropped.
*/
Drupal.tableDrag.prototype.updateFields = function (changedRow) {
for (var group in this.tableSettings) {
// Each group may have a different setting for relationship, so we find
// the source rows for each separately.
this.updateField(changedRow, group);
}
};
/**
* After the row is dropped, update a single table field according to specific
* settings.
*
* @param changedRow
* DOM object for the row that was just dropped.
* @param group
* The settings group on which field updates will occur.
*/
Drupal.tableDrag.prototype.updateField = function (changedRow, group) {
var rowSettings = this.rowSettings(group, changedRow);
// Set the row as its own target.
if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') {
var sourceRow = changedRow;
}
// Siblings are easy, check previous and next rows.
else if (rowSettings.relationship == 'sibling') {
var previousRow = $(changedRow).prev('tr').get(0);
var nextRow = $(changedRow).next('tr').get(0);
var sourceRow = changedRow;
if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) {
if (this.indentEnabled) {
if ($('.indentations', previousRow).size() == $('.indentations', changedRow)) {
sourceRow = previousRow;
}
}
else {
sourceRow = previousRow;
}
}
else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) {
if (this.indentEnabled) {
if ($('.indentations', nextRow).size() == $('.indentations', changedRow)) {
sourceRow = nextRow;
}
}
else {
sourceRow = nextRow;
}
}
}
// Parents, look up the tree until we find a field not in this group.
// Go up as many parents as indentations in the changed row.
else if (rowSettings.relationship == 'parent') {
var previousRow = $(changedRow).prev('tr');
while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) {
previousRow = previousRow.prev('tr');
}
// If we found a row.
if (previousRow.length) {
sourceRow = previousRow[0];
}
// Otherwise we went all the way to the left of the table without finding
// a parent, meaning this item has been placed at the root level.
else {
// Use the first row in the table as source, because it's guaranteed to
// be at the root level. Find the first item, then compare this row
// against it as a sibling.
sourceRow = $(this.table).find('tr.draggable:first').get(0);
if (sourceRow == this.rowObject.element) {
sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0);
}
var useSibling = true;
}
}
// Because we may have moved the row from one category to another,
// take a look at our sibling and borrow its sources and targets.
this.copyDragClasses(sourceRow, changedRow, group);
rowSettings = this.rowSettings(group, changedRow);
// In the case that we're looking for a parent, but the row is at the top
// of the tree, copy our sibling's values.
if (useSibling) {
rowSettings.relationship = 'sibling';
rowSettings.source = rowSettings.target;
}
var targetClass = '.' + rowSettings.target;
var targetElement = $(targetClass, changedRow).get(0);
// Check if a target element exists in this row.
if (targetElement) {
var sourceClass = '.' + rowSettings.source;
var sourceElement = $(sourceClass, sourceRow).get(0);
switch (rowSettings.action) {
case 'depth':
// Get the depth of the target row.
targetElement.value = $('.indentation', $(sourceElement).parents('tr:first')).size();
break;
case 'match':
// Update the value.
targetElement.value = sourceElement.value;
break;
case 'order':
var siblings = this.rowObject.findSiblings(rowSettings);
if ($(targetElement).is('select')) {
// Get a list of acceptable values.
var values = [];
$('option', targetElement).each(function () {
values.push(this.value);
});
var maxVal = values[values.length - 1];
// Populate the values in the siblings.
$(targetClass, siblings).each(function () {
// If there are more items than possible values, assign the maximum value to the row.
if (values.length > 0) {
this.value = values.shift();
}
else {
this.value = maxVal;
}
});
}
else {
// Assume a numeric input field.
var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0;
$(targetClass, siblings).each(function () {
this.value = weight;
weight++;
});
}
break;
}
}
};
/**
* Copy all special tableDrag classes from one row's form elements to a
* different one, removing any special classes that the destination row
* may have had.
*/
Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) {
var sourceElement = $('.' + group, sourceRow);
var targetElement = $('.' + group, targetRow);
if (sourceElement.length && targetElement.length) {
targetElement[0].className = sourceElement[0].className;
}
};
Drupal.tableDrag.prototype.checkScroll = function (cursorY) {
var de = document.documentElement;
var b = document.body;
var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight);
var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY));
var trigger = this.scrollSettings.trigger;
var delta = 0;
// Return a scroll speed relative to the edge of the screen.
if (cursorY - scrollY > windowHeight - trigger) {
delta = trigger / (windowHeight + scrollY - cursorY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return delta * this.scrollSettings.amount;
}
else if (cursorY - scrollY < trigger) {
delta = trigger / (cursorY - scrollY);
delta = (delta > 0 && delta < trigger) ? delta : trigger;
return -delta * this.scrollSettings.amount;
}
};
Drupal.tableDrag.prototype.setScroll = function (scrollAmount) {
var self = this;
this.scrollInterval = setInterval(function () {
// Update the scroll values stored in the object.
self.checkScroll(self.currentMouseCoords.y);
var aboveTable = self.scrollY > self.table.topY;
var belowTable = self.scrollY + self.windowHeight < self.table.bottomY;
if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) {
window.scrollBy(0, scrollAmount);
}
}, this.scrollSettings.interval);
};
Drupal.tableDrag.prototype.restripeTable = function () {
// :even and :odd are reversed because jQuery counts from 0 and
// we count from 1, so we're out of sync.
// Match immediate children of the parent element to allow nesting.
$('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table)
.removeClass('odd even')
.filter(':odd').addClass('even').end()
.filter(':even').addClass('odd');
};
/**
* Stub function. Allows a custom handler when a row begins dragging.
*/
Drupal.tableDrag.prototype.onDrag = function () {
return null;
};
/**
* Stub function. Allows a custom handler when a row is dropped.
*/
Drupal.tableDrag.prototype.onDrop = function () {
return null;
};
/**
* Constructor to make a new object to manipulate a table row.
*
* @param tableRow
* The DOM element for the table row we will be manipulating.
* @param method
* The method in which this row is being moved. Either 'keyboard' or 'mouse'.
* @param indentEnabled
* Whether the containing table uses indentations. Used for optimizations.
* @param maxDepth
* The maximum amount of indentations this row may contain.
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) {
this.element = tableRow;
this.method = method;
this.group = [tableRow];
this.groupDepth = $('.indentation', tableRow).size();
this.changed = false;
this.table = $(tableRow).parents('table:first').get(0);
this.indentEnabled = indentEnabled;
this.maxDepth = maxDepth;
this.direction = ''; // Direction the row is being moved.
if (this.indentEnabled) {
this.indents = $('.indentation', tableRow).size();
this.children = this.findChildren(addClasses);
this.group = $.merge(this.group, this.children);
// Find the depth of this entire group.
for (var n = 0; n < this.group.length; n++) {
this.groupDepth = Math.max($('.indentation', this.group[n]).size(), this.groupDepth);
}
}
};
/**
* Find all children of rowObject by indentation.
*
* @param addClasses
* Whether we want to add classes to this row to indicate child relationships.
*/
Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) {
var parentIndentation = this.indents;
var currentRow = $(this.element, this.table).next('tr.draggable');
var rows = [];
var child = 0;
while (currentRow.length) {
var rowIndentation = $('.indentation', currentRow).length;
// A greater indentation indicates this is a child.
if (rowIndentation > parentIndentation) {
child++;
rows.push(currentRow[0]);
if (addClasses) {
$('.indentation', currentRow).each(function (indentNum) {
if (child == 1 && (indentNum == parentIndentation)) {
$(this).addClass('tree-child-first');
}
if (indentNum == parentIndentation) {
$(this).addClass('tree-child');
}
else if (indentNum > parentIndentation) {
$(this).addClass('tree-child-horizontal');
}
});
}
}
else {
break;
}
currentRow = currentRow.next('tr.draggable');
}
if (addClasses && rows.length) {
$('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last');
}
return rows;
};
/**
* Ensure that two rows are allowed to be swapped.
*
* @param row
* DOM object for the row being considered for swapping.
*/
Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) {
if (this.indentEnabled) {
var prevRow, nextRow;
if (this.direction == 'down') {
prevRow = row;
nextRow = $(row).next('tr').get(0);
}
else {
prevRow = $(row).prev('tr').get(0);
nextRow = row;
}
this.interval = this.validIndentInterval(prevRow, nextRow);
// We have an invalid swap if the valid indentations interval is empty.
if (this.interval.min > this.interval.max) {
return false;
}
}
// Do not let an un-draggable first row have anything put before it.
if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) {
return false;
}
return true;
};
/**
* Perform the swap between two rows.
*
* @param position
* Whether the swap will occur 'before' or 'after' the given row.
* @param row
* DOM element what will be swapped with the row group.
*/
Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) {
Drupal.detachBehaviors(this.group, Drupal.settings, 'move');
$(row)[position](this.group);
Drupal.attachBehaviors(this.group, Drupal.settings);
this.changed = true;
this.onSwap(row);
};
/**
* Determine the valid indentations interval for the row at a given position
* in the table.
*
* @param prevRow
* DOM object for the row before the tested position
* (or null for first position in the table).
* @param nextRow
* DOM object for the row after the tested position
* (or null for last position in the table).
*/
Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) {
var minIndent, maxIndent;
// Minimum indentation:
// Do not orphan the next row.
minIndent = nextRow ? $('.indentation', nextRow).size() : 0;
// Maximum indentation:
if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) {
// Do not indent:
// - the first row in the table,
// - rows dragged below a non-draggable row,
// - 'root' rows.
maxIndent = 0;
}
else {
// Do not go deeper than as a child of the previous row.
maxIndent = $('.indentation', prevRow).size() + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1);
// Limit by the maximum allowed depth for the table.
if (this.maxDepth) {
maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents));
}
}
return { 'min': minIndent, 'max': maxIndent };
};
/**
* Indent a row within the legal bounds of the table.
*
* @param indentDiff
* The number of additional indentations proposed for the row (can be
* positive or negative). This number will be adjusted to nearest valid
* indentation level for the row.
*/
Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) {
// Determine the valid indentations interval if not available yet.
if (!this.interval) {
prevRow = $(this.element).prev('tr').get(0);
nextRow = $(this.group).filter(':last').next('tr').get(0);
this.interval = this.validIndentInterval(prevRow, nextRow);
}
// Adjust to the nearest valid indentation.
var indent = this.indents + indentDiff;
indent = Math.max(indent, this.interval.min);
indent = Math.min(indent, this.interval.max);
indentDiff = indent - this.indents;
for (var n = 1; n <= Math.abs(indentDiff); n++) {
// Add or remove indentations.
if (indentDiff < 0) {
$('.indentation:first', this.group).remove();
this.indents--;
}
else {
$('td:first', this.group).prepend(Drupal.theme('tableDragIndentation'));
this.indents++;
}
}
if (indentDiff) {
// Update indentation for this row.
this.changed = true;
this.groupDepth += indentDiff;
this.onIndent();
}
return indentDiff;
};
/**
* Find all siblings for a row, either according to its subgroup or indentation.
* Note that the passed-in row is included in the list of siblings.
*
* @param settings
* The field settings we're using to identify what constitutes a sibling.
*/
Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) {
var siblings = [];
var directions = ['prev', 'next'];
var rowIndentation = this.indents;
for (var d = 0; d < directions.length; d++) {
var checkRow = $(this.element)[directions[d]]();
while (checkRow.length) {
// Check that the sibling contains a similar target field.
if ($('.' + rowSettings.target, checkRow)) {
// Either add immediately if this is a flat table, or check to ensure
// that this row has the same level of indentation.
if (this.indentEnabled) {
var checkRowIndentation = $('.indentation', checkRow).length;
}
if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) {
siblings.push(checkRow[0]);
}
else if (checkRowIndentation < rowIndentation) {
// No need to keep looking for siblings when we get to a parent.
break;
}
}
else {
break;
}
checkRow = $(checkRow)[directions[d]]();
}
// Since siblings are added in reverse order for previous, reverse the
// completed list of previous siblings. Add the current row and continue.
if (directions[d] == 'prev') {
siblings.reverse();
siblings.push(this.element);
}
}
return siblings;
};
/**
* Remove indentation helper classes from the current row group.
*/
Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () {
for (var n in this.children) {
$('.indentation', this.children[n])
.removeClass('tree-child')
.removeClass('tree-child-first')
.removeClass('tree-child-last')
.removeClass('tree-child-horizontal');
}
};
/**
* Add an asterisk or other marker to the changed row.
*/
Drupal.tableDrag.prototype.row.prototype.markChanged = function () {
var marker = Drupal.theme('tableDragChangedMarker');
var cell = $('td:first', this.element);
if ($('span.tabledrag-changed', cell).length == 0) {
cell.append(marker);
}
};
/**
* Stub function. Allows a custom handler when a row is indented.
*/
Drupal.tableDrag.prototype.row.prototype.onIndent = function () {
return null;
};
/**
* Stub function. Allows a custom handler when a row is swapped.
*/
Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
return null;
};
Drupal.theme.prototype.tableDragChangedMarker = function () {
return '<span class="warning tabledrag-changed">*</span>';
};
Drupal.theme.prototype.tableDragIndentation = function () {
return '<div class="indentation"> </div>';
};
Drupal.theme.prototype.tableDragChangedWarning = function () {
return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>';
};
})(jQuery);
;
(function ($) {
Drupal.viewsSlideshow = Drupal.viewsSlideshow || {};
/**
* Views Slideshow Controls
*/
Drupal.viewsSlideshowControls = Drupal.viewsSlideshowControls || {};
/**
* Implement the play hook for controls.
*/
Drupal.viewsSlideshowControls.play = function (options) {
// Route the control call to the correct control type.
// Need to use try catch so we don't have to check to make sure every part
// of the object is defined.
try {
if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].play == 'function') {
Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].play(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
try {
if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].play == 'function') {
Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].play(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
};
/**
* Implement the pause hook for controls.
*/
Drupal.viewsSlideshowControls.pause = function (options) {
// Route the control call to the correct control type.
// Need to use try catch so we don't have to check to make sure every part
// of the object is defined.
try {
if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].pause == 'function') {
Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].top.type].pause(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
try {
if (typeof Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].pause == 'function') {
Drupal[Drupal.settings.viewsSlideshowControls[options.slideshowID].bottom.type].pause(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
};
/**
* Views Slideshow Text Controls
*/
// Add views slieshow api calls for views slideshow text controls.
Drupal.behaviors.viewsSlideshowControlsText = {
attach: function (context) {
// Process previous link
$('.views_slideshow_controls_text_previous:not(.views-slideshow-controls-text-previous-processed)', context).addClass('views-slideshow-controls-text-previous-processed').each(function() {
var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_previous_', '');
$(this).click(function() {
Drupal.viewsSlideshow.action({ "action": 'previousSlide', "slideshowID": uniqueID });
return false;
});
});
// Process next link
$('.views_slideshow_controls_text_next:not(.views-slideshow-controls-text-next-processed)', context).addClass('views-slideshow-controls-text-next-processed').each(function() {
var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_next_', '');
$(this).click(function() {
Drupal.viewsSlideshow.action({ "action": 'nextSlide', "slideshowID": uniqueID });
return false;
});
});
// Process pause link
$('.views_slideshow_controls_text_pause:not(.views-slideshow-controls-text-pause-processed)', context).addClass('views-slideshow-controls-text-pause-processed').each(function() {
var uniqueID = $(this).attr('id').replace('views_slideshow_controls_text_pause_', '');
$(this).click(function() {
if (Drupal.settings.viewsSlideshow[uniqueID].paused) {
Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": uniqueID, "force": true });
}
else {
Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": uniqueID, "force": true });
}
return false;
});
});
}
};
Drupal.viewsSlideshowControlsText = Drupal.viewsSlideshowControlsText || {};
/**
* Implement the pause hook for text controls.
*/
Drupal.viewsSlideshowControlsText.pause = function (options) {
var pauseText = Drupal.theme.prototype['viewsSlideshowControlsPause'] ? Drupal.theme('viewsSlideshowControlsPause') : '';
$('#views_slideshow_controls_text_pause_' + options.slideshowID + ' a').text(pauseText);
};
/**
* Implement the play hook for text controls.
*/
Drupal.viewsSlideshowControlsText.play = function (options) {
var playText = Drupal.theme.prototype['viewsSlideshowControlsPlay'] ? Drupal.theme('viewsSlideshowControlsPlay') : '';
$('#views_slideshow_controls_text_pause_' + options.slideshowID + ' a').text(playText);
};
// Theme the resume control.
Drupal.theme.prototype.viewsSlideshowControlsPause = function () {
return Drupal.t('Resume');
};
// Theme the pause control.
Drupal.theme.prototype.viewsSlideshowControlsPlay = function () {
return Drupal.t('Pause');
};
/**
* Views Slideshow Pager
*/
Drupal.viewsSlideshowPager = Drupal.viewsSlideshowPager || {};
/**
* Implement the transitionBegin hook for pagers.
*/
Drupal.viewsSlideshowPager.transitionBegin = function (options) {
// Route the pager call to the correct pager type.
// Need to use try catch so we don't have to check to make sure every part
// of the object is defined.
try {
if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].transitionBegin == 'function') {
Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].transitionBegin(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
try {
if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].transitionBegin == 'function') {
Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].transitionBegin(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
};
/**
* Implement the goToSlide hook for pagers.
*/
Drupal.viewsSlideshowPager.goToSlide = function (options) {
// Route the pager call to the correct pager type.
// Need to use try catch so we don't have to check to make sure every part
// of the object is defined.
try {
if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].goToSlide == 'function') {
Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].goToSlide(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
try {
if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].goToSlide == 'function') {
Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].goToSlide(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
};
/**
* Implement the previousSlide hook for pagers.
*/
Drupal.viewsSlideshowPager.previousSlide = function (options) {
// Route the pager call to the correct pager type.
// Need to use try catch so we don't have to check to make sure every part
// of the object is defined.
try {
if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].previousSlide == 'function') {
Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].previousSlide(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
try {
if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].previousSlide == 'function') {
Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].previousSlide(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
};
/**
* Implement the nextSlide hook for pagers.
*/
Drupal.viewsSlideshowPager.nextSlide = function (options) {
// Route the pager call to the correct pager type.
// Need to use try catch so we don't have to check to make sure every part
// of the object is defined.
try {
if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].nextSlide == 'function') {
Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].top.type].nextSlide(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
try {
if (typeof Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type != "undefined" && typeof Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].nextSlide == 'function') {
Drupal[Drupal.settings.viewsSlideshowPager[options.slideshowID].bottom.type].nextSlide(options);
}
}
catch(err) {
// Don't need to do anything on error.
}
};
/**
* Views Slideshow Pager Fields
*/
// Add views slieshow api calls for views slideshow pager fields.
Drupal.behaviors.viewsSlideshowPagerFields = {
attach: function (context) {
// Process pause on hover.
$('.views_slideshow_pager_field:not(.views-slideshow-pager-field-processed)', context).addClass('views-slideshow-pager-field-processed').each(function() {
// Parse out the location and unique id from the full id.
var pagerInfo = $(this).attr('id').split('_');
var location = pagerInfo[2];
pagerInfo.splice(0, 3);
var uniqueID = pagerInfo.join('_');
// Add the activate and pause on pager hover event to each pager item.
if (Drupal.settings.viewsSlideshowPagerFields[uniqueID][location].activatePauseOnHover) {
$(this).children().each(function(index, pagerItem) {
var mouseIn = function() {
Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index });
Drupal.viewsSlideshow.action({ "action": 'pause', "slideshowID": uniqueID });
}
var mouseOut = function() {
Drupal.viewsSlideshow.action({ "action": 'play', "slideshowID": uniqueID });
}
if (jQuery.fn.hoverIntent) {
$(pagerItem).hoverIntent(mouseIn, mouseOut);
}
else {
$(pagerItem).hover(mouseIn, mouseOut);
}
});
}
else {
$(this).children().each(function(index, pagerItem) {
$(pagerItem).click(function() {
Drupal.viewsSlideshow.action({ "action": 'goToSlide', "slideshowID": uniqueID, "slideNum": index });
});
});
}
});
}
};
Drupal.viewsSlideshowPagerFields = Drupal.viewsSlideshowPagerFields || {};
/**
* Implement the transitionBegin hook for pager fields pager.
*/
Drupal.viewsSlideshowPagerFields.transitionBegin = function (options) {
for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) {
// Remove active class from pagers
$('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active');
// Add active class to active pager.
$('#views_slideshow_pager_field_item_'+ pagerLocation + '_' + options.slideshowID + '_' + options.slideNum).addClass('active');
}
};
/**
* Implement the goToSlide hook for pager fields pager.
*/
Drupal.viewsSlideshowPagerFields.goToSlide = function (options) {
for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) {
// Remove active class from pagers
$('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active');
// Add active class to active pager.
$('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + options.slideNum).addClass('active');
}
};
/**
* Implement the previousSlide hook for pager fields pager.
*/
Drupal.viewsSlideshowPagerFields.previousSlide = function (options) {
for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) {
// Get the current active pager.
var pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"].active').attr('id').replace('views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_', '');
// If we are on the first pager then activate the last pager.
// Otherwise activate the previous pager.
if (pagerNum == 0) {
pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').length() - 1;
}
else {
pagerNum--;
}
// Remove active class from pagers
$('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active');
// Add active class to active pager.
$('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + pagerNum).addClass('active');
}
};
/**
* Implement the nextSlide hook for pager fields pager.
*/
Drupal.viewsSlideshowPagerFields.nextSlide = function (options) {
for (pagerLocation in Drupal.settings.viewsSlideshowPager[options.slideshowID]) {
// Get the current active pager.
var pagerNum = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"].active').attr('id').replace('views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_', '');
var totalPagers = $('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').length();
// If we are on the last pager then activate the first pager.
// Otherwise activate the next pager.
pagerNum++;
if (pagerNum == totalPagers) {
pagerNum = 0;
}
// Remove active class from pagers
$('[id^="views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '"]').removeClass('active');
// Add active class to active pager.
$('#views_slideshow_pager_field_item_' + pagerLocation + '_' + options.slideshowID + '_' + slideNum).addClass('active');
}
};
/**
* Views Slideshow Slide Counter
*/
Drupal.viewsSlideshowSlideCounter = Drupal.viewsSlideshowSlideCounter || {};
/**
* Implement the transitionBegin for the slide counter.
*/
Drupal.viewsSlideshowSlideCounter.transitionBegin = function (options) {
$('#views_slideshow_slide_counter_' + options.slideshowID + ' .num').text(options.slideNum + 1);
};
/**
* This is used as a router to process actions for the slideshow.
*/
Drupal.viewsSlideshow.action = function (options) {
// Set default values for our return status.
var status = {
'value': true,
'text': ''
}
// If an action isn't specified return false.
if (typeof options.action == 'undefined' || options.action == '') {
status.value = false;
status.text = Drupal.t('There was no action specified.');
return error;
}
// If we are using pause or play switch paused state accordingly.
if (options.action == 'pause') {
Drupal.settings.viewsSlideshow[options.slideshowID].paused = 1;
// If the calling method is forcing a pause then mark it as such.
if (options.force) {
Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce = 1;
}
}
else if (options.action == 'play') {
// If the slideshow isn't forced pause or we are forcing a play then play
// the slideshow.
// Otherwise return telling the calling method that it was forced paused.
if (!Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce || options.force) {
Drupal.settings.viewsSlideshow[options.slideshowID].paused = 0;
Drupal.settings.viewsSlideshow[options.slideshowID].pausedForce = 0;
}
else {
status.value = false;
status.text += ' ' + Drupal.t('This slideshow is forced paused.');
return status;
}
}
// We use a switch statement here mainly just to limit the type of actions
// that are available.
switch (options.action) {
case "goToSlide":
case "transitionBegin":
case "transitionEnd":
// The three methods above require a slide number. Checking if it is
// defined and it is a number that is an integer.
if (typeof options.slideNum == 'undefined' || typeof options.slideNum !== 'number' || parseInt(options.slideNum) != (options.slideNum - 0)) {
status.value = false;
status.text = Drupal.t('An invalid integer was specified for slideNum.');
}
case "pause":
case "play":
case "nextSlide":
case "previousSlide":
// Grab our list of methods.
var methods = Drupal.settings.viewsSlideshow[options.slideshowID]['methods'];
// if the calling method specified methods that shouldn't be called then
// exclude calling them.
var excludeMethodsObj = {};
if (typeof options.excludeMethods !== 'undefined') {
// We need to turn the excludeMethods array into an object so we can use the in
// function.
for (var i=0; i < excludeMethods.length; i++) {
excludeMethodsObj[excludeMethods[i]] = '';
}
}
// Call every registered method and don't call excluded ones.
for (i = 0; i < methods[options.action].length; i++) {
if (Drupal[methods[options.action][i]] != undefined && typeof Drupal[methods[options.action][i]][options.action] == 'function' && !(methods[options.action][i] in excludeMethodsObj)) {
Drupal[methods[options.action][i]][options.action](options);
}
}
break;
// If it gets here it's because it's an invalid action.
default:
status.value = false;
status.text = Drupal.t('An invalid action "!action" was specified.', { "!action": options.action });
}
return status;
};
})(jQuery);
;
| Jackamomo/beta.designmesh.co.uk | sites/default/files/js/js_epbrEI_0goJi4R57mtzv1h04XFGpS-jRxZzMGykmego.js | JavaScript | gpl-2.0 | 60,971 |
'use strict';
var path = require('path');
var _ = require('lodash');
module.exports = function (from, to, context, tplSettings) {
context = context || {};
tplSettings = tplSettings || {};
this.copy(from, to, {
process: function (contents) {
return _.template(contents.toString(), tplSettings)(context);
}
});
};
| ph3l1x/realestate | sites/all/themes/default/bootstrap/node_modules/mem-fs-editor/actions/copy-tpl.js | JavaScript | gpl-2.0 | 336 |
/*
* Require-CSS RequireJS css! loader plugin
* 0.1.8
* Guy Bedford 2014
* MIT
*/
/*
*
* Usage:
* require(['css!./mycssFile']);
*
* Tested and working in (up to latest versions as of March 2013):
* Android
* iOS 6
* IE 6 - 10
* Chome 3 - 26
* Firefox 3.5 - 19
* Opera 10 - 12
*
* browserling.com used for virtual testing environment
*
* Credit to B Cavalier & J Hann for the IE 6 - 9 method,
* refined with help from Martin Cermak
*
* Sources that helped along the way:
* - https://developer.mozilla.org/en-US/docs/Browser_detection_using_the_user_agent
* - http://www.phpied.com/when-is-a-stylesheet-really-loaded/
* - https://github.com/cujojs/curl/blob/master/src/curl/plugin/css.js
*
*/
define(function() {
//>>excludeStart('excludeRequireCss', pragmas.excludeRequireCss)
if (typeof window == 'undefined')
return { load: function(n, r, load){ load() } };
var head = document.getElementsByTagName('head')[0];
var engine = window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/) || 0;
// use <style> @import load method (IE < 9, Firefox < 18)
var useImportLoad = false;
// set to false for explicit <link> load checking when onload doesn't work perfectly (webkit)
var useOnload = true;
// trident / msie
if (engine[1] || engine[7])
useImportLoad = parseInt(engine[1]) < 6 || parseInt(engine[7]) <= 9;
// webkit
else if (engine[2] || engine[8])
useOnload = false;
// gecko
else if (engine[4])
useImportLoad = parseInt(engine[4]) < 18;
//>>excludeEnd('excludeRequireCss')
//main api object
var cssAPI = {};
//>>excludeStart('excludeRequireCss', pragmas.excludeRequireCss)
cssAPI.pluginBuilder = './css-builder';
// <style> @import load method
var curStyle, curSheet;
var createStyle = function () {
curStyle = document.createElement('style');
head.appendChild(curStyle);
curSheet = curStyle.styleSheet || curStyle.sheet;
}
var ieCnt = 0;
var ieLoads = [];
var ieCurCallback;
var createIeLoad = function(url) {
curSheet.addImport(url);
curStyle.onload = function(){ processIeLoad() };
ieCnt++;
if (ieCnt == 31) {
createStyle();
ieCnt = 0;
}
}
var processIeLoad = function() {
ieCurCallback();
var nextLoad = ieLoads.shift();
if (!nextLoad) {
ieCurCallback = null;
return;
}
ieCurCallback = nextLoad[1];
createIeLoad(nextLoad[0]);
}
var importLoad = function(url, callback) {
if (!curSheet || !curSheet.addImport)
createStyle();
if (curSheet && curSheet.addImport) {
// old IE
if (ieCurCallback) {
ieLoads.push([url, callback]);
}
else {
createIeLoad(url);
ieCurCallback = callback;
}
}
else {
// old Firefox
curStyle.textContent = '@import "' + url + '";';
var loadInterval = setInterval(function() {
try {
curStyle.sheet.cssRules;
clearInterval(loadInterval);
callback();
} catch(e) {}
}, 10);
}
}
// <link> load method
var linkLoad = function(url, callback) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
if (useOnload)
link.onload = function() {
link.onload = function() {};
// for style dimensions queries, a short delay can still be necessary
setTimeout(callback, 7);
}
else
var loadInterval = setInterval(function() {
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if (sheet.href == link.href) {
clearInterval(loadInterval);
return callback();
}
}
}, 10);
link.href = url;
head.appendChild(link);
}
//>>excludeEnd('excludeRequireCss')
cssAPI.normalize = function(name, normalize) {
if (name.substr(name.length - 4, 4) == '.css')
name = name.substr(0, name.length - 4);
return normalize(name);
}
//>>excludeStart('excludeRequireCss', pragmas.excludeRequireCss)
cssAPI.load = function(cssId, req, load, config) {
(useImportLoad ? importLoad : linkLoad)(req.toUrl(cssId + '.css'), load);
}
//>>excludeEnd('excludeRequireCss')
return cssAPI;
}); | sergez/carpc_client | www_src/js/requirejs/css.js | JavaScript | gpl-2.0 | 4,397 |
/*jslint unparam: true, browser: true, indent: 2 */
;(function ($, window, document, undefined) {
'use strict';
Foundation.libs.section = {
name: 'section',
version : '4.1.2',
settings : {
deep_linking: false,
one_up: true,
callback: function (){}
},
init : function (scope, method, options) {
var self = this;
Foundation.inherit(this, 'throttle data_options position_right offset_right');
if (typeof method != 'string') {
this.set_active_from_hash();
this.events();
return true;
} else {
return this[method].call(this, options);
}
},
events : function () {
var self = this;
$(this.scope)
.on('click.fndtn.section', '[data-section] .title, [data-section] [data-section-title]', function (e) {
var $this = $(this),
section = $this.closest('[data-section]');
self.toggle_active.call(this, e, self);
});
$(window)
.on('resize.fndtn.section', self.throttle(function () {
self.resize.call(this);
}, 30))
.on('hashchange', function () {
if (!self.settings.toggled){
self.set_active_from_hash();
$(this).trigger('resize');
}
}).trigger('resize');
$(document)
.on('click.fndtn.section', function (e) {
if ($(e.target).closest('.title, [data-section-title]').length < 1) {
$('[data-section="vertical-nav"], [data-section="horizontal-nav"]')
.find('section, .section, [data-section-region]')
.removeClass('active')
.attr('style', '');
}
});
},
toggle_active : function (e, self) {
var $this = $(this),
section = $this.closest('section, .section, [data-section-region]'),
content = section.find('.content, [data-section-content]'),
parent = section.closest('[data-section]'),
self = Foundation.libs.section,
settings = $.extend({}, self.settings, self.data_options(parent));
self.settings.toggled = true;
if (!settings.deep_linking && content.length > 0) {
e.preventDefault();
}
if (section.hasClass('active')) {
if (self.small(parent)
|| self.is_vertical(parent)
|| self.is_horizontal(parent)
|| self.is_accordion(parent)) {
section
.removeClass('active')
.attr('style', '');
}
} else {
var prev_active_section = null,
title_height = self.outerHeight(section.find('.title, [data-section-title]'));
if (self.small(parent) || settings.one_up) {
prev_active_section = $this.closest('[data-section]').find('section.active, .section.active, .active[data-section-region]');
if (self.small(parent)) {
prev_active_section.attr('style', '');
} else {
prev_active_section.attr('style', 'visibility: hidden; padding-top: '+title_height+'px;');
}
}
if (self.small(parent)) {
section.attr('style', '');
} else {
section.css('padding-top', title_height);
}
section.addClass('active');
if (prev_active_section !== null) {
prev_active_section.removeClass('active').attr('style', '');
}
}
setTimeout(function () {
self.settings.toggled = false;
}, 300);
settings.callback();
},
resize : function () {
var sections = $('[data-section]'),
self = Foundation.libs.section;
sections.each(function() {
var $this = $(this),
active_section = $this.find('section.active, .section.active, .active[data-section-region]'),
settings = $.extend({}, self.settings, self.data_options($this));
if (active_section.length > 1) {
active_section
.not(':first')
.removeClass('active')
.attr('style', '');
} else if (active_section.length < 1
&& !self.is_vertical($this)
&& !self.is_horizontal($this)
&& !self.is_accordion($this)) {
var first = $this.find('section, .section, [data-section-region]').first();
if (settings.one_up) {
first.addClass('active');
}
if (self.small($this)) {
first.attr('style', '');
} else {
first.css('padding-top', self.outerHeight(first.find('.title, [data-section-title]')));
}
}
if (self.small($this)) {
active_section.attr('style', '');
} else {
active_section.css('padding-top', self.outerHeight(active_section.find('.title, [data-section-title]')));
}
self.position_titles($this);
if (self.is_horizontal($this) && !self.small($this)) {
self.position_content($this);
} else {
self.position_content($this, false);
}
});
},
is_vertical : function (el) {
return /vertical-nav/i.test(el.data('section'));
},
is_horizontal : function (el) {
return /horizontal-nav/i.test(el.data('section'));
},
is_accordion : function (el) {
return /accordion/i.test(el.data('section'));
},
is_tabs : function (el) {
return /tabs/i.test(el.data('section'));
},
set_active_from_hash : function () {
var hash = window.location.hash.substring(1),
sections = $('[data-section]'),
self = this;
sections.each(function () {
var section = $(this),
settings = $.extend({}, self.settings, self.data_options(section));
if (hash.length > 0 && settings.deep_linking) {
section
.find('section, .section, [data-section-region]')
.attr('style', '')
.removeClass('active');
section
.find('.content[data-slug="' + hash + '"], [data-section-content][data-slug="' + hash + '"]')
.closest('section, .section, [data-section-region]')
.addClass('active');
}
});
},
position_titles : function (section, off) {
var titles = section.find('.title, [data-section-title]'),
previous_width = 0,
self = this;
if (typeof off === 'boolean') {
titles.attr('style', '');
} else {
titles.each(function () {
if (!self.rtl) {
$(this).css('left', previous_width);
} else {
$(this).css('right', previous_width);
}
previous_width += self.outerWidth($(this));
});
}
},
position_content : function (section, off) {
var titles = section.find('.title, [data-section-title]'),
content = section.find('.content, [data-section-content]'),
self = this;
if (typeof off === 'boolean') {
content.attr('style', '');
section.attr('style', '');
} else {
section.find('section, .section, [data-section-region]').each(function () {
var title = $(this).find('.title, [data-section-title]'),
content = $(this).find('.content, [data-section-content]');
if (!self.rtl) {
content.css({left: title.position().left - 1, top: self.outerHeight(title) - 2});
} else {
content.css({right: self.position_right(title) + 1, top: self.outerHeight(title) - 2});
}
});
// temporary work around for Zepto outerheight calculation issues.
if (typeof Zepto === 'function') {
section.height(this.outerHeight(titles.first()));
} else {
section.height(this.outerHeight(titles.first()) - 2);
}
}
},
position_right : function (el) {
var section = el.closest('[data-section]'),
section_width = el.closest('[data-section]').width(),
offset = section.find('.title, [data-section-title]').length;
return (section_width - el.position().left - el.width() * (el.index() + 1) - offset);
},
reflow : function () {
$('[data-section]').trigger('resize');
},
small : function (el) {
var settings = $.extend({}, this.settings, this.data_options(el));
if (this.is_tabs(el)) {
return false;
}
if (el && this.is_accordion(el)) {
return true;
}
if ($('html').hasClass('lt-ie9')) {
return true;
}
if ($('html').hasClass('ie8compat')) {
return true;
}
return $(this.scope).width() < 768;
},
off : function () {
$(this.scope).off('.fndtn.section');
$(window).off('.fndtn.section');
$(document).off('.fndtn.section')
}
};
}(Foundation.zj, this, this.document)); | slamorte/dk | wp-content/themes/spine_old/foundation/javascripts/foundation/foundation.section.js | JavaScript | gpl-2.0 | 9,145 |
/**
* @name jQuery FullScreen Plugin
* @author Martin Angelov
* @version 1.0
* @url http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/
* @license MIT License
*/
(function($){
// Adding a new test to the jQuery support object
$.support.fullscreen = supportFullScreen();
// Creating the plugin
$.fn.fullScreen = function(props){
if(!$.support.fullscreen || this.length != 1){
// The plugin can be called only
// on one element at a time
return this;
}
if(fullScreenStatus()){
// if we are already in fullscreen, exit
cancelFullScreen();
return this;
}
// You can potentially pas two arguments a color
// for the background and a callback function
var options = $.extend({
'background' : '#111',
'callback' : function(){}
}, props);
// This temporary div is the element that is
// actually going to be enlarged in full screen
var fs = $('<div>',{
'css' : {
'background' : options.background,
'width' : '100%',
'height' : '100%'
}
});
var elem = this;
// You can use the .fullScreen class to
// apply styling to your element
elem.addClass('fullScreen');
// Inserting our element in the temporary
// div, after which we zoom it in fullscreen
fs.insertBefore(elem);
fs.append(elem);
requestFullScreen(fs.get(0));
fs.click(function(e){
if(e.target == this){
// If the black bar was clicked
cancelFullScreen();
}
});
elem.cancel = function(){
cancelFullScreen();
return elem;
};
onFullScreenEvent(function(fullScreen){
if(!fullScreen){
// We have exited full screen.
// Remove the class and destroy
// the temporary div
elem.removeClass('fullScreen').insertBefore(fs);
fs.remove();
}
// Calling the user supplied callback
options.callback(fullScreen);
});
return elem;
};
// These helper functions available only to our plugin scope.
function supportFullScreen(){
var doc = document.documentElement;
return ('requestFullscreen' in doc) ||
('mozRequestFullScreen' in doc && document.mozFullScreenEnabled) ||
('webkitRequestFullScreen' in doc);
}
function requestFullScreen(elem){
if (elem.requestFullscreen) {
elem.requestFullscreen();
}
else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
}
else if (elem.webkitRequestFullScreen) {
elem.webkitRequestFullScreen();
}
}
function fullScreenStatus(){
return document.fullscreen ||
document.mozFullScreen ||
document.webkitIsFullScreen;
}
function cancelFullScreen(){
if (document.exitFullscreen) {
document.exitFullscreen();
}
else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
}
else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
function onFullScreenEvent(callback){
$(document).on("fullscreenchange mozfullscreenchange webkitfullscreenchange", function(){
// The full screen status is automatically
// passed to our callback as an argument.
callback(fullScreenStatus());
});
}
})(jQuery);
| mperceau/PhotoFloat | web/js/004-fullscreen.js | JavaScript | gpl-2.0 | 3,176 |
(function ($) {
/**
* Move a block in the blocks table from one region to another via select list.
*
* This behavior is dependent on the tableDrag behavior, since it uses the
* objects initialized in that behavior to update the row.
*/
Drupal.behaviors.taskbarUIDrag = {
attach: function (context, settings) {
// tableDrag is required and we should be on the Taskbar UI admin page.
if (typeof Drupal.tableDrag == 'undefined' || typeof Drupal.tableDrag.items == 'undefined') {
return;
}
var table = $('table#items');
var tableDrag = Drupal.tableDrag.items; // Get the items tableDrag object.
// Add a handler for when a row is swapped, update empty regions.
tableDrag.row.prototype.onSwap = function(swappedRow) {
checkEmptyRegions(table, this);
};
// A custom message for the blocks page specifically.
Drupal.theme.tableDragChangedWarning = function () {
return '<div class="messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t("The changes to these items will not be saved until the <em>Save items</em> button is clicked.") + '</div>';
};
// Add a handler so when a row is dropped, update fields dropped into new regions.
tableDrag.onDrop = function() {
dragObject = this;
var regionRow = $(dragObject.rowObject.element).prevAll('tr.region-message').get(0);
var regionName = regionRow.className.replace(/([^ ]+[ ]+)*region-([^ ]+)-message([ ]+[^ ]+)*/, '$2');
var regionField = $('select.item-region-select', dragObject.rowObject.element);
if ($('option[value=' + regionName + ']', regionField).length == 0) {
alert(Drupal.t('The item cannot be placed in this region.'));
// Simulate that there was a selected element change, so the row is put
// back to from where the user tried to drag it.
regionField.change();
}
else if ($(dragObject.rowObject.element).prev('tr').is('.region-message')) {
var weightField = $('select.item-weight', dragObject.rowObject.element);
var oldRegionName = weightField[0].className.replace(/([^ ]+[ ]+)*item-weight-([^ ]+)([ ]+[^ ]+)*/, '$2');
if (!regionField.is('.item-region-'+ regionName)) {
regionField.removeClass('item-region-' + oldRegionName).addClass('item-region-' + regionName);
weightField.removeClass('item-weight-' + oldRegionName).addClass('item-weight-' + regionName);
regionField.val(regionName);
}
}
};
// Add the behavior to each region select list.
$('select.item-region-select', context).once('item-region-select', function() {
$(this).change(function(event) {
// Make our new row and select field.
var row = $(this).parents('tr:first');
var select = $(this);
tableDrag.rowObject = new tableDrag.row(row);
// Find the correct region and insert the row as the first in the region.
$('tr.region-message', table).each(function() {
if ($(this).is('.region-' + select[0].value + '-message')) {
// Add the new row and remove the old one.
$(this).after(row);
// Manually update weights and restripe.
tableDrag.updateFields(row.get(0));
tableDrag.rowObject.changed = true;
if (tableDrag.oldRowElement) {
$(tableDrag.oldRowElement).removeClass('drag-previous');
}
tableDrag.oldRowElement = row.get(0);
tableDrag.restripeTable();
tableDrag.rowObject.markChanged();
tableDrag.oldRowElement = row;
$(row).addClass('drag-previous');
}
});
// Modify empty regions with added or removed fields.
checkEmptyRegions(table, row);
// Remove focus from selectbox.
select.get(0).blur();
});
$(this).addClass('itemregionselect-processed');
});
var checkEmptyRegions = function(table, rowObject) {
$('tr.region-message', table).each(function() {
// If the dragged row is in this region, but above the message row, swap it down one space.
if ($(this).prev('tr').get(0) == rowObject.element) {
// Prevent a recursion problem when using the keyboard to move rows up.
if ((rowObject.method != 'keyboard' || rowObject.direction == 'down')) {
rowObject.swap('after', this);
}
}
// This region has become empty
if ($(this).next('tr').is(':not(.draggable)') || $(this).next('tr').size() == 0) {
$(this).removeClass('region-populated').addClass('region-empty');
}
// This region has become populated.
else if ($(this).is('.region-empty')) {
$(this).removeClass('region-empty').addClass('region-populated');
}
});
};
}
};
})(jQuery);
| chandra20/ch | sites/all/modules/taskbar/modules/taskbar_ui/taskbar_ui.js | JavaScript | gpl-2.0 | 4,863 |
// Can also be used with $(document).ready()
jQuery(window).load(function() {
jQuery('.flexslider').flexslider({
animation: "slide"
});
});
| kikecastillo/countries | themes/business/js/custom.js | JavaScript | gpl-3.0 | 148 |
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"fullDate": "EEEE dd MMMM y",
"longDate": "dd MMMM y",
"medium": "MMM d, y h:mm:ss a",
"mediumDate": "MMM d, y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/yy h:mm a",
"shortDate": "dd/MM/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "(\u00a4",
"negSuf": ")",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-bw",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | arie-benichou/go-dot | src/main/webapp/app/lib/angular/i18n/angular-locale_en-bw.js | JavaScript | gpl-3.0 | 2,001 |
/*
//! version : 3.1.3
=========================================================
bootstrap-datetimepicker.js
https://github.com/Eonasdan/bootstrap-datetimepicker
=========================================================
The MIT License (MIT)
Copyright (c) 2014 Jonathan Peterson
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.
*/
;(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD is used - Register as an anonymous module.
define(['jquery', 'moment'], factory);
} else if (typeof exports === 'object') {
factory(require('jquery'), require('moment'));
}
else {
// Neither AMD or CommonJS used. Use global variables.
if (!jQuery) {
throw new Error('bootstrap-datetimepicker requires jQuery to be loaded first');
}
if (!moment) {
throw new Error('bootstrap-datetimepicker requires moment.js to be loaded first');
}
factory(root.jQuery, moment);
}
}(this, function ($, moment) {
'use strict';
if (typeof moment === 'undefined') {
throw new Error('momentjs is required');
}
var dpgId = 0,
DateTimePicker = function (element, options) {
var defaults = $.fn.datetimepicker.defaults,
icons = {
time: 'glyphicon glyphicon-time',
date: 'glyphicon glyphicon-calendar',
up: 'glyphicon glyphicon-chevron-up',
down: 'glyphicon glyphicon-chevron-down'
},
picker = this,
errored = false,
dDate,
init = function () {
var icon = false, localeData, rInterval;
picker.options = $.extend({}, defaults, options);
picker.options.icons = $.extend({}, icons, picker.options.icons);
picker.element = $(element);
dataToOptions();
if (!(picker.options.pickTime || picker.options.pickDate)) {
throw new Error('Must choose at least one picker');
}
picker.id = dpgId++;
moment.locale(picker.options.language);
picker.date = moment();
picker.unset = false;
picker.isInput = picker.element.is('input');
picker.component = false;
if (picker.element.hasClass('input-group')) {
if (picker.element.find('.datepickerbutton').size() === 0) {//in case there is more then one 'input-group-addon' Issue #48
picker.component = picker.element.find('[class^="input-group-"]');
}
else {
picker.component = picker.element.find('.datepickerbutton');
}
}
picker.format = picker.options.format;
localeData = moment().localeData();
if (!picker.format) {
picker.format = (picker.options.pickDate ? localeData.longDateFormat('L') : '');
if (picker.options.pickDate && picker.options.pickTime) {
picker.format += ' ';
}
picker.format += (picker.options.pickTime ? localeData.longDateFormat('LT') : '');
if (picker.options.useSeconds) {
if (localeData.longDateFormat('LT').indexOf(' A') !== -1) {
picker.format = picker.format.split(' A')[0] + ':ss A';
}
else {
picker.format += ':ss';
}
}
}
picker.use24hours = (picker.format.toLowerCase().indexOf('a') < 0 && picker.format.indexOf('h') < 0);
if (picker.component) {
icon = picker.component.find('span');
}
if (picker.options.pickTime) {
if (icon) {
icon.addClass(picker.options.icons.time);
}
}
if (picker.options.pickDate) {
if (icon) {
icon.removeClass(picker.options.icons.time);
icon.addClass(picker.options.icons.date);
}
}
picker.options.widgetParent =
typeof picker.options.widgetParent === 'string' && picker.options.widgetParent ||
picker.element.parents().filter(function () {
return 'scroll' === $(this).css('overflow-y');
}).get(0) ||
'body';
picker.widget = $(getTemplate()).appendTo(picker.options.widgetParent);
picker.minViewMode = picker.options.minViewMode || 0;
if (typeof picker.minViewMode === 'string') {
switch (picker.minViewMode) {
case 'months':
picker.minViewMode = 1;
break;
case 'years':
picker.minViewMode = 2;
break;
default:
picker.minViewMode = 0;
break;
}
}
picker.viewMode = picker.options.viewMode || 0;
if (typeof picker.viewMode === 'string') {
switch (picker.viewMode) {
case 'months':
picker.viewMode = 1;
break;
case 'years':
picker.viewMode = 2;
break;
default:
picker.viewMode = 0;
break;
}
}
picker.viewMode = Math.max(picker.viewMode, picker.minViewMode);
picker.options.disabledDates = indexGivenDates(picker.options.disabledDates);
picker.options.enabledDates = indexGivenDates(picker.options.enabledDates);
picker.startViewMode = picker.viewMode;
picker.setMinDate(picker.options.minDate);
picker.setMaxDate(picker.options.maxDate);
fillDow();
fillMonths();
fillHours();
fillMinutes();
fillSeconds();
update();
showMode();
if (!getPickerInput().prop('disabled')) {
attachDatePickerEvents();
}
if (picker.options.defaultDate !== '' && getPickerInput().val() === '') {
picker.setValue(picker.options.defaultDate);
}
if (picker.options.minuteStepping !== 1) {
rInterval = picker.options.minuteStepping;
picker.date.minutes((Math.round(picker.date.minutes() / rInterval) * rInterval) % 60).seconds(0);
}
},
getPickerInput = function () {
var input;
if (picker.isInput) {
return picker.element;
}
input = picker.element.find('.datepickerinput');
if (input.size() === 0) {
input = picker.element.find('input');
}
else if (!input.is('input')) {
throw new Error('CSS class "datepickerinput" cannot be applied to non input element');
}
return input;
},
dataToOptions = function () {
var eData;
if (picker.element.is('input')) {
eData = picker.element.data();
}
else {
eData = picker.element.find('input').data();
}
if (eData.dateFormat !== undefined) {
picker.options.format = eData.dateFormat;
}
if (eData.datePickdate !== undefined) {
picker.options.pickDate = eData.datePickdate;
}
if (eData.datePicktime !== undefined) {
picker.options.pickTime = eData.datePicktime;
}
if (eData.dateUseminutes !== undefined) {
picker.options.useMinutes = eData.dateUseminutes;
}
if (eData.dateUseseconds !== undefined) {
picker.options.useSeconds = eData.dateUseseconds;
}
if (eData.dateUsecurrent !== undefined) {
picker.options.useCurrent = eData.dateUsecurrent;
}
if (eData.calendarWeeks !== undefined) {
picker.options.calendarWeeks = eData.calendarWeeks;
}
if (eData.dateMinutestepping !== undefined) {
picker.options.minuteStepping = eData.dateMinutestepping;
}
if (eData.dateMindate !== undefined) {
picker.options.minDate = eData.dateMindate;
}
if (eData.dateMaxdate !== undefined) {
picker.options.maxDate = eData.dateMaxdate;
}
if (eData.dateShowtoday !== undefined) {
picker.options.showToday = eData.dateShowtoday;
}
if (eData.dateCollapse !== undefined) {
picker.options.collapse = eData.dateCollapse;
}
if (eData.dateLanguage !== undefined) {
picker.options.language = eData.dateLanguage;
}
if (eData.dateDefaultdate !== undefined) {
picker.options.defaultDate = eData.dateDefaultdate;
}
if (eData.dateDisableddates !== undefined) {
picker.options.disabledDates = eData.dateDisableddates;
}
if (eData.dateEnableddates !== undefined) {
picker.options.enabledDates = eData.dateEnableddates;
}
if (eData.dateIcons !== undefined) {
picker.options.icons = eData.dateIcons;
}
if (eData.dateUsestrict !== undefined) {
picker.options.useStrict = eData.dateUsestrict;
}
if (eData.dateDirection !== undefined) {
picker.options.direction = eData.dateDirection;
}
if (eData.dateSidebyside !== undefined) {
picker.options.sideBySide = eData.dateSidebyside;
}
if (eData.dateDaysofweekdisabled !== undefined) {
picker.options.daysOfWeekDisabled = eData.dateDaysofweekdisabled;
}
},
place = function () {
var position = 'absolute',
offset = picker.component ? picker.component.offset() : picker.element.offset(),
$window = $(window),
placePosition;
picker.width = picker.component ? picker.component.outerWidth() : picker.element.outerWidth();
offset.top = offset.top + picker.element.outerHeight();
if (picker.options.direction === 'up') {
placePosition = 'top';
} else if (picker.options.direction === 'bottom') {
placePosition = 'bottom';
} else if (picker.options.direction === 'auto') {
if (offset.top + picker.widget.height() > $window.height() + $window.scrollTop() && picker.widget.height() + picker.element.outerHeight() < offset.top) {
placePosition = 'top';
} else {
placePosition = 'bottom';
}
}
if (placePosition === 'top') {
offset.bottom = $window.height() - offset.top + picker.element.outerHeight() + 3;
picker.widget.addClass('top').removeClass('bottom');
} else {
offset.top += 1;
picker.widget.addClass('bottom').removeClass('top');
}
if (picker.options.width !== undefined) {
picker.widget.width(picker.options.width);
}
if (picker.options.orientation === 'left') {
picker.widget.addClass('left-oriented');
offset.left = offset.left - picker.widget.width() + 20;
}
if (isInFixed()) {
position = 'fixed';
offset.top -= $window.scrollTop();
offset.left -= $window.scrollLeft();
}
if ($window.width() < offset.left + picker.widget.outerWidth()) {
offset.right = $window.width() - offset.left - picker.width;
offset.left = 'auto';
picker.widget.addClass('pull-right');
} else {
offset.right = 'auto';
picker.widget.removeClass('pull-right');
}
if (placePosition === 'top') {
picker.widget.css({
position: position,
bottom: offset.bottom,
top: 'auto',
left: offset.left,
right: offset.right
});
} else {
picker.widget.css({
position: position,
top: offset.top,
bottom: 'auto',
left: offset.left,
right: offset.right
});
}
},
notifyChange = function (oldDate, eventType) {
if (moment(picker.date).isSame(moment(oldDate)) && !errored) {
return;
}
errored = false;
picker.element.trigger({
type: 'dp.change',
date: moment(picker.date),
oldDate: moment(oldDate)
});
if (eventType !== 'change') {
picker.element.change();
}
},
notifyError = function (date) {
errored = true;
picker.element.trigger({
type: 'dp.error',
date: moment(date, picker.format, picker.options.useStrict)
});
},
update = function (newDate) {
moment.locale(picker.options.language);
var dateStr = newDate;
if (!dateStr) {
dateStr = getPickerInput().val();
if (dateStr) {
picker.date = moment(dateStr, picker.format, picker.options.useStrict);
}
if (!picker.date) {
picker.date = moment();
}
}
picker.viewDate = moment(picker.date).startOf('month');
fillDate();
fillTime();
},
fillDow = function () {
moment.locale(picker.options.language);
var html = $('<tr>'), weekdaysMin = moment.weekdaysMin(), i;
if (picker.options.calendarWeeks === true) {
html.append('<th class="cw">#</th>');
}
if (moment().localeData()._week.dow === 0) { // starts on Sunday
for (i = 0; i < 7; i++) {
html.append('<th class="dow">' + weekdaysMin[i] + '</th>');
}
} else {
for (i = 1; i < 8; i++) {
if (i === 7) {
html.append('<th class="dow">' + weekdaysMin[0] + '</th>');
} else {
html.append('<th class="dow">' + weekdaysMin[i] + '</th>');
}
}
}
picker.widget.find('.datepicker-days thead').append(html);
},
fillMonths = function () {
moment.locale(picker.options.language);
var html = '', i, monthsShort = moment.monthsShort();
for (i = 0; i < 12; i++) {
html += '<span class="month">' + monthsShort[i] + '</span>';
}
picker.widget.find('.datepicker-months td').append(html);
},
fillDate = function () {
if (!picker.options.pickDate) {
return;
}
moment.locale(picker.options.language);
var year = picker.viewDate.year(),
month = picker.viewDate.month(),
startYear = picker.options.minDate.year(),
startMonth = picker.options.minDate.month(),
endYear = picker.options.maxDate.year(),
endMonth = picker.options.maxDate.month(),
currentDate,
prevMonth, nextMonth, html = [], row, clsName, i, days, yearCont, currentYear, months = moment.months();
picker.widget.find('.datepicker-days').find('.disabled').removeClass('disabled');
picker.widget.find('.datepicker-months').find('.disabled').removeClass('disabled');
picker.widget.find('.datepicker-years').find('.disabled').removeClass('disabled');
picker.widget.find('.datepicker-days th:eq(1)').text(
months[month] + ' ' + year);
prevMonth = moment(picker.viewDate, picker.format, picker.options.useStrict).subtract(1, 'months');
days = prevMonth.daysInMonth();
prevMonth.date(days).startOf('week');
if ((year === startYear && month <= startMonth) || year < startYear) {
picker.widget.find('.datepicker-days th:eq(0)').addClass('disabled');
}
if ((year === endYear && month >= endMonth) || year > endYear) {
picker.widget.find('.datepicker-days th:eq(2)').addClass('disabled');
}
nextMonth = moment(prevMonth).add(42, 'd');
while (prevMonth.isBefore(nextMonth)) {
if (prevMonth.weekday() === moment().startOf('week').weekday()) {
row = $('<tr>');
html.push(row);
if (picker.options.calendarWeeks === true) {
row.append('<td class="cw">' + prevMonth.week() + '</td>');
}
}
clsName = '';
if (prevMonth.year() < year || (prevMonth.year() === year && prevMonth.month() < month)) {
clsName += ' old';
} else if (prevMonth.year() > year || (prevMonth.year() === year && prevMonth.month() > month)) {
clsName += ' new';
}
if (prevMonth.isSame(moment({y: picker.date.year(), M: picker.date.month(), d: picker.date.date()}))) {
clsName += ' active';
}
if (isInDisableDates(prevMonth, 'day') || !isInEnableDates(prevMonth)) {
clsName += ' disabled';
}
if (picker.options.showToday === true) {
if (prevMonth.isSame(moment(), 'day')) {
clsName += ' today';
}
}
if (picker.options.daysOfWeekDisabled) {
for (i = 0; i < picker.options.daysOfWeekDisabled.length; i++) {
if (prevMonth.day() === picker.options.daysOfWeekDisabled[i]) {
clsName += ' disabled';
break;
}
}
}
row.append('<td class="day' + clsName + '">' + prevMonth.date() + '</td>');
currentDate = prevMonth.date();
prevMonth.add(1, 'd');
if (currentDate === prevMonth.date()) {
prevMonth.add(1, 'd');
}
}
picker.widget.find('.datepicker-days tbody').empty().append(html);
currentYear = picker.date.year();
months = picker.widget.find('.datepicker-months').find('th:eq(1)').text(year).end().find('span').removeClass('active');
if (currentYear === year) {
months.eq(picker.date.month()).addClass('active');
}
if (year - 1 < startYear) {
picker.widget.find('.datepicker-months th:eq(0)').addClass('disabled');
}
if (year + 1 > endYear) {
picker.widget.find('.datepicker-months th:eq(2)').addClass('disabled');
}
for (i = 0; i < 12; i++) {
if ((year === startYear && startMonth > i) || (year < startYear)) {
$(months[i]).addClass('disabled');
} else if ((year === endYear && endMonth < i) || (year > endYear)) {
$(months[i]).addClass('disabled');
}
}
html = '';
year = parseInt(year / 10, 10) * 10;
yearCont = picker.widget.find('.datepicker-years').find(
'th:eq(1)').text(year + '-' + (year + 9)).parents('table').find('td');
picker.widget.find('.datepicker-years').find('th').removeClass('disabled');
if (startYear > year) {
picker.widget.find('.datepicker-years').find('th:eq(0)').addClass('disabled');
}
if (endYear < year + 9) {
picker.widget.find('.datepicker-years').find('th:eq(2)').addClass('disabled');
}
year -= 1;
for (i = -1; i < 11; i++) {
html += '<span class="year' + (i === -1 || i === 10 ? ' old' : '') + (currentYear === year ? ' active' : '') + ((year < startYear || year > endYear) ? ' disabled' : '') + '">' + year + '</span>';
year += 1;
}
yearCont.html(html);
},
fillHours = function () {
moment.locale(picker.options.language);
var table = picker.widget.find('.timepicker .timepicker-hours table'), html = '', current, i, j;
table.parent().hide();
if (picker.use24hours) {
current = 0;
for (i = 0; i < 6; i += 1) {
html += '<tr>';
for (j = 0; j < 4; j += 1) {
html += '<td class="hour">' + padLeft(current.toString()) + '</td>';
current++;
}
html += '</tr>';
}
}
else {
current = 1;
for (i = 0; i < 3; i += 1) {
html += '<tr>';
for (j = 0; j < 4; j += 1) {
html += '<td class="hour">' + padLeft(current.toString()) + '</td>';
current++;
}
html += '</tr>';
}
}
table.html(html);
},
fillMinutes = function () {
var table = picker.widget.find('.timepicker .timepicker-minutes table'), html = '', current = 0, i, j, step = picker.options.minuteStepping;
table.parent().hide();
if (step === 1) {
step = 5;
}
for (i = 0; i < Math.ceil(60 / step / 4) ; i++) {
html += '<tr>';
for (j = 0; j < 4; j += 1) {
if (current < 60) {
html += '<td class="minute">' + padLeft(current.toString()) + '</td>';
current += step;
} else {
html += '<td></td>';
}
}
html += '</tr>';
}
table.html(html);
},
fillSeconds = function () {
var table = picker.widget.find('.timepicker .timepicker-seconds table'), html = '', current = 0, i, j;
table.parent().hide();
for (i = 0; i < 3; i++) {
html += '<tr>';
for (j = 0; j < 4; j += 1) {
html += '<td class="second">' + padLeft(current.toString()) + '</td>';
current += 5;
}
html += '</tr>';
}
table.html(html);
},
fillTime = function () {
if (!picker.date) {
return;
}
var timeComponents = picker.widget.find('.timepicker span[data-time-component]'),
hour = picker.date.hours(),
period = picker.date.format('A');
if (!picker.use24hours) {
if (hour === 0) {
hour = 12;
} else if (hour !== 12) {
hour = hour % 12;
}
picker.widget.find('.timepicker [data-action=togglePeriod]').text(period);
}
timeComponents.filter('[data-time-component=hours]').text(padLeft(hour));
timeComponents.filter('[data-time-component=minutes]').text(padLeft(picker.date.minutes()));
timeComponents.filter('[data-time-component=seconds]').text(padLeft(picker.date.second()));
},
click = function (e) {
e.stopPropagation();
e.preventDefault();
picker.unset = false;
var target = $(e.target).closest('span, td, th'), month, year, step, day, oldDate = moment(picker.date);
if (target.length === 1) {
if (!target.is('.disabled')) {
switch (target[0].nodeName.toLowerCase()) {
case 'th':
switch (target[0].className) {
case 'picker-switch':
showMode(1);
break;
case 'prev':
case 'next':
step = dpGlobal.modes[picker.viewMode].navStep;
if (target[0].className === 'prev') {
step = step * -1;
}
picker.viewDate.add(step, dpGlobal.modes[picker.viewMode].navFnc);
fillDate();
break;
}
break;
case 'span':
if (target.is('.month')) {
month = target.parent().find('span').index(target);
picker.viewDate.month(month);
} else {
year = parseInt(target.text(), 10) || 0;
picker.viewDate.year(year);
}
if (picker.viewMode === picker.minViewMode) {
picker.date = moment({
y: picker.viewDate.year(),
M: picker.viewDate.month(),
d: picker.viewDate.date(),
h: picker.date.hours(),
m: picker.date.minutes(),
s: picker.date.seconds()
});
set();
notifyChange(oldDate, e.type);
}
showMode(-1);
fillDate();
break;
case 'td':
if (target.is('.day')) {
day = parseInt(target.text(), 10) || 1;
month = picker.viewDate.month();
year = picker.viewDate.year();
if (target.is('.old')) {
if (month === 0) {
month = 11;
year -= 1;
} else {
month -= 1;
}
} else if (target.is('.new')) {
if (month === 11) {
month = 0;
year += 1;
} else {
month += 1;
}
}
picker.date = moment({
y: year,
M: month,
d: day,
h: picker.date.hours(),
m: picker.date.minutes(),
s: picker.date.seconds()
}
);
picker.viewDate = moment({
y: year, M: month, d: Math.min(28, day)
});
fillDate();
set();
notifyChange(oldDate, e.type);
}
break;
}
}
}
},
actions = {
incrementHours: function () {
checkDate('add', 'hours', 1);
},
incrementMinutes: function () {
checkDate('add', 'minutes', picker.options.minuteStepping);
},
incrementSeconds: function () {
checkDate('add', 'seconds', 1);
},
decrementHours: function () {
checkDate('subtract', 'hours', 1);
},
decrementMinutes: function () {
checkDate('subtract', 'minutes', picker.options.minuteStepping);
},
decrementSeconds: function () {
checkDate('subtract', 'seconds', 1);
},
togglePeriod: function () {
var hour = picker.date.hours();
if (hour >= 12) {
hour -= 12;
} else {
hour += 12;
}
picker.date.hours(hour);
},
showPicker: function () {
picker.widget.find('.timepicker > div:not(.timepicker-picker)').hide();
picker.widget.find('.timepicker .timepicker-picker').show();
},
showHours: function () {
picker.widget.find('.timepicker .timepicker-picker').hide();
picker.widget.find('.timepicker .timepicker-hours').show();
},
showMinutes: function () {
picker.widget.find('.timepicker .timepicker-picker').hide();
picker.widget.find('.timepicker .timepicker-minutes').show();
},
showSeconds: function () {
picker.widget.find('.timepicker .timepicker-picker').hide();
picker.widget.find('.timepicker .timepicker-seconds').show();
},
selectHour: function (e) {
var hour = parseInt($(e.target).text(), 10);
if (!picker.use24hours) {
if (picker.date.hours() >= 12) {
if (hour !== 12) {
hour += 12;
}
} else {
if (hour === 12) {
hour = 0;
}
}
}
picker.date.hours(hour);
actions.showPicker.call(picker);
},
selectMinute: function (e) {
picker.date.minutes(parseInt($(e.target).text(), 10));
actions.showPicker.call(picker);
},
selectSecond: function (e) {
picker.date.seconds(parseInt($(e.target).text(), 10));
actions.showPicker.call(picker);
}
},
doAction = function (e) {
var oldDate = moment(picker.date),
action = $(e.currentTarget).data('action'),
rv = actions[action].apply(picker, arguments);
stopEvent(e);
if (!picker.date) {
picker.date = moment({y: 1970});
}
set();
fillTime();
notifyChange(oldDate, e.type);
return rv;
},
stopEvent = function (e) {
e.stopPropagation();
e.preventDefault();
},
keydown = function (e) {
if (e.keyCode === 27) { // allow escape to hide picker
picker.hide();
}
},
change = function (e) {
moment.locale(picker.options.language);
var input = $(e.target), oldDate = moment(picker.date), newDate = moment(input.val(), picker.format, picker.options.useStrict);
if (newDate.isValid() && !isInDisableDates(newDate) && isInEnableDates(newDate)) {
update();
picker.setValue(newDate);
notifyChange(oldDate, e.type);
set();
}
else {
picker.viewDate = oldDate;
picker.unset = true;
notifyChange(oldDate, e.type);
notifyError(newDate);
}
},
showMode = function (dir) {
if (dir) {
picker.viewMode = Math.max(picker.minViewMode, Math.min(2, picker.viewMode + dir));
}
picker.widget.find('.datepicker > div').hide().filter('.datepicker-' + dpGlobal.modes[picker.viewMode].clsName).show();
},
attachDatePickerEvents = function () {
var $this, $parent, expanded, closed, collapseData;
picker.widget.on('click', '.datepicker *', $.proxy(click, this)); // this handles date picker clicks
picker.widget.on('click', '[data-action]', $.proxy(doAction, this)); // this handles time picker clicks
picker.widget.on('mousedown', $.proxy(stopEvent, this));
picker.element.on('keydown', $.proxy(keydown, this));
if (picker.options.pickDate && picker.options.pickTime) {
picker.widget.on('click.togglePicker', '.accordion-toggle', function (e) {
e.stopPropagation();
$this = $(this);
$parent = $this.closest('ul');
expanded = $parent.find('.in');
closed = $parent.find('.collapse:not(.in)');
if (expanded && expanded.length) {
collapseData = expanded.data('collapse');
if (collapseData && collapseData.transitioning) {
return;
}
expanded.collapse('hide');
closed.collapse('show');
$this.find('span').toggleClass(picker.options.icons.time + ' ' + picker.options.icons.date);
if (picker.component) {
picker.component.find('span').toggleClass(picker.options.icons.time + ' ' + picker.options.icons.date);
}
}
});
}
if (picker.isInput) {
picker.element.on({
'click': $.proxy(picker.show, this),
'focus': $.proxy(picker.show, this),
'change': $.proxy(change, this),
'blur': $.proxy(picker.hide, this)
});
} else {
picker.element.on({
'change': $.proxy(change, this)
}, 'input');
if (picker.component) {
picker.component.on('click', $.proxy(picker.show, this));
picker.component.on('mousedown', $.proxy(stopEvent, this));
} else {
picker.element.on('click', $.proxy(picker.show, this));
}
}
},
attachDatePickerGlobalEvents = function () {
$(window).on(
'resize.datetimepicker' + picker.id, $.proxy(place, this));
if (!picker.isInput) {
$(document).on(
'mousedown.datetimepicker' + picker.id, $.proxy(picker.hide, this));
}
},
detachDatePickerEvents = function () {
picker.widget.off('click', '.datepicker *', picker.click);
picker.widget.off('click', '[data-action]');
picker.widget.off('mousedown', picker.stopEvent);
if (picker.options.pickDate && picker.options.pickTime) {
picker.widget.off('click.togglePicker');
}
if (picker.isInput) {
picker.element.off({
'focus': picker.show,
'change': change,
'click': picker.show,
'blur' : picker.hide
});
} else {
picker.element.off({
'change': change
}, 'input');
if (picker.component) {
picker.component.off('click', picker.show);
picker.component.off('mousedown', picker.stopEvent);
} else {
picker.element.off('click', picker.show);
}
}
},
detachDatePickerGlobalEvents = function () {
$(window).off('resize.datetimepicker' + picker.id);
if (!picker.isInput) {
$(document).off('mousedown.datetimepicker' + picker.id);
}
},
isInFixed = function () {
if (picker.element) {
var parents = picker.element.parents(), inFixed = false, i;
for (i = 0; i < parents.length; i++) {
if ($(parents[i]).css('position') === 'fixed') {
inFixed = true;
break;
}
}
return inFixed;
} else {
return false;
}
},
set = function () {
moment.locale(picker.options.language);
var formatted = '';
if (!picker.unset) {
formatted = moment(picker.date).format(picker.format);
}
getPickerInput().val(formatted);
picker.element.data('date', formatted);
if (!picker.options.pickTime) {
picker.hide();
}
},
checkDate = function (direction, unit, amount) {
moment.locale(picker.options.language);
var newDate;
if (direction === 'add') {
newDate = moment(picker.date);
if (newDate.hours() === 23) {
newDate.add(amount, unit);
}
newDate.add(amount, unit);
}
else {
newDate = moment(picker.date).subtract(amount, unit);
}
if (isInDisableDates(moment(newDate.subtract(amount, unit))) || isInDisableDates(newDate)) {
notifyError(newDate.format(picker.format));
return;
}
if (direction === 'add') {
picker.date.add(amount, unit);
}
else {
picker.date.subtract(amount, unit);
}
picker.unset = false;
},
isInDisableDates = function (date, timeUnit) {
moment.locale(picker.options.language);
var maxDate = moment(picker.options.maxDate, picker.format, picker.options.useStrict),
minDate = moment(picker.options.minDate, picker.format, picker.options.useStrict);
if (timeUnit) {
maxDate = maxDate.endOf(timeUnit);
minDate = minDate.startOf(timeUnit);
}
if (date.isAfter(maxDate) || date.isBefore(minDate)) {
return true;
}
if (picker.options.disabledDates === false) {
return false;
}
return picker.options.disabledDates[date.format('YYYY-MM-DD')] === true;
},
isInEnableDates = function (date) {
moment.locale(picker.options.language);
if (picker.options.enabledDates === false) {
return true;
}
return picker.options.enabledDates[date.format('YYYY-MM-DD')] === true;
},
indexGivenDates = function (givenDatesArray) {
// Store given enabledDates and disabledDates as keys.
// This way we can check their existence in O(1) time instead of looping through whole array.
// (for example: picker.options.enabledDates['2014-02-27'] === true)
var givenDatesIndexed = {}, givenDatesCount = 0, i;
for (i = 0; i < givenDatesArray.length; i++) {
if (moment.isMoment(givenDatesArray[i]) || givenDatesArray[i] instanceof Date) {
dDate = moment(givenDatesArray[i]);
} else {
dDate = moment(givenDatesArray[i], picker.format, picker.options.useStrict);
}
if (dDate.isValid()) {
givenDatesIndexed[dDate.format('YYYY-MM-DD')] = true;
givenDatesCount++;
}
}
if (givenDatesCount > 0) {
return givenDatesIndexed;
}
return false;
},
padLeft = function (string) {
string = string.toString();
if (string.length >= 2) {
return string;
}
return '0' + string;
},
getTemplate = function () {
var
headTemplate =
'<thead>' +
'<tr>' +
'<th class="prev">‹</th><th colspan="' + (picker.options.calendarWeeks ? '6' : '5') + '" class="picker-switch"></th><th class="next">›</th>' +
'</tr>' +
'</thead>',
contTemplate =
'<tbody><tr><td colspan="' + (picker.options.calendarWeeks ? '8' : '7') + '"></td></tr></tbody>',
template = '<div class="datepicker-days">' +
'<table class="table-condensed">' + headTemplate + '<tbody></tbody></table>' +
'</div>' +
'<div class="datepicker-months">' +
'<table class="table-condensed">' + headTemplate + contTemplate + '</table>' +
'</div>' +
'<div class="datepicker-years">' +
'<table class="table-condensed">' + headTemplate + contTemplate + '</table>' +
'</div>',
ret = '';
if (picker.options.pickDate && picker.options.pickTime) {
ret = '<div class="bootstrap-datetimepicker-widget' + (picker.options.sideBySide ? ' timepicker-sbs' : '') + (picker.use24hours ? ' usetwentyfour' : '') + ' dropdown-menu" style="z-index:9999 !important;">';
if (picker.options.sideBySide) {
ret += '<div class="row">' +
'<div class="col-sm-6 datepicker">' + template + '</div>' +
'<div class="col-sm-6 timepicker">' + tpGlobal.getTemplate() + '</div>' +
'</div>';
} else {
ret += '<ul class="list-unstyled">' +
'<li' + (picker.options.collapse ? ' class="collapse in"' : '') + '>' +
'<div class="datepicker">' + template + '</div>' +
'</li>' +
'<li class="picker-switch accordion-toggle"><a class="btn" style="width:100%"><span class="' + picker.options.icons.time + '"></span></a></li>' +
'<li' + (picker.options.collapse ? ' class="collapse"' : '') + '>' +
'<div class="timepicker">' + tpGlobal.getTemplate() + '</div>' +
'</li>' +
'</ul>';
}
ret += '</div>';
return ret;
}
if (picker.options.pickTime) {
return (
'<div class="bootstrap-datetimepicker-widget dropdown-menu">' +
'<div class="timepicker">' + tpGlobal.getTemplate() + '</div>' +
'</div>'
);
}
return (
'<div class="bootstrap-datetimepicker-widget dropdown-menu">' +
'<div class="datepicker">' + template + '</div>' +
'</div>'
);
},
dpGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'year',
navStep: 1
},
{
clsName: 'years',
navFnc: 'year',
navStep: 10
}
]
},
tpGlobal = {
hourTemplate: '<span data-action="showHours" data-time-component="hours" class="timepicker-hour"></span>',
minuteTemplate: '<span data-action="showMinutes" data-time-component="minutes" class="timepicker-minute"></span>',
secondTemplate: '<span data-action="showSeconds" data-time-component="seconds" class="timepicker-second"></span>'
};
tpGlobal.getTemplate = function () {
return (
'<div class="timepicker-picker">' +
'<table class="table-condensed">' +
'<tr>' +
'<td><a href="#" class="btn" data-action="incrementHours"><span class="' + picker.options.icons.up + '"></span></a></td>' +
'<td class="separator"></td>' +
'<td>' + (picker.options.useMinutes ? '<a href="#" class="btn" data-action="incrementMinutes"><span class="' + picker.options.icons.up + '"></span></a>' : '') + '</td>' +
(picker.options.useSeconds ?
'<td class="separator"></td><td><a href="#" class="btn" data-action="incrementSeconds"><span class="' + picker.options.icons.up + '"></span></a></td>' : '') +
(picker.use24hours ? '' : '<td class="separator"></td>') +
'</tr>' +
'<tr>' +
'<td>' + tpGlobal.hourTemplate + '</td> ' +
'<td class="separator">:</td>' +
'<td>' + (picker.options.useMinutes ? tpGlobal.minuteTemplate : '<span class="timepicker-minute">00</span>') + '</td> ' +
(picker.options.useSeconds ?
'<td class="separator">:</td><td>' + tpGlobal.secondTemplate + '</td>' : '') +
(picker.use24hours ? '' : '<td class="separator"></td>' +
'<td><button type="button" class="btn btn-primary" data-action="togglePeriod"></button></td>') +
'</tr>' +
'<tr>' +
'<td><a href="#" class="btn" data-action="decrementHours"><span class="' + picker.options.icons.down + '"></span></a></td>' +
'<td class="separator"></td>' +
'<td>' + (picker.options.useMinutes ? '<a href="#" class="btn" data-action="decrementMinutes"><span class="' + picker.options.icons.down + '"></span></a>' : '') + '</td>' +
(picker.options.useSeconds ?
'<td class="separator"></td><td><a href="#" class="btn" data-action="decrementSeconds"><span class="' + picker.options.icons.down + '"></span></a></td>' : '') +
(picker.use24hours ? '' : '<td class="separator"></td>') +
'</tr>' +
'</table>' +
'</div>' +
'<div class="timepicker-hours" data-action="selectHour">' +
'<table class="table-condensed"></table>' +
'</div>' +
'<div class="timepicker-minutes" data-action="selectMinute">' +
'<table class="table-condensed"></table>' +
'</div>' +
(picker.options.useSeconds ?
'<div class="timepicker-seconds" data-action="selectSecond"><table class="table-condensed"></table></div>' : '')
);
};
picker.destroy = function () {
detachDatePickerEvents();
detachDatePickerGlobalEvents();
picker.widget.remove();
picker.element.removeData('DateTimePicker');
if (picker.component) {
picker.component.removeData('DateTimePicker');
}
};
picker.show = function (e) {
if (getPickerInput().prop('disabled')) {
return;
}
if (picker.options.useCurrent) {
if (getPickerInput().val() === '') {
if (picker.options.minuteStepping !== 1) {
var mDate = moment(),
rInterval = picker.options.minuteStepping;
mDate.minutes((Math.round(mDate.minutes() / rInterval) * rInterval) % 60).seconds(0);
picker.setValue(mDate.format(picker.format));
} else {
picker.setValue(moment().format(picker.format));
}
notifyChange('', e.type);
}
}
// if this is a click event on the input field and picker is already open don't hide it
if (e && e.type === 'click' && picker.isInput && picker.widget.hasClass('picker-open')) {
return;
}
if (picker.widget.hasClass('picker-open')) {
picker.widget.hide();
picker.widget.removeClass('picker-open');
}
else {
picker.widget.show();
picker.widget.addClass('picker-open');
}
picker.height = picker.component ? picker.component.outerHeight() : picker.element.outerHeight();
place();
picker.element.trigger({
type: 'dp.show',
date: moment(picker.date)
});
attachDatePickerGlobalEvents();
if (e) {
stopEvent(e);
}
};
picker.disable = function () {
var input = getPickerInput();
if (input.prop('disabled')) {
return;
}
input.prop('disabled', true);
detachDatePickerEvents();
};
picker.enable = function () {
var input = getPickerInput();
if (!input.prop('disabled')) {
return;
}
input.prop('disabled', false);
attachDatePickerEvents();
};
picker.hide = function () {
// Ignore event if in the middle of a picker transition
var collapse = picker.widget.find('.collapse'), i, collapseData;
for (i = 0; i < collapse.length; i++) {
collapseData = collapse.eq(i).data('collapse');
if (collapseData && collapseData.transitioning) {
return;
}
}
picker.widget.hide();
picker.widget.removeClass('picker-open');
picker.viewMode = picker.startViewMode;
showMode();
picker.element.trigger({
type: 'dp.hide',
date: moment(picker.date)
});
detachDatePickerGlobalEvents();
};
picker.setValue = function (newDate) {
moment.locale(picker.options.language);
if (!newDate) {
picker.unset = true;
set();
} else {
picker.unset = false;
}
if (!moment.isMoment(newDate)) {
newDate = (newDate instanceof Date) ? moment(newDate) : moment(newDate, picker.format, picker.options.useStrict);
} else {
newDate = newDate.locale(picker.options.language);
}
if (newDate.isValid()) {
picker.date = newDate;
set();
picker.viewDate = moment({y: picker.date.year(), M: picker.date.month()});
fillDate();
fillTime();
}
else {
notifyError(newDate);
}
};
picker.getDate = function () {
if (picker.unset) {
return null;
}
return moment(picker.date);
};
picker.setDate = function (date) {
var oldDate = moment(picker.date);
if (!date) {
picker.setValue(null);
} else {
picker.setValue(date);
}
notifyChange(oldDate, 'function');
};
picker.setDisabledDates = function (dates) {
picker.options.disabledDates = indexGivenDates(dates);
if (picker.viewDate) {
update();
}
};
picker.setEnabledDates = function (dates) {
picker.options.enabledDates = indexGivenDates(dates);
if (picker.viewDate) {
update();
}
};
picker.setMaxDate = function (date) {
if (date === undefined) {
return;
}
if (moment.isMoment(date) || date instanceof Date) {
picker.options.maxDate = moment(date);
} else {
picker.options.maxDate = moment(date, picker.format, picker.options.useStrict);
}
if (picker.viewDate) {
update();
}
};
picker.setMinDate = function (date) {
if (date === undefined) {
return;
}
if (moment.isMoment(date) || date instanceof Date) {
picker.options.minDate = moment(date);
} else {
picker.options.minDate = moment(date, picker.format, picker.options.useStrict);
}
if (picker.viewDate) {
update();
}
};
init();
};
$.fn.datetimepicker = function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data('DateTimePicker');
if (!data) {
$this.data('DateTimePicker', new DateTimePicker(this, options));
}
});
};
$.fn.datetimepicker.defaults = {
format: false,
pickDate: true,
pickTime: true,
useMinutes: true,
useSeconds: false,
useCurrent: true,
calendarWeeks: false,
minuteStepping: 1,
minDate: moment({y: 1900}),
maxDate: moment().add(100, 'y'),
showToday: true,
collapse: true,
language: moment.locale(),
defaultDate: '',
disabledDates: false,
enabledDates: false,
icons: {},
useStrict: false,
direction: 'auto',
sideBySide: false,
daysOfWeekDisabled: [],
widgetParent: false
};
}));
| edwardbrosens/ambacht | upload/admin/view/javascript/jquery/datetimepicker/bootstrap-datetimepicker.min.js | JavaScript | gpl-3.0 | 58,299 |
/**
* Collapse sections then reveal them when an associated link is clicked.
*
* - Each section should have the class `js-hide-reveal`
* - Each section should have an id attribute
* - Links that open a section should have the class `js-hide-reveal-link`
* - Each links' href attribute should specify the id of the section to reveal.
*/
(function($) {
/**
* Event handler which hides or reveals the element referred to
* by the event target's href attribute.
*
* @param {jQuery.Event} e The jQuery event object
*/
var hideOrRevealHref = function(e) {
e.preventDefault();
var $this = $(this);
$($this.attr('href')).slideToggle(200);
};
var revealAllHref = function (e) {
e.preventDefault();
$('.js-hide-reveal').show();
};
$(document).ready(function() {
$('.js-hide-reveal').hide();
$('.js-hide-reveal-link').click(hideOrRevealHref);
$('.js-reveal-all-link').click(revealAllHref);
});
})(jQuery);
| patricmutwiri/pombola | pombola/core/static/js/hide-reveal.js | JavaScript | agpl-3.0 | 1,019 |
/**
* @file
* @copyright 2020 WarlockD (https://github.com/warlockd)
* @author Original WarlockD (https://github.com/warlockd)
* @author Changes stylemistake
* @author Changes ThePotato97
* @author Changes Ghommie
* @author Changes Timberpoes
* @license MIT
*/
import { classes } from 'common/react';
import { Component } from 'inferno';
import { marked } from 'marked';
import { useBackend } from '../backend';
import { Box, Flex, Tabs, TextArea } from '../components';
import { Window } from '../layouts';
import { clamp } from 'common/math';
import { sanitizeText } from '../sanitize';
const MAX_PAPER_LENGTH = 5000; // Question, should we send this with ui_data?
// Hacky, yes, works?...yes
const textWidth = (text, font, fontsize) => {
// default font height is 12 in tgui
font = fontsize + "x " + font;
const c = document.createElement('canvas');
const ctx = c.getContext("2d");
ctx.font = font;
const width = ctx.measureText(text).width;
return width;
};
const setFontinText = (text, font, color, bold=false) => {
return "<span style=\""
+ "color:" + color + ";"
+ "font-family:'" + font + "';"
+ ((bold)
? "font-weight: bold;"
: "")
+ "\">" + text + "</span>";
};
const createIDHeader = index => {
return "paperfield_" + index;
};
// To make a field you do a [_______] or however long the field is
// we will then output a TEXT input for it that hopefully covers
// the exact amount of spaces
const field_regex = /\[(_+)\]/g;
const field_tag_regex = /\[<input\s+(?!disabled)(.*?)\s+id="(?<id>paperfield_\d+)"(.*?)\/>\]/gm;
const sign_regex = /%s(?:ign)?(?=\\s|$)?/igm;
const createInputField = (length, width, font,
fontsize, color, id) => {
return "[<input "
+ "type=\"text\" "
+ "style=\""
+ "font:'" + fontsize + "x " + font + "';"
+ "color:" + color + ";"
+ "min-width:" + width + ";"
+ "max-width:" + width + ";"
+ "\" "
+ "id=\"" + id + "\" "
+ "maxlength=" + length +" "
+ "size=" + length + " "
+ "/>]";
};
const createFields = (txt, font, fontsize, color, counter) => {
const ret_text = txt.replace(field_regex, (match, p1, offset, string) => {
const width = textWidth(match, font, fontsize) + "px";
return createInputField(p1.length,
width, font, fontsize, color, createIDHeader(counter++));
});
return {
counter,
text: ret_text,
};
};
const signDocument = (txt, color, user) => {
return txt.replace(sign_regex, () => {
return setFontinText(user, "Times New Roman", color, true);
});
};
const run_marked_default = value => {
// Override function, any links and images should
// kill any other marked tokens we don't want here
const walkTokens = token => {
switch (token.type) {
case 'url':
case 'autolink':
case 'reflink':
case 'link':
case 'image':
token.type = 'text';
// Once asset system is up change to some default image
// or rewrite for icon images
token.href = "";
break;
}
};
return marked(value, {
breaks: true,
smartypants: true,
smartLists: true,
walkTokens,
// Once assets are fixed might need to change this for them
baseUrl: 'thisshouldbreakhttp',
});
};
/*
** This gets the field, and finds the dom object and sees if
** the user has typed something in. If so, it replaces,
** the dom object, in txt with the value, spaces so it
** fits the [] format and saves the value into a object
** There may be ways to optimize this in javascript but
** doing this in byond is nightmarish.
**
** It returns any values that were saved and a corrected
** html code or null if nothing was updated
*/
const checkAllFields = (txt, font, color, user_name, bold=false) => {
let matches;
let values = {};
let replace = [];
// I know its tempting to wrap ALL this in a .replace
// HOWEVER the user might not of entered anything
// if thats the case we are rebuilding the entire string
// for nothing, if nothing is entered, txt is just returned
while ((matches = field_tag_regex.exec(txt)) !== null) {
const full_match = matches[0];
const id = matches.groups.id;
if (id) {
const dom = document.getElementById(id);
// make sure we got data, and kill any html that might
// be in it
const dom_text = dom && dom.value ? dom.value : "";
if (dom_text.length === 0) {
continue;
}
const sanitized_text = sanitizeText(dom.value.trim(), []);
if (sanitized_text.length === 0) {
continue;
}
// this is easier than doing a bunch of text manipulations
const target = dom.cloneNode(true);
// in case they sign in a field
if (sanitized_text.match(sign_regex)) {
target.style.fontFamily = "Times New Roman";
bold = true;
target.defaultValue = user_name;
}
else {
target.style.fontFamily = font;
target.defaultValue = sanitized_text;
}
if (bold) {
target.style.fontWeight = "bold";
}
target.style.color = color;
target.disabled = true;
const wrap = document.createElement('div');
wrap.appendChild(target);
values[id] = sanitized_text; // save the data
replace.push({ value: "[" + wrap.innerHTML + "]", raw_text: full_match });
}
}
if (replace.length > 0) {
for (const o of replace) {
txt = txt.replace(o.raw_text, o.value);
}
}
return { text: txt, fields: values };
};
const pauseEvent = e => {
if (e.stopPropagation) { e.stopPropagation(); }
if (e.preventDefault) { e.preventDefault(); }
e.cancelBubble=true;
e.returnValue=false;
return false;
};
const Stamp = (props, context) => {
const {
image,
opacity,
} = props;
const stamp_transform = {
'left': image.x + 'px',
'top': image.y + 'px',
'transform': 'rotate(' + image.rotate + 'deg)',
'opacity': opacity || 1.0,
};
return (
<div
id="stamp"
className={classes([
'Paper__Stamp',
image.sprite,
])}
style={stamp_transform} />
);
};
const setInputReadonly = (text, readonly) => {
return readonly
? text.replace(/<input\s[^d]/g, '<input disabled ')
: text.replace(/<input\sdisabled\s/g, '<input ');
};
// got to make this a full component if we
// want to control updates
const PaperSheetView = (props, context) => {
const {
value = "",
stamps = [],
backgroundColor,
readOnly,
} = props;
const stamp_list = stamps;
const text_html = {
__html: '<span class="paper-text">'
+ setInputReadonly(value, readOnly)
+ '</span>',
};
return (
<Box
position="relative"
backgroundColor={backgroundColor}
width="100%"
height="100%" >
<Box
className="Paper__Page"
fillPositionedParent
width="100%"
height="100%"
dangerouslySetInnerHTML={text_html}
p="10px" />
{stamp_list.map((o, i) => (
<Stamp key={o[0] + i}
image={{ sprite: o[0], x: o[1], y: o[2], rotate: o[3] }} />
))}
</Box>
);
};
// again, need the states for dragging and such
class PaperSheetStamper extends Component {
constructor(props, context) {
super(props, context);
this.state = {
x: 0,
y: 0,
rotate: 0,
};
this.style = null;
this.handleMouseMove = e => {
const pos = this.findStampPosition(e);
if (!pos) { return; }
// center offset of stamp & rotate
pauseEvent(e);
this.setState({ x: pos[0], y: pos[1], rotate: pos[2] });
};
this.handleMouseClick = e => {
if (e.pageY <= 30) { return; }
const { act, data } = useBackend(this.context);
const stamp_obj = {
x: this.state.x, y: this.state.y, r: this.state.rotate,
stamp_class: this.props.stamp_class,
stamp_icon_state: data.stamp_icon_state,
};
act("stamp", stamp_obj);
};
}
findStampPosition(e) {
let rotating;
const windowRef = document.querySelector('.Layout__content');
if (e.shiftKey) {
rotating = true;
}
if (document.getElementById("stamp"))
{
const stamp = document.getElementById("stamp");
const stampHeight = stamp.clientHeight;
const stampWidth = stamp.clientWidth;
const currentHeight = rotating ? this.state.y : e.pageY
- windowRef.scrollTop - stampHeight;
const currentWidth = rotating ? this.state.x : e.pageX - (stampWidth / 2);
const widthMin = 0;
const heightMin = 0;
const widthMax = (windowRef.clientWidth) - (
stampWidth);
const heightMax = (windowRef.clientHeight - windowRef.scrollTop) - (
stampHeight);
const radians = Math.atan2(
e.pageX - currentWidth,
e.pageY - currentHeight
);
const rotate = rotating ? (radians * (180 / Math.PI) * -1)
: this.state.rotate;
const pos = [
clamp(currentWidth, widthMin, widthMax),
clamp(currentHeight, heightMin, heightMax),
rotate,
];
return pos;
}
}
componentDidMount() {
document.addEventListener("mousemove", this.handleMouseMove);
document.addEventListener("click", this.handleMouseClick);
}
componentWillUnmount() {
document.removeEventListener("mousemove", this.handleMouseMove);
document.removeEventListener("click", this.handleMouseClick);
}
render() {
const {
value,
stamp_class,
stamps,
} = this.props;
const stamp_list = stamps || [];
const current_pos = {
sprite: stamp_class,
x: this.state.x,
y: this.state.y,
rotate: this.state.rotate,
};
return (
<>
<PaperSheetView
readOnly
value={value}
stamps={stamp_list} />
<Stamp
active_stamp
opacity={0.5} image={current_pos} />
</>
);
}
}
// This creates the html from marked text as well as the form fields
const createPreview = (
value,
text,
do_fields = false,
field_counter,
color,
font,
user_name,
is_crayon = false,
) => {
const out = { text: text };
// check if we are adding to paper, if not
// we still have to check if someone entered something
// into the fields
value = value.trim();
if (value.length > 0) {
// First lets make sure it ends in a new line
value += value[value.length] === "\n" ? " \n" : "\n \n";
// Second, we sanitize the text of html
const sanitized_text = sanitizeText(value);
const signed_text = signDocument(sanitized_text, color, user_name);
// Third we replace the [__] with fields as markedjs fucks them up
const fielded_text = createFields(
signed_text, font, 12, color, field_counter);
// Fourth, parse the text using markup
const formatted_text = run_marked_default(fielded_text.text);
// Fifth, we wrap the created text in the pin color, and font.
// crayon is bold (<b> tags), maybe make fountain pin italic?
const fonted_text = setFontinText(
formatted_text, font, color, is_crayon);
out.text += fonted_text;
out.field_counter = fielded_text.counter;
}
if (do_fields) {
// finally we check all the form fields to see
// if any data was entered by the user and
// if it was return the data and modify the text
const final_processing = checkAllFields(
out.text, font, color, user_name, is_crayon);
out.text = final_processing.text;
out.form_fields = final_processing.fields;
}
return out;
};
// ugh. So have to turn this into a full
// component too if I want to keep updates
// low and keep the weird flashing down
class PaperSheetEdit extends Component {
constructor(props, context) {
super(props, context);
this.state = {
previewSelected: "Preview",
old_text: props.value || "",
counter: props.counter || 0,
textarea_text: "",
combined_text: props.value || "",
};
}
createPreviewFromData(value, do_fields = false) {
const { data } = useBackend(this.context);
return createPreview(value,
this.state.old_text,
do_fields,
this.state.counter,
data.pen_color,
data.pen_font,
data.edit_usr,
data.is_crayon,
);
}
onInputHandler(e, value) {
if (value !== this.state.textarea_text) {
const combined_length = this.state.old_text.length
+ this.state.textarea_text.length;
if (combined_length > MAX_PAPER_LENGTH) {
if ((combined_length - MAX_PAPER_LENGTH) >= value.length) {
// Basically we cannot add any more text to the paper
value = '';
} else {
value = value.substr(0, value.length
- (combined_length - MAX_PAPER_LENGTH));
}
// we check again to save an update
if (value === this.state.textarea_text) {
// Do nothing
return;
}
}
this.setState(() => ({
textarea_text: value,
combined_text: this.createPreviewFromData(value),
}));
}
}
// the final update send to byond, final upkeep
finalUpdate(new_text) {
const { act } = useBackend(this.context);
const final_processing = this.createPreviewFromData(new_text, true);
act('save', final_processing);
this.setState(() => { return {
textarea_text: "",
previewSelected: "save",
combined_text: final_processing.text,
old_text: final_processing.text,
counter: final_processing.field_counter,
}; });
// byond should switch us to readonly mode from here
}
render() {
const {
textColor,
fontFamily,
stamps,
backgroundColor,
} = this.props;
return (
<Flex
direction="column"
fillPositionedParent>
<Flex.Item>
<Tabs>
<Tabs.Tab
key="marked_edit"
textColor={'black'}
backgroundColor={this.state.previewSelected === "Edit"
? "grey"
: "white"}
selected={this.state.previewSelected === "Edit"}
onClick={() => this.setState({ previewSelected: "Edit" })}>
Edit
</Tabs.Tab>
<Tabs.Tab
key="marked_preview"
textColor={'black'}
backgroundColor={this.state.previewSelected === "Preview"
? "grey"
: "white"}
selected={this.state.previewSelected === "Preview"}
onClick={() => this.setState(() => {
const new_state = {
previewSelected: "Preview",
textarea_text: this.state.textarea_text,
combined_text: this.createPreviewFromData(
this.state.textarea_text).text,
};
return new_state;
})}>
Preview
</Tabs.Tab>
<Tabs.Tab
key="marked_done"
textColor={'black'}
backgroundColor={this.state.previewSelected === "confirm"
? "red"
: this.state.previewSelected === "save"
? "grey"
: "white"}
selected={this.state.previewSelected === "confirm"
|| this.state.previewSelected === "save"}
onClick={() => {
if (this.state.previewSelected === "confirm") {
this.finalUpdate(this.state.textarea_text);
}
else if (this.state.previewSelected === "Edit") {
this.setState(() => {
const new_state = {
previewSelected: "confirm",
textarea_text: this.state.textarea_text,
combined_text: this.createPreviewFromData(
this.state.textarea_text).text,
};
return new_state;
});
}
else {
this.setState({ previewSelected: "confirm" });
}
}}>
{this.state.previewSelected === "confirm" ? "Confirm" : "Save"}
</Tabs.Tab>
</Tabs>
</Flex.Item>
<Flex.Item
grow={1}
basis={1}>
{this.state.previewSelected === "Edit" && (
<TextArea
value={this.state.textarea_text}
textColor={textColor}
fontFamily={fontFamily}
height={(window.innerHeight - 80) + "px"}
backgroundColor={backgroundColor}
onInput={this.onInputHandler.bind(this)} />
) || (
<PaperSheetView
value={this.state.combined_text}
stamps={stamps}
fontFamily={fontFamily}
textColor={textColor} />
)}
</Flex.Item>
</Flex>
);
}
}
export const PaperSheet = (props, context) => {
const { data } = useBackend(context);
const {
edit_mode,
text,
paper_color = "white",
pen_color = "black",
pen_font = "Verdana",
stamps,
stamp_class,
sizeX,
sizeY,
name,
add_text,
add_font,
add_color,
add_sign,
field_counter,
} = data;
// some features can add text to a paper sheet outside of this ui
// we need to parse, sanitize and add any of it to the text value.
const values = { text: text, field_counter: field_counter };
if (add_text) {
for (let index = 0; index < add_text.length; index++) {
const used_color = add_color[index];
const used_font = add_font[index];
const used_sign = add_sign[index];
const processing = createPreview(
add_text[index],
values.text,
false,
values.field_counter,
used_color,
used_font,
used_sign
);
values.text = processing.text;
values.field_counter = processing.field_counter;
}
}
const stamp_list = !stamps
? []
: stamps;
const decide_mode = mode => {
switch (mode) {
case 0:
return (
<PaperSheetView
value={values.text}
stamps={stamp_list}
readOnly />
);
case 1:
return (
<PaperSheetEdit
value={values.text}
counter={values.field_counter}
textColor={pen_color}
fontFamily={pen_font}
stamps={stamp_list}
backgroundColor={paper_color} />
);
case 2:
return (
<PaperSheetStamper
value={values.text}
stamps={stamp_list}
stamp_class={stamp_class} />
);
default:
return "ERROR ERROR WE CANNOT BE HERE!!";
}
};
return (
<Window
title={name}
theme="paper"
width={sizeX || 400}
height={sizeY || 500}>
<Window.Content
backgroundColor={paper_color}
scrollable>
<Box
id="page"
fitted
fillPositionedParent>
{decide_mode(edit_mode)}
</Box>
</Window.Content>
</Window>
);
};
| Bawhoppen/-tg-station | tgui/packages/tgui/interfaces/PaperSheet.js | JavaScript | agpl-3.0 | 19,192 |
description(
"Tests that the CompareEq optimization for the case where one side is predicted final object and the other side is predicted either final object or other (i.e. null or undefined) doesn't assert when the other side is also proven final object."
);
function foo(a, b) {
return [b.f, a == b];
}
for (var i = 0; i < 100; ++i) {
if (i%2) {
var o = {f:42};
shouldBe("foo(o, o)", "[42, true]");
} else
shouldThrow("foo({f:42}, null)");
}
| youfoh/webkit-efl | LayoutTests/fast/js/script-tests/dfg-compare-final-object-to-final-object-or-other-when-proven-final-object.js | JavaScript | lgpl-2.1 | 483 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
var MIN_NODE_VER = "0.9.9",
ERROR_VALUE = 2,
exit = require('exit'),
signingUtils = require('./lib/signing-utils');
function isNodeNewerThanMin () {
//Current version is stored as a String in format "X.X.X"
//Must be newer than "0.9.9"
var currentVer = process.versions.node.split(".").map(function (verNumStr) { return parseInt(verNumStr, 10);});
return (currentVer[0] > 0 || currentVer[1] > 9 || currentVer[1] === 9 && currentVer[2] >= 9);
}
if (!isNodeNewerThanMin()) {
console.log("Node version '" + process.versions.node + "' is not new enough. Please upgrade to " + MIN_NODE_VER + " or newer. Aborting.");
exit(ERROR_VALUE);
}
exit(0);
| zosiakropka/flat-calc | platforms/blackberry10/cordova/check_reqs.js | JavaScript | apache-2.0 | 1,491 |
import eachWeekendOfInterval from '../eachWeekendOfInterval/index.js';
import startOfMonth from '../startOfMonth/index.js';
import endOfMonth from '../endOfMonth/index.js';
import requiredArgs from '../_lib/requiredArgs/index.js';
/**
* @name eachWeekendOfMonth
* @category Month Helpers
* @summary List all the Saturdays and Sundays in the given month.
*
* @description
* Get all the Saturdays and Sundays in the given month.
*
* @param {Date|Number} date - the given month
* @returns {Date[]} an array containing all the Saturdays and Sundays
* @throws {TypeError} 1 argument required
* @throws {RangeError} The passed date is invalid
*
* @example
* // Lists all Saturdays and Sundays in the given month
* var result = eachWeekendOfMonth(new Date(2022, 1, 1))
* //=> [
* // Sat Feb 05 2022 00:00:00,
* // Sun Feb 06 2022 00:00:00,
* // Sat Feb 12 2022 00:00:00,
* // Sun Feb 13 2022 00:00:00,
* // Sat Feb 19 2022 00:00:00,
* // Sun Feb 20 2022 00:00:00,
* // Sat Feb 26 2022 00:00:00,
* // Sun Feb 27 2022 00:00:00
* // ]
*/
export default function eachWeekendOfMonth(dirtyDate) {
requiredArgs(1, arguments);
var startDate = startOfMonth(dirtyDate);
if (isNaN(startDate)) throw new RangeError('The passed date is invalid');
var endDate = endOfMonth(dirtyDate);
return eachWeekendOfInterval({
start: startDate,
end: endDate
});
} | BigBoss424/portfolio | v8/development/node_modules/date-fns/esm/eachWeekendOfMonth/index.js | JavaScript | apache-2.0 | 1,394 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("placeholder","no",{title:"Egenskaper for plassholder",toolbar:"Opprett plassholder",name:"Navn på plassholder",invalidName:"Plassholderen kan ikke være tom, og kan ikke inneholde følgende tegn: [, ], <, >",pathName:"plassholder"}); | viticm/pfadmin | vendor/frozennode/administrator/public/js/ckeditor/plugins/placeholder/lang/no.js | JavaScript | apache-2.0 | 405 |
module.exports = function () {
this.When(/^I use S3 managed upload to upload(?: a| an) (empty|small|large) buffer to the key "([^"]*)"$/, function (size, key, callback) {
var self = this;
var buffer = self.createBuffer(size);
var params = {Bucket: self.sharedBucket, Key: key, Body: buffer};
self.s3.upload(params, function (err, data) {
self.error = err;
self.data = data;
callback();
});
});
this.Given(/^I generate the MD5 checksum of a (\d+MB) buffer$/, function(size, next) {
this.uploadBuffer = this.createBuffer(size);
this.sentContentMD5 = this.AWS.util.crypto.md5(this.uploadBuffer, 'base64');
next();
});
this.Given(/^I use S3 managed upload to upload the buffer to the key "([^"]*)"$/, function (key, callback) {
var self = this;
var params = {Bucket: self.sharedBucket, Key: key, Body: self.uploadBuffer};
self.s3.upload(params, function (err, data) {
self.error = err;
self.data = data;
callback();
});
});
this.Then(/^the multipart upload should succeed$/, function (callback) {
this.assert.equal(this.error, null);
this.assert.equal(typeof this.data.Location, 'string');
callback();
});
this.When(/^I use S3 managed upload to upload(?: a| an) (empty|small|large) stream to the key "([^"]*)"$/, function (size, key, callback) {
var fs = require('fs');
var self = this;
var fileName = self.createFile(size);
var params = {Bucket: self.sharedBucket, Key: key, Body: fs.createReadStream(fileName)};
self.progressEvents = [];
var progress = function(info) {
self.progressEvents.push(info);
};
self.s3.upload(params).on('httpUploadProgress', progress).send(function (err, data) {
self.error = err;
self.data = data;
callback();
});
});
this.Then(/^I should get progress events$/, function (callback) {
this.assert.compare(this.progressEvents.length, '>', 0);
callback();
});
this.Then(/^the ContentLength should equal (\d+)$/, function (val, callback) {
this.assert.equal(this.data.ContentLength, val);
callback();
});
this.When(/^I use S3 managed upload to upload some (\d+MB) buffer to the key "([^"]*)"$/, function(size, key, callback) {
var self = this;
var params = {
Bucket: self.sharedBucket,
Key: key,
Body: self.createBuffer(size)
};
self.progressEvents = [];
var progress = function progress(info) {
self.progressEvents.push(info);
};
var managedUpload = self.managedUpload = new self.AWS.S3.ManagedUpload({
leavePartsOnError: true,
params: params,
service: self.s3
});
managedUpload.on('httpUploadProgress', progress).send(function(err, data) {
self.error = err;
self.data = data;
});
callback();
});
this.When(/^I use S3 managed upload to partially upload some (\d+MB) buffer to the key "([^"]*)"$/, function(size, key, callback) {
var self = this;
var params = {
Bucket: self.sharedBucket,
Key: key,
Body: self.createBuffer(size)
};
self.progressEvents = [];
var didAbort = false;
var progress = function progress(info) {
if (self.progressEvents.length && !didAbort) {
didAbort = true;
self.managedUpload.abort();
}
self.progressEvents.push(info);
};
var managedUpload = self.managedUpload = new self.AWS.S3.ManagedUpload({
leavePartsOnError: true,
queueSize: 1,
params: params,
service: self.s3
});
managedUpload.on('httpUploadProgress', progress).send(function(err, data) {
self.error = err;
self.data = data;
callback();
});
});
this.When(/^I abort the upload$/, function(callback) {
this.managedUpload.abort();
callback();
});
this.Then(/^I receive a "([^"]*)" error$/, function(errName, callback) {
this.assert.equal(this.error.name, errName);
callback();
});
this.When(/^I resume the upload$/, function(callback) {
var self = this;
self.managedUpload.send(function(err, data) {
self.error = err;
self.data = data;
callback();
});
});
this.Then(/^uploadPart should have been called (\d+) times$/, function(count, callback) {
this.assert.equal(this.progressEvents.length, count);
callback();
});
};
| guymguym/aws-sdk-js | features/s3/step_definitions/managed_upload.js | JavaScript | apache-2.0 | 4,358 |
require('./node_loader');
var AWS = require('./core');
// Load all service classes
require('../clients/all');
/**
* @api private
*/
module.exports = AWS;
| chrisradek/aws-sdk-js | lib/aws.js | JavaScript | apache-2.0 | 159 |
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 23.2.3.2
description: >
Set.prototype.clear ( )
17 ECMAScript Standard Built-in Objects
includes: [propertyHelper.js]
---*/
assert.sameValue(Set.prototype.clear.name, "clear", "The value of `Set.prototype.clear.name` is `'clear'`");
verifyNotEnumerable(Set.prototype.clear, "name");
verifyNotWritable(Set.prototype.clear, "name");
verifyConfigurable(Set.prototype.clear, "name");
| sebastienros/jint | Jint.Tests.Test262/test/built-ins/Set/prototype/clear/name.js | JavaScript | bsd-2-clause | 543 |
/*
* L.SVG renders vector layers with SVG. All SVG-specific code goes here.
*/
L.SVG = L.Renderer.extend({
_initContainer: function () {
this._container = L.SVG.create('svg');
// makes it possible to click through svg root; we'll reset it back in individual paths
this._container.setAttribute('pointer-events', 'none');
},
_update: function () {
if (this._map._animatingZoom && this._bounds) { return; }
L.Renderer.prototype._update.call(this);
var b = this._bounds,
size = b.getSize(),
container = this._container;
L.DomUtil.setPosition(container, b.min);
// set size of svg-container if changed
if (!this._svgSize || !this._svgSize.equals(size)) {
this._svgSize = size;
container.setAttribute('width', size.x);
container.setAttribute('height', size.y);
}
// movement: update container viewBox so that we don't have to change coordinates of individual layers
L.DomUtil.setPosition(container, b.min);
container.setAttribute('viewBox', [b.min.x, b.min.y, size.x, size.y].join(' '));
},
// methods below are called by vector layers implementations
_initPath: function (layer) {
var path = layer._path = L.SVG.create('path');
if (layer.options.className) {
L.DomUtil.addClass(path, layer.options.className);
}
if (layer.options.interactive) {
L.DomUtil.addClass(path, 'leaflet-interactive');
}
this._updateStyle(layer);
},
_addPath: function (layer) {
this._container.appendChild(layer._path);
layer.addInteractiveTarget(layer._path);
},
_removePath: function (layer) {
L.DomUtil.remove(layer._path);
layer.removeInteractiveTarget(layer._path);
},
_updatePath: function (layer) {
layer._project();
layer._update();
},
_updateStyle: function (layer) {
var path = layer._path,
options = layer.options;
if (!path) { return; }
if (options.stroke) {
path.setAttribute('stroke', options.color);
path.setAttribute('stroke-opacity', options.opacity);
path.setAttribute('stroke-width', options.weight);
path.setAttribute('stroke-linecap', options.lineCap);
path.setAttribute('stroke-linejoin', options.lineJoin);
if (options.dashArray) {
path.setAttribute('stroke-dasharray', options.dashArray);
} else {
path.removeAttribute('stroke-dasharray');
}
if (options.dashOffset) {
path.setAttribute('stroke-dashoffset', options.dashOffset);
} else {
path.removeAttribute('stroke-dashoffset');
}
} else {
path.setAttribute('stroke', 'none');
}
if (options.fill) {
path.setAttribute('fill', options.fillColor || options.color);
path.setAttribute('fill-opacity', options.fillOpacity);
path.setAttribute('fill-rule', options.fillRule || 'evenodd');
} else {
path.setAttribute('fill', 'none');
}
path.setAttribute('pointer-events', options.pointerEvents || (options.interactive ? 'visiblePainted' : 'none'));
},
_updatePoly: function (layer, closed) {
this._setPath(layer, L.SVG.pointsToPath(layer._parts, closed));
},
_updateCircle: function (layer) {
var p = layer._point,
r = layer._radius,
r2 = layer._radiusY || r,
arc = 'a' + r + ',' + r2 + ' 0 1,0 ';
// drawing a circle with two half-arcs
var d = layer._empty() ? 'M0 0' :
'M' + (p.x - r) + ',' + p.y +
arc + (r * 2) + ',0 ' +
arc + (-r * 2) + ',0 ';
this._setPath(layer, d);
},
_setPath: function (layer, path) {
layer._path.setAttribute('d', path);
},
// SVG does not have the concept of zIndex so we resort to changing the DOM order of elements
_bringToFront: function (layer) {
L.DomUtil.toFront(layer._path);
},
_bringToBack: function (layer) {
L.DomUtil.toBack(layer._path);
}
});
L.extend(L.SVG, {
create: function (name) {
return document.createElementNS('http://www.w3.org/2000/svg', name);
},
// generates SVG path string for multiple rings, with each ring turning into "M..L..L.." instructions
pointsToPath: function (rings, closed) {
var str = '',
i, j, len, len2, points, p;
for (i = 0, len = rings.length; i < len; i++) {
points = rings[i];
for (j = 0, len2 = points.length; j < len2; j++) {
p = points[j];
str += (j ? 'L' : 'M') + p.x + ' ' + p.y;
}
// closes the ring for polygons; "x" is VML syntax
str += closed ? (L.Browser.svg ? 'z' : 'x') : '';
}
// SVG complains about empty path strings
return str || 'M0 0';
}
});
L.Browser.svg = !!(document.createElementNS && L.SVG.create('svg').createSVGRect);
L.svg = function (options) {
return L.Browser.svg || L.Browser.vml ? new L.SVG(options) : null;
};
| lee101/Leaflet | src/layer/vector/SVG.js | JavaScript | bsd-2-clause | 4,575 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// 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 A singleton object for managing Javascript code modules.
*
*/
goog.provide('goog.module.ModuleManager');
goog.provide('goog.module.ModuleManager.CallbackType');
goog.provide('goog.module.ModuleManager.FailureType');
goog.require('goog.Disposable');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.async.Deferred');
goog.require('goog.debug.Trace');
/** @suppress {extraRequire} */
goog.require('goog.dispose');
goog.require('goog.log');
/** @suppress {extraRequire} */
goog.require('goog.module');
/** @suppress {extraRequire} interface */
goog.require('goog.module.AbstractModuleLoader');
goog.require('goog.module.ModuleInfo');
goog.require('goog.module.ModuleLoadCallback');
goog.require('goog.object');
/**
* The ModuleManager keeps track of all modules in the environment.
* Since modules may not have their code loaded, we must keep track of them.
* @constructor
* @extends {goog.Disposable}
* @struct
*/
goog.module.ModuleManager = function() {
goog.module.ModuleManager.base(this, 'constructor');
/**
* A mapping from module id to ModuleInfo object.
* @private {Object<string, !goog.module.ModuleInfo>}
*/
this.moduleInfoMap_ = {};
// TODO (malteubl): Switch this to a reentrant design.
/**
* The ids of the currently loading modules. If batch mode is disabled, then
* this array will never contain more than one element at a time.
* @type {Array<string>}
* @private
*/
this.loadingModuleIds_ = [];
/**
* The requested ids of the currently loading modules. This does not include
* module dependencies that may also be loading.
* @type {Array<string>}
* @private
*/
this.requestedLoadingModuleIds_ = [];
// TODO(user): Make these and other arrays that are used as sets be
// actual sets.
/**
* All module ids that have ever been requested. In concurrent loading these
* are the ones to subtract from future requests.
* @type {!Array<string>}
* @private
*/
this.requestedModuleIds_ = [];
/**
* A queue of the ids of requested but not-yet-loaded modules. The zero
* position is the front of the queue. This is a 2-D array to group modules
* together with other modules that should be batch loaded with them, if
* batch loading is enabled.
* @type {Array<Array<string>>}
* @private
*/
this.requestedModuleIdsQueue_ = [];
/**
* The ids of the currently loading modules which have been initiated by user
* actions.
* @type {Array<string>}
* @private
*/
this.userInitiatedLoadingModuleIds_ = [];
/**
* A map of callback types to the functions to call for the specified
* callback type.
* @type {Object<goog.module.ModuleManager.CallbackType, Array<Function>>}
* @private
*/
this.callbackMap_ = {};
/**
* Module info for the base module (the one that contains the module
* manager code), which we set as the loading module so one can
* register initialization callbacks in the base module.
*
* The base module is considered loaded when #setAllModuleInfo is called or
* #setModuleContext is called, whichever comes first.
*
* @type {goog.module.ModuleInfo}
* @private
*/
this.baseModuleInfo_ = new goog.module.ModuleInfo([], '');
/**
* The module that is currently loading, or null if not loading anything.
* @type {goog.module.ModuleInfo}
* @private
*/
this.currentlyLoadingModule_ = this.baseModuleInfo_;
/**
* The id of the last requested initial module. When it loaded
* the deferred in {@code this.initialModulesLoaded_} resolves.
* @private {?string}
*/
this.lastInitialModuleId_ = null;
/**
* Deferred for when all initial modules have loaded. We currently block
* sending additional module requests until this deferred resolves. In a
* future optimization it may be possible to use the initial modules as
* seeds for the module loader "requested module ids" and start making new
* requests even sooner.
* @private {!goog.async.Deferred}
*/
this.initialModulesLoaded_ = new goog.async.Deferred();
/**
* A logger.
* @private {goog.log.Logger}
*/
this.logger_ = goog.log.getLogger('goog.module.ModuleManager');
/**
* Whether the batch mode (i.e. the loading of multiple modules with just one
* request) has been enabled.
* @private {boolean}
*/
this.batchModeEnabled_ = false;
/**
* Whether the module requests may be sent out of order.
* @private {boolean}
*/
this.concurrentLoadingEnabled_ = false;
/**
* A loader for the modules that implements loadModules(ids, moduleInfoMap,
* opt_successFn, opt_errorFn, opt_timeoutFn, opt_forceReload) method.
* @private {goog.module.AbstractModuleLoader}
*/
this.loader_ = null;
// TODO(user): Remove tracer.
/**
* Tracer that measures how long it takes to load a module.
* @private {?number}
*/
this.loadTracer_ = null;
/**
* The number of consecutive failures that have happened upon module load
* requests.
* @private {number}
*/
this.consecutiveFailures_ = 0;
/**
* Determines if the module manager was just active before the processing of
* the last data.
* @private {boolean}
*/
this.lastActive_ = false;
/**
* Determines if the module manager was just user active before the processing
* of the last data. The module manager is user active if any of the
* user-initiated modules are loading or queued up to load.
* @private {boolean}
*/
this.userLastActive_ = false;
/**
* The module context needed for module initialization.
* @private {Object}
*/
this.moduleContext_ = null;
};
goog.inherits(goog.module.ModuleManager, goog.Disposable);
goog.addSingletonGetter(goog.module.ModuleManager);
/**
* The type of callbacks that can be registered with the module manager,.
* @enum {string}
*/
goog.module.ModuleManager.CallbackType = {
/**
* Fired when an error has occurred.
*/
ERROR: 'error',
/**
* Fired when it becomes idle and has no more module loads to process.
*/
IDLE: 'idle',
/**
* Fired when it becomes active and has module loads to process.
*/
ACTIVE: 'active',
/**
* Fired when it becomes idle and has no more user-initiated module loads to
* process.
*/
USER_IDLE: 'userIdle',
/**
* Fired when it becomes active and has user-initiated module loads to
* process.
*/
USER_ACTIVE: 'userActive'
};
/**
* A non-HTTP status code indicating a corruption in loaded module.
* This should be used by a ModuleLoader as a replacement for the HTTP code
* given to the error handler function to indicated that the module was
* corrupted.
* This will set the forceReload flag on the loadModules method when retrying
* module loading.
* @type {number}
*/
goog.module.ModuleManager.CORRUPT_RESPONSE_STATUS_CODE = 8001;
/**
* Sets the batch mode as enabled or disabled for the module manager.
* @param {boolean} enabled Whether the batch mode is to be enabled or not.
*/
goog.module.ModuleManager.prototype.setBatchModeEnabled = function(enabled) {
this.batchModeEnabled_ = enabled;
};
/**
* Sets the concurrent loading mode as enabled or disabled for the module
* manager. Requires a moduleloader implementation that supports concurrent
* loads. The default {@see goog.module.ModuleLoader} does not.
* @param {boolean} enabled
*/
goog.module.ModuleManager.prototype.setConcurrentLoadingEnabled = function(
enabled) {
this.concurrentLoadingEnabled_ = enabled;
};
/**
* Sets the module info for all modules. Should only be called once.
*
* @param {Object<Array<string>>} infoMap An object that contains a mapping
* from module id (String) to list of required module ids (Array).
*/
goog.module.ModuleManager.prototype.setAllModuleInfo = function(infoMap) {
for (var id in infoMap) {
this.moduleInfoMap_[id] = new goog.module.ModuleInfo(infoMap[id], id);
}
if (!this.initialModulesLoaded_.hasFired()) {
this.initialModulesLoaded_.callback();
}
this.maybeFinishBaseLoad_();
};
/**
* Sets the module info for all modules. Should only be called once. Also
* marks modules that are currently being loaded.
*
* @param {string=} opt_info A string representation of the module dependency
* graph, in the form: module1:dep1,dep2/module2:dep1,dep2 etc.
* Where depX is the base-36 encoded position of the dep in the module list.
* @param {Array<string>=} opt_loadingModuleIds A list of moduleIds that
* are currently being loaded.
*/
goog.module.ModuleManager.prototype.setAllModuleInfoString = function(
opt_info, opt_loadingModuleIds) {
if (!goog.isString(opt_info)) {
// The call to this method is generated in two steps, the argument is added
// after some of the compilation passes. This means that the initial code
// doesn't have any arguments and causes compiler errors. We make it
// optional to satisfy this constraint.
return;
}
var modules = opt_info.split('/');
var moduleIds = [];
// Split the string into the infoMap of id->deps
for (var i = 0; i < modules.length; i++) {
var parts = modules[i].split(':');
var id = parts[0];
var deps;
if (parts[1]) {
deps = parts[1].split(',');
for (var j = 0; j < deps.length; j++) {
var index = parseInt(deps[j], 36);
goog.asserts.assert(
moduleIds[index], 'No module @ %s, dep of %s @ %s', index, id, i);
deps[j] = moduleIds[index];
}
} else {
deps = [];
}
moduleIds.push(id);
this.moduleInfoMap_[id] = new goog.module.ModuleInfo(deps, id);
}
if (opt_loadingModuleIds && opt_loadingModuleIds.length) {
goog.array.extend(this.loadingModuleIds_, opt_loadingModuleIds);
// The last module in the list of initial modules. When it has loaded all
// initial modules have loaded.
this.lastInitialModuleId_ =
/** @type {?string} */ (goog.array.peek(opt_loadingModuleIds));
} else {
if (!this.initialModulesLoaded_.hasFired()) {
this.initialModulesLoaded_.callback();
}
}
this.maybeFinishBaseLoad_();
};
/**
* Gets a module info object by id.
* @param {string} id A module identifier.
* @return {!goog.module.ModuleInfo} The module info.
*/
goog.module.ModuleManager.prototype.getModuleInfo = function(id) {
return this.moduleInfoMap_[id];
};
/**
* Sets the module uris.
*
* @param {Object} moduleUriMap The map of id/uris pairs for each module.
*/
goog.module.ModuleManager.prototype.setModuleUris = function(moduleUriMap) {
for (var id in moduleUriMap) {
this.moduleInfoMap_[id].setUris(moduleUriMap[id]);
}
};
/**
* Gets the application-specific module loader.
* @return {goog.module.AbstractModuleLoader} An object that has a
* loadModules(ids, moduleInfoMap, opt_successFn, opt_errFn,
* opt_timeoutFn, opt_forceReload) method.
*/
goog.module.ModuleManager.prototype.getLoader = function() {
return this.loader_;
};
/**
* Sets the application-specific module loader.
* @param {goog.module.AbstractModuleLoader} loader An object that has a
* loadModules(ids, moduleInfoMap, opt_successFn, opt_errFn,
* opt_timeoutFn, opt_forceReload) method.
*/
goog.module.ModuleManager.prototype.setLoader = function(loader) {
this.loader_ = loader;
};
/**
* Gets the module context to use to initialize the module.
* @return {Object} The context.
*/
goog.module.ModuleManager.prototype.getModuleContext = function() {
return this.moduleContext_;
};
/**
* Sets the module context to use to initialize the module.
* @param {Object} context The context.
*/
goog.module.ModuleManager.prototype.setModuleContext = function(context) {
this.moduleContext_ = context;
this.maybeFinishBaseLoad_();
};
/**
* Determines if the ModuleManager is active
* @return {boolean} TRUE iff the ModuleManager is active (i.e., not idle).
*/
goog.module.ModuleManager.prototype.isActive = function() {
return this.loadingModuleIds_.length > 0;
};
/**
* Determines if the ModuleManager is user active
* @return {boolean} TRUE iff the ModuleManager is user active (i.e., not idle).
*/
goog.module.ModuleManager.prototype.isUserActive = function() {
return this.userInitiatedLoadingModuleIds_.length > 0;
};
/**
* Dispatches an ACTIVE or IDLE event if necessary.
* @private
*/
goog.module.ModuleManager.prototype.dispatchActiveIdleChangeIfNeeded_ =
function() {
var lastActive = this.lastActive_;
var active = this.isActive();
if (active != lastActive) {
this.executeCallbacks_(
active ? goog.module.ModuleManager.CallbackType.ACTIVE :
goog.module.ModuleManager.CallbackType.IDLE);
// Flip the last active value.
this.lastActive_ = active;
}
// Check if the module manager is user active i.e., there are user initiated
// modules being loaded or queued up to be loaded.
var userLastActive = this.userLastActive_;
var userActive = this.isUserActive();
if (userActive != userLastActive) {
this.executeCallbacks_(
userActive ? goog.module.ModuleManager.CallbackType.USER_ACTIVE :
goog.module.ModuleManager.CallbackType.USER_IDLE);
// Flip the last user active value.
this.userLastActive_ = userActive;
}
};
/**
* Preloads a module after a short delay.
*
* @param {string} id The id of the module to preload.
* @param {number=} opt_timeout The number of ms to wait before adding the
* module id to the loading queue (defaults to 0 ms). Note that the module
* will be loaded asynchronously regardless of the value of this parameter.
* @return {!goog.async.Deferred} A deferred object.
*/
goog.module.ModuleManager.prototype.preloadModule = function(id, opt_timeout) {
var d = new goog.async.Deferred();
window.setTimeout(
goog.bind(this.addLoadModule_, this, id, d), opt_timeout || 0);
return d;
};
/**
* Prefetches a JavaScript module and its dependencies, which means that the
* module will be downloaded, but not evaluated. To complete the module load,
* the caller should also call load or execOnLoad after prefetching the module.
*
* @param {string} id The id of the module to prefetch.
*/
goog.module.ModuleManager.prototype.prefetchModule = function(id) {
var moduleInfo = this.getModuleInfo(id);
if (moduleInfo.isLoaded() || this.isModuleLoading(id)) {
throw new Error('Module load already requested: ' + id);
} else if (this.batchModeEnabled_) {
throw new Error('Modules prefetching is not supported in batch mode');
} else {
var idWithDeps = this.getNotYetLoadedTransitiveDepIds_(id);
for (var i = 0; i < idWithDeps.length; i++) {
this.loader_.prefetchModule(
idWithDeps[i], this.moduleInfoMap_[idWithDeps[i]]);
}
}
};
/**
* Loads a single module for use with a given deferred.
*
* @param {string} id The id of the module to load.
* @param {goog.async.Deferred} d A deferred object.
* @private
*/
goog.module.ModuleManager.prototype.addLoadModule_ = function(id, d) {
var moduleInfo = this.getModuleInfo(id);
if (moduleInfo.isLoaded()) {
d.callback(this.moduleContext_);
return;
}
this.registerModuleLoadCallbacks_(id, moduleInfo, false, d);
if (!this.isModuleLoading(id)) {
this.loadModulesOrEnqueue_([id]);
}
};
/**
* Loads a list of modules or, if some other module is currently being loaded,
* appends the ids to the queue of requested module ids. Registers callbacks a
* module that is currently loading and returns a fired deferred for a module
* that is already loaded.
*
* @param {Array<string>} ids The id of the module to load.
* @param {boolean=} opt_userInitiated If the load is a result of a user action.
* @return {!Object<string, !goog.async.Deferred>} A mapping from id (String)
* to deferred objects that will callback or errback when the load for that
* id is finished.
* @private
*/
goog.module.ModuleManager.prototype.loadModulesOrEnqueueIfNotLoadedOrLoading_ =
function(ids, opt_userInitiated) {
var uniqueIds = [];
goog.array.removeDuplicates(ids, uniqueIds);
var idsToLoad = [];
var deferredMap = {};
for (var i = 0; i < uniqueIds.length; i++) {
var id = uniqueIds[i];
var moduleInfo = this.getModuleInfo(id);
if (!moduleInfo) {
throw new Error('Unknown module: ' + id);
}
var d = new goog.async.Deferred();
deferredMap[id] = d;
if (moduleInfo.isLoaded()) {
d.callback(this.moduleContext_);
} else {
this.registerModuleLoadCallbacks_(id, moduleInfo, !!opt_userInitiated, d);
if (!this.isModuleLoading(id)) {
idsToLoad.push(id);
}
}
}
// If there are ids to load, load them, otherwise, they are all loading or
// loaded.
if (idsToLoad.length > 0) {
this.loadModulesOrEnqueue_(idsToLoad);
}
return deferredMap;
};
/**
* Registers the callbacks and handles logic if it is a user initiated module
* load.
*
* @param {string} id The id of the module to possibly load.
* @param {!goog.module.ModuleInfo} moduleInfo The module identifier for the
* given id.
* @param {boolean} userInitiated If the load was user initiated.
* @param {goog.async.Deferred} d A deferred object.
* @private
*/
goog.module.ModuleManager.prototype.registerModuleLoadCallbacks_ = function(
id, moduleInfo, userInitiated, d) {
moduleInfo.registerCallback(d.callback, d);
moduleInfo.registerErrback(function(err) { d.errback(Error(err)); });
// If it's already loading, we don't have to do anything besides handle
// if it was user initiated
if (this.isModuleLoading(id)) {
if (userInitiated) {
goog.log.info(
this.logger_, 'User initiated module already loading: ' + id);
this.addUserInitiatedLoadingModule_(id);
this.dispatchActiveIdleChangeIfNeeded_();
}
} else {
if (userInitiated) {
goog.log.info(this.logger_, 'User initiated module load: ' + id);
this.addUserInitiatedLoadingModule_(id);
} else {
goog.log.info(this.logger_, 'Initiating module load: ' + id);
}
}
};
/**
* Initiates loading of a list of modules or, if a module is currently being
* loaded, appends the modules to the queue of requested module ids.
*
* The caller should verify that the requested modules are not already loaded or
* loading. {@link #loadModulesOrEnqueueIfNotLoadedOrLoading_} is a more lenient
* alternative to this method.
*
* @param {Array<string>} ids The ids of the modules to load.
* @private
*/
goog.module.ModuleManager.prototype.loadModulesOrEnqueue_ = function(ids) {
// With concurrent loading we always just send off the request.
if (this.concurrentLoadingEnabled_) {
// For now we wait for initial modules to have downloaded as this puts the
// loader in a good state for calculating the needed deps of additional
// loads.
// TODO(user): Make this wait unnecessary.
this.initialModulesLoaded_.addCallback(
goog.bind(this.loadModules_, this, ids));
} else {
if (goog.array.isEmpty(this.loadingModuleIds_)) {
this.loadModules_(ids);
} else {
this.requestedModuleIdsQueue_.push(ids);
this.dispatchActiveIdleChangeIfNeeded_();
}
}
};
/**
* Gets the amount of delay to wait before sending a request for more modules.
* If a certain module request fails, we backoff a little bit and try again.
* @return {number} Delay, in ms.
* @private
*/
goog.module.ModuleManager.prototype.getBackOff_ = function() {
// 5 seconds after one error, 20 seconds after 2.
return Math.pow(this.consecutiveFailures_, 2) * 5000;
};
/**
* Loads a list of modules and any of their not-yet-loaded prerequisites.
* If batch mode is enabled, the prerequisites will be loaded together with the
* requested modules and all requested modules will be loaded at the same time.
*
* The caller should verify that the requested modules are not already loaded
* and that no modules are currently loading before calling this method.
*
* @param {Array<string>} ids The ids of the modules to load.
* @param {boolean=} opt_isRetry If the load is a retry of a previous load
* attempt.
* @param {boolean=} opt_forceReload Whether to bypass cache while loading the
* module.
* @private
*/
goog.module.ModuleManager.prototype.loadModules_ = function(
ids, opt_isRetry, opt_forceReload) {
if (!opt_isRetry) {
this.consecutiveFailures_ = 0;
}
// Not all modules may be loaded immediately if batch mode is not enabled.
var idsToLoadImmediately = this.processModulesForLoad_(ids);
goog.log.info(this.logger_, 'Loading module(s): ' + idsToLoadImmediately);
this.loadingModuleIds_ = idsToLoadImmediately;
if (this.batchModeEnabled_) {
this.requestedLoadingModuleIds_ = ids;
} else {
// If batch mode is disabled, we treat each dependency load as a separate
// load.
this.requestedLoadingModuleIds_ = goog.array.clone(idsToLoadImmediately);
}
// Dispatch an active/idle change if needed.
this.dispatchActiveIdleChangeIfNeeded_();
if (goog.array.isEmpty(idsToLoadImmediately)) {
// All requested modules and deps have been either loaded already or have
// already been requested.
return;
}
this.requestedModuleIds_.push.apply(
this.requestedModuleIds_, idsToLoadImmediately);
var loadFn = goog.bind(
this.loader_.loadModules, this.loader_,
goog.array.clone(idsToLoadImmediately), this.moduleInfoMap_, null,
goog.bind(
this.handleLoadError_, this, this.requestedLoadingModuleIds_,
idsToLoadImmediately),
goog.bind(this.handleLoadTimeout_, this), !!opt_forceReload);
var delay = this.getBackOff_();
if (delay) {
window.setTimeout(loadFn, delay);
} else {
loadFn();
}
};
/**
* Processes a list of module ids for loading. Checks if any of the modules are
* already loaded and then gets transitive deps. Queues any necessary modules
* if batch mode is not enabled. Returns the list of ids that should be loaded.
*
* @param {Array<string>} ids The ids that need to be loaded.
* @return {!Array<string>} The ids to load, including dependencies.
* @throws {Error} If the module is already loaded.
* @private
*/
goog.module.ModuleManager.prototype.processModulesForLoad_ = function(ids) {
for (var i = 0; i < ids.length; i++) {
var moduleInfo = this.moduleInfoMap_[ids[i]];
if (moduleInfo.isLoaded()) {
throw new Error('Module already loaded: ' + ids[i]);
}
}
// Build a list of the ids of this module and any of its not-yet-loaded
// prerequisite modules in dependency order.
var idsWithDeps = [];
for (var i = 0; i < ids.length; i++) {
idsWithDeps =
idsWithDeps.concat(this.getNotYetLoadedTransitiveDepIds_(ids[i]));
}
goog.array.removeDuplicates(idsWithDeps);
if (!this.batchModeEnabled_ && idsWithDeps.length > 1) {
var idToLoad = idsWithDeps.shift();
goog.log.info(
this.logger_, 'Must load ' + idToLoad + ' module before ' + ids);
// Insert the requested module id and any other not-yet-loaded prereqs
// that it has at the front of the queue.
var queuedModules =
goog.array.map(idsWithDeps, function(id) { return [id]; });
this.requestedModuleIdsQueue_ =
queuedModules.concat(this.requestedModuleIdsQueue_);
return [idToLoad];
} else {
return idsWithDeps;
}
};
/**
* Builds a list of the ids of the not-yet-loaded modules that a particular
* module transitively depends on, including itself.
*
* @param {string} id The id of a not-yet-loaded module.
* @return {!Array<string>} An array of module ids in dependency order that's
* guaranteed to end with the provided module id.
* @private
*/
goog.module.ModuleManager.prototype.getNotYetLoadedTransitiveDepIds_ = function(
id) {
// NOTE(user): We want the earliest occurrence of a module, not the first
// dependency we find. Therefore we strip duplicates at the end rather than
// during. See the tests for concrete examples.
var ids = [];
if (!goog.array.contains(this.requestedModuleIds_, id)) {
ids.push(id);
}
var depIds = goog.array.clone(this.getModuleInfo(id).getDependencies());
while (depIds.length) {
var depId = depIds.pop();
if (!this.getModuleInfo(depId).isLoaded() &&
!goog.array.contains(this.requestedModuleIds_, depId)) {
ids.unshift(depId);
// We need to process direct dependencies first.
Array.prototype.unshift.apply(
depIds, this.getModuleInfo(depId).getDependencies());
}
}
goog.array.removeDuplicates(ids);
return ids;
};
/**
* If we are still loading the base module, consider the load complete.
* @private
*/
goog.module.ModuleManager.prototype.maybeFinishBaseLoad_ = function() {
if (this.currentlyLoadingModule_ == this.baseModuleInfo_) {
this.currentlyLoadingModule_ = null;
var error =
this.baseModuleInfo_.onLoad(goog.bind(this.getModuleContext, this));
if (error) {
this.dispatchModuleLoadFailed_(
goog.module.ModuleManager.FailureType.INIT_ERROR);
}
this.dispatchActiveIdleChangeIfNeeded_();
}
};
/**
* Records that a module was loaded. Also initiates loading the next module if
* any module requests are queued. This method is called by code that is
* generated and appended to each dynamic module's code at compilation time.
*
* @param {string} id A module id.
*/
goog.module.ModuleManager.prototype.setLoaded = function(id) {
if (this.isDisposed()) {
goog.log.warning(
this.logger_, 'Module loaded after module manager was disposed: ' + id);
return;
}
goog.log.info(this.logger_, 'Module loaded: ' + id);
var error =
this.moduleInfoMap_[id].onLoad(goog.bind(this.getModuleContext, this));
if (error) {
this.dispatchModuleLoadFailed_(
goog.module.ModuleManager.FailureType.INIT_ERROR);
}
// Remove the module id from the user initiated set if it existed there.
goog.array.remove(this.userInitiatedLoadingModuleIds_, id);
// Remove the module id from the loading modules if it exists there.
goog.array.remove(this.loadingModuleIds_, id);
if (goog.array.isEmpty(this.loadingModuleIds_)) {
// No more modules are currently being loaded (e.g. arriving later in the
// same HTTP response), so proceed to load the next module in the queue.
this.loadNextModules_();
}
if (this.lastInitialModuleId_ && id == this.lastInitialModuleId_) {
if (!this.initialModulesLoaded_.hasFired()) {
this.initialModulesLoaded_.callback();
}
}
// Dispatch an active/idle change if needed.
this.dispatchActiveIdleChangeIfNeeded_();
};
/**
* Gets whether a module is currently loading or in the queue, waiting to be
* loaded.
* @param {string} id A module id.
* @return {boolean} TRUE iff the module is loading.
*/
goog.module.ModuleManager.prototype.isModuleLoading = function(id) {
if (goog.array.contains(this.loadingModuleIds_, id)) {
return true;
}
for (var i = 0; i < this.requestedModuleIdsQueue_.length; i++) {
if (goog.array.contains(this.requestedModuleIdsQueue_[i], id)) {
return true;
}
}
return false;
};
/**
* Requests that a function be called once a particular module is loaded.
* Client code can use this method to safely call into modules that may not yet
* be loaded. For consistency, this method always calls the function
* asynchronously -- even if the module is already loaded. Initiates loading of
* the module if necessary, unless opt_noLoad is true.
*
* @param {string} moduleId A module id.
* @param {Function} fn Function to execute when the module has loaded.
* @param {Object=} opt_handler Optional handler under whose scope to execute
* the callback.
* @param {boolean=} opt_noLoad TRUE iff not to initiate loading of the module.
* @param {boolean=} opt_userInitiated TRUE iff the loading of the module was
* user initiated.
* @param {boolean=} opt_preferSynchronous TRUE iff the function should be
* executed synchronously if the module has already been loaded.
* @return {!goog.module.ModuleLoadCallback} A callback wrapper that exposes
* an abort and execute method.
*/
goog.module.ModuleManager.prototype.execOnLoad = function(
moduleId, fn, opt_handler, opt_noLoad, opt_userInitiated,
opt_preferSynchronous) {
var moduleInfo = this.moduleInfoMap_[moduleId];
var callbackWrapper;
if (moduleInfo.isLoaded()) {
goog.log.info(this.logger_, moduleId + ' module already loaded');
// Call async so that code paths don't change between loaded and unloaded
// cases.
callbackWrapper = new goog.module.ModuleLoadCallback(fn, opt_handler);
if (opt_preferSynchronous) {
callbackWrapper.execute(this.moduleContext_);
} else {
window.setTimeout(goog.bind(callbackWrapper.execute, callbackWrapper), 0);
}
} else if (this.isModuleLoading(moduleId)) {
goog.log.info(this.logger_, moduleId + ' module already loading');
callbackWrapper = moduleInfo.registerCallback(fn, opt_handler);
if (opt_userInitiated) {
goog.log.info(
this.logger_, 'User initiated module already loading: ' + moduleId);
this.addUserInitiatedLoadingModule_(moduleId);
this.dispatchActiveIdleChangeIfNeeded_();
}
} else {
goog.log.info(this.logger_, 'Registering callback for module: ' + moduleId);
callbackWrapper = moduleInfo.registerCallback(fn, opt_handler);
if (!opt_noLoad) {
if (opt_userInitiated) {
goog.log.info(this.logger_, 'User initiated module load: ' + moduleId);
this.addUserInitiatedLoadingModule_(moduleId);
}
goog.log.info(this.logger_, 'Initiating module load: ' + moduleId);
this.loadModulesOrEnqueue_([moduleId]);
}
}
return callbackWrapper;
};
/**
* Loads a module, returning a goog.async.Deferred for keeping track of the
* result.
*
* @param {string} moduleId A module id.
* @param {boolean=} opt_userInitiated If the load is a result of a user action.
* @return {goog.async.Deferred} A deferred object.
*/
goog.module.ModuleManager.prototype.load = function(
moduleId, opt_userInitiated) {
return this.loadModulesOrEnqueueIfNotLoadedOrLoading_(
[moduleId], opt_userInitiated)[moduleId];
};
/**
* Loads a list of modules, returning a goog.async.Deferred for keeping track of
* the result.
*
* @param {Array<string>} moduleIds A list of module ids.
* @param {boolean=} opt_userInitiated If the load is a result of a user action.
* @return {!Object<string, !goog.async.Deferred>} A mapping from id (String)
* to deferred objects that will callback or errback when the load for that
* id is finished.
*/
goog.module.ModuleManager.prototype.loadMultiple = function(
moduleIds, opt_userInitiated) {
return this.loadModulesOrEnqueueIfNotLoadedOrLoading_(
moduleIds, opt_userInitiated);
};
/**
* Ensures that the module with the given id is listed as a user-initiated
* module that is being loaded. This method guarantees that a module will never
* get listed more than once.
* @param {string} id Identifier of the module.
* @private
*/
goog.module.ModuleManager.prototype.addUserInitiatedLoadingModule_ = function(
id) {
if (!goog.array.contains(this.userInitiatedLoadingModuleIds_, id)) {
this.userInitiatedLoadingModuleIds_.push(id);
}
};
/**
* Method called just before a module code is loaded.
* @param {string} id Identifier of the module.
*/
goog.module.ModuleManager.prototype.beforeLoadModuleCode = function(id) {
this.loadTracer_ =
goog.debug.Trace.startTracer('Module Load: ' + id, 'Module Load');
if (this.currentlyLoadingModule_) {
goog.log.error(
this.logger_, 'beforeLoadModuleCode called with module "' + id +
'" while module "' + this.currentlyLoadingModule_.getId() +
'" is loading');
}
this.currentlyLoadingModule_ = this.getModuleInfo(id);
};
/**
* Method called just after module code is loaded
* @param {string} id Identifier of the module.
*/
goog.module.ModuleManager.prototype.afterLoadModuleCode = function(id) {
if (!this.currentlyLoadingModule_ ||
id != this.currentlyLoadingModule_.getId()) {
goog.log.error(
this.logger_, 'afterLoadModuleCode called with module "' + id +
'" while loading module "' +
(this.currentlyLoadingModule_ &&
this.currentlyLoadingModule_.getId()) +
'"');
}
this.currentlyLoadingModule_ = null;
goog.debug.Trace.stopTracer(this.loadTracer_);
};
/**
* Register an initialization callback for the currently loading module. This
* should only be called by script that is executed during the evaluation of
* a module's javascript. This is almost equivalent to calling the function
* inline, but ensures that all the code from the currently loading module
* has been loaded. This makes it cleaner and more robust than calling the
* function inline.
*
* If this function is called from the base module (the one that contains
* the module manager code), the callback is held until #setAllModuleInfo
* is called, or until #setModuleContext is called, whichever happens first.
*
* @param {Function} fn A callback function that takes a single argument
* which is the module context.
* @param {Object=} opt_handler Optional handler under whose scope to execute
* the callback.
*/
goog.module.ModuleManager.prototype.registerInitializationCallback = function(
fn, opt_handler) {
if (!this.currentlyLoadingModule_) {
goog.log.error(this.logger_, 'No module is currently loading');
} else {
this.currentlyLoadingModule_.registerEarlyCallback(fn, opt_handler);
}
};
/**
* Register a late initialization callback for the currently loading module.
* Callbacks registered via this function are executed similar to
* {@see registerInitializationCallback}, but they are fired after all
* initialization callbacks are called.
*
* @param {Function} fn A callback function that takes a single argument
* which is the module context.
* @param {Object=} opt_handler Optional handler under whose scope to execute
* the callback.
*/
goog.module.ModuleManager.prototype.registerLateInitializationCallback =
function(fn, opt_handler) {
if (!this.currentlyLoadingModule_) {
goog.log.error(this.logger_, 'No module is currently loading');
} else {
this.currentlyLoadingModule_.registerCallback(fn, opt_handler);
}
};
/**
* Sets the constructor to use for the module object for the currently
* loading module. The constructor should derive from
* {@see goog.module.BaseModule}.
* @param {Function} fn The constructor function.
*/
goog.module.ModuleManager.prototype.setModuleConstructor = function(fn) {
if (!this.currentlyLoadingModule_) {
goog.log.error(this.logger_, 'No module is currently loading');
return;
}
this.currentlyLoadingModule_.setModuleConstructor(fn);
};
/**
* The possible reasons for a module load failure callback being fired.
* @enum {number}
*/
goog.module.ModuleManager.FailureType = {
/** 401 Status. */
UNAUTHORIZED: 0,
/** Error status (not 401) returned multiple times. */
CONSECUTIVE_FAILURES: 1,
/** Request timeout. */
TIMEOUT: 2,
/** 410 status, old code gone. */
OLD_CODE_GONE: 3,
/** The onLoad callbacks failed. */
INIT_ERROR: 4
};
/**
* Handles a module load failure.
*
* @param {!Array<string>} requestedLoadingModuleIds Modules ids that were
* requested in failed request. Does not included calculated dependencies.
* @param {!Array<string>} requestedModuleIdsWithDeps All module ids requested
* in the failed request including all dependencies.
* @param {?number} status The error status.
* @private
*/
goog.module.ModuleManager.prototype.handleLoadError_ = function(
requestedLoadingModuleIds, requestedModuleIdsWithDeps, status) {
this.consecutiveFailures_++;
// Module manager was not designed to be reentrant. Reinstate the instance
// var with actual value when request failed (Other requests may have
// started already.)
this.requestedLoadingModuleIds_ = requestedLoadingModuleIds;
// Pretend we never requested the failed modules.
goog.array.forEach(
requestedModuleIdsWithDeps,
goog.partial(goog.array.remove, this.requestedModuleIds_), this);
if (status == 401) {
// The user is not logged in. They've cleared their cookies or logged out
// from another window.
goog.log.info(this.logger_, 'Module loading unauthorized');
this.dispatchModuleLoadFailed_(
goog.module.ModuleManager.FailureType.UNAUTHORIZED);
// Drop any additional module requests.
this.requestedModuleIdsQueue_.length = 0;
} else if (status == 410) {
// The requested module js is old and not available.
this.requeueBatchOrDispatchFailure_(
goog.module.ModuleManager.FailureType.OLD_CODE_GONE);
this.loadNextModules_();
} else if (this.consecutiveFailures_ >= 3) {
goog.log.info(
this.logger_,
'Aborting after failure to load: ' + this.loadingModuleIds_);
this.requeueBatchOrDispatchFailure_(
goog.module.ModuleManager.FailureType.CONSECUTIVE_FAILURES);
this.loadNextModules_();
} else {
goog.log.info(
this.logger_,
'Retrying after failure to load: ' + this.loadingModuleIds_);
var forceReload =
status == goog.module.ModuleManager.CORRUPT_RESPONSE_STATUS_CODE;
this.loadModules_(this.requestedLoadingModuleIds_, true, forceReload);
}
};
/**
* Handles a module load timeout.
* @private
*/
goog.module.ModuleManager.prototype.handleLoadTimeout_ = function() {
goog.log.info(
this.logger_, 'Aborting after timeout: ' + this.loadingModuleIds_);
this.requeueBatchOrDispatchFailure_(
goog.module.ModuleManager.FailureType.TIMEOUT);
this.loadNextModules_();
};
/**
* Requeues batch loads that had more than one requested module
* (i.e. modules that were not included as dependencies) as separate loads or
* if there was only one requested module, fails that module with the received
* cause.
* @param {goog.module.ModuleManager.FailureType} cause The reason for the
* failure.
* @private
*/
goog.module.ModuleManager.prototype.requeueBatchOrDispatchFailure_ = function(
cause) {
// The load failed, so if there are more than one requested modules, then we
// need to retry each one as a separate load. Otherwise, if there is only one
// requested module, remove it and its dependencies from the queue.
if (this.requestedLoadingModuleIds_.length > 1) {
var queuedModules = goog.array.map(
this.requestedLoadingModuleIds_, function(id) { return [id]; });
this.requestedModuleIdsQueue_ =
queuedModules.concat(this.requestedModuleIdsQueue_);
} else {
this.dispatchModuleLoadFailed_(cause);
}
};
/**
* Handles when a module load failed.
* @param {goog.module.ModuleManager.FailureType} cause The reason for the
* failure.
* @private
*/
goog.module.ModuleManager.prototype.dispatchModuleLoadFailed_ = function(
cause) {
var failedIds = this.requestedLoadingModuleIds_;
this.loadingModuleIds_.length = 0;
// If any pending modules depend on the id that failed,
// they need to be removed from the queue.
var idsToCancel = [];
for (var i = 0; i < this.requestedModuleIdsQueue_.length; i++) {
var dependentModules = goog.array.filter(
this.requestedModuleIdsQueue_[i],
/**
* Returns true if the requestedId has dependencies on the modules that
* just failed to load.
* @param {string} requestedId The module to check for dependencies.
* @return {boolean} True if the module depends on failed modules.
*/
function(requestedId) {
var requestedDeps =
this.getNotYetLoadedTransitiveDepIds_(requestedId);
return goog.array.some(failedIds, function(id) {
return goog.array.contains(requestedDeps, id);
});
},
this);
goog.array.extend(idsToCancel, dependentModules);
}
// Also insert the ids that failed to load as ids to cancel.
for (var i = 0; i < failedIds.length; i++) {
goog.array.insert(idsToCancel, failedIds[i]);
}
// Remove ids to cancel from the queues.
for (var i = 0; i < idsToCancel.length; i++) {
for (var j = 0; j < this.requestedModuleIdsQueue_.length; j++) {
goog.array.remove(this.requestedModuleIdsQueue_[j], idsToCancel[i]);
}
goog.array.remove(this.userInitiatedLoadingModuleIds_, idsToCancel[i]);
}
// Call the functions for error notification.
var errorCallbacks =
this.callbackMap_[goog.module.ModuleManager.CallbackType.ERROR];
if (errorCallbacks) {
for (var i = 0; i < errorCallbacks.length; i++) {
var callback = errorCallbacks[i];
for (var j = 0; j < idsToCancel.length; j++) {
callback(
goog.module.ModuleManager.CallbackType.ERROR, idsToCancel[j],
cause);
}
}
}
// Call the errbacks on the module info.
for (var i = 0; i < failedIds.length; i++) {
if (this.moduleInfoMap_[failedIds[i]]) {
this.moduleInfoMap_[failedIds[i]].onError(cause);
}
}
// Clear the requested loading module ids.
this.requestedLoadingModuleIds_.length = 0;
this.dispatchActiveIdleChangeIfNeeded_();
};
/**
* Loads the next modules on the queue.
* @private
*/
goog.module.ModuleManager.prototype.loadNextModules_ = function() {
while (this.requestedModuleIdsQueue_.length) {
// Remove modules that are already loaded.
var nextIds = goog.array.filter(
this.requestedModuleIdsQueue_.shift(),
function(id) { return !this.getModuleInfo(id).isLoaded(); }, this);
if (nextIds.length > 0) {
this.loadModules_(nextIds);
return;
}
}
// Dispatch an active/idle change if needed.
this.dispatchActiveIdleChangeIfNeeded_();
};
/**
* The function to call if the module manager is in error.
* @param
* {goog.module.ModuleManager.CallbackType|Array<goog.module.ModuleManager.CallbackType>}
* types
* The callback type.
* @param {Function} fn The function to register as a callback.
*/
goog.module.ModuleManager.prototype.registerCallback = function(types, fn) {
if (!goog.isArray(types)) {
types = [types];
}
for (var i = 0; i < types.length; i++) {
this.registerCallback_(types[i], fn);
}
};
/**
* Register a callback for the specified callback type.
* @param {goog.module.ModuleManager.CallbackType} type The callback type.
* @param {Function} fn The callback function.
* @private
*/
goog.module.ModuleManager.prototype.registerCallback_ = function(type, fn) {
var callbackMap = this.callbackMap_;
if (!callbackMap[type]) {
callbackMap[type] = [];
}
callbackMap[type].push(fn);
};
/**
* Call the callback functions of the specified type.
* @param {goog.module.ModuleManager.CallbackType} type The callback type.
* @private
*/
goog.module.ModuleManager.prototype.executeCallbacks_ = function(type) {
var callbacks = this.callbackMap_[type];
for (var i = 0; callbacks && i < callbacks.length; i++) {
callbacks[i](type);
}
};
/** @override */
goog.module.ModuleManager.prototype.disposeInternal = function() {
goog.module.ModuleManager.base(this, 'disposeInternal');
// Dispose of each ModuleInfo object.
goog.disposeAll(
goog.object.getValues(this.moduleInfoMap_), this.baseModuleInfo_);
this.moduleInfoMap_ = null;
this.loadingModuleIds_ = null;
this.requestedLoadingModuleIds_ = null;
this.userInitiatedLoadingModuleIds_ = null;
this.requestedModuleIdsQueue_ = null;
this.callbackMap_ = null;
};
| isabela-angelo/scratch-tangible-blocks | scratch-blocks/node_modules/google-closure-library/closure/goog/module/modulemanager.js | JavaScript | bsd-3-clause | 44,420 |
var assert = require('chai').assert;
assert.isDeferred = function (object) {
if (typeof object.resolve !== 'function') {
return false;
}
return String(object.resolve) === String($.Deferred().resolve);
};
var sinon;
var withData = require('leche').withData;
var StringUtils = {
repeatString: function (value, times) {
return (new Array(times + 1)).join(value);
}
};
var jsdom = require('mocha-jsdom');
var punycode = require('../../../vendor/bower-asset/punycode/punycode');
var fs = require('fs');
var vm = require('vm');
var yii;
describe('yii.validation', function () {
var VALIDATOR_SUCCESS_MESSAGE = 'should leave messages as is';
var VALIDATOR_ERROR_MESSAGE = 'should add appropriate errors(s) to messages';
function getValidatorMessage(expectedResult) {
var isTrueBoolean = typeof expectedResult === 'boolean' && expectedResult === true;
var isEmptyArray = Array.isArray(expectedResult) && expectedResult.length === 0;
return isTrueBoolean || isEmptyArray ? VALIDATOR_SUCCESS_MESSAGE : VALIDATOR_ERROR_MESSAGE;
}
var $;
var code;
var script;
function FileReader() {
this.readAsDataURL = function() {
};
}
function Image() {
}
function registerTestableCode(customSandbox) {
if (customSandbox === undefined) {
customSandbox = {
File: {},
FileReader: FileReader,
Image: Image,
punycode: punycode
};
}
var path = 'framework/assets/yii.validation.js';
if (code === undefined) {
code = fs.readFileSync(path);
}
if (script === undefined) {
script = new vm.Script(code);
}
var defaultSandbox = {yii: {}, jQuery: $};
var sandbox = $.extend({}, defaultSandbox, customSandbox);
var context = new vm.createContext(sandbox);
script.runInContext(context);
yii = sandbox.yii;
}
jsdom({
src: fs.readFileSync('vendor/bower-asset/jquery/dist/jquery.js', 'utf-8')
});
before(function () {
$ = window.$;
registerTestableCode();
sinon = require('sinon');
});
it('should exist', function () {
assert.isObject(yii.validation);
});
describe('isEmpty method', function () {
withData({
'undefined': [undefined, true],
'null': [null, true],
'empty array': [[], true],
'empty string': ['', true],
'string containing whitespace': [' ', false],
'empty object': [{}, false],
'non-zero integer': [1, false],
'non-empty string': ['a', false],
'non-empty array': [[1], false]
}, function (value, expectedValue) {
var message = expectedValue ? 'should return "true"' : 'should return "false"';
it(message, function () {
assert.strictEqual(yii.validation.isEmpty(value), expectedValue);
});
});
});
describe('addMessage method', function () {
withData({
'empty messages': [[], 'Message', 1, ['Message']],
'non-empty messages': [['Message 1'], 'Message 2', 1, ['Message 1', 'Message 2']],
'message as template': [[], 'Message with value {value}', 1, ['Message with value 1']]
}, function (messages, message, value, expectedMessages) {
it('should extend messages and replace value in template', function () {
yii.validation.addMessage(messages, message, value);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('required validator', function () {
withData({
'empty string': ['', {}, false],
'empty string, strict mode': ['', {strict: true}, true],
'string containing whitespace': [' ', {}, false],
'string containing whitespace, strict mode': [' ', {strict: true}, true],
'non-empty string': ['a', {}, true],
'undefined': [undefined, {}, false],
'undefined, strict mode': [undefined, {strict: true}, false],
// requiredValue
'integer and required value set to different integer': [1, {requiredValue: 2}, false],
'string and required value set to integer with the same value': ['1', {requiredValue: 1}, true],
'string and required value set to integer with the same value, strict mode': [
'1',
{requiredValue: 1, strict: true},
false
],
'integer and required value set to same integer, strict mode': [
1,
{requiredValue: 1, strict: true},
true
]
}, function (value, options, expectValid) {
it(getValidatorMessage(expectValid), function () {
options.message = 'This field is required.';
var messages = [];
var expectedMessages = expectValid ? [] : ['This field is required.'];
yii.validation.required(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('boolean validator', function () {
var defaultOptions = {
message: 'The value must have a boolean type.',
trueValue: '1',
falseValue: '0'
};
withData({
'empty string': ['', {}, false],
'empty string, skip on empty': ['', {skipOnEmpty: true}, true],
'non-empty string, does not equal neither trueValue no falseValue': ['a', {}, false],
'integer, value equals falseValue': [0, {}, true],
'integer, value equals trueValue': [1, {}, true],
'string equals falseValue': ['0', {}, true],
'string equals trueValue': ['1', {}, true],
'integer, value equals falseValue, strict mode': [0, {strict: true}, false],
'integer, value equals trueValue, strict mode': [1, {strict: true}, false],
// trueValue, falseValue
'string equals custom trueValue, custom trueValue is set': ['yes', {trueValue: 'yes'}, true],
'string does not equal neither trueValue no falseValue, custom trueValue is set': [
'no',
{trueValue: 'yes'},
false
],
'string equals custom falseValue, custom falseValue is set': ['no', {falseValue: 'no'}, true],
'string does not equal neither trueValue no falseValue, custom falseValue is set': [
'yes',
{falseValue: 'no'},
false
],
'string equals custom trueValue, custom trueValue and falseValue are set': [
'yes',
{trueValue: 'yes', falseValue: 'no'},
true
],
'string equals custom falseValue, custom trueValue and falseValue are set': [
'no',
{trueValue: 'yes', falseValue: 'no'},
true
],
'string does not equal neither custom trueValue no falseValue, custom trueValue and falseValue are set': [
'a',
{trueValue: 'yes', falseValue: 'no'},
false
]
}, function (value, customOptions, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
var expectedMessages = expectValid ? [] : ['The value must have a boolean type.'];
yii.validation.boolean(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('string validator', function () {
var defaultOptions = {
message: 'Invalid type.',
tooShort: 'Too short.',
tooLong: 'Too long.',
notEqual: 'Not equal.'
};
withData({
'empty string': ['', {}, []],
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
'non-empty string': ['a', {}, []],
'integer': [1, {}, ['Invalid type.']],
// min
'string less than min': ['Word', {min: 5}, ['Too short.']],
'string more than min': ['Some string', {min: 5}, []],
'string equals min': ['Equal', {min: 5}, []],
// max
'string less than max': ['Word', {max: 5}, []],
'string more than max': ['Some string', {max: 5}, ['Too long.']],
'string equals max': ['Equal', {max: 5}, []],
// is
'string equals exact length': ['Equal', {is: 5}, []],
'string does not equal exact length': ['Does not equal', {is: 5}, ['Not equal.']],
'string does not equal exact length and less than min': ['Word', {is: 5, min: 5}, ['Not equal.']],
// min and max
'string less than min, both min and max are set': ['Word', {min: 5, max: 10}, ['Too short.']],
'string in between of min and max, both min and max are set': ['Between', {min: 5, max: 10}, []],
'string more than max, both min and max are set': ['Some string', {min: 5, max: 10}, ['Too long.']]
}, function (value, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
yii.validation.string(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('file validator', function () {
var defaultOptions = {
message: 'Unable to upload a file.',
uploadRequired: 'Upload is required.',
tooMany: 'Too many files.',
wrongExtension: 'File {file} has wrong extension.',
wrongMimeType: 'File {file} has wrong mime type.',
tooSmall: 'File {file} is too small.',
tooBig: 'File {file} is too big.'
};
var attribute = {
input: '#input-id',
$form: 'jQuery form object'
};
var files;
var filesService = {
getFiles: function () {
return files;
}
};
var $input = {
get: function (value) {
return value === 0 ? {files: filesService.getFiles()} : undefined;
}
};
var jQueryInitStub;
var inputGetSpy;
var filesServiceSpy;
beforeEach(function () {
jQueryInitStub = sinon.stub($.fn, 'init');
jQueryInitStub.withArgs(attribute.input, attribute.$form).returns($input);
inputGetSpy = sinon.spy($input, 'get');
filesServiceSpy = sinon.spy(filesService, 'getFiles');
});
afterEach(function () {
jQueryInitStub.restore();
inputGetSpy.restore();
filesServiceSpy.restore();
});
describe('with File API is not available', function () {
beforeEach(function () {
registerTestableCode({File: undefined});
});
afterEach(function () {
registerTestableCode();
});
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
yii.validation.file(attribute, messages, defaultOptions);
assert.deepEqual(messages, []);
assert.isFalse(jQueryInitStub.called);
assert.isFalse(inputGetSpy.called);
assert.isFalse(filesServiceSpy.called);
});
});
describe('with File API is available', function () {
withData({
'files are not available': [undefined, {}, ['Unable to upload a file.']],
'no files': [[], {}, ['Upload is required.']],
'no files, skip on empty': [[], {skipOnEmpty: true}, []],
// maxFiles
'number of files less than maximum': [
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{maxFiles: 2},
[]
],
'number of files equals maximum': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{maxFiles: 2},
[]
],
'number of files more than maximum': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024},
{name: 'file.bmp', type: 'image/bmp', size: 200 * 1024}
],
{maxFiles: 2},
['Too many files.']
],
// extensions
'files in extensions list': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{extensions: ['jpg', 'png']},
[]
],
'file not in extensions list': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.bmp', type: 'image/bmp', size: 150 * 1024}
],
{extensions: ['jpg', 'png']},
['File file.bmp has wrong extension.']
],
// mimeTypes
'mime type in mime types list': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{mimeTypes: ['image/jpeg', 'image/png']},
[]
],
'mime type not in mime types list': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.bmp', type: 'image/bmp', size: 150 * 1024}
],
{mimeTypes: ['image/jpeg', 'image/png']},
['File file.bmp has wrong mime type.']
],
// maxSize
'size less than maximum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{maxSize: 200 * 1024},
[]
],
'size equals maximum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 100 * 1024}
],
{maxSize: 100 * 1024},
[]
],
'size more than maximum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{maxSize: 50 * 1024},
['File file.jpg is too big.', 'File file.png is too big.']
],
// minSize
'size less than minimum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 150 * 1024}
],
{minSize: 120 * 1024},
['File file.jpg is too small.']
],
'size equals minimum size': [
[
{name: 'file.jpg', type: 'image/bmp', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 100 * 1024}
],
{maxSize: 100 * 1024},
[]
],
'size more than minimum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.bmp', type: 'image/bmp', size: 150 * 1024}
],
{minSize: 80 * 1024},
[]
],
'one file is less than minimum size, one file is more than maximum size': [
[
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024},
{name: 'file.png', type: 'image/png', size: 250 * 1024}
],
{minSize: 150 * 1024, maxSize: 200 * 1024},
['File file.jpg is too small.', 'File file.png is too big.']
]
}, function (uploadedFiles, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
files = uploadedFiles;
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
yii.validation.file(attribute, messages, options);
assert.deepEqual(messages, expectedMessages);
assert.isTrue(jQueryInitStub.calledOnce);
assert.deepEqual(jQueryInitStub.getCall(0).args, [attribute.input, attribute.$form]);
assert.isTrue(inputGetSpy.calledOnce);
assert.deepEqual(inputGetSpy.getCall(0).args, [0]);
assert.isTrue(filesServiceSpy.calledOnce);
});
});
});
});
describe('image validator', function () {
var attribute = {
input: '#input-id',
$form: 'jQuery form object'
};
var files;
var filesService = {
getFiles: function () {
return files;
}
};
var $input = {
get: function (value) {
return value === 0 ? {files: filesService.getFiles()} : undefined;
}
};
var deferred;
var jQueryInitStub;
var inputGetSpy;
var filesServiceSpy;
var validateImageStub;
var deferredStub;
beforeEach(function () {
jQueryInitStub = sinon.stub($.fn, 'init');
jQueryInitStub.withArgs(attribute.input, attribute.$form).returns($input);
inputGetSpy = sinon.spy($input, 'get');
filesServiceSpy = sinon.spy(filesService, 'getFiles');
validateImageStub = sinon.stub(yii.validation, 'validateImage');
deferred = $.Deferred();
deferredStub = sinon.stub(deferred, 'resolve');
});
afterEach(function () {
jQueryInitStub.restore();
inputGetSpy.restore();
filesServiceSpy.restore();
validateImageStub.restore();
deferredStub.restore();
});
describe('with FileReader API is not available', function () {
beforeEach(function () {
registerTestableCode({FileReader: undefined});
});
afterEach(function () {
registerTestableCode();
});
it(VALIDATOR_SUCCESS_MESSAGE, function () {
files = [
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024, width: 100, height: 100},
{name: 'file.png', type: 'image/png', size: 150 * 1024, width: 250, height: 250}
];
var messages = [];
var deferredList = [];
yii.validation.image(attribute, messages, {}, deferredList);
assert.deepEqual(messages, []);
assert.isFalse(validateImageStub.called);
assert.isFalse(deferredStub.called);
assert.deepEqual(deferredList, []);
});
});
describe('with FileReader API is available', function () {
it(VALIDATOR_ERROR_MESSAGE, function () {
files = [
{name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024, width: 100, height: 100},
{name: 'file.bmp', type: 'image/bmp', size: 150 * 1024, width: 250, height: 250}
];
var options = {
extensions: ['jpg', 'png'],
wrongExtension: 'File {file} has wrong extension.',
minWidth: 200,
underWidth: 'File {file} has small width.'
};
var messages = [];
var deferredList = [];
yii.validation.image(attribute, messages, options, deferredList);
assert.deepEqual(messages, ['File file.bmp has wrong extension.']);
assert.equal(validateImageStub.callCount, files.length);
for (var i = 0; i < validateImageStub.callCount; i++) {
assert.equal(validateImageStub.getCall(i).args.length, 6);
assert.deepEqual(validateImageStub.getCall(i).args[0], files[i]);
assert.deepEqual(validateImageStub.getCall(i).args[1], ['File file.bmp has wrong extension.']);
assert.deepEqual(validateImageStub.getCall(i).args[2], options);
assert.isDeferred(validateImageStub.getCall(i).args[3]);
assert.instanceOf(validateImageStub.getCall(i).args[4], FileReader);
assert.instanceOf(validateImageStub.getCall(i).args[5], Image);
}
assert.equal(deferredList.length, files.length);
for (i = 0; i < deferredList.length; i++) {
assert.isDeferred(deferredList[i]);
}
});
});
});
describe('validateImage method', function () {
var file = {name: 'file.jpg', type: 'image/jpeg', size: 100 * 1024};
var image = new Image();
var deferred;
var fileReader = new FileReader();
var deferredStub;
var fileReaderStub;
beforeEach(function () {
deferred = $.Deferred();
deferredStub = sinon.stub(deferred, 'resolve');
});
afterEach(function () {
deferredStub.restore();
fileReaderStub.restore();
});
function verifyStubs() {
assert.isTrue(fileReaderStub.calledOnce);
assert.isTrue(deferredStub.calledOnce);
}
describe('with error while reading data', function () {
beforeEach(function () {
fileReaderStub = sinon.stub(fileReader, 'readAsDataURL', function () {
this.onerror();
});
});
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
yii.validation.validateImage(file, messages, {}, deferred, fileReader, image);
assert.deepEqual(messages, []);
verifyStubs();
});
});
describe('with error while reading image', function () {
beforeEach(function () {
fileReaderStub = sinon.stub(fileReader, 'readAsDataURL', function () {
this.onload = function () {
image.onerror();
};
this.onload();
});
});
it(VALIDATOR_ERROR_MESSAGE, function () {
var messages = [];
var options = {notImage: 'File {file} is not an image.'};
yii.validation.validateImage(file, messages, options, deferred, fileReader, image);
assert.deepEqual(messages, ['File file.jpg is not an image.']);
verifyStubs();
});
});
describe('with successfully read image', function () {
var defaultOptions = {
underWidth: 'File {file} has small width.',
overWidth: 'File {file} has big width.',
underHeight: 'File {file} has small height.',
overHeight: 'File {file} has big height.'
};
beforeEach(function () {
fileReaderStub = sinon.stub(fileReader, 'readAsDataURL', function () {
this.onload = function () {
image.onload();
};
this.onload();
});
});
withData({
// minWidth
'width less than minimum width': [
{width: 100, height: 100},
{minWidth: 200},
['File file.jpg has small width.']
],
'width equals minimum width': [{width: 100, height: 100}, {minWidth: 100}, []],
'width more than minimum width': [{width: 200, height: 200}, {minWidth: 100}, []],
// maxWidth
'width less than maximum width': [{width: 100, height: 100}, {maxWidth: 200}, []],
'width equals maximum width': [{width: 100, height: 100}, {maxWidth: 100}, []],
'width more than maximum width': [
{width: 200, height: 200},
{maxWidth: 100},
['File file.jpg has big width.']
],
// minHeight
'height less than minimum height': [
{width: 100, height: 100},
{minHeight: 200},
['File file.jpg has small height.']
],
'height equals minimum height': [{width: 100, height: 100}, {minHeight: 100}, []],
'height more than minimum height': [{width: 200, height: 200}, {minHeight: 100}, []],
// maxHeight
'height less than maximum height': [{width: 100, height: 100}, {maxHeight: 200}, []],
'height equals maximum height': [{width: 100, height: 100}, {maxHeight: 100}, []],
'height more than maximum height': [
{width: 200, height: 200},
{maxHeight: 100},
['File file.jpg has big height.']
],
// minWidth and minHeight
'width less than minimum width and height less than minimum height': [
{width: 100, height: 100},
{minWidth: 200, minHeight: 200},
['File file.jpg has small width.', 'File file.jpg has small height.']
]
}, function (imageSize, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
image.width = imageSize.width;
image.height = imageSize.height;
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
yii.validation.validateImage(file, messages, options, deferred, fileReader, image);
assert.deepEqual(messages, expectedMessages);
verifyStubs();
});
});
});
});
describe('number validator', function () {
var integerPattern = /^\s*[+-]?\d+\s*$/;
var numberPattern = /^\s*[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?\s*$/;
var defaultOptions = {
message: 'Not a number.',
tooSmall: 'Number is too small.',
tooBig: 'Number is too big.'
};
describe('with integer pattern', function () {
withData({
'empty string': ['', false],
'non-empty string': ['a', false],
'zero': ['0', true],
'positive integer, no sign': ['2', true],
'positive integer with sign': ['+2', true],
'negative integer': ['-2', true],
'decimal fraction with dot': ['2.5', false],
'decimal fraction with comma': ['2,5', false]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, {pattern: integerPattern});
var messages = [];
var expectedMessages = expectValid ? [] : ['Not a number.'];
yii.validation.number(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with number pattern', function () {
withData({
'empty string': ['', false],
'non-empty string': ['a', false],
'zero': ['0', true],
'positive integer, no sign': ['2', true],
'positive integer with sign': ['+2', true],
'negative integer': ['-2', true],
'decimal fraction with dot, no sign': ['2.5', true],
'positive decimal fraction with dot and sign': ['+2.5', true],
'negative decimal fraction with dot': ['-2.5', true],
'decimal fraction with comma': ['2,5', false],
'floating number with exponential part': ['-1.23e-10', true]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, {pattern: numberPattern});
var messages = [];
var expectedMessages = expectValid ? [] : ['Not a number.'];
yii.validation.number(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with different options, integer pattern', function () {
withData({
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
// Not a string
'undefined': [undefined, {}, []],
'integer, fits pattern': [2, {}, []],
'integer, does not fit pattern': [2.5, {}, []],
// min
'less than minimum': ['1', {min: 2}, ['Number is too small.']],
'equals minimum': ['2', {min: 2}, []],
'more than minimum': ['3', {min: 2}, []],
'wrong integer and less than min': ['1.5', {min: 2}, ['Not a number.']],
// max
'less than maximum': ['1', {max: 2}, []],
'equals maximum': ['2', {max: 2}, []],
'more than maximum': ['3', {max: 2}, ['Number is too big.']]
}, function (value, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
customOptions.pattern = integerPattern;
var options = $.extend({}, defaultOptions, customOptions);
var messages = [];
yii.validation.number(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
});
describe('range validator', function () {
withData({
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
'array and arrays are not allowed': [['a', 'b'], {}, ['Invalid value.']],
'string in array': ['a', {range: ['a', 'b', 'c']}, []],
'string not in array': ['d', {range: ['a', 'b', 'c']}, ['Invalid value.']],
'array in array': [['a', 'b'], {range: ['a', 'b', 'c'], allowArray: true}, []],
'array not in array': [['a', 'd'], {range: ['a', 'b', 'c'], allowArray: true}, ['Invalid value.']],
'string in array and inverted logic': ['a', {range: ['a', 'b', 'c'], not: true}, ['Invalid value.']],
'string not in array and inverted logic': ['d', {range: ['a', 'b', 'c'], not: true}, []],
'array in array and inverted logic': [
['a', 'b'],
{range: ['a', 'b', 'c'], allowArray: true, not: true},
['Invalid value.']
],
'array not in array and inverted logic': [
['a', 'd'],
{range: ['a', 'b', 'c'], allowArray: true, not: true},
[]
]
}, function (value, options, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
options.message = 'Invalid value.';
var messages = [];
yii.validation.range(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('regular expression validator', function () {
var integerPattern = /^\s*[+-]?\d+\s*$/;
describe('with integer pattern', function () {
withData({
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
'regular integer': ['2', {}, []],
'non-integer': ['2.5', {}, ['Invalid value.']],
'regular integer, inverted logic': ['2', {not: true}, ['Invalid value.']],
'integer pattern, non-integer, inverted logic': ['2.5', {pattern: integerPattern, not: true}, []]
}, function (value, options, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
options.message = 'Invalid value.';
options.pattern = integerPattern;
var messages = [];
yii.validation.regularExpression(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
});
describe('email validator', function () {
var pattern = "^[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9]" +
"(?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$";
pattern = new RegExp(pattern);
var fullPattern = "^[^@]*<[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@" +
"(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$";
fullPattern = new RegExp(fullPattern);
var defaultOptions = {
pattern: pattern,
fullPattern: fullPattern,
message: 'Invalid value.'
};
describe('with empty string, skip on empty', function () {
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
var options = $.extend({}, defaultOptions, {skipOnEmpty: true});
yii.validation.email('', messages, options);
assert.deepEqual(messages, []);
});
});
describe('with basic configuration', function () {
withData({
'letters only': ['sam@rmcreative.ru', true],
'numbers in local-part': ['5011@gmail.com', true],
'uppercase and lowercase letters, dot and numbers in local-part': ['Abc.123@example.com', true],
'user mailbox': ['user+mailbox/department=shipping@example.com', true],
'special symbols in local-part': ['!#$%&\'*+-/=?^_`.{|}~@example.com', true],
'domain only': ['rmcreative.ru', false],
'double dot': ['ex..ample@example.com', false],
'unicode in domain': ['example@äüößìà.de', false],
'unicode (russian characters) in domain': ['sam@рмкреатиф.ru', false],
'ASCII in domain': ['example@xn--zcack7ayc9a.de', true],
'angle brackets, name': ['Carsten Brandt <mail@cebe.cc>', false],
'angle brackets, quoted name': ['"Carsten Brandt" <mail@cebe.cc>', false],
'angle brackets, no name': ['<mail@cebe.cc>', false],
'angle brackets, name, dot in local-part': ['John Smith <john.smith@example.com>', false],
'angle brackets, name, domain only': ['John Smith <example.com>', false],
'no angle brackets, name': ['Information info@oertliches.de', false],
'no angle brackets, name, unicode in domain': ['Information info@örtliches.de', false],
'angle brackets, long quoted name': [
'"' + StringUtils.repeatString('a', 300) + '" <shortmail@example.com>',
false
],
'angle brackets, name, local part more than 64 characters': [
'Short Name <' + StringUtils.repeatString('a', 65) + '@example.com>',
false
],
'angle brackets, name, domain more than 254 characters': [
'Short Name <' + StringUtils.repeatString('a', 255) + '.com>',
false
],
'angle brackets, name, unicode in domain': ['Information <info@örtliches.de>', false],
'angle brackets, name, unicode, local-part length is close to 64 characters': [
// 21 * 3 = 63
'Короткое имя <' + StringUtils.repeatString('бла', 21) + '@пример.com>',
false
],
'angle brackets, name, unicode, domain length is close to 254 characters': [
// 83 * 3 + 4 = 253
'Короткое имя <тест@' + StringUtils.repeatString('бла', 83) + '.com>',
false
]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.email(value, messages, defaultOptions);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with allowed name', function () {
withData({
'letters only': ['sam@rmcreative.ru', true],
'numbers in local-part': ['5011@gmail.com', true],
'uppercase and lowercase letters, dot and numbers in local-part': ['Abc.123@example.com', true],
'user mailbox': ['user+mailbox/department=shipping@example.com', true],
'special symbols in local-part': ['!#$%&\'*+-/=?^_`.{|}~@example.com', true],
'domain only': ['rmcreative.ru', false],
'unicode in domain': ['example@äüößìà.de', false],
'unicode (russian characters) in domain': ['sam@рмкреатиф.ru', false],
'ASCII in domain': ['example@xn--zcack7ayc9a.de', true],
'angle brackets, name': ['Carsten Brandt <mail@cebe.cc>', true],
'angle brackets, quoted name': ['"Carsten Brandt" <mail@cebe.cc>', true],
'angle brackets, no name': ['<mail@cebe.cc>', true],
'angle brackets, name, dot in local-part': ['John Smith <john.smith@example.com>', true],
'angle brackets, name, domain only': ['John Smith <example.com>', false],
'no angle brackets, name': ['Information info@oertliches.de', false],
'no angle brackets, name, unicode in domain': ['Information info@örtliches.de', false],
'angle brackets, long quoted name': [
'"' + StringUtils.repeatString('a', 300) + '" <shortmail@example.com>',
true
],
'angle brackets, name, local part more than 64 characters': [
'Short Name <' + StringUtils.repeatString('a', 65) + '@example.com>',
false
],
'angle brackets, name, domain more than 254 characters': [
'Short Name <' + StringUtils.repeatString('a', 255) + '.com>',
false
],
'angle brackets, name, unicode in domain': ['Information <info@örtliches.de>', false],
'angle brackets, name, unicode, local-part length is close to 64 characters': [
// 21 * 3 = 63
'Короткое имя <' + StringUtils.repeatString('бла', 21) + '@пример.com>',
false
],
'angle brackets, name, unicode, domain length is close to 254 characters': [
// 83 * 3 + 4 = 253
'Короткое имя <тест@' + StringUtils.repeatString('бла', 83) + '.com>',
false
]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, {allowName: true});
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.email(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with enabled IDN', function () {
withData({
'letters only': ['sam@rmcreative.ru', true],
'numbers in local-part': ['5011@gmail.com', true],
'uppercase and lowercase letters, dot and numbers in local-part': ['Abc.123@example.com', true],
'user mailbox': ['user+mailbox/department=shipping@example.com', true],
'special symbols in local-part': ['!#$%&\'*+-/=?^_`.{|}~@example.com', true],
'domain only': ['rmcreative.ru', false],
'unicode in domain': ['example@äüößìà.de', true],
'unicode (russian characters) in domain': ['sam@рмкреатиф.ru', true],
'ASCII in domain': ['example@xn--zcack7ayc9a.de', true],
'angle brackets, name': ['Carsten Brandt <mail@cebe.cc>', false],
'angle brackets, quoted name': ['"Carsten Brandt" <mail@cebe.cc>', false],
'angle brackets, no name': ['<mail@cebe.cc>', false],
'angle brackets, name, dot in local-part': ['John Smith <john.smith@example.com>', false],
'angle brackets, name, domain only': ['John Smith <example.com>', false],
'no angle brackets, name': ['Information info@oertliches.de', false],
'no angle brackets, name, unicode in domain': ['Information info@örtliches.de', false],
'angle brackets, long quoted name': [
'"' + StringUtils.repeatString('a', 300) + '" <shortmail@example.com>',
false
],
'angle brackets, name, local part more than 64 characters': [
'Short Name <' + StringUtils.repeatString('a', 65) + '@example.com>',
false
],
'angle brackets, name, domain more than 254 characters': [
'Short Name <' + StringUtils.repeatString('a', 255) + '.com>',
false
],
'angle brackets, name, unicode in domain': ['Information <info@örtliches.de>', false],
'angle brackets, name, unicode, local-part length is close to 64 characters': [
// 21 * 3 = 63
'Короткое имя <' + StringUtils.repeatString('бла', 21) + '@пример.com>',
false
],
'angle brackets, name, unicode, domain length is close to 254 characters': [
// 83 * 3 + 4 = 253
'Короткое имя <тест@' + StringUtils.repeatString('бла', 83) + '.com>',
false
]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, {enableIDN: true});
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.email(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with allowed name and enabled IDN', function () {
withData({
'letters only': ['sam@rmcreative.ru', true],
'numbers in local-part': ['5011@gmail.com', true],
'uppercase and lowercase letters, dot and numbers in local-part': ['Abc.123@example.com', true],
'user mailbox': ['user+mailbox/department=shipping@example.com', true],
'special symbols in local-part': ['!#$%&\'*+-/=?^_`.{|}~@example.com', true],
'domain only': ['rmcreative.ru', false],
'unicode in domain': ['example@äüößìà.de', true],
'unicode (russian characters) in domain': ['sam@рмкреатиф.ru', true],
'ASCII in domain': ['example@xn--zcack7ayc9a.de', true],
'angle brackets, name': ['Carsten Brandt <mail@cebe.cc>', true],
'angle brackets, quoted name': ['"Carsten Brandt" <mail@cebe.cc>', true],
'angle brackets, no name': ['<mail@cebe.cc>', true],
'angle brackets, name, dot in local-part': ['John Smith <john.smith@example.com>', true],
'angle brackets, name, domain only': ['John Smith <example.com>', false],
'no angle brackets, name': ['Information info@oertliches.de', false],
'no angle brackets, name, unicode in domain': ['Information info@örtliches.de', false],
'angle brackets, long quoted name': [
'"' + StringUtils.repeatString('a', 300) + '" <shortmail@example.com>',
true
],
'angle brackets, name, local part more than 64 characters': [
'Short Name <' + StringUtils.repeatString('a', 65) + '@example.com>',
false
],
'angle brackets, name, domain more than 254 characters': [
'Short Name <' + StringUtils.repeatString('a', 255) + '.com>',
false
],
'angle brackets, name, unicode in domain': ['Information <info@örtliches.de>', true],
'angle brackets, name, unicode, local-part length is close to 64 characters': [
// 21 * 3 = 63
'Короткое имя <' + StringUtils.repeatString('бла', 21) + '@пример.com>',
false
],
'angle brackets, name, unicode, domain length is close to 254 characters': [
// 83 * 3 + 4 = 253
'Короткое имя <тест@' + StringUtils.repeatString('бла', 83) + '.com>',
false
]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var options = $.extend({}, defaultOptions, {allowName: true, enableIDN: true});
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.email(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
});
describe('url validator', function () {
function getPattern(validSchemes) {
if (validSchemes === undefined) {
validSchemes = ['http', 'https'];
}
var pattern = '^{schemes}://(([A-Z0-9][A-Z0-9_-]*)(\\.[A-Z0-9][A-Z0-9_-]*)+)(?::\\d{1,5})?(?:$|[?\\/#])';
pattern = pattern.replace('{schemes}', '(' + validSchemes.join('|') + ')');
return new RegExp(pattern, 'i');
}
var defaultOptions = {
pattern: getPattern(),
message: 'Invalid value.'
};
describe('with empty string, skip on empty', function () {
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
var options = $.extend({}, defaultOptions, {skipOnEmpty: true});
yii.validation.url('', messages, options);
assert.deepEqual(messages, []);
});
});
describe('with basic configuration', function () {
withData({
'domain only': ['google.de', false],
'http': ['http://google.de', true],
'https': ['https://google.de', true],
'scheme with typo': ['htp://yiiframework.com', false],
'https, action with get parameters': [
'https://www.google.de/search?q=yii+framework&ie=utf-8&oe=utf-8&rls=org.mozilla:de:official' +
'&client=firefox-a&gws_rd=cr',
true
],
'scheme not in valid schemes': ['ftp://ftp.ruhr-uni-bochum.de/', false],
'invalid domain': ['http://invalid,domain', false],
'not allowed symbol (comma) after domain': ['http://example.com,', false],
'not allowed symbol (star) after domain': ['http://example.com*12', false],
'symbols after slash': ['http://example.com/*12', true],
'get parameter without value': ['http://example.com/?test', true],
'anchor': ['http://example.com/#test', true],
'port, anchor': ['http://example.com:80/#test', true],
'port (length equals limit), anchor': ['http://example.com:65535/#test', true],
'port, get parameter without value': ['http://example.com:81/?good', true],
'get parameter without value and slash': ['http://example.com?test', true],
'anchor without slash': ['http://example.com#test', true],
'port and anchor without slash': ['http://example.com:81#test', true],
'port and get parameter without value and slash': ['http://example.com:81?good', true],
'not allowed symbol after domain followed by get parameter without value': [
'http://example.com,?test',
false
],
'skipped port and get parameter without value': ['http://example.com:?test', false],
'skipped port and action': ['http://example.com:test', false],
'port (length more than limit) and action': ['http://example.com:123456/test', false],
'unicode, special symbols': ['http://äüö?=!"§$%&/()=}][{³²€.edu', false]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.url(value, messages, defaultOptions);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with default scheme', function () {
withData({
'no scheme': ['yiiframework.com', true],
'http': ['http://yiiframework.com', true]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
var options = $.extend({}, defaultOptions, {defaultScheme: 'https'});
yii.validation.url(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('without scheme', function () {
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
var options = $.extend({}, defaultOptions, {
pattern: /(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)/i
});
yii.validation.url('yiiframework.com', messages, options);
assert.deepEqual(messages, []);
});
});
describe('with default scheme and custom schemes', function () {
withData({
'ftp': ['ftp://ftp.ruhr-uni-bochum.de/', true],
'no scheme': ['google.de', true],
'http': ['http://google.de', true],
'https': ['https://google.de', true],
'scheme with typo': ['htp://yiiframework.com', false],
'relative url': ['//yiiframework.com', false]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
var options = $.extend({}, defaultOptions, {
pattern: getPattern(['http', 'https', 'ftp', 'ftps']),
defaultScheme: 'http'
});
yii.validation.url(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
describe('with enabled IDN', function () {
withData({
'unicode in domain': ['http://äüößìà.de', true],
// converted via http://mct.verisign-grs.com/convertServlet
'ASCII in domain': ['http://xn--zcack7ayc9a.de', true]
}, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
var options = $.extend({}, defaultOptions, {enableIDN: true});
yii.validation.url(value, messages, options);
assert.deepEqual(messages, expectedMessages);
});
});
});
});
describe('trim filter', function () {
var attribute = {input: '#input-id'};
var getInputVal;
var $input = {
val: function () {
return getInputVal();
},
is: function () {
return false;
}
};
var $form = {
find: function () {
return $input;
}
};
var formSpy;
var inputSpy;
beforeEach(function () {
formSpy = sinon.spy($form, 'find');
inputSpy = sinon.spy($input, 'val');
});
afterEach(function () {
formSpy.restore();
inputSpy.restore();
});
describe('with empty string, skip on empty', function () {
it('should leave value and element value as is and return not changed value', function () {
getInputVal = function () {
return '';
};
assert.strictEqual(yii.validation.trim($form, attribute, {skipOnEmpty: true}), '');
assert.isTrue(formSpy.calledOnce);
assert.equal(formSpy.getCall(0).args[0], attribute.input);
assert.isTrue(inputSpy.calledOnce);
assert.strictEqual(inputSpy.getCall(0).args[0], undefined);
});
});
withData({
'nothing to trim': ['value', 'value'],
'spaces at the beginning and end': [' value ', 'value'],
'newlines at the beginning and end': ['\nvalue\n', 'value'],
'spaces and newlines at the beginning and end': ['\n value \n', 'value']
}, function (value, expectedValue) {
it('should return trimmed value and set it as value of element', function () {
getInputVal = function (val) {
return val === undefined ? value : undefined;
};
assert.equal(yii.validation.trim($form, attribute, {}), expectedValue);
assert.isTrue(formSpy.calledOnce);
assert.equal(formSpy.getCall(0).args[0], attribute.input);
assert.equal(inputSpy.callCount, 2);
assert.strictEqual(inputSpy.getCall(0).args[0], undefined);
assert.equal(inputSpy.getCall(1).args[0], expectedValue);
});
});
});
describe('trim filter on checkbox', function () {
var attribute = {input: '#input-id'};
var getInputVal;
var $checkbox = {
is: function (selector) {
if (selector === ':checked') {
return true;
}
if (selector === ':checkbox, :radio') {
return true;
}
}
};
var $form = {
find: function () {
return $checkbox;
}
};
it('should be left as is', function () {
assert.strictEqual(yii.validation.trim($form, attribute, {}, true), true);
});
});
describe('captcha validator', function () {
// Converted using yii\captcha\CaptchaAction generateValidationHash() method
var hashes = {'Code': 1497, 'code': 1529};
var caseInSensitiveData = {
'valid code in lowercase': ['code', true],
'valid code in uppercase': ['CODE', true],
'valid code as is': ['Code', true],
'invalid code': ['invalid code', false]
};
var caseSensitiveData = {
'valid code in lowercase': ['code', false],
'valid code in uppercase': ['CODE', false],
'valid code as is': ['Code', true],
'invalid code': ['invalid code', false]
};
var defaultOptions = {
message: 'Invalid value.',
hashKey: 'hashKey'
};
var hashesData = [hashes['Code'], hashes['code']];
var jQueryDataStub;
beforeEach(function () {
jQueryDataStub = sinon.stub($.prototype, 'data', function () {
return hashesData;
});
});
afterEach(function () {
jQueryDataStub.restore();
});
function verifyJQueryDataStub() {
assert.isTrue(jQueryDataStub.calledOnce);
assert.equal(jQueryDataStub.getCall(0).args[0], defaultOptions.hashKey);
}
describe('with empty string, skip on empty', function () {
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var messages = [];
var options = $.extend({}, defaultOptions, {skipOnEmpty: true});
yii.validation.captcha('', messages, options);
assert.deepEqual(messages, []);
assert.isFalse(jQueryDataStub.called);
});
});
describe('with ajax, case insensitive', function () {
withData(caseInSensitiveData, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.captcha(value, messages, defaultOptions);
assert.deepEqual(messages, expectedMessages);
verifyJQueryDataStub();
});
});
});
describe('with ajax, case sensitive', function () {
withData(caseSensitiveData, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
var options = $.extend({}, defaultOptions, {caseSensitive: true});
yii.validation.captcha(value, messages, options);
assert.deepEqual(messages, expectedMessages);
verifyJQueryDataStub();
});
});
});
describe('with hash, case insensitive', function () {
withData(caseInSensitiveData, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
hashesData = undefined;
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
var options = $.extend({}, defaultOptions, {hash: hashes['code']});
yii.validation.captcha(value, messages, options);
assert.deepEqual(messages, expectedMessages);
verifyJQueryDataStub();
});
});
});
describe('with hash, case sensitive', function () {
withData(caseSensitiveData, function (value, expectValid) {
it(getValidatorMessage(expectValid), function () {
hashesData = undefined;
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
var options = $.extend({}, defaultOptions, {hash: hashes['Code'], caseSensitive: true});
yii.validation.captcha(value, messages, options);
assert.deepEqual(messages, expectedMessages);
verifyJQueryDataStub();
});
});
});
});
describe('compare validator', function () {
var $input = {
val: function () {
return 'b';
}
};
var jQueryInitStub;
var inputSpy;
beforeEach(function () {
jQueryInitStub = sinon.stub($.fn, 'init', function () {
return $input;
});
inputSpy = sinon.spy($input, 'val');
});
afterEach(function () {
jQueryInitStub.restore();
inputSpy.restore();
});
withData({
'empty string, skip on empty': ['', {skipOnEmpty: true}, true],
// ==
'"==" operator, 2 identical integers': [2, {operator: '==', compareValue: 2}, true],
'"==" operator, 2 different integers': [2, {operator: '==', compareValue: 3}, false],
'"==" operator, 2 identical decimal fractions': [2.5, {operator: '==', compareValue: 2.5}, true],
'"==" operator, integer and string with the same values': [2, {operator: '==', compareValue: '2'}, true],
'"==" operator, integer and string with the different values': [
2,
{operator: '==', compareValue: '3'},
false
],
'"==" operator, 2 identical strings': ['b', {operator: '==', compareValue: 'b'}, true],
// ===
'"===" operator, 2 identical integers': [2, {operator: '===', compareValue: 2}, true],
'"===" operator, 2 different integers': [2, {operator: '===', compareValue: 3}, false],
'"===" operator, 2 identical decimal fractions': [2.5, {operator: '===', compareValue: 2.5}, true],
'"===" operator, integer and string with the same value': [2, {operator: '===', compareValue: '2'}, false],
'"===" operator, integer and string with the different values': [
2,
{operator: '===', compareValue: '3'},
false
],
'"===" operator, 2 identical strings': ['b', {operator: '===', compareValue: 'b'}, true],
// !=
'"!=" operator, 2 identical integers': [2, {operator: '!=', compareValue: 2}, false],
'"!=" operator, 2 different integers': [2, {operator: '!=', compareValue: 3}, true],
'"!=" operator, 2 identical decimal fractions': [2.5, {operator: '!=', compareValue: 2.5}, false],
'"!=" operator, integer and string with the same value': [2, {operator: '!=', compareValue: '2'}, false],
'"!=" operator, integer and string with the different values': [
2,
{operator: '!=', compareValue: '3'},
true
],
'"!=" operator, 2 identical strings': ['b', {operator: '!=', compareValue: 'b'}, false],
// !==
'"!==" operator, 2 identical integers': [2, {operator: '!==', compareValue: 2}, false],
'"!==" operator, 2 different integers': [2, {operator: '!==', compareValue: 3}, true],
'"!==" operator, 2 identical decimal fractions': [2.5, {operator: '!==', compareValue: 2.5}, false],
'"!==" operator, integer and string with the same value': [2, {operator: '!==', compareValue: '2'}, true],
'"!==" operator, integer and string with the different values': [
2,
{operator: '!==', compareValue: '3'},
true
],
'"!==" operator, 2 identical strings': ['b', {operator: '!==', compareValue: 'b'}, false],
// >
'">" operator, 2 identical integers': [2, {operator: '>', compareValue: 2}, false],
'">" operator, 2 integers, 2nd is greater': [2, {operator: '>', compareValue: 3}, false],
'">" operator, 2 integers, 2nd is lower': [2, {operator: '>', compareValue: 1}, true],
'">" operator, 2 identical strings': ['b', {operator: '>', compareValue: 'b'}, false],
'">" operator, 2 strings, 2nd is greater': ['a', {operator: '>', compareValue: 'b'}, false],
'">" operator, 2 strings, 2nd is lower': ['b', {operator: '>', compareValue: 'a'}, true],
// >=
'">=" operator, 2 identical integers': [2, {operator: '>=', compareValue: 2}, true],
'">=" operator, 2 integers, 2nd is greater': [2, {operator: '>=', compareValue: 3}, false],
'">=" operator, 2 integers, 2nd is lower': [2, {operator: '>=', compareValue: 1}, true],
'">=" operator, 2 identical strings': ['b', {operator: '>=', compareValue: 'b'}, true],
'">=" operator, 2 strings, 2nd is greater': ['a', {operator: '>=', compareValue: 'b'}, false],
'">=" operator, 2 strings, 2nd is lower': ['b', {operator: '>=', compareValue: 'a'}, true],
// <
'"<" operator, 2 identical integers': [2, {operator: '<', compareValue: 2}, false],
'"<" operator, 2 integers, 2nd is greater': [2, {operator: '<', compareValue: 3}, true],
'"<" operator, 2 integers, 2nd is lower': [2, {operator: '<', compareValue: 1}, false],
'"<" operator, 2 identical strings': ['b', {operator: '<', compareValue: 'b'}, false],
'"<" operator, 2 strings, 2nd is greater': ['a', {operator: '<', compareValue: 'b'}, true],
'"<" operator, 2 strings, 2nd is lower': ['b', {operator: '<', compareValue: 'a'}, false],
'"<" operator, strings "10" and "2"': ['10', {operator: '<', compareValue: '2'}, true],
// <=
'"<=" operator, 2 identical integers': [2, {operator: '<=', compareValue: 2}, true],
'"<=" operator, 2 integers, 2nd is greater': [2, {operator: '<=', compareValue: 3}, true],
'"<=" operator, 2 integers, 2nd is lower': [2, {operator: '<=', compareValue: 1}, false],
'"<=" operator, 2 identical strings': ['b', {operator: '<=', compareValue: 'b'}, true],
'"<=" operator, 2 strings, 2nd is greater': ['a', {operator: '<=', compareValue: 'b'}, true],
'"<=" operator, 2 strings, 2nd is lower': ['b', {operator: '<=', compareValue: 'a'}, false],
// type
'number type, "<" operator, strings "10" and "2"': [
'10',
{operator: '<', compareValue: '2', type: 'number'},
false
],
'number type, ">=" operator, 2nd is lower': [
10,
{operator: '>=', compareValue: 2, type: 'number'},
true
],
'number type, "<=" operator, 2nd is lower': [
10,
{operator: '<=', compareValue: 2, type: 'number'},
false
],
'number type, ">" operator, 2nd is lower': [
10,
{operator: '>', compareValue: 2, type: 'number'},
true
],
'number type, ">" operator, compare value undefined': [
undefined,
{operator: '>', compareValue: 2, type: 'number'},
false
],
'number type, "<" operator, compare value undefined': [
undefined,
{operator: '<', compareValue: 2, type: 'number'},
true
],
'number type, ">=" operator, compare value undefined': [
undefined,
{operator: '>=', compareValue: 2, type: 'number'},
false
],
'number type, "<=" operator, compare value undefined': [
undefined,
{operator: '<=', compareValue: 2, type: 'number'},
true
],
// default compare value
'default compare value, "===" operator, against undefined': [undefined, {operator: '==='}, true]
}, function (value, options, expectValid) {
it(getValidatorMessage(expectValid), function () {
options.message = 'Invalid value.';
var messages = [];
var expectedMessages = expectValid ? [] : ['Invalid value.'];
yii.validation.compare(value, messages, options);
assert.deepEqual(messages, expectedMessages);
assert.isFalse(jQueryInitStub.called);
assert.isFalse(inputSpy.called);
})
});
describe('with compareAttribute, "==" operator and 2 identical strings', function () {
it(VALIDATOR_SUCCESS_MESSAGE, function () {
var $form = {
find: function(){
return $input;
}
};
var messages = [];
yii.validation.compare('b', messages, {operator: '==', compareAttribute: 'input-id'}, $form);
assert.deepEqual(messages, []);
assert.isTrue(jQueryInitStub.calledOnce);
assert.equal(jQueryInitStub.getCall(0).args[0], '#input-id');
assert.isTrue(inputSpy.calledOnce);
assert.strictEqual(inputSpy.getCall(0).args[0], undefined);
});
});
});
describe('ip validator', function () {
var ipParsePattern = '^(\\!?)(.+?)(\/(\\d+))?$';
var ipv4Pattern = '^(?:(?:2(?:[0-4][0-9]|5[0-5])|[0-1]?[0-9]?[0-9])\\.){3}(?:(?:2([0-4][0-9]|5[0-5])|[0-1]?' +
'[0-9]?[0-9]))$';
var ipv6Pattern = '^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:)' +
'{1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}' +
'(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}' +
'(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|' +
'fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}' +
'[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|' +
'(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$';
var defaultOptions = {
messages: {
message: 'Invalid value.',
noSubnet: 'No subnet.',
hasSubnet: 'Has subnet.',
ipv4NotAllowed: 'IPv4 is not allowed.',
ipv6NotAllowed: 'IPv6 is not allowed.'
},
'ipParsePattern': ipParsePattern,
'ipv4Pattern': ipv4Pattern,
'ipv6Pattern': ipv6Pattern,
ipv4: true,
ipv6: true
};
withData({
'empty string, skip on empty': ['', {skipOnEmpty: true}, []],
'not IP': ['not IP', {}, ['Invalid value.']],
'not IP, IPv4 is disabled': ['not:IP', {ipv4: false}, ['Invalid value.']],
'not IP, IPv6 is disabled': ['not IP', {ipv6: false}, ['Invalid value.']],
// subnet, IPv4
'IPv4, subnet option is not defined': ['192.168.10.0', {}, []],
'IPv4, subnet option is set to "false"': ['192.168.10.0', {subnet: false}, []],
'IPv4, subnet option is set to "true"': ['192.168.10.0', {subnet: true}, ['No subnet.']],
'IPv4 with CIDR subnet, subnet option is not defined': ['192.168.10.0/24', {}, []],
'IPv4 with CIDR subnet, subnet option is set to "false"': [
'192.168.10.0/24',
{subnet: false},
['Has subnet.']
],
'IPv4 with CIDR subnet, subnet option is set to "true"': ['192.168.10.0/24', {subnet: true}, []],
// subnet, IPv6
'IPv6, subnet option is not defined': ['2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d', {}, []],
'IPv6, subnet option is set to "false"': ['2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d', {subnet: false}, []],
'IPv6, subnet option is set to "true"': [
'2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d',
{subnet: true},
['No subnet.']
],
'IPv6 with CIDR subnet, subnet option is not defined': [
'2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d/24',
{},
[]
],
'IPv6 with CIDR subnet, subnet option is set to "false"': [
'2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d/24',
{subnet: false},
['Has subnet.']
],
'IPv6 with CIDR subnet, subnet option is set to "true"': [
'2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d/24',
{subnet: true},
[]
],
// negation, IPv4
'IPv4, negation option is not defined': ['192.168.10.0', {}, []],
'IPv4, negation option is set to "false"': ['192.168.10.0', {negation: false}, []],
'IPv4, negation option is set to "true"': ['192.168.10.0', {negation: true}, []],
'IPv4 with negation, negation option is not defined': ['!192.168.10.0', {}, []],
'IPv4 with negation, negation option is set to "false"': [
'!192.168.10.0',
{negation: false},
['Invalid value.']
],
'IPv4 with negation, negation option is set to "true"': ['!192.168.10.0', {negation: true}, []],
// negation, IPv6
'IPv6, negation option is not defined': ['2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d', {}, []],
'IPv6, negation option is set to "false"': [
'2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d',
{negation: false},
[]
],
'IPv6, negation option is set to "true"': ['2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d', {negation: true}, []],
'IPv6 with negation, negation option is not defined': ['!2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d', {}, []],
'IPv6 with negation, negation option is set to "false"': [
'!2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d',
{negation: false},
['Invalid value.']
],
'IPv6 with negation, negation option is set to "true"': [
'!2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d',
{negation: true},
[]
],
// ipv4, ipv6
'IPv4, IPv4 option is set to "false"': ['192.168.10.0', {ipv4: false}, ['IPv4 is not allowed.']],
'IPv6, IPv6 option is set to "false"': [
'2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d',
{ipv6: false},
['IPv6 is not allowed.']
],
'IPv6, short variation (4 groups)': ['2001:db8::ae21:ad12', {}, []],
'IPv6, short variation (2 groups)': ['::ae21:ad12', {}, []],
'IPv4, IPv4 and IPv6 options are set to "false"': [
'192.168.10.0',
{ipv4: false, ipv6: false},
['IPv4 is not allowed.']
],
'IPv6, IPv4 and IPv6 options are set to "false"': [
'2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d',
{ipv4: false, ipv6: false},
['IPv6 is not allowed.']
],
'invalid IPv4': ['192,168.10.0', {}, ['Invalid value.']],
'invalid IPv6': ['2001,0db8:11a3:09d7:1f34:8a2e:07a0:765d', {}, ['Invalid value.']],
'invalid IPv4, IPv4 option is set to "false"': [
'192,168.10.0',
{ipv4: false},
['Invalid value.', 'IPv4 is not allowed.']
],
'invalid IPv6, IPv6 option is set to "false"': [
'2001,0db8:11a3:09d7:1f34:8a2e:07a0:765d',
{ipv6: false},
['Invalid value.', 'IPv6 is not allowed.']
]
}, function (value, customOptions, expectedMessages) {
it(getValidatorMessage(expectedMessages), function () {
var messages = [];
var options = $.extend({}, defaultOptions, customOptions);
yii.validation.ip(value, messages, options);
assert.deepEqual(messages, expectedMessages);
})
});
});
});
| yiisoft/yii2 | tests/js/tests/yii.validation.test.js | JavaScript | bsd-3-clause | 79,127 |
/**
GridStoreAdapter
Stores files in Mongo using GridStore
Requires the database adapter to be based on mongoclient
@flow weak
*/
import { MongoClient, GridStore, Db} from 'mongodb';
import { FilesAdapter } from './FilesAdapter';
import defaults from '../../defaults';
export class GridStoreAdapter extends FilesAdapter {
_databaseURI: string;
_connectionPromise: Promise<Db>;
constructor(mongoDatabaseURI = defaults.DefaultMongoURI) {
super();
this._databaseURI = mongoDatabaseURI;
}
_connect() {
if (!this._connectionPromise) {
this._connectionPromise = MongoClient.connect(this._databaseURI);
}
return this._connectionPromise;
}
// For a given config object, filename, and data, store a file
// Returns a promise
createFile(filename: string, data) {
return this._connect().then(database => {
const gridStore = new GridStore(database, filename, 'w');
return gridStore.open();
}).then(gridStore => {
return gridStore.write(data);
}).then(gridStore => {
return gridStore.close();
});
}
deleteFile(filename: string) {
return this._connect().then(database => {
const gridStore = new GridStore(database, filename, 'r');
return gridStore.open();
}).then((gridStore) => {
return gridStore.unlink();
}).then((gridStore) => {
return gridStore.close();
});
}
getFileData(filename: string) {
return this._connect().then(database => {
return GridStore.exist(database, filename)
.then(() => {
const gridStore = new GridStore(database, filename, 'r');
return gridStore.open();
});
}).then(gridStore => {
return gridStore.read();
});
}
getFileLocation(config, filename) {
return (config.mount + '/files/' + config.applicationId + '/' + encodeURIComponent(filename));
}
getFileStream(filename: string) {
return this._connect().then(database => {
return GridStore.exist(database, filename).then(() => {
const gridStore = new GridStore(database, filename, 'r');
return gridStore.open();
});
});
}
}
export default GridStoreAdapter;
| rendongsc/parse-server | src/Adapters/Files/GridStoreAdapter.js | JavaScript | bsd-3-clause | 2,208 |
//>>built
define("dijit/form/HorizontalRule",["dojo/_base/declare","../_Widget","../_TemplatedMixin"],function(_1,_2,_3){return _1("dijit.form.HorizontalRule",[_2,_3],{templateString:"<div class=\"dijitRuleContainer dijitRuleContainerH\"></div>",count:3,container:"containerNode",ruleStyle:"",_positionPrefix:"<div class=\"dijitRuleMark dijitRuleMarkH\" style=\"left:",_positionSuffix:"%;",_suffix:"\"></div>",_genHTML:function(_4){return this._positionPrefix+_4+this._positionSuffix+this.ruleStyle+this._suffix;},_isHorizontal:true,buildRendering:function(){this.inherited(arguments);var _5;if(this.count==1){_5=this._genHTML(50,0);}else{var i;var _6=100/(this.count-1);if(!this._isHorizontal||this.isLeftToRight()){_5=this._genHTML(0,0);for(i=1;i<this.count-1;i++){_5+=this._genHTML(_6*i,i);}_5+=this._genHTML(100,this.count-1);}else{_5=this._genHTML(100,0);for(i=1;i<this.count-1;i++){_5+=this._genHTML(100-_6*i,i);}_5+=this._genHTML(0,this.count-1);}}this.domNode.innerHTML=_5;}});}); | NCIP/cabio | software/cabio-api/system/web/dijit/form/HorizontalRule.js | JavaScript | bsd-3-clause | 989 |
/**
* @author Yongnan
* @version 1.0
* @time 11/26/2014
* @name PathBubble_BiPartite
*/
PATHBUBBLES.BiPartite = function (x, y, w, h, data, name) {
var tmp;
PATHBUBBLES.BubbleBase.call(this, {
type: 'BiPartite',
mainMenu: true, closeMenu: true, groupMenu: true,
html_elements: ['svg', 'menuView'],
name: name || 'biPartite'
});
this.button = new PATHBUBBLES.Button(this); //Button 0 for file selection
tmp = '';
// tmp += '<input type="text" id=file style="position: absolute; left:' + this.x + ' px; top:' + this.y + 'px; ">';
// tmp += '<input type="button" id=export value= "Link TO WebGiVi" style="position: absolute; left:' + this.x + ' px; top:' + this.y + 25 + 'px; ">';
// tmp += '<div id=colorpickerField style="position: absolute; left:' + this.x + ' px; top: ' + this.y + 55 + ' px; "></div>';
tmp += '<input type="button" id=saveFile value= "Save" style="position: absolute; left:' + this.x + ' px; top:' + this.y + 50 + 'px; ">';
// tmp += '<input type="button" id=delete value= "Delete" style="position: absolute; left:' + this.x + ' px; top:' + this.y + 105 + 'px; ">';
this.button.addButton(tmp);
this.data = data || null;
};
PATHBUBBLES.BiPartite.prototype = $.extend(Object.create(PATHBUBBLES.BubbleBase.prototype), {
constructor: PATHBUBBLES.BiPartite,
addHtml: function (header) {
var _this=this;
this.setOffset();
var tmp = '';
tmp += '<div id= svg' + this.id + ' style="position: absolute;"> </div>';
$("#bubble").append($(tmp));
this.biPartite = new PATHBUBBLES.D3BiPartite(this, this.w, this.h);
if(header!==undefined)
this.biPartite.header = header;
this.biPartite.init();
},
menuOperation: function () {
var _this = this;
var $menuBarbubble = $('#menuView' + this.id);
$menuBarbubble.find("#saveFile").on('click',function(){
var currentData= _this.biPartite.data[0].data;
var saveString = "";
if(currentData.data!==undefined)
{
var tempData = currentData.data;
var tempKey = currentData.keys;
for(var i=0; i<tempData[0].length; ++i)
{
for(var j=0;j<tempData[0][i].length; ++j)
{
if(tempData[0][i][j] ==1)
{
saveString += tempKey[0][i];
saveString += "\t";
saveString += tempKey[1][j];
saveString += "\n";
}
}
}
for(var i=0; i<tempData[1].length; ++i)
{
for(var j=0;j<tempData[1][i].length; ++j)
{
if(tempData[1][i][j] ==1)
{
saveString += tempKey[0][j];
saveString += "\t";
saveString += tempKey[1][i];
saveString += "\n";
}
}
}
// var blob = new Blob([saveString],{type:"text/plain;chartset=utf-8"});
// download(blob, "geneSymbol.txt", "text/plain");
download(saveString, "geneSymbol.txt", "text/plain");
}
});
},
updateMenu: function () {
var $menuBarbubble = $('#menuView' + this.id);
$menuBarbubble.css({
left: this.x + this.offsetX + this.w + 10,
top: this.y + this.offsetY + this.cornerRadius / 2 + 40,
width: 200,
height: 215
});
// $menuBarbubble.find('#export').css({
// left: 10,
// top: 25,
// width: 180
// });
$menuBarbubble.find('#saveFile').css({
left: 10,
top: 25,
width: 180
});
},
drawSVG: function() {
var space = 6; // leave 6 space for tree ring
$('#svg' + this.id).css({
width: this.w - 15 - space,
height: this.h - 20 - space,
left: this.x + this.w / 2 - this.biPartite.w / 2 + 5 + space / 2,
top: this.y + 50 + 10 + space / 2 + 5
});
}
});
| garba1/GraphMirrors | js/BiPartite.js | JavaScript | bsd-3-clause | 3,873 |
// DATA_TEMPLATE: empty_table
oTest.fnStart( "oLanguage.sProcessing" );
$(document).ready( function () {
/* Check the default */
var oTable = $('#example').dataTable( {
"sAjaxSource": "../../../examples/ajax/sources/arrays.txt",
"bDeferRender": true,
"bProcessing": true
} );
var oSettings = oTable.fnSettings();
oTest.fnWaitTest(
"Processing language is 'Processing...' by default",
null,
function () { return oSettings.oLanguage.sProcessing == "Processing..."; }
);
oTest.fnTest(
"Processing language default is in the DOM",
null,
function () { return document.getElementById('example_processing').innerHTML = "Processing..."; }
);
oTest.fnWaitTest(
"Processing language can be defined",
function () {
oSession.fnRestore();
oTable = $('#example').dataTable( {
"sAjaxSource": "../../../examples/ajax/sources/arrays.txt",
"bDeferRender": true,
"bProcessing": true,
"oLanguage": {
"sProcessing": "unit test"
}
} );
oSettings = oTable.fnSettings();
},
function () { return oSettings.oLanguage.sProcessing == "unit test"; }
);
oTest.fnTest(
"Processing language definition is in the DOM",
null,
function () { return document.getElementById('example_processing').innerHTML = "unit test"; }
);
oTest.fnComplete();
} ); | stevemoore113/ch_web_- | 資源/Facemash/DataTables-1.9.4/media/unit_testing/tests_onhold/6_delayed_rendering/oLanguage.sProcessing.js | JavaScript | mit | 1,314 |
import React from "react";
import { NotFoundRoute, Route } from "react-router";
import App from "./components/App";
import Home from "./components/Home";
import NotFound from "./components/NotFound";
import Stargazer from "./components/Stargazer";
import Stargazers from "./components/Stargazers";
export default (
<Route handler={App}>
// Query-able URLs (for POSTs & crawlers)
<Route name="query.repo" path="/repo" handler={Stargazers} />
// Canonical URLs
<Route name="home" path="/" handler={Home} />
<Route name="user" path="/:user" handler={Stargazer} />
<Route name="repo" path="/:user/:repo" handler={Stargazers} />
<NotFoundRoute name="404" handler={NotFound} />
</Route>
);
| shaunstanislaus/react-resolver | examples/react-v0.13/src/routes.js | JavaScript | isc | 720 |
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
export default isLength; | hoka-plus/p-01-web | tmp/babel-output_path-MNyU5yIO.tmp/modules/lodash/internal/isLength.js | JavaScript | mit | 641 |
/*
html2canvas 0.5.0-alpha1 <http://html2canvas.hertzen.com>
Copyright (c) 2015 Niklas von Hertzen
Released under MIT License
*/
(function(window, document, exports, global, define, undefined){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 2.0.1
*/
(function(){function r(a,b){n[l]=a;n[l+1]=b;l+=2;2===l&&A()}function s(a){return"function"===typeof a}function F(){return function(){process.nextTick(t)}}function G(){var a=0,b=new B(t),c=document.createTextNode("");b.observe(c,{characterData:!0});return function(){c.data=a=++a%2}}function H(){var a=new MessageChannel;a.port1.onmessage=t;return function(){a.port2.postMessage(0)}}function I(){return function(){setTimeout(t,1)}}function t(){for(var a=0;a<l;a+=2)(0,n[a])(n[a+1]),n[a]=void 0,n[a+1]=void 0;
l=0}function p(){}function J(a,b,c,d){try{a.call(b,c,d)}catch(e){return e}}function K(a,b,c){r(function(a){var e=!1,f=J(c,b,function(c){e||(e=!0,b!==c?q(a,c):m(a,c))},function(b){e||(e=!0,g(a,b))});!e&&f&&(e=!0,g(a,f))},a)}function L(a,b){1===b.a?m(a,b.b):2===a.a?g(a,b.b):u(b,void 0,function(b){q(a,b)},function(b){g(a,b)})}function q(a,b){if(a===b)g(a,new TypeError("You cannot resolve a promise with itself"));else if("function"===typeof b||"object"===typeof b&&null!==b)if(b.constructor===a.constructor)L(a,
b);else{var c;try{c=b.then}catch(d){v.error=d,c=v}c===v?g(a,v.error):void 0===c?m(a,b):s(c)?K(a,b,c):m(a,b)}else m(a,b)}function M(a){a.f&&a.f(a.b);x(a)}function m(a,b){void 0===a.a&&(a.b=b,a.a=1,0!==a.e.length&&r(x,a))}function g(a,b){void 0===a.a&&(a.a=2,a.b=b,r(M,a))}function u(a,b,c,d){var e=a.e,f=e.length;a.f=null;e[f]=b;e[f+1]=c;e[f+2]=d;0===f&&a.a&&r(x,a)}function x(a){var b=a.e,c=a.a;if(0!==b.length){for(var d,e,f=a.b,g=0;g<b.length;g+=3)d=b[g],e=b[g+c],d?C(c,d,e,f):e(f);a.e.length=0}}function D(){this.error=
null}function C(a,b,c,d){var e=s(c),f,k,h,l;if(e){try{f=c(d)}catch(n){y.error=n,f=y}f===y?(l=!0,k=f.error,f=null):h=!0;if(b===f){g(b,new TypeError("A promises callback cannot return that same promise."));return}}else f=d,h=!0;void 0===b.a&&(e&&h?q(b,f):l?g(b,k):1===a?m(b,f):2===a&&g(b,f))}function N(a,b){try{b(function(b){q(a,b)},function(b){g(a,b)})}catch(c){g(a,c)}}function k(a,b,c,d){this.n=a;this.c=new a(p,d);this.i=c;this.o(b)?(this.m=b,this.d=this.length=b.length,this.l(),0===this.length?m(this.c,
this.b):(this.length=this.length||0,this.k(),0===this.d&&m(this.c,this.b))):g(this.c,this.p())}function h(a){O++;this.b=this.a=void 0;this.e=[];if(p!==a){if(!s(a))throw new TypeError("You must pass a resolver function as the first argument to the promise constructor");if(!(this instanceof h))throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");N(this,a)}}var E=Array.isArray?Array.isArray:function(a){return"[object Array]"===
Object.prototype.toString.call(a)},l=0,w="undefined"!==typeof window?window:{},B=w.MutationObserver||w.WebKitMutationObserver,w="undefined"!==typeof Uint8ClampedArray&&"undefined"!==typeof importScripts&&"undefined"!==typeof MessageChannel,n=Array(1E3),A;A="undefined"!==typeof process&&"[object process]"==={}.toString.call(process)?F():B?G():w?H():I();var v=new D,y=new D;k.prototype.o=function(a){return E(a)};k.prototype.p=function(){return Error("Array Methods must be provided an Array")};k.prototype.l=
function(){this.b=Array(this.length)};k.prototype.k=function(){for(var a=this.length,b=this.c,c=this.m,d=0;void 0===b.a&&d<a;d++)this.j(c[d],d)};k.prototype.j=function(a,b){var c=this.n;"object"===typeof a&&null!==a?a.constructor===c&&void 0!==a.a?(a.f=null,this.g(a.a,b,a.b)):this.q(c.resolve(a),b):(this.d--,this.b[b]=this.h(a))};k.prototype.g=function(a,b,c){var d=this.c;void 0===d.a&&(this.d--,this.i&&2===a?g(d,c):this.b[b]=this.h(c));0===this.d&&m(d,this.b)};k.prototype.h=function(a){return a};
k.prototype.q=function(a,b){var c=this;u(a,void 0,function(a){c.g(1,b,a)},function(a){c.g(2,b,a)})};var O=0;h.all=function(a,b){return(new k(this,a,!0,b)).c};h.race=function(a,b){function c(a){q(e,a)}function d(a){g(e,a)}var e=new this(p,b);if(!E(a))return (g(e,new TypeError("You must pass an array to race.")), e);for(var f=a.length,h=0;void 0===e.a&&h<f;h++)u(this.resolve(a[h]),void 0,c,d);return e};h.resolve=function(a,b){if(a&&"object"===typeof a&&a.constructor===this)return a;var c=new this(p,b);
q(c,a);return c};h.reject=function(a,b){var c=new this(p,b);g(c,a);return c};h.prototype={constructor:h,then:function(a,b){var c=this.a;if(1===c&&!a||2===c&&!b)return this;var d=new this.constructor(p),e=this.b;if(c){var f=arguments[c-1];r(function(){C(c,d,f,e)})}else u(this,d,a,b);return d},"catch":function(a){return this.then(null,a)}};var z={Promise:h,polyfill:function(){var a;a="undefined"!==typeof global?global:"undefined"!==typeof window&&window.document?window:self;"Promise"in a&&"resolve"in
a.Promise&&"reject"in a.Promise&&"all"in a.Promise&&"race"in a.Promise&&function(){var b;new a.Promise(function(a){b=a});return s(b)}()||(a.Promise=h)}};"function"===typeof define&&define.amd?define(function(){return z}):"undefined"!==typeof module&&module.exports?module.exports=z:"undefined"!==typeof this&&(this.ES6Promise=z);}).call(window);
if (window) {
window.ES6Promise.polyfill();
}
if (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") {
(window || module.exports).html2canvas = function() {
return Promise.reject("No canvas support");
};
return;
}
/*! https://mths.be/punycode v1.3.1 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports &&
!exports.nodeType && exports;
var freeModule = typeof module == 'object' && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
var labels = string.split(regexSeparators);
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* http://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.3.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && freeModule) {
if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = punycode;
} else { // in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else { // in Rhino or a web browser
root.punycode = punycode;
}
}(this));
var html2canvasNodeAttribute = "data-html2canvas-node";
var html2canvasCanvasCloneAttribute = "data-html2canvas-canvas-clone";
var html2canvasCanvasCloneIndex = 0;
var html2canvasCloneIndex = 0;
window.html2canvas = function(nodeList, options) {
var index = html2canvasCloneIndex++;
options = options || {};
if (options.logging) {
window.html2canvas.logging = true;
window.html2canvas.start = Date.now();
}
options.async = typeof(options.async) === "undefined" ? true : options.async;
options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
options.strict = !!options.strict;
if (typeof(nodeList) === "string") {
if (typeof(options.proxy) !== "string") {
return Promise.reject("Proxy must be used when rendering url");
}
var width = options.width != null ? options.width : window.innerWidth;
var height = options.height != null ? options.height : window.innerHeight;
return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
});
}
var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
node.setAttribute(html2canvasNodeAttribute + index, index);
return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
if (typeof(options.onrendered) === "function") {
log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
options.onrendered(canvas);
}
return canvas;
});
};
window.html2canvas.punycode = this.punycode;
window.html2canvas.proxy = {};
function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
log("Document cloned");
var attributeName = html2canvasNodeAttribute + html2canvasIndex;
var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
document.querySelector(selector).removeAttribute(attributeName);
var clonedWindow = container.contentWindow;
var node = clonedWindow.document.querySelector(selector);
var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
return oncloneHandler.then(function() {
return renderWindow(node, container, options, windowWidth, windowHeight);
});
});
}
function renderWindow(node, container, options, windowWidth, windowHeight) {
var clonedWindow = container.contentWindow;
var support = new Support(clonedWindow.document);
var imageLoader = new ImageLoader(options, support);
var bounds = getBounds(node);
var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
var renderer = new options.renderer(width, height, imageLoader, options, document);
var parser = new NodeParser(node, renderer, support, imageLoader, options);
return parser.ready.then(function() {
log("Finished rendering");
var canvas;
if (options.type === "view") {
canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
} else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
canvas = renderer.canvas;
} else {
canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: clonedWindow.pageXOffset, y: clonedWindow.pageYOffset});
}
cleanupContainer(container, options);
return canvas;
});
}
function cleanupContainer(container, options) {
if (options.removeContainer) {
container.parentNode.removeChild(container);
log("Cleaned up container");
}
}
function crop(canvas, bounds) {
var croppedCanvas = document.createElement("canvas");
var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
croppedCanvas.width = bounds.width;
croppedCanvas.height = bounds.height;
log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", (x2-x1), "height:", (y2-y1));
log("Resulting crop with width", bounds.width, "and height", bounds.height, " with x", x1, "and y", y1);
croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, x2-x1, y2-y1, bounds.x, bounds.y, x2-x1, y2-y1);
return croppedCanvas;
}
function documentWidth (doc) {
return Math.max(
Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
);
}
function documentHeight (doc) {
return Math.max(
Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
);
}
function smallImage() {
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
}
function isIE9() {
return document.documentMode && document.documentMode <= 9;
}
// https://github.com/niklasvh/html2canvas/issues/503
function cloneNodeIE9(node, javascriptEnabled) {
var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
var child = node.firstChild;
while(child) {
if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
clone.appendChild(cloneNodeIE9(child, javascriptEnabled));
}
child = child.nextSibling;
}
return clone;
}
function createWindowClone(ownerDocument, containerDocument, width, height, options, x ,y) {
labelCanvasElements(ownerDocument);
var documentElement = isIE9() ? cloneNodeIE9(ownerDocument.documentElement, options.javascriptEnabled) : ownerDocument.documentElement.cloneNode(true);
var container = containerDocument.createElement("iframe");
container.className = "html2canvas-container";
container.style.visibility = "hidden";
container.style.position = "fixed";
container.style.left = "-10000px";
container.style.top = "0px";
container.style.border = "0";
container.width = width;
container.height = height;
container.scrolling = "no"; // ios won't scroll without it
containerDocument.body.appendChild(container);
return new Promise(function(resolve) {
var documentClone = container.contentWindow.document;
cloneNodeValues(ownerDocument.documentElement, documentElement, "textarea");
cloneNodeValues(ownerDocument.documentElement, documentElement, "select");
/* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
if window url is about:blank, we can assign the url to current by writing onto the document
*/
container.contentWindow.onload = container.onload = function() {
var interval = setInterval(function() {
if (documentClone.body.childNodes.length > 0) {
cloneCanvasContents(ownerDocument, documentClone);
clearInterval(interval);
if (options.type === "view") {
container.contentWindow.scrollTo(x, y);
}
resolve(container);
}
}, 50);
};
documentClone.open();
documentClone.write("<!DOCTYPE html><html></html>");
// Chrome scrolls the parent document for some reason after the write to the cloned window???
restoreOwnerScroll(ownerDocument, x, y);
documentClone.replaceChild(options.javascriptEnabled === true ? documentClone.adoptNode(documentElement) : removeScriptNodes(documentClone.adoptNode(documentElement)), documentClone.documentElement);
documentClone.close();
});
}
function cloneNodeValues(document, clone, nodeName) {
var originalNodes = document.getElementsByTagName(nodeName);
var clonedNodes = clone.getElementsByTagName(nodeName);
var count = originalNodes.length;
for (var i = 0; i < count; i++) {
clonedNodes[i].value = originalNodes[i].value;
}
}
function restoreOwnerScroll(ownerDocument, x, y) {
if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
ownerDocument.defaultView.scrollTo(x, y);
}
}
function loadUrlDocument(src, proxy, document, width, height, options) {
return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
return createWindowClone(doc, document, width, height, options, 0, 0);
});
}
function documentFromHTML(src) {
return function(html) {
var parser = new DOMParser(), doc;
try {
doc = parser.parseFromString(html, "text/html");
} catch(e) {
log("DOMParser not supported, falling back to createHTMLDocument");
doc = document.implementation.createHTMLDocument("");
try {
doc.open();
doc.write(html);
doc.close();
} catch(ee) {
log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
}
}
var b = doc.querySelector("base");
if (!b || !b.href.host) {
var base = doc.createElement("base");
base.href = src;
doc.head.insertBefore(base, doc.head.firstChild);
}
return doc;
};
}
function labelCanvasElements(ownerDocument) {
[].slice.call(ownerDocument.querySelectorAll("canvas"), 0).forEach(function(canvas) {
canvas.setAttribute(html2canvasCanvasCloneAttribute, "canvas-" + html2canvasCanvasCloneIndex++);
});
}
function cloneCanvasContents(ownerDocument, documentClone) {
[].slice.call(ownerDocument.querySelectorAll("[" + html2canvasCanvasCloneAttribute + "]"), 0).forEach(function(canvas) {
try {
var clonedCanvas = documentClone.querySelector('[' + html2canvasCanvasCloneAttribute + '="' + canvas.getAttribute(html2canvasCanvasCloneAttribute) + '"]');
if (clonedCanvas) {
clonedCanvas.width = canvas.width;
clonedCanvas.height = canvas.height;
clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
}
} catch(e) {
log("Unable to copy canvas content from", canvas, e);
}
canvas.removeAttribute(html2canvasCanvasCloneAttribute);
});
}
function removeScriptNodes(parent) {
[].slice.call(parent.childNodes, 0).filter(isElementNode).forEach(function(node) {
if (node.tagName === "SCRIPT") {
parent.removeChild(node);
} else {
removeScriptNodes(node);
}
});
return parent;
}
function isElementNode(node) {
return node.nodeType === Node.ELEMENT_NODE;
}
function absoluteUrl(url) {
var link = document.createElement("a");
link.href = url;
link.href = link.href;
return link;
}
// http://dev.w3.org/csswg/css-color/
function Color(value) {
this.r = 0;
this.g = 0;
this.b = 0;
this.a = null;
var result = this.fromArray(value) ||
this.namedColor(value) ||
this.rgb(value) ||
this.rgba(value) ||
this.hex6(value) ||
this.hex3(value);
}
Color.prototype.darken = function(amount) {
var a = 1 - amount;
return new Color([
Math.round(this.r * a),
Math.round(this.g * a),
Math.round(this.b * a),
this.a
]);
};
Color.prototype.isTransparent = function() {
return this.a === 0;
};
Color.prototype.isBlack = function() {
return this.r === 0 && this.g === 0 && this.b === 0;
};
Color.prototype.fromArray = function(array) {
if (Array.isArray(array)) {
this.r = Math.min(array[0], 255);
this.g = Math.min(array[1], 255);
this.b = Math.min(array[2], 255);
if (array.length > 3) {
this.a = array[3];
}
}
return (Array.isArray(array));
};
var _hex3 = /^#([a-f0-9]{3})$/i;
Color.prototype.hex3 = function(value) {
var match = null;
if ((match = value.match(_hex3)) !== null) {
this.r = parseInt(match[1][0] + match[1][0], 16);
this.g = parseInt(match[1][1] + match[1][1], 16);
this.b = parseInt(match[1][2] + match[1][2], 16);
}
return match !== null;
};
var _hex6 = /^#([a-f0-9]{6})$/i;
Color.prototype.hex6 = function(value) {
var match = null;
if ((match = value.match(_hex6)) !== null) {
this.r = parseInt(match[1].substring(0, 2), 16);
this.g = parseInt(match[1].substring(2, 4), 16);
this.b = parseInt(match[1].substring(4, 6), 16);
}
return match !== null;
};
var _rgb = /^rgb\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3})\)$/;
Color.prototype.rgb = function(value) {
var match = null;
if ((match = value.match(_rgb)) !== null) {
this.r = Number(match[1]);
this.g = Number(match[2]);
this.b = Number(match[3]);
}
return match !== null;
};
var _rgba = /^rgba\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3}) *, *(\d+\.?\d*)\)$/;
Color.prototype.rgba = function(value) {
var match = null;
if ((match = value.match(_rgba)) !== null) {
this.r = Number(match[1]);
this.g = Number(match[2]);
this.b = Number(match[3]);
this.a = Number(match[4]);
}
return match !== null;
};
Color.prototype.toString = function() {
return this.a !== null && this.a !== 1 ?
"rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
"rgb(" + [this.r, this.g, this.b].join(",") + ")";
};
Color.prototype.namedColor = function(value) {
var color = colors[value.toLowerCase()];
if (color) {
this.r = color[0];
this.g = color[1];
this.b = color[2];
} else if (value.toLowerCase() === "transparent") {
this.r = this.g = this.b = this.a = 0;
return true;
}
return !!color;
};
Color.prototype.isColor = true;
// JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
var colors = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
function DummyImageContainer(src) {
this.src = src;
log("DummyImageContainer for", src);
if (!this.promise || !this.image) {
log("Initiating DummyImageContainer");
DummyImageContainer.prototype.image = new Image();
var image = this.image;
DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
image.onload = resolve;
image.onerror = reject;
image.src = smallImage();
if (image.complete === true) {
resolve(image);
}
});
}
}
function Font(family, size) {
var container = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span'),
sampleText = 'Hidden Text',
baseline,
middle;
container.style.visibility = "hidden";
container.style.fontFamily = family;
container.style.fontSize = size;
container.style.margin = 0;
container.style.padding = 0;
document.body.appendChild(container);
img.src = smallImage();
img.width = 1;
img.height = 1;
img.style.margin = 0;
img.style.padding = 0;
img.style.verticalAlign = "baseline";
span.style.fontFamily = family;
span.style.fontSize = size;
span.style.margin = 0;
span.style.padding = 0;
span.appendChild(document.createTextNode(sampleText));
container.appendChild(span);
container.appendChild(img);
baseline = (img.offsetTop - span.offsetTop) + 1;
container.removeChild(span);
container.appendChild(document.createTextNode(sampleText));
container.style.lineHeight = "normal";
img.style.verticalAlign = "super";
middle = (img.offsetTop-container.offsetTop) + 1;
document.body.removeChild(container);
this.baseline = baseline;
this.lineWidth = 1;
this.middle = middle;
}
function FontMetrics() {
this.data = {};
}
FontMetrics.prototype.getMetrics = function(family, size) {
if (this.data[family + "-" + size] === undefined) {
this.data[family + "-" + size] = new Font(family, size);
}
return this.data[family + "-" + size];
};
function FrameContainer(container, sameOrigin, options) {
this.image = null;
this.src = container;
var self = this;
var bounds = getBounds(container);
this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
container.contentWindow.onload = container.onload = function() {
resolve(container);
};
} else {
resolve(container);
}
})).then(function(container) {
return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2});
}).then(function(canvas) {
return self.image = canvas;
});
}
FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
var container = this.src;
return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
};
function GradientContainer(imageData) {
this.src = imageData.value;
this.colorStops = [];
this.type = null;
this.x0 = 0.5;
this.y0 = 0.5;
this.x1 = 0.5;
this.y1 = 0.5;
this.promise = Promise.resolve(true);
}
GradientContainer.prototype.TYPES = {
LINEAR: 1,
RADIAL: 2
};
function ImageContainer(src, cors) {
this.src = src;
this.image = new Image();
var self = this;
this.tainted = null;
this.promise = new Promise(function(resolve, reject) {
self.image.onload = resolve;
self.image.onerror = reject;
if (cors) {
self.image.crossOrigin = "anonymous";
}
self.image.src = src;
if (self.image.complete === true) {
resolve(self.image);
}
});
}
function ImageLoader(options, support) {
this.link = null;
this.options = options;
this.support = support;
this.origin = this.getOrigin(window.location.href);
}
ImageLoader.prototype.findImages = function(nodes) {
var images = [];
nodes.reduce(function(imageNodes, container) {
switch(container.node.nodeName) {
case "IMG":
return imageNodes.concat([{
args: [container.node.src],
method: "url"
}]);
case "svg":
case "IFRAME":
return imageNodes.concat([{
args: [container.node],
method: container.node.nodeName
}]);
}
return imageNodes;
}, []).forEach(this.addImage(images, this.loadImage), this);
return images;
};
ImageLoader.prototype.findBackgroundImage = function(images, container) {
container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
return images;
};
ImageLoader.prototype.addImage = function(images, callback) {
return function(newImage) {
newImage.args.forEach(function(image) {
if (!this.imageExists(images, image)) {
images.splice(0, 0, callback.call(this, newImage));
log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
}
}, this);
};
};
ImageLoader.prototype.hasImageBackground = function(imageData) {
return imageData.method !== "none";
};
ImageLoader.prototype.loadImage = function(imageData) {
if (imageData.method === "url") {
var src = imageData.args[0];
if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
return new SVGContainer(src);
} else if (src.match(/data:image\/.*;base64,/i)) {
return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
} else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
return new ImageContainer(src, false);
} else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
return new ImageContainer(src, true);
} else if (this.options.proxy) {
return new ProxyImageContainer(src, this.options.proxy);
} else {
return new DummyImageContainer(src);
}
} else if (imageData.method === "linear-gradient") {
return new LinearGradientContainer(imageData);
} else if (imageData.method === "gradient") {
return new WebkitGradientContainer(imageData);
} else if (imageData.method === "svg") {
return new SVGNodeContainer(imageData.args[0], this.support.svg);
} else if (imageData.method === "IFRAME") {
return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
} else {
return new DummyImageContainer(imageData);
}
};
ImageLoader.prototype.isSVG = function(src) {
return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
};
ImageLoader.prototype.imageExists = function(images, src) {
return images.some(function(image) {
return image.src === src;
});
};
ImageLoader.prototype.isSameOrigin = function(url) {
return (this.getOrigin(url) === this.origin);
};
ImageLoader.prototype.getOrigin = function(url) {
var link = this.link || (this.link = document.createElement("a"));
link.href = url;
link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
return link.protocol + link.hostname + link.port;
};
ImageLoader.prototype.getPromise = function(container) {
return this.timeout(container, this.options.imageTimeout)['catch'](function() {
var dummy = new DummyImageContainer(container.src);
return dummy.promise.then(function(image) {
container.image = image;
});
});
};
ImageLoader.prototype.get = function(src) {
var found = null;
return this.images.some(function(img) {
return (found = img).src === src;
}) ? found : null;
};
ImageLoader.prototype.fetch = function(nodes) {
this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
this.images.forEach(function(image, index) {
image.promise.then(function() {
log("Succesfully loaded image #"+ (index+1), image);
}, function(e) {
log("Failed loading image #"+ (index+1), image, e);
});
});
this.ready = Promise.all(this.images.map(this.getPromise, this));
log("Finished searching images");
return this;
};
ImageLoader.prototype.timeout = function(container, timeout) {
var timer;
var promise = Promise.race([container.promise, new Promise(function(res, reject) {
timer = setTimeout(function() {
log("Timed out loading image", container);
reject(container);
}, timeout);
})]).then(function(container) {
clearTimeout(timer);
return container;
});
promise['catch'](function() {
clearTimeout(timer);
});
return promise;
};
function LinearGradientContainer(imageData) {
GradientContainer.apply(this, arguments);
this.type = this.TYPES.LINEAR;
var hasDirection = imageData.args[0].match(this.stepRegExp) === null;
if (hasDirection) {
imageData.args[0].split(" ").reverse().forEach(function(position) {
switch(position) {
case "left":
this.x0 = 0;
this.x1 = 1;
break;
case "top":
this.y0 = 0;
this.y1 = 1;
break;
case "right":
this.x0 = 1;
this.x1 = 0;
break;
case "bottom":
this.y0 = 1;
this.y1 = 0;
break;
case "to":
var y0 = this.y0;
var x0 = this.x0;
this.y0 = this.y1;
this.x0 = this.x1;
this.x1 = x0;
this.y1 = y0;
break;
}
}, this);
} else {
this.y0 = 0;
this.y1 = 1;
}
this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
var colorStopMatch = colorStop.match(this.stepRegExp);
return {
color: new Color(colorStopMatch[1]),
stop: colorStopMatch[3] === "%" ? colorStopMatch[2] / 100 : null
};
}, this);
if (this.colorStops[0].stop === null) {
this.colorStops[0].stop = 0;
}
if (this.colorStops[this.colorStops.length - 1].stop === null) {
this.colorStops[this.colorStops.length - 1].stop = 1;
}
this.colorStops.forEach(function(colorStop, index) {
if (colorStop.stop === null) {
this.colorStops.slice(index).some(function(find, count) {
if (find.stop !== null) {
colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
return true;
} else {
return false;
}
}, this);
}
}, this);
}
LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
LinearGradientContainer.prototype.stepRegExp = /((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/;
function log() {
if (window.html2canvas.logging && window.console && window.console.log) {
Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - window.html2canvas.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
}
}
function NodeContainer(node, parent) {
this.node = node;
this.parent = parent;
this.stack = null;
this.bounds = null;
this.borders = null;
this.clip = [];
this.backgroundClip = [];
this.offsetBounds = null;
this.visible = null;
this.computedStyles = null;
this.colors = {};
this.styles = {};
this.backgroundImages = null;
this.transformData = null;
this.transformMatrix = null;
this.isPseudoElement = false;
this.opacity = null;
}
NodeContainer.prototype.cloneTo = function(stack) {
stack.visible = this.visible;
stack.borders = this.borders;
stack.bounds = this.bounds;
stack.clip = this.clip;
stack.backgroundClip = this.backgroundClip;
stack.computedStyles = this.computedStyles;
stack.styles = this.styles;
stack.backgroundImages = this.backgroundImages;
stack.opacity = this.opacity;
};
NodeContainer.prototype.getOpacity = function() {
return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
};
NodeContainer.prototype.assignStack = function(stack) {
this.stack = stack;
stack.children.push(this);
};
NodeContainer.prototype.isElementVisible = function() {
return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
this.css('display') !== "none" &&
this.css('visibility') !== "hidden" &&
!this.node.hasAttribute("data-html2canvas-ignore") &&
(this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
);
};
NodeContainer.prototype.css = function(attribute) {
if (!this.computedStyles) {
this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
}
return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
};
NodeContainer.prototype.prefixedCss = function(attribute) {
var prefixes = ["webkit", "moz", "ms", "o"];
var value = this.css(attribute);
if (value === undefined) {
prefixes.some(function(prefix) {
value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
return value !== undefined;
}, this);
}
return value === undefined ? null : value;
};
NodeContainer.prototype.computedStyle = function(type) {
return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
};
NodeContainer.prototype.cssInt = function(attribute) {
var value = parseInt(this.css(attribute), 10);
return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
};
NodeContainer.prototype.color = function(attribute) {
return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
};
NodeContainer.prototype.cssFloat = function(attribute) {
var value = parseFloat(this.css(attribute));
return (isNaN(value)) ? 0 : value;
};
NodeContainer.prototype.fontWeight = function() {
var weight = this.css("fontWeight");
switch(parseInt(weight, 10)){
case 401:
weight = "bold";
break;
case 400:
weight = "normal";
break;
}
return weight;
};
NodeContainer.prototype.parseClip = function() {
var matches = this.css('clip').match(this.CLIP);
if (matches) {
return {
top: parseInt(matches[1], 10),
right: parseInt(matches[2], 10),
bottom: parseInt(matches[3], 10),
left: parseInt(matches[4], 10)
};
}
return null;
};
NodeContainer.prototype.parseBackgroundImages = function() {
return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
};
NodeContainer.prototype.cssList = function(property, index) {
var value = (this.css(property) || '').split(',');
value = value[index || 0] || value[0] || 'auto';
value = value.trim().split(' ');
if (value.length === 1) {
value = [value[0], value[0]];
}
return value;
};
NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
var size = this.cssList("backgroundSize", index);
var width, height;
if (isPercentage(size[0])) {
width = bounds.width * parseFloat(size[0]) / 100;
} else if (/contain|cover/.test(size[0])) {
var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
} else {
width = parseInt(size[0], 10);
}
if (size[0] === 'auto' && size[1] === 'auto') {
height = image.height;
} else if (size[1] === 'auto') {
height = width / image.width * image.height;
} else if (isPercentage(size[1])) {
height = bounds.height * parseFloat(size[1]) / 100;
} else {
height = parseInt(size[1], 10);
}
if (size[0] === 'auto') {
width = height / image.height * image.width;
}
return {width: width, height: height};
};
NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
var position = this.cssList('backgroundPosition', index);
var left, top;
if (isPercentage(position[0])){
left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
} else {
left = parseInt(position[0], 10);
}
if (position[1] === 'auto') {
top = left / image.width * image.height;
} else if (isPercentage(position[1])){
top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
} else {
top = parseInt(position[1], 10);
}
if (position[0] === 'auto') {
left = top / image.height * image.width;
}
return {left: left, top: top};
};
NodeContainer.prototype.parseBackgroundRepeat = function(index) {
return this.cssList("backgroundRepeat", index)[0];
};
NodeContainer.prototype.parseTextShadows = function() {
var textShadow = this.css("textShadow");
var results = [];
if (textShadow && textShadow !== 'none') {
var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
for (var i = 0; shadows && (i < shadows.length); i++) {
var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
results.push({
color: new Color(s[0]),
offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
blur: s[3] ? s[3].replace('px', '') : 0
});
}
}
return results;
};
NodeContainer.prototype.parseTransform = function() {
if (!this.transformData) {
if (this.hasTransform()) {
var offset = this.parseBounds();
var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
origin[0] += offset.left;
origin[1] += offset.top;
this.transformData = {
origin: origin,
matrix: this.parseTransformMatrix()
};
} else {
this.transformData = {
origin: [0, 0],
matrix: [1, 0, 0, 1, 0, 0]
};
}
}
return this.transformData;
};
NodeContainer.prototype.parseTransformMatrix = function() {
if (!this.transformMatrix) {
var transform = this.prefixedCss("transform");
var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
}
return this.transformMatrix;
};
NodeContainer.prototype.parseBounds = function() {
return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
};
NodeContainer.prototype.hasTransform = function() {
return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
};
NodeContainer.prototype.getValue = function() {
var value = this.node.value || "";
if (this.node.tagName === "SELECT") {
value = selectionValue(this.node);
} else if (this.node.type === "password") {
value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
}
return value.length === 0 ? (this.node.placeholder || "") : value;
};
NodeContainer.prototype.MATRIX_PROPERTY = /(matrix)\((.+)\)/;
NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
function selectionValue(node) {
var option = node.options[node.selectedIndex || 0];
return option ? (option.text || "") : "";
}
function parseMatrix(match) {
if (match && match[1] === "matrix") {
return match[2].split(",").map(function(s) {
return parseFloat(s.trim());
});
}
}
function isPercentage(value) {
return value.toString().indexOf("%") !== -1;
}
function parseBackgrounds(backgroundImage) {
var whitespace = ' \r\n\t',
method, definition, prefix, prefix_i, block, results = [],
mode = 0, numParen = 0, quote, args;
var appendResult = function() {
if(method) {
if (definition.substr(0, 1) === '"') {
definition = definition.substr(1, definition.length - 2);
}
if (definition) {
args.push(definition);
}
if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
prefix = method.substr(0, prefix_i);
method = method.substr(prefix_i);
}
results.push({
prefix: prefix,
method: method.toLowerCase(),
value: block,
args: args,
image: null
});
}
args = [];
method = prefix = definition = block = '';
};
args = [];
method = prefix = definition = block = '';
backgroundImage.split("").forEach(function(c) {
if (mode === 0 && whitespace.indexOf(c) > -1) {
return;
}
switch(c) {
case '"':
if(!quote) {
quote = c;
} else if(quote === c) {
quote = null;
}
break;
case '(':
if(quote) {
break;
} else if(mode === 0) {
mode = 1;
block += c;
return;
} else {
numParen++;
}
break;
case ')':
if (quote) {
break;
} else if(mode === 1) {
if(numParen === 0) {
mode = 0;
block += c;
appendResult();
return;
} else {
numParen--;
}
}
break;
case ',':
if (quote) {
break;
} else if(mode === 0) {
appendResult();
return;
} else if (mode === 1) {
if (numParen === 0 && !method.match(/^url$/i)) {
args.push(definition);
definition = '';
block += c;
return;
}
}
break;
}
block += c;
if (mode === 0) {
method += c;
} else {
definition += c;
}
});
appendResult();
return results;
}
function removePx(str) {
return str.replace("px", "");
}
function asFloat(str) {
return parseFloat(str);
}
function getBounds(node) {
if (node.getBoundingClientRect) {
var clientRect = node.getBoundingClientRect();
var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
return {
top: clientRect.top,
bottom: clientRect.bottom || (clientRect.top + clientRect.height),
right: clientRect.left + width,
left: clientRect.left,
width: width,
height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
};
}
return {};
}
function offsetBounds(node) {
var parent = node.offsetParent ? offsetBounds(node.offsetParent) : {top: 0, left: 0};
return {
top: node.offsetTop + parent.top,
bottom: node.offsetTop + node.offsetHeight + parent.top,
right: node.offsetLeft + parent.left + node.offsetWidth,
left: node.offsetLeft + parent.left,
width: node.offsetWidth,
height: node.offsetHeight
};
}
function NodeParser(element, renderer, support, imageLoader, options) {
log("Starting NodeParser");
this.renderer = renderer;
this.options = options;
this.range = null;
this.support = support;
this.renderQueue = [];
this.stack = new StackingContext(true, 1, element.ownerDocument, null);
var parent = new NodeContainer(element, null);
if (options.background) {
renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
}
if (element === element.ownerDocument.documentElement) {
// http://www.w3.org/TR/css3-background/#special-backgrounds
var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
}
parent.visibile = parent.isElementVisible();
this.createPseudoHideStyles(element.ownerDocument);
this.disableAnimations(element.ownerDocument);
this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
return container.visible = container.isElementVisible();
}).map(this.getPseudoElements, this));
this.fontMetrics = new FontMetrics();
log("Fetched nodes, total:", this.nodes.length);
log("Calculate overflow clips");
this.calculateOverflowClips();
log("Start fetching images");
this.images = imageLoader.fetch(this.nodes.filter(isElement));
this.ready = this.images.ready.then(bind(function() {
log("Images loaded, starting parsing");
log("Creating stacking contexts");
this.createStackingContexts();
log("Sorting stacking contexts");
this.sortStackingContexts(this.stack);
this.parse(this.stack);
log("Render queue created with " + this.renderQueue.length + " items");
return new Promise(bind(function(resolve) {
if (!options.async) {
this.renderQueue.forEach(this.paint, this);
resolve();
} else if (typeof(options.async) === "function") {
options.async.call(this, this.renderQueue, resolve);
} else if (this.renderQueue.length > 0){
this.renderIndex = 0;
this.asyncRenderer(this.renderQueue, resolve);
} else {
resolve();
}
}, this));
}, this));
}
NodeParser.prototype.calculateOverflowClips = function() {
this.nodes.forEach(function(container) {
if (isElement(container)) {
if (isPseudoElement(container)) {
container.appendToDOM();
}
container.borders = this.parseBorders(container);
var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
var cssClip = container.parseClip();
if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
clip.push([["rect",
container.bounds.left + cssClip.left,
container.bounds.top + cssClip.top,
cssClip.right - cssClip.left,
cssClip.bottom - cssClip.top
]]);
}
container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
if (isPseudoElement(container)) {
container.cleanDOM();
}
} else if (isTextNode(container)) {
container.clip = hasParentClip(container) ? container.parent.clip : [];
}
if (!isPseudoElement(container)) {
container.bounds = null;
}
}, this);
};
function hasParentClip(container) {
return container.parent && container.parent.clip.length;
}
NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
asyncTimer = asyncTimer || Date.now();
this.paint(queue[this.renderIndex++]);
if (queue.length === this.renderIndex) {
resolve();
} else if (asyncTimer + 20 > Date.now()) {
this.asyncRenderer(queue, resolve, asyncTimer);
} else {
setTimeout(bind(function() {
this.asyncRenderer(queue, resolve);
}, this), 0);
}
};
NodeParser.prototype.createPseudoHideStyles = function(document) {
this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
'.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
};
NodeParser.prototype.disableAnimations = function(document) {
this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
'-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
};
NodeParser.prototype.createStyles = function(document, styles) {
var hidePseudoElements = document.createElement('style');
hidePseudoElements.innerHTML = styles;
document.body.appendChild(hidePseudoElements);
};
NodeParser.prototype.getPseudoElements = function(container) {
var nodes = [[container]];
if (container.node.nodeType === Node.ELEMENT_NODE) {
var before = this.getPseudoElement(container, ":before");
var after = this.getPseudoElement(container, ":after");
if (before) {
nodes.push(before);
}
if (after) {
nodes.push(after);
}
}
return flatten(nodes);
};
function toCamelCase(str) {
return str.replace(/(\-[a-z])/g, function(match){
return match.toUpperCase().replace('-','');
});
}
NodeParser.prototype.getPseudoElement = function(container, type) {
var style = container.computedStyle(type);
if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
return null;
}
var content = stripQuotes(style.content);
var isImage = content.substr(0, 3) === 'url';
var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
for (var i = style.length-1; i >= 0; i--) {
var property = toCamelCase(style.item(i));
pseudoNode.style[property] = style[property];
}
pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
if (isImage) {
pseudoNode.src = parseBackgrounds(content)[0].args[0];
return [pseudoContainer];
} else {
var text = document.createTextNode(content);
pseudoNode.appendChild(text);
return [pseudoContainer, new TextContainer(text, pseudoContainer)];
}
};
NodeParser.prototype.getChildren = function(parentContainer) {
return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
}, this));
};
NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
container.cloneTo(stack);
var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
parentStack.contexts.push(stack);
container.stack = stack;
};
NodeParser.prototype.createStackingContexts = function() {
this.nodes.forEach(function(container) {
if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
this.newStackingContext(container, true);
} else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
this.newStackingContext(container, false);
} else {
container.assignStack(container.parent.stack);
}
}, this);
};
NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
};
NodeParser.prototype.isRootElement = function(container) {
return container.parent === null;
};
NodeParser.prototype.sortStackingContexts = function(stack) {
stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
stack.contexts.forEach(this.sortStackingContexts, this);
};
NodeParser.prototype.parseTextBounds = function(container) {
return function(text, index, textList) {
if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
if (this.support.rangeBounds && !container.parent.hasTransform()) {
var offset = textList.slice(0, index).join("").length;
return this.getRangeBounds(container.node, offset, text.length);
} else if (container.node && typeof(container.node.data) === "string") {
var replacementNode = container.node.splitText(text.length);
var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
container.node = replacementNode;
return bounds;
}
} else if(!this.support.rangeBounds || container.parent.hasTransform()){
container.node = container.node.splitText(text.length);
}
return {};
};
};
NodeParser.prototype.getWrapperBounds = function(node, transform) {
var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
var parent = node.parentNode,
backupText = node.cloneNode(true);
wrapper.appendChild(node.cloneNode(true));
parent.replaceChild(wrapper, node);
var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
parent.replaceChild(backupText, wrapper);
return bounds;
};
NodeParser.prototype.getRangeBounds = function(node, offset, length) {
var range = this.range || (this.range = node.ownerDocument.createRange());
range.setStart(node, offset);
range.setEnd(node, offset + length);
return range.getBoundingClientRect();
};
function ClearTransform() {}
NodeParser.prototype.parse = function(stack) {
// http://www.w3.org/TR/CSS21/visuren.html#z-index
var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
var descendantElements = stack.children.filter(isElement);
var descendantNonFloats = descendantElements.filter(not(isFloating));
var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
var text = stack.children.filter(isTextNode).filter(hasText);
var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
.concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
this.renderQueue.push(container);
if (isStackingContext(container)) {
this.parse(container);
this.renderQueue.push(new ClearTransform());
}
}, this);
};
NodeParser.prototype.paint = function(container) {
try {
if (container instanceof ClearTransform) {
this.renderer.ctx.restore();
} else if (isTextNode(container)) {
if (isPseudoElement(container.parent)) {
container.parent.appendToDOM();
}
this.paintText(container);
if (isPseudoElement(container.parent)) {
container.parent.cleanDOM();
}
} else {
this.paintNode(container);
}
} catch(e) {
log(e);
if (this.options.strict) {
throw e;
}
}
};
NodeParser.prototype.paintNode = function(container) {
if (isStackingContext(container)) {
this.renderer.setOpacity(container.opacity);
this.renderer.ctx.save();
if (container.hasTransform()) {
this.renderer.setTransform(container.parseTransform());
}
}
if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
this.paintCheckbox(container);
} else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
this.paintRadio(container);
} else {
this.paintElement(container);
}
};
NodeParser.prototype.paintElement = function(container) {
var bounds = container.parseBounds();
this.renderer.clip(container.backgroundClip, function() {
this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
}, this);
this.renderer.clip(container.clip, function() {
this.renderer.renderBorders(container.borders.borders);
}, this);
this.renderer.clip(container.backgroundClip, function() {
switch (container.node.nodeName) {
case "svg":
case "IFRAME":
var imgContainer = this.images.get(container.node);
if (imgContainer) {
this.renderer.renderImage(container, bounds, container.borders, imgContainer);
} else {
log("Error loading <" + container.node.nodeName + ">", container.node);
}
break;
case "IMG":
var imageContainer = this.images.get(container.node.src);
if (imageContainer) {
this.renderer.renderImage(container, bounds, container.borders, imageContainer);
} else {
log("Error loading <img>", container.node.src);
}
break;
case "CANVAS":
this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
break;
case "SELECT":
case "INPUT":
case "TEXTAREA":
this.paintFormValue(container);
break;
}
}, this);
};
NodeParser.prototype.paintCheckbox = function(container) {
var b = container.parseBounds();
var size = Math.min(b.width, b.height);
var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
var r = [3, 3];
var radius = [r, r, r, r];
var borders = [1,1,1,1].map(function(w) {
return {color: new Color('#A5A5A5'), width: w};
});
var borderPoints = calculateCurvePoints(bounds, radius, borders);
this.renderer.clip(container.backgroundClip, function() {
this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
if (container.node.checked) {
this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
}
}, this);
};
NodeParser.prototype.paintRadio = function(container) {
var bounds = container.parseBounds();
var size = Math.min(bounds.width, bounds.height) - 2;
this.renderer.clip(container.backgroundClip, function() {
this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
if (container.node.checked) {
this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
}
}, this);
};
NodeParser.prototype.paintFormValue = function(container) {
var value = container.getValue();
if (value.length > 0) {
var document = container.node.ownerDocument;
var wrapper = document.createElement('html2canvaswrapper');
var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
'boxSizing', 'whiteSpace', 'wordWrap'];
properties.forEach(function(property) {
try {
wrapper.style[property] = container.css(property);
} catch(e) {
// Older IE has issues with "border"
log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
}
});
var bounds = container.parseBounds();
wrapper.style.position = "fixed";
wrapper.style.left = bounds.left + "px";
wrapper.style.top = bounds.top + "px";
wrapper.textContent = value;
document.body.appendChild(wrapper);
this.paintText(new TextContainer(wrapper.firstChild, container));
document.body.removeChild(wrapper);
}
};
NodeParser.prototype.paintText = function(container) {
container.applyTextTransform();
var characters = window.html2canvas.punycode.ucs2.decode(container.node.data);
var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
return window.html2canvas.punycode.ucs2.encode([character]);
});
var weight = container.parent.fontWeight();
var size = container.parent.css('fontSize');
var family = container.parent.css('fontFamily');
var shadows = container.parent.parseTextShadows();
this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
if (shadows.length) {
// TODO: support multiple text shadows
this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
} else {
this.renderer.clearShadow();
}
this.renderer.clip(container.parent.clip, function() {
textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
if (bounds) {
this.renderer.text(textList[index], bounds.left, bounds.bottom);
this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
}
}, this);
}, this);
};
NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
switch(container.css("textDecoration").split(" ")[0]) {
case "underline":
// Draws a line at the baseline of the font
// TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
break;
case "overline":
this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
break;
case "line-through":
// TODO try and find exact position for line-through
this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
break;
}
};
var borderColorTransforms = {
inset: [
["darken", 0.60],
["darken", 0.10],
["darken", 0.10],
["darken", 0.60]
]
};
NodeParser.prototype.parseBorders = function(container) {
var nodeBounds = container.parseBounds();
var radius = getBorderRadiusData(container);
var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
var style = container.css('border' + side + 'Style');
var color = container.color('border' + side + 'Color');
if (style === "inset" && color.isBlack()) {
color = new Color([255, 255, 255, color.a]); // this is wrong, but
}
var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
return {
width: container.cssInt('border' + side + 'Width'),
color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
args: null
};
});
var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
return {
clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
};
};
function calculateBorders(borders, nodeBounds, borderPoints, radius) {
return borders.map(function(border, borderSide) {
if (border.width > 0) {
var bx = nodeBounds.left;
var by = nodeBounds.top;
var bw = nodeBounds.width;
var bh = nodeBounds.height - (borders[2].width);
switch(borderSide) {
case 0:
// top border
bh = borders[0].width;
border.args = drawSide({
c1: [bx, by],
c2: [bx + bw, by],
c3: [bx + bw - borders[1].width, by + bh],
c4: [bx + borders[3].width, by + bh]
}, radius[0], radius[1],
borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
break;
case 1:
// right border
bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
bw = borders[1].width;
border.args = drawSide({
c1: [bx + bw, by],
c2: [bx + bw, by + bh + borders[2].width],
c3: [bx, by + bh],
c4: [bx, by + borders[0].width]
}, radius[1], radius[2],
borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
break;
case 2:
// bottom border
by = (by + nodeBounds.height) - (borders[2].width);
bh = borders[2].width;
border.args = drawSide({
c1: [bx + bw, by + bh],
c2: [bx, by + bh],
c3: [bx + borders[3].width, by],
c4: [bx + bw - borders[3].width, by]
}, radius[2], radius[3],
borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
break;
case 3:
// left border
bw = borders[3].width;
border.args = drawSide({
c1: [bx, by + bh + borders[2].width],
c2: [bx, by],
c3: [bx + bw, by + borders[0].width],
c4: [bx + bw, by + bh]
}, radius[3], radius[0],
borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
break;
}
}
return border;
});
}
NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
var backgroundClip = container.css('backgroundClip'),
borderArgs = [];
switch(backgroundClip) {
case "content-box":
case "padding-box":
parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
break;
default:
parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
break;
}
return borderArgs;
};
function getCurvePoints(x, y, r1, r2) {
var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
var ox = (r1) * kappa, // control point offset horizontal
oy = (r2) * kappa, // control point offset vertical
xm = x + r1, // x-middle
ym = y + r2; // y-middle
return {
topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
};
}
function calculateCurvePoints(bounds, borderRadius, borders) {
var x = bounds.left,
y = bounds.top,
width = bounds.width,
height = bounds.height,
tlh = borderRadius[0][0],
tlv = borderRadius[0][1],
trh = borderRadius[1][0],
trv = borderRadius[1][1],
brh = borderRadius[2][0],
brv = borderRadius[2][1],
blh = borderRadius[3][0],
blv = borderRadius[3][1];
var topWidth = width - trh,
rightHeight = height - brv,
bottomWidth = width - brh,
leftHeight = height - blv;
return {
topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
};
}
function bezierCurve(start, startControl, endControl, end) {
var lerp = function (a, b, t) {
return {
x: a.x + (b.x - a.x) * t,
y: a.y + (b.y - a.y) * t
};
};
return {
start: start,
startControl: startControl,
endControl: endControl,
end: end,
subdivide: function(t) {
var ab = lerp(start, startControl, t),
bc = lerp(startControl, endControl, t),
cd = lerp(endControl, end, t),
abbc = lerp(ab, bc, t),
bccd = lerp(bc, cd, t),
dest = lerp(abbc, bccd, t);
return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
},
curveTo: function(borderArgs) {
borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
},
curveToReversed: function(borderArgs) {
borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
}
};
}
function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
var borderArgs = [];
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
outer1[1].curveTo(borderArgs);
} else {
borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
}
if (radius2[0] > 0 || radius2[1] > 0) {
borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
outer2[0].curveTo(borderArgs);
borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
inner2[0].curveToReversed(borderArgs);
} else {
borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
}
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
inner1[1].curveToReversed(borderArgs);
} else {
borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
}
return borderArgs;
}
function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
corner1[0].curveTo(borderArgs);
corner1[1].curveTo(borderArgs);
} else {
borderArgs.push(["line", x, y]);
}
if (radius2[0] > 0 || radius2[1] > 0) {
borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
}
}
function negativeZIndex(container) {
return container.cssInt("zIndex") < 0;
}
function positiveZIndex(container) {
return container.cssInt("zIndex") > 0;
}
function zIndex0(container) {
return container.cssInt("zIndex") === 0;
}
function inlineLevel(container) {
return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
}
function isStackingContext(container) {
return (container instanceof StackingContext);
}
function hasText(container) {
return container.node.data.trim().length > 0;
}
function noLetterSpacing(container) {
return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
}
function getBorderRadiusData(container) {
return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
var value = container.css('border' + side + 'Radius');
var arr = value.split(" ");
if (arr.length <= 1) {
arr[1] = arr[0];
}
return arr.map(asInt);
});
}
function renderableNode(node) {
return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
}
function isPositionedForStacking(container) {
var position = container.css("position");
var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
return zIndex !== "auto";
}
function isPositioned(container) {
return container.css("position") !== "static";
}
function isFloating(container) {
return container.css("float") !== "none";
}
function isInlineBlock(container) {
return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
}
function not(callback) {
var context = this;
return function() {
return !callback.apply(context, arguments);
};
}
function isElement(container) {
return container.node.nodeType === Node.ELEMENT_NODE;
}
function isPseudoElement(container) {
return container.isPseudoElement === true;
}
function isTextNode(container) {
return container.node.nodeType === Node.TEXT_NODE;
}
function zIndexSort(contexts) {
return function(a, b) {
return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
};
}
function hasOpacity(container) {
return container.getOpacity() < 1;
}
function bind(callback, context) {
return function() {
return callback.apply(context, arguments);
};
}
function asInt(value) {
return parseInt(value, 10);
}
function getWidth(border) {
return border.width;
}
function nonIgnoredElement(nodeContainer) {
return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
}
function flatten(arrays) {
return [].concat.apply([], arrays);
}
function stripQuotes(content) {
var first = content.substr(0, 1);
return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
}
function getWords(characters) {
var words = [], i = 0, onWordBoundary = false, word;
while(characters.length) {
if (isWordBoundary(characters[i]) === onWordBoundary) {
word = characters.splice(0, i);
if (word.length) {
words.push(window.html2canvas.punycode.ucs2.encode(word));
}
onWordBoundary =! onWordBoundary;
i = 0;
} else {
i++;
}
if (i >= characters.length) {
word = characters.splice(0, i);
if (word.length) {
words.push(window.html2canvas.punycode.ucs2.encode(word));
}
}
}
return words;
}
function isWordBoundary(characterCode) {
return [
32, // <space>
13, // \r
10, // \n
9, // \t
45 // -
].indexOf(characterCode) !== -1;
}
function hasUnicode(string) {
return (/[^\u0000-\u00ff]/).test(string);
}
function Proxy(src, proxyUrl, document) {
if (!proxyUrl) {
return Promise.reject("No proxy configured");
}
var callback = createCallback(supportsCORS);
var url = createProxyUrl(proxyUrl, src, callback);
return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
return decode64(response.content);
}));
}
var proxyCount = 0;
var supportsCORS = ('withCredentials' in new XMLHttpRequest());
var supportsCORSImage = ('crossOrigin' in new Image());
function ProxyURL(src, proxyUrl, document) {
var callback = createCallback(supportsCORSImage);
var url = createProxyUrl(proxyUrl, src, callback);
return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
return "data:" + response.type + ";base64," + response.content;
}));
}
function jsonp(document, url, callback) {
return new Promise(function(resolve, reject) {
var s = document.createElement("script");
var cleanup = function() {
delete window.html2canvas.proxy[callback];
document.body.removeChild(s);
};
window.html2canvas.proxy[callback] = function(response) {
cleanup();
resolve(response);
};
s.src = url;
s.onerror = function(e) {
cleanup();
reject(e);
};
document.body.appendChild(s);
});
}
function createCallback(useCORS) {
return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
}
function createProxyUrl(proxyUrl, src, callback) {
return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
}
function ProxyImageContainer(src, proxy) {
var script = document.createElement("script");
var link = document.createElement("a");
link.href = src;
src = link.href;
this.src = src;
this.image = new Image();
var self = this;
this.promise = new Promise(function(resolve, reject) {
self.image.crossOrigin = "Anonymous";
self.image.onload = resolve;
self.image.onerror = reject;
new ProxyURL(src, proxy, document).then(function(url) {
self.image.src = url;
})['catch'](reject);
});
}
function PseudoElementContainer(node, parent, type) {
NodeContainer.call(this, node, parent);
this.isPseudoElement = true;
this.before = type === ":before";
}
PseudoElementContainer.prototype.cloneTo = function(stack) {
PseudoElementContainer.prototype.cloneTo.call(this, stack);
stack.isPseudoElement = true;
stack.before = this.before;
};
PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
PseudoElementContainer.prototype.appendToDOM = function() {
if (this.before) {
this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
} else {
this.parent.node.appendChild(this.node);
}
this.parent.node.className += " " + this.getHideClass();
};
PseudoElementContainer.prototype.cleanDOM = function() {
this.node.parentNode.removeChild(this.node);
this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
};
PseudoElementContainer.prototype.getHideClass = function() {
return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
};
PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
function Renderer(width, height, images, options, document) {
this.width = width;
this.height = height;
this.images = images;
this.options = options;
this.document = document;
}
Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
var paddingLeft = container.cssInt('paddingLeft'),
paddingTop = container.cssInt('paddingTop'),
paddingRight = container.cssInt('paddingRight'),
paddingBottom = container.cssInt('paddingBottom'),
borders = borderData.borders;
var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
this.drawImage(
imageContainer,
0,
0,
imageContainer.image.width || width,
imageContainer.image.height || height,
bounds.left + paddingLeft + borders[3].width,
bounds.top + paddingTop + borders[0].width,
width,
height
);
};
Renderer.prototype.renderBackground = function(container, bounds, borderData) {
if (bounds.height > 0 && bounds.width > 0) {
this.renderBackgroundColor(container, bounds);
this.renderBackgroundImage(container, bounds, borderData);
}
};
Renderer.prototype.renderBackgroundColor = function(container, bounds) {
var color = container.color("backgroundColor");
if (!color.isTransparent()) {
this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
}
};
Renderer.prototype.renderBorders = function(borders) {
borders.forEach(this.renderBorder, this);
};
Renderer.prototype.renderBorder = function(data) {
if (!data.color.isTransparent() && data.args !== null) {
this.drawShape(data.args, data.color);
}
};
Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
var backgroundImages = container.parseBackgroundImages();
backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
switch(backgroundImage.method) {
case "url":
var image = this.images.get(backgroundImage.args[0]);
if (image) {
this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
} else {
log("Error loading background-image", backgroundImage.args[0]);
}
break;
case "linear-gradient":
case "gradient":
var gradientImage = this.images.get(backgroundImage.value);
if (gradientImage) {
this.renderBackgroundGradient(gradientImage, bounds, borderData);
} else {
log("Error loading background-image", backgroundImage.args[0]);
}
break;
case "none":
break;
default:
log("Unknown background-image type", backgroundImage.args[0]);
}
}, this);
};
Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
var repeat = container.parseBackgroundRepeat(index);
switch (repeat) {
case "repeat-x":
case "repeat no-repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
break;
case "repeat-y":
case "no-repeat repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
break;
case "no-repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
break;
default:
this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
break;
}
};
function StackingContext(hasOwnStacking, opacity, element, parent) {
NodeContainer.call(this, element, parent);
this.ownStacking = hasOwnStacking;
this.contexts = [];
this.children = [];
this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
}
StackingContext.prototype = Object.create(NodeContainer.prototype);
StackingContext.prototype.getParentStack = function(context) {
var parentStack = (this.parent) ? this.parent.stack : null;
return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
};
function Support(document) {
this.rangeBounds = this.testRangeBounds(document);
this.cors = this.testCORS();
this.svg = this.testSVG();
}
Support.prototype.testRangeBounds = function(document) {
var range, testElement, rangeBounds, rangeHeight, support = false;
if (document.createRange) {
range = document.createRange();
if (range.getBoundingClientRect) {
testElement = document.createElement('boundtest');
testElement.style.height = "123px";
testElement.style.display = "block";
document.body.appendChild(testElement);
range.selectNode(testElement);
rangeBounds = range.getBoundingClientRect();
rangeHeight = rangeBounds.height;
if (rangeHeight === 123) {
support = true;
}
document.body.removeChild(testElement);
}
}
return support;
};
Support.prototype.testCORS = function() {
return typeof((new Image()).crossOrigin) !== "undefined";
};
Support.prototype.testSVG = function() {
var img = new Image();
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
try {
ctx.drawImage(img, 0, 0);
canvas.toDataURL();
} catch(e) {
return false;
}
return true;
};
function SVGContainer(src) {
this.src = src;
this.image = null;
var self = this;
this.promise = this.hasFabric().then(function() {
return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
}).then(function(svg) {
return new Promise(function(resolve) {
html2canvas.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
});
});
}
SVGContainer.prototype.hasFabric = function() {
return !html2canvas.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
};
SVGContainer.prototype.inlineFormatting = function(src) {
return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
};
SVGContainer.prototype.removeContentType = function(src) {
return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
};
SVGContainer.prototype.isInline = function(src) {
return (/^data:image\/svg\+xml/i.test(src));
};
SVGContainer.prototype.createCanvas = function(resolve) {
var self = this;
return function (objects, options) {
var canvas = new html2canvas.fabric.StaticCanvas('c');
self.image = canvas.lowerCanvasEl;
canvas
.setWidth(options.width)
.setHeight(options.height)
.add(html2canvas.fabric.util.groupSVGElements(objects, options))
.renderAll();
resolve(canvas.lowerCanvasEl);
};
};
SVGContainer.prototype.decode64 = function(str) {
return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
};
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
function decode64(base64) {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
var output = "";
for (i = 0; i < len; i+=4) {
encoded1 = chars.indexOf(base64[i]);
encoded2 = chars.indexOf(base64[i+1]);
encoded3 = chars.indexOf(base64[i+2]);
encoded4 = chars.indexOf(base64[i+3]);
byte1 = (encoded1 << 2) | (encoded2 >> 4);
byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
byte3 = ((encoded3 & 3) << 6) | encoded4;
if (encoded3 === 64) {
output += String.fromCharCode(byte1);
} else if (encoded4 === 64 || encoded4 === -1) {
output += String.fromCharCode(byte1, byte2);
} else{
output += String.fromCharCode(byte1, byte2, byte3);
}
}
return output;
}
function SVGNodeContainer(node, native) {
this.src = node;
this.image = null;
var self = this;
this.promise = native ? new Promise(function(resolve, reject) {
self.image = new Image();
self.image.onload = resolve;
self.image.onerror = reject;
self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
if (self.image.complete === true) {
resolve(self.image);
}
}) : this.hasFabric().then(function() {
return new Promise(function(resolve) {
html2canvas.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
});
});
}
SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
function TextContainer(node, parent) {
NodeContainer.call(this, node, parent);
}
TextContainer.prototype = Object.create(NodeContainer.prototype);
TextContainer.prototype.applyTextTransform = function() {
this.node.data = this.transform(this.parent.css("textTransform"));
};
TextContainer.prototype.transform = function(transform) {
var text = this.node.data;
switch(transform){
case "lowercase":
return text.toLowerCase();
case "capitalize":
return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
case "uppercase":
return text.toUpperCase();
default:
return text;
}
};
function capitalize(m, p1, p2) {
if (m.length > 0) {
return p1 + p2.toUpperCase();
}
}
function WebkitGradientContainer(imageData) {
GradientContainer.apply(this, arguments);
this.type = (imageData.args[0] === "linear") ? this.TYPES.LINEAR : this.TYPES.RADIAL;
}
WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
function XHR(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = function() {
reject(new Error("Network Error"));
};
xhr.send();
});
}
function CanvasRenderer(width, height) {
Renderer.apply(this, arguments);
this.canvas = this.options.canvas || this.document.createElement("canvas");
if (!this.options.canvas) {
this.canvas.width = width;
this.canvas.height = height;
}
this.ctx = this.canvas.getContext("2d");
this.taintCtx = this.document.createElement("canvas").getContext("2d");
this.ctx.textBaseline = "bottom";
this.variables = {};
log("Initialized CanvasRenderer with size", width, "x", height);
}
CanvasRenderer.prototype = Object.create(Renderer.prototype);
CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
return this.ctx;
};
CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
this.setFillStyle(color).fillRect(left, top, width, height);
};
CanvasRenderer.prototype.circle = function(left, top, size, color) {
this.setFillStyle(color);
this.ctx.beginPath();
this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
this.ctx.closePath();
this.ctx.fill();
};
CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
this.circle(left, top, size, color);
this.ctx.strokeStyle = strokeColor.toString();
this.ctx.stroke();
};
CanvasRenderer.prototype.drawShape = function(shape, color) {
this.shape(shape);
this.setFillStyle(color).fill();
};
CanvasRenderer.prototype.taints = function(imageContainer) {
if (imageContainer.tainted === null) {
this.taintCtx.drawImage(imageContainer.image, 0, 0);
try {
this.taintCtx.getImageData(0, 0, 1, 1);
imageContainer.tainted = false;
} catch(e) {
this.taintCtx = document.createElement("canvas").getContext("2d");
imageContainer.tainted = true;
}
}
return imageContainer.tainted;
};
CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
if (!this.taints(imageContainer) || this.options.allowTaint) {
this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
}
};
CanvasRenderer.prototype.clip = function(shapes, callback, context) {
this.ctx.save();
shapes.filter(hasEntries).forEach(function(shape) {
this.shape(shape).clip();
}, this);
callback.call(context);
this.ctx.restore();
};
CanvasRenderer.prototype.shape = function(shape) {
this.ctx.beginPath();
shape.forEach(function(point, index) {
if (point[0] === "rect") {
this.ctx.rect.apply(this.ctx, point.slice(1));
} else {
this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
}
}, this);
this.ctx.closePath();
return this.ctx;
};
CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
};
CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
this.setVariable("shadowColor", color.toString())
.setVariable("shadowOffsetY", offsetX)
.setVariable("shadowOffsetX", offsetY)
.setVariable("shadowBlur", blur);
};
CanvasRenderer.prototype.clearShadow = function() {
this.setVariable("shadowColor", "rgba(0,0,0,0)");
};
CanvasRenderer.prototype.setOpacity = function(opacity) {
this.ctx.globalAlpha = opacity;
};
CanvasRenderer.prototype.setTransform = function(transform) {
this.ctx.translate(transform.origin[0], transform.origin[1]);
this.ctx.transform.apply(this.ctx, transform.matrix);
this.ctx.translate(-transform.origin[0], -transform.origin[1]);
};
CanvasRenderer.prototype.setVariable = function(property, value) {
if (this.variables[property] !== value) {
this.variables[property] = this.ctx[property] = value;
}
return this;
};
CanvasRenderer.prototype.text = function(text, left, bottom) {
this.ctx.fillText(text, left, bottom);
};
CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
var shape = [
["line", Math.round(left), Math.round(top)],
["line", Math.round(left + width), Math.round(top)],
["line", Math.round(left + width), Math.round(height + top)],
["line", Math.round(left), Math.round(height + top)]
];
this.clip([shape], function() {
this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
}, this);
};
CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
this.ctx.translate(offsetX, offsetY);
this.ctx.fill();
this.ctx.translate(-offsetX, -offsetY);
};
CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
if (gradientImage instanceof LinearGradientContainer) {
var gradient = this.ctx.createLinearGradient(
bounds.left + bounds.width * gradientImage.x0,
bounds.top + bounds.height * gradientImage.y0,
bounds.left + bounds.width * gradientImage.x1,
bounds.top + bounds.height * gradientImage.y1);
gradientImage.colorStops.forEach(function(colorStop) {
gradient.addColorStop(colorStop.stop, colorStop.color.toString());
});
this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
}
};
CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
var image = imageContainer.image;
if(image.width === size.width && image.height === size.height) {
return image;
}
var ctx, canvas = document.createElement('canvas');
canvas.width = size.width;
canvas.height = size.height;
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
return canvas;
};
function hasEntries(array) {
return array.length > 0;
}
}).call({}, typeof(window) !== "undefined" ? window : undefined, typeof(document) !== "undefined" ? document : undefined);
| tttor/csipb-jamu-prj | webserver/src/assets/js/h2c/html2canvas.js | JavaScript | mit | 123,760 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _moment = require('moment');
var _moment2 = _interopRequireDefault(_moment);
var _en_US = require('rc-pagination/lib/locale/en_US');
var _en_US2 = _interopRequireDefault(_en_US);
var _en_US3 = require('../date-picker/locale/en_US');
var _en_US4 = _interopRequireDefault(_en_US3);
var _en_US5 = require('../time-picker/locale/en_US');
var _en_US6 = _interopRequireDefault(_en_US5);
var _en_US7 = require('../calendar/locale/en_US');
var _en_US8 = _interopRequireDefault(_en_US7);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
_moment2['default'].locale('en');
exports['default'] = {
locale: 'en',
Pagination: _en_US2['default'],
DatePicker: _en_US4['default'],
TimePicker: _en_US6['default'],
Calendar: _en_US8['default'],
Table: {
filterTitle: 'Filter menu',
filterConfirm: 'OK',
filterReset: 'Reset',
emptyText: 'No data',
selectAll: 'Select current page',
selectInvert: 'Invert current page'
},
Modal: {
okText: 'OK',
cancelText: 'Cancel',
justOkText: 'OK'
},
Popconfirm: {
okText: 'OK',
cancelText: 'Cancel'
},
Transfer: {
notFoundContent: 'Not Found',
searchPlaceholder: 'Search here',
itemUnit: 'item',
itemsUnit: 'items'
},
Select: {
notFoundContent: 'Not Found'
},
Upload: {
uploading: 'Uploading...',
removeFile: 'Remove file',
uploadError: 'Upload error',
previewFile: 'Preview file'
}
};
module.exports = exports['default']; | yhx0634/foodshopfront | node_modules/antd/lib/locale-provider/en_US.js | JavaScript | mit | 1,712 |
;(function(){
// CommonJS require()
function require(p){
var path = require.resolve(p)
, mod = require.modules[path];
if (!mod) throw new Error('failed to require "' + p + '"');
if (!mod.exports) {
mod.exports = {};
mod.call(mod.exports, mod, mod.exports, require.relative(path));
}
return mod.exports;
}
require.modules = {};
require.resolve = function (path){
var orig = path
, reg = path + '.js'
, index = path + '/index.js';
return require.modules[reg] && reg
|| require.modules[index] && index
|| orig;
};
require.register = function (path, fn){
require.modules[path] = fn;
};
require.relative = function (parent) {
return function(p){
if ('.' != p.charAt(0)) return require(p);
var path = parent.split('/')
, segs = p.split('/');
path.pop();
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
if ('..' == seg) path.pop();
else if ('.' != seg) path.push(seg);
}
return require(path.join('/'));
};
};
require.register("browser/debug.js", function(module, exports, require){
module.exports = function(type){
return function(){
}
};
}); // module: browser/debug.js
require.register("browser/diff.js", function(module, exports, require){
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
var JsDiff = (function() {
/*jshint maxparams: 5*/
function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) };
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&');
n = n.replace(/</g, '<');
n = n.replace(/>/g, '>');
n = n.replace(/"/g, '"');
return n;
}
var Diff = function(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
};
Diff.prototype = {
diff: function(oldString, newString) {
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return [{ value: newString }];
}
if (!newString) {
return [{ value: oldString, removed: true }];
}
if (!oldString) {
return [{ value: newString, added: true }];
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }];
// Seed editLength = 0
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
return bestPath[0].components;
}
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
var basePath;
var addPath = bestPath[diagonalPath-1],
removePath = bestPath[diagonalPath+1];
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined;
}
var canAdd = addPath && addPath.newPos+1 < newLen;
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
} else {
basePath = clonePath(addPath);
basePath.newPos++;
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
}
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
return basePath.components;
} else {
bestPath[diagonalPath] = basePath;
}
}
}
},
pushComponent: function(components, value, added, removed) {
var last = components[components.length-1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length-1] =
{value: this.join(last.value, value), added: added, removed: removed };
} else {
components.push({value: value, added: added, removed: removed });
}
},
extractCommon: function(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
newPos++;
oldPos++;
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
}
basePath.newPos = newPos;
return oldPos;
},
equals: function(left, right) {
var reWhitespace = /\S/;
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
return true;
} else {
return left === right;
}
},
join: function(left, right) {
return left + right;
},
tokenize: function(value) {
return value;
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
LineDiff.tokenize = function(value) {
var retLines = [],
lines = value.split(/^/m);
for(var i = 0; i < lines.length; i++) {
var line = lines[i],
lastLine = lines[i - 1];
// Merge lines that may contain windows new lines
if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') {
retLines[retLines.length - 1] += '\n';
} else if (line) {
retLines.push(line);
}
}
return retLines;
};
return {
Diff: Diff,
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
ret.push('Index: ' + fileName);
ret.push('===================================================================');
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
}
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
function contextLines(lines) {
return lines.map(function(entry) { return ' ' + entry; });
}
function eofNL(curRange, i, current) {
var last = diff[diff.length-2],
isLast = i === diff.length-2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
// Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
var prev = diff[i-1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; }));
eofNL(curRange, i, current);
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0; newRangeStart = 0; curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
applyPatch: function(oldStr, uniDiff) {
var diffstr = uniDiff.split('\n');
var diff = [];
var remEOFNL = false,
addEOFNL = false;
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
if(diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({
start:meh[3],
oldlength:meh[2],
oldlines:[],
newlength:meh[4],
newlines:[]
});
} else if(diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') {
remEOFNL = true;
} else if(diffstr[i-1][0] === '-') {
addEOFNL = true;
}
}
}
var str = oldStr.split('\n');
for (var i = diff.length - 1; i >= 0; i--) {
var d = diff[i];
for (var j = 0; j < d.oldlength; j++) {
if(str[d.start-1+j] !== d.oldlines[j]) {
return false;
}
}
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
}
if (remEOFNL) {
while (!str[str.length-1]) {
str.pop();
}
} else if (addEOFNL) {
str.push('');
}
return str.join('\n');
},
convertChangesToXML: function(changes){
var ret = [];
for ( var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) | wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/should/node_modules/vinyl-source-stream2/node_modules/vinyl-map/node_modules/gulp/node_modules/vinyl-fs/node_modules/glob-stream/node_modules/unique-stream/node_modules/mocha/mocha.js | JavaScript | mit | 13,312 |
module.exports = require('./lib/knox'); | heroku/vulcan | server/node_modules/knox/index.js | JavaScript | mit | 40 |
//>>built
define("dijit/tree/_dndSelector",["dojo/_base/array","dojo/_base/connect","dojo/_base/declare","dojo/_base/Deferred","dojo/_base/kernel","dojo/_base/lang","dojo/cookie","dojo/mouse","dojo/on","dojo/touch","./_dndContainer"],function(_1,_2,_3,_4,_5,_6,_7,_8,on,_9,_a){
return _3("dijit.tree._dndSelector",_a,{constructor:function(){
this.selection={};
this.anchor=null;
if(!this.cookieName&&this.tree.id){
this.cookieName=this.tree.id+"SaveSelectedCookie";
}
this.events.push(on(this.tree.domNode,_9.press,_6.hitch(this,"onMouseDown")),on(this.tree.domNode,_9.release,_6.hitch(this,"onMouseUp")),on(this.tree.domNode,_9.move,_6.hitch(this,"onMouseMove")));
},singular:false,getSelectedTreeNodes:function(){
var _b=[],_c=this.selection;
for(var i in _c){
_b.push(_c[i]);
}
return _b;
},selectNone:function(){
this.setSelection([]);
return this;
},destroy:function(){
this.inherited(arguments);
this.selection=this.anchor=null;
},addTreeNode:function(_d,_e){
this.setSelection(this.getSelectedTreeNodes().concat([_d]));
if(_e){
this.anchor=_d;
}
return _d;
},removeTreeNode:function(_f){
this.setSelection(this._setDifference(this.getSelectedTreeNodes(),[_f]));
return _f;
},isTreeNodeSelected:function(_10){
return _10.id&&!!this.selection[_10.id];
},setSelection:function(_11){
var _12=this.getSelectedTreeNodes();
_1.forEach(this._setDifference(_12,_11),_6.hitch(this,function(_13){
_13.setSelected(false);
if(this.anchor==_13){
delete this.anchor;
}
delete this.selection[_13.id];
}));
_1.forEach(this._setDifference(_11,_12),_6.hitch(this,function(_14){
_14.setSelected(true);
this.selection[_14.id]=_14;
}));
this._updateSelectionProperties();
},_setDifference:function(xs,ys){
_1.forEach(ys,function(y){
y.__exclude__=true;
});
var ret=_1.filter(xs,function(x){
return !x.__exclude__;
});
_1.forEach(ys,function(y){
delete y["__exclude__"];
});
return ret;
},_updateSelectionProperties:function(){
var _15=this.getSelectedTreeNodes();
var _16=[],_17=[],_18=[];
_1.forEach(_15,function(_19){
var ary=_19.getTreePath(),_1a=this.tree.model;
_17.push(_19);
_16.push(ary);
ary=_1.map(ary,function(_1b){
return _1a.getIdentity(_1b);
},this);
_18.push(ary.join("/"));
},this);
var _1c=_1.map(_17,function(_1d){
return _1d.item;
});
this.tree._set("paths",_16);
this.tree._set("path",_16[0]||[]);
this.tree._set("selectedNodes",_17);
this.tree._set("selectedNode",_17[0]||null);
this.tree._set("selectedItems",_1c);
this.tree._set("selectedItem",_1c[0]||null);
if(this.tree.persist&&_18.length>0){
_7(this.cookieName,_18.join(","),{expires:365});
}
},_getSavedPaths:function(){
var _1e=this.tree;
if(_1e.persist&&_1e.dndController.cookieName){
var _1f,_20=[];
_1f=_7(_1e.dndController.cookieName);
if(_1f){
_20=_1.map(_1f.split(","),function(_21){
return _21.split("/");
});
}
return _20;
}
},onMouseDown:function(e){
if(!this.current||this.tree.isExpandoNode(e.target,this.current)){
return;
}
if(e.type!="touchstart"&&!_8.isLeft(e)){
return;
}
var _22=this.current,_23=_2.isCopyKey(e),id=_22.id;
if(!this.singular&&!e.shiftKey&&this.selection[id]){
this._doDeselect=true;
return;
}else{
this._doDeselect=false;
}
this.userSelect(_22,_23,e.shiftKey);
},onMouseUp:function(e){
if(!this._doDeselect){
return;
}
this._doDeselect=false;
this.userSelect(this.current,_2.isCopyKey(e),e.shiftKey);
},onMouseMove:function(){
this._doDeselect=false;
},_compareNodes:function(n1,n2){
if(n1===n2){
return 0;
}
if("sourceIndex" in document.documentElement){
return n1.sourceIndex-n2.sourceIndex;
}else{
if("compareDocumentPosition" in document.documentElement){
return n1.compareDocumentPosition(n2)&2?1:-1;
}else{
if(document.createRange){
var r1=doc.createRange();
r1.setStartBefore(n1);
var r2=doc.createRange();
r2.setStartBefore(n2);
return r1.compareBoundaryPoints(r1.END_TO_END,r2);
}else{
throw Error("dijit.tree._compareNodes don't know how to compare two different nodes in this browser");
}
}
}
},userSelect:function(_24,_25,_26){
if(this.singular){
if(this.anchor==_24&&_25){
this.selectNone();
}else{
this.setSelection([_24]);
this.anchor=_24;
}
}else{
if(_26&&this.anchor){
var cr=this._compareNodes(this.anchor.rowNode,_24.rowNode),_27,end,_28=this.anchor;
if(cr<0){
_27=_28;
end=_24;
}else{
_27=_24;
end=_28;
}
var _29=[];
while(_27!=end){
_29.push(_27);
_27=this.tree._getNextNode(_27);
}
_29.push(end);
this.setSelection(_29);
}else{
if(this.selection[_24.id]&&_25){
this.removeTreeNode(_24);
}else{
if(_25){
this.addTreeNode(_24,true);
}else{
this.setSelection([_24]);
this.anchor=_24;
}
}
}
}
},getItem:function(key){
var _2a=this.selection[key];
return {data:_2a,type:["treeNode"]};
},forInSelectedItems:function(f,o){
o=o||_5.global;
for(var id in this.selection){
f.call(o,this.getItem(id),id,this);
}
}});
});
| niug/DirClia | web/dojo/dijit/tree/_dndSelector.js | JavaScript | mit | 4,729 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/solarized_dark', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-solarized-dark";
exports.cssText = ".ace-solarized-dark .ace_editor {\
border: 2px solid rgb(159, 159, 159)\
}\
\
.ace-solarized-dark .ace_editor.ace_focus {\
border: 2px solid #327fbd\
}\
\
.ace-solarized-dark .ace_gutter {\
background: #01313f;\
color: #d0edf7\
}\
\
.ace-solarized-dark .ace_print_margin {\
width: 1px;\
background: #33555E\
}\
\
.ace-solarized-dark .ace_scroller {\
background-color: #002B36\
}\
\
.ace-solarized-dark .ace_entity.ace_other.ace_attribute-name,\
.ace-solarized-dark .ace_storage,\
.ace-solarized-dark .ace_text-layer {\
color: #93A1A1\
}\
\
.ace-solarized-dark .ace_cursor {\
border-left: 2px solid #D30102\
}\
\
.ace-solarized-dark .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #D30102\
}\
\
.ace-solarized-dark .ace_marker-layer .ace_active_line,\
.ace-solarized-dark .ace_marker-layer .ace_selection {\
background: rgba(255, 255, 255, 0.1)\
}\
\
.ace-solarized-dark.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #002B36;\
border-radius: 2px\
}\
\
.ace-solarized-dark .ace_marker-layer .ace_step {\
background: rgb(102, 82, 0)\
}\
\
.ace-solarized-dark .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgba(147, 161, 161, 0.50)\
}\
\
.ace-solarized-dark .ace_gutter_active_line {\
background-color: #0d3440\
}\
\
.ace-solarized-dark .ace_marker-layer .ace_selected_word {\
border: 1px solid #073642\
}\
\
.ace-solarized-dark .ace_invisible {\
color: rgba(147, 161, 161, 0.50)\
}\
\
.ace-solarized-dark .ace_keyword,\
.ace-solarized-dark .ace_meta,\
.ace-solarized-dark .ace_support.ace_class,\
.ace-solarized-dark .ace_support.ace_type {\
color: #859900\
}\
\
.ace-solarized-dark .ace_constant.ace_character,\
.ace-solarized-dark .ace_constant.ace_other {\
color: #CB4B16\
}\
\
.ace-solarized-dark .ace_constant.ace_language {\
color: #B58900\
}\
\
.ace-solarized-dark .ace_constant.ace_numeric {\
color: #D33682\
}\
\
.ace-solarized-dark .ace_fold {\
background-color: #268BD2;\
border-color: #93A1A1\
}\
\
.ace-solarized-dark .ace_entity.ace_name.ace_function,\
.ace-solarized-dark .ace_entity.ace_name.ace_tag,\
.ace-solarized-dark .ace_support.ace_function,\
.ace-solarized-dark .ace_variable,\
.ace-solarized-dark .ace_variable.ace_language {\
color: #268BD2\
}\
\
.ace-solarized-dark .ace_string {\
color: #2AA198\
}\
\
.ace-solarized-dark .ace_string.ace_regexp {\
color: #D30102\
}\
\
.ace-solarized-dark .ace_comment {\
font-style: italic;\
color: #657B83\
}\
\
.ace-solarized-dark .ace_markup.ace_underline {\
text-decoration: underline\
}\
\
.ace-solarized-dark .ace_indent-guide {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWNg0Db7zzBz5sz/AA82BCv7wOIDAAAAAElFTkSuQmCC) right repeat-y\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
| darwin/terraform | src/editor/ace/theme-solarized_dark.js | JavaScript | mit | 4,766 |
var ContactUs = function () {
return {
//main function to initiate the module
init: function () {
var map;
$(document).ready(function(){
map = new GMaps({
div: '#map',
lat: -13.004333,
lng: -38.494333,
});
var marker = map.addMarker({
lat: -13.004333,
lng: -38.494333,
title: 'Loop, Inc.',
infoWindow: {
content: "<b>Loop, Inc.</b> 795 Park Ave, Suite 120<br>San Francisco, CA 94107"
}
});
marker.infoWindow.open(map, marker);
});
}
};
}(); | EssamKhaled/es-blog | web/bundles/layout/Frontend/assets/scripts/contact-us.js | JavaScript | mit | 642 |
/*
My Profile link: https://app.roll20.net/users/262130/dxwarlock
GIT link: https://github.com/dxwarlock/Roll20/blob/master/Public/HeathColors
Roll20Link: https://app.roll20.net/forum/post/4630083/script-aura-slash-tint-healthcolor
Last Updated 2/27/2017
*/
/*global createObj getAttrByName spawnFxWithDefinition getObj state playerIsGM sendChat _ findObjs log on*/
var HealthColors = HealthColors || (function() {
'use strict';
var version = '1.2.0',
ScriptName = "HealthColors",
schemaVersion = '1.0.3',
Updated = "Feb 27 2017",
/*--------
ON TOKEN UPDATE
--------*/
handleToken = function(obj, prev) {
var ColorOn = state.HealthColors.auraColorOn;
var bar = state.HealthColors.auraBar;
var tint = state.HealthColors.auraTint;
var onPerc = state.HealthColors.auraPerc;
var dead = state.HealthColors.auraDead;
if (obj.get("represents") !== "" || (obj.get("represents") == "" && state.HealthColors.OneOff == true)) {
if (ColorOn !== true) return; //Check Toggle
//ATTRIBUTE CHECK------------
var oCharacter = getObj('character', obj.get("_represents"));
if (oCharacter !== undefined) {
//SET BLOOD ATTRIB------------
if (getAttrByName(oCharacter.id, 'BLOODCOLOR') === undefined) CreateAttrib(oCharacter, 'BLOODCOLOR', 'DEFAULT');
var Blood = findObjs({name: 'BLOODCOLOR',_type: "attribute",characterid: oCharacter.id}, {caseInsensitive: true})[0];
var UseBlood = Blood.get("current");
UseBlood = UseBlood.toString().toUpperCase();
//SET DISABLED AURA/TINT ATTRIB------------
if (getAttrByName(oCharacter.id, 'USECOLOR') === undefined) CreateAttrib(oCharacter, 'USECOLOR', 'YES');
var UseAuraAtt = findObjs({name: "USECOLOR",_type: "attribute",characterid: oCharacter.id}, {caseInsensitive: true})[0];
var UseAura = UseAuraAtt.get("current");
UseAura = UseAura.toString().toUpperCase();
//DISABLE OR ENABLE AURA/TINT ON TOKEN------------
if (UseAura != "YES" && UseAura != "NO") {
UseAuraAtt.set('current', "YES");
var name = oCharacter.get('name');
GMW(name + ": USECOLOR NOT SET TO YES or NO, SETTING TO YES");
}
UseAura = UseAuraAtt.get("current").toUpperCase();
if (UseAura == "NO") return;
}
//CHECK BARS------------
if (obj.get(bar + "_max") === "" || obj.get(bar + "_value") === "") return;
var maxValue = parseInt(obj.get(bar + "_max"), 10);
var curValue = parseInt(obj.get(bar + "_value"), 10);
var prevValue = prev[bar + "_value"];
if (isNaN(maxValue) && isNaN(curValue)) return;
//CALC PERCENTAGE------------
var perc = Math.round((curValue / maxValue) * 100);
var percReal = Math.min(100, perc);
//PERCENTAGE OFF------------
if (percReal > onPerc) {
SetAuraNone(obj);
return;
}
//SET DEAD------------
if (curValue <= 0 && dead === true) {
obj.set("status_dead", true);
SetAuraNone(obj);
if (state.HealthColors.auraDeadFX !== "None") PlayDeath(state.HealthColors.auraDeadFX);
return;
}
else if (dead === true) obj.set("status_dead", false);
//CHECK MONSTER OR PLAYER------------
var type = (oCharacter === undefined || oCharacter.get("controlledby") === "") ? 'Monster' : 'Player';
//IF PLAYER------------
var GM = '', PC = '';
var markerColor = PercentToRGB(Math.min(100, percReal));
var pColor = '#ffffff';
if (type == 'Player') {
if (state.HealthColors.PCAura === false) return;
var cBy = oCharacter.get('controlledby');
var player = getObj('player', cBy);
pColor = '#000000';
if (player !== undefined) pColor = player.get('color');
GM = state.HealthColors.GM_PCNames;
if (GM != 'Off') {
GM = (GM == "Yes") ? true : false;
obj.set({'showname': GM});
}
PC = state.HealthColors.PCNames;
if (PC != 'Off') {
PC = (PC == "Yes") ? true : false;
obj.set({'showplayers_name': PC});
}
}
//IF MONSTER------------
if (type == 'Monster') {
if (state.HealthColors.NPCAura === false) return;
GM = state.HealthColors.GM_NPCNames;
if (GM != 'Off') {
GM = (GM == "Yes") ? true : false;
obj.set({'showname': GM});
}
PC = state.HealthColors.NPCNames;
if (PC != 'Off') {
PC = (PC == "Yes") ? true : false;
obj.set({'showplayers_name': PC});
}
}
//SET AURA|TINT------------
if (tint === true) obj.set({'tint_color': markerColor,});
else {
TokenSet(obj, state.HealthColors.AuraSize, markerColor, pColor);
}
//SPURT FX------------
if (state.HealthColors.FX == true && obj.get("layer") == "objects" && UseBlood !== "OFF") {
if (curValue == prevValue || prevValue == "") return;
var amount = Math.abs(curValue - prevValue);
var HitSizeCalc = Math.min((amount / maxValue) * 4, 1);
var HitSize = Math.max(HitSizeCalc, 0.2) * (_.random(60, 100) / 100);
var HealColor = HEXtoRGB(state.HealthColors.HealFX);
var HurtColor = HEXtoRGB(state.HealthColors.HurtFX);
if (UseBlood !== "DEFAULT") HurtColor = HEXtoRGB(UseBlood);
var size = obj.get("height");
var multi = size / 70;
var StartColor;
var EndColor;
var HITS;
if (curValue > prevValue && prevValue !== "") {
StartColor = HealColor;
EndColor = [255, 255, 255, 0];
HITS = Heal(HitSize, multi, StartColor, EndColor, size);
}
else {
StartColor = HurtColor;
EndColor = [0, 0, 0, 0];
HITS = Hurt(HitSize, multi, StartColor, EndColor, size);
}
spawnFxWithDefinition(obj.get("left"), obj.get("top"), HITS, obj.get("_pageid"));
}
}
},
/*--------
CHAT MESSAGES
--------*/
handleInput = function(msg) {
var msgFormula = msg.content.split(/\s+/);
var command = msgFormula[0].toUpperCase();
if (msg.type == "api" && command.indexOf("!AURA") !== -1) {
if (!playerIsGM(msg.playerid)) {
sendChat('HealthColors', "/w " + msg.who + " you must be a GM to use this command!");
return;
}
else {
var option = msgFormula[1];
if (option === undefined) {
aurahelp();
return;
}
switch (msgFormula[1].toUpperCase()) {
case "ON":
state.HealthColors.auraColorOn = !state.HealthColors.auraColorOn;
aurahelp();
break;
case "BAR":
state.HealthColors.auraBar = "bar" + msgFormula[2];
aurahelp();
break;
case "TINT":
state.HealthColors.auraTint = !state.HealthColors.auraTint;
aurahelp();
break;
case "PERC":
state.HealthColors.auraPerc = parseInt(msgFormula[2], 10);
aurahelp();
break;
case "PC":
state.HealthColors.PCAura = !state.HealthColors.PCAura;
aurahelp();
break;
case "NPC":
state.HealthColors.NPCAura = !state.HealthColors.NPCAura;
aurahelp();
break;
case "GMNPC":
state.HealthColors.GM_NPCNames = msgFormula[2];
aurahelp();
break;
case "GMPC":
state.HealthColors.GM_PCNames = msgFormula[2];
aurahelp();
break;
case "PCNPC":
state.HealthColors.NPCNames = msgFormula[2];
aurahelp();
break;
case "PCPC":
state.HealthColors.PCNames = msgFormula[2];
aurahelp();
break;
case "DEAD":
state.HealthColors.auraDead = !state.HealthColors.auraDead;
aurahelp();
break;
case "DEADFX":
state.HealthColors.auraDeadFX = msgFormula[2];
aurahelp();
break;
case "SIZE":
state.HealthColors.AuraSize = parseFloat(msgFormula[2]);
aurahelp();
break;
case "ONEOFF":
state.HealthColors.OneOff = !state.HealthColors.OneOff;
aurahelp();
break;
case "FX":
state.HealthColors.FX = !state.HealthColors.FX;
aurahelp();
break;
case "HEAL":
var UPPER = msgFormula[2];
UPPER = UPPER.toUpperCase();
state.HealthColors.HealFX = UPPER;
aurahelp();
break;
case "HURT":
var UPPER = msgFormula[2];
UPPER = UPPER.toUpperCase();
state.HealthColors.HurtFX = UPPER;
aurahelp();
break;
default:
return;
}
}
}
},
/*--------
FUNCTIONS
--------*/
//HURT FX----------
Hurt = function(HitSize, multi, StartColor, EndColor, size) {
var FX = {
"maxParticles": 150,
"duration": 70 * HitSize,
"size": size / 10 * HitSize,
"sizeRandom": 3,
"lifeSpan": 25,
"lifeSpanRandom": 5,
"speed": multi * 8,
"speedRandom": multi * 3,
"gravity": {
"x": multi * 0.01,
"y": multi * 0.65
},
"angle": 270,
"angleRandom": 25,
"emissionRate": 100 * HitSize,
"startColour": StartColor,
"endColour": EndColor,
};
return FX;
},
//HEAL FX----------
Heal = function(HitSize, multi, StartColor, EndColor, size) {
var FX = {
"maxParticles": 150,
"duration": 50 * HitSize,
"size": size / 10 * HitSize,
"sizeRandom": 15 * HitSize,
"lifeSpan": multi * 50,
"lifeSpanRandom": 30,
"speed": multi * 0.5,
"speedRandom": multi / 2 * 1.1,
"angle": 0,
"angleRandom": 180,
"emissionRate": 1000,
"startColour": StartColor,
"endColour": EndColor,
};
return FX;
},
//WHISPER GM------------
GMW = function(text) {
sendChat('HealthColors', "/w GM <br><b> " + text + "</b>");
},
//DEATH SOUND------------
PlayDeath = function(trackname) {
var track = findObjs({type: 'jukeboxtrack',title: trackname})[0];
if (track) {
track.set('playing', false);
track.set('softstop', false);
track.set('volume', 50);
track.set('playing', true);
}
else {
log("No track found");
}
},
//CREATE USECOLOR ATTR------------
CreateAttrib = function(oCharacter, attrib, value) {
log("Creating "+ attrib);
createObj("attribute", {name: attrib,current: value,characterid: oCharacter.id});
},
//SET TOKEN COLORS------------
TokenSet = function(obj, sizeSet, markerColor, pColor) {
var Pageon = getObj("page", obj.get("_pageid"));
var scale = Pageon.get("scale_number") / 10;
obj.set({
'aura1_radius': sizeSet * scale * 1.8,
'aura2_radius': sizeSet * scale * 0.1,
'aura1_color': markerColor,
'aura2_color': pColor,
'showplayers_aura1': true,
'showplayers_aura2': true,
});
},
//HELP MENU------------
aurahelp = function() {
var img = "background-image: -webkit-linear-gradient(-45deg, #a7c7dc 0%,#85b2d3 100%);";
var tshadow = "-1px -1px #000, 1px -1px #000, -1px 1px #000, 1px 1px #000 , 2px 2px #222;";
var style = 'style="padding-top: 1px; text-align:center; font-size: 9pt; width: 45px; height: 14px; border: 1px solid black; margin: 1px; background-color: #6FAEC7;border-radius: 4px; box-shadow: 1px 1px 1px #707070;';
var off = "#A84D4D";
var disable = "#D6D6D6";
var HR = "<hr style='background-color: #000000; margin: 5px; border-width:0;color: #000000;height: 1px;'/>";
var FX = state.HealthColors.auraDeadFX.substring(0, 4);
sendChat('HealthColors', "/w GM <b><br>" + '<div style="border-radius: 8px 8px 8px 8px; padding: 5px; font-size: 9pt; text-shadow: ' + tshadow + '; box-shadow: 3px 3px 1px #707070; '+img+' color:#FFF; border:2px solid black; text-align:right; vertical-align:middle;">' + '<u>HealthColors Version: ' + version + '</u><br>' + //--
HR + //--
'Is On: <a ' + style + 'background-color:' + (state.HealthColors.auraColorOn !== true ? off : "") + ';" href="!aura on">' + (state.HealthColors.auraColorOn !== true ? "No" : "Yes") + '</a><br>' + //--
'Bar: <a ' + style + '" href="!aura bar ?{Bar|1|2|3}">' + state.HealthColors.auraBar + '</a><br>' + //--
'Use Tint: <a ' + style + 'background-color:' + (state.HealthColors.auraTint !== true ? off : "") + ';" href="!aura tint">' + (state.HealthColors.auraTint !== true ? "No" : "Yes") + '</a><br>' + //--
'Percentage: <a ' + style + '" href="!aura perc ?{Percent?|100}">' + state.HealthColors.auraPerc + '</a><br>' + //--
'Show on PC: <a ' + style + 'background-color:' + (state.HealthColors.PCAura !== true ? off : "") + ';" href="!aura pc">' + (state.HealthColors.PCAura !== true ? "No" : "Yes") + '</a><br>' + //--
'Show on NPC: <a ' + style + 'background-color:' + (state.HealthColors.NPCAura !== true ? off : "") + ';" href="!aura npc">' + (state.HealthColors.NPCAura !== true ? "No" : "Yes") + '</a><br>' + //--
'Show Dead: <a ' + style + 'background-color:' + (state.HealthColors.auraDead !== true ? off : "") + ';" href="!aura dead">' + (state.HealthColors.auraDead !== true ? "No" : "Yes") + '</a><br>' + //--
'DeathSFX: <a ' + style + '" href="!aura deadfx ?{Sound Name?|None}">' + FX + '</a><br>' + //--
HR + //--
'GM Sees all NPC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.GM_NPCNames, off, disable) + ';" href="!aura gmnpc ?{Setting|Yes|No|Off}">' + state.HealthColors.GM_NPCNames + '</a><br>' + //---
'GM Sees all PC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.GM_PCNames, off, disable) + ';" href="!aura gmpc ?{Setting|Yes|No|Off}">' + state.HealthColors.GM_PCNames + '</a><br>' + //--
HR + //--
'PC Sees all NPC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.NPCNames, off, disable) + ';" href="!aura pcnpc ?{Setting|Yes|No|Off}">' + state.HealthColors.NPCNames + '</a><br>' + //--
'PC Sees all PC Names: <a ' + style + 'background-color:' + ButtonColor(state.HealthColors.PCNames, off, disable) + ';" href="!aura pcpc ?{Setting|Yes|No|Off}">' + state.HealthColors.PCNames + '</a><br>' + //--
HR + //--
'Aura Size: <a ' + style + '" href="!aura size ?{Size?|0.7}">' + state.HealthColors.AuraSize + '</a><br>' + //--
'One Offs: <a ' + style + 'background-color:' + (state.HealthColors.OneOff !== true ? off : "") + ';" href="!aura ONEOFF">' + (state.HealthColors.OneOff !== true ? "No" : "Yes") + '</a><br>' + //--
'FX: <a ' + style + 'background-color:' + (state.HealthColors.FX !== true ? off : "") + ';" href="!aura FX">' + (state.HealthColors.FX !== true ? "No" : "Yes") + '</a><br>' + //--
'HealFX Color: <a ' + style + 'background-color:#' + state.HealthColors.HealFX + ';""href="!aura HEAL ?{Color?|00FF00}">' + state.HealthColors.HealFX + '</a><br>' + //--
'HurtFX Color: <a ' + style + 'background-color:#' + state.HealthColors.HurtFX + ';""href="!aura HURT ?{Color?|FF0000}">' + state.HealthColors.HurtFX + '</a><br>' + //--
HR + //--
'</div>');
},
//OFF BUTTON COLORS------------
ButtonColor = function(state, off, disable) {
var color;
if (state == "No") color = off;
if (state == "Off") color = disable;
return color;
},
//REMOVE ALL------------
SetAuraNone = function(obj) {
var tint = state.HealthColors.auraTint;
if (tint === true) {
obj.set({'tint_color': "transparent",});
}
else {
obj.set({
'aura1_color': "",
'aura2_color': "",
});
}
},
//PERC TO RGB------------
PercentToRGB = function(percent) {
if (percent === 100) percent = 99;
var r, g, b;
if (percent < 50) {
g = Math.floor(255 * (percent / 50));
r = 255;
}
else {
g = 255;
r = Math.floor(255 * ((50 - percent % 50) / 50));
}
b = 0;
var Gradient = rgbToHex(r, g, b);
return Gradient;
},
//RGB TO HEX------------
rgbToHex = function(r, g, b) {
var Color = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
return Color;
},
//HEX TO RGB------------
HEXtoRGB = function(hex) {
let parts = hex.match(/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/);
if (parts) {
let rgb = _.chain(parts)
.rest()
.map((d) => parseInt(d, 16))
.value();
rgb.push(1.0);
return rgb;
}
return [0, 0, 0, 1.0];
},
//CHECK INSTALL & SET STATE------------
checkInstall = function() {
log('<' + ScriptName + ' v' + version + ' Ready [Updated: '+ Updated+']>');
if (!_.has(state, 'HealthColors') || state.HealthColors.schemaVersion !== schemaVersion) {
log('<' + ScriptName + ' Updating Schema to v' + schemaVersion + '>');
state.HealthColors = {
schemaVersion: schemaVersion
};
state.HealthColors.version = version;
}
if (_.isUndefined(state.HealthColors.auraColorOn)) state.HealthColors.auraColorOn = true; //global on or off
if (_.isUndefined(state.HealthColors.auraBar)) state.HealthColors.auraBar = "bar1"; //bar to use
if (_.isUndefined(state.HealthColors.PCAura)) state.HealthColors.PCAura = true; //show players Health?
if (_.isUndefined(state.HealthColors.NPCAura)) state.HealthColors.NPCAura = true; //show NPC Health?
if (_.isUndefined(state.HealthColors.auraTint)) state.HealthColors.auraTint = false; //use tint instead?
if (_.isUndefined(state.HealthColors.auraPerc)) state.HealthColors.auraPerc = 100; //precent to start showing
if (_.isUndefined(state.HealthColors.auraDead)) state.HealthColors.auraDead = true; //show dead X status
if (_.isUndefined(state.HealthColors.auraDeadFX)) state.HealthColors.auraDeadFX = 'None'; //Sound FX Name
if (_.isUndefined(state.HealthColors.GM_NPCNames)) state.HealthColors.GM_NPCNames = "Yes"; //show GM NPC names?
if (_.isUndefined(state.HealthColors.NPCNames)) state.HealthColors.NPCNames = "Yes"; //show players NPC Names?
if (_.isUndefined(state.HealthColors.GM_PCNames)) state.HealthColors.GM_PCNames = "Yes"; //show GM PC names?
if (_.isUndefined(state.HealthColors.PCNames)) state.HealthColors.PCNames = "Yes"; //show players PC Names?
if (_.isUndefined(state.HealthColors.AuraSize)) state.HealthColors.AuraSize = 0.7; //set aura size?
if (_.isUndefined(state.HealthColors.FX)) state.HealthColors.FX = true; //set FX ON/OFF?
if (_.isUndefined(state.HealthColors.HealFX)) state.HealthColors.HealFX = "00FF00"; //set FX HEAL COLOR
if (_.isUndefined(state.HealthColors.HurtFX)) state.HealthColors.HurtFX = "FF0000"; //set FX HURT COLOR?
},
registerEventHandlers = function() {
on('chat:message', handleInput);
on("change:token", handleToken);
};
/*-------------
RETURN OUTSIDE FUNCTIONS
-----------*/
return {
CheckInstall: checkInstall,
RegisterEventHandlers: registerEventHandlers
};
}());
//On Ready
on('ready', function() {
'use strict';
HealthColors.CheckInstall();
HealthColors.RegisterEventHandlers();
}); | shdwjk/roll20-api-scripts | HealthColors/1.2.0/HealthColors.js | JavaScript | mit | 23,582 |
describe('paging', function(){
var welcomeHolder = app.PageStore.welcome;
var roomsHolder = app.PageStore.rooms;
beforeEach(function(){
app.PageStore.welcome = welcomeHolder;
app.PageStore.rooms = roomsHolder;
});
it('should have a welcome route that invokes a callback', function(){
var counter = 0;
app.PageStore.welcome = function(){counter++;};
app.PageActions.navigate({
dest: 'welcome'
});
expect(counter).to.equal(1);
});
it('should have a rooms route that passes the roomId to a callback', function(){
var id;
app.PageStore.rooms = function(roomId){id = roomId;};
app.PageActions.navigate({
dest: 'rooms',
props: '0'
});
expect(id).to.equal('0');
});
it('should emit events when routing', function(){
var callcount = 0;
var callback = function(){callcount++;};
app.PageStore.addChangeListener(callback);
app.PageActions.navigate({
dest: 'welcome'
});
expect(callcount).to.equal(1);
app.PageActions.navigate({
dest: 'rooms'
});
expect(callcount).to.equal(2);
app.PageStore.removeChangeListener(callback);
});
});
| drabinowitz/Brainstorm | specs/client/PageStoreSpec.js | JavaScript | mit | 1,171 |
/**
*
* Copyright 2005 Sabre Airline Solutions
*
* 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.
**/
//-------------------- rico.js
var Rico = {
Version: '1.1.2',
prototypeVersion: parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1])
}
if((typeof Prototype=='undefined') || Rico.prototypeVersion < 1.3)
throw("Rico requires the Prototype JavaScript framework >= 1.3");
Rico.ArrayExtensions = new Array();
if (Object.prototype.extend) {
Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Object.prototype.extend;
}else{
Object.prototype.extend = function(object) {
return Object.extend.apply(this, [this, object]);
}
Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Object.prototype.extend;
}
if (Array.prototype.push) {
Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Array.prototype.push;
}
if (!Array.prototype.remove) {
Array.prototype.remove = function(dx) {
if( isNaN(dx) || dx > this.length )
return false;
for( var i=0,n=0; i<this.length; i++ )
if( i != dx )
this[n++]=this[i];
this.length-=1;
};
Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Array.prototype.remove;
}
if (!Array.prototype.removeItem) {
Array.prototype.removeItem = function(item) {
for ( var i = 0 ; i < this.length ; i++ )
if ( this[i] == item ) {
this.remove(i);
break;
}
};
Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Array.prototype.removeItem;
}
if (!Array.prototype.indices) {
Array.prototype.indices = function() {
var indexArray = new Array();
for ( index in this ) {
var ignoreThis = false;
for ( var i = 0 ; i < Rico.ArrayExtensions.length ; i++ ) {
if ( this[index] == Rico.ArrayExtensions[i] ) {
ignoreThis = true;
break;
}
}
if ( !ignoreThis )
indexArray[ indexArray.length ] = index;
}
return indexArray;
}
Rico.ArrayExtensions[ Rico.ArrayExtensions.length ] = Array.prototype.indices;
}
// Create the loadXML method and xml getter for Mozilla
if ( window.DOMParser &&
window.XMLSerializer &&
window.Node && Node.prototype && Node.prototype.__defineGetter__ ) {
if (!Document.prototype.loadXML) {
Document.prototype.loadXML = function (s) {
var doc2 = (new DOMParser()).parseFromString(s, "text/xml");
while (this.hasChildNodes())
this.removeChild(this.lastChild);
for (var i = 0; i < doc2.childNodes.length; i++) {
this.appendChild(this.importNode(doc2.childNodes[i], true));
}
};
}
Document.prototype.__defineGetter__( "xml",
function () {
return (new XMLSerializer()).serializeToString(this);
}
);
}
document.getElementsByTagAndClassName = function(tagName, className) {
if ( tagName == null )
tagName = '*';
var children = document.getElementsByTagName(tagName) || document.all;
var elements = new Array();
if ( className == null )
return children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
var classNames = child.className.split(' ');
for (var j = 0; j < classNames.length; j++) {
if (classNames[j] == className) {
elements.push(child);
break;
}
}
}
return elements;
}
//-------------------- ricoAccordion.js
Rico.Accordion = Class.create();
Rico.Accordion.prototype = {
initialize: function(container, options) {
this.container = $(container);
this.lastExpandedTab = null;
this.accordionTabs = new Array();
this.setOptions(options);
this._attachBehaviors();
if(!container) return;
this.container.style.borderBottom = '1px solid ' + this.options.borderColor;
// validate onloadShowTab
if (this.options.onLoadShowTab >= this.accordionTabs.length)
this.options.onLoadShowTab = 0;
// set the initial visual state...
for ( var i=0 ; i < this.accordionTabs.length ; i++ )
{
if (i != this.options.onLoadShowTab){
this.accordionTabs[i].collapse();
this.accordionTabs[i].content.style.display = 'none';
}
}
this.lastExpandedTab = this.accordionTabs[this.options.onLoadShowTab];
if (this.options.panelHeight == 'auto'){
var tabToCheck = (this.options.onloadShowTab === 0)? 1 : 0;
var titleBarSize = parseInt(RicoUtil.getElementsComputedStyle(this.accordionTabs[tabToCheck].titleBar, 'height'));
if (isNaN(titleBarSize))
titleBarSize = this.accordionTabs[tabToCheck].titleBar.offsetHeight;
var totalTitleBarSize = this.accordionTabs.length * titleBarSize;
var parentHeight = parseInt(RicoUtil.getElementsComputedStyle(this.container.parentNode, 'height'));
if (isNaN(parentHeight))
parentHeight = this.container.parentNode.offsetHeight;
this.options.panelHeight = parentHeight - totalTitleBarSize-2;
}
this.lastExpandedTab.content.style.height = this.options.panelHeight + "px";
this.lastExpandedTab.showExpanded();
this.lastExpandedTab.titleBar.style.fontWeight = this.options.expandedFontWeight;
},
setOptions: function(options) {
this.options = {
expandedBg : '#545985',
hoverBg : '#63699c',
collapsedBg : '#6b79a5',
expandedTextColor : '#ffffff',
expandedFontWeight : 'bold',
hoverTextColor : '#ffffff',
collapsedTextColor : '#ced7ef',
collapsedFontWeight : 'normal',
hoverTextColor : '#ffffff',
borderColor : '#ffffff',
panelHeight : 200,
onHideTab : null,
onShowTab : null,
onLoadShowTab : 0
}
Object.extend(this.options, options || {});
},
showTabByIndex: function( anIndex, animate ) {
var doAnimate = arguments.length == 1 ? true : animate;
this.showTab( this.accordionTabs[anIndex], doAnimate );
},
showTab: function( accordionTab, animate ) {
if ( this.lastExpandedTab == accordionTab )
return;
var doAnimate = arguments.length == 1 ? true : animate;
if ( this.options.onHideTab )
this.options.onHideTab(this.lastExpandedTab);
this.lastExpandedTab.showCollapsed();
var accordion = this;
var lastExpandedTab = this.lastExpandedTab;
this.lastExpandedTab.content.style.height = (this.options.panelHeight - 1) + 'px';
accordionTab.content.style.display = '';
accordionTab.titleBar.style.fontWeight = this.options.expandedFontWeight;
if ( doAnimate ) {
new Rico.Effect.AccordionSize( this.lastExpandedTab.content,
accordionTab.content,
1,
this.options.panelHeight,
100, 10,
{ complete: function() {accordion.showTabDone(lastExpandedTab)} } );
this.lastExpandedTab = accordionTab;
}
else {
this.lastExpandedTab.content.style.height = "1px";
accordionTab.content.style.height = this.options.panelHeight + "px";
this.lastExpandedTab = accordionTab;
this.showTabDone(lastExpandedTab);
}
},
showTabDone: function(collapsedTab) {
collapsedTab.content.style.display = 'none';
this.lastExpandedTab.showExpanded();
if ( this.options.onShowTab )
this.options.onShowTab(this.lastExpandedTab);
},
_attachBehaviors: function() {
var panels = this._getDirectChildrenByTag(this.container, 'DIV');
for ( var i = 0 ; i < panels.length ; i++ ) {
var tabChildren = this._getDirectChildrenByTag(panels[i],'DIV');
if ( tabChildren.length != 2 )
continue; // unexpected
var tabTitleBar = tabChildren[0];
var tabContentBox = tabChildren[1];
this.accordionTabs.push( new Rico.Accordion.Tab(this,tabTitleBar,tabContentBox) );
}
},
_getDirectChildrenByTag: function(e, tagName) {
var kids = new Array();
var allKids = e.childNodes;
for( var i = 0 ; i < allKids.length ; i++ )
if ( allKids[i] && allKids[i].tagName && allKids[i].tagName == tagName )
kids.push(allKids[i]);
return kids;
}
};
Rico.Accordion.Tab = Class.create();
Rico.Accordion.Tab.prototype = {
initialize: function(accordion, titleBar, content) {
this.accordion = accordion;
this.titleBar = titleBar;
this.content = content;
this._attachBehaviors();
},
collapse: function() {
this.showCollapsed();
this.content.style.height = "1px";
},
showCollapsed: function() {
this.expanded = false;
this.titleBar.style.backgroundColor = this.accordion.options.collapsedBg;
this.titleBar.style.color = this.accordion.options.collapsedTextColor;
this.titleBar.style.fontWeight = this.accordion.options.collapsedFontWeight;
this.content.style.overflow = "hidden";
},
showExpanded: function() {
this.expanded = true;
this.titleBar.style.backgroundColor = this.accordion.options.expandedBg;
this.titleBar.style.color = this.accordion.options.expandedTextColor;
this.content.style.overflow = "auto";
},
titleBarClicked: function(e) {
if ( this.accordion.lastExpandedTab == this )
return;
this.accordion.showTab(this);
},
hover: function(e) {
this.titleBar.style.backgroundColor = this.accordion.options.hoverBg;
this.titleBar.style.color = this.accordion.options.hoverTextColor;
},
unhover: function(e) {
if ( this.expanded ) {
this.titleBar.style.backgroundColor = this.accordion.options.expandedBg;
this.titleBar.style.color = this.accordion.options.expandedTextColor;
}
else {
this.titleBar.style.backgroundColor = this.accordion.options.collapsedBg;
this.titleBar.style.color = this.accordion.options.collapsedTextColor;
}
},
_attachBehaviors: function() {
this.content.style.border = "1px solid " + this.accordion.options.borderColor;
this.content.style.borderTopWidth = "0px";
this.content.style.borderBottomWidth = "0px";
this.content.style.margin = "0px";
this.titleBar.onclick = this.titleBarClicked.bindAsEventListener(this);
this.titleBar.onmouseover = this.hover.bindAsEventListener(this);
this.titleBar.onmouseout = this.unhover.bindAsEventListener(this);
}
};
//-------------------- ricoAjaxEngine.js
Rico.AjaxEngine = Class.create();
Rico.AjaxEngine.prototype = {
initialize: function() {
this.ajaxElements = new Array();
this.ajaxObjects = new Array();
this.requestURLS = new Array();
this.options = {};
},
registerAjaxElement: function( anId, anElement ) {
if ( !anElement )
anElement = $(anId);
this.ajaxElements[anId] = anElement;
},
registerAjaxObject: function( anId, anObject ) {
this.ajaxObjects[anId] = anObject;
},
registerRequest: function (requestLogicalName, requestURL) {
this.requestURLS[requestLogicalName] = requestURL;
},
sendRequest: function(requestName, options) {
// Allow for backwards Compatibility
if ( arguments.length >= 2 )
if (typeof arguments[1] == 'string')
options = {parameters: this._createQueryString(arguments, 1)};
this.sendRequestWithData(requestName, null, options);
},
sendRequestWithData: function(requestName, xmlDocument, options) {
var requestURL = this.requestURLS[requestName];
if ( requestURL == null )
return;
// Allow for backwards Compatibility
if ( arguments.length >= 3 )
if (typeof arguments[2] == 'string')
options.parameters = this._createQueryString(arguments, 2);
new Ajax.Request(requestURL, this._requestOptions(options,xmlDocument));
},
sendRequestAndUpdate: function(requestName,container,options) {
// Allow for backwards Compatibility
if ( arguments.length >= 3 )
if (typeof arguments[2] == 'string')
options.parameters = this._createQueryString(arguments, 2);
this.sendRequestWithDataAndUpdate(requestName, null, container, options);
},
sendRequestWithDataAndUpdate: function(requestName,xmlDocument,container,options) {
var requestURL = this.requestURLS[requestName];
if ( requestURL == null )
return;
// Allow for backwards Compatibility
if ( arguments.length >= 4 )
if (typeof arguments[3] == 'string')
options.parameters = this._createQueryString(arguments, 3);
var updaterOptions = this._requestOptions(options,xmlDocument);
new Ajax.Updater(container, requestURL, updaterOptions);
},
// Private -- not part of intended engine API --------------------------------------------------------------------
_requestOptions: function(options,xmlDoc) {
var requestHeaders = ['X-Rico-Version', Rico.Version ];
var sendMethod = 'post';
if ( xmlDoc == null )
if (Rico.prototypeVersion < 1.4)
requestHeaders.push( 'Content-type', 'text/xml' );
else
sendMethod = 'get';
(!options) ? options = {} : '';
if (!options._RicoOptionsProcessed){
// Check and keep any user onComplete functions
if (options.onComplete)
options.onRicoComplete = options.onComplete;
// Fix onComplete
if (options.overrideOnComplete)
options.onComplete = options.overrideOnComplete;
else
options.onComplete = this._onRequestComplete.bind(this);
options._RicoOptionsProcessed = true;
}
// Set the default options and extend with any user options
this.options = {
requestHeaders: requestHeaders,
parameters: options.parameters,
postBody: xmlDoc,
method: sendMethod,
onComplete: options.onComplete
};
// Set any user options:
Object.extend(this.options, options);
return this.options;
},
_createQueryString: function( theArgs, offset ) {
var queryString = ""
for ( var i = offset ; i < theArgs.length ; i++ ) {
if ( i != offset )
queryString += "&";
var anArg = theArgs[i];
if ( anArg.name != undefined && anArg.value != undefined ) {
queryString += anArg.name + "=" + escape(anArg.value);
}
else {
var ePos = anArg.indexOf('=');
var argName = anArg.substring( 0, ePos );
var argValue = anArg.substring( ePos + 1 );
queryString += argName + "=" + escape(argValue);
}
}
return queryString;
},
_onRequestComplete : function(request) {
if(!request)
return;
// User can set an onFailure option - which will be called by prototype
if (request.status != 200)
return;
var response = request.responseXML.getElementsByTagName("ajax-response");
if (response == null || response.length != 1)
return;
this._processAjaxResponse( response[0].childNodes );
// Check if user has set a onComplete function
var onRicoComplete = this.options.onRicoComplete;
if (onRicoComplete != null)
onRicoComplete();
},
_processAjaxResponse: function( xmlResponseElements ) {
for ( var i = 0 ; i < xmlResponseElements.length ; i++ ) {
var responseElement = xmlResponseElements[i];
// only process nodes of type element.....
if ( responseElement.nodeType != 1 )
continue;
var responseType = responseElement.getAttribute("type");
var responseId = responseElement.getAttribute("id");
if ( responseType == "object" )
this._processAjaxObjectUpdate( this.ajaxObjects[ responseId ], responseElement );
else if ( responseType == "element" )
this._processAjaxElementUpdate( this.ajaxElements[ responseId ], responseElement );
else
alert('unrecognized AjaxResponse type : ' + responseType );
}
},
_processAjaxObjectUpdate: function( ajaxObject, responseElement ) {
ajaxObject.ajaxUpdate( responseElement );
},
_processAjaxElementUpdate: function( ajaxElement, responseElement ) {
ajaxElement.innerHTML = RicoUtil.getContentAsString(responseElement);
}
}
var ajaxEngine = new Rico.AjaxEngine();
//-------------------- ricoColor.js
Rico.Color = Class.create();
Rico.Color.prototype = {
initialize: function(red, green, blue) {
this.rgb = { r: red, g : green, b : blue };
},
setRed: function(r) {
this.rgb.r = r;
},
setGreen: function(g) {
this.rgb.g = g;
},
setBlue: function(b) {
this.rgb.b = b;
},
setHue: function(h) {
// get an HSB model, and set the new hue...
var hsb = this.asHSB();
hsb.h = h;
// convert back to RGB...
this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, hsb.b);
},
setSaturation: function(s) {
// get an HSB model, and set the new hue...
var hsb = this.asHSB();
hsb.s = s;
// convert back to RGB and set values...
this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, hsb.b);
},
setBrightness: function(b) {
// get an HSB model, and set the new hue...
var hsb = this.asHSB();
hsb.b = b;
// convert back to RGB and set values...
this.rgb = Rico.Color.HSBtoRGB( hsb.h, hsb.s, hsb.b );
},
darken: function(percent) {
var hsb = this.asHSB();
this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, Math.max(hsb.b - percent,0));
},
brighten: function(percent) {
var hsb = this.asHSB();
this.rgb = Rico.Color.HSBtoRGB(hsb.h, hsb.s, Math.min(hsb.b + percent,1));
},
blend: function(other) {
this.rgb.r = Math.floor((this.rgb.r + other.rgb.r)/2);
this.rgb.g = Math.floor((this.rgb.g + other.rgb.g)/2);
this.rgb.b = Math.floor((this.rgb.b + other.rgb.b)/2);
},
isBright: function() {
var hsb = this.asHSB();
return this.asHSB().b > 0.5;
},
isDark: function() {
return ! this.isBright();
},
asRGB: function() {
return "rgb(" + this.rgb.r + "," + this.rgb.g + "," + this.rgb.b + ")";
},
asHex: function() {
return "#" + this.rgb.r.toColorPart() + this.rgb.g.toColorPart() + this.rgb.b.toColorPart();
},
asHSB: function() {
return Rico.Color.RGBtoHSB(this.rgb.r, this.rgb.g, this.rgb.b);
},
toString: function() {
return this.asHex();
}
};
Rico.Color.createFromHex = function(hexCode) {
if(hexCode.length==4) {
var shortHexCode = hexCode;
var hexCode = '#';
for(var i=1;i<4;i++) hexCode += (shortHexCode.charAt(i) +
shortHexCode.charAt(i));
}
if ( hexCode.indexOf('#') == 0 )
hexCode = hexCode.substring(1);
var red = hexCode.substring(0,2);
var green = hexCode.substring(2,4);
var blue = hexCode.substring(4,6);
return new Rico.Color( parseInt(red,16), parseInt(green,16), parseInt(blue,16) );
}
/**
* Factory method for creating a color from the background of
* an HTML element.
*/
Rico.Color.createColorFromBackground = function(elem) {
var actualColor = RicoUtil.getElementsComputedStyle($(elem), "backgroundColor", "background-color");
if ( actualColor == "transparent" && elem.parentNode )
return Rico.Color.createColorFromBackground(elem.parentNode);
if ( actualColor == null )
return new Rico.Color(255,255,255);
if ( actualColor.indexOf("rgb(") == 0 ) {
var colors = actualColor.substring(4, actualColor.length - 1 );
var colorArray = colors.split(",");
return new Rico.Color( parseInt( colorArray[0] ),
parseInt( colorArray[1] ),
parseInt( colorArray[2] ) );
}
else if ( actualColor.indexOf("#") == 0 ) {
return Rico.Color.createFromHex(actualColor);
}
else
return new Rico.Color(255,255,255);
}
Rico.Color.HSBtoRGB = function(hue, saturation, brightness) {
var red = 0;
var green = 0;
var blue = 0;
if (saturation == 0) {
red = parseInt(brightness * 255.0 + 0.5);
green = red;
blue = red;
}
else {
var h = (hue - Math.floor(hue)) * 6.0;
var f = h - Math.floor(h);
var p = brightness * (1.0 - saturation);
var q = brightness * (1.0 - saturation * f);
var t = brightness * (1.0 - (saturation * (1.0 - f)));
switch (parseInt(h)) {
case 0:
red = (brightness * 255.0 + 0.5);
green = (t * 255.0 + 0.5);
blue = (p * 255.0 + 0.5);
break;
case 1:
red = (q * 255.0 + 0.5);
green = (brightness * 255.0 + 0.5);
blue = (p * 255.0 + 0.5);
break;
case 2:
red = (p * 255.0 + 0.5);
green = (brightness * 255.0 + 0.5);
blue = (t * 255.0 + 0.5);
break;
case 3:
red = (p * 255.0 + 0.5);
green = (q * 255.0 + 0.5);
blue = (brightness * 255.0 + 0.5);
break;
case 4:
red = (t * 255.0 + 0.5);
green = (p * 255.0 + 0.5);
blue = (brightness * 255.0 + 0.5);
break;
case 5:
red = (brightness * 255.0 + 0.5);
green = (p * 255.0 + 0.5);
blue = (q * 255.0 + 0.5);
break;
}
}
return { r : parseInt(red), g : parseInt(green) , b : parseInt(blue) };
}
Rico.Color.RGBtoHSB = function(r, g, b) {
var hue;
var saturation;
var brightness;
var cmax = (r > g) ? r : g;
if (b > cmax)
cmax = b;
var cmin = (r < g) ? r : g;
if (b < cmin)
cmin = b;
brightness = cmax / 255.0;
if (cmax != 0)
saturation = (cmax - cmin)/cmax;
else
saturation = 0;
if (saturation == 0)
hue = 0;
else {
var redc = (cmax - r)/(cmax - cmin);
var greenc = (cmax - g)/(cmax - cmin);
var bluec = (cmax - b)/(cmax - cmin);
if (r == cmax)
hue = bluec - greenc;
else if (g == cmax)
hue = 2.0 + redc - bluec;
else
hue = 4.0 + greenc - redc;
hue = hue / 6.0;
if (hue < 0)
hue = hue + 1.0;
}
return { h : hue, s : saturation, b : brightness };
}
//-------------------- ricoCorner.js
Rico.Corner = {
round: function(e, options) {
var e = $(e);
this._setOptions(options);
var color = this.options.color;
if ( this.options.color == "fromElement" )
color = this._background(e);
var bgColor = this.options.bgColor;
if ( this.options.bgColor == "fromParent" )
bgColor = this._background(e.offsetParent);
this._roundCornersImpl(e, color, bgColor);
},
_roundCornersImpl: function(e, color, bgColor) {
if(this.options.border)
this._renderBorder(e,bgColor);
if(this._isTopRounded())
this._roundTopCorners(e,color,bgColor);
if(this._isBottomRounded())
this._roundBottomCorners(e,color,bgColor);
},
_renderBorder: function(el,bgColor) {
var borderValue = "1px solid " + this._borderColor(bgColor);
var borderL = "border-left: " + borderValue;
var borderR = "border-right: " + borderValue;
var style = "style='" + borderL + ";" + borderR + "'";
el.innerHTML = "<div " + style + ">" + el.innerHTML + "</div>"
},
_roundTopCorners: function(el, color, bgColor) {
var corner = this._createCorner(bgColor);
for(var i=0 ; i < this.options.numSlices ; i++ )
corner.appendChild(this._createCornerSlice(color,bgColor,i,"top"));
el.style.paddingTop = 0;
el.insertBefore(corner,el.firstChild);
},
_roundBottomCorners: function(el, color, bgColor) {
var corner = this._createCorner(bgColor);
for(var i=(this.options.numSlices-1) ; i >= 0 ; i-- )
corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom"));
el.style.paddingBottom = 0;
el.appendChild(corner);
},
_createCorner: function(bgColor) {
var corner = document.createElement("div");
corner.style.backgroundColor = (this._isTransparent() ? "transparent" : bgColor);
return corner;
},
_createCornerSlice: function(color,bgColor, n, position) {
var slice = document.createElement("span");
var inStyle = slice.style;
inStyle.backgroundColor = color;
inStyle.display = "block";
inStyle.height = "1px";
inStyle.overflow = "hidden";
inStyle.fontSize = "1px";
var borderColor = this._borderColor(color,bgColor);
if ( this.options.border && n == 0 ) {
inStyle.borderTopStyle = "solid";
inStyle.borderTopWidth = "1px";
inStyle.borderLeftWidth = "0px";
inStyle.borderRightWidth = "0px";
inStyle.borderBottomWidth = "0px";
inStyle.height = "0px"; // assumes css compliant box model
inStyle.borderColor = borderColor;
}
else if(borderColor) {
inStyle.borderColor = borderColor;
inStyle.borderStyle = "solid";
inStyle.borderWidth = "0px 1px";
}
if ( !this.options.compact && (n == (this.options.numSlices-1)) )
inStyle.height = "2px";
this._setMargin(slice, n, position);
this._setBorder(slice, n, position);
return slice;
},
_setOptions: function(options) {
this.options = {
corners : "all",
color : "fromElement",
bgColor : "fromParent",
blend : true,
border : false,
compact : false
}
Object.extend(this.options, options || {});
this.options.numSlices = this.options.compact ? 2 : 4;
if ( this._isTransparent() )
this.options.blend = false;
},
_whichSideTop: function() {
if ( this._hasString(this.options.corners, "all", "top") )
return "";
if ( this.options.corners.indexOf("tl") >= 0 && this.options.corners.indexOf("tr") >= 0 )
return "";
if (this.options.corners.indexOf("tl") >= 0)
return "left";
else if (this.options.corners.indexOf("tr") >= 0)
return "right";
return "";
},
_whichSideBottom: function() {
if ( this._hasString(this.options.corners, "all", "bottom") )
return "";
if ( this.options.corners.indexOf("bl")>=0 && this.options.corners.indexOf("br")>=0 )
return "";
if(this.options.corners.indexOf("bl") >=0)
return "left";
else if(this.options.corners.indexOf("br")>=0)
return "right";
return "";
},
_borderColor : function(color,bgColor) {
if ( color == "transparent" )
return bgColor;
else if ( this.options.border )
return this.options.border;
else if ( this.options.blend )
return this._blend( bgColor, color );
else
return "";
},
_setMargin: function(el, n, corners) {
var marginSize = this._marginSize(n);
var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom();
if ( whichSide == "left" ) {
el.style.marginLeft = marginSize + "px"; el.style.marginRight = "0px";
}
else if ( whichSide == "right" ) {
el.style.marginRight = marginSize + "px"; el.style.marginLeft = "0px";
}
else {
el.style.marginLeft = marginSize + "px"; el.style.marginRight = marginSize + "px";
}
},
_setBorder: function(el,n,corners) {
var borderSize = this._borderSize(n);
var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom();
if ( whichSide == "left" ) {
el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = "0px";
}
else if ( whichSide == "right" ) {
el.style.borderRightWidth = borderSize + "px"; el.style.borderLeftWidth = "0px";
}
else {
el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px";
}
if (this.options.border != false)
el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px";
},
_marginSize: function(n) {
if ( this._isTransparent() )
return 0;
var marginSizes = [ 5, 3, 2, 1 ];
var blendedMarginSizes = [ 3, 2, 1, 0 ];
var compactMarginSizes = [ 2, 1 ];
var smBlendedMarginSizes = [ 1, 0 ];
if ( this.options.compact && this.options.blend )
return smBlendedMarginSizes[n];
else if ( this.options.compact )
return compactMarginSizes[n];
else if ( this.options.blend )
return blendedMarginSizes[n];
else
return marginSizes[n];
},
_borderSize: function(n) {
var transparentBorderSizes = [ 5, 3, 2, 1 ];
var blendedBorderSizes = [ 2, 1, 1, 1 ];
var compactBorderSizes = [ 1, 0 ];
var actualBorderSizes = [ 0, 2, 0, 0 ];
if ( this.options.compact && (this.options.blend || this._isTransparent()) )
return 1;
else if ( this.options.compact )
return compactBorderSizes[n];
else if ( this.options.blend )
return blendedBorderSizes[n];
else if ( this.options.border )
return actualBorderSizes[n];
else if ( this._isTransparent() )
return transparentBorderSizes[n];
return 0;
},
_hasString: function(str) { for(var i=1 ; i<arguments.length ; i++) if (str.indexOf(arguments[i]) >= 0) return true; return false; },
_blend: function(c1, c2) { var cc1 = Rico.Color.createFromHex(c1); cc1.blend(Rico.Color.createFromHex(c2)); return cc1; },
_background: function(el) { try { return Rico.Color.createColorFromBackground(el).asHex(); } catch(err) { return "#ffffff"; } },
_isTransparent: function() { return this.options.color == "transparent"; },
_isTopRounded: function() { return this._hasString(this.options.corners, "all", "top", "tl", "tr"); },
_isBottomRounded: function() { return this._hasString(this.options.corners, "all", "bottom", "bl", "br"); },
_hasSingleTextChild: function(el) { return el.childNodes.length == 1 && el.childNodes[0].nodeType == 3; }
}
//-------------------- ricoDragAndDrop.js
Rico.DragAndDrop = Class.create();
Rico.DragAndDrop.prototype = {
initialize: function() {
this.dropZones = new Array();
this.draggables = new Array();
this.currentDragObjects = new Array();
this.dragElement = null;
this.lastSelectedDraggable = null;
this.currentDragObjectVisible = false;
this.interestedInMotionEvents = false;
this._mouseDown = this._mouseDownHandler.bindAsEventListener(this);
this._mouseMove = this._mouseMoveHandler.bindAsEventListener(this);
this._mouseUp = this._mouseUpHandler.bindAsEventListener(this);
},
registerDropZone: function(aDropZone) {
this.dropZones[ this.dropZones.length ] = aDropZone;
},
deregisterDropZone: function(aDropZone) {
var newDropZones = new Array();
var j = 0;
for ( var i = 0 ; i < this.dropZones.length ; i++ ) {
if ( this.dropZones[i] != aDropZone )
newDropZones[j++] = this.dropZones[i];
}
this.dropZones = newDropZones;
},
clearDropZones: function() {
this.dropZones = new Array();
},
registerDraggable: function( aDraggable ) {
this.draggables[ this.draggables.length ] = aDraggable;
this._addMouseDownHandler( aDraggable );
},
clearSelection: function() {
for ( var i = 0 ; i < this.currentDragObjects.length ; i++ )
this.currentDragObjects[i].deselect();
this.currentDragObjects = new Array();
this.lastSelectedDraggable = null;
},
hasSelection: function() {
return this.currentDragObjects.length > 0;
},
setStartDragFromElement: function( e, mouseDownElement ) {
this.origPos = RicoUtil.toDocumentPosition(mouseDownElement);
this.startx = e.screenX - this.origPos.x
this.starty = e.screenY - this.origPos.y
//this.startComponentX = e.layerX ? e.layerX : e.offsetX;
//this.startComponentY = e.layerY ? e.layerY : e.offsetY;
//this.adjustedForDraggableSize = false;
this.interestedInMotionEvents = this.hasSelection();
this._terminateEvent(e);
},
updateSelection: function( draggable, extendSelection ) {
if ( ! extendSelection )
this.clearSelection();
if ( draggable.isSelected() ) {
this.currentDragObjects.removeItem(draggable);
draggable.deselect();
if ( draggable == this.lastSelectedDraggable )
this.lastSelectedDraggable = null;
}
else {
this.currentDragObjects[ this.currentDragObjects.length ] = draggable;
draggable.select();
this.lastSelectedDraggable = draggable;
}
},
_mouseDownHandler: function(e) {
if ( arguments.length == 0 )
e = event;
// if not button 1 ignore it...
var nsEvent = e.which != undefined;
if ( (nsEvent && e.which != 1) || (!nsEvent && e.button != 1))
return;
var eventTarget = e.target ? e.target : e.srcElement;
var draggableObject = eventTarget.draggable;
var candidate = eventTarget;
while (draggableObject == null && candidate.parentNode) {
candidate = candidate.parentNode;
draggableObject = candidate.draggable;
}
if ( draggableObject == null )
return;
this.updateSelection( draggableObject, e.ctrlKey );
// clear the drop zones postion cache...
if ( this.hasSelection() )
for ( var i = 0 ; i < this.dropZones.length ; i++ )
this.dropZones[i].clearPositionCache();
this.setStartDragFromElement( e, draggableObject.getMouseDownHTMLElement() );
},
_mouseMoveHandler: function(e) {
var nsEvent = e.which != undefined;
if ( !this.interestedInMotionEvents ) {
//this._terminateEvent(e);
return;
}
if ( ! this.hasSelection() )
return;
if ( ! this.currentDragObjectVisible )
this._startDrag(e);
if ( !this.activatedDropZones )
this._activateRegisteredDropZones();
//if ( !this.adjustedForDraggableSize )
// this._adjustForDraggableSize(e);
this._updateDraggableLocation(e);
this._updateDropZonesHover(e);
this._terminateEvent(e);
},
_makeDraggableObjectVisible: function(e)
{
if ( !this.hasSelection() )
return;
var dragElement;
if ( this.currentDragObjects.length > 1 )
dragElement = this.currentDragObjects[0].getMultiObjectDragGUI(this.currentDragObjects);
else
dragElement = this.currentDragObjects[0].getSingleObjectDragGUI();
// go ahead and absolute position it...
if ( RicoUtil.getElementsComputedStyle(dragElement, "position") != "absolute" )
dragElement.style.position = "absolute";
// need to parent him into the document...
if ( dragElement.parentNode == null || dragElement.parentNode.nodeType == 11 )
document.body.appendChild(dragElement);
this.dragElement = dragElement;
this._updateDraggableLocation(e);
this.currentDragObjectVisible = true;
},
/**
_adjustForDraggableSize: function(e) {
var dragElementWidth = this.dragElement.offsetWidth;
var dragElementHeight = this.dragElement.offsetHeight;
if ( this.startComponentX > dragElementWidth )
this.startx -= this.startComponentX - dragElementWidth + 2;
if ( e.offsetY ) {
if ( this.startComponentY > dragElementHeight )
this.starty -= this.startComponentY - dragElementHeight + 2;
}
this.adjustedForDraggableSize = true;
},
**/
_leftOffset: function(e) {
return e.offsetX ? document.body.scrollLeft : 0
},
_topOffset: function(e) {
return e.offsetY ? document.body.scrollTop:0
},
_updateDraggableLocation: function(e) {
var dragObjectStyle = this.dragElement.style;
dragObjectStyle.left = (e.screenX + this._leftOffset(e) - this.startx) + "px"
dragObjectStyle.top = (e.screenY + this._topOffset(e) - this.starty) + "px";
},
_updateDropZonesHover: function(e) {
var n = this.dropZones.length;
for ( var i = 0 ; i < n ; i++ ) {
if ( ! this._mousePointInDropZone( e, this.dropZones[i] ) )
this.dropZones[i].hideHover();
}
for ( var i = 0 ; i < n ; i++ ) {
if ( this._mousePointInDropZone( e, this.dropZones[i] ) ) {
if ( this.dropZones[i].canAccept(this.currentDragObjects) )
this.dropZones[i].showHover();
}
}
},
_startDrag: function(e) {
for ( var i = 0 ; i < this.currentDragObjects.length ; i++ )
this.currentDragObjects[i].startDrag();
this._makeDraggableObjectVisible(e);
},
_mouseUpHandler: function(e) {
if ( ! this.hasSelection() )
return;
var nsEvent = e.which != undefined;
if ( (nsEvent && e.which != 1) || (!nsEvent && e.button != 1))
return;
this.interestedInMotionEvents = false;
if ( this.dragElement == null ) {
this._terminateEvent(e);
return;
}
if ( this._placeDraggableInDropZone(e) )
this._completeDropOperation(e);
else {
this._terminateEvent(e);
new Rico.Effect.Position( this.dragElement,
this.origPos.x,
this.origPos.y,
200,
20,
{ complete : this._doCancelDragProcessing.bind(this) } );
}
Event.stopObserving(document.body, "mousemove", this._mouseMove);
Event.stopObserving(document.body, "mouseup", this._mouseUp);
},
_retTrue: function () {
return true;
},
_completeDropOperation: function(e) {
if ( this.dragElement != this.currentDragObjects[0].getMouseDownHTMLElement() ) {
if ( this.dragElement.parentNode != null )
this.dragElement.parentNode.removeChild(this.dragElement);
}
this._deactivateRegisteredDropZones();
this._endDrag();
this.clearSelection();
this.dragElement = null;
this.currentDragObjectVisible = false;
this._terminateEvent(e);
},
_doCancelDragProcessing: function() {
this._cancelDrag();
if ( this.dragElement != this.currentDragObjects[0].getMouseDownHTMLElement() && this.dragElement)
if ( this.dragElement.parentNode != null )
this.dragElement.parentNode.removeChild(this.dragElement);
this._deactivateRegisteredDropZones();
this.dragElement = null;
this.currentDragObjectVisible = false;
},
_placeDraggableInDropZone: function(e) {
var foundDropZone = false;
var n = this.dropZones.length;
for ( var i = 0 ; i < n ; i++ ) {
if ( this._mousePointInDropZone( e, this.dropZones[i] ) ) {
if ( this.dropZones[i].canAccept(this.currentDragObjects) ) {
this.dropZones[i].hideHover();
this.dropZones[i].accept(this.currentDragObjects);
foundDropZone = true;
break;
}
}
}
return foundDropZone;
},
_cancelDrag: function() {
for ( var i = 0 ; i < this.currentDragObjects.length ; i++ )
this.currentDragObjects[i].cancelDrag();
},
_endDrag: function() {
for ( var i = 0 ; i < this.currentDragObjects.length ; i++ )
this.currentDragObjects[i].endDrag();
},
_mousePointInDropZone: function( e, dropZone ) {
var absoluteRect = dropZone.getAbsoluteRect();
return e.clientX > absoluteRect.left + this._leftOffset(e) &&
e.clientX < absoluteRect.right + this._leftOffset(e) &&
e.clientY > absoluteRect.top + this._topOffset(e) &&
e.clientY < absoluteRect.bottom + this._topOffset(e);
},
_addMouseDownHandler: function( aDraggable )
{
htmlElement = aDraggable.getMouseDownHTMLElement();
if ( htmlElement != null ) {
htmlElement.draggable = aDraggable;
Event.observe(htmlElement , "mousedown", this._onmousedown.bindAsEventListener(this));
Event.observe(htmlElement, "mousedown", this._mouseDown);
}
},
_activateRegisteredDropZones: function() {
var n = this.dropZones.length;
for ( var i = 0 ; i < n ; i++ ) {
var dropZone = this.dropZones[i];
if ( dropZone.canAccept(this.currentDragObjects) )
dropZone.activate();
}
this.activatedDropZones = true;
},
_deactivateRegisteredDropZones: function() {
var n = this.dropZones.length;
for ( var i = 0 ; i < n ; i++ )
this.dropZones[i].deactivate();
this.activatedDropZones = false;
},
_onmousedown: function () {
Event.observe(document.body, "mousemove", this._mouseMove);
Event.observe(document.body, "mouseup", this._mouseUp);
},
_terminateEvent: function(e) {
if ( e.stopPropagation != undefined )
e.stopPropagation();
else if ( e.cancelBubble != undefined )
e.cancelBubble = true;
if ( e.preventDefault != undefined )
e.preventDefault();
else
e.returnValue = false;
},
initializeEventHandlers: function() {
if ( typeof document.implementation != "undefined" &&
document.implementation.hasFeature("HTML", "1.0") &&
document.implementation.hasFeature("Events", "2.0") &&
document.implementation.hasFeature("CSS", "2.0") ) {
document.addEventListener("mouseup", this._mouseUpHandler.bindAsEventListener(this), false);
document.addEventListener("mousemove", this._mouseMoveHandler.bindAsEventListener(this), false);
}
else {
document.attachEvent( "onmouseup", this._mouseUpHandler.bindAsEventListener(this) );
document.attachEvent( "onmousemove", this._mouseMoveHandler.bindAsEventListener(this) );
}
}
}
var dndMgr = new Rico.DragAndDrop();
dndMgr.initializeEventHandlers();
//-------------------- ricoDraggable.js
Rico.Draggable = Class.create();
Rico.Draggable.prototype = {
initialize: function( type, htmlElement ) {
this.type = type;
this.htmlElement = $(htmlElement);
this.selected = false;
},
/**
* Returns the HTML element that should have a mouse down event
* added to it in order to initiate a drag operation
*
**/
getMouseDownHTMLElement: function() {
return this.htmlElement;
},
select: function() {
this.selected = true;
if ( this.showingSelected )
return;
var htmlElement = this.getMouseDownHTMLElement();
var color = Rico.Color.createColorFromBackground(htmlElement);
color.isBright() ? color.darken(0.033) : color.brighten(0.033);
this.saveBackground = RicoUtil.getElementsComputedStyle(htmlElement, "backgroundColor", "background-color");
htmlElement.style.backgroundColor = color.asHex();
this.showingSelected = true;
},
deselect: function() {
this.selected = false;
if ( !this.showingSelected )
return;
var htmlElement = this.getMouseDownHTMLElement();
htmlElement.style.backgroundColor = this.saveBackground;
this.showingSelected = false;
},
isSelected: function() {
return this.selected;
},
startDrag: function() {
},
cancelDrag: function() {
},
endDrag: function() {
},
getSingleObjectDragGUI: function() {
return this.htmlElement;
},
getMultiObjectDragGUI: function( draggables ) {
return this.htmlElement;
},
getDroppedGUI: function() {
return this.htmlElement;
},
toString: function() {
return this.type + ":" + this.htmlElement + ":";
}
}
//-------------------- ricoDropzone.js
Rico.Dropzone = Class.create();
Rico.Dropzone.prototype = {
initialize: function( htmlElement ) {
this.htmlElement = $(htmlElement);
this.absoluteRect = null;
},
getHTMLElement: function() {
return this.htmlElement;
},
clearPositionCache: function() {
this.absoluteRect = null;
},
getAbsoluteRect: function() {
if ( this.absoluteRect == null ) {
var htmlElement = this.getHTMLElement();
var pos = RicoUtil.toViewportPosition(htmlElement);
this.absoluteRect = {
top: pos.y,
left: pos.x,
bottom: pos.y + htmlElement.offsetHeight,
right: pos.x + htmlElement.offsetWidth
};
}
return this.absoluteRect;
},
activate: function() {
var htmlElement = this.getHTMLElement();
if (htmlElement == null || this.showingActive)
return;
this.showingActive = true;
this.saveBackgroundColor = htmlElement.style.backgroundColor;
var fallbackColor = "#ffea84";
var currentColor = Rico.Color.createColorFromBackground(htmlElement);
if ( currentColor == null )
htmlElement.style.backgroundColor = fallbackColor;
else {
currentColor.isBright() ? currentColor.darken(0.2) : currentColor.brighten(0.2);
htmlElement.style.backgroundColor = currentColor.asHex();
}
},
deactivate: function() {
var htmlElement = this.getHTMLElement();
if (htmlElement == null || !this.showingActive)
return;
htmlElement.style.backgroundColor = this.saveBackgroundColor;
this.showingActive = false;
this.saveBackgroundColor = null;
},
showHover: function() {
var htmlElement = this.getHTMLElement();
if ( htmlElement == null || this.showingHover )
return;
this.saveBorderWidth = htmlElement.style.borderWidth;
this.saveBorderStyle = htmlElement.style.borderStyle;
this.saveBorderColor = htmlElement.style.borderColor;
this.showingHover = true;
htmlElement.style.borderWidth = "1px";
htmlElement.style.borderStyle = "solid";
//htmlElement.style.borderColor = "#ff9900";
htmlElement.style.borderColor = "#ffff00";
},
hideHover: function() {
var htmlElement = this.getHTMLElement();
if ( htmlElement == null || !this.showingHover )
return;
htmlElement.style.borderWidth = this.saveBorderWidth;
htmlElement.style.borderStyle = this.saveBorderStyle;
htmlElement.style.borderColor = this.saveBorderColor;
this.showingHover = false;
},
canAccept: function(draggableObjects) {
return true;
},
accept: function(draggableObjects) {
var htmlElement = this.getHTMLElement();
if ( htmlElement == null )
return;
n = draggableObjects.length;
for ( var i = 0 ; i < n ; i++ )
{
var theGUI = draggableObjects[i].getDroppedGUI();
if ( RicoUtil.getElementsComputedStyle( theGUI, "position" ) == "absolute" )
{
theGUI.style.position = "static";
theGUI.style.top = "";
theGUI.style.top = "";
}
htmlElement.appendChild(theGUI);
}
}
}
//-------------------- ricoEffects.js
Rico.Effect = {};
Rico.Effect.SizeAndPosition = Class.create();
Rico.Effect.SizeAndPosition.prototype = {
initialize: function(element, x, y, w, h, duration, steps, options) {
this.element = $(element);
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.duration = duration;
this.steps = steps;
this.options = arguments[7] || {};
this.sizeAndPosition();
},
sizeAndPosition: function() {
if (this.isFinished()) {
if(this.options.complete) this.options.complete(this);
return;
}
if (this.timer)
clearTimeout(this.timer);
var stepDuration = Math.round(this.duration/this.steps) ;
// Get original values: x,y = top left corner; w,h = width height
var currentX = this.element.offsetLeft;
var currentY = this.element.offsetTop;
var currentW = this.element.offsetWidth;
var currentH = this.element.offsetHeight;
// If values not set, or zero, we do not modify them, and take original as final as well
this.x = (this.x) ? this.x : currentX;
this.y = (this.y) ? this.y : currentY;
this.w = (this.w) ? this.w : currentW;
this.h = (this.h) ? this.h : currentH;
// how much do we need to modify our values for each step?
var difX = this.steps > 0 ? (this.x - currentX)/this.steps : 0;
var difY = this.steps > 0 ? (this.y - currentY)/this.steps : 0;
var difW = this.steps > 0 ? (this.w - currentW)/this.steps : 0;
var difH = this.steps > 0 ? (this.h - currentH)/this.steps : 0;
this.moveBy(difX, difY);
this.resizeBy(difW, difH);
this.duration -= stepDuration;
this.steps--;
this.timer = setTimeout(this.sizeAndPosition.bind(this), stepDuration);
},
isFinished: function() {
return this.steps <= 0;
},
moveBy: function( difX, difY ) {
var currentLeft = this.element.offsetLeft;
var currentTop = this.element.offsetTop;
var intDifX = parseInt(difX);
var intDifY = parseInt(difY);
var style = this.element.style;
if ( intDifX != 0 )
style.left = (currentLeft + intDifX) + "px";
if ( intDifY != 0 )
style.top = (currentTop + intDifY) + "px";
},
resizeBy: function( difW, difH ) {
var currentWidth = this.element.offsetWidth;
var currentHeight = this.element.offsetHeight;
var intDifW = parseInt(difW);
var intDifH = parseInt(difH);
var style = this.element.style;
if ( intDifW != 0 )
style.width = (currentWidth + intDifW) + "px";
if ( intDifH != 0 )
style.height = (currentHeight + intDifH) + "px";
}
}
Rico.Effect.Size = Class.create();
Rico.Effect.Size.prototype = {
initialize: function(element, w, h, duration, steps, options) {
new Rico.Effect.SizeAndPosition(element, null, null, w, h, duration, steps, options);
}
}
Rico.Effect.Position = Class.create();
Rico.Effect.Position.prototype = {
initialize: function(element, x, y, duration, steps, options) {
new Rico.Effect.SizeAndPosition(element, x, y, null, null, duration, steps, options);
}
}
Rico.Effect.Round = Class.create();
Rico.Effect.Round.prototype = {
initialize: function(tagName, className, options) {
var elements = document.getElementsByTagAndClassName(tagName,className);
for ( var i = 0 ; i < elements.length ; i++ )
Rico.Corner.round( elements[i], options );
}
};
Rico.Effect.FadeTo = Class.create();
Rico.Effect.FadeTo.prototype = {
initialize: function( element, opacity, duration, steps, options) {
this.element = $(element);
this.opacity = opacity;
this.duration = duration;
this.steps = steps;
this.options = arguments[4] || {};
this.fadeTo();
},
fadeTo: function() {
if (this.isFinished()) {
if(this.options.complete) this.options.complete(this);
return;
}
if (this.timer)
clearTimeout(this.timer);
var stepDuration = Math.round(this.duration/this.steps) ;
var currentOpacity = this.getElementOpacity();
var delta = this.steps > 0 ? (this.opacity - currentOpacity)/this.steps : 0;
this.changeOpacityBy(delta);
this.duration -= stepDuration;
this.steps--;
this.timer = setTimeout(this.fadeTo.bind(this), stepDuration);
},
changeOpacityBy: function(v) {
var currentOpacity = this.getElementOpacity();
var newOpacity = Math.max(0, Math.min(currentOpacity+v, 1));
this.element.ricoOpacity = newOpacity;
this.element.style.filter = "alpha(opacity:"+Math.round(newOpacity*100)+")";
this.element.style.opacity = newOpacity; /*//*/;
},
isFinished: function() {
return this.steps <= 0;
},
getElementOpacity: function() {
if ( this.element.ricoOpacity == undefined ) {
var opacity = RicoUtil.getElementsComputedStyle(this.element, 'opacity');
this.element.ricoOpacity = opacity != undefined ? opacity : 1.0;
}
return parseFloat(this.element.ricoOpacity);
}
}
Rico.Effect.AccordionSize = Class.create();
Rico.Effect.AccordionSize.prototype = {
initialize: function(e1, e2, start, end, duration, steps, options) {
this.e1 = $(e1);
this.e2 = $(e2);
this.start = start;
this.end = end;
this.duration = duration;
this.steps = steps;
this.options = arguments[6] || {};
this.accordionSize();
},
accordionSize: function() {
if (this.isFinished()) {
// just in case there are round errors or such...
this.e1.style.height = this.start + "px";
this.e2.style.height = this.end + "px";
if(this.options.complete)
this.options.complete(this);
return;
}
if (this.timer)
clearTimeout(this.timer);
var stepDuration = Math.round(this.duration/this.steps) ;
var diff = this.steps > 0 ? (parseInt(this.e1.offsetHeight) - this.start)/this.steps : 0;
this.resizeBy(diff);
this.duration -= stepDuration;
this.steps--;
this.timer = setTimeout(this.accordionSize.bind(this), stepDuration);
},
isFinished: function() {
return this.steps <= 0;
},
resizeBy: function(diff) {
var h1Height = this.e1.offsetHeight;
var h2Height = this.e2.offsetHeight;
var intDiff = parseInt(diff);
if ( diff != 0 ) {
this.e1.style.height = (h1Height - intDiff) + "px";
this.e2.style.height = (h2Height + intDiff) + "px";
}
}
};
//-------------------- ricoLiveGrid.js
// Rico.LiveGridMetaData -----------------------------------------------------
Rico.LiveGridMetaData = Class.create();
Rico.LiveGridMetaData.prototype = {
initialize: function( pageSize, totalRows, columnCount, options ) {
this.pageSize = pageSize;
this.totalRows = totalRows;
this.setOptions(options);
this.ArrowHeight = 16;
this.columnCount = columnCount;
},
setOptions: function(options) {
this.options = {
largeBufferSize : 7.0, // 7 pages
nearLimitFactor : 0.2 // 20% of buffer
};
Object.extend(this.options, options || {});
},
getPageSize: function() {
return this.pageSize;
},
getTotalRows: function() {
return this.totalRows;
},
setTotalRows: function(n) {
this.totalRows = n;
},
getLargeBufferSize: function() {
return parseInt(this.options.largeBufferSize * this.pageSize);
},
getLimitTolerance: function() {
return parseInt(this.getLargeBufferSize() * this.options.nearLimitFactor);
}
};
// Rico.LiveGridScroller -----------------------------------------------------
Rico.LiveGridScroller = Class.create();
Rico.LiveGridScroller.prototype = {
initialize: function(liveGrid, viewPort) {
this.isIE = navigator.userAgent.toLowerCase().indexOf("msie") >= 0;
this.liveGrid = liveGrid;
this.metaData = liveGrid.metaData;
this.createScrollBar();
this.scrollTimeout = null;
this.lastScrollPos = 0;
this.viewPort = viewPort;
this.rows = new Array();
},
isUnPlugged: function() {
return this.scrollerDiv.onscroll == null;
},
plugin: function() {
this.scrollerDiv.onscroll = this.handleScroll.bindAsEventListener(this);
},
unplug: function() {
this.scrollerDiv.onscroll = null;
},
sizeIEHeaderHack: function() {
if ( !this.isIE ) return;
var headerTable = $(this.liveGrid.tableId + "_header");
if ( headerTable )
headerTable.rows[0].cells[0].style.width =
(headerTable.rows[0].cells[0].offsetWidth + 1) + "px";
},
createScrollBar: function() {
var visibleHeight = this.liveGrid.viewPort.visibleHeight();
// create the outer div...
this.scrollerDiv = document.createElement("div");
var scrollerStyle = this.scrollerDiv.style;
scrollerStyle.borderRight = this.liveGrid.options.scrollerBorderRight;
scrollerStyle.position = "relative";
scrollerStyle.left = this.isIE ? "-6px" : "-3px";
scrollerStyle.width = "19px";
scrollerStyle.height = visibleHeight + "px";
scrollerStyle.overflow = "auto";
// create the inner div...
this.heightDiv = document.createElement("div");
this.heightDiv.style.width = "1px";
this.heightDiv.style.height = parseInt(visibleHeight *
this.metaData.getTotalRows()/this.metaData.getPageSize()) + "px" ;
this.scrollerDiv.appendChild(this.heightDiv);
this.scrollerDiv.onscroll = this.handleScroll.bindAsEventListener(this);
var table = this.liveGrid.table;
table.parentNode.parentNode.insertBefore( this.scrollerDiv, table.parentNode.nextSibling );
var eventName = this.isIE ? "mousewheel" : "DOMMouseScroll";
Event.observe(table, eventName,
function(evt) {
if (evt.wheelDelta>=0 || evt.detail < 0) //wheel-up
this.scrollerDiv.scrollTop -= (2*this.viewPort.rowHeight);
else
this.scrollerDiv.scrollTop += (2*this.viewPort.rowHeight);
this.handleScroll(false);
}.bindAsEventListener(this),
false);
},
updateSize: function() {
var table = this.liveGrid.table;
var visibleHeight = this.viewPort.visibleHeight();
this.heightDiv.style.height = parseInt(visibleHeight *
this.metaData.getTotalRows()/this.metaData.getPageSize()) + "px";
},
rowToPixel: function(rowOffset) {
return (rowOffset / this.metaData.getTotalRows()) * this.heightDiv.offsetHeight
},
moveScroll: function(rowOffset) {
this.scrollerDiv.scrollTop = this.rowToPixel(rowOffset);
if ( this.metaData.options.onscroll )
this.metaData.options.onscroll( this.liveGrid, rowOffset );
},
handleScroll: function() {
if ( this.scrollTimeout )
clearTimeout( this.scrollTimeout );
var scrollDiff = this.lastScrollPos-this.scrollerDiv.scrollTop;
if (scrollDiff != 0.00) {
var r = this.scrollerDiv.scrollTop % this.viewPort.rowHeight;
if (r != 0) {
this.unplug();
if ( scrollDiff < 0 ) {
this.scrollerDiv.scrollTop += (this.viewPort.rowHeight-r);
} else {
this.scrollerDiv.scrollTop -= r;
}
this.plugin();
}
}
var contentOffset = parseInt(this.scrollerDiv.scrollTop / this.viewPort.rowHeight);
this.liveGrid.requestContentRefresh(contentOffset);
this.viewPort.scrollTo(this.scrollerDiv.scrollTop);
if ( this.metaData.options.onscroll )
this.metaData.options.onscroll( this.liveGrid, contentOffset );
this.scrollTimeout = setTimeout(this.scrollIdle.bind(this), 1200 );
this.lastScrollPos = this.scrollerDiv.scrollTop;
},
scrollIdle: function() {
if ( this.metaData.options.onscrollidle )
this.metaData.options.onscrollidle();
}
};
// Rico.LiveGridBuffer -----------------------------------------------------
Rico.LiveGridBuffer = Class.create();
Rico.LiveGridBuffer.prototype = {
initialize: function(metaData, viewPort) {
this.startPos = 0;
this.size = 0;
this.metaData = metaData;
this.rows = new Array();
this.updateInProgress = false;
this.viewPort = viewPort;
this.maxBufferSize = metaData.getLargeBufferSize() * 2;
this.maxFetchSize = metaData.getLargeBufferSize();
this.lastOffset = 0;
},
getBlankRow: function() {
if (!this.blankRow ) {
this.blankRow = new Array();
for ( var i=0; i < this.metaData.columnCount ; i++ )
this.blankRow[i] = " ";
}
return this.blankRow;
},
loadRows: function(ajaxResponse) {
var rowsElement = ajaxResponse.getElementsByTagName('rows')[0];
this.updateUI = rowsElement.getAttribute("update_ui") == "true"
var newRows = new Array()
var trs = rowsElement.getElementsByTagName("tr");
for ( var i=0 ; i < trs.length; i++ ) {
var row = newRows[i] = new Array();
var cells = trs[i].getElementsByTagName("td");
for ( var j=0; j < cells.length ; j++ ) {
var cell = cells[j];
var convertSpaces = cell.getAttribute("convert_spaces") == "true";
var cellContent = RicoUtil.getContentAsString(cell);
row[j] = convertSpaces ? this.convertSpaces(cellContent) : cellContent;
if (!row[j])
row[j] = ' ';
}
}
return newRows;
},
update: function(ajaxResponse, start) {
var newRows = this.loadRows(ajaxResponse);
if (this.rows.length == 0) { // initial load
this.rows = newRows;
this.size = this.rows.length;
this.startPos = start;
return;
}
if (start > this.startPos) { //appending
if (this.startPos + this.rows.length < start) {
this.rows = newRows;
this.startPos = start;//
} else {
this.rows = this.rows.concat( newRows.slice(0, newRows.length));
if (this.rows.length > this.maxBufferSize) {
var fullSize = this.rows.length;
this.rows = this.rows.slice(this.rows.length - this.maxBufferSize, this.rows.length)
this.startPos = this.startPos + (fullSize - this.rows.length);
}
}
} else { //prepending
if (start + newRows.length < this.startPos) {
this.rows = newRows;
} else {
this.rows = newRows.slice(0, this.startPos).concat(this.rows);
if (this.rows.length > this.maxBufferSize)
this.rows = this.rows.slice(0, this.maxBufferSize)
}
this.startPos = start;
}
this.size = this.rows.length;
},
clear: function() {
this.rows = new Array();
this.startPos = 0;
this.size = 0;
},
isOverlapping: function(start, size) {
return ((start < this.endPos()) && (this.startPos < start + size)) || (this.endPos() == 0)
},
isInRange: function(position) {
return (position >= this.startPos) && (position + this.metaData.getPageSize() <= this.endPos());
//&& this.size() != 0;
},
isNearingTopLimit: function(position) {
return position - this.startPos < this.metaData.getLimitTolerance();
},
endPos: function() {
return this.startPos + this.rows.length;
},
isNearingBottomLimit: function(position) {
return this.endPos() - (position + this.metaData.getPageSize()) < this.metaData.getLimitTolerance();
},
isAtTop: function() {
return this.startPos == 0;
},
isAtBottom: function() {
return this.endPos() == this.metaData.getTotalRows();
},
isNearingLimit: function(position) {
return ( !this.isAtTop() && this.isNearingTopLimit(position)) ||
( !this.isAtBottom() && this.isNearingBottomLimit(position) )
},
getFetchSize: function(offset) {
var adjustedOffset = this.getFetchOffset(offset);
var adjustedSize = 0;
if (adjustedOffset >= this.startPos) { //apending
var endFetchOffset = this.maxFetchSize + adjustedOffset;
if (endFetchOffset > this.metaData.totalRows)
endFetchOffset = this.metaData.totalRows;
adjustedSize = endFetchOffset - adjustedOffset;
if(adjustedOffset == 0 && adjustedSize < this.maxFetchSize){
adjustedSize = this.maxFetchSize;
}
} else {//prepending
var adjustedSize = this.startPos - adjustedOffset;
if (adjustedSize > this.maxFetchSize)
adjustedSize = this.maxFetchSize;
}
return adjustedSize;
},
getFetchOffset: function(offset) {
var adjustedOffset = offset;
if (offset > this.startPos) //apending
adjustedOffset = (offset > this.endPos()) ? offset : this.endPos();
else { //prepending
if (offset + this.maxFetchSize >= this.startPos) {
var adjustedOffset = this.startPos - this.maxFetchSize;
if (adjustedOffset < 0)
adjustedOffset = 0;
}
}
this.lastOffset = adjustedOffset;
return adjustedOffset;
},
getRows: function(start, count) {
var begPos = start - this.startPos
var endPos = begPos + count
// er? need more data...
if ( endPos > this.size )
endPos = this.size
var results = new Array()
var index = 0;
for ( var i=begPos ; i < endPos; i++ ) {
results[index++] = this.rows[i]
}
return results
},
convertSpaces: function(s) {
return s.split(" ").join(" ");
}
};
//Rico.GridViewPort --------------------------------------------------
Rico.GridViewPort = Class.create();
Rico.GridViewPort.prototype = {
initialize: function(table, rowHeight, visibleRows, buffer, liveGrid) {
this.lastDisplayedStartPos = 0;
this.div = table.parentNode;
this.table = table
this.rowHeight = rowHeight;
this.div.style.height = (this.rowHeight * visibleRows) + "px";
this.div.style.overflow = "hidden";
this.buffer = buffer;
this.liveGrid = liveGrid;
this.visibleRows = visibleRows + 1;
this.lastPixelOffset = 0;
this.startPos = 0;
},
populateRow: function(htmlRow, row) {
for (var j=0; j < row.length; j++) {
htmlRow.cells[j].innerHTML = row[j]
}
},
bufferChanged: function() {
this.refreshContents( parseInt(this.lastPixelOffset / this.rowHeight));
},
clearRows: function() {
if (!this.isBlank) {
this.liveGrid.table.className = this.liveGrid.options.loadingClass;
for (var i=0; i < this.visibleRows; i++)
this.populateRow(this.table.rows[i], this.buffer.getBlankRow());
this.isBlank = true;
}
},
clearContents: function() {
this.clearRows();
this.scrollTo(0);
this.startPos = 0;
this.lastStartPos = -1;
},
refreshContents: function(startPos) {
if (startPos == this.lastRowPos && !this.isPartialBlank && !this.isBlank) {
return;
}
if ((startPos + this.visibleRows < this.buffer.startPos)
|| (this.buffer.startPos + this.buffer.size < startPos)
|| (this.buffer.size == 0)) {
this.clearRows();
return;
}
this.isBlank = false;
var viewPrecedesBuffer = this.buffer.startPos > startPos
var contentStartPos = viewPrecedesBuffer ? this.buffer.startPos: startPos;
var contentEndPos = (this.buffer.startPos + this.buffer.size < startPos + this.visibleRows)
? this.buffer.startPos + this.buffer.size
: startPos + this.visibleRows;
var rowSize = contentEndPos - contentStartPos;
var rows = this.buffer.getRows(contentStartPos, rowSize );
var blankSize = this.visibleRows - rowSize;
var blankOffset = viewPrecedesBuffer ? 0: rowSize;
var contentOffset = viewPrecedesBuffer ? blankSize: 0;
for (var i=0; i < rows.length; i++) {//initialize what we have
this.populateRow(this.table.rows[i + contentOffset], rows[i]);
}
for (var i=0; i < blankSize; i++) {// blank out the rest
this.populateRow(this.table.rows[i + blankOffset], this.buffer.getBlankRow());
}
this.isPartialBlank = blankSize > 0;
this.lastRowPos = startPos;
this.liveGrid.table.className = this.liveGrid.options.tableClass;
// Check if user has set a onRefreshComplete function
var onRefreshComplete = this.liveGrid.options.onRefreshComplete;
if (onRefreshComplete != null)
onRefreshComplete();
},
scrollTo: function(pixelOffset) {
if (this.lastPixelOffset == pixelOffset)
return;
this.refreshContents(parseInt(pixelOffset / this.rowHeight))
this.div.scrollTop = pixelOffset % this.rowHeight
this.lastPixelOffset = pixelOffset;
},
visibleHeight: function() {
return parseInt(RicoUtil.getElementsComputedStyle(this.div, 'height'));
}
};
Rico.LiveGridRequest = Class.create();
Rico.LiveGridRequest.prototype = {
initialize: function( requestOffset, options ) {
this.requestOffset = requestOffset;
}
};
// Rico.LiveGrid -----------------------------------------------------
Rico.LiveGrid = Class.create();
Rico.LiveGrid.prototype = {
initialize: function( tableId, visibleRows, totalRows, url, options, ajaxOptions ) {
this.options = {
tableClass: $(tableId).className,
loadingClass: $(tableId).className,
scrollerBorderRight: '1px solid #ababab',
bufferTimeout: 20000,
sortAscendImg: 'images/sort_asc.gif',
sortDescendImg: 'images/sort_desc.gif',
sortImageWidth: 9,
sortImageHeight: 5,
ajaxSortURLParms: [],
onRefreshComplete: null,
requestParameters: null,
inlineStyles: true
};
Object.extend(this.options, options || {});
this.ajaxOptions = {parameters: null};
Object.extend(this.ajaxOptions, ajaxOptions || {});
this.tableId = tableId;
this.table = $(tableId);
this.addLiveGridHtml();
var columnCount = this.table.rows[0].cells.length;
this.metaData = new Rico.LiveGridMetaData(visibleRows, totalRows, columnCount, options);
this.buffer = new Rico.LiveGridBuffer(this.metaData);
var rowCount = this.table.rows.length;
this.viewPort = new Rico.GridViewPort(this.table,
this.table.offsetHeight/rowCount,
visibleRows,
this.buffer, this);
this.scroller = new Rico.LiveGridScroller(this,this.viewPort);
this.options.sortHandler = this.sortHandler.bind(this);
if ( $(tableId + '_header') )
this.sort = new Rico.LiveGridSort(tableId + '_header', this.options)
this.processingRequest = null;
this.unprocessedRequest = null;
this.initAjax(url);
if ( this.options.prefetchBuffer || this.options.prefetchOffset > 0) {
var offset = 0;
if (this.options.offset ) {
offset = this.options.offset;
this.scroller.moveScroll(offset);
this.viewPort.scrollTo(this.scroller.rowToPixel(offset));
}
if (this.options.sortCol) {
this.sortCol = options.sortCol;
this.sortDir = options.sortDir;
}
this.requestContentRefresh(offset);
}
},
addLiveGridHtml: function() {
// Check to see if need to create a header table.
if (this.table.getElementsByTagName("thead").length > 0){
// Create Table this.tableId+'_header'
var tableHeader = this.table.cloneNode(true);
tableHeader.setAttribute('id', this.tableId+'_header');
tableHeader.setAttribute('class', this.table.className+'_header');
// Clean up and insert
for( var i = 0; i < tableHeader.tBodies.length; i++ )
tableHeader.removeChild(tableHeader.tBodies[i]);
this.table.deleteTHead();
this.table.parentNode.insertBefore(tableHeader,this.table);
}
new Insertion.Before(this.table, "<div id='"+this.tableId+"_container'></div>");
this.table.previousSibling.appendChild(this.table);
new Insertion.Before(this.table,"<div id='"+this.tableId+"_viewport' style='float:left;'></div>");
this.table.previousSibling.appendChild(this.table);
},
resetContents: function() {
this.scroller.moveScroll(0);
this.buffer.clear();
this.viewPort.clearContents();
},
sortHandler: function(column) {
if(!column) return ;
this.sortCol = column.name;
this.sortDir = column.currentSort;
this.resetContents();
this.requestContentRefresh(0)
},
adjustRowSize: function() {
},
setTotalRows: function( newTotalRows ) {
this.resetContents();
this.metaData.setTotalRows(newTotalRows);
this.scroller.updateSize();
},
initAjax: function(url) {
ajaxEngine.registerRequest( this.tableId + '_request', url );
ajaxEngine.registerAjaxObject( this.tableId + '_updater', this );
},
invokeAjax: function() {
},
handleTimedOut: function() {
//server did not respond in 4 seconds... assume that there could have been
//an error or something, and allow requests to be processed again...
this.processingRequest = null;
this.processQueuedRequest();
},
fetchBuffer: function(offset) {
if ( this.buffer.isInRange(offset) &&
!this.buffer.isNearingLimit(offset)) {
return;
}
if (this.processingRequest) {
this.unprocessedRequest = new Rico.LiveGridRequest(offset);
return;
}
var bufferStartPos = this.buffer.getFetchOffset(offset);
this.processingRequest = new Rico.LiveGridRequest(offset);
this.processingRequest.bufferOffset = bufferStartPos;
var fetchSize = this.buffer.getFetchSize(offset);
var partialLoaded = false;
var queryString
if (this.options.requestParameters)
queryString = this._createQueryString(this.options.requestParameters, 0);
queryString = (queryString == null) ? '' : queryString+'&';
queryString = queryString+'id='+this.tableId+'&page_size='+fetchSize+'&offset='+bufferStartPos;
if (this.sortCol)
queryString = queryString+'&sort_col='+escape(this.sortCol)+'&sort_dir='+this.sortDir;
this.ajaxOptions.parameters = queryString;
ajaxEngine.sendRequest( this.tableId + '_request', this.ajaxOptions );
this.timeoutHandler = setTimeout( this.handleTimedOut.bind(this), this.options.bufferTimeout);
},
setRequestParams: function() {
this.options.requestParameters = [];
for ( var i=0 ; i < arguments.length ; i++ )
this.options.requestParameters[i] = arguments[i];
},
requestContentRefresh: function(contentOffset) {
this.fetchBuffer(contentOffset);
},
ajaxUpdate: function(ajaxResponse) {
try {
clearTimeout( this.timeoutHandler );
this.buffer.update(ajaxResponse,this.processingRequest.bufferOffset);
this.viewPort.bufferChanged();
}
catch(err) {}
finally {this.processingRequest = null; }
this.processQueuedRequest();
},
_createQueryString: function( theArgs, offset ) {
var queryString = ""
if (!theArgs)
return queryString;
for ( var i = offset ; i < theArgs.length ; i++ ) {
if ( i != offset )
queryString += "&";
var anArg = theArgs[i];
if ( anArg.name != undefined && anArg.value != undefined ) {
queryString += anArg.name + "=" + escape(anArg.value);
}
else {
var ePos = anArg.indexOf('=');
var argName = anArg.substring( 0, ePos );
var argValue = anArg.substring( ePos + 1 );
queryString += argName + "=" + escape(argValue);
}
}
return queryString;
},
processQueuedRequest: function() {
if (this.unprocessedRequest != null) {
this.requestContentRefresh(this.unprocessedRequest.requestOffset);
this.unprocessedRequest = null
}
}
};
//-------------------- ricoLiveGridSort.js
Rico.LiveGridSort = Class.create();
Rico.LiveGridSort.prototype = {
initialize: function(headerTableId, options) {
this.headerTableId = headerTableId;
this.headerTable = $(headerTableId);
this.options = options;
this.setOptions();
this.applySortBehavior();
if ( this.options.sortCol ) {
this.setSortUI( this.options.sortCol, this.options.sortDir );
}
},
setSortUI: function( columnName, sortDirection ) {
var cols = this.options.columns;
for ( var i = 0 ; i < cols.length ; i++ ) {
if ( cols[i].name == columnName ) {
this.setColumnSort(i, sortDirection);
break;
}
}
},
setOptions: function() {
// preload the images...
new Image().src = this.options.sortAscendImg;
new Image().src = this.options.sortDescendImg;
this.sort = this.options.sortHandler;
if ( !this.options.columns )
this.options.columns = this.introspectForColumnInfo();
else {
// allow client to pass { columns: [ ["a", true], ["b", false] ] }
// and convert to an array of Rico.TableColumn objs...
this.options.columns = this.convertToTableColumns(this.options.columns);
}
},
applySortBehavior: function() {
var headerRow = this.headerTable.rows[0];
var headerCells = headerRow.cells;
for ( var i = 0 ; i < headerCells.length ; i++ ) {
this.addSortBehaviorToColumn( i, headerCells[i] );
}
},
addSortBehaviorToColumn: function( n, cell ) {
if ( this.options.columns[n].isSortable() ) {
cell.id = this.headerTableId + '_' + n;
cell.style.cursor = 'pointer';
cell.onclick = this.headerCellClicked.bindAsEventListener(this);
cell.innerHTML = cell.innerHTML + '<span id="' + this.headerTableId + '_img_' + n + '">'
+ ' </span>';
}
},
// event handler....
headerCellClicked: function(evt) {
var eventTarget = evt.target ? evt.target : evt.srcElement;
var cellId = eventTarget.id;
var columnNumber = parseInt(cellId.substring( cellId.lastIndexOf('_') + 1 ));
var sortedColumnIndex = this.getSortedColumnIndex();
if ( sortedColumnIndex != -1 ) {
if ( sortedColumnIndex != columnNumber ) {
this.removeColumnSort(sortedColumnIndex);
this.setColumnSort(columnNumber, Rico.TableColumn.SORT_ASC);
}
else
this.toggleColumnSort(sortedColumnIndex);
}
else
this.setColumnSort(columnNumber, Rico.TableColumn.SORT_ASC);
if (this.options.sortHandler) {
this.options.sortHandler(this.options.columns[columnNumber]);
}
},
removeColumnSort: function(n) {
this.options.columns[n].setUnsorted();
this.setSortImage(n);
},
setColumnSort: function(n, direction) {
if(isNaN(n)) return ;
this.options.columns[n].setSorted(direction);
this.setSortImage(n);
},
toggleColumnSort: function(n) {
this.options.columns[n].toggleSort();
this.setSortImage(n);
},
setSortImage: function(n) {
var sortDirection = this.options.columns[n].getSortDirection();
var sortImageSpan = $( this.headerTableId + '_img_' + n );
if ( sortDirection == Rico.TableColumn.UNSORTED )
sortImageSpan.innerHTML = ' ';
else if ( sortDirection == Rico.TableColumn.SORT_ASC )
sortImageSpan.innerHTML = ' <img width="' + this.options.sortImageWidth + '" ' +
'height="'+ this.options.sortImageHeight + '" ' +
'src="' + this.options.sortAscendImg + '"/>';
else if ( sortDirection == Rico.TableColumn.SORT_DESC )
sortImageSpan.innerHTML = ' <img width="' + this.options.sortImageWidth + '" ' +
'height="'+ this.options.sortImageHeight + '" ' +
'src="' + this.options.sortDescendImg + '"/>';
},
getSortedColumnIndex: function() {
var cols = this.options.columns;
for ( var i = 0 ; i < cols.length ; i++ ) {
if ( cols[i].isSorted() )
return i;
}
return -1;
},
introspectForColumnInfo: function() {
var columns = new Array();
var headerRow = this.headerTable.rows[0];
var headerCells = headerRow.cells;
for ( var i = 0 ; i < headerCells.length ; i++ )
columns.push( new Rico.TableColumn( this.deriveColumnNameFromCell(headerCells[i],i), true ) );
return columns;
},
convertToTableColumns: function(cols) {
var columns = new Array();
for ( var i = 0 ; i < cols.length ; i++ )
columns.push( new Rico.TableColumn( cols[i][0], cols[i][1] ) );
return columns;
},
deriveColumnNameFromCell: function(cell,columnNumber) {
var cellContent = cell.innerText != undefined ? cell.innerText : cell.textContent;
return cellContent ? cellContent.toLowerCase().split(' ').join('_') : "col_" + columnNumber;
}
};
Rico.TableColumn = Class.create();
Rico.TableColumn.UNSORTED = 0;
Rico.TableColumn.SORT_ASC = "ASC";
Rico.TableColumn.SORT_DESC = "DESC";
Rico.TableColumn.prototype = {
initialize: function(name, sortable) {
this.name = name;
this.sortable = sortable;
this.currentSort = Rico.TableColumn.UNSORTED;
},
isSortable: function() {
return this.sortable;
},
isSorted: function() {
return this.currentSort != Rico.TableColumn.UNSORTED;
},
getSortDirection: function() {
return this.currentSort;
},
toggleSort: function() {
if ( this.currentSort == Rico.TableColumn.UNSORTED || this.currentSort == Rico.TableColumn.SORT_DESC )
this.currentSort = Rico.TableColumn.SORT_ASC;
else if ( this.currentSort == Rico.TableColumn.SORT_ASC )
this.currentSort = Rico.TableColumn.SORT_DESC;
},
setUnsorted: function(direction) {
this.setSorted(Rico.TableColumn.UNSORTED);
},
setSorted: function(direction) {
// direction must by one of Rico.TableColumn.UNSORTED, .SORT_ASC, or .SORT_DESC...
this.currentSort = direction;
}
};
//-------------------- ricoUtil.js
var RicoUtil = {
getElementsComputedStyle: function ( htmlElement, cssProperty, mozillaEquivalentCSS) {
if ( arguments.length == 2 )
mozillaEquivalentCSS = cssProperty;
var el = $(htmlElement);
if ( el.currentStyle )
return el.currentStyle[cssProperty];
else
return document.defaultView.getComputedStyle(el, null).getPropertyValue(mozillaEquivalentCSS);
},
createXmlDocument : function() {
if (document.implementation && document.implementation.createDocument) {
var doc = document.implementation.createDocument("", "", null);
if (doc.readyState == null) {
doc.readyState = 1;
doc.addEventListener("load", function () {
doc.readyState = 4;
if (typeof doc.onreadystatechange == "function")
doc.onreadystatechange();
}, false);
}
return doc;
}
if (window.ActiveXObject)
return Try.these(
function() { return new ActiveXObject('MSXML2.DomDocument') },
function() { return new ActiveXObject('Microsoft.DomDocument')},
function() { return new ActiveXObject('MSXML.DomDocument') },
function() { return new ActiveXObject('MSXML3.DomDocument') }
) || false;
return null;
},
getContentAsString: function( parentNode ) {
return parentNode.xml != undefined ?
this._getContentAsStringIE(parentNode) :
this._getContentAsStringMozilla(parentNode);
},
_getContentAsStringIE: function(parentNode) {
var contentStr = "";
for ( var i = 0 ; i < parentNode.childNodes.length ; i++ ) {
var n = parentNode.childNodes[i];
if (n.nodeType == 4) {
contentStr += n.nodeValue;
}
else {
contentStr += n.xml;
}
}
return contentStr;
},
_getContentAsStringMozilla: function(parentNode) {
var xmlSerializer = new XMLSerializer();
var contentStr = "";
for ( var i = 0 ; i < parentNode.childNodes.length ; i++ ) {
var n = parentNode.childNodes[i];
if (n.nodeType == 4) { // CDATA node
contentStr += n.nodeValue;
}
else {
contentStr += xmlSerializer.serializeToString(n);
}
}
return contentStr;
},
toViewportPosition: function(element) {
return this._toAbsolute(element,true);
},
toDocumentPosition: function(element) {
return this._toAbsolute(element,false);
},
/**
* Compute the elements position in terms of the window viewport
* so that it can be compared to the position of the mouse (dnd)
* This is additions of all the offsetTop,offsetLeft values up the
* offsetParent hierarchy, ...taking into account any scrollTop,
* scrollLeft values along the way...
*
* IE has a bug reporting a correct offsetLeft of elements within a
* a relatively positioned parent!!!
**/
_toAbsolute: function(element,accountForDocScroll) {
if ( navigator.userAgent.toLowerCase().indexOf("msie") == -1 )
return this._toAbsoluteMozilla(element,accountForDocScroll);
var x = 0;
var y = 0;
var parent = element;
while ( parent ) {
var borderXOffset = 0;
var borderYOffset = 0;
if ( parent != element ) {
var borderXOffset = parseInt(this.getElementsComputedStyle(parent, "borderLeftWidth" ));
var borderYOffset = parseInt(this.getElementsComputedStyle(parent, "borderTopWidth" ));
borderXOffset = isNaN(borderXOffset) ? 0 : borderXOffset;
borderYOffset = isNaN(borderYOffset) ? 0 : borderYOffset;
}
x += parent.offsetLeft - parent.scrollLeft + borderXOffset;
y += parent.offsetTop - parent.scrollTop + borderYOffset;
parent = parent.offsetParent;
}
if ( accountForDocScroll ) {
x -= this.docScrollLeft();
y -= this.docScrollTop();
}
return { x:x, y:y };
},
/**
* Mozilla did not report all of the parents up the hierarchy via the
* offsetParent property that IE did. So for the calculation of the
* offsets we use the offsetParent property, but for the calculation of
* the scrollTop/scrollLeft adjustments we navigate up via the parentNode
* property instead so as to get the scroll offsets...
*
**/
_toAbsoluteMozilla: function(element,accountForDocScroll) {
var x = 0;
var y = 0;
var parent = element;
while ( parent ) {
x += parent.offsetLeft;
y += parent.offsetTop;
parent = parent.offsetParent;
}
parent = element;
while ( parent &&
parent != document.body &&
parent != document.documentElement ) {
if ( parent.scrollLeft )
x -= parent.scrollLeft;
if ( parent.scrollTop )
y -= parent.scrollTop;
parent = parent.parentNode;
}
if ( accountForDocScroll ) {
x -= this.docScrollLeft();
y -= this.docScrollTop();
}
return { x:x, y:y };
},
docScrollLeft: function() {
if ( window.pageXOffset )
return window.pageXOffset;
else if ( document.documentElement && document.documentElement.scrollLeft )
return document.documentElement.scrollLeft;
else if ( document.body )
return document.body.scrollLeft;
else
return 0;
},
docScrollTop: function() {
if ( window.pageYOffset )
return window.pageYOffset;
else if ( document.documentElement && document.documentElement.scrollTop )
return document.documentElement.scrollTop;
else if ( document.body )
return document.body.scrollTop;
else
return 0;
}
};
| sgruhier/prototype_window | samples/rico/rico_change.js | JavaScript | mit | 92,933 |
var struct_jmcpp_1_1_group_info_updated_event =
[
[ "fromUser", "struct_jmcpp_1_1_group_info_updated_event.html#a01d445e6f171e3f38103f38d1f82e041", null ],
[ "groupId", "struct_jmcpp_1_1_group_info_updated_event.html#a7775458e8f2504cbdea378e5005a544a", null ],
[ "users", "struct_jmcpp_1_1_group_info_updated_event.html#a58c9232407bf86989e54d824182fe5f4", null ]
]; | xiongtiancheng/jpush-docs | zh/jmessage/client/im_win_api_docs/struct_jmcpp_1_1_group_info_updated_event.js | JavaScript | mit | 377 |
define({
"unit": "Jedinica",
"style": "Stil",
"dual": "dvostruki",
"english": "engleski",
"metric": "metrički",
"ruler": "ravnalo",
"line": "linija",
"number": "broj",
"spinnerLabel": "Zaokruži broj mjerila na: ",
"decimalPlace": "decimalno mjesto",
"separator": "Prikaži razdjelnik tisućica"
}); | tmcgee/cmv-wab-widgets | wab/2.15/widgets/Scalebar/setting/nls/hr/strings.js | JavaScript | mit | 322 |
var fs = require('fs');
var path = require('path');
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
copy: {
main: {
files: [
{src: 'numbro.js', dest: 'dist/numbro.js'},
]
}
},
concat: {
languages: {
src: [
'languages/**/*.js',
],
dest: 'dist/languages.js',
},
},
uglify: {
target: {
files: [
{ src: [ 'dist/languages.js' ], dest: 'dist/languages.min.js', },
{ src: [ 'numbro.js' ], dest: 'dist/numbro.min.js', },
].concat( fs.readdirSync('./languages').map(function (fileName) {
var lang = path.basename(fileName, '.js');
return {
src: [path.join('languages/', fileName)],
dest: path.join('dist/languages/', lang + '.min.js'),
};
}))
},
options: {
preserveComments: 'some',
},
},
bump: {
options: {
files: [
'package.json',
'bower.json',
'component.json',
'numbro.js',
],
updateConfigs: ['pkg'],
commit: false,
createTag: false,
push: false,
globalReplace: true,
regExp: new RegExp('([\'|\"]?version[\'|\"]?[ ]*[:=][ ]*[\'|\"]?)'+
'(\\d+\\.\\d+\\.\\d+(-\\.\\d+)?(-\\d+)?)[\\d||A-a|.|-]*([\'|\"]?)')
},
},
confirm: {
release: {
options: {
question: 'Are you sure you want to publish a new release' +
' with version <%= pkg.version %>? (yes/no)',
continue: function(answer) {
return ['yes', 'y'].indexOf(answer.toLowerCase()) !== -1;
}
}
}
},
release:{
options: {
bump: false,
commit: false,
tagName: '<%= version %>',
},
},
nodeunit: {
all: ['tests/**/*.js'],
},
jshint: {
options: {
jshintrc : '.jshintrc'
},
all: [
'Gruntfile.js',
'numbro.js',
'languages/**/*.js'
]
},
jscs: {
src: [
'Gruntfile.js',
'numbro.js',
'languages/**/*.js'
],
options: {
config: '.jscsrc',
esnext: true, // If you use ES6 http://jscs.info/overview.html#esnext
verbose: true, // If you need output with rule names http://jscs.info/overview.html#verbose
validateIndentation: 4
}
}
});
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-confirm');
grunt.loadNpmTasks('grunt-release');
grunt.loadNpmTasks('grunt-jscs');
grunt.registerTask('default', [
'test'
]);
grunt.registerTask('lint', [
'jshint',
'jscs'
]);
grunt.registerTask('test', [
'lint',
'nodeunit'
]);
grunt.registerTask('build', [
'test',
'copy:main',
'concat',
'uglify'
]);
// wrap grunt-release with confirmation
grunt.registerTask('publish', [
'confirm:release',
'release',
]);
// Travis CI task.
grunt.registerTask('travis', ['test']);
};
| atuttle/numbro | Gruntfile.js | JavaScript | mit | 4,121 |
module.exports={title:"RubyGems",slug:"rubygems",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>RubyGems icon</title><path d="M7.81 7.9l-2.97 2.95 7.19 7.18 2.96-2.95 4.22-4.23-2.96-2.96v-.01H7.8zM12 0L1.53 6v12L12 24l10.47-6V6L12 0zm8.47 16.85L12 21.73l-8.47-4.88V7.12L12 2.24l8.47 4.88v9.73z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://rubygems.org/pages/about",hex:"E9573F",license:void 0}; | cdnjs/cdnjs | ajax/libs/simple-icons/4.16.0/rubygems.min.js | JavaScript | mit | 470 |
/*
Copyright (c) 2007 John Dyer (http://johndyer.name)
MIT style license
*/
if (!window.Refresh) Refresh = {};
if (!Refresh.Web) Refresh.Web = {};
Refresh.Web.ColorValuePicker = Class.create();
Refresh.Web.ColorValuePicker.prototype = {
initialize: function(id) {
this.id = id;
this.onValuesChanged = null;
this._hueInput = $(this.id + '_Hue');
this._valueInput = $(this.id + '_Brightness');
this._saturationInput = $(this.id + '_Saturation');
this._redInput = $(this.id + '_Red');
this._greenInput = $(this.id + '_Green');
this._blueInput = $(this.id + '_Blue');
this._hexInput = $(this.id + '_Hex');
// assign events
// events
this._event_onHsvKeyUp = this._onHsvKeyUp.bindAsEventListener(this);
this._event_onHsvBlur = this._onHsvBlur.bindAsEventListener(this);
this._event_onRgbKeyUp = this._onRgbKeyUp.bindAsEventListener(this);
this._event_onRgbBlur = this._onRgbBlur.bindAsEventListener(this);
this._event_onHexKeyUp = this._onHexKeyUp.bindAsEventListener(this);
// HSB
Event.observe( this._hueInput,'keyup', this._event_onHsvKeyUp);
Event.observe( this._valueInput,'keyup',this._event_onHsvKeyUp);
Event.observe( this._saturationInput,'keyup',this._event_onHsvKeyUp);
Event.observe( this._hueInput,'blur', this._event_onHsvBlur);
Event.observe( this._valueInput,'blur',this._event_onHsvBlur);
Event.observe( this._saturationInput,'blur',this._event_onHsvBlur);
// RGB
Event.observe( this._redInput,'keyup', this._event_onRgbKeyUp);
Event.observe( this._greenInput,'keyup', this._event_onRgbKeyUp);
Event.observe( this._blueInput,'keyup', this._event_onRgbKeyUp);
Event.observe( this._redInput,'blur', this._event_onRgbBlur);
Event.observe( this._greenInput,'blur', this._event_onRgbBlur);
Event.observe( this._blueInput,'blur', this._event_onRgbBlur);
// HEX
Event.observe( this._hexInput,'keyup', this._event_onHexKeyUp);
this.color = new Refresh.Web.Color();
// get an initial value
if (this._hexInput.value != '')
this.color.setHex(this._hexInput.value);
// set the others based on initial value
this._hexInput.value = this.color.hex;
this._redInput.value = this.color.r;
this._greenInput.value = this.color.g;
this._blueInput.value = this.color.b;
this._hueInput.value = this.color.h;
this._saturationInput.value = this.color.s;
this._valueInput.value = this.color.v;
},
_onHsvKeyUp: function(e) {
if (e.target.value == '') return;
this.validateHsv(e);
this.setValuesFromHsv();
if (this.onValuesChanged) this.onValuesChanged(this);
},
_onRgbKeyUp: function(e) {
if (e.target.value == '') return;
this.validateRgb(e);
this.setValuesFromRgb();
if (this.onValuesChanged) this.onValuesChanged(this);
},
_onHexKeyUp: function(e) {
if (e.target.value == '') return;
this.validateHex(e);
this.setValuesFromHex();
if (this.onValuesChanged) this.onValuesChanged(this);
},
_onHsvBlur: function(e) {
if (e.target.value == '')
this.setValuesFromRgb();
},
_onRgbBlur: function(e) {
if (e.target.value == '')
this.setValuesFromHsv();
},
HexBlur: function(e) {
if (e.target.value == '')
this.setValuesFromHsv();
},
validateRgb: function(e) {
if (!this._keyNeedsValidation(e)) return e;
this._redInput.value = this._setValueInRange(this._redInput.value,0,255);
this._greenInput.value = this._setValueInRange(this._greenInput.value,0,255);
this._blueInput.value = this._setValueInRange(this._blueInput.value,0,255);
},
validateHsv: function(e) {
if (!this._keyNeedsValidation(e)) return e;
this._hueInput.value = this._setValueInRange(this._hueInput.value,0,359);
this._saturationInput.value = this._setValueInRange(this._saturationInput.value,0,100);
this._valueInput.value = this._setValueInRange(this._valueInput.value,0,100);
},
validateHex: function(e) {
if (!this._keyNeedsValidation(e)) return e;
var hex = new String(this._hexInput.value).toUpperCase();
hex = hex.replace(/[^A-F0-9]/g, '0');
if (hex.length > 6) hex = hex.substring(0, 6);
this._hexInput.value = hex;
},
_keyNeedsValidation: function(e) {
if (e.keyCode == 9 || // TAB
e.keyCode == 16 || // Shift
e.keyCode == 38 || // Up arrow
e.keyCode == 29 || // Right arrow
e.keyCode == 40 || // Down arrow
e.keyCode == 37 // Left arrow
||
(e.ctrlKey && (e.keyCode == 'c'.charCodeAt() || e.keyCode == 'v'.charCodeAt()) )
) return false;
return true;
},
_setValueInRange: function(value,min,max) {
if (value == '' || isNaN(value))
return min;
value = parseInt(value);
if (value > max)
return max;
if (value < min)
return min;
return value;
},
setValuesFromRgb: function() {
this.color.setRgb(this._redInput.value, this._greenInput.value, this._blueInput.value);
this._hexInput.value = this.color.hex;
this._hueInput.value = this.color.h;
this._saturationInput.value = this.color.s;
this._valueInput.value = this.color.v;
},
setValuesFromHsv: function() {
this.color.setHsv(this._hueInput.value, this._saturationInput.value, this._valueInput.value);
this._hexInput.value = this.color.hex;
this._redInput.value = this.color.r;
this._greenInput.value = this.color.g;
this._blueInput.value = this.color.b;
},
setValuesFromHex: function() {
this.color.setHex(this._hexInput.value);
this._redInput.value = this.color.r;
this._greenInput.value = this.color.g;
this._blueInput.value = this.color.b;
this._hueInput.value = this.color.h;
this._saturationInput.value = this.color.s;
this._valueInput.value = this.color.v;
}
};
| williamgrosset/OSCAR-ConCert | src/main/webapp/colorpicker/colorvaluepicker.js | JavaScript | gpl-2.0 | 5,774 |
//>>built
define("dijit/nls/da/loading",({loadingState:"Indlæser...",errorState:"Der er opstået en fejl"}));
| hariomkumarmth/champaranexpress | wp-content/plugins/dojo/dijit/nls/da/loading.js | JavaScript | gpl-2.0 | 113 |
OSM.Note = function (map) {
var content = $("#sidebar_content"),
page = {},
halo, currentNote;
var noteIcons = {
"new": L.icon({
iconUrl: OSM.NEW_NOTE_MARKER,
iconSize: [25, 40],
iconAnchor: [12, 40]
}),
"open": L.icon({
iconUrl: OSM.OPEN_NOTE_MARKER,
iconSize: [25, 40],
iconAnchor: [12, 40]
}),
"closed": L.icon({
iconUrl: OSM.CLOSED_NOTE_MARKER,
iconSize: [25, 40],
iconAnchor: [12, 40]
})
};
function updateNote(form, method, url) {
$(form).find("input[type=submit]").prop("disabled", true);
$.ajax({
url: url,
type: method,
oauth: true,
data: { text: $(form.text).val() },
success: function () {
OSM.loadSidebarContent(window.location.pathname, page.load);
}
});
}
page.pushstate = page.popstate = function (path) {
OSM.loadSidebarContent(path, function () {
initialize(function () {
var data = $(".details").data(),
latLng = L.latLng(data.coordinates.split(","));
if (!map.getBounds().contains(latLng)) moveToNote();
});
});
};
page.load = function () {
initialize(moveToNote);
};
function initialize(callback) {
content.find("input[type=submit]").on("click", function (e) {
e.preventDefault();
var data = $(e.target).data();
updateNote(e.target.form, data.method, data.url);
});
content.find("textarea").on("input", function (e) {
var form = e.target.form;
if ($(e.target).val() === "") {
$(form.close).val(I18n.t("javascripts.notes.show.resolve"));
$(form.comment).prop("disabled", true);
} else {
$(form.close).val(I18n.t("javascripts.notes.show.comment_and_resolve"));
$(form.comment).prop("disabled", false);
}
});
content.find("textarea").val("").trigger("input");
var data = $(".details").data(),
latLng = L.latLng(data.coordinates.split(","));
if (!map.hasLayer(halo)) {
halo = L.circleMarker(latLng, {
weight: 2.5,
radius: 20,
fillOpacity: 0.5,
color: "#FF6200"
});
map.addLayer(halo);
}
if (map.hasLayer(currentNote)) map.removeLayer(currentNote);
currentNote = L.marker(latLng, {
icon: noteIcons[data.status],
opacity: 1,
interactive: true
});
map.addLayer(currentNote);
if (callback) callback();
}
function moveToNote() {
var data = $(".details").data(),
latLng = L.latLng(data.coordinates.split(","));
if (!window.location.hash || window.location.hash.match(/^#?c[0-9]+$/)) {
OSM.router.withoutMoveListener(function () {
map.setView(latLng, 15, { reset: true });
});
}
}
page.unload = function () {
if (map.hasLayer(halo)) map.removeLayer(halo);
if (map.hasLayer(currentNote)) map.removeLayer(currentNote);
};
return page;
};
| tomhughes/openstreetmap-website | app/assets/javascripts/index/note.js | JavaScript | gpl-2.0 | 2,943 |
import Ember from 'ember';
export default Ember.Component.extend({
tagName: 'tr',
classNames: ['clickable'],
click() {
this.sendAction('action', this.imaging);
}
});
| tsaron/dariya | app/imaging/index/requested-list-item/component.js | JavaScript | gpl-3.0 | 180 |
import { Type } from 'angular2/src/core/facade/lang';
import { CanActivate } from './lifecycle_annotations_impl';
import { reflector } from 'angular2/src/core/reflection/reflection';
export function hasLifecycleHook(e, type) {
if (!(type instanceof Type))
return false;
return e.name in type.prototype;
}
export function getCanActivateHook(type) {
var annotations = reflector.annotations(type);
for (let i = 0; i < annotations.length; i += 1) {
let annotation = annotations[i];
if (annotation instanceof CanActivate) {
return annotation.fn;
}
}
return null;
}
//# sourceMappingURL=route_lifecycle_reflector.js.map | NodeVision/NodeVision | node_modules/angular2/es6/prod/src/router/route_lifecycle_reflector.js | JavaScript | gpl-3.0 | 681 |