text
string | size
int64 | token_count
int64 |
|---|---|---|
var Discord = require("discord.js"),
client = new Discord.Client(),
Enmap = require("enmap"),
db = new Enmap({name: "tickets"}),
devs = ["345152850751389697"],
prefix = "-"
const http = require("http");
const express = require("express");
const app = express();
app.get("/", (request, response) => {
console.log(Date.now() + " Ping Received");
response.sendStatus(200);
});
app.listen(process.env.PORT);
setInterval(() => {
http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
}, 280000);
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
client.on("ready", () => {
console.log("ready! " + client.user.id);
});
client.on('raw',async event => {
const events = {
MESSAGE_REACTION_ADD: 'messageReactionAdd',
};
if (!events.hasOwnProperty(event.t)) return;
if (event.t === 'MESSAGE_REACTION_ADD'){
const { d: data } = event;
const channel = client.channels.get(data.channel_id);
const msg = await channel.fetchMessage(data.message_id).catch(e => console.error(e))
const user = client.users.get(data.user_id);
const member = msg.guild.members.get(user.id);
const emojiKey = (data.emoji.id) ? `${data.emoji.name}:${data.emoji.id}` : data.emoji.name;
const reaction = msg.reactions.get(emojiKey);
db.ensure(`guilds`, [] , `${msg.guild.id}.reactionMessages`)
const MessagesID = await db.get(`guilds`, `${msg.guild.id}.reactionMessages`)
if(!MessagesID) return console.log(`${msg.guild.id}, ${msg.guild.name}, no messages id`)
if(MessagesID.length < 1 || !MessagesID) return
if(!MessagesID.includes(msg.id)) return
if(!emojiKey === '✉') return
if(user.bot) return;
reaction.remove(user);
if(db.get(`ticket${user.id}`,"blacklist") !== false) return user.send(`**❌ | You cannot create a ticket because: You're on blacklist.**`).catch(e => console.error(e));
if(db.get(`ticket${msg.guild.id}`,"onoff") !== 'on') return user.send(`**❌ | You cannot create a ticket because: ticket has been disabled or you not setup.**`).catch(e => console.error(e));
if(!msg.guild.member(client.user).hasPermission("ADMINISTRATOR")) return user.send(`**❌ | I do not have permission.**`).catch(e => console.error(e));
if(db.get(`ticket${user.id}`,"limited") == 1) return user.send(`**❌ | You already opened ticket.**`).catch(e => console.error(e));
msg.guild.createChannel(`ticket-` + db.get(`ticket${msg.guild.id}`,"count"), "text").then(c => {
let role = msg.guild.roles.find(r => r.id == db.get(`ticket${msg.guild.id}`,"adminrole"));
let role2 = msg.guild.roles.find(r => r.name == "@everyone");
c.overwritePermissions(role, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.overwritePermissions(role2, {
SEND_MESSAGES: false,
READ_MESSAGES: false
});
c.overwritePermissions(member, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.setParent(db.get(`ticket${msg.guild.id}`,"category"))
const new1 = new Discord.RichEmbed()
.setColor(db.get(`ticket${msg.guild.id}`,"embedcolor"))
.setAuthor(user.username,user.displayAvatarURL)
.setDescription(`**✅ | Done Open your Ticket: ${c || "Ticket Has Been Closed"}**`)
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp();
user.send(new1).catch(e => e);
db.math(`ticket${msg.guild.id}`,"add",1,"count")
db.math(`ticket${user.id}`,"add",1,"count")
db.set(`ticket${user.id}`,c.id,"ticketid")
c.send(`${db.get(`ticket${msg.guild.id}`,"message").replace("{user}", member).replace("{userid}",user.id).replace("{guildname}",msg.guild.name).replace("{guildid}",msg.guild.id).replace("{ticketname}",c.name).replace("{ticketid}",c.id)}`);
let channel = msg.guild.channels.find(c => c.id == db.get(`ticket${msg.guild.id}`,"log"))
if(!channel) return undefined;
let lognew = new Discord.RichEmbed()
.setTitle("Ticket Opened!")
.setAuthor(user.username,user.avatarURL)
.addField("❯ By",`» ${member}`,true)
.addField("❯ Ticket name",`» ${c}`,true)
.setColor(db.get(`ticket${msg.guild.id}`,"embedcolor"))
.setFooter(client.user.username,client.user.avatarURL)
channel.send(lognew).catch(e => e);
})
}
});
client.on('message', async message => {
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `add-rtickets`) {
db.ensure(`guilds`, [], `${message.guild.id}.reactionMessages`)
db.ensure(`guilds`, {}, `${message.guild.id}.reactionTickets`)
let channel = message.guild.channels.get(args[1]) || message.guild.channels.find(c => c.name.toLowerCase().includes(args.slice(1).join(' '))) || message.mentions.channels.first()
let embed = new Discord.RichEmbed()
.setTitle("تذكرة ردة الفعل")
.setDescription(`** اضغط عالرياكشن ✉ لفتح تذكرة **`)
.setFooter(client.user.username)
.setColor("BLUE")
channel.send(embed).then(m => {
m.react('✉')
db.set(`guilds`, channel.id,`${message.guild.id}.reactionTickets.${m.id}.channel`)
message.channel.send(channel+" تم اضافة تيكت ريأكشن الى")
}).catch(e => console.log(e))
}
});
client.on('message', async message => {
if(message.author.bot) return undefined;
db.ensure(`ticket${message.guild.id}`,{count: 1,category: "",log: "",adminrole: "",message: "",embedcolor: "",onoff: "off"})
db.ensure(`ticket${message.author.id}`,{count: 1,limited: 0,blacklist: false,ticketid: "",userid: message.author.id})
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `setup`) {
if(!message.guild.member(client.user).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | I do not have permission.**`);
if(!message.guild.member(message.author).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | You do not have permission.**`);
if(db.get(`ticket${message.guild.id}`,"setup" !== "off")) return message.channel.send(`**❌ | You already setup**`)
let e = new Discord.RichEmbed()
.setAuthor("Step 1",message.author.avatarURL)
.setTitle(`Set-adminrole`)
.setDescription(`⚠ | Mention Role`)
.setColor("BLACK")
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
message.channel.send(e).then(mes => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(r => {
let role = message.guild.roles.find(e => e.id === r.first().mentions.roles.first().id)
if(!role) return message.channel.send(`**❌ | Error**`)
let e = new Discord.RichEmbed()
.setAuthor("Step 2",message.author.avatarURL)
.setTitle(`Set-ticketlog channel`)
.setDescription(`⚠ | Mention Room`)
.setColor("BLACK")
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
mes.edit(e).then(mssaes => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(ro => {
let channelid = message.guild.channels.find(e => e.id === ro.first().mentions.channels.first().id)
if(!channelid) return message.channel.send(`**❌ | Error**`)
let e = new Discord.RichEmbed()
.setAuthor("Step 3",message.author.avatarURL)
.setTitle(`Set-category`)
.setDescription(`⚠ | Type Category ID`)
.setColor("BLACK")
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
mssaes.edit(e).then(mesadfcvs => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(rsdo => {
let c = message.guild.channels.filter(e => e.type === "category").find(e=>e.id === rsdo.first().content)
if(!c) return message.channel.send(`**❌ | Error**`)
let e = new Discord.RichEmbed()
.setAuthor("Step 4",message.author.avatarURL)
.setTitle(`Set-message`)
.setDescription(`⚠ | Type Message`)
.addField(`✅ | To show the user name, type:`,`\`\`{user}\`\``)
.addField(`✅ | To show the user ID, type:`,`\`\`{userid}\`\``)
.addField(`✅ | To show server name, type:`,`\`\`{guildname}\`\``)
.addField(`✅ | To show server name, type:`,`\`\`{guildid}\`\``)
.addField(`✅ | To show ticket name, type:`,`\`\`{ticketname}\`\``)
.addField(`✅ | To show ticket ID, type:`,`\`\`{ticketid}\`\``)
.addField(`✅ | Example:`,`Hey {user} \`(UserID: {userid})\`, you in **{guildname}** \`(GuildID: {guildid})\` your ticket is: {ticketname} \`(TicketID: {ticketid})\``)
.setColor("BLACK")
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
mesadfcvs.edit(e).then(mes => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(me => {
let e = new Discord.RichEmbed()
.setAuthor("Step 5",message.author.avatarURL)
.setTitle(`Set-Embedcolor`)
.setDescription(`⚠ | Send Color`)
.addField(`✅ | Example:`,`#000000`)
.setColor("BLACK")
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
mes.edit(e).then(mes => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(color => {
if(!color.first().content.startsWith("#")) return message.channel.send(`**❌ | Error**`)
db.set(`ticket${message.guild.id}`, role.id,"adminrole")
db.set(`ticket${message.guild.id}`, channelid.id,"log")
db.set(`ticket${message.guild.id}`, c.id,"category")
db.set(`ticket${message.guild.id}`, me.first().content,"message")
db.set(`ticket${message.guild.id}`, color.first().content,"embedcolor")
db.set(`ticket${message.guild.id}`, "on","onoff")
message.channel.send("**✅ | Done**")
message.channel.bulkDelete(8)
})
})
})
})
})
})
})
})
})
})
}
})
client.on('message', async message => {
db.ensure(`ticket${message.author.id}`,{count: 1,limited: 0,blacklist: false,ticketid: "",userid: message.author.id})
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `new`) {
if(db.get(`ticket${message.author.id}`,"blacklist") !== false) return message.channel.send(`**❌ | You cannot create a ticket because: You're on blacklist.**`)
if(db.get(`ticket${message.guild.id}`,"onoff") !== 'on') return message.channel.send(`**❌ | You cannot create a ticket because: ticket has been disabled or you not setup.**`)
if(!message.guild.member(client.user).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | I do not have permission.**`);
if(db.get(`ticket${message.author.id}`,"limited") == 1) return message.channel.send(`**❌ | You already opened ticket.**`);
message.guild.createChannel(`ticket-` + db.get(`ticket${message.guild.id}`,"count"), "text").then(c => {
let role = message.guild.roles.find("id",db.get(`ticket${message.guild.id}`,"adminrole"));
let role2 = message.guild.roles.find("name", "@everyone");
c.overwritePermissions(role, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.overwritePermissions(role2, {
SEND_MESSAGES: false,
READ_MESSAGES: false
});
c.overwritePermissions(message.author, {
SEND_MESSAGES: true,
READ_MESSAGES: true
});
c.setParent(db.get(`ticket${message.guild.id}`,"category"))
const new1 = new Discord.RichEmbed()
.setColor(db.get(`ticket${message.guild.id}`,"embedcolor"))
.setAuthor(message.author.username,message.author.displayAvatarURL)
.setDescription(`**✅ | Done Open your Ticket: ${c || "Ticket Has Been Closed"}**`)
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp();
message.channel.send(new1);
db.math(`ticket${message.guild.id}`,"add",1,"count")
db.math(`ticket${message.author.id}`,"add",1,"count")
db.set(`ticket${message.author.id}`,c.id,"ticketid")
c.send(`${db.get(`ticket${message.guild.id}`,"message").replace("{user}", message.author).replace("{userid}",message.author.id).replace("{guildname}",message.guild.name).replace("{guildid}",message.guild.id).replace("{ticketname}",c.name).replace("{ticketid}",c.id)}`);
let channel = message.guild.channels.find("id",db.get(`ticket${message.guild.id}`,"log"))
if(!channel) return undefined;
let lognew = new Discord.RichEmbed()
.setTitle("Ticket Opened!")
.setAuthor(message.author.username,message.author.avatarURL)
.addField("❯ By",`» ${message.author}`,true)
.addField("❯ Ticket name",`» ${c}`,true)
.setColor(db.get(`ticket${message.guild.id}`,"embedcolor"))
.setFooter(client.user.username,client.user.avatarURL)
channel.send(lognew);
})
}
})
client.on('message', async message => {
db.ensure(`ticket${message.author.id}`,{count: 1,limited: 0,blacklist: false,ticketid: "",userid: message.author.id})
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `close`) {
if(db.get(`ticket${message.author.id}`,"blacklist") !== false) return message.channel.send(`**❌ | You cannot create a ticket because: You're on blacklist.**`)
if(db.get(`ticket${message.guild.id}`,"onoff") !== 'on') return message.channel.send(`**❌ | You cannot create a ticket because: ticket has been disabled or you not setup.**`)
if(!message.channel.name.startsWith(`ticket-`)) return message.channel.send(`**❌ | You Can't Close Ticket Please Go To Your Ticket.**`);
let e = new Discord.RichEmbed()
.setAuthor(message.guild.name,message.guild.iconURL)
.setColor("BLUE")
.addField("» \`\`Close\`\`","» <a:off:955582836327465000>")
.setFooter(message.author.username,message.author.avatarURL)
message.channel.send(e).then(async o => {
await o.react("<a:off:955582836327465000>")
let cow = (react,user) => react.emoji.name === "<a:off:955582836327465000>" && user.id === message.author.id;
let coutwith = o.createReactionCollector(cow, { time: 0})
coutwith.on("collect", r => {
message.channel.delete()
let channel = message.guild.channels.find("id", db.get(`ticket${message.guild.id}`,"log"))
if(!channel) return undefined;
let logclose = new Discord.RichEmbed()
.setTitle("Ticket Closed!")
.setAuthor(message.author.username,message.author.avatarURL)
.addField("❯ Ticket",`» \`\`${message.channel.name}\`\``,true)
.addField("❯ Closed By",`» <@${message.author.id}>`,true)
.setColor(db.get(`ticket${message.guild.id}`,"embedcolor"))
.setFooter(client.user.username,client.user.avatarURL)
channel.send(logclose);
channel.send({files: [`./tickets/transcript-${message.channel.name}.html`]})
db.delete(`ticket${message.author.id}`,"userid")
})
})
}
})
client.on('message', async message => {
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `set-ticketlog`) {
if(!message.guild.member(client.user).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | I do not have permission.**`);
if(!message.guild.member(message.author).roles.find(e => e.id === db.get(`ticket${message.guild.id}`,"adminrole"))) return message.channel.send(`**❌ | You do not have the required rank or you not setup**`);
let e = new Discord.RichEmbed()
.setAuthor(message.author.username,message.author.avatarURL)
.setTitle(`Set-ticketlog`)
.setDescription(`⚠ | Mention Room`)
.setColor(db.get(`ticket${message.guild.id}`,"embedcolor"))
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
message.channel.send(e).then(mes => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(me => {
db.set(`ticket${message.guild.id}`, me.first().mentions.channels.first().id,"log")
message.channel.send(`**✅ | Done**`).then(e=>e.delete(5000))
mes.delete()
me.delete()
})
})
}
})
client.on('message', async message => {
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `reset-tickets`) {
if(!message.guild.member(client.user).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | I do not have permission.**`);
if(!message.guild.member(message.author).roles.find(e => e.id === db.get(`ticket${message.guild.id}`,"adminrole"))) return message.channel.send(`**❌ | You do not have the required rank or you not setup**`);
message.channel.send(`**✅ | Done**`).then(e=>e.delete(5000))
db.set(`ticket${message.guild.id}`, 1,"count")
}
})
client.on('message', async message => {
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `toggle-ticket`) {
if(!message.guild.member(client.user).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | I do not have permission.**`);
if(!message.guild.member(message.author).roles.find(e => e.id === db.get(`ticket${message.guild.id}`,"adminrole"))) return message.channel.send(`**❌ | You do not have the required rank or you not setup**`);
let e = new Discord.RichEmbed()
.setColor("BLUE")
.setDescription(`**» ON › 1️⃣
» OFF › 2️⃣**`)
.setFooter(message.author.username,message.author.avatarURL)
message.channel.send(e).then(o => {
o.react("1️⃣")
o.react("2️⃣")
let n = (react,user) => react.emoji.name === "1️⃣" && user.id === message.author.id;
let on = o.createReactionCollector(n, { time: 0})
let off = (react,user) => react.emoji.name === "2️⃣" && user.id === message.author.id;
let offf = o.createReactionCollector(off, { time: 0})
on.on("collect", r => {
message.channel.send(`**✅ | Done**`).then(e=>e.delete(5000))
db.set(`ticket${message.guild.id}`, "on","onoff")
})
offf.on("collect", r => {
message.channel.send(`**✅ | Done**`).then(e=>e.delete(5000))
db.set(`ticket${message.guild.id}`, "off","onoff")
})
})
}
})
client.on('message', async message => {
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `add-blacklist`) {
if(!message.guild.member(client.user).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | I do not have permission.**`);
if(!message.guild.member(message.author).roles.find(e => e.id === db.get(`ticket${message.guild.id}`,"adminrole"))) return message.channel.send(`**❌ | You do not have the required rank or you not setup**`);
let e = new Discord.RichEmbed()
.setAuthor(message.author.username,message.author.avatarURL)
.setTitle(`Add-blacklist`)
.setDescription(`⚠ | Mention user`)
.setColor(db.get(`ticket${message.guild.id}`,"embedcolor"))
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
message.channel.send(e).then(mes => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(me => {
db.ensure(`ticket${me.first().mentions.users.first().id}`,{count: 1,limited: 0,blacklist: false,ticketid: "",userid: me.first().mentions.users.first().id})
db.set(`ticket${me.first().mentions.users.first().id}`, true,"blacklist")
message.channel.send(`**✅ | Done**`).then(e=>e.delete(5000))
mes.delete()
me.delete()
})
})
}
})
client.on('message', async message => {
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `remove-blacklist`) {
if(!message.guild.member(client.user).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | I do not have permission.**`);
if(!message.guild.member(message.author).roles.find(e => e.id === db.get(`ticket${message.guild.id}`,"adminrole"))) return message.channel.send(`**❌ | You do not have the required rank or you not setup**`);
let e = new Discord.RichEmbed()
.setAuthor(message.author.username,message.author.avatarURL)
.setTitle(`Remove-blacklist`)
.setDescription(`⚠ | Mention user`)
.setColor(db.get(`ticket${message.guild.id}`,"embedcolor"))
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
message.channel.send(e).then(mes => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(me => {
db.ensure(`ticket${me.first().mentions.users.first().id}`,{count: 1,limited: 0,blacklist: false,ticketid: "",userid: me.first().mentions.users.first().id})
db.set(`ticket${me.first().mentions.users.first().id}`, false,"blacklist")
message.channel.send(`**✅ | Done**`).then(e=>e.delete(5000))
mes.delete()
me.delete()
})
})
}
})
client.on('message', async message => {
if(message.author.bot) return undefined;
let args = message.content.split(' ');
if(args[0].toLowerCase() == prefix + `set-message`) {
if(!message.guild.member(client.user).hasPermission("ADMINISTRATOR")) return message.channel.send(`**❌ | I do not have permission.**`);
if(!message.guild.member(message.author).roles.find(e => e.id === db.get(`ticket${message.guild.id}`,"adminrole"))) return message.channel.send(`**❌ | You do not have the required rank or you not setup**`);
let e = new Discord.RichEmbed()
.setAuthor(message.author.username,message.author.avatarURL)
.setTitle(`Set-newmessage`)
.setDescription(`⚠ | Type Message`)
.addField(`✅ | To show the user name, type:`,`\`\`{user}\`\``)
.addField(`✅ | To show the user ID, type:`,`\`\`{userid}\`\``)
.addField(`✅ | To show server name, type:`,`\`\`{guildname}\`\``)
.addField(`✅ | To show server name, type:`,`\`\`{guildid}\`\``)
.addField(`✅ | To show ticket name, type:`,`\`\`{ticketname}\`\``)
.addField(`✅ | To show ticket ID, type:`,`\`\`{ticketid}\`\``)
.addField(`✅ | Example:`,`Hey {user} \`(UserID: {userid})\`, you in **{guildname}** \`(GuildID: {guildid})\` your ticket is: {ticketname} \`(TicketID: {ticketid})\``)
.setColor(db.get(`ticket${message.guild.id}`,"embedcolor"))
.setFooter(client.user.username,client.user.avatarURL)
.setTimestamp()
message.channel.send(e).then(mes => {
message.channel.awaitMessages(m => m.author.id == message.author.id, {
max: 1,
time: 120000,
errors: ['time']
}).then(me => {
db.set(`ticket${message.guild.id}`, me.first().content,"message")
message.channel.send(`**✅ | Done**`).then(e=>e.delete(5000))
mes.delete()
me.delete()
})
})
}
})
client.on("message", async message => {
if (!message.guild || message.author.bot) return;
let args = message.content.split(" ");
if(devs.includes(message.author.id)) {
if (args[0] == `${prefix}setname`) {
message.delete();
if (!args[1]) return message.reply("Type the new username!").then(message => {
message.delete(20000);
});
try {
await client.user.setUsername(args.slice(1).join(" "));
await message.reply("Done").then(message => {
message.delete(20000);
});
} catch (e) {
await message.reply(`Error! ${e.message || e}`);
}
}
}
});
client.on("message", async message => {
if (!message.guild || message.author.bot) return;
let args = message.content.split(" ");
if(devs.includes(message.author.id)) {
if (args[0] == `${prefix}setavatar`) {
message.delete();
if (!args[1]) return message.reply("Type the avatar URL!").then(message => {
message.delete(20000);
});
try {
await client.user.setAvatar(args[1]);
await message.reply("Done").then(message => {
message.delete(20000);
});
message.delete();
} catch (e) {
message.reply(`Error! ${e.message || e}`);
}
}
}
});
client.login(process.env.BOT_TOKEN);
| 22,733
| 8,525
|
export default {
namespace: 'common',
state: {},
reducers: {
updateState(state, { payload }) {
return {
...state,
...payload,
};
},
replaceState(state, { payload }) {
if (payload) {
return payload;
}
return state;
},
},
};
| 302
| 94
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-36c22a7e"],{"6bae":function(t,e,n){},a96d:function(t,e,n){"use strict";n("6bae")},ded8:function(t,e,n){"use strict";n.r(e);var a=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"about"},[n("van-nav-bar",{attrs:{title:"软件介绍","left-text":"返回","left-arrow":""},on:{"click-left":t.onClickLeft}}),t._m(0)],1)},c=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"container"},[n("h2",[t._v("1、软件名称")]),n("p",[t._v("二少美发店收银管理软件")]),n("h2",[t._v("2、软件简介")]),n("p",[t._v(" 专为中小型美发店研发的集员工管理、会员登记、散客收银、会员收银、营收统计、报表分析 等功能为一体的美发店收银管理软件,UI界面简洁清晰,操作简单,所有管理工作都可在手机 上完成,同时也支持电脑端使用 ")]),n("h2",[t._v("3、软件作者")]),n("p",[t._v("土生土长的襄阳娃儿")]),n("h2",[t._v("4、技术支持")]),n("p",[t._v("18210953348(儿娃子)15629130580(俩娃儿)")])])}],i={methods:{onClickLeft:function(){this.$router.go(-1)}}},s=i,l=(n("a96d"),n("2877")),o=Object(l["a"])(s,a,c,!1,null,null,null);e["default"]=o.exports}}]);
//# sourceMappingURL=chunk-36c22a7e.c5fce76d.js.map
| 1,046
| 656
|
const req = require('bd-require')
const {decrypt} = req('./libs/crypto')
module.exports = async function (context, next) {
if (/^\/login/.test(context.url)) {
await next()
} else {
let auth = context.header.authorization
let result = auth && decrypt(auth)
if (result && String(result.token) === '123') {
await next()
} else {
context.body = {
code: 403,
msg: 'Forbidden'
}
}
}
}
| 445
| 154
|
module.exports = {
root: true,
parserOptions: {
parser: '@typescript-eslint/parser'
},
env: {
browser: true,
jest: true,
node: true
},
extends: [
'airbnb-typescript/base',
'plugin:@typescript-eslint/recommended',
'plugin:vue/strongly-recommended',
'prettier',
'prettier/vue',
'prettier/@typescript-eslint'
],
plugins: ['@typescript-eslint', 'prettier', 'vue'],
// add your custom rules here
rules: {
'prettier/prettier': [
'error',
{ singleQuote: true, trailingComma: 'es5', printWidth: 100 }
],
'import/extensions': [
'error',
'always',
{
js: 'never',
ts: 'never'
}
],
'no-console': 0,
'@typescript-eslint/no-explicit-any': 0,
'@typescript-eslint/no-var-requires': 0,
'import/no-dynamic-require': 0,
'global-require': 0,
'no-underscore-dangle': 0,
'class-methods-use-this': 0,
'vue/max-attributes-per-line': 'off',
'vue/component-name-in-template-casing': [1, 'kebab-case']
},
settings: {
'import/core-modules': [
'@nuxt/config',
'@nuxt/vue-app',
'@nuxt/types',
'purgecss-webpack-plugin',
'vue',
'vuex',
'vue-meta',
'vue-server-renderer',
'vue-router'
],
'import/resolver': {
webpack: {
config: {
resolve: {
extensions: ['.js', '.json', '.ts', '.vue'],
alias: {
'~': __dirname + '/app',
'@': __dirname + '/app'
}
}
}
}
}
}
}
| 1,578
| 583
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pickProps;
/**
* Copyright (c) 2015-present, Zippy Technologies
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function pickProps(props, targetProps) {
var pickedProps = {};
Object.keys(targetProps).forEach(function (key) {
if (props[key] !== undefined) {
pickedProps[key] = props[key];
}
});
return pickedProps;
}
| 523
| 167
|
import { memo } from "react";
import {
useVirtual,
areItemPropsEqual,
List
} from "@af-utils/react-virtual-list";
const Item = memo(
({ i }) => <div className="border-t p-2 border-zinc-400">row {i}</div>,
areItemPropsEqual
);
const SimpleList = () => {
const model = useVirtual({
itemCount: 50000
});
return <List model={model}>{Item}</List>;
};
export default SimpleList;
| 417
| 145
|
// @ts-check
"use strict";
const fs = require("fs");
const path = require("path");
const { URL } = require("url");
const markdownIt = require("markdown-it");
const rules = require("./rules");
const helpers = require("../helpers");
const cache = require("./cache");
const deprecatedRuleNames = [ "MD002" ];
// Validates the list of rules for structure and reuse
function validateRuleList(ruleList) {
let result = null;
if (ruleList.length === rules.length) {
// No need to validate if only using built-in rules
return result;
}
const allIds = {};
ruleList.forEach(function forRule(rule, index) {
const customIndex = index - rules.length;
function newError(property) {
return new Error(
"Property '" + property + "' of custom rule at index " +
customIndex + " is incorrect.");
}
[ "names", "tags" ].forEach(function forProperty(property) {
const value = rule[property];
if (!result &&
(!value || !Array.isArray(value) || (value.length === 0) ||
!value.every(helpers.isString) || value.some(helpers.isEmptyString))) {
result = newError(property);
}
});
[
[ "description", "string" ],
[ "function", "function" ]
].forEach(function forProperty(propertyInfo) {
const property = propertyInfo[0];
const value = rule[property];
if (!result && (!value || (typeof value !== propertyInfo[1]))) {
result = newError(property);
}
});
if (!result && rule.information) {
if (Object.getPrototypeOf(rule.information) !== URL.prototype) {
result = newError("information");
}
}
if (!result) {
rule.names.forEach(function forName(name) {
const nameUpper = name.toUpperCase();
if (!result && (allIds[nameUpper] !== undefined)) {
result = new Error("Name '" + name + "' of custom rule at index " +
customIndex + " is already used as a name or tag.");
}
allIds[nameUpper] = true;
});
rule.tags.forEach(function forTag(tag) {
const tagUpper = tag.toUpperCase();
if (!result && allIds[tagUpper]) {
result = new Error("Tag '" + tag + "' of custom rule at index " +
customIndex + " is already used as a name.");
}
allIds[tagUpper] = false;
});
}
});
return result;
}
// Class for results with toString for pretty display
function newResults(ruleList) {
function Results() {}
Results.prototype.toString = function toString(useAlias) {
const that = this;
let ruleNameToRule = null;
const results = [];
Object.keys(that).forEach(function forFile(file) {
const fileResults = that[file];
if (Array.isArray(fileResults)) {
fileResults.forEach(function forResult(result) {
const ruleMoniker = result.ruleNames ?
result.ruleNames.join("/") :
(result.ruleName + "/" + result.ruleAlias);
results.push(
file + ": " +
result.lineNumber + ": " +
ruleMoniker + " " +
result.ruleDescription +
(result.errorDetail ?
" [" + result.errorDetail + "]" :
"") +
(result.errorContext ?
" [Context: \"" + result.errorContext + "\"]" :
""));
});
} else {
if (!ruleNameToRule) {
ruleNameToRule = {};
ruleList.forEach(function forRule(rule) {
const ruleName = rule.names[0].toUpperCase();
ruleNameToRule[ruleName] = rule;
});
}
Object.keys(fileResults).forEach(function forRule(ruleName) {
const rule = ruleNameToRule[ruleName.toUpperCase()];
const ruleResults = fileResults[ruleName];
ruleResults.forEach(function forLine(lineNumber) {
const nameIndex = Math.min(useAlias ? 1 : 0, rule.names.length - 1);
const result =
file + ": " +
lineNumber + ": " +
rule.names[nameIndex] + " " +
rule.description;
results.push(result);
});
});
}
});
return results.join("\n");
};
return new Results();
}
// Remove front matter (if present at beginning of content)
function removeFrontMatter(content, frontMatter) {
let frontMatterLines = [];
if (frontMatter) {
const frontMatterMatch = content.match(frontMatter);
if (frontMatterMatch && !frontMatterMatch.index) {
const contentMatched = frontMatterMatch[0];
content = content.slice(contentMatched.length);
frontMatterLines = contentMatched.split(helpers.newLineRe);
if (frontMatterLines.length &&
(frontMatterLines[frontMatterLines.length - 1] === "")) {
frontMatterLines.length--;
}
}
}
return {
"content": content,
"frontMatterLines": frontMatterLines
};
}
// Annotate tokens with line/lineNumber
function annotateTokens(tokens, lines) {
let tbodyMap = null;
tokens.forEach(function forToken(token) {
// Handle missing maps for table body
if (token.type === "tbody_open") {
tbodyMap = token.map.slice();
} else if ((token.type === "tr_close") && tbodyMap) {
tbodyMap[0]++;
} else if (token.type === "tbody_close") {
tbodyMap = null;
}
if (tbodyMap && !token.map) {
token.map = tbodyMap.slice();
}
// Update token metadata
if (token.map) {
token.line = lines[token.map[0]];
token.lineNumber = token.map[0] + 1;
// Trim bottom of token to exclude whitespace lines
while (token.map[1] && !((lines[token.map[1] - 1] || "").trim())) {
token.map[1]--;
}
// Annotate children with lineNumber
let lineNumber = token.lineNumber;
const codeSpanExtraLines = [];
helpers.forEachInlineCodeSpan(
token.content,
function handleInlineCodeSpan(code) {
codeSpanExtraLines.push(code.split(helpers.newLineRe).length - 1);
}
);
(token.children || []).forEach(function forChild(child) {
child.lineNumber = lineNumber;
child.line = lines[lineNumber - 1];
if ((child.type === "softbreak") || (child.type === "hardbreak")) {
lineNumber++;
} else if (child.type === "code_inline") {
lineNumber += codeSpanExtraLines.shift();
}
});
}
});
}
// Map rule names/tags to canonical rule name
function mapAliasToRuleNames(ruleList) {
const aliasToRuleNames = {};
// const tagToRuleNames = {};
ruleList.forEach(function forRule(rule) {
const ruleName = rule.names[0].toUpperCase();
// The following is useful for updating README.md:
// console.log(
// "* **[" + ruleName + "](doc/Rules.md#" + ruleName.toLowerCase() +
// ")** *" + rule.names.slice(1).join("/") + "* - " + rule.description);
rule.names.forEach(function forName(name) {
const nameUpper = name.toUpperCase();
aliasToRuleNames[nameUpper] = [ ruleName ];
});
rule.tags.forEach(function forTag(tag) {
const tagUpper = tag.toUpperCase();
const ruleNames = aliasToRuleNames[tagUpper] || [];
ruleNames.push(ruleName);
aliasToRuleNames[tagUpper] = ruleNames;
// tagToRuleNames[tag] = ruleName;
});
});
// The following is useful for updating README.md:
// Object.keys(tagToRuleNames).sort().forEach(function forTag(tag) {
// console.log("* **" + tag + "** - " +
// aliasToRuleNames[tag.toUpperCase()].join(", "));
// });
return aliasToRuleNames;
}
// Apply (and normalize) config
function getEffectiveConfig(ruleList, config, aliasToRuleNames) {
const defaultKey = Object.keys(config).filter(
(key) => key.toUpperCase() === "DEFAULT"
);
const ruleDefault = (defaultKey.length === 0) || !!config[defaultKey[0]];
const effectiveConfig = {};
ruleList.forEach((rule) => {
const ruleName = rule.names[0].toUpperCase();
effectiveConfig[ruleName] = ruleDefault;
});
deprecatedRuleNames.forEach((ruleName) => {
effectiveConfig[ruleName] = false;
});
Object.keys(config).forEach((key) => {
let value = config[key];
if (value) {
if (!(value instanceof Object)) {
value = {};
}
} else {
value = false;
}
const keyUpper = key.toUpperCase();
(aliasToRuleNames[keyUpper] || []).forEach((ruleName) => {
effectiveConfig[ruleName] = value;
});
});
return effectiveConfig;
}
// Create mapping of enabled rules per line
function getEnabledRulesPerLineNumber(
ruleList, lines, frontMatterLines, noInlineConfig,
effectiveConfig, aliasToRuleNames) {
let enabledRules = {};
const allRuleNames = [];
ruleList.forEach((rule) => {
const ruleName = rule.names[0].toUpperCase();
allRuleNames.push(ruleName);
enabledRules[ruleName] = !!effectiveConfig[ruleName];
});
let capturedRules = enabledRules;
function forMatch(match, byLine) {
const action = match[1].toUpperCase();
if (action === "CAPTURE") {
if (byLine) {
capturedRules = { ...enabledRules };
}
} else if (action === "RESTORE") {
if (byLine) {
enabledRules = { ...capturedRules };
}
} else {
// action in [ENABLE, DISABLE, ENABLE-FILE, DISABLE-FILE]
const isfile = action.endsWith("-FILE");
if ((byLine && !isfile) || (!byLine && isfile)) {
const enabled = (action.startsWith("ENABLE"));
const items = match[2] ?
match[2].trim().toUpperCase().split(/\s+/) :
allRuleNames;
items.forEach((nameUpper) => {
(aliasToRuleNames[nameUpper] || []).forEach((ruleName) => {
enabledRules[ruleName] = enabled;
});
});
}
}
}
const enabledRulesPerLineNumber = new Array(1 + frontMatterLines.length);
[ false, true ].forEach((byLine) => {
lines.forEach((line) => {
if (!noInlineConfig) {
let match = helpers.inlineCommentRe.exec(line);
if (match) {
enabledRules = { ...enabledRules };
while (match) {
forMatch(match, byLine);
match = helpers.inlineCommentRe.exec(line);
}
}
}
if (byLine) {
enabledRulesPerLineNumber.push(enabledRules);
}
});
});
return enabledRulesPerLineNumber;
}
// Array.sort comparison for objects in errors array
function lineNumberComparison(a, b) {
return a.lineNumber - b.lineNumber;
}
// Function to return true for all inputs
function filterAllValues() {
return true;
}
// Function to return unique values from a sorted errors array
function uniqueFilterForSortedErrors(value, index, array) {
return (index === 0) || (value.lineNumber > array[index - 1].lineNumber);
}
// Lints a single string
function lintContent(
ruleList,
name,
content,
md,
config,
frontMatter,
handleRuleFailures,
noInlineConfig,
resultVersion,
callback) {
// Remove UTF-8 byte order marker (if present)
content = content.replace(/^\ufeff/, "");
// Remove front matter
const removeFrontMatterResult = removeFrontMatter(content, frontMatter);
const frontMatterLines = removeFrontMatterResult.frontMatterLines;
// Ignore the content of HTML comments
content = helpers.clearHtmlCommentText(removeFrontMatterResult.content);
// Parse content into tokens and lines
const tokens = md.parse(content, {});
const lines = content.split(helpers.newLineRe);
annotateTokens(tokens, lines);
const aliasToRuleNames = mapAliasToRuleNames(ruleList);
const effectiveConfig =
getEffectiveConfig(ruleList, config, aliasToRuleNames);
const enabledRulesPerLineNumber = getEnabledRulesPerLineNumber(
ruleList, lines, frontMatterLines, noInlineConfig,
effectiveConfig, aliasToRuleNames);
// Create parameters for rules
const params = {
name,
tokens,
lines,
frontMatterLines
};
cache.lineMetadata(helpers.getLineMetadata(params));
cache.flattenedLists(helpers.flattenLists(params));
// Function to run for each rule
const result = (resultVersion === 0) ? {} : [];
function forRule(rule) {
// Configure rule
const ruleNameFriendly = rule.names[0];
const ruleName = ruleNameFriendly.toUpperCase();
params.config = effectiveConfig[ruleName];
function throwError(property) {
throw new Error(
"Property '" + property + "' of onError parameter is incorrect.");
}
const errors = [];
function onError(errorInfo) {
if (!errorInfo ||
!helpers.isNumber(errorInfo.lineNumber) ||
(errorInfo.lineNumber < 1) ||
(errorInfo.lineNumber > lines.length)) {
throwError("lineNumber");
}
if (errorInfo.detail &&
!helpers.isString(errorInfo.detail)) {
throwError("detail");
}
if (errorInfo.context &&
!helpers.isString(errorInfo.context)) {
throwError("context");
}
if (errorInfo.range &&
(!Array.isArray(errorInfo.range) ||
(errorInfo.range.length !== 2) ||
!helpers.isNumber(errorInfo.range[0]) ||
(errorInfo.range[0] < 1) ||
!helpers.isNumber(errorInfo.range[1]) ||
(errorInfo.range[1] < 1) ||
((errorInfo.range[0] + errorInfo.range[1] - 1) >
lines[errorInfo.lineNumber - 1].length))) {
throwError("range");
}
const fixInfo = errorInfo.fixInfo;
const cleanFixInfo = {};
if (fixInfo) {
if (!helpers.isObject(fixInfo)) {
throwError("fixInfo");
}
if (fixInfo.lineNumber !== undefined) {
if ((!helpers.isNumber(fixInfo.lineNumber) ||
(fixInfo.lineNumber < 1) ||
(fixInfo.lineNumber > lines.length))) {
throwError("fixInfo.lineNumber");
}
cleanFixInfo.lineNumber =
fixInfo.lineNumber + frontMatterLines.length;
}
const effectiveLineNumber = fixInfo.lineNumber || errorInfo.lineNumber;
if (fixInfo.editColumn !== undefined) {
if ((!helpers.isNumber(fixInfo.editColumn) ||
(fixInfo.editColumn < 1) ||
(fixInfo.editColumn >
lines[effectiveLineNumber - 1].length + 1))) {
throwError("fixInfo.editColumn");
}
cleanFixInfo.editColumn = fixInfo.editColumn;
}
if (fixInfo.deleteCount !== undefined) {
if ((!helpers.isNumber(fixInfo.deleteCount) ||
(fixInfo.deleteCount < -1) ||
(fixInfo.deleteCount >
lines[effectiveLineNumber - 1].length))) {
throwError("fixInfo.deleteCount");
}
cleanFixInfo.deleteCount = fixInfo.deleteCount;
}
if (fixInfo.insertText !== undefined) {
if (!helpers.isString(fixInfo.insertText)) {
throwError("fixInfo.insertText");
}
cleanFixInfo.insertText = fixInfo.insertText;
}
}
errors.push({
"lineNumber": errorInfo.lineNumber + frontMatterLines.length,
"detail": errorInfo.detail || null,
"context": errorInfo.context || null,
"range": errorInfo.range || null,
"fixInfo": fixInfo ? cleanFixInfo : null
});
}
// Call (possibly external) rule function
if (handleRuleFailures) {
try {
rule.function(params, onError);
} catch (ex) {
onError({
"lineNumber": 1,
"detail": `This rule threw an exception: ${ex.message}`
});
}
} else {
rule.function(params, onError);
}
// Record any errors (significant performance benefit from length check)
if (errors.length) {
errors.sort(lineNumberComparison);
const filteredErrors = errors
.filter((resultVersion === 3) ?
filterAllValues :
uniqueFilterForSortedErrors)
.filter(function removeDisabledRules(error) {
return enabledRulesPerLineNumber[error.lineNumber][ruleName];
})
.map(function formatResults(error) {
if (resultVersion === 0) {
return error.lineNumber;
}
const errorObject = {};
errorObject.lineNumber = error.lineNumber;
if (resultVersion === 1) {
errorObject.ruleName = ruleNameFriendly;
errorObject.ruleAlias = rule.names[1] || rule.names[0];
} else {
errorObject.ruleNames = rule.names;
}
errorObject.ruleDescription = rule.description;
errorObject.ruleInformation =
rule.information ? rule.information.href : null;
errorObject.errorDetail = error.detail;
errorObject.errorContext = error.context;
errorObject.errorRange = error.range;
if (resultVersion === 3) {
errorObject.fixInfo = error.fixInfo;
}
return errorObject;
});
if (filteredErrors.length) {
if (resultVersion === 0) {
result[ruleNameFriendly] = filteredErrors;
} else {
Array.prototype.push.apply(result, filteredErrors);
}
}
}
}
// Run all rules
try {
ruleList.forEach(forRule);
} catch (ex) {
cache.clear();
return callback(ex);
}
cache.clear();
return callback(null, result);
}
// Lints a single file
function lintFile(
ruleList,
file,
md,
config,
frontMatter,
handleRuleFailures,
noInlineConfig,
resultVersion,
synchronous,
callback) {
function lintContentWrapper(err, content) {
if (err) {
return callback(err);
}
return lintContent(ruleList, file, content, md, config, frontMatter,
handleRuleFailures, noInlineConfig, resultVersion, callback);
}
// Make a/synchronous call to read file
if (synchronous) {
lintContentWrapper(null, fs.readFileSync(file, helpers.utf8Encoding));
} else {
fs.readFile(file, helpers.utf8Encoding, lintContentWrapper);
}
}
// Lints files and strings
function lintInput(options, synchronous, callback) {
// Normalize inputs
options = options || {};
callback = callback || function noop() {};
const ruleList = rules.concat(options.customRules || []);
const ruleErr = validateRuleList(ruleList);
if (ruleErr) {
return callback(ruleErr);
}
let files = [];
if (Array.isArray(options.files)) {
files = options.files.slice();
} else if (options.files) {
files = [ String(options.files) ];
}
const strings = options.strings || {};
const stringsKeys = Object.keys(strings);
const config = options.config || { "default": true };
const frontMatter = (options.frontMatter === undefined) ?
helpers.frontMatterRe : options.frontMatter;
const handleRuleFailures = !!options.handleRuleFailures;
const noInlineConfig = !!options.noInlineConfig;
const resultVersion = (options.resultVersion === undefined) ?
2 : options.resultVersion;
const md = markdownIt({ "html": true });
const markdownItPlugins = options.markdownItPlugins || [];
markdownItPlugins.forEach(function forPlugin(plugin) {
// @ts-ignore
md.use(...plugin);
});
const results = newResults(ruleList);
// Helper to lint the next string or file
/* eslint-disable consistent-return */
function lintNextItem() {
let iterating = true;
let item = null;
function lintNextItemCallback(err, result) {
if (err) {
iterating = false;
return callback(err);
}
results[item] = result;
return iterating || lintNextItem();
}
while (iterating) {
if ((item = stringsKeys.shift())) {
lintContent(
ruleList,
item,
strings[item] || "",
md,
config,
frontMatter,
handleRuleFailures,
noInlineConfig,
resultVersion,
lintNextItemCallback);
} else if ((item = files.shift())) {
iterating = synchronous;
lintFile(
ruleList,
item,
md,
config,
frontMatter,
handleRuleFailures,
noInlineConfig,
resultVersion,
synchronous,
lintNextItemCallback);
} else {
return callback(null, results);
}
}
}
return lintNextItem();
}
/**
* Lint specified Markdown files.
*
* @param {Options} options Configuration options.
* @param {LintCallback} callback Callback (err, result) function.
* @returns {void}
*/
function markdownlint(options, callback) {
return lintInput(options, false, callback);
}
/**
* Lint specified Markdown files synchronously.
*
* @param {Options} options Configuration options.
* @returns {LintResults} Results object.
*/
function markdownlintSync(options) {
let results = null;
lintInput(options, true, function callback(error, res) {
if (error) {
throw error;
}
results = res;
});
return results;
}
// Parses the content of a configuration file
function parseConfiguration(name, content, parsers) {
let config = null;
let message = "";
const errors = [];
// Try each parser
(parsers || [ JSON.parse ]).every((parser) => {
try {
config = parser(content);
} catch (ex) {
errors.push(ex.message);
}
return !config;
});
// Message if unable to parse
if (!config) {
errors.unshift(`Unable to parse '${name}'`);
message = errors.join("; ");
}
return {
config,
message
};
}
/**
* Read specified configuration file.
*
* @param {string} file Configuration file name.
* @param {ConfigurationParser[] | null} parsers Parsing function(s).
* @param {ReadConfigCallback} callback Callback (err, result) function.
* @returns {void}
*/
function readConfig(file, parsers, callback) {
if (!callback) {
// @ts-ignore
callback = parsers;
parsers = null;
}
// Read file
fs.readFile(file, helpers.utf8Encoding, (err, content) => {
if (err) {
return callback(err);
}
// Try to parse file
const { config, message } = parseConfiguration(file, content, parsers);
if (!config) {
return callback(new Error(message));
}
// Extend configuration
const configExtends = config.extends;
if (configExtends) {
delete config.extends;
const extendsFile = path.resolve(path.dirname(file), configExtends);
return readConfig(extendsFile, parsers, (errr, extendsConfig) => {
if (errr) {
return callback(errr);
}
return callback(null, {
...extendsConfig,
...config
});
});
}
return callback(null, config);
});
}
/**
* Read specified configuration file synchronously.
*
* @param {string} file Configuration file name.
* @param {ConfigurationParser[]} [parsers] Parsing function(s).
* @returns {Configuration} Configuration object.
*/
function readConfigSync(file, parsers) {
// Read file
const content = fs.readFileSync(file, helpers.utf8Encoding);
// Try to parse file
const { config, message } = parseConfiguration(file, content, parsers);
if (!config) {
throw new Error(message);
}
// Extend configuration
const configExtends = config.extends;
if (configExtends) {
delete config.extends;
return {
...readConfigSync(
path.resolve(path.dirname(file), configExtends),
parsers
),
...config
};
}
return config;
}
// Export a/synchronous APIs
markdownlint.sync = markdownlintSync;
markdownlint.readConfig = readConfig;
markdownlint.readConfigSync = readConfigSync;
module.exports = markdownlint;
// Type declarations
/**
* Function to implement rule logic.
*
* @callback RuleFunction
* @param {RuleParams} params Rule parameters.
* @param {RuleOnError} onError Error-reporting callback.
* @returns {void}
*/
/**
* Rule parameters.
*
* @typedef {Object} RuleParams
* @property {string} name File/string name.
* @property {MarkdownItToken[]} tokens markdown-it token objects.
* @property {string[]} lines File/string lines.
* @property {string[]} frontMatterLines Front matter lines.
* @property {RuleConfiguration} config Rule configuration.
*/
/**
* Markdown-It token.
*
* @typedef {Object} MarkdownItToken
* @property {string[][]} attrs HTML attributes.
* @property {boolean} block Block-level token.
* @property {MarkdownItToken[]} children Child nodes.
* @property {string} content Tag contents.
* @property {boolean} hidden Ignore element.
* @property {string} info Fence info.
* @property {number} level Nesting level.
* @property {number[]} map Beginning/ending line numbers.
* @property {string} markup Markup text.
* @property {Object} meta Arbitrary data.
* @property {number} nesting Level change.
* @property {string} tag HTML tag name.
* @property {string} type Token type.
* @property {number} lineNumber Line number (1-based).
* @property {string} line Line content.
*/
/**
* Error-reporting callback.
*
* @callback RuleOnError
* @param {RuleOnErrorInfo} onErrorInfo Error information.
* @returns {void}
*/
/**
* Fix information for RuleOnError callback.
*
* @typedef {Object} RuleOnErrorInfo
* @property {number} lineNumber Line number (1-based).
* @property {string} [details] Details about the error.
* @property {string} [context] Context for the error.
* @property {number[]} [range] Column number (1-based) and length.
* @property {RuleOnErrorFixInfo} [fixInfo] Fix information.
*/
/**
* Fix information for RuleOnErrorInfo.
*
* @typedef {Object} RuleOnErrorFixInfo
* @property {number} [lineNumber] Line number (1-based).
* @property {number} [editColumn] Column of the fix (1-based).
* @property {number} [deleteCount] Count of characters to delete.
* @property {string} [insertText] Text to insert (after deleting).
*/
/**
* Rule definition.
*
* @typedef {Object} Rule
* @property {string[]} names Rule name(s).
* @property {string} description Rule description.
* @property {URL} [information] Link to more information.
* @property {string[]} tags Rule tag(s).
* @property {RuleFunction} function Rule implementation.
*/
/**
* Configuration options.
*
* @typedef {Object} Options
* @property {string[] | string} [files] Files to lint.
* @property {Object.<string, string>} [strings] Strings to lint.
* @property {Configuration} [config] Configuration object.
* @property {Rule[] | Rule} [customRules] Custom rules.
* @property {RegExp} [frontMatter] Front matter pattern.
* @property {boolean} [handleRuleFailures] True to catch exceptions.
* @property {boolean} [noInlineConfig] True to ignore HTML directives.
* @property {number} [resultVersion] Results object version.
* @property {Plugin[]} [markdownItPlugins] Additional plugins.
*/
/**
* markdown-it plugin.
*
* @typedef {Array} Plugin
*/
/**
* Function to pretty-print lint results.
*
* @callback ToStringCallback
* @param {boolean} [ruleAliases] True to use rule aliases.
* @returns {string}
*/
/**
* Lint results (for resultVersion 3).
*
* @typedef {Object.<string, LintError[]>} LintResults
*/
// The following should be part of the LintResults typedef, but that causes
// TypeScript to "forget" about the string map.
// * @property {ToStringCallback} toString String representation.
// https://github.com/microsoft/TypeScript/issues/34911
/**
* Lint error.
*
* @typedef {Object} LintError
* @property {number} lineNumber Line number (1-based).
* @property {string[]} ruleNames Rule name(s).
* @property {string} ruleDescription Rule description.
* @property {string} ruleInformation Link to more information.
* @property {string} errorDetail Detail about the error.
* @property {string} errorContext Context for the error.
* @property {number[]} errorRange Column number (1-based) and length.
* @property {FixInfo} fixInfo Fix information.
*/
/**
* Fix information.
*
* @typedef {Object} FixInfo
* @property {number} [editColumn] Column of the fix (1-based).
* @property {number} [deleteCount] Count of characters to delete.
* @property {string} [insertText] Text to insert (after deleting).
*/
/**
* Called with the result of the lint operation.
*
* @callback LintCallback
* @param {Error | null} err Error object or null.
* @param {LintResults} [results] Lint results.
* @returns {void}
*/
/**
* Configuration object for linting rules. For a detailed schema, see
* {@link ../schema/markdownlint-config-schema.json}.
*
* @typedef {Object.<string, RuleConfiguration>} Configuration
*/
/**
* Rule configuration object.
*
* @typedef {boolean | Object} RuleConfiguration Rule configuration.
*/
/**
* Parses a configuration string and returns a configuration object.
*
* @callback ConfigurationParser
* @param {string} text Configuration string.
* @returns {Configuration}
*/
/**
* Called with the result of the readConfig operation.
*
* @callback ReadConfigCallback
* @param {Error | null} err Error object or null.
* @param {Configuration} [config] Configuration object.
* @returns {void}
*/
| 29,957
| 8,850
|
define(["require", "exports", "@fluentui/style-utilities"], function (require, exports, style_utilities_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.styles = void 0;
var GlobalClassNames = {
root: 'ms-DatePicker',
callout: 'ms-DatePicker-callout',
withLabel: 'ms-DatePicker-event--with-label',
withoutLabel: 'ms-DatePicker-event--without-label',
disabled: 'msDatePickerDisabled ',
};
var styles = function (props) {
var className = props.className, theme = props.theme, disabled = props.disabled, label = props.label, isDatePickerShown = props.isDatePickerShown;
var palette = theme.palette, semanticColors = theme.semanticColors, fonts = theme.fonts;
var classNames = style_utilities_1.getGlobalClassNames(GlobalClassNames, theme);
var DatePickerIcon = {
color: palette.neutralSecondary,
fontSize: style_utilities_1.FontSizes.icon,
lineHeight: '18px',
pointerEvents: 'none',
position: 'absolute',
right: '4px',
padding: '5px',
};
return {
root: [classNames.root, theme.fonts.large, isDatePickerShown && 'is-open', style_utilities_1.normalize, className],
textField: [
{
position: 'relative',
selectors: {
'& input[readonly]': {
cursor: 'pointer',
},
input: {
selectors: {
'::-ms-clear': {
display: 'none',
},
},
},
},
},
disabled && {
selectors: {
'& input[readonly]': {
cursor: 'default',
},
},
},
],
callout: [classNames.callout],
icon: [
DatePickerIcon,
label ? classNames.withLabel : classNames.withoutLabel,
{ paddingTop: '7px' },
!disabled && [
classNames.disabled,
{
pointerEvents: 'initial',
cursor: 'pointer',
},
],
disabled && {
color: semanticColors.disabledText,
cursor: 'default',
},
],
statusMessage: [
fonts.small,
{
color: semanticColors.errorText,
marginTop: 5,
},
],
};
};
exports.styles = styles;
});
//# sourceMappingURL=DatePicker.styles.js.map
| 2,987
| 718
|
const fs = require('fs')
const path = require('path')
const puppeteer = require('puppeteer')
const DOCUMENT_URL = {
classes: 'https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes',
elements: 'https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements',
}
const CODES_SELECTOR = '#index>ul>li>a>code'
/**
* @typedef {import("puppeteer").Browser} Browser
*/
/**
* @param {Browser} browser
* @returns {Promise<string[]>}
*/
const getPseudos = async (browser, url, selector = CODES_SELECTOR) => {
const page = await browser.newPage()
await page.goto(url)
const codeElements = await page.$$(selector)
const codes = await Promise.all(
codeElements.map((element) =>
element.evaluate((node) =>
node.innerText.split(/\s/)[0].replace(/^:+/, '')
)
)
)
return codes.filter((code) => code.indexOf('(') === -1)
}
;(async () => {
const browser = await puppeteer.launch()
const [classes, elements] = await Promise.all([
getPseudos(browser, DOCUMENT_URL.classes),
getPseudos(browser, DOCUMENT_URL.elements),
])
await browser.close()
const output = `/* DON'T EDIT THIS FILE. This is generated by 'scripts/update-pseudos.js' */
module.exports = {
pseudoElements: [
${elements.map((e) => ` '${e}'`).join(',\n')},
],
pseudoClasses: [
${classes.map((c) => ` '${c}'`).join(',\n')},
],
}
`
fs.writeFileSync(path.resolve(__dirname, '../lib.js'), output, 'utf-8')
})()
| 1,452
| 531
|
/** ****************************************************************************************************
* File: jsdocs.js
* Project: template-npm-module
* @author Nick Soggin <[email protected]> on 30-May-2018
*******************************************************************************************************/
'use strict';
/**
* @global
* @alias <a href="demo/">Demo</a>
*/
module.exports = {
plugins: [
'plugins/markdown'
],
recurseDepth: 20,
source: {
include: [
'README.md',
'./'
],
exclude: [
'demo',
'docs',
'node_modules'
],
includePattern: '.+\\.js(doc|x)?$',
excludePattern: '(^|\\/|\\\\)_|(^|\\/|\\\\)node_modules'
},
sourceType: 'module',
tags: {
allowUnknownTags: true,
dictionaries: [
'jsdoc',
'closure'
]
},
templates: {
cleverLinks: true,
monospaceLinks: true
},
opts: {
encoding: 'utf8',
destination: 'docs/',
recurse: true,
template: './node_modules/postman-jsdoc-theme'
}
};
| 1,183
| 357
|
'use strict';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.API = void 0;
const CWC = __importStar(require("crypto-wallet-core"));
const events_1 = require("events");
const lodash_1 = __importDefault(require("lodash"));
const sjcl_1 = __importDefault(require("sjcl"));
const common_1 = require("./common");
const credentials_1 = require("./credentials");
const key_1 = require("./key");
const paypro_1 = require("./paypro");
const payproV2_1 = require("./payproV2");
const request_1 = require("./request");
const verifier_1 = require("./verifier");
var $ = require('preconditions').singleton();
var util = require('util');
var async = require('async');
var events = require('events');
var Bitcore = CWC.BitcoreLib;
var Bitcore_ = {
btc: CWC.BitcoreLib,
bch: CWC.BitcoreLibCash,
eth: CWC.BitcoreLib,
xrp: CWC.BitcoreLib,
doge: CWC.BitcoreLibDoge,
edu: CWC.BitcoreLibEdu,
tik: CWC.BitcoreLibTik
};
var Mnemonic = require('bitcore-mnemonic');
var url = require('url');
var querystring = require('querystring');
var log = require('./log');
const Errors = require('./errors');
var BASE_URL = 'http://localhost:3232/bws/api';
class API extends events_1.EventEmitter {
constructor(opts) {
super();
opts = opts || {};
this.doNotVerifyPayPro = opts.doNotVerifyPayPro;
this.timeout = opts.timeout || 50000;
this.logLevel = opts.logLevel || 'silent';
this.supportStaffWalletId = opts.supportStaffWalletId;
this.bp_partner = opts.bp_partner;
this.bp_partner_version = opts.bp_partner_version;
this.request = new request_1.Request(opts.baseUrl || BASE_URL, {
r: opts.request,
supportStaffWalletId: opts.supportStaffWalletId
});
log.setLevel(this.logLevel);
}
initNotifications(cb) {
log.warn('DEPRECATED: use initialize() instead.');
this.initialize({}, cb);
}
initialize(opts, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <initialize()>');
this.notificationIncludeOwn = !!opts.notificationIncludeOwn;
this._initNotifications(opts);
return cb();
}
dispose(cb) {
this._disposeNotifications();
this.request.logout(cb);
}
_fetchLatestNotifications(interval, cb) {
cb = cb || function () { };
var opts = {
lastNotificationId: this.lastNotificationId,
includeOwn: this.notificationIncludeOwn
};
if (!this.lastNotificationId) {
opts.timeSpan = interval + 1;
}
this.getNotifications(opts, (err, notifications) => {
if (err) {
log.warn('Error receiving notifications.');
log.debug(err);
return cb(err);
}
if (notifications.length > 0) {
this.lastNotificationId = lodash_1.default.last(notifications).id;
}
lodash_1.default.each(notifications, notification => {
this.emit('notification', notification);
});
return cb();
});
}
_initNotifications(opts) {
opts = opts || {};
var interval = opts.notificationIntervalSeconds || 5;
this.notificationsIntervalId = setInterval(() => {
this._fetchLatestNotifications(interval, err => {
if (err) {
if (err instanceof Errors.NOT_FOUND ||
err instanceof Errors.NOT_AUTHORIZED) {
this._disposeNotifications();
}
}
});
}, interval * 1000);
}
_disposeNotifications() {
if (this.notificationsIntervalId) {
clearInterval(this.notificationsIntervalId);
this.notificationsIntervalId = null;
}
}
setNotificationsInterval(notificationIntervalSeconds) {
this._disposeNotifications();
if (notificationIntervalSeconds > 0) {
this._initNotifications({
notificationIntervalSeconds
});
}
}
getRootPath() {
return this.credentials.getRootPath();
}
static _encryptMessage(message, encryptingKey) {
if (!message)
return null;
return common_1.Utils.encryptMessage(message, encryptingKey);
}
_processTxNotes(notes) {
if (!notes)
return;
var encryptingKey = this.credentials.sharedEncryptingKey;
lodash_1.default.each([].concat(notes), note => {
note.encryptedBody = note.body;
note.body = common_1.Utils.decryptMessageNoThrow(note.body, encryptingKey);
note.encryptedEditedByName = note.editedByName;
note.editedByName = common_1.Utils.decryptMessageNoThrow(note.editedByName, encryptingKey);
});
}
_processTxps(txps) {
if (!txps)
return;
var encryptingKey = this.credentials.sharedEncryptingKey;
lodash_1.default.each([].concat(txps), txp => {
txp.encryptedMessage = txp.message;
txp.message =
common_1.Utils.decryptMessageNoThrow(txp.message, encryptingKey) || null;
txp.creatorName = common_1.Utils.decryptMessageNoThrow(txp.creatorName, encryptingKey);
lodash_1.default.each(txp.actions, action => {
action.copayerName = common_1.Utils.decryptMessageNoThrow(action.copayerName, encryptingKey);
action.comment = common_1.Utils.decryptMessageNoThrow(action.comment, encryptingKey);
});
lodash_1.default.each(txp.outputs, output => {
output.encryptedMessage = output.message;
output.message =
common_1.Utils.decryptMessageNoThrow(output.message, encryptingKey) || null;
});
txp.hasUnconfirmedInputs = lodash_1.default.some(txp.inputs, input => {
return input.confirmations == 0;
});
this._processTxNotes(txp.note);
});
}
validateKeyDerivation(opts, cb) {
var _deviceValidated;
opts = opts || {};
var c = this.credentials;
var testMessageSigning = (xpriv, xpub) => {
var nonHardenedPath = 'm/0/0';
var message = 'Lorem ipsum dolor sit amet, ne amet urbanitas percipitur vim, libris disputando his ne, et facer suavitate qui. Ei quidam laoreet sea. Cu pro dico aliquip gubergren, in mundi postea usu. Ad labitur posidonium interesset duo, est et doctus molestie adipiscing.';
var priv = xpriv.deriveChild(nonHardenedPath).privateKey;
var signature = common_1.Utils.signMessage(message, priv);
var pub = xpub.deriveChild(nonHardenedPath).publicKey;
return common_1.Utils.verifyMessage(message, signature, pub);
};
var testHardcodedKeys = () => {
var words = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
var xpriv = Mnemonic(words).toHDPrivateKey();
if (xpriv.toString() !=
'xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu')
return false;
xpriv = xpriv.deriveChild("m/44'/0'/0'");
if (xpriv.toString() !=
'xprv9xpXFhFpqdQK3TmytPBqXtGSwS3DLjojFhTGht8gwAAii8py5X6pxeBnQ6ehJiyJ6nDjWGJfZ95WxByFXVkDxHXrqu53WCRGypk2ttuqncb')
return false;
var xpub = Bitcore.HDPublicKey.fromString('xpub6BosfCnifzxcFwrSzQiqu2DBVTshkCXacvNsWGYJVVhhawA7d4R5WSWGFNbi8Aw6ZRc1brxMyWMzG3DSSSSoekkudhUd9yLb6qx39T9nMdj');
return testMessageSigning(xpriv, xpub);
};
var testLiveKeys = () => {
var words;
try {
words = c.getMnemonic();
}
catch (ex) { }
var xpriv;
if (words && (!c.mnemonicHasPassphrase || opts.passphrase)) {
var m = new Mnemonic(words);
xpriv = m.toHDPrivateKey(opts.passphrase, c.network);
}
if (!xpriv) {
xpriv = new Bitcore.HDPrivateKey(c.xPrivKey);
}
xpriv = xpriv.deriveChild(c.getBaseAddressDerivationPath());
var xpub = new Bitcore.HDPublicKey(c.xPubKey);
return testMessageSigning(xpriv, xpub);
};
var hardcodedOk = true;
if (!_deviceValidated && !opts.skipDeviceValidation) {
hardcodedOk = testHardcodedKeys();
_deviceValidated = true;
}
this.keyDerivationOk = hardcodedOk;
return cb(null, this.keyDerivationOk);
}
toObj() {
$.checkState(this.credentials, 'Failed state: this.credentials at <toObj()>');
return this.credentials.toObj();
}
toString(opts) {
$.checkState(this.credentials, 'Failed state: this.credentials at <toString()>');
$.checkArgument(!this.noSign, 'no Sign not supported');
$.checkArgument(!this.password, 'password not supported');
opts = opts || {};
var output;
output = JSON.stringify(this.toObj());
return output;
}
fromObj(credentials) {
$.checkArgument(lodash_1.default.isObject(credentials), 'Argument should be an object');
try {
credentials = credentials_1.Credentials.fromObj(credentials);
this.credentials = credentials;
}
catch (ex) {
log.warn(`Error importing wallet: ${ex}`);
if (ex.toString().match(/Obsolete/)) {
throw new Errors.OBSOLETE_BACKUP();
}
else {
throw new Errors.INVALID_BACKUP();
}
}
this.request.setCredentials(this.credentials);
}
fromString(credentials) {
if (lodash_1.default.isObject(credentials)) {
log.warn('WARN: Please use fromObj instead of fromString when importing strings');
return this.fromObj(credentials);
}
let c;
try {
c = JSON.parse(credentials);
}
catch (ex) {
log.warn(`Error importing wallet: ${ex}`);
throw new Errors.INVALID_BACKUP();
}
return this.fromObj(c);
}
decryptBIP38PrivateKey(encryptedPrivateKeyBase58, passphrase, opts, cb) {
var Bip38 = require('bip38');
var bip38 = new Bip38();
var privateKeyWif;
try {
privateKeyWif = bip38.decrypt(encryptedPrivateKeyBase58, passphrase);
}
catch (ex) {
return cb(new Error('Could not decrypt BIP38 private key' + ex));
}
var privateKey = new Bitcore.PrivateKey(privateKeyWif);
var address = privateKey.publicKey.toAddress().toString();
var addrBuff = Buffer.from(address, 'ascii');
var actualChecksum = Bitcore.crypto.Hash.sha256sha256(addrBuff)
.toString('hex')
.substring(0, 8);
var expectedChecksum = Bitcore.encoding.Base58Check.decode(encryptedPrivateKeyBase58)
.toString('hex')
.substring(6, 14);
if (actualChecksum != expectedChecksum)
return cb(new Error('Incorrect passphrase'));
return cb(null, privateKeyWif);
}
getBalanceFromPrivateKey(privateKey, coin, cb) {
if (lodash_1.default.isFunction(coin)) {
cb = coin;
coin = 'btc';
}
var B = Bitcore_[coin];
var privateKey = new B.PrivateKey(privateKey);
var address = privateKey.publicKey.toAddress().toString(true);
this.getUtxos({
addresses: address
}, (err, utxos) => {
if (err)
return cb(err);
return cb(null, lodash_1.default.sumBy(utxos, 'satoshis'));
});
}
buildTxFromPrivateKey(privateKey, destinationAddress, opts, cb) {
opts = opts || {};
var coin = opts.coin || 'btc';
var signingMethod = opts.signingMethod || 'ecdsa';
if (!lodash_1.default.includes(common_1.Constants.COINS, coin))
return cb(new Error('Invalid coin'));
if (coin == 'eth')
return cb(new Error('ETH not supported for this action'));
var B = Bitcore_[coin];
var privateKey = B.PrivateKey(privateKey);
var address = privateKey.publicKey.toAddress().toString(true);
async.waterfall([
next => {
this.getUtxos({
addresses: address
}, (err, utxos) => {
return next(err, utxos);
});
},
(utxos, next) => {
if (!lodash_1.default.isArray(utxos) || utxos.length == 0)
return next(new Error('No utxos found'));
var fee = opts.fee || 10000;
var amount = lodash_1.default.sumBy(utxos, 'satoshis') - fee;
if (amount <= 0)
return next(new Errors.INSUFFICIENT_FUNDS());
var tx;
try {
var toAddress = B.Address.fromString(destinationAddress);
tx = new B.Transaction()
.from(utxos)
.to(toAddress, amount)
.fee(fee)
.sign(privateKey, undefined, signingMethod);
tx.serialize();
}
catch (ex) {
log.error('Could not build transaction from private key', ex);
return next(new Errors.COULD_NOT_BUILD_TRANSACTION());
}
return next(null, tx);
}
], cb);
}
openWallet(opts, cb) {
if (lodash_1.default.isFunction(opts)) {
cb = opts;
}
opts = opts || {};
$.checkState(this.credentials, 'Failed state: this.credentials at <openWallet()>');
if (this.credentials.isComplete() && this.credentials.hasWalletInfo())
return cb(null, true);
var qs = [];
qs.push('includeExtendedInfo=1');
qs.push('serverMessageArray=1');
this.request.get('/v3/wallets/?' + qs.join('&'), (err, ret) => {
if (err)
return cb(err);
var wallet = ret.wallet;
this._processStatus(ret);
if (!this.credentials.hasWalletInfo()) {
var me = lodash_1.default.find(wallet.copayers, {
id: this.credentials.copayerId
});
if (!me)
return cb(new Error('Copayer not in wallet'));
try {
this.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, me["name"], opts);
}
catch (e) {
if (e.message) {
log.info('Trying credentials...', e.message);
}
if (e.message && e.message.match(/Bad\snr/)) {
return cb(new Errors.WALLET_DOES_NOT_EXIST());
}
throw e;
}
}
if (wallet.status != 'complete')
return cb(null, ret);
if (this.credentials.walletPrivKey) {
if (!verifier_1.Verifier.checkCopayers(this.credentials, wallet.copayers)) {
return cb(new Errors.SERVER_COMPROMISED());
}
}
else {
log.warn('Could not verify copayers key (missing wallet Private Key)');
}
this.credentials.addPublicKeyRing(this._extractPublicKeyRing(wallet.copayers));
this.emit('walletCompleted', wallet);
return cb(null, ret);
});
}
static _buildSecret(walletId, walletPrivKey, coin, network) {
if (lodash_1.default.isString(walletPrivKey)) {
walletPrivKey = Bitcore.PrivateKey.fromString(walletPrivKey);
}
var widHex = Buffer.from(walletId.replace(/-/g, ''), 'hex');
var widBase58 = new Bitcore.encoding.Base58(widHex).toString();
return (lodash_1.default.padEnd(widBase58, 22, '0') +
walletPrivKey.toWIF() +
(network == 'testnet' ? 'T' : 'L') +
coin);
}
static parseSecret(secret) {
$.checkArgument(secret);
var split = (str, indexes) => {
var parts = [];
indexes.push(str.length);
var i = 0;
while (i < indexes.length) {
parts.push(str.substring(i == 0 ? 0 : indexes[i - 1], indexes[i]));
i++;
}
return parts;
};
try {
var secretSplit = split(secret, [22, 74, 75]);
var widBase58 = secretSplit[0].replace(/0/g, '');
var widHex = Bitcore.encoding.Base58.decode(widBase58).toString('hex');
var walletId = split(widHex, [8, 12, 16, 20]).join('-');
var walletPrivKey = Bitcore.PrivateKey.fromString(secretSplit[1]);
var networkChar = secretSplit[2];
var coin = secretSplit[3] || 'btc';
return {
walletId,
walletPrivKey,
coin,
network: networkChar == 'T' ? 'testnet' : 'livenet'
};
}
catch (ex) {
throw new Error('Invalid secret');
}
}
static getRawTx(txp) {
var t = common_1.Utils.buildTx(txp);
return t.uncheckedSerialize();
}
_getCurrentSignatures(txp) {
var acceptedActions = lodash_1.default.filter(txp.actions, {
type: 'accept'
});
return lodash_1.default.map(acceptedActions, x => {
return {
signatures: x["signatures"],
xpub: x["xpub"]
};
});
}
_addSignaturesToBitcoreTxBitcoin(txp, t, signatures, xpub) {
$.checkState(txp.coin, 'Failed state: txp.coin undefined at _addSignaturesToBitcoreTxBitcoin');
$.checkState(txp.signingMethod, 'Failed state: txp.signingMethod undefined at _addSignaturesToBitcoreTxBitcoin');
const bitcore = Bitcore_[txp.coin];
if (signatures.length != txp.inputs.length)
throw new Error('Number of signatures does not match number of inputs');
let i = 0;
const x = new bitcore.HDPublicKey(xpub);
lodash_1.default.each(signatures, signatureHex => {
try {
const signature = bitcore.crypto.Signature.fromString(signatureHex);
const pub = x.deriveChild(txp.inputPaths[i]).publicKey;
const s = {
inputIndex: i,
signature,
sigtype: bitcore.crypto.Signature.SIGHASH_ALL |
bitcore.crypto.Signature.SIGHASH_FORKID,
publicKey: pub
};
t.inputs[i].addSignature(t, s, txp.signingMethod);
i++;
}
catch (e) { }
});
if (i != txp.inputs.length)
throw new Error('Wrong signatures');
}
_addSignaturesToBitcoreTx(txp, t, signatures, xpub) {
const { coin, network } = txp;
const chain = common_1.Utils.getChain(coin);
switch (chain) {
case 'XRP':
case 'ETH':
const unsignedTxs = t.uncheckedSerialize();
const signedTxs = [];
for (let index = 0; index < signatures.length; index++) {
const signed = CWC.Transactions.applySignature({
chain,
tx: unsignedTxs[index],
signature: signatures[index]
});
signedTxs.push(signed);
t.id = CWC.Transactions.getHash({ tx: signed, chain, network });
}
t.uncheckedSerialize = () => signedTxs;
t.serialize = () => signedTxs;
break;
default:
return this._addSignaturesToBitcoreTxBitcoin(txp, t, signatures, xpub);
}
}
_applyAllSignatures(txp, t) {
$.checkState(txp.status == 'accepted', 'Failed state: txp.status at _applyAllSignatures');
var sigs = this._getCurrentSignatures(txp);
lodash_1.default.each(sigs, x => {
this._addSignaturesToBitcoreTx(txp, t, x.signatures, x.xpub);
});
}
_doJoinWallet(walletId, walletPrivKey, xPubKey, requestPubKey, copayerName, opts, cb) {
$.shouldBeFunction(cb);
opts = opts || {};
opts.customData = opts.customData || {};
opts.customData.walletPrivKey = walletPrivKey.toString();
var encCustomData = common_1.Utils.encryptMessage(JSON.stringify(opts.customData), this.credentials.personalEncryptingKey);
var encCopayerName = common_1.Utils.encryptMessage(copayerName, this.credentials.sharedEncryptingKey);
var args = {
walletId,
coin: opts.coin,
name: encCopayerName,
xPubKey,
requestPubKey,
customData: encCustomData
};
if (opts.dryRun)
args.dryRun = true;
if (lodash_1.default.isBoolean(opts.supportBIP44AndP2PKH))
args.supportBIP44AndP2PKH = opts.supportBIP44AndP2PKH;
var hash = common_1.Utils.getCopayerHash(args.name, args.xPubKey, args.requestPubKey);
args.copayerSignature = common_1.Utils.signMessage(hash, walletPrivKey);
var url = '/v2/wallets/' + walletId + '/copayers';
this.request.post(url, args, (err, body) => {
if (err)
return cb(err);
this._processWallet(body.wallet);
return cb(null, body.wallet);
});
}
isComplete() {
return this.credentials && this.credentials.isComplete();
}
_extractPublicKeyRing(copayers) {
return lodash_1.default.map(copayers, copayer => {
var pkr = lodash_1.default.pick(copayer, ['xPubKey', 'requestPubKey']);
pkr.copayerName = copayer.name;
return pkr;
});
}
getFeeLevels(coin, network, cb) {
$.checkArgument(coin || lodash_1.default.includes(common_1.Constants.COINS, coin));
$.checkArgument(network || lodash_1.default.includes(['livenet', 'testnet'], network));
const chain = common_1.Utils.getChain(coin).toLowerCase();
this.request.get('/v2/feelevels/?coin=' +
(chain || 'btc') +
'&network=' +
(network || 'livenet'), (err, result) => {
if (err)
return cb(err);
return cb(err, result);
});
}
clearCache(cb) {
this.request.post('/v1/clearcache/', {}, (err, res) => {
return cb(err, res);
});
}
getVersion(cb) {
this.request.get('/v1/version/', cb);
}
_checkKeyDerivation() {
var isInvalid = this.keyDerivationOk === false;
if (isInvalid) {
log.error('Key derivation for this device is not working as expected');
}
return !isInvalid;
}
createWallet(walletName, copayerName, m, n, opts, cb) {
if (!this._checkKeyDerivation())
return cb(new Error('Cannot create new wallet'));
if (opts)
$.shouldBeObject(opts);
opts = opts || {};
var coin = opts.coin || 'btc';
if (!lodash_1.default.includes(common_1.Constants.COINS, coin))
return cb(new Error('Invalid coin'));
var network = opts.network || 'livenet';
if (!lodash_1.default.includes(['testnet', 'livenet'], network))
return cb(new Error('Invalid network'));
if (!this.credentials) {
return cb(new Error('Import credentials first with setCredentials()'));
}
if (coin != this.credentials.coin) {
return cb(new Error('Existing keys were created for a different coin'));
}
if (network != this.credentials.network) {
return cb(new Error('Existing keys were created for a different network'));
}
var walletPrivKey = opts.walletPrivKey || new Bitcore.PrivateKey();
var c = this.credentials;
c.addWalletPrivateKey(walletPrivKey.toString());
var encWalletName = common_1.Utils.encryptMessage(walletName, c.sharedEncryptingKey);
var args = {
name: encWalletName,
m,
n,
pubKey: new Bitcore.PrivateKey(walletPrivKey).toPublicKey().toString(),
coin,
network,
singleAddress: !!opts.singleAddress,
id: opts.id,
usePurpose48: n > 1,
useNativeSegwit: !!opts.useNativeSegwit
};
this.request.post('/v2/wallets/', args, (err, res) => {
if (err)
return cb(err);
var walletId = res.walletId;
c.addWalletInfo(walletId, walletName, m, n, copayerName, {
useNativeSegwit: opts.useNativeSegwit
});
var secret = API._buildSecret(c.walletId, c.walletPrivKey, c.coin, c.network);
this._doJoinWallet(walletId, walletPrivKey, c.xPubKey, c.requestPubKey, copayerName, {
coin
}, (err, wallet) => {
if (err)
return cb(err);
return cb(null, n > 1 ? secret : null);
});
});
}
joinWallet(secret, copayerName, opts, cb) {
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: joinWallet should receive 4 parameters.');
}
if (!this._checkKeyDerivation())
return cb(new Error('Cannot join wallet'));
opts = opts || {};
var coin = opts.coin || 'btc';
if (!lodash_1.default.includes(common_1.Constants.COINS, coin))
return cb(new Error('Invalid coin'));
try {
var secretData = API.parseSecret(secret);
}
catch (ex) {
return cb(ex);
}
if (!this.credentials) {
return cb(new Error('Import credentials first with setCredentials()'));
}
this.credentials.addWalletPrivateKey(secretData.walletPrivKey.toString());
this._doJoinWallet(secretData.walletId, secretData.walletPrivKey, this.credentials.xPubKey, this.credentials.requestPubKey, copayerName, {
coin,
dryRun: !!opts.dryRun
}, (err, wallet) => {
if (err)
return cb(err);
if (!opts.dryRun) {
this.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, copayerName, {
useNativeSegwit: wallet.addressType === common_1.Constants.SCRIPT_TYPES.P2WSH,
allowOverwrite: true
});
}
return cb(null, wallet);
});
}
recreateWallet(cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <recreateWallet()>');
$.checkState(this.credentials.isComplete());
$.checkState(this.credentials.walletPrivKey);
this.getStatus({
includeExtendedInfo: true
}, err => {
if (!err) {
log.info('Wallet is already created');
return cb();
}
var c = this.credentials;
var walletPrivKey = Bitcore.PrivateKey.fromString(c.walletPrivKey);
var walletId = c.walletId;
var supportBIP44AndP2PKH = c.derivationStrategy != common_1.Constants.DERIVATION_STRATEGIES.BIP45;
var encWalletName = common_1.Utils.encryptMessage(c.walletName || 'recovered wallet', c.sharedEncryptingKey);
var coin = c.coin;
var args = {
name: encWalletName,
m: c.m,
n: c.n,
pubKey: walletPrivKey.toPublicKey().toString(),
coin: c.coin,
network: c.network,
id: walletId,
supportBIP44AndP2PKH
};
this.request.post('/v2/wallets/', args, (err, body) => {
if (err) {
log.info('openWallet error' + err);
return cb(new Errors.WALLET_DOES_NOT_EXIST());
}
if (!walletId) {
walletId = body.walletId;
}
var i = 1;
async.each(this.credentials.publicKeyRing, (item, next) => {
var name = item.copayerName || 'copayer ' + i++;
this._doJoinWallet(walletId, walletPrivKey, item.xPubKey, item.requestPubKey, name, {
coin: c.coin,
supportBIP44AndP2PKH
}, err => {
if (err && err instanceof Errors.COPAYER_IN_WALLET)
return next();
return next(err);
});
}, cb);
});
});
}
_processWallet(wallet) {
var encryptingKey = this.credentials.sharedEncryptingKey;
var name = common_1.Utils.decryptMessageNoThrow(wallet.name, encryptingKey);
if (name != wallet.name) {
wallet.encryptedName = wallet.name;
}
wallet.name = name;
lodash_1.default.each(wallet.copayers, copayer => {
var name = common_1.Utils.decryptMessageNoThrow(copayer.name, encryptingKey);
if (name != copayer.name) {
copayer.encryptedName = copayer.name;
}
copayer.name = name;
lodash_1.default.each(copayer.requestPubKeys, access => {
if (!access.name)
return;
var name = common_1.Utils.decryptMessageNoThrow(access.name, encryptingKey);
if (name != access.name) {
access.encryptedName = access.name;
}
access.name = name;
});
});
}
_processStatus(status) {
var processCustomData = data => {
var copayers = data.wallet.copayers;
if (!copayers)
return;
var me = lodash_1.default.find(copayers, {
id: this.credentials.copayerId
});
if (!me || !me["customData"])
return;
var customData;
try {
customData = JSON.parse(common_1.Utils.decryptMessage(me["customData"], this.credentials.personalEncryptingKey));
}
catch (e) {
log.warn('Could not decrypt customData:', me["customData"]);
}
if (!customData)
return;
data.customData = customData;
if (!this.credentials.walletPrivKey && customData.walletPrivKey)
this.credentials.addWalletPrivateKey(customData.walletPrivKey);
};
processCustomData(status);
this._processWallet(status.wallet);
this._processTxps(status.pendingTxps);
}
getNotifications(opts, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <getNotifications()>');
opts = opts || {};
var url = '/v1/notifications/';
if (opts.lastNotificationId) {
url += '?notificationId=' + opts.lastNotificationId;
}
else if (opts.timeSpan) {
url += '?timeSpan=' + opts.timeSpan;
}
this.request.getWithLogin(url, (err, result) => {
if (err)
return cb(err);
var notifications = lodash_1.default.filter(result, notification => {
return (opts.includeOwn ||
notification.creatorId != this.credentials.copayerId);
});
return cb(null, notifications);
});
}
getStatus(opts, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <getStatus()>');
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: getStatus should receive 2 parameters.');
}
opts = opts || {};
var qs = [];
qs.push('includeExtendedInfo=' + (opts.includeExtendedInfo ? '1' : '0'));
qs.push('twoStep=' + (opts.twoStep ? '1' : '0'));
qs.push('serverMessageArray=1');
if (opts.tokenAddress) {
qs.push('tokenAddress=' + opts.tokenAddress);
}
if (opts.multisigContractAddress) {
qs.push('multisigContractAddress=' + opts.multisigContractAddress);
qs.push('network=' + this.credentials.network);
}
this.request.get('/v3/wallets/?' + qs.join('&'), (err, result) => {
if (err)
return cb(err);
if (result.wallet.status == 'pending') {
var c = this.credentials;
result.wallet.secret = API._buildSecret(c.walletId, c.walletPrivKey, c.coin, c.network);
}
this._processStatus(result);
return cb(err, result);
});
}
getPreferences(cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <getPreferences()>');
$.checkArgument(cb);
this.request.get('/v1/preferences/', (err, preferences) => {
if (err)
return cb(err);
return cb(null, preferences);
});
}
savePreferences(preferences, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <savePreferences()>');
$.checkArgument(cb);
this.request.put('/v1/preferences/', preferences, cb);
}
fetchPayPro(opts, cb) {
$.checkArgument(opts).checkArgument(opts.payProUrl);
paypro_1.PayPro.get({
url: opts.payProUrl,
coin: this.credentials.coin || 'btc',
network: this.credentials.network || 'livenet',
request: this.request
}, (err, paypro) => {
if (err)
return cb(err);
return cb(null, paypro);
});
}
getUtxos(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <getUtxos()>');
opts = opts || {};
var url = '/v1/utxos/';
if (opts.addresses) {
url +=
'?' +
querystring.stringify({
addresses: [].concat(opts.addresses).join(',')
});
}
this.request.get(url, cb);
}
getCoinsForTx(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <getCoinsForTx()>');
opts = opts || {};
var url = '/v1/txcoins/';
url +=
'?' +
querystring.stringify({
coin: opts.coin,
network: opts.network,
txId: opts.txId
});
this.request.get(url, cb);
}
_getCreateTxProposalArgs(opts) {
var args = lodash_1.default.cloneDeep(opts);
args.message =
API._encryptMessage(opts.message, this.credentials.sharedEncryptingKey) ||
null;
args.payProUrl = opts.payProUrl || null;
lodash_1.default.each(args.outputs, o => {
o.message =
API._encryptMessage(o.message, this.credentials.sharedEncryptingKey) ||
null;
});
return args;
}
createTxProposal(opts, cb, baseUrl) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <createTxProposal()>');
$.checkState(this.credentials.sharedEncryptingKey);
$.checkArgument(opts);
if (!opts.signingMethod && this.credentials.coin == 'bch') {
opts.signingMethod = 'schnorr';
}
var args = this._getCreateTxProposalArgs(opts);
baseUrl = baseUrl || '/v3/txproposals/';
this.request.post(baseUrl, args, (err, txp) => {
if (err)
return cb(err);
this._processTxps(txp);
if (!verifier_1.Verifier.checkProposalCreation(args, txp, this.credentials.sharedEncryptingKey)) {
return cb(new Errors.SERVER_COMPROMISED());
}
return cb(null, txp);
});
}
publishTxProposal(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <publishTxProposal()>');
$.checkArgument(opts).checkArgument(opts.txp);
$.checkState(parseInt(opts.txp.version) >= 3);
var t = common_1.Utils.buildTx(opts.txp);
var hash = t.uncheckedSerialize();
var args = {
proposalSignature: common_1.Utils.signMessage(hash, this.credentials.requestPrivKey)
};
var url = '/v2/txproposals/' + opts.txp.id + '/publish/';
this.request.post(url, args, (err, txp) => {
if (err)
return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
}
createAddress(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <createAddress()>');
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: createAddress should receive 2 parameters.');
}
if (!this._checkKeyDerivation())
return cb(new Error('Cannot create new address for this wallet'));
opts = opts || {};
this.request.post('/v4/addresses/', opts, (err, address) => {
if (err)
return cb(err);
if (!verifier_1.Verifier.checkAddress(this.credentials, address)) {
return cb(new Errors.SERVER_COMPROMISED());
}
return cb(null, address);
});
}
getMainAddresses(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete());
opts = opts || {};
var args = [];
if (opts.limit)
args.push('limit=' + opts.limit);
if (opts.reverse)
args.push('reverse=1');
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
var url = '/v1/addresses/' + qs;
this.request.get(url, (err, addresses) => {
if (err)
return cb(err);
if (!opts.doNotVerify) {
var fake = lodash_1.default.some(addresses, address => {
return !verifier_1.Verifier.checkAddress(this.credentials, address);
});
if (fake)
return cb(new Errors.SERVER_COMPROMISED());
}
return cb(null, addresses);
});
}
getBalance(opts, cb) {
if (!cb) {
cb = opts;
opts = {};
log.warn('DEPRECATED WARN: getBalance should receive 2 parameters.');
}
opts = opts || {};
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <getBalance()>');
var args = [];
if (opts.coin) {
if (!lodash_1.default.includes(common_1.Constants.COINS, opts.coin))
return cb(new Error('Invalid coin'));
args.push('coin=' + opts.coin);
}
if (opts.tokenAddress) {
args.push('tokenAddress=' + opts.tokenAddress);
}
if (opts.multisigContractAddress) {
args.push('multisigContractAddress=' + opts.multisigContractAddress);
}
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
var url = '/v1/balance/' + qs;
this.request.get(url, cb);
}
getTxProposals(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <getTxProposals()>');
this.request.get('/v2/txproposals/', (err, txps) => {
if (err)
return cb(err);
this._processTxps(txps);
async.every(txps, (txp, acb) => {
if (opts.doNotVerify)
return acb(true);
this.getPayProV2(txp)
.then(paypro => {
var isLegit = verifier_1.Verifier.checkTxProposal(this.credentials, txp, {
paypro
});
return acb(isLegit);
})
.catch(err => {
return acb(err);
});
}, isLegit => {
if (!isLegit)
return cb(new Errors.SERVER_COMPROMISED());
var result;
if (opts.forAirGapped) {
result = {
txps: JSON.parse(JSON.stringify(txps)),
encryptedPkr: opts.doNotEncryptPkr
? null
: common_1.Utils.encryptMessage(JSON.stringify(this.credentials.publicKeyRing), this.credentials.personalEncryptingKey),
unencryptedPkr: opts.doNotEncryptPkr
? JSON.stringify(this.credentials.publicKeyRing)
: null,
m: this.credentials.m,
n: this.credentials.n
};
}
else {
result = txps;
}
return cb(null, result);
});
});
}
getPayPro(txp, cb) {
if (!txp.payProUrl || this.doNotVerifyPayPro)
return cb();
paypro_1.PayPro.get({
url: txp.payProUrl,
coin: txp.coin || 'btc',
network: txp.network || 'livenet',
request: this.request
}, (err, paypro) => {
if (err)
return cb(new Error('Could not fetch invoice:' + (err.message ? err.message : err)));
return cb(null, paypro);
});
}
getPayProV2(txp) {
if (!txp.payProUrl || this.doNotVerifyPayPro)
return Promise.resolve();
const chain = common_1.Utils.getChain(txp.coin);
const currency = txp.coin.toUpperCase();
const payload = {
address: txp.from
};
return payproV2_1.PayProV2.selectPaymentOption({
paymentUrl: txp.payProUrl,
chain,
currency,
payload
});
}
pushSignatures(txp, signatures, cb, base) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <pushSignatures()>');
$.checkArgument(txp.creatorId);
if (lodash_1.default.isEmpty(signatures)) {
return cb('No signatures to push. Sign the transaction with Key first');
}
this.getPayProV2(txp)
.then(paypro => {
var isLegit = verifier_1.Verifier.checkTxProposal(this.credentials, txp, {
paypro
});
if (!isLegit)
return cb(new Errors.SERVER_COMPROMISED());
let defaultBase = '/v2/txproposals/';
base = base || defaultBase;
let url = base + txp.id + '/signatures/';
var args = {
signatures
};
this.request.post(url, args, (err, txp) => {
if (err)
return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
})
.catch(err => {
return cb(err);
});
}
createAdvertisement(opts, cb) {
var url = '/v1/advertisements/';
let args = opts;
this.request.post(url, args, (err, createdAd) => {
if (err) {
return cb(err);
}
return cb(null, createdAd);
});
}
getAdvertisements(opts, cb) {
var url = '/v1/advertisements/';
if (opts.testing === true) {
url = '/v1/advertisements/' + '?testing=true';
}
this.request.get(url, (err, ads) => {
if (err) {
return cb(err);
}
return cb(null, ads);
});
}
getAdvertisementsByCountry(opts, cb) {
var url = '/v1/advertisements/country/' + opts.country;
this.request.get(url, (err, ads) => {
if (err) {
return cb(err);
}
return cb(null, ads);
});
}
getAdvertisement(opts, cb) {
var url = '/v1/advertisements/' + opts.adId;
this.request.get(url, (err, body) => {
if (err) {
return cb(err);
}
return cb(null, body);
});
}
activateAdvertisement(opts, cb) {
var url = '/v1/advertisements/' + opts.adId + '/activate';
let args = opts;
this.request.post(url, args, (err, body) => {
if (err) {
return cb(err);
}
return cb(null, body);
});
}
deactivateAdvertisement(opts, cb) {
var url = '/v1/advertisements/' + opts.adId + '/deactivate';
let args = opts;
this.request.post(url, args, (err, body) => {
if (err) {
return cb(err);
}
return cb(null, body);
});
}
deleteAdvertisement(opts, cb) {
var url = '/v1/advertisements/' + opts.adId;
this.request.delete(url, (err, body) => {
if (err) {
return cb(err);
}
return cb(null, body);
});
}
signTxProposalFromAirGapped(txp, encryptedPkr, m, n, password) {
throw new Error('signTxProposalFromAirGapped not yet implemented in v9.0.0');
}
static signTxProposalFromAirGapped(key, txp, unencryptedPkr, m, n, opts, cb) {
opts = opts || {};
var coin = opts.coin || 'btc';
if (!lodash_1.default.includes(common_1.Constants.COINS, coin))
return cb(new Error('Invalid coin'));
var publicKeyRing = JSON.parse(unencryptedPkr);
if (!lodash_1.default.isArray(publicKeyRing) || publicKeyRing.length != n) {
throw new Error('Invalid public key ring');
}
var newClient = new API({
baseUrl: 'https://bws.example.com/bws/api'
});
if (key.slice(0, 4) === 'xprv' || key.slice(0, 4) === 'tprv') {
if (key.slice(0, 4) === 'xprv' && txp.network == 'testnet')
throw new Error('testnet HD keys must start with tprv');
if (key.slice(0, 4) === 'tprv' && txp.network == 'livenet')
throw new Error('livenet HD keys must start with xprv');
newClient.seedFromExtendedPrivateKey(key, {
coin,
account: opts.account,
derivationStrategy: opts.derivationStrategy
});
}
else {
newClient.seedFromMnemonic(key, {
coin,
network: txp.network,
passphrase: opts.passphrase,
account: opts.account,
derivationStrategy: opts.derivationStrategy
});
}
newClient.credentials.m = m;
newClient.credentials.n = n;
newClient.credentials.addressType = txp.addressType;
newClient.credentials.addPublicKeyRing(publicKeyRing);
if (!verifier_1.Verifier.checkTxProposalSignature(newClient.credentials, txp))
throw new Error('Fake transaction proposal');
return newClient._signTxp(txp);
}
rejectTxProposal(txp, reason, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <rejectTxProposal()>');
$.checkArgument(cb);
var url = '/v1/txproposals/' + txp.id + '/rejections/';
var args = {
reason: API._encryptMessage(reason, this.credentials.sharedEncryptingKey) || ''
};
this.request.post(url, args, (err, txp) => {
if (err)
return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
}
broadcastRawTx(opts, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <broadcastRawTx()>');
$.checkArgument(cb);
opts = opts || {};
var url = '/v1/broadcast_raw/';
this.request.post(url, opts, (err, txid) => {
if (err)
return cb(err);
return cb(null, txid);
});
}
_doBroadcast(txp, cb) {
var url = '/v1/txproposals/' + txp.id + '/broadcast/';
this.request.post(url, {}, (err, txp) => {
if (err)
return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
}
broadcastTxProposal(txp, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <broadcastTxProposal()>');
this.getPayProV2(txp)
.then(paypro => {
if (paypro) {
var t_unsigned = common_1.Utils.buildTx(txp);
var t = lodash_1.default.cloneDeep(t_unsigned);
this._applyAllSignatures(txp, t);
const chain = common_1.Utils.getChain(txp.coin);
const currency = txp.coin.toUpperCase();
const rawTxUnsigned = t_unsigned.uncheckedSerialize();
const serializedTx = t.serialize({
disableSmallFees: true,
disableLargeFees: true,
disableDustOutputs: true
});
const unsignedTransactions = [];
const signedTransactions = [];
const unserializedTxs = typeof rawTxUnsigned === 'string' ? [rawTxUnsigned] : rawTxUnsigned;
const serializedTxs = typeof serializedTx === 'string' ? [serializedTx] : serializedTx;
const weightedSize = [];
let isBtcSegwit = txp.coin == 'btc' &&
(txp.addressType == 'P2WSH' || txp.addressType == 'P2WPKH');
let i = 0;
for (const unsigned of unserializedTxs) {
let size;
if (isBtcSegwit) {
size = Math.floor((txp.fee / txp.feePerKb) * 1000) - 10;
}
else {
size = serializedTxs[i].length / 2;
}
unsignedTransactions.push({
tx: unsigned,
weightedSize: size
});
weightedSize.push(size);
i++;
}
i = 0;
for (const signed of serializedTxs) {
signedTransactions.push({
tx: signed,
weightedSize: weightedSize[i++]
});
}
payproV2_1.PayProV2.verifyUnsignedPayment({
paymentUrl: txp.payProUrl,
chain,
currency,
unsignedTransactions
})
.then(() => {
payproV2_1.PayProV2.sendSignedPayment({
paymentUrl: txp.payProUrl,
chain,
currency,
signedTransactions,
bpPartner: {
bp_partner: this.bp_partner,
bp_partner_version: this.bp_partner_version
}
})
.then(payProDetails => {
if (payProDetails.memo) {
log.debug('Merchant memo:', payProDetails.memo);
}
return cb(null, txp, payProDetails.memo);
})
.catch(err => {
return cb(err);
});
})
.catch(err => {
return cb(err);
});
}
else {
this._doBroadcast(txp, cb);
}
})
.catch(err => {
return cb(err);
});
}
removeTxProposal(txp, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <removeTxProposal()>');
var url = '/v1/txproposals/' + txp.id;
this.request.delete(url, err => {
return cb(err);
});
}
getTxHistory(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <getTxHistory()>');
var args = [];
if (opts) {
if (opts.skip)
args.push('skip=' + opts.skip);
if (opts.limit)
args.push('limit=' + opts.limit);
if (opts.tokenAddress)
args.push('tokenAddress=' + opts.tokenAddress);
if (opts.multisigContractAddress)
args.push('multisigContractAddress=' + opts.multisigContractAddress);
if (opts.includeExtendedInfo)
args.push('includeExtendedInfo=1');
}
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
var url = '/v1/txhistory/' + qs;
this.request.get(url, (err, txs) => {
if (err)
return cb(err);
this._processTxps(txs);
return cb(null, txs);
});
}
getTx(id, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <getTx()>');
var url = '/v1/txproposals/' + id;
this.request.get(url, (err, txp) => {
if (err)
return cb(err);
this._processTxps(txp);
return cb(null, txp);
});
}
startScan(opts, cb) {
$.checkState(this.credentials && this.credentials.isComplete(), 'Failed state: this.credentials at <startScan()>');
var args = {
includeCopayerBranches: opts.includeCopayerBranches
};
this.request.post('/v1/addresses/scan', args, err => {
return cb(err);
});
}
addAccess(opts, cb) {
$.checkState(this.credentials, 'Failed state: no this.credentials at <addAccess()>');
$.shouldBeString(opts.requestPrivKey, 'Failed state: no requestPrivKey at addAccess() ');
$.shouldBeString(opts.signature, 'Failed state: no signature at addAccess()');
opts = opts || {};
var requestPubKey = new Bitcore.PrivateKey(opts.requestPrivKey)
.toPublicKey()
.toString();
var copayerId = this.credentials.copayerId;
var encCopayerName = opts.name
? common_1.Utils.encryptMessage(opts.name, this.credentials.sharedEncryptingKey)
: null;
var opts2 = {
copayerId,
requestPubKey,
signature: opts.signature,
name: encCopayerName,
restrictions: opts.restrictions
};
this.request.put('/v1/copayers/' + copayerId + '/', opts2, (err, res) => {
if (err)
return cb(err);
return cb(null, res.wallet, opts.requestPrivKey);
});
}
getTxNote(opts, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <getTxNote()>');
opts = opts || {};
this.request.get('/v1/txnotes/' + opts.txid + '/', (err, note) => {
if (err)
return cb(err);
this._processTxNotes(note);
return cb(null, note);
});
}
editTxNote(opts, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <editTxNote()>');
opts = opts || {};
if (opts.body) {
opts.body = API._encryptMessage(opts.body, this.credentials.sharedEncryptingKey);
}
this.request.put('/v1/txnotes/' + opts.txid + '/', opts, (err, note) => {
if (err)
return cb(err);
this._processTxNotes(note);
return cb(null, note);
});
}
getTxNotes(opts, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <getTxNotes()>');
opts = opts || {};
var args = [];
if (lodash_1.default.isNumber(opts.minTs)) {
args.push('minTs=' + opts.minTs);
}
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
this.request.get('/v1/txnotes/' + qs, (err, notes) => {
if (err)
return cb(err);
this._processTxNotes(notes);
return cb(null, notes);
});
}
getFiatRate(opts, cb) {
$.checkArgument(cb);
var opts = opts || {};
var args = [];
if (opts.ts)
args.push('ts=' + opts.ts);
if (opts.coin)
args.push('coin=' + opts.coin);
var qs = '';
if (args.length > 0) {
qs = '?' + args.join('&');
}
this.request.get('/v1/fiatrates/' + opts.code + '/' + qs, (err, rates) => {
if (err)
return cb(err);
return cb(null, rates);
});
}
pushNotificationsSubscribe(opts, cb) {
var url = '/v1/pushnotifications/subscriptions/';
this.request.post(url, opts, (err, response) => {
if (err)
return cb(err);
return cb(null, response);
});
}
pushNotificationsUnsubscribe(token, cb) {
var url = '/v2/pushnotifications/subscriptions/' + token;
this.request.delete(url, cb);
}
txConfirmationSubscribe(opts, cb) {
var url = '/v1/txconfirmations/';
this.request.post(url, opts, (err, response) => {
if (err)
return cb(err);
return cb(null, response);
});
}
txConfirmationUnsubscribe(txid, cb) {
var url = '/v1/txconfirmations/' + txid;
this.request.delete(url, cb);
}
getSendMaxInfo(opts, cb) {
var args = [];
opts = opts || {};
if (opts.feeLevel)
args.push('feeLevel=' + opts.feeLevel);
if (opts.feePerKb != null)
args.push('feePerKb=' + opts.feePerKb);
if (opts.excludeUnconfirmedUtxos)
args.push('excludeUnconfirmedUtxos=1');
if (opts.returnInputs)
args.push('returnInputs=1');
var qs = '';
if (args.length > 0)
qs = '?' + args.join('&');
var url = '/v1/sendmaxinfo/' + qs;
this.request.get(url, (err, result) => {
if (err)
return cb(err);
return cb(null, result);
});
}
getEstimateGas(opts, cb) {
var url = '/v3/estimateGas/';
this.request.post(url, opts, (err, gasLimit) => {
if (err)
return cb(err);
return cb(null, gasLimit);
});
}
getMultisigContractInstantiationInfo(opts, cb) {
var url = '/v1/ethmultisig/';
opts.network = this.credentials.network;
this.request.post(url, opts, (err, contractInstantiationInfo) => {
if (err)
return cb(err);
return cb(null, contractInstantiationInfo);
});
}
getMultisigContractInfo(opts, cb) {
var url = '/v1/ethmultisig/info';
opts.network = this.credentials.network;
this.request.post(url, opts, (err, contractInfo) => {
if (err)
return cb(err);
return cb(null, contractInfo);
});
}
getStatusByIdentifier(opts, cb) {
$.checkState(this.credentials, 'Failed state: this.credentials at <getStatusByIdentifier()>');
opts = opts || {};
var qs = [];
qs.push('includeExtendedInfo=' + (opts.includeExtendedInfo ? '1' : '0'));
qs.push('walletCheck=' + (opts.walletCheck ? '1' : '0'));
this.request.get('/v1/wallets/' + opts.identifier + '?' + qs.join('&'), (err, result) => {
if (err || !result || !result.wallet)
return cb(err);
if (result.wallet.status == 'pending') {
var c = this.credentials;
result.wallet.secret = API._buildSecret(c.walletId, c.walletPrivKey, c.coin, c.network);
}
this._processStatus(result);
return cb(err, result);
});
}
_oldCopayDecrypt(username, password, blob) {
var SEP1 = '@#$';
var SEP2 = '%^#@';
var decrypted;
try {
var passphrase = username + SEP1 + password;
decrypted = sjcl_1.default.decrypt(passphrase, blob);
}
catch (e) {
passphrase = username + SEP2 + password;
try {
decrypted = sjcl_1.default.decrypt(passphrase, blob);
}
catch (e) {
log.debug(e);
}
}
if (!decrypted)
return null;
var ret;
try {
ret = JSON.parse(decrypted);
}
catch (e) { }
return ret;
}
getWalletIdsFromOldCopay(username, password, blob) {
var p = this._oldCopayDecrypt(username, password, blob);
if (!p)
return null;
var ids = p.walletIds.concat(lodash_1.default.keys(p.focusedTimestamps));
return lodash_1.default.uniq(ids);
}
static upgradeCredentialsV1(x) {
$.shouldBeObject(x);
if (!lodash_1.default.isUndefined(x.version) ||
(!x.xPrivKey && !x.xPrivKeyEncrypted && !x.xPubKey)) {
throw new Error('Could not recognize old version');
}
let k;
if (x.xPrivKey || x.xPrivKeyEncrypted) {
k = new key_1.Key({ seedData: x, seedType: 'objectV1' });
}
else {
k = false;
}
let obsoleteFields = {
version: true,
xPrivKey: true,
xPrivKeyEncrypted: true,
hwInfo: true,
entropySourcePath: true,
mnemonic: true,
mnemonicEncrypted: true
};
var c = new credentials_1.Credentials();
lodash_1.default.each(credentials_1.Credentials.FIELDS, i => {
if (!obsoleteFields[i]) {
c[i] = x[i];
}
});
if (c.externalSource) {
throw new Error('External Wallets are no longer supported');
}
c.coin = c.coin || 'btc';
c.addressType = c.addressType || common_1.Constants.SCRIPT_TYPES.P2SH;
c.account = c.account || 0;
c.rootPath = c.getRootPath();
c.keyId = k.id;
return { key: k, credentials: c };
}
static upgradeMultipleCredentialsV1(oldCredentials) {
let newKeys = [], newCrededentials = [];
lodash_1.default.each(oldCredentials, credentials => {
let migrated;
if (!credentials.version || credentials.version < 2) {
log.info('About to migrate : ' + credentials.walletId);
migrated = API.upgradeCredentialsV1(credentials);
newCrededentials.push(migrated.credentials);
if (migrated.key) {
log.info(`Wallet ${credentials.walletId} key's extracted`);
newKeys.push(migrated.key);
}
else {
log.info(`READ-ONLY Wallet ${credentials.walletId} migrated`);
}
}
});
if (newKeys.length > 0) {
let credGroups = lodash_1.default.groupBy(newCrededentials, x => {
$.checkState(x.xPubKey, 'Failed state: no xPubKey at credentials!');
let xpub = new Bitcore.HDPublicKey(x.xPubKey);
let fingerPrint = xpub.fingerPrint.toString('hex');
return fingerPrint;
});
if (lodash_1.default.keys(credGroups).length < newCrededentials.length) {
log.info('Found some wallets using the SAME key. Merging...');
let uniqIds = {};
lodash_1.default.each(lodash_1.default.values(credGroups), credList => {
let toKeep = credList.shift();
if (!toKeep.keyId)
return;
uniqIds[toKeep.keyId] = true;
if (!credList.length)
return;
log.info(`Merging ${credList.length} keys to ${toKeep.keyId}`);
lodash_1.default.each(credList, x => {
log.info(`\t${x.keyId} is now ${toKeep.keyId}`);
x.keyId = toKeep.keyId;
});
});
newKeys = lodash_1.default.filter(newKeys, x => uniqIds[x.id]);
}
}
return {
keys: newKeys,
credentials: newCrededentials
};
}
static serverAssistedImport(opts, clientOpts, callback) {
$.checkArgument(opts.words || opts.xPrivKey, 'provide opts.words or opts.xPrivKey');
let copayerIdAlreadyTested = {};
var checkCredentials = (key, opts, icb) => {
let c = key.createCredentials(null, {
coin: opts.coin,
network: opts.network,
account: opts.account,
n: opts.n
});
if (copayerIdAlreadyTested[c.copayerId + ':' + opts.n]) {
return icb();
}
else {
copayerIdAlreadyTested[c.copayerId + ':' + opts.n] = true;
}
let client = clientOpts.clientFactory
? clientOpts.clientFactory()
: new API(clientOpts);
client.fromString(c);
client.openWallet({}, (err, status) => {
if (!err) {
if (opts.coin == 'btc' &&
(status.wallet.addressType == 'P2WPKH' ||
status.wallet.addressType == 'P2WSH')) {
client.credentials.addressType =
status.wallet.n == 1
? common_1.Constants.SCRIPT_TYPES.P2WPKH
: common_1.Constants.SCRIPT_TYPES.P2WSH;
}
let clients = [client];
const tokenAddresses = status.preferences.tokenAddresses;
if (!lodash_1.default.isEmpty(tokenAddresses)) {
lodash_1.default.each(tokenAddresses, t => {
const token = common_1.Constants.TOKEN_OPTS[t];
if (!token) {
log.warn(`Token ${t} unknown`);
return;
}
log.info(`Importing token: ${token.name}`);
const tokenCredentials = client.credentials.getTokenCredentials(token);
let tokenClient = lodash_1.default.cloneDeep(client);
tokenClient.credentials = tokenCredentials;
clients.push(tokenClient);
});
}
const multisigEthInfo = status.preferences.multisigEthInfo;
if (!lodash_1.default.isEmpty(multisigEthInfo)) {
lodash_1.default.each(multisigEthInfo, info => {
log.info(`Importing multisig wallet. Address: ${info.multisigContractAddress} - m: ${info.m} - n: ${info.n}`);
const multisigEthCredentials = client.credentials.getMultisigEthCredentials({
walletName: info.walletName,
multisigContractAddress: info.multisigContractAddress,
n: info.n,
m: info.m
});
let multisigEthClient = lodash_1.default.cloneDeep(client);
multisigEthClient.credentials = multisigEthCredentials;
clients.push(multisigEthClient);
const tokenAddresses = info.tokenAddresses;
if (!lodash_1.default.isEmpty(tokenAddresses)) {
lodash_1.default.each(tokenAddresses, t => {
const token = common_1.Constants.TOKEN_OPTS[t];
if (!token) {
log.warn(`Token ${t} unknown`);
return;
}
log.info(`Importing multisig token: ${token.name}`);
const tokenCredentials = multisigEthClient.credentials.getTokenCredentials(token);
let tokenClient = lodash_1.default.cloneDeep(multisigEthClient);
tokenClient.credentials = tokenCredentials;
clients.push(tokenClient);
});
}
});
}
return icb(null, clients);
}
if (err instanceof Errors.NOT_AUTHORIZED ||
err instanceof Errors.WALLET_DOES_NOT_EXIST) {
return icb();
}
return icb(err);
});
};
var checkKey = (key, cb) => {
let opts = [
['btc', 'livenet'],
['edu', 'livenet'],
['tik', 'livenet'],
['bch', 'livenet'],
['eth', 'livenet'],
['eth', 'testnet'],
['xrp', 'livenet'],
['xrp', 'testnet'],
['doge', 'livenet'],
['doge', 'testnet'],
['btc', 'livenet', true],
['edu', 'livenet', true],
['tik', 'livenet', true],
['bch', 'livenet', true]
];
if (key.use44forMultisig) {
opts = opts.filter(x => {
return x[2];
});
}
if (key.use0forBCH) {
opts = opts.filter(x => {
return x[0] == 'bch';
});
}
if (!key.nonCompliantDerivation) {
let testnet = lodash_1.default.cloneDeep(opts);
testnet.forEach(x => {
x[1] = 'testnet';
});
opts = opts.concat(testnet);
}
else {
opts = opts.filter(x => {
return x[0] == 'btc';
});
}
let clients = [];
async.eachSeries(opts, (x, next) => {
let optsObj = {
coin: x[0],
network: x[1],
account: 0,
n: x[2] ? 2 : 1
};
checkCredentials(key, optsObj, (err, iclients) => {
if (err)
return next(err);
if (lodash_1.default.isEmpty(iclients))
return next();
clients = clients.concat(iclients);
if (key.use0forBCH ||
!key.compliantDerivation ||
key.use44forMultisig ||
key.BIP45)
return next();
let cont = true, account = 1;
async.whilst(() => {
return cont;
}, icb => {
optsObj.account = account++;
checkCredentials(key, optsObj, (err, iclients) => {
if (err)
return icb(err);
cont = !lodash_1.default.isEmpty(iclients);
if (cont) {
clients = clients.concat(iclients);
}
return icb();
});
}, err => {
return next(err);
});
});
}, err => {
if (err)
return cb(err);
return cb(null, clients);
});
};
let sets = [
{
nonCompliantDerivation: false,
useLegacyCoinType: false,
useLegacyPurpose: false
},
{
nonCompliantDerivation: false,
useLegacyCoinType: true,
useLegacyPurpose: false
},
{
nonCompliantDerivation: false,
useLegacyCoinType: false,
useLegacyPurpose: true
},
{
nonCompliantDerivation: false,
useLegacyCoinType: true,
useLegacyPurpose: true
},
{
nonCompliantDerivation: true,
useLegacyPurpose: true
}
];
let s, resultingClients = [], k;
async.whilst(() => {
if (!lodash_1.default.isEmpty(resultingClients))
return false;
s = sets.shift();
if (!s)
return false;
try {
if (opts.words) {
if (opts.passphrase) {
s.passphrase = opts.passphrase;
}
k = new key_1.Key(Object.assign({ seedData: opts.words, seedType: 'mnemonic' }, s));
}
else {
k = new key_1.Key(Object.assign({ seedData: opts.xPrivKey, seedType: 'extendedPrivateKey' }, s));
}
}
catch (e) {
log.info('Backup error:', e);
return callback(new Errors.INVALID_BACKUP());
}
return true;
}, icb => {
checkKey(k, (err, clients) => {
if (err)
return icb(err);
if (clients && clients.length) {
resultingClients = clients;
}
return icb();
});
}, err => {
if (err)
return callback(err);
if (lodash_1.default.isEmpty(resultingClients))
k = null;
return callback(null, k, resultingClients);
});
}
simplexGetQuote(data) {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/simplex/quote', data, (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
simplexPaymentRequest(data) {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/simplex/paymentRequest', data, (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
simplexGetEvents(data) {
return new Promise((resolve, reject) => {
let qs = [];
qs.push('env=' + data.env);
this.request.get('/v1/service/simplex/events/?' + qs.join('&'), (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
wyreWalletOrderQuotation(data) {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/wyre/walletOrderQuotation', data, (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
wyreWalletOrderReservation(data) {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/wyre/walletOrderReservation', data, (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
changellyGetPairsParams(data) {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/changelly/getPairsParams', data, (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
changellyGetFixRateForAmount(data) {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/changelly/getFixRateForAmount', data, (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
changellyCreateFixTransaction(data) {
return new Promise((resolve, reject) => {
this.request.post('/v1/service/changelly/createFixTransaction', data, (err, data) => {
if (err)
return reject(err);
return resolve(data);
});
});
}
}
exports.API = API;
API.PayProV2 = payproV2_1.PayProV2;
API.PayPro = paypro_1.PayPro;
API.Key = key_1.Key;
API.Verifier = verifier_1.Verifier;
API.Core = CWC;
API.Utils = common_1.Utils;
API.sjcl = sjcl_1.default;
API.errors = Errors;
API.Bitcore = CWC.BitcoreLib;
API.BitcoreCash = CWC.BitcoreLibCash;
API.BitcoreDoge = CWC.BitcoreLibDoge;
API.BitcoreEdu = CWC.BitcoreLibEdu;
API.BitcoreTik = CWC.BitcoreLibTik;
API.privateKeyEncryptionOpts = {
iter: 10000
};
//# sourceMappingURL=api.js.map
| 79,742
| 23,318
|
module.exports = {
getWindowHeight: function () {
return window.innerHeight || window.clientHeight;
},
getWindowWidth: function () {
return window.innerWidth;
},
getPageHeight: function () {
return document.body.scrollHeight || document.documentElement.scrollHeight;
}
};
| 296
| 84
|
const BusinessSubscriptionPlanStatus = require('./BusinessSubscriptionPlanStatus');
const AnnouncementAccessibilityType = require('./AnnouncementAccessibilityType');
const DashboardNotificationCategory = require('./DashboardNotificationCategory');
const ReleaseNoteAccessibilityType = require('./ReleaseNoteAccessibilityType');
const BusinessVerificationStatus = require('./BusinessVerificationStatus');
const DashboardNotificationType = require('./DashboardNotificationType');
const AnnouncementFrequencyType = require('./AnnouncementFrequencyType');
const OrderProcessingFeeStatus = require('./OrderProcessingFeeStatus');
const BusinessVerificationType = require('./BusinessVerificationType');
const AnnouncementScheduleType = require('./AnnouncementScheduleType');
const OrderFeeTransactionType = require('./OrderFeeTransactionType');
const UserIntroductionStatus = require('./UserIntroductionStatus');
const OrderChargeAmountType = require('./OrderChargeAmountType');
const NotificationCategory = require('./NotificationCategory');
const SubscriptionPlanType = require('./SubscriptionPlanType');
const UserVerificationType = require('./UserVerificationType');
const ThreadConditionType = require('./ThreadConditionType');
const TicketRequestStatus = require('./TicketRequestStatus');
const AnnouncementStatus = require('./AnnouncementStatus');
const PaymentGatewayType = require('./PaymentGatewayType');
const InvoiceChargeState = require('./InvoiceChargeState');
const OrderPaymentStatus = require('./OrderPaymentStatus');
const IntroductionMethod = require('./IntroductionMethod');
const IntroductionStatus = require('./IntroductionStatus');
const ActivityGroupType = require('./ActivityGroupType');
const AnnouncementType = require('./AnnouncementType');
const MessageTopicType = require('./MessageTopicType');
const InterlocutorType = require('./InterlocutorType');
const MessageEventType = require('./MessageEventType');
const ActivityCategory = require('./ActivityCategory');
const NotificationType = require('./NotificationType');
const BusinessRoleType = require('./BusinessRoleType');
const StripeSourceType = require('./StripeSourceType');
const IntroductionStep = require('./IntroductionStep');
const OrderChargeType = require('./OrderChargeType');
const AdminPermission = require('./AdminPermission');
const AgreementStatus = require('./AgreementStatus');
const BusinessSubType = require('./BusinessSubType');
const PermissionType = require('./PermissionType');
const BusinessStatus = require('./BusinessStatus');
const AttachmentType = require('./AttachmentType');
const PaymentMethod = require('./PaymentMethod');
const MessageStatus = require('./MessageStatus');
const RequestStatus = require('./RequestStatus');
const UserTokenType = require('./UserTokenType');
const ConnectStatus = require('./ConnectStatus');
const FolderSubType = require('./FolderSubType');
const ProductStatus = require('./ProductStatus');
const AgreementType = require('./AgreementType');
const ReportSubType = require('./ReportSubType');
const ReferralType = require('./ReferralType');
const TicketStatus = require('./TicketStatus');
const LegalityType = require('./LegalityType');
const ActivityType = require('./ActivityType');
const BusinessType = require('./BusinessType');
const CurrencyType = require('./CurrencyType');
const ThreadStatus = require('./ThreadStatus');
const TimeZoneType = require('./TimeZoneType');
const ReportStatus = require('./ReportStatus');
const SellingType = require('./SellingType');
const AccountType = require('./AccountType');
const StoreStatus = require('./StoreStatus');
const AdminStatus = require('./AdminStatus');
const OrderStatus = require('./OrderStatus');
const ThreadType = require('./ThreadType');
const UserStatus = require('./UserStatus');
const FolderType = require('./FolderType');
const TicketType = require('./TicketType');
const ReportType = require('./ReportType');
const StoreType = require('./StoreType');
const AppStatus = require('./AppStatus');
const AdminRole = require('./AdminRole');
const EinState = require('./EinState');
const AppMode = require('./AppMode');
module.exports = {
BusinessSubscriptionPlanStatus,
AnnouncementAccessibilityType,
DashboardNotificationCategory,
ReleaseNoteAccessibilityType,
BusinessVerificationStatus,
DashboardNotificationType,
AnnouncementFrequencyType,
OrderProcessingFeeStatus,
BusinessVerificationType,
AnnouncementScheduleType,
OrderFeeTransactionType,
UserIntroductionStatus,
OrderChargeAmountType,
NotificationCategory,
SubscriptionPlanType,
UserVerificationType,
ThreadConditionType,
TicketRequestStatus,
AnnouncementStatus,
PaymentGatewayType,
InvoiceChargeState,
OrderPaymentStatus,
IntroductionMethod,
IntroductionStatus,
ActivityGroupType,
MessageTopicType,
InterlocutorType,
MessageEventType,
ActivityCategory,
NotificationType,
BusinessRoleType,
StripeSourceType,
IntroductionStep,
AnnouncementType,
OrderChargeType,
AdminPermission,
AgreementStatus,
BusinessSubType,
AttachmentType,
PermissionType,
BusinessStatus,
PaymentMethod,
MessageStatus,
RequestStatus,
UserTokenType,
ConnectStatus,
FolderSubType,
ProductStatus,
AgreementType,
ReportSubType,
TicketStatus,
ActivityType,
ReferralType,
LegalityType,
CurrencyType,
ThreadStatus,
BusinessType,
TimeZoneType,
ReportStatus,
SellingType,
AccountType,
StoreStatus,
AdminStatus,
OrderStatus,
ThreadType,
UserStatus,
FolderType,
TicketType,
ReportType,
StoreType,
AppStatus,
AdminRole,
EinState,
AppMode
};
| 5,755
| 1,477
|
// Reference: https://prettier.io/docs/en/options.html
module.exports = {
$schema: 'http://json.schemastore.org/prettierrc',
// Specify the line length that the printer will wrap on.
printWidth: 80,
// Specify the number of spaces per indentation-level.
tabWidth: 2,
// Indent lines with tabs instead of spaces.
useTabs: false,
// Print semicolons at the ends of statements.
semi: false,
// Use single quotes instead of double quotes.
singleQuote: true,
// Use single quotes instead of double quotes in JSX.
jsxSingleQuote: false,
// Change when properties in objects are quoted.
quoteProps: 'as-needed',
// Print trailing commas wherever possible when multi-line. (A single-line array, for example, never gets trailing commas.)
trailingComma: 'es5',
// Print spaces between brackets in object literals.
bracketSpacing: true,
// Put the > of a multi-line JSX element at the end of the last line instead of being alone on the next line
jsxBracketSameLine: false,
// Include parentheses around a sole arrow function parameter.
arrowParens: 'always'
}
| 1,106
| 336
|
/*
artifact generator: /wizzi/lib/artifacts/js/module/gen/main.js
primary source IttfDocument: c:\my\wizzi\v3\next\sources\webpacks\cssstyle\ittf\webpacks\cssstyle\src\containers\appcontainer.js.ittf
utc time: Wed, 19 Jul 2017 08:08:01 GMT
*/
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import sizeMe from 'react-sizeme';
import dhQuery from 'dom-helpers/query';
import App from '../components/App';
import StylesData from './StylesData';
class AppContainer extends React.Component {
state = {
selectedStyledId: null,
styledStyles: null,
metaPlay: null
};
componentWillMount() {
this.stylesData = new StylesData();
console.log('componentDidMount.this.stylesData', this.stylesData);
this.refreshStylesState(() => {
this.updateDimensions();
});
}
componentDidMount() {
window.addEventListener("resize", this.updateDimensions);
}
updateDimensions = () => {
this.setState({
...this.state,
width: dhQuery.width(window),
height: dhQuery.height(window)
})
}
handleStyledChange = (id, value) => {
console.log('handleStyledChange', arguments);
this.stylesData.selectStyled(value);
this.refreshStylesState();
}
handleStyleChange = (id, values) => {
this.stylesData.updateStyles(values);
this.refreshStylesState();
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
refreshStylesState(callback) {
console.log('refreshStylesState.stylesData', this.stylesData);
this.setState({
...this.state,
selectedStyledId: this.stylesData.selectedStyledId,
styledStyles: this.stylesData.styledStyles,
metaPlay: this.stylesData.metaPlay
}, () => {
console.log('refreshStylesState', this.state);
if (callback) {
callback();
}
});
}
render() {
const {
width,
height
} = this.props;
console.log('render.state', this.state);
const { metaPlay, styledStyles } = this.state;
const { styledMeta } = this.stylesData;
const styledIds = this.stylesData.maps.styledIds || [];
return (
<div>
<App selectedStyledId={this.state.selectedStyledId} styledIds={styledIds} onStyledChange={this.handleStyledChange} metaForm={metaPlay} onStyleChange={this.handleStyleChange} styledMeta={styledMeta} styledStyles={styledStyles}>
</App>
<div>
App size: {width}px x {height}px
</div>
<div>
Window size: {this.state.width}px x {this.state.height}px
</div>
</div>
)
;
}
}
const mapDispatchToProps = (dispatch) => {
return {};
};
const mapStateToProps = (state) => {
return {};
};
const mergeProps = (stateProps, dispatchProps, ownProps) => {
console.log('DocumentEditor.mergeProps.stateProps', stateProps);
console.log('DocumentEditor.mergeProps.dispatchProps', dispatchProps);
console.log('DocumentEditor.mergeProps.ownProps', ownProps);
return Object.assign({}, ownProps, stateProps, dispatchProps, {})
;
};
const AppContainerConnected = connect(mapStateToProps, mapDispatchToProps, mergeProps)(AppContainer)
;
export default sizeMe({
monitorHeight: true,
monitorPosition: true
})(AppContainerConnected)
;
| 3,754
| 1,091
|
module.exports.pointToPixel = function(fontSize, dpi){
dpi = dpi || dpi === 0 ? dpi : 96;
fontSize = fontSize * dpi / 72;
return Math.round(fontSize);
};
module.exports.getPxScale = function(font, fontSize) {
if(font.bitmap)
return 1.0;
fontSize = typeof fontSize === "number" ? fontSize : this.pointToPixel(font.size);
var sz = font.units_per_EM/64;
sz = (sz/font.size * fontSize);
//var val = ( 1 / 64/ font.size * fontSize ) ;
return ((font.resolution * 1/72 * sz) / font.units_per_EM);
};
module.exports.getDistance = function(pt1, pt2){
var dx = pt1.x - pt2.x;
var dy = pt1.y - pt2.y;
var dis = Math.sqrt( dx * dx + dy * dy );
return dis;
}
| 717
| 291
|
(function(exports){
crossfilter.version = "1.3.7";
function crossfilter_identity(d) {
return d;
}
crossfilter.permute = permute;
function permute(array, index) {
for (var i = 0, n = index.length, copy = new Array(n); i < n; ++i) {
copy[i] = array[index[i]];
}
return copy;
}
var bisect = crossfilter.bisect = bisect_by(crossfilter_identity);
bisect.by = bisect_by;
function bisect_by(f) {
// Locate the insertion point for x in a to maintain sorted order. The
// arguments lo and hi may be used to specify a subset of the array which
// should be considered; by default the entire array is used. If x is already
// present in a, the insertion point will be before (to the left of) any
// existing entries. The return value is suitable for use as the first
// argument to `array.splice` assuming that a is already sorted.
//
// The returned insertion point i partitions the array a into two halves so
// that all v < x for v in a[lo:i] for the left side and all v >= x for v in
// a[i:hi] for the right side.
function bisectLeft(a, x, lo, hi) {
while (lo < hi) {
var mid = lo + hi >>> 1;
if (f(a[mid]) < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
// Similar to bisectLeft, but returns an insertion point which comes after (to
// the right of) any existing entries of x in a.
//
// The returned insertion point i partitions the array into two halves so that
// all v <= x for v in a[lo:i] for the left side and all v > x for v in
// a[i:hi] for the right side.
function bisectRight(a, x, lo, hi) {
while (lo < hi) {
var mid = lo + hi >>> 1;
if (x < f(a[mid])) hi = mid;
else lo = mid + 1;
}
return lo;
}
bisectRight.right = bisectRight;
bisectRight.left = bisectLeft;
return bisectRight;
}
var heap = crossfilter.heap = heap_by(crossfilter_identity);
heap.by = heap_by;
function heap_by(f) {
// Builds a binary heap within the specified array a[lo:hi]. The heap has the
// property such that the parent a[lo+i] is always less than or equal to its
// two children: a[lo+2*i+1] and a[lo+2*i+2].
function heap(a, lo, hi) {
var n = hi - lo,
i = (n >>> 1) + 1;
while (--i > 0) sift(a, i, n, lo);
return a;
}
// Sorts the specified array a[lo:hi] in descending order, assuming it is
// already a heap.
function sort(a, lo, hi) {
var n = hi - lo,
t;
while (--n > 0) t = a[lo], a[lo] = a[lo + n], a[lo + n] = t, sift(a, 1, n, lo);
return a;
}
// Sifts the element a[lo+i-1] down the heap, where the heap is the contiguous
// slice of array a[lo:lo+n]. This method can also be used to update the heap
// incrementally, without incurring the full cost of reconstructing the heap.
function sift(a, i, n, lo) {
var d = a[--lo + i],
x = f(d),
child;
while ((child = i << 1) <= n) {
if (child < n && f(a[lo + child]) > f(a[lo + child + 1])) child++;
if (x <= f(a[lo + child])) break;
a[lo + i] = a[lo + child];
i = child;
}
a[lo + i] = d;
}
heap.sort = sort;
return heap;
}
var heapselect = crossfilter.heapselect = heapselect_by(crossfilter_identity);
heapselect.by = heapselect_by;
function heapselect_by(f) {
var heap = heap_by(f);
// Returns a new array containing the top k elements in the array a[lo:hi].
// The returned array is not sorted, but maintains the heap property. If k is
// greater than hi - lo, then fewer than k elements will be returned. The
// order of elements in a is unchanged by this operation.
function heapselect(a, lo, hi, k) {
var queue = new Array(k = Math.min(hi - lo, k)),
min,
i,
x,
d;
for (i = 0; i < k; ++i) queue[i] = a[lo++];
heap(queue, 0, k);
if (lo < hi) {
min = f(queue[0]);
do {
if (x = f(d = a[lo]) > min) {
queue[0] = d;
min = f(heap(queue, 0, k)[0]);
}
} while (++lo < hi);
}
return queue;
}
return heapselect;
}
var insertionsort = crossfilter.insertionsort = insertionsort_by(crossfilter_identity);
insertionsort.by = insertionsort_by;
function insertionsort_by(f) {
function insertionsort(a, lo, hi) {
for (var i = lo + 1; i < hi; ++i) {
for (var j = i, t = a[i], x = f(t); j > lo && f(a[j - 1]) > x; --j) {
a[j] = a[j - 1];
}
a[j] = t;
}
return a;
}
return insertionsort;
}
// Algorithm designed by Vladimir Yaroslavskiy.
// Implementation based on the Dart project; see lib/dart/LICENSE for details.
var quicksort = crossfilter.quicksort = quicksort_by(crossfilter_identity);
quicksort.by = quicksort_by;
function quicksort_by(f) {
var insertionsort = insertionsort_by(f);
function sort(a, lo, hi) {
return (hi - lo < quicksort_sizeThreshold
? insertionsort
: quicksort)(a, lo, hi);
}
function quicksort(a, lo, hi) {
// Compute the two pivots by looking at 5 elements.
var sixth = (hi - lo) / 6 | 0,
i1 = lo + sixth,
i5 = hi - 1 - sixth,
i3 = lo + hi - 1 >> 1, // The midpoint.
i2 = i3 - sixth,
i4 = i3 + sixth;
var e1 = a[i1], x1 = f(e1),
e2 = a[i2], x2 = f(e2),
e3 = a[i3], x3 = f(e3),
e4 = a[i4], x4 = f(e4),
e5 = a[i5], x5 = f(e5);
var t;
// Sort the selected 5 elements using a sorting network.
if (x1 > x2) t = e1, e1 = e2, e2 = t, t = x1, x1 = x2, x2 = t;
if (x4 > x5) t = e4, e4 = e5, e5 = t, t = x4, x4 = x5, x5 = t;
if (x1 > x3) t = e1, e1 = e3, e3 = t, t = x1, x1 = x3, x3 = t;
if (x2 > x3) t = e2, e2 = e3, e3 = t, t = x2, x2 = x3, x3 = t;
if (x1 > x4) t = e1, e1 = e4, e4 = t, t = x1, x1 = x4, x4 = t;
if (x3 > x4) t = e3, e3 = e4, e4 = t, t = x3, x3 = x4, x4 = t;
if (x2 > x5) t = e2, e2 = e5, e5 = t, t = x2, x2 = x5, x5 = t;
if (x2 > x3) t = e2, e2 = e3, e3 = t, t = x2, x2 = x3, x3 = t;
if (x4 > x5) t = e4, e4 = e5, e5 = t, t = x4, x4 = x5, x5 = t;
var pivot1 = e2, pivotValue1 = x2,
pivot2 = e4, pivotValue2 = x4;
// e2 and e4 have been saved in the pivot variables. They will be written
// back, once the partitioning is finished.
a[i1] = e1;
a[i2] = a[lo];
a[i3] = e3;
a[i4] = a[hi - 1];
a[i5] = e5;
var less = lo + 1, // First element in the middle partition.
great = hi - 2; // Last element in the middle partition.
// Note that for value comparison, <, <=, >= and > coerce to a primitive via
// Object.prototype.valueOf; == and === do not, so in order to be consistent
// with natural order (such as for Date objects), we must do two compares.
var pivotsEqual = pivotValue1 <= pivotValue2 && pivotValue1 >= pivotValue2;
if (pivotsEqual) {
// Degenerated case where the partitioning becomes a dutch national flag
// problem.
//
// [ | < pivot | == pivot | unpartitioned | > pivot | ]
// ^ ^ ^ ^ ^
// left less k great right
//
// a[left] and a[right] are undefined and are filled after the
// partitioning.
//
// Invariants:
// 1) for x in ]left, less[ : x < pivot.
// 2) for x in [less, k[ : x == pivot.
// 3) for x in ]great, right[ : x > pivot.
for (var k = less; k <= great; ++k) {
var ek = a[k], xk = f(ek);
if (xk < pivotValue1) {
if (k !== less) {
a[k] = a[less];
a[less] = ek;
}
++less;
} else if (xk > pivotValue1) {
// Find the first element <= pivot in the range [k - 1, great] and
// put [:ek:] there. We know that such an element must exist:
// When k == less, then el3 (which is equal to pivot) lies in the
// interval. Otherwise a[k - 1] == pivot and the search stops at k-1.
// Note that in the latter case invariant 2 will be violated for a
// short amount of time. The invariant will be restored when the
// pivots are put into their final positions.
while (true) {
var greatValue = f(a[great]);
if (greatValue > pivotValue1) {
great--;
// This is the only location in the while-loop where a new
// iteration is started.
continue;
} else if (greatValue < pivotValue1) {
// Triple exchange.
a[k] = a[less];
a[less++] = a[great];
a[great--] = ek;
break;
} else {
a[k] = a[great];
a[great--] = ek;
// Note: if great < k then we will exit the outer loop and fix
// invariant 2 (which we just violated).
break;
}
}
}
}
} else {
// We partition the list into three parts:
// 1. < pivot1
// 2. >= pivot1 && <= pivot2
// 3. > pivot2
//
// During the loop we have:
// [ | < pivot1 | >= pivot1 && <= pivot2 | unpartitioned | > pivot2 | ]
// ^ ^ ^ ^ ^
// left less k great right
//
// a[left] and a[right] are undefined and are filled after the
// partitioning.
//
// Invariants:
// 1. for x in ]left, less[ : x < pivot1
// 2. for x in [less, k[ : pivot1 <= x && x <= pivot2
// 3. for x in ]great, right[ : x > pivot2
for (var k = less; k <= great; k++) {
var ek = a[k], xk = f(ek);
if (xk < pivotValue1) {
if (k !== less) {
a[k] = a[less];
a[less] = ek;
}
++less;
} else {
if (xk > pivotValue2) {
while (true) {
var greatValue = f(a[great]);
if (greatValue > pivotValue2) {
great--;
if (great < k) break;
// This is the only location inside the loop where a new
// iteration is started.
continue;
} else {
// a[great] <= pivot2.
if (greatValue < pivotValue1) {
// Triple exchange.
a[k] = a[less];
a[less++] = a[great];
a[great--] = ek;
} else {
// a[great] >= pivot1.
a[k] = a[great];
a[great--] = ek;
}
break;
}
}
}
}
}
}
// Move pivots into their final positions.
// We shrunk the list from both sides (a[left] and a[right] have
// meaningless values in them) and now we move elements from the first
// and third partition into these locations so that we can store the
// pivots.
a[lo] = a[less - 1];
a[less - 1] = pivot1;
a[hi - 1] = a[great + 1];
a[great + 1] = pivot2;
// The list is now partitioned into three partitions:
// [ < pivot1 | >= pivot1 && <= pivot2 | > pivot2 ]
// ^ ^ ^ ^
// left less great right
// Recursive descent. (Don't include the pivot values.)
sort(a, lo, less - 1);
sort(a, great + 2, hi);
if (pivotsEqual) {
// All elements in the second partition are equal to the pivot. No
// need to sort them.
return a;
}
// In theory it should be enough to call _doSort recursively on the second
// partition.
// The Android source however removes the pivot elements from the recursive
// call if the second partition is too large (more than 2/3 of the list).
if (less < i1 && great > i5) {
var lessValue, greatValue;
while ((lessValue = f(a[less])) <= pivotValue1 && lessValue >= pivotValue1) ++less;
while ((greatValue = f(a[great])) <= pivotValue2 && greatValue >= pivotValue2) --great;
// Copy paste of the previous 3-way partitioning with adaptions.
//
// We partition the list into three parts:
// 1. == pivot1
// 2. > pivot1 && < pivot2
// 3. == pivot2
//
// During the loop we have:
// [ == pivot1 | > pivot1 && < pivot2 | unpartitioned | == pivot2 ]
// ^ ^ ^
// less k great
//
// Invariants:
// 1. for x in [ *, less[ : x == pivot1
// 2. for x in [less, k[ : pivot1 < x && x < pivot2
// 3. for x in ]great, * ] : x == pivot2
for (var k = less; k <= great; k++) {
var ek = a[k], xk = f(ek);
if (xk <= pivotValue1 && xk >= pivotValue1) {
if (k !== less) {
a[k] = a[less];
a[less] = ek;
}
less++;
} else {
if (xk <= pivotValue2 && xk >= pivotValue2) {
while (true) {
var greatValue = f(a[great]);
if (greatValue <= pivotValue2 && greatValue >= pivotValue2) {
great--;
if (great < k) break;
// This is the only location inside the loop where a new
// iteration is started.
continue;
} else {
// a[great] < pivot2.
if (greatValue < pivotValue1) {
// Triple exchange.
a[k] = a[less];
a[less++] = a[great];
a[great--] = ek;
} else {
// a[great] == pivot1.
a[k] = a[great];
a[great--] = ek;
}
break;
}
}
}
}
}
}
// The second partition has now been cleared of pivot elements and looks
// as follows:
// [ * | > pivot1 && < pivot2 | * ]
// ^ ^
// less great
// Sort the second partition using recursive descent.
// The second partition looks as follows:
// [ * | >= pivot1 && <= pivot2 | * ]
// ^ ^
// less great
// Simply sort it by recursive descent.
return sort(a, less, great + 1);
}
return sort;
}
var quicksort_sizeThreshold = 64;
var crossfilter_array8 = crossfilter_arrayUntyped,
crossfilter_array16 = crossfilter_arrayUntyped,
crossfilter_array64 = crossfilter_arrayUntyped,
crossfilter_arrayLengthen = crossfilter_arrayLengthenUntyped,
crossfilter_arrayWiden = crossfilter_arrayWidenUntyped;
if (typeof Uint8Array !== "undefined") {
crossfilter_array8 = function(n) { return new Uint8Array(n); };
crossfilter_array16 = function(n) { return new Uint16Array(n); };
crossfilter_array64 = function(n) { return new Uint64Array(n); };
crossfilter_arrayLengthen = function(array, length) {
if (array.length >= length) return array;
var copy = new array.constructor(length);
copy.set(array);
return copy;
};
crossfilter_arrayWiden = function(array, width) {
var copy;
switch (width) {
case 16: copy = crossfilter_array16(array.length); break;
case 64: copy = crossfilter_array64(array.length); break;
default: throw new Error("invalid array width!");
}
copy.set(array);
return copy;
};
}
function crossfilter_arrayUntyped(n) {
var array = new Array(n), i = -1;
while (++i < n) array[i] = 0;
return array;
}
function crossfilter_arrayLengthenUntyped(array, length) {
var n = array.length;
while (n < length) array[n++] = 0;
return array;
}
function crossfilter_arrayWidenUntyped(array, width) {
if (width > 64) throw new Error("invalid array width!");
return array;
}
function crossfilter_filterExact(bisect, value) {
return function(values) {
var n = values.length;
return [bisect.left(values, value, 0, n), bisect.right(values, value, 0, n)];
};
}
function crossfilter_filterRange(bisect, range) {
var min = range[0],
max = range[1];
return function(values) {
var n = values.length;
return [bisect.left(values, min, 0, n), bisect.left(values, max, 0, n)];
};
}
function crossfilter_filterAll(values) {
return [0, values.length];
}
function crossfilter_null() {
return null;
}
function crossfilter_zero() {
return 0;
}
function crossfilter_reduceIncrement(p) {
return p + 1;
}
function crossfilter_reduceDecrement(p) {
return p - 1;
}
function crossfilter_reduceAdd(f) {
return function(p, v) {
return p + +f(v);
};
}
function crossfilter_reduceSubtract(f) {
return function(p, v) {
return p - f(v);
};
}
exports.crossfilter = crossfilter;
function crossfilter() {
var crossfilter = {
add: add,
remove: removeData,
dimension: dimension,
groupAll: groupAll,
size: size
};
var data = [], // the records
n = 0, // the number of records; data.length
m = 0, // a bit mask representing which dimensions are in use
M = 8, // number of dimensions that can fit in `filters`
filters = crossfilter_array8(0), // M bits per record; 1 is filtered out
filterListeners = [], // when the filters change
dataListeners = [], // when data is added
removeDataListeners = []; // when data is removed
// Adds the specified new records to this crossfilter.
function add(newData) {
var n0 = n,
n1 = newData.length;
// If there's actually new data to add…
// Merge the new data into the existing data.
// Lengthen the filter bitset to handle the new records.
// Notify listeners (dimensions and groups) that new data is available.
if (n1) {
data = data.concat(newData);
filters = crossfilter_arrayLengthen(filters, n += n1);
dataListeners.forEach(function(l) { l(newData, n0, n1); });
}
return crossfilter;
}
// Removes all records that match the current filters.
function removeData() {
var newIndex = crossfilter_index(n, n),
removed = [];
for (var i = 0, j = 0; i < n; ++i) {
if (filters[i]) newIndex[i] = j++;
else removed.push(i);
}
// Remove all matching records from groups.
filterListeners.forEach(function(l) { l(0, [], removed); });
// Update indexes.
removeDataListeners.forEach(function(l) { l(newIndex); });
// Remove old filters and data by overwriting.
for (var i = 0, j = 0, k; i < n; ++i) {
if (k = filters[i]) {
if (i !== j) filters[j] = k, data[j] = data[i];
++j;
}
}
data.length = j;
while (n > j) filters[--n] = 0;
}
// Adds a new dimension with the specified value accessor function.
function dimension(value) {
var dimension = {
filter: filter,
filterExact: filterExact,
filterRange: filterRange,
filterFunction: filterFunction,
filterAll: filterAll,
top: top,
bottom: bottom,
group: group,
groupAll: groupAll,
dispose: dispose,
remove: dispose // for backwards-compatibility
};
var one = ~m & -~m, // lowest unset bit as mask, e.g., 00001000
zero = ~one, // inverted one, e.g., 11110111
values, // sorted, cached array
index, // value rank ↦ object id
newValues, // temporary array storing newly-added values
newIndex, // temporary array storing newly-added index
sort = quicksort_by(function(i) { return newValues[i]; }),
refilter = crossfilter_filterAll, // for recomputing filter
refilterFunction, // the custom filter function in use
indexListeners = [], // when data is added
dimensionGroups = [],
lo0 = 0,
hi0 = 0;
// Updating a dimension is a two-stage process. First, we must update the
// associated filters for the newly-added records. Once all dimensions have
// updated their filters, the groups are notified to update.
dataListeners.unshift(preAdd);
dataListeners.push(postAdd);
removeDataListeners.push(removeData);
// Incorporate any existing data into this dimension, and make sure that the
// filter bitset is wide enough to handle the new dimension.
m |= one;
if (M >= 64 ? !one : m & (1 << M) - 1) {
filters = crossfilter_arrayWiden(filters, M <<= 1);
}
preAdd(data, 0, n);
postAdd(data, 0, n);
// Incorporates the specified new records into this dimension.
// This function is responsible for updating filters, values, and index.
function preAdd(newData, n0, n1) {
// Permute new values into natural order using a sorted index.
newValues = newData.map(value);
newIndex = sort(crossfilter_range(n1), 0, n1);
newValues = permute(newValues, newIndex);
// Bisect newValues to determine which new records are selected.
var bounds = refilter(newValues), lo1 = bounds[0], hi1 = bounds[1], i;
if (refilterFunction) {
for (i = 0; i < n1; ++i) {
if (!refilterFunction(newValues[i], i)) filters[newIndex[i] + n0] |= one;
}
} else {
for (i = 0; i < lo1; ++i) filters[newIndex[i] + n0] |= one;
for (i = hi1; i < n1; ++i) filters[newIndex[i] + n0] |= one;
}
// If this dimension previously had no data, then we don't need to do the
// more expensive merge operation; use the new values and index as-is.
if (!n0) {
values = newValues;
index = newIndex;
lo0 = lo1;
hi0 = hi1;
return;
}
var oldValues = values,
oldIndex = index,
i0 = 0,
i1 = 0;
// Otherwise, create new arrays into which to merge new and old.
values = new Array(n);
index = crossfilter_index(n, n);
// Merge the old and new sorted values, and old and new index.
for (i = 0; i0 < n0 && i1 < n1; ++i) {
if (oldValues[i0] < newValues[i1]) {
values[i] = oldValues[i0];
index[i] = oldIndex[i0++];
} else {
values[i] = newValues[i1];
index[i] = newIndex[i1++] + n0;
}
}
// Add any remaining old values.
for (; i0 < n0; ++i0, ++i) {
values[i] = oldValues[i0];
index[i] = oldIndex[i0];
}
// Add any remaining new values.
for (; i1 < n1; ++i1, ++i) {
values[i] = newValues[i1];
index[i] = newIndex[i1] + n0;
}
// Bisect again to recompute lo0 and hi0.
bounds = refilter(values), lo0 = bounds[0], hi0 = bounds[1];
}
// When all filters have updated, notify index listeners of the new values.
function postAdd(newData, n0, n1) {
indexListeners.forEach(function(l) { l(newValues, newIndex, n0, n1); });
newValues = newIndex = null;
}
function removeData(reIndex) {
for (var i = 0, j = 0, k; i < n; ++i) {
if (filters[k = index[i]]) {
if (i !== j) values[j] = values[i];
index[j] = reIndex[k];
++j;
}
}
values.length = j;
while (j < n) index[j++] = 0;
// Bisect again to recompute lo0 and hi0.
var bounds = refilter(values);
lo0 = bounds[0], hi0 = bounds[1];
}
// Updates the selected values based on the specified bounds [lo, hi].
// This implementation is used by all the public filter methods.
function filterIndexBounds(bounds) {
var lo1 = bounds[0],
hi1 = bounds[1];
if (refilterFunction) {
refilterFunction = null;
filterIndexFunction(function(d, i) { return lo1 <= i && i < hi1; });
lo0 = lo1;
hi0 = hi1;
return dimension;
}
var i,
j,
k,
added = [],
removed = [];
// Fast incremental update based on previous lo index.
if (lo1 < lo0) {
for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) {
filters[k = index[i]] ^= one;
added.push(k);
}
} else if (lo1 > lo0) {
for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) {
filters[k = index[i]] ^= one;
removed.push(k);
}
}
// Fast incremental update based on previous hi index.
if (hi1 > hi0) {
for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) {
filters[k = index[i]] ^= one;
added.push(k);
}
} else if (hi1 < hi0) {
for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) {
filters[k = index[i]] ^= one;
removed.push(k);
}
}
lo0 = lo1;
hi0 = hi1;
filterListeners.forEach(function(l) { l(one, added, removed); });
return dimension;
}
// Filters this dimension using the specified range, value, or null.
// If the range is null, this is equivalent to filterAll.
// If the range is an array, this is equivalent to filterRange.
// Otherwise, this is equivalent to filterExact.
function filter(range) {
return range == null
? filterAll() : Array.isArray(range)
? filterRange(range) : typeof range === "function"
? filterFunction(range)
: filterExact(range);
}
// Filters this dimension to select the exact value.
function filterExact(value) {
return filterIndexBounds((refilter = crossfilter_filterExact(bisect, value))(values));
}
// Filters this dimension to select the specified range [lo, hi].
// The lower bound is inclusive, and the upper bound is exclusive.
function filterRange(range) {
return filterIndexBounds((refilter = crossfilter_filterRange(bisect, range))(values));
}
// Clears any filters on this dimension.
function filterAll() {
return filterIndexBounds((refilter = crossfilter_filterAll)(values));
}
// Filters this dimension using an arbitrary function.
function filterFunction(f) {
refilter = crossfilter_filterAll;
filterIndexFunction(refilterFunction = f);
lo0 = 0;
hi0 = n;
return dimension;
}
function filterIndexFunction(f) {
var i,
k,
x,
added = [],
removed = [];
for (i = 0; i < n; ++i) {
if (!(filters[k = index[i]] & one) ^ (x = f(values[i], i))) {
if (x) filters[k] &= zero, added.push(k);
else filters[k] |= one, removed.push(k);
}
}
filterListeners.forEach(function(l) { l(one, added, removed); });
}
// Returns the top K selected records based on this dimension's order.
// Note: observes this dimension's filter, unlike group and groupAll.
function top(k) {
var array = [],
i = hi0,
j;
while (--i >= lo0 && k > 0) {
if (!filters[j = index[i]]) {
array.push(data[j]);
--k;
}
}
return array;
}
// Returns the bottom K selected records based on this dimension's order.
// Note: observes this dimension's filter, unlike group and groupAll.
function bottom(k) {
var array = [],
i = lo0,
j;
while (i < hi0 && k > 0) {
if (!filters[j = index[i]]) {
array.push(data[j]);
--k;
}
i++;
}
return array;
}
// Adds a new group to this dimension, using the specified key function.
function group(key) {
var group = {
top: top,
all: all,
reduce: reduce,
reduceCount: reduceCount,
reduceSum: reduceSum,
order: order,
orderNatural: orderNatural,
size: size,
dispose: dispose,
remove: dispose // for backwards-compatibility
};
// Ensure that this group will be removed when the dimension is removed.
dimensionGroups.push(group);
var groups, // array of {key, value}
groupIndex, // object id ↦ group id
groupWidth = 8,
groupCapacity = crossfilter_capacity(groupWidth),
k = 0, // cardinality
select,
heap,
reduceAdd,
reduceRemove,
reduceInitial,
update = crossfilter_null,
reset = crossfilter_null,
resetNeeded = true;
if (arguments.length < 1) key = crossfilter_identity;
// The group listens to the crossfilter for when any dimension changes, so
// that it can update the associated reduce values. It must also listen to
// the parent dimension for when data is added, and compute new keys.
filterListeners.push(update);
indexListeners.push(add);
removeDataListeners.push(removeData);
// Incorporate any existing data into the grouping.
add(values, index, 0, n);
// Incorporates the specified new values into this group.
// This function is responsible for updating groups and groupIndex.
function add(newValues, newIndex, n0, n1) {
var oldGroups = groups,
reIndex = crossfilter_index(k, groupCapacity),
add = reduceAdd,
initial = reduceInitial,
k0 = k, // old cardinality
i0 = 0, // index of old group
i1 = 0, // index of new record
j, // object id
g0, // old group
x0, // old key
x1, // new key
g, // group to add
x; // key of group to add
// If a reset is needed, we don't need to update the reduce values.
if (resetNeeded) add = initial = crossfilter_null;
// Reset the new groups (k is a lower bound).
// Also, make sure that groupIndex exists and is long enough.
groups = new Array(k), k = 0;
groupIndex = k0 > 1 ? crossfilter_arrayLengthen(groupIndex, n) : crossfilter_index(n, groupCapacity);
// Get the first old key (x0 of g0), if it exists.
if (k0) x0 = (g0 = oldGroups[0]).key;
// Find the first new key (x1), skipping NaN keys.
while (i1 < n1 && !((x1 = key(newValues[i1])) >= x1)) ++i1;
// While new keys remain…
while (i1 < n1) {
// Determine the lesser of the two current keys; new and old.
// If there are no old keys remaining, then always add the new key.
if (g0 && x0 <= x1) {
g = g0, x = x0;
// Record the new index of the old group.
reIndex[i0] = k;
// Retrieve the next old key.
if (g0 = oldGroups[++i0]) x0 = g0.key;
} else {
g = {key: x1, value: initial()}, x = x1;
}
// Add the lesser group.
groups[k] = g;
// Add any selected records belonging to the added group, while
// advancing the new key and populating the associated group index.
while (!(x1 > x)) {
groupIndex[j = newIndex[i1] + n0] = k;
if (!(filters[j] & zero)) g.value = add(g.value, data[j]);
if (++i1 >= n1) break;
x1 = key(newValues[i1]);
}
groupIncrement();
}
// Add any remaining old groups that were greater than all new keys.
// No incremental reduce is needed; these groups have no new records.
// Also record the new index of the old group.
while (i0 < k0) {
groups[reIndex[i0] = k] = oldGroups[i0++];
groupIncrement();
}
// If we added any new groups before any old groups,
// update the group index of all the old records.
if (k > i0) for (i0 = 0; i0 < n0; ++i0) {
groupIndex[i0] = reIndex[groupIndex[i0]];
}
// Modify the update and reset behavior based on the cardinality.
// If the cardinality is less than or equal to one, then the groupIndex
// is not needed. If the cardinality is zero, then there are no records
// and therefore no groups to update or reset. Note that we also must
// change the registered listener to point to the new method.
j = filterListeners.indexOf(update);
if (k > 1) {
update = updateMany;
reset = resetMany;
} else {
if (k === 1) {
update = updateOne;
reset = resetOne;
} else {
update = crossfilter_null;
reset = crossfilter_null;
}
groupIndex = null;
}
filterListeners[j] = update;
// Count the number of added groups,
// and widen the group index as needed.
function groupIncrement() {
if (++k === groupCapacity) {
reIndex = crossfilter_arrayWiden(reIndex, groupWidth <<= 1);
groupIndex = crossfilter_arrayWiden(groupIndex, groupWidth);
groupCapacity = crossfilter_capacity(groupWidth);
}
}
}
function removeData() {
if (k > 1) {
var oldK = k,
oldGroups = groups,
seenGroups = crossfilter_index(oldK, oldK);
// Filter out non-matches by copying matching group index entries to
// the beginning of the array.
for (var i = 0, j = 0; i < n; ++i) {
if (filters[i]) {
seenGroups[groupIndex[j] = groupIndex[i]] = 1;
++j;
}
}
// Reassemble groups including only those groups that were referred
// to by matching group index entries. Note the new group index in
// seenGroups.
groups = [], k = 0;
for (i = 0; i < oldK; ++i) {
if (seenGroups[i]) {
seenGroups[i] = k++;
groups.push(oldGroups[i]);
}
}
if (k > 1) {
// Reindex the group index using seenGroups to find the new index.
for (var i = 0; i < j; ++i) groupIndex[i] = seenGroups[groupIndex[i]];
} else {
groupIndex = null;
}
filterListeners[filterListeners.indexOf(update)] = k > 1
? (reset = resetMany, update = updateMany)
: k === 1 ? (reset = resetOne, update = updateOne)
: reset = update = crossfilter_null;
} else if (k === 1) {
for (var i = 0; i < n; ++i) if (filters[i]) return;
groups = [], k = 0;
filterListeners[filterListeners.indexOf(update)] =
update = reset = crossfilter_null;
}
}
// Reduces the specified selected or deselected records.
// This function is only used when the cardinality is greater than 1.
function updateMany(filterOne, added, removed) {
if (filterOne === one || resetNeeded) return;
var i,
k,
n,
g;
// Add the added values.
for (i = 0, n = added.length; i < n; ++i) {
if (!(filters[k = added[i]] & zero)) {
g = groups[groupIndex[k]];
g.value = reduceAdd(g.value, data[k]);
}
}
// Remove the removed values.
for (i = 0, n = removed.length; i < n; ++i) {
if ((filters[k = removed[i]] & zero) === filterOne) {
g = groups[groupIndex[k]];
g.value = reduceRemove(g.value, data[k]);
}
}
}
// Reduces the specified selected or deselected records.
// This function is only used when the cardinality is 1.
function updateOne(filterOne, added, removed) {
if (filterOne === one || resetNeeded) return;
var i,
k,
n,
g = groups[0];
// Add the added values.
for (i = 0, n = added.length; i < n; ++i) {
if (!(filters[k = added[i]] & zero)) {
g.value = reduceAdd(g.value, data[k]);
}
}
// Remove the removed values.
for (i = 0, n = removed.length; i < n; ++i) {
if ((filters[k = removed[i]] & zero) === filterOne) {
g.value = reduceRemove(g.value, data[k]);
}
}
}
// Recomputes the group reduce values from scratch.
// This function is only used when the cardinality is greater than 1.
function resetMany() {
var i,
g;
// Reset all group values.
for (i = 0; i < k; ++i) {
groups[i].value = reduceInitial();
}
// Add any selected records.
for (i = 0; i < n; ++i) {
if (!(filters[i] & zero)) {
g = groups[groupIndex[i]];
g.value = reduceAdd(g.value, data[i]);
}
}
}
// Recomputes the group reduce values from scratch.
// This function is only used when the cardinality is 1.
function resetOne() {
var i,
g = groups[0];
// Reset the singleton group values.
g.value = reduceInitial();
// Add any selected records.
for (i = 0; i < n; ++i) {
if (!(filters[i] & zero)) {
g.value = reduceAdd(g.value, data[i]);
}
}
}
// Returns the array of group values, in the dimension's natural order.
function all() {
if (resetNeeded) reset(), resetNeeded = false;
return groups;
}
// Returns a new array containing the top K group values, in reduce order.
function top(k) {
var top = select(all(), 0, groups.length, k);
return heap.sort(top, 0, top.length);
}
// Sets the reduce behavior for this group to use the specified functions.
// This method lazily recomputes the reduce values, waiting until needed.
function reduce(add, remove, initial) {
reduceAdd = add;
reduceRemove = remove;
reduceInitial = initial;
resetNeeded = true;
return group;
}
// A convenience method for reducing by count.
function reduceCount() {
return reduce(crossfilter_reduceIncrement, crossfilter_reduceDecrement, crossfilter_zero);
}
// A convenience method for reducing by sum(value).
function reduceSum(value) {
return reduce(crossfilter_reduceAdd(value), crossfilter_reduceSubtract(value), crossfilter_zero);
}
// Sets the reduce order, using the specified accessor.
function order(value) {
select = heapselect_by(valueOf);
heap = heap_by(valueOf);
function valueOf(d) { return value(d.value); }
return group;
}
// A convenience method for natural ordering by reduce value.
function orderNatural() {
return order(crossfilter_identity);
}
// Returns the cardinality of this group, irrespective of any filters.
function size() {
return k;
}
// Removes this group and associated event listeners.
function dispose() {
var i = filterListeners.indexOf(update);
if (i >= 0) filterListeners.splice(i, 1);
i = indexListeners.indexOf(add);
if (i >= 0) indexListeners.splice(i, 1);
i = removeDataListeners.indexOf(removeData);
if (i >= 0) removeDataListeners.splice(i, 1);
return group;
}
return reduceCount().orderNatural();
}
// A convenience function for generating a singleton group.
function groupAll() {
var g = group(crossfilter_null), all = g.all;
delete g.all;
delete g.top;
delete g.order;
delete g.orderNatural;
delete g.size;
g.value = function() { return all()[0].value; };
return g;
}
// Removes this dimension and associated groups and event listeners.
function dispose() {
dimensionGroups.forEach(function(group) { group.dispose(); });
var i = dataListeners.indexOf(preAdd);
if (i >= 0) dataListeners.splice(i, 1);
i = dataListeners.indexOf(postAdd);
if (i >= 0) dataListeners.splice(i, 1);
i = removeDataListeners.indexOf(removeData);
if (i >= 0) removeDataListeners.splice(i, 1);
for (i = 0; i < n; ++i) filters[i] &= zero;
m &= zero;
return dimension;
}
return dimension;
}
// A convenience method for groupAll on a dummy dimension.
// This implementation can be optimized since it always has cardinality 1.
function groupAll() {
var group = {
reduce: reduce,
reduceCount: reduceCount,
reduceSum: reduceSum,
value: value,
dispose: dispose,
remove: dispose // for backwards-compatibility
};
var reduceValue,
reduceAdd,
reduceRemove,
reduceInitial,
resetNeeded = true;
// The group listens to the crossfilter for when any dimension changes, so
// that it can update the reduce value. It must also listen to the parent
// dimension for when data is added.
filterListeners.push(update);
dataListeners.push(add);
// For consistency; actually a no-op since resetNeeded is true.
add(data, 0, n);
// Incorporates the specified new values into this group.
function add(newData, n0) {
var i;
if (resetNeeded) return;
// Add the added values.
for (i = n0; i < n; ++i) {
if (!filters[i]) {
reduceValue = reduceAdd(reduceValue, data[i]);
}
}
}
// Reduces the specified selected or deselected records.
function update(filterOne, added, removed) {
var i,
k,
n;
if (resetNeeded) return;
// Add the added values.
for (i = 0, n = added.length; i < n; ++i) {
if (!filters[k = added[i]]) {
reduceValue = reduceAdd(reduceValue, data[k]);
}
}
// Remove the removed values.
for (i = 0, n = removed.length; i < n; ++i) {
if (filters[k = removed[i]] === filterOne) {
reduceValue = reduceRemove(reduceValue, data[k]);
}
}
}
// Recomputes the group reduce value from scratch.
function reset() {
var i;
reduceValue = reduceInitial();
for (i = 0; i < n; ++i) {
if (!filters[i]) {
reduceValue = reduceAdd(reduceValue, data[i]);
}
}
}
// Sets the reduce behavior for this group to use the specified functions.
// This method lazily recomputes the reduce value, waiting until needed.
function reduce(add, remove, initial) {
reduceAdd = add;
reduceRemove = remove;
reduceInitial = initial;
resetNeeded = true;
return group;
}
// A convenience method for reducing by count.
function reduceCount() {
return reduce(crossfilter_reduceIncrement, crossfilter_reduceDecrement, crossfilter_zero);
}
// A convenience method for reducing by sum(value).
function reduceSum(value) {
return reduce(crossfilter_reduceAdd(value), crossfilter_reduceSubtract(value), crossfilter_zero);
}
// Returns the computed reduce value.
function value() {
if (resetNeeded) reset(), resetNeeded = false;
return reduceValue;
}
// Removes this group and associated event listeners.
function dispose() {
var i = filterListeners.indexOf(update);
if (i >= 0) filterListeners.splice(i);
i = dataListeners.indexOf(add);
if (i >= 0) dataListeners.splice(i);
return group;
}
return reduceCount();
}
// Returns the number of records in this crossfilter, irrespective of any filters.
function size() {
return n;
}
return arguments.length
? add(arguments[0])
: crossfilter;
}
// Returns an array of size n, big enough to store ids up to m.
function crossfilter_index(n, m) {
return (m < 0x101
? crossfilter_array8 : m < 0x10001
? crossfilter_array16
: crossfilter_array64)(n);
}
// Constructs a new array of size n, with sequential values from 0 to n - 1.
function crossfilter_range(n) {
var range = crossfilter_index(n, n);
for (var i = -1; ++i < n;) range[i] = i;
return range;
}
function crossfilter_capacity(w) {
return w === 8
? 0x100 : w === 16
? 0x10000
: 0x100000000;
}
})(typeof exports !== 'undefined' && exports || this);
| 44,228
| 14,005
|
const express = require("express");
const router = express.Router();
const Users = require("./users-model");
// All recorded Sauti Databank users
router.get("/all", (req, res) => {
Users.get()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
});
});
// Gender routes //
// All users who had a gender field
router.get("/all/gender/all", (req, res) => {
Users.getGenderAll()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
})
})
// Getting number of users who marked female
router.get("/all/gender/female/count", (req, res) => {
Users.getGenderFemale()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
})
})
// Getting number of users who marked male
router.get("/all/gender/male/count", (req, res) => {
Users.getGenderMale()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
})
})
// Border crossing routes //
// All border crossing frequencies
router.get("/all/crossingfreq/all", (req, res) => {
Users.getCrossingFreqAll()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
})
})
// Daily
router.get("/all/crossingfreq/daily/count", (req, res) => {
Users.getCrossingFreqDaily()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
})
})
// Weekly
router.get("/all/crossingfreq/weekly/count", (req, res) => {
Users.getCrossingFreqWeekly()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
})
})
// Monthly
router.get("/all/crossingfreq/monthly/count", (req, res) => {
Users.getCrossingFreqMonthly()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
})
})
// Never
router.get("/all/crossingfreq/never/count", (req, res) => {
Users.getCrossingFreqNever()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
})
})
// Education routes //
router.get("/all/education/all", (req, res) => {
Users.getEducation()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
});
});
router.get("/all/education/primary/count", (req, res) => {
Users.getEducationPrimary()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
router.get("/all/education/secondary/count", (req, res) => {
Users.getEducationSecondary()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
router.get("/all/education/uni/count", (req, res) => {
Users.getEducationUni()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
router.get("/all/education/none/count", (req, res) => {
Users.getEducationNone()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Language routes //
// All users who filled out a language
router.get("/all/language/all", (req, res) => {
Users.getLanguageAll()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
});
});
// English language count
router.get("/all/language/english/count", (req, res) => {
Users.getLanguageEnglish()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Swahili count
router.get("/all/language/swahili/count", (req, res) => {
Users.getLanguageSwahili()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Kinyarwanda count
router.get("/all/language/kinya/count", (req, res) => {
Users.getLanguageKinya()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Luganda count
router.get("/all/language/luganda/count", (req, res) => {
Users.getLanguageLug()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Lukiga count
router.get("/all/language/lukiga/count", (req, res) => {
Users.getLanguageLuk()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Country of residence routes //
// All users who input a country
router.get("/all/country/all", (req, res) => {
Users.getCountryAll()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
});
});
// Kenya
router.get("/all/country/kenya/count", (req, res) => {
Users.getCountryKenya()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Uganda
router.get("/all/country/uganda/count", (req, res) => {
Users.getCountryUganda()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Rwanda
router.get("/all/country/rwanda/count", (req, res) => {
Users.getCountryRwanda()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Age routes //
// All users with age
router.get("/all/age/all", (req, res) => {
Users.getAgeAll()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
});
});
// Group zero, 10-20
router.get("/all/age/group-zero/count", (req, res) => {
Users.getAgeGroupZero()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Group one, 20-30
router.get("/all/age/group-one/count", (req, res) => {
Users.getAgeGroupOne()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Group two, 30-40
router.get("/all/age/group-two/count", (req, res) => {
Users.getAgeGroupTwo()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Group three, 40-50
router.get("/all/age/group-three/count", (req, res) => {
Users.getAgeGroupThree()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Group four, 50-60
router.get("/all/age/group-four/count", (req, res) => {
Users.getAgeGroupFour()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
// Group five, 60-70
router.get("/all/age/group-five/count", (req, res) => {
Users.getAgeGroupFive()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
/* ************************************
PRIMARY INCOME ROUTES
************************************ */
router.get('/all/primary-income/all', (req, res) => {
Users.getPrimaryIncomeAll()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
});
});
router.get('/all/primary-income/yes/count', (req, res) => {
Users.getPrimaryIncomeYes()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
router.get('/all/primary-income/no/count', (req, res) => {
Users.getPrimaryIncomeNo()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
/* ************************************
PRODUCE ROUTES
************************************ */
router.get('/all/produce/all', (req, res) => {
Users.getProduceAll()
.then(users => {
res.status(200).json(users);
})
.catch(err => {
res.status(500).json(err);
});
});
router.get('/all/produce/yes/count', (req, res) => {
Users.getProduceYes()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
router.get('/all/produce/no/count', (req, res) => {
Users.getProduceNo()
.then(users => {
res.status(200).json(users.length);
})
.catch(err => {
res.status(500).json(err);
});
});
module.exports = router;
| 8,910
| 3,526
|
export default {
domain: "https://damp-river-04072.herokuapp.com",
METHOD: {
GET: 'get',
POST: 'post',
PUT: 'put',
DELETE: 'delete'
}
}
| 179
| 71
|
export {default } from './graph.container'
| 42
| 11
|
// ThreeCanvas.js r46 - http://github.com/mrdoob/three.js
var THREE=THREE||{};if(!self.Int32Array)self.Int32Array=Array,self.Float32Array=Array;THREE.Color=function(a){a!==void 0&&this.setHex(a);return this};
THREE.Color.prototype={constructor:THREE.Color,r:1,g:1,b:1,copy:function(a){this.r=a.r;this.g=a.g;this.b=a.b;return this},copyGammaToLinear:function(a){this.r=a.r*a.r;this.g=a.g*a.g;this.b=a.b*a.b;return this},copyLinearToGamma:function(a){this.r=Math.sqrt(a.r);this.g=Math.sqrt(a.g);this.b=Math.sqrt(a.b);return this},setRGB:function(a,b,c){this.r=a;this.g=b;this.b=c;return this},setHSV:function(a,b,c){var d,f,e;if(c===0)this.r=this.g=this.b=0;else switch(d=Math.floor(a*6),f=a*6-d,a=c*(1-b),e=c*(1-
b*f),b=c*(1-b*(1-f)),d){case 1:this.r=e;this.g=c;this.b=a;break;case 2:this.r=a;this.g=c;this.b=b;break;case 3:this.r=a;this.g=e;this.b=c;break;case 4:this.r=b;this.g=a;this.b=c;break;case 5:this.r=c;this.g=a;this.b=e;break;case 6:case 0:this.r=c,this.g=b,this.b=a}return this},setHex:function(a){a=Math.floor(a);this.r=(a>>16&255)/255;this.g=(a>>8&255)/255;this.b=(a&255)/255;return this},getHex:function(){return~~(this.r*255)<<16^~~(this.g*255)<<8^~~(this.b*255)},getContextStyle:function(){return"rgb("+
Math.floor(this.r*255)+","+Math.floor(this.g*255)+","+Math.floor(this.b*255)+")"},clone:function(){return(new THREE.Color).setRGB(this.r,this.g,this.b)}};THREE.Vector2=function(a,b){this.x=a||0;this.y=b||0};
THREE.Vector2.prototype={constructor:THREE.Vector2,set:function(a,b){this.x=a;this.y=b;return this},copy:function(a){this.x=a.x;this.y=a.y;return this},clone:function(){return new THREE.Vector2(this.x,this.y)},add:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this},addSelf:function(a){this.x+=a.x;this.y+=a.y;return this},sub:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this},subSelf:function(a){this.x-=a.x;this.y-=a.y;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;return this},
divideScalar:function(a){a?(this.x/=a,this.y/=a):this.set(0,0);return this},negate:function(){return this.multiplyScalar(-1)},dot:function(a){return this.x*a.x+this.y*a.y},lengthSq:function(){return this.x*this.x+this.y*this.y},length:function(){return Math.sqrt(this.lengthSq())},normalize:function(){return this.divideScalar(this.length())},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){var b=this.x-a.x,a=this.y-a.y;return b*b+a*a},setLength:function(a){return this.normalize().multiplyScalar(a)},
equals:function(a){return a.x===this.x&&a.y===this.y}};THREE.Vector3=function(a,b,c){this.x=a||0;this.y=b||0;this.z=c||0};
THREE.Vector3.prototype={constructor:THREE.Vector3,set:function(a,b,c){this.x=a;this.y=b;this.z=c;return this},setX:function(a){this.x=a;return this},setY:function(a){this.y=a;return this},setZ:function(a){this.z=a;return this},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;return this},clone:function(){return new THREE.Vector3(this.x,this.y,this.z)},add:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this},addSelf:function(a){this.x+=a.x;this.y+=a.y;this.z+=a.z;return this},
addScalar:function(a){this.x+=a;this.y+=a;this.z+=a;return this},sub:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this},subSelf:function(a){this.x-=a.x;this.y-=a.y;this.z-=a.z;return this},multiply:function(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this},multiplySelf:function(a){this.x*=a.x;this.y*=a.y;this.z*=a.z;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;return this},divideSelf:function(a){this.x/=a.x;this.y/=a.y;this.z/=a.z;return this},
divideScalar:function(a){a?(this.x/=a,this.y/=a,this.z/=a):this.z=this.y=this.x=0;return this},negate:function(){return this.multiplyScalar(-1)},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z},lengthSq:function(){return this.x*this.x+this.y*this.y+this.z*this.z},length:function(){return Math.sqrt(this.lengthSq())},lengthManhattan:function(){return this.x+this.y+this.z},normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.normalize().multiplyScalar(a)},
cross:function(a,b){this.x=a.y*b.z-a.z*b.y;this.y=a.z*b.x-a.x*b.z;this.z=a.x*b.y-a.y*b.x;return this},crossSelf:function(a){var b=this.x,c=this.y,d=this.z;this.x=c*a.z-d*a.y;this.y=d*a.x-b*a.z;this.z=b*a.y-c*a.x;return this},distanceTo:function(a){return Math.sqrt(this.distanceToSquared(a))},distanceToSquared:function(a){return(new THREE.Vector3).sub(this,a).lengthSq()},setPositionFromMatrix:function(a){this.x=a.n14;this.y=a.n24;this.z=a.n34},setRotationFromMatrix:function(a){var b=Math.cos(this.y);
this.y=Math.asin(a.n13);Math.abs(b)>1.0E-5?(this.x=Math.atan2(-a.n23/b,a.n33/b),this.z=Math.atan2(-a.n12/b,a.n11/b)):(this.x=0,this.z=Math.atan2(a.n21,a.n22))},isZero:function(){return this.lengthSq()<1.0E-4}};THREE.Vector4=function(a,b,c,d){this.x=a||0;this.y=b||0;this.z=c||0;this.w=d!==void 0?d:1};
THREE.Vector4.prototype={constructor:THREE.Vector4,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=a.w!==void 0?a.w:1},clone:function(){return new THREE.Vector4(this.x,this.y,this.z,this.w)},add:function(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this},addSelf:function(a){this.x+=a.x;this.y+=a.y;this.z+=a.z;this.w+=a.w;return this},sub:function(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-
b.z;this.w=a.w-b.w;return this},subSelf:function(a){this.x-=a.x;this.y-=a.y;this.z-=a.z;this.w-=a.w;return this},multiplyScalar:function(a){this.x*=a;this.y*=a;this.z*=a;this.w*=a;return this},divideScalar:function(a){a?(this.x/=a,this.y/=a,this.z/=a,this.w/=a):(this.z=this.y=this.x=0,this.w=1);return this},negate:function(){return this.multiplyScalar(-1)},dot:function(a){return this.x*a.x+this.y*a.y+this.z*a.z+this.w*a.w},lengthSq:function(){return this.dot(this)},length:function(){return Math.sqrt(this.lengthSq())},
normalize:function(){return this.divideScalar(this.length())},setLength:function(a){return this.normalize().multiplyScalar(a)},lerpSelf:function(a,b){this.x+=(a.x-this.x)*b;this.y+=(a.y-this.y)*b;this.z+=(a.z-this.z)*b;this.w+=(a.w-this.w)*b;return this}};
THREE.Ray=function(a,b){function c(a,b,c){i.sub(c,a);p=i.dot(b);if(p<=0)return null;k=n.add(a,o.copy(b).multiplyScalar(p));return s=c.distanceTo(k)}function d(a,b,c,d){i.sub(d,b);n.sub(c,b);o.sub(a,b);K=i.dot(i);C=i.dot(n);Q=i.dot(o);O=n.dot(n);w=n.dot(o);F=1/(K*O-C*C);z=(O*Q-C*w)*F;D=(K*w-C*Q)*F;return z>=0&&D>=0&&z+D<1}this.origin=a||new THREE.Vector3;this.direction=b||new THREE.Vector3;this.intersectScene=function(a){return this.intersectObjects(a.children)};this.intersectObjects=function(a){var b,
c,d=[];b=0;for(c=a.length;b<c;b++)Array.prototype.push.apply(d,this.intersectObject(a[b]));d.sort(function(a,b){return a.distance-b.distance});return d};var f=new THREE.Vector3,e=new THREE.Vector3,g=new THREE.Vector3,h=new THREE.Vector3,a=new THREE.Vector3,b=new THREE.Vector3,m=new THREE.Vector3,l=new THREE.Vector3,j=new THREE.Vector3;this.intersectObject=function(k){for(var i,o=[],n=0,W=k.children.length;n<W;n++)Array.prototype.push.apply(o,this.intersectObject(k.children[n]));if(k instanceof THREE.Particle){n=
c(this.origin,this.direction,k.matrixWorld.getPosition());if(n===null||n>k.scale.x)return[];i={distance:n,point:k.position,face:null,object:k};o.push(i)}else if(k instanceof THREE.Mesh){n=c(this.origin,this.direction,k.matrixWorld.getPosition());if(n===null||n>k.geometry.boundingSphere.radius*Math.max(k.scale.x,Math.max(k.scale.y,k.scale.z)))return o;var p,G=k.geometry,H=G.vertices,I;k.matrixRotationWorld.extractRotation(k.matrixWorld);n=0;for(W=G.faces.length;n<W;n++)if(i=G.faces[n],a.copy(this.origin),
b.copy(this.direction),I=k.matrixWorld,m=I.multiplyVector3(m.copy(i.centroid)).subSelf(a),p=m.dot(b),!(p<=0)&&(f=I.multiplyVector3(f.copy(H[i.a].position)),e=I.multiplyVector3(e.copy(H[i.b].position)),g=I.multiplyVector3(g.copy(H[i.c].position)),i instanceof THREE.Face4&&(h=I.multiplyVector3(h.copy(H[i.d].position))),l=k.matrixRotationWorld.multiplyVector3(l.copy(i.normal)),p=b.dot(l),k.doubleSided||(k.flipSided?p>0:p<0)))if(p=l.dot(m.sub(f,a))/p,j.add(a,b.multiplyScalar(p)),i instanceof THREE.Face3)d(j,
f,e,g)&&(i={distance:a.distanceTo(j),point:j.clone(),face:i,object:k},o.push(i));else if(i instanceof THREE.Face4&&(d(j,f,e,h)||d(j,e,g,h)))i={distance:a.distanceTo(j),point:j.clone(),face:i,object:k},o.push(i)}return o};var i=new THREE.Vector3,n=new THREE.Vector3,o=new THREE.Vector3,p,k,s,K,C,Q,O,w,F,z,D};
THREE.Rectangle=function(){function a(){e=d-b;g=f-c}var b,c,d,f,e,g,h=!0;this.getX=function(){return b};this.getY=function(){return c};this.getWidth=function(){return e};this.getHeight=function(){return g};this.getLeft=function(){return b};this.getTop=function(){return c};this.getRight=function(){return d};this.getBottom=function(){return f};this.set=function(e,g,j,i){h=!1;b=e;c=g;d=j;f=i;a()};this.addPoint=function(e,g){h?(h=!1,b=e,c=g,d=e,f=g):(b=b<e?b:e,c=c<g?c:g,d=d>e?d:e,f=f>g?f:g);a()};this.add3Points=
function(e,g,j,i,n,o){h?(h=!1,b=e<j?e<n?e:n:j<n?j:n,c=g<i?g<o?g:o:i<o?i:o,d=e>j?e>n?e:n:j>n?j:n,f=g>i?g>o?g:o:i>o?i:o):(b=e<j?e<n?e<b?e:b:n<b?n:b:j<n?j<b?j:b:n<b?n:b,c=g<i?g<o?g<c?g:c:o<c?o:c:i<o?i<c?i:c:o<c?o:c,d=e>j?e>n?e>d?e:d:n>d?n:d:j>n?j>d?j:d:n>d?n:d,f=g>i?g>o?g>f?g:f:o>f?o:f:i>o?i>f?i:f:o>f?o:f);a()};this.addRectangle=function(e){h?(h=!1,b=e.getLeft(),c=e.getTop(),d=e.getRight(),f=e.getBottom()):(b=b<e.getLeft()?b:e.getLeft(),c=c<e.getTop()?c:e.getTop(),d=d>e.getRight()?d:e.getRight(),f=f>
e.getBottom()?f:e.getBottom());a()};this.inflate=function(e){b-=e;c-=e;d+=e;f+=e;a()};this.minSelf=function(e){b=b>e.getLeft()?b:e.getLeft();c=c>e.getTop()?c:e.getTop();d=d<e.getRight()?d:e.getRight();f=f<e.getBottom()?f:e.getBottom();a()};this.intersects=function(a){return Math.min(d,a.getRight())-Math.max(b,a.getLeft())>=0&&Math.min(f,a.getBottom())-Math.max(c,a.getTop())>=0};this.empty=function(){h=!0;f=d=c=b=0;a()};this.isEmpty=function(){return h}};
THREE.Math={clamp:function(a,b,c){return a<b?b:a>c?c:a},clampBottom:function(a,b){return a<b?b:a},mapLinear:function(a,b,c,d,f){return d+(a-b)*(f-d)/(c-b)},random16:function(){return(65280*Math.random()+255*Math.random())/65535}};THREE.Matrix3=function(){this.m=[]};
THREE.Matrix3.prototype={constructor:THREE.Matrix3,transpose:function(){var a,b=this.m;a=b[1];b[1]=b[3];b[3]=a;a=b[2];b[2]=b[6];b[6]=a;a=b[5];b[5]=b[7];b[7]=a;return this},transposeIntoArray:function(a){var b=this.m;a[0]=b[0];a[1]=b[3];a[2]=b[6];a[3]=b[1];a[4]=b[4];a[5]=b[7];a[6]=b[2];a[7]=b[5];a[8]=b[8];return this}};
THREE.Matrix4=function(a,b,c,d,f,e,g,h,m,l,j,i,n,o,p,k){this.set(a!==void 0?a:1,b||0,c||0,d||0,f||0,e!==void 0?e:1,g||0,h||0,m||0,l||0,j!==void 0?j:1,i||0,n||0,o||0,p||0,k!==void 0?k:1);this.flat=Array(16);this.m33=new THREE.Matrix3};
THREE.Matrix4.prototype={constructor:THREE.Matrix4,set:function(a,b,c,d,f,e,g,h,m,l,j,i,n,o,p,k){this.n11=a;this.n12=b;this.n13=c;this.n14=d;this.n21=f;this.n22=e;this.n23=g;this.n24=h;this.n31=m;this.n32=l;this.n33=j;this.n34=i;this.n41=n;this.n42=o;this.n43=p;this.n44=k;return this},identity:function(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this},copy:function(a){this.set(a.n11,a.n12,a.n13,a.n14,a.n21,a.n22,a.n23,a.n24,a.n31,a.n32,a.n33,a.n34,a.n41,a.n42,a.n43,a.n44);return this},lookAt:function(a,
b,c){var d=THREE.Matrix4.__v1,f=THREE.Matrix4.__v2,e=THREE.Matrix4.__v3;e.sub(a,b).normalize();if(e.length()===0)e.z=1;d.cross(c,e).normalize();d.length()===0&&(e.x+=1.0E-4,d.cross(c,e).normalize());f.cross(e,d).normalize();this.n11=d.x;this.n12=f.x;this.n13=e.x;this.n21=d.y;this.n22=f.y;this.n23=e.y;this.n31=d.z;this.n32=f.z;this.n33=e.z;return this},multiply:function(a,b){var c=a.n11,d=a.n12,f=a.n13,e=a.n14,g=a.n21,h=a.n22,m=a.n23,l=a.n24,j=a.n31,i=a.n32,n=a.n33,o=a.n34,p=a.n41,k=a.n42,s=a.n43,
K=a.n44,C=b.n11,Q=b.n12,O=b.n13,w=b.n14,F=b.n21,z=b.n22,D=b.n23,u=b.n24,r=b.n31,E=b.n32,N=b.n33,W=b.n34,da=b.n41,G=b.n42,H=b.n43,I=b.n44;this.n11=c*C+d*F+f*r+e*da;this.n12=c*Q+d*z+f*E+e*G;this.n13=c*O+d*D+f*N+e*H;this.n14=c*w+d*u+f*W+e*I;this.n21=g*C+h*F+m*r+l*da;this.n22=g*Q+h*z+m*E+l*G;this.n23=g*O+h*D+m*N+l*H;this.n24=g*w+h*u+m*W+l*I;this.n31=j*C+i*F+n*r+o*da;this.n32=j*Q+i*z+n*E+o*G;this.n33=j*O+i*D+n*N+o*H;this.n34=j*w+i*u+n*W+o*I;this.n41=p*C+k*F+s*r+K*da;this.n42=p*Q+k*z+s*E+K*G;this.n43=p*
O+k*D+s*N+K*H;this.n44=p*w+k*u+s*W+K*I;return this},multiplySelf:function(a){return this.multiply(this,a)},multiplyToArray:function(a,b,c){this.multiply(a,b);c[0]=this.n11;c[1]=this.n21;c[2]=this.n31;c[3]=this.n41;c[4]=this.n12;c[5]=this.n22;c[6]=this.n32;c[7]=this.n42;c[8]=this.n13;c[9]=this.n23;c[10]=this.n33;c[11]=this.n43;c[12]=this.n14;c[13]=this.n24;c[14]=this.n34;c[15]=this.n44;return this},multiplyScalar:function(a){this.n11*=a;this.n12*=a;this.n13*=a;this.n14*=a;this.n21*=a;this.n22*=a;this.n23*=
a;this.n24*=a;this.n31*=a;this.n32*=a;this.n33*=a;this.n34*=a;this.n41*=a;this.n42*=a;this.n43*=a;this.n44*=a;return this},multiplyVector3:function(a){var b=a.x,c=a.y,d=a.z,f=1/(this.n41*b+this.n42*c+this.n43*d+this.n44);a.x=(this.n11*b+this.n12*c+this.n13*d+this.n14)*f;a.y=(this.n21*b+this.n22*c+this.n23*d+this.n24)*f;a.z=(this.n31*b+this.n32*c+this.n33*d+this.n34)*f;return a},multiplyVector4:function(a){var b=a.x,c=a.y,d=a.z,f=a.w;a.x=this.n11*b+this.n12*c+this.n13*d+this.n14*f;a.y=this.n21*b+this.n22*
c+this.n23*d+this.n24*f;a.z=this.n31*b+this.n32*c+this.n33*d+this.n34*f;a.w=this.n41*b+this.n42*c+this.n43*d+this.n44*f;return a},rotateAxis:function(a){var b=a.x,c=a.y,d=a.z;a.x=b*this.n11+c*this.n12+d*this.n13;a.y=b*this.n21+c*this.n22+d*this.n23;a.z=b*this.n31+c*this.n32+d*this.n33;a.normalize();return a},crossVector:function(a){var b=new THREE.Vector4;b.x=this.n11*a.x+this.n12*a.y+this.n13*a.z+this.n14*a.w;b.y=this.n21*a.x+this.n22*a.y+this.n23*a.z+this.n24*a.w;b.z=this.n31*a.x+this.n32*a.y+this.n33*
a.z+this.n34*a.w;b.w=a.w?this.n41*a.x+this.n42*a.y+this.n43*a.z+this.n44*a.w:1;return b},determinant:function(){var a=this.n11,b=this.n12,c=this.n13,d=this.n14,f=this.n21,e=this.n22,g=this.n23,h=this.n24,m=this.n31,l=this.n32,j=this.n33,i=this.n34,n=this.n41,o=this.n42,p=this.n43,k=this.n44;return d*g*l*n-c*h*l*n-d*e*j*n+b*h*j*n+c*e*i*n-b*g*i*n-d*g*m*o+c*h*m*o+d*f*j*o-a*h*j*o-c*f*i*o+a*g*i*o+d*e*m*p-b*h*m*p-d*f*l*p+a*h*l*p+b*f*i*p-a*e*i*p-c*e*m*k+b*g*m*k+c*f*l*k-a*g*l*k-b*f*j*k+a*e*j*k},transpose:function(){var a;
a=this.n21;this.n21=this.n12;this.n12=a;a=this.n31;this.n31=this.n13;this.n13=a;a=this.n32;this.n32=this.n23;this.n23=a;a=this.n41;this.n41=this.n14;this.n14=a;a=this.n42;this.n42=this.n24;this.n24=a;a=this.n43;this.n43=this.n34;this.n43=a;return this},clone:function(){var a=new THREE.Matrix4;a.n11=this.n11;a.n12=this.n12;a.n13=this.n13;a.n14=this.n14;a.n21=this.n21;a.n22=this.n22;a.n23=this.n23;a.n24=this.n24;a.n31=this.n31;a.n32=this.n32;a.n33=this.n33;a.n34=this.n34;a.n41=this.n41;a.n42=this.n42;
a.n43=this.n43;a.n44=this.n44;return a},flatten:function(){this.flat[0]=this.n11;this.flat[1]=this.n21;this.flat[2]=this.n31;this.flat[3]=this.n41;this.flat[4]=this.n12;this.flat[5]=this.n22;this.flat[6]=this.n32;this.flat[7]=this.n42;this.flat[8]=this.n13;this.flat[9]=this.n23;this.flat[10]=this.n33;this.flat[11]=this.n43;this.flat[12]=this.n14;this.flat[13]=this.n24;this.flat[14]=this.n34;this.flat[15]=this.n44;return this.flat},flattenToArray:function(a){a[0]=this.n11;a[1]=this.n21;a[2]=this.n31;
a[3]=this.n41;a[4]=this.n12;a[5]=this.n22;a[6]=this.n32;a[7]=this.n42;a[8]=this.n13;a[9]=this.n23;a[10]=this.n33;a[11]=this.n43;a[12]=this.n14;a[13]=this.n24;a[14]=this.n34;a[15]=this.n44;return a},flattenToArrayOffset:function(a,b){a[b]=this.n11;a[b+1]=this.n21;a[b+2]=this.n31;a[b+3]=this.n41;a[b+4]=this.n12;a[b+5]=this.n22;a[b+6]=this.n32;a[b+7]=this.n42;a[b+8]=this.n13;a[b+9]=this.n23;a[b+10]=this.n33;a[b+11]=this.n43;a[b+12]=this.n14;a[b+13]=this.n24;a[b+14]=this.n34;a[b+15]=this.n44;return a},
setTranslation:function(a,b,c){this.set(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1);return this},setScale:function(a,b,c){this.set(a,0,0,0,0,b,0,0,0,0,c,0,0,0,0,1);return this},setRotationX:function(a){var b=Math.cos(a),a=Math.sin(a);this.set(1,0,0,0,0,b,-a,0,0,a,b,0,0,0,0,1);return this},setRotationY:function(a){var b=Math.cos(a),a=Math.sin(a);this.set(b,0,a,0,0,1,0,0,-a,0,b,0,0,0,0,1);return this},setRotationZ:function(a){var b=Math.cos(a),a=Math.sin(a);this.set(b,-a,0,0,a,b,0,0,0,0,1,0,0,0,0,1);return this},
setRotationAxis:function(a,b){var c=Math.cos(b),d=Math.sin(b),f=1-c,e=a.x,g=a.y,h=a.z,m=f*e,l=f*g;this.set(m*e+c,m*g-d*h,m*h+d*g,0,m*g+d*h,l*g+c,l*h-d*e,0,m*h-d*g,l*h+d*e,f*h*h+c,0,0,0,0,1);return this},setPosition:function(a){this.n14=a.x;this.n24=a.y;this.n34=a.z;return this},getPosition:function(){return THREE.Matrix4.__v1.set(this.n14,this.n24,this.n34)},getColumnX:function(){return THREE.Matrix4.__v1.set(this.n11,this.n21,this.n31)},getColumnY:function(){return THREE.Matrix4.__v1.set(this.n12,
this.n22,this.n32)},getColumnZ:function(){return THREE.Matrix4.__v1.set(this.n13,this.n23,this.n33)},getInverse:function(a){var b=a.n11,c=a.n12,d=a.n13,f=a.n14,e=a.n21,g=a.n22,h=a.n23,m=a.n24,l=a.n31,j=a.n32,i=a.n33,n=a.n34,o=a.n41,p=a.n42,k=a.n43,s=a.n44;this.n11=h*n*p-m*i*p+m*j*k-g*n*k-h*j*s+g*i*s;this.n12=f*i*p-d*n*p-f*j*k+c*n*k+d*j*s-c*i*s;this.n13=d*m*p-f*h*p+f*g*k-c*m*k-d*g*s+c*h*s;this.n14=f*h*j-d*m*j-f*g*i+c*m*i+d*g*n-c*h*n;this.n21=m*i*o-h*n*o-m*l*k+e*n*k+h*l*s-e*i*s;this.n22=d*n*o-f*i*o+
f*l*k-b*n*k-d*l*s+b*i*s;this.n23=f*h*o-d*m*o-f*e*k+b*m*k+d*e*s-b*h*s;this.n24=d*m*l-f*h*l+f*e*i-b*m*i-d*e*n+b*h*n;this.n31=g*n*o-m*j*o+m*l*p-e*n*p-g*l*s+e*j*s;this.n32=f*j*o-c*n*o-f*l*p+b*n*p+c*l*s-b*j*s;this.n33=d*m*o-f*g*o+f*e*p-b*m*p-c*e*s+b*g*s;this.n34=f*g*l-c*m*l-f*e*j+b*m*j+c*e*n-b*g*n;this.n41=h*j*o-g*i*o-h*l*p+e*i*p+g*l*k-e*j*k;this.n42=c*i*o-d*j*o+d*l*p-b*i*p-c*l*k+b*j*k;this.n43=d*g*o-c*h*o-d*e*p+b*h*p+c*e*k-b*g*k;this.n44=c*h*l-d*g*l+d*e*j-b*h*j-c*e*i+b*g*i;this.multiplyScalar(1/a.determinant());
return this},setRotationFromEuler:function(a,b){var c=a.x,d=a.y,f=a.z,e=Math.cos(c),c=Math.sin(c),g=Math.cos(d),d=Math.sin(d),h=Math.cos(f),f=Math.sin(f);switch(b){case "YXZ":var m=g*h,l=g*f,j=d*h,i=d*f;this.n11=m+i*c;this.n12=j*c-l;this.n13=e*d;this.n21=e*f;this.n22=e*h;this.n23=-c;this.n31=l*c-j;this.n32=i+m*c;this.n33=e*g;break;case "ZXY":m=g*h;l=g*f;j=d*h;i=d*f;this.n11=m-i*c;this.n12=-e*f;this.n13=j+l*c;this.n21=l+j*c;this.n22=e*h;this.n23=i-m*c;this.n31=-e*d;this.n32=c;this.n33=e*g;break;case "ZYX":m=
e*h;l=e*f;j=c*h;i=c*f;this.n11=g*h;this.n12=j*d-l;this.n13=m*d+i;this.n21=g*f;this.n22=i*d+m;this.n23=l*d-j;this.n31=-d;this.n32=c*g;this.n33=e*g;break;case "YZX":m=e*g;l=e*d;j=c*g;i=c*d;this.n11=g*h;this.n12=i-m*f;this.n13=j*f+l;this.n21=f;this.n22=e*h;this.n23=-c*h;this.n31=-d*h;this.n32=l*f+j;this.n33=m-i*f;break;case "XZY":m=e*g;l=e*d;j=c*g;i=c*d;this.n11=g*h;this.n12=-f;this.n13=d*h;this.n21=m*f+i;this.n22=e*h;this.n23=l*f-j;this.n31=j*f-l;this.n32=c*h;this.n33=i*f+m;break;default:m=e*h,l=e*
f,j=c*h,i=c*f,this.n11=g*h,this.n12=-g*f,this.n13=d,this.n21=l+j*d,this.n22=m-i*d,this.n23=-c*g,this.n31=i-m*d,this.n32=j+l*d,this.n33=e*g}return this},setRotationFromQuaternion:function(a){var b=a.x,c=a.y,d=a.z,f=a.w,e=b+b,g=c+c,h=d+d,a=b*e,m=b*g;b*=h;var l=c*g;c*=h;d*=h;e*=f;g*=f;f*=h;this.n11=1-(l+d);this.n12=m-f;this.n13=b+g;this.n21=m+f;this.n22=1-(a+d);this.n23=c-e;this.n31=b-g;this.n32=c+e;this.n33=1-(a+l);return this},scale:function(a){var b=a.x,c=a.y,a=a.z;this.n11*=b;this.n12*=c;this.n13*=
a;this.n21*=b;this.n22*=c;this.n23*=a;this.n31*=b;this.n32*=c;this.n33*=a;this.n41*=b;this.n42*=c;this.n43*=a;return this},compose:function(a,b,c){var d=THREE.Matrix4.__m1,f=THREE.Matrix4.__m2;d.identity();d.setRotationFromQuaternion(b);f.setScale(c.x,c.y,c.z);this.multiply(d,f);this.n14=a.x;this.n24=a.y;this.n34=a.z;return this},decompose:function(a,b,c){var d=THREE.Matrix4.__v1,f=THREE.Matrix4.__v2,e=THREE.Matrix4.__v3;d.set(this.n11,this.n21,this.n31);f.set(this.n12,this.n22,this.n32);e.set(this.n13,
this.n23,this.n33);a=a instanceof THREE.Vector3?a:new THREE.Vector3;b=b instanceof THREE.Quaternion?b:new THREE.Quaternion;c=c instanceof THREE.Vector3?c:new THREE.Vector3;c.x=d.length();c.y=f.length();c.z=e.length();a.x=this.n14;a.y=this.n24;a.z=this.n34;d=THREE.Matrix4.__m1;d.copy(this);d.n11/=c.x;d.n21/=c.x;d.n31/=c.x;d.n12/=c.y;d.n22/=c.y;d.n32/=c.y;d.n13/=c.z;d.n23/=c.z;d.n33/=c.z;b.setFromRotationMatrix(d);return[a,b,c]},extractPosition:function(a){this.n14=a.n14;this.n24=a.n24;this.n34=a.n34;
return this},extractRotation:function(a){var b=THREE.Matrix4.__v1,c=1/b.set(a.n11,a.n21,a.n31).length(),d=1/b.set(a.n12,a.n22,a.n32).length(),b=1/b.set(a.n13,a.n23,a.n33).length();this.n11=a.n11*c;this.n21=a.n21*c;this.n31=a.n31*c;this.n12=a.n12*d;this.n22=a.n22*d;this.n32=a.n32*d;this.n13=a.n13*b;this.n23=a.n23*b;this.n33=a.n33*b;return this}};
THREE.Matrix4.makeInvert3x3=function(a){var b=a.m33,c=b.m,d=a.n33*a.n22-a.n32*a.n23,f=-a.n33*a.n21+a.n31*a.n23,e=a.n32*a.n21-a.n31*a.n22,g=-a.n33*a.n12+a.n32*a.n13,h=a.n33*a.n11-a.n31*a.n13,m=-a.n32*a.n11+a.n31*a.n12,l=a.n23*a.n12-a.n22*a.n13,j=-a.n23*a.n11+a.n21*a.n13,i=a.n22*a.n11-a.n21*a.n12,a=a.n11*d+a.n21*g+a.n31*l;a===0&&console.error("THREE.Matrix4.makeInvert3x3: Matrix not invertible.");a=1/a;c[0]=a*d;c[1]=a*f;c[2]=a*e;c[3]=a*g;c[4]=a*h;c[5]=a*m;c[6]=a*l;c[7]=a*j;c[8]=a*i;return b};
THREE.Matrix4.makeFrustum=function(a,b,c,d,f,e){var g;g=new THREE.Matrix4;g.n11=2*f/(b-a);g.n12=0;g.n13=(b+a)/(b-a);g.n14=0;g.n21=0;g.n22=2*f/(d-c);g.n23=(d+c)/(d-c);g.n24=0;g.n31=0;g.n32=0;g.n33=-(e+f)/(e-f);g.n34=-2*e*f/(e-f);g.n41=0;g.n42=0;g.n43=-1;g.n44=0;return g};THREE.Matrix4.makePerspective=function(a,b,c,d){var f,a=c*Math.tan(a*Math.PI/360);f=-a;return THREE.Matrix4.makeFrustum(f*b,a*b,f,a,c,d)};
THREE.Matrix4.makeOrtho=function(a,b,c,d,f,e){var g,h,m,l;g=new THREE.Matrix4;h=b-a;m=c-d;l=e-f;g.n11=2/h;g.n12=0;g.n13=0;g.n14=-((b+a)/h);g.n21=0;g.n22=2/m;g.n23=0;g.n24=-((c+d)/m);g.n31=0;g.n32=0;g.n33=-2/l;g.n34=-((e+f)/l);g.n41=0;g.n42=0;g.n43=0;g.n44=1;return g};THREE.Matrix4.__v1=new THREE.Vector3;THREE.Matrix4.__v2=new THREE.Vector3;THREE.Matrix4.__v3=new THREE.Vector3;THREE.Matrix4.__m1=new THREE.Matrix4;THREE.Matrix4.__m2=new THREE.Matrix4;
THREE.Object3D=function(){this.name="";this.id=THREE.Object3DCount++;this.parent=void 0;this.children=[];this.up=new THREE.Vector3(0,1,0);this.position=new THREE.Vector3;this.rotation=new THREE.Vector3;this.eulerOrder="XYZ";this.scale=new THREE.Vector3(1,1,1);this.flipSided=this.doubleSided=this.dynamic=!1;this.renderDepth=null;this.rotationAutoUpdate=!0;this.matrix=new THREE.Matrix4;this.matrixWorld=new THREE.Matrix4;this.matrixRotationWorld=new THREE.Matrix4;this.matrixWorldNeedsUpdate=this.matrixAutoUpdate=
!0;this.quaternion=new THREE.Quaternion;this.useQuaternion=!1;this.boundRadius=0;this.boundRadiusScale=1;this.visible=!0;this.receiveShadow=this.castShadow=!1;this.frustumCulled=!0;this._vector=new THREE.Vector3};
THREE.Object3D.prototype={constructor:THREE.Object3D,translate:function(a,b){this.matrix.rotateAxis(b);this.position.addSelf(b.multiplyScalar(a))},translateX:function(a){this.translate(a,this._vector.set(1,0,0))},translateY:function(a){this.translate(a,this._vector.set(0,1,0))},translateZ:function(a){this.translate(a,this._vector.set(0,0,1))},lookAt:function(a){this.matrix.lookAt(a,this.position,this.up);this.rotationAutoUpdate&&this.rotation.setRotationFromMatrix(this.matrix)},add:function(a){if(this.children.indexOf(a)===
-1){a.parent!==void 0&&a.parent.remove(a);a.parent=this;this.children.push(a);for(var b=this;b.parent!==void 0;)b=b.parent;b!==void 0&&b instanceof THREE.Scene&&b.addObject(a)}},remove:function(a){var b=this.children.indexOf(a);if(b!==-1){a.parent=void 0;this.children.splice(b,1);for(b=this;b.parent!==void 0;)b=b.parent;b!==void 0&&b instanceof THREE.Scene&&b.removeObject(a)}},getChildByName:function(a,b){var c,d,f;c=0;for(d=this.children.length;c<d;c++){f=this.children[c];if(f.name===a)return f;
if(b&&(f=f.getChildByName(a,b),f!==void 0))return f}},updateMatrix:function(){this.matrix.setPosition(this.position);this.useQuaternion?this.matrix.setRotationFromQuaternion(this.quaternion):this.matrix.setRotationFromEuler(this.rotation,this.eulerOrder);if(this.scale.x!==1||this.scale.y!==1||this.scale.z!==1)this.matrix.scale(this.scale),this.boundRadiusScale=Math.max(this.scale.x,Math.max(this.scale.y,this.scale.z));this.matrixWorldNeedsUpdate=!0},updateMatrixWorld:function(a){this.matrixAutoUpdate&&
this.updateMatrix();if(this.matrixWorldNeedsUpdate||a)this.parent?this.matrixWorld.multiply(this.parent.matrixWorld,this.matrix):this.matrixWorld.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,a=!0;for(var b=0,c=this.children.length;b<c;b++)this.children[b].updateMatrixWorld(a)}};THREE.Object3DCount=0;
THREE.Projector=function(){function a(){var a=g[e]=g[e]||new THREE.RenderableObject;e++;return a}function b(){var a=l[m]=l[m]||new THREE.RenderableVertex;m++;return a}function c(a,b){return b.z-a.z}function d(a,b){var c=0,d=1,e=a.z+a.w,f=b.z+b.w,g=-a.z+a.w,h=-b.z+b.w;return e>=0&&f>=0&&g>=0&&h>=0?!0:e<0&&f<0||g<0&&h<0?!1:(e<0?c=Math.max(c,e/(e-f)):f<0&&(d=Math.min(d,e/(e-f))),g<0?c=Math.max(c,g/(g-h)):h<0&&(d=Math.min(d,g/(g-h))),d<c?!1:(a.lerpSelf(b,c),b.lerpSelf(a,1-d),!0))}var f,e,g=[],h,m,l=[],
j,i,n=[],o,p=[],k,s,K=[],C,Q,O=[],w={objects:[],sprites:[],lights:[],elements:[]},F=new THREE.Vector3,z=new THREE.Vector4,D=new THREE.Matrix4,u=new THREE.Matrix4,r=[new THREE.Vector4,new THREE.Vector4,new THREE.Vector4,new THREE.Vector4,new THREE.Vector4,new THREE.Vector4],E=new THREE.Vector4,N=new THREE.Vector4;this.computeFrustum=function(a){r[0].set(a.n41-a.n11,a.n42-a.n12,a.n43-a.n13,a.n44-a.n14);r[1].set(a.n41+a.n11,a.n42+a.n12,a.n43+a.n13,a.n44+a.n14);r[2].set(a.n41+a.n21,a.n42+a.n22,a.n43+
a.n23,a.n44+a.n24);r[3].set(a.n41-a.n21,a.n42-a.n22,a.n43-a.n23,a.n44-a.n24);r[4].set(a.n41-a.n31,a.n42-a.n32,a.n43-a.n33,a.n44-a.n34);r[5].set(a.n41+a.n31,a.n42+a.n32,a.n43+a.n33,a.n44+a.n34);for(a=0;a<6;a++){var b=r[a];b.divideScalar(Math.sqrt(b.x*b.x+b.y*b.y+b.z*b.z))}};this.projectVector=function(a,b){b.matrixWorldInverse.getInverse(b.matrixWorld);D.multiply(b.projectionMatrix,b.matrixWorldInverse);D.multiplyVector3(a);return a};this.unprojectVector=function(a,b){b.projectionMatrixInverse.getInverse(b.projectionMatrix);
D.multiply(b.matrixWorld,b.projectionMatrixInverse);D.multiplyVector3(a);return a};this.pickingRay=function(a,b){var c;a.z=-1;c=new THREE.Vector3(a.x,a.y,1);this.unprojectVector(a,b);this.unprojectVector(c,b);c.subSelf(a).normalize();return new THREE.Ray(a,c)};this.projectGraph=function(b,d){e=0;w.objects.length=0;w.sprites.length=0;w.lights.length=0;var g=function(b){if(b.visible!==!1){var c;if(c=b instanceof THREE.Mesh||b instanceof THREE.Line)if(!(c=b.frustumCulled===!1))a:{for(var d=b.matrixWorld,
e=-b.geometry.boundingSphere.radius*Math.max(b.scale.x,Math.max(b.scale.y,b.scale.z)),h=0;h<6;h++)if(c=r[h].x*d.n14+r[h].y*d.n24+r[h].z*d.n34+r[h].w,c<=e){c=!1;break a}c=!0}c?(D.multiplyVector3(F.copy(b.position)),f=a(),f.object=b,f.z=F.z,w.objects.push(f)):b instanceof THREE.Sprite||b instanceof THREE.Particle?(D.multiplyVector3(F.copy(b.position)),f=a(),f.object=b,f.z=F.z,w.sprites.push(f)):b instanceof THREE.Light&&w.lights.push(b);c=0;for(d=b.children.length;c<d;c++)g(b.children[c])}};g(b);d&&
w.objects.sort(c);return w};this.projectScene=function(a,e,f){var g=e.near,r=e.far,F,L,B,S,v,R,P,V,J,t,A,x,y,M,la,fa;Q=s=o=i=0;w.elements.length=0;e.parent===void 0&&(console.warn("DEPRECATED: Camera hasn't been added to a Scene. Adding it..."),a.add(e));a.updateMatrixWorld();e.matrixWorldInverse.getInverse(e.matrixWorld);D.multiply(e.projectionMatrix,e.matrixWorldInverse);this.computeFrustum(D);w=this.projectGraph(a,!1);a=0;for(F=w.objects.length;a<F;a++)if(J=w.objects[a].object,t=J.matrixWorld,
x=J.material,m=0,J instanceof THREE.Mesh){A=J.geometry;y=J.geometry.materials;S=A.vertices;M=A.faces;la=A.faceVertexUvs;A=J.matrixRotationWorld.extractRotation(t);L=0;for(B=S.length;L<B;L++)h=b(),h.positionWorld.copy(S[L].position),t.multiplyVector3(h.positionWorld),h.positionScreen.copy(h.positionWorld),D.multiplyVector4(h.positionScreen),h.positionScreen.x/=h.positionScreen.w,h.positionScreen.y/=h.positionScreen.w,h.visible=h.positionScreen.z>g&&h.positionScreen.z<r;S=0;for(L=M.length;S<L;S++){B=
M[S];if(B instanceof THREE.Face3)if(v=l[B.a],R=l[B.b],P=l[B.c],v.visible&&R.visible&&P.visible&&(J.doubleSided||J.flipSided!=(P.positionScreen.x-v.positionScreen.x)*(R.positionScreen.y-v.positionScreen.y)-(P.positionScreen.y-v.positionScreen.y)*(R.positionScreen.x-v.positionScreen.x)<0))V=n[i]=n[i]||new THREE.RenderableFace3,i++,j=V,j.v1.copy(v),j.v2.copy(R),j.v3.copy(P);else continue;else if(B instanceof THREE.Face4)if(v=l[B.a],R=l[B.b],P=l[B.c],V=l[B.d],v.visible&&R.visible&&P.visible&&V.visible&&
(J.doubleSided||J.flipSided!=((V.positionScreen.x-v.positionScreen.x)*(R.positionScreen.y-v.positionScreen.y)-(V.positionScreen.y-v.positionScreen.y)*(R.positionScreen.x-v.positionScreen.x)<0||(R.positionScreen.x-P.positionScreen.x)*(V.positionScreen.y-P.positionScreen.y)-(R.positionScreen.y-P.positionScreen.y)*(V.positionScreen.x-P.positionScreen.x)<0)))fa=p[o]=p[o]||new THREE.RenderableFace4,o++,j=fa,j.v1.copy(v),j.v2.copy(R),j.v3.copy(P),j.v4.copy(V);else continue;j.normalWorld.copy(B.normal);
A.multiplyVector3(j.normalWorld);j.centroidWorld.copy(B.centroid);t.multiplyVector3(j.centroidWorld);j.centroidScreen.copy(j.centroidWorld);D.multiplyVector3(j.centroidScreen);P=B.vertexNormals;v=0;for(R=P.length;v<R;v++)V=j.vertexNormalsWorld[v],V.copy(P[v]),A.multiplyVector3(V);v=0;for(R=la.length;v<R;v++)if(fa=la[v][S]){P=0;for(V=fa.length;P<V;P++)j.uvs[v][P]=fa[P]}j.material=x;j.faceMaterial=B.materialIndex!==null?y[B.materialIndex]:null;j.z=j.centroidScreen.z;w.elements.push(j)}}else if(J instanceof
THREE.Line){u.multiply(D,t);S=J.geometry.vertices;v=b();v.positionScreen.copy(S[0].position);u.multiplyVector4(v.positionScreen);L=1;for(B=S.length;L<B;L++)if(v=b(),v.positionScreen.copy(S[L].position),u.multiplyVector4(v.positionScreen),R=l[m-2],E.copy(v.positionScreen),N.copy(R.positionScreen),d(E,N))E.multiplyScalar(1/E.w),N.multiplyScalar(1/N.w),J=K[s]=K[s]||new THREE.RenderableLine,s++,k=J,k.v1.positionScreen.copy(E),k.v2.positionScreen.copy(N),k.z=Math.max(E.z,N.z),k.material=x,w.elements.push(k)}a=
0;for(F=w.sprites.length;a<F;a++)if(J=w.sprites[a].object,t=J.matrixWorld,J instanceof THREE.Particle&&(z.set(t.n14,t.n24,t.n34,1),D.multiplyVector4(z),z.z/=z.w,z.z>0&&z.z<1))g=O[Q]=O[Q]||new THREE.RenderableParticle,Q++,C=g,C.x=z.x/z.w,C.y=z.y/z.w,C.z=z.z,C.rotation=J.rotation.z,C.scale.x=J.scale.x*Math.abs(C.x-(z.x+e.projectionMatrix.n11)/(z.w+e.projectionMatrix.n14)),C.scale.y=J.scale.y*Math.abs(C.y-(z.y+e.projectionMatrix.n22)/(z.w+e.projectionMatrix.n24)),C.material=J.material,w.elements.push(C);
f&&w.elements.sort(c);return w}};THREE.Quaternion=function(a,b,c,d){this.set(a||0,b||0,c||0,d!==void 0?d:1)};
THREE.Quaternion.prototype={constructor:THREE.Quaternion,set:function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.w=d;return this},copy:function(a){this.x=a.x;this.y=a.y;this.z=a.z;this.w=a.w;return this},setFromEuler:function(a){var b=Math.PI/360,c=a.x*b,d=a.y*b,f=a.z*b,a=Math.cos(d),d=Math.sin(d),b=Math.cos(-f),f=Math.sin(-f),e=Math.cos(c),c=Math.sin(c),g=a*b,h=d*f;this.w=g*e-h*c;this.x=g*c+h*e;this.y=d*b*e+a*f*c;this.z=a*f*e-d*b*c;return this},setFromAxisAngle:function(a,b){var c=b/2,d=Math.sin(c);
this.x=a.x*d;this.y=a.y*d;this.z=a.z*d;this.w=Math.cos(c);return this},setFromRotationMatrix:function(a){var b=Math.pow(a.determinant(),1/3);this.w=Math.sqrt(Math.max(0,b+a.n11+a.n22+a.n33))/2;this.x=Math.sqrt(Math.max(0,b+a.n11-a.n22-a.n33))/2;this.y=Math.sqrt(Math.max(0,b-a.n11+a.n22-a.n33))/2;this.z=Math.sqrt(Math.max(0,b-a.n11-a.n22+a.n33))/2;this.x=a.n32-a.n23<0?-Math.abs(this.x):Math.abs(this.x);this.y=a.n13-a.n31<0?-Math.abs(this.y):Math.abs(this.y);this.z=a.n21-a.n12<0?-Math.abs(this.z):Math.abs(this.z);
this.normalize();return this},calculateW:function(){this.w=-Math.sqrt(Math.abs(1-this.x*this.x-this.y*this.y-this.z*this.z));return this},inverse:function(){this.x*=-1;this.y*=-1;this.z*=-1;return this},length:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},normalize:function(){var a=Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);a===0?this.w=this.z=this.y=this.x=0:(a=1/a,this.x*=a,this.y*=a,this.z*=a,this.w*=a);return this},multiplySelf:function(a){var b=
this.x,c=this.y,d=this.z,f=this.w,e=a.x,g=a.y,h=a.z,a=a.w;this.x=b*a+f*e+c*h-d*g;this.y=c*a+f*g+d*e-b*h;this.z=d*a+f*h+b*g-c*e;this.w=f*a-b*e-c*g-d*h;return this},multiply:function(a,b){this.x=a.x*b.w+a.y*b.z-a.z*b.y+a.w*b.x;this.y=-a.x*b.z+a.y*b.w+a.z*b.x+a.w*b.y;this.z=a.x*b.y-a.y*b.x+a.z*b.w+a.w*b.z;this.w=-a.x*b.x-a.y*b.y-a.z*b.z+a.w*b.w;return this},multiplyVector3:function(a,b){b||(b=a);var c=a.x,d=a.y,f=a.z,e=this.x,g=this.y,h=this.z,m=this.w,l=m*c+g*f-h*d,j=m*d+h*c-e*f,i=m*f+e*d-g*c,c=-e*
c-g*d-h*f;b.x=l*m+c*-e+j*-h-i*-g;b.y=j*m+c*-g+i*-e-l*-h;b.z=i*m+c*-h+l*-g-j*-e;return b}};
THREE.Quaternion.slerp=function(a,b,c,d){var f=a.w*b.w+a.x*b.x+a.y*b.y+a.z*b.z;f<0?(c.w=-b.w,c.x=-b.x,c.y=-b.y,c.z=-b.z,f=-f):c.copy(b);if(Math.abs(f)>=1)return c.w=a.w,c.x=a.x,c.y=a.y,c.z=a.z,c;var e=Math.acos(f),f=Math.sqrt(1-f*f);if(Math.abs(f)<0.001)return c.w=0.5*(a.w+b.w),c.x=0.5*(a.x+b.x),c.y=0.5*(a.y+b.y),c.z=0.5*(a.z+b.z),c;b=Math.sin((1-d)*e)/f;d=Math.sin(d*e)/f;c.w=a.w*b+c.w*d;c.x=a.x*b+c.x*d;c.y=a.y*b+c.y*d;c.z=a.z*b+c.z*d;return c};THREE.Vertex=function(a){this.position=a||new THREE.Vector3};
THREE.Face3=function(a,b,c,d,f,e){this.a=a;this.b=b;this.c=c;this.normal=d instanceof THREE.Vector3?d:new THREE.Vector3;this.vertexNormals=d instanceof Array?d:[];this.color=f instanceof THREE.Color?f:new THREE.Color;this.vertexColors=f instanceof Array?f:[];this.vertexTangents=[];this.materialIndex=e;this.centroid=new THREE.Vector3};
THREE.Face4=function(a,b,c,d,f,e,g){this.a=a;this.b=b;this.c=c;this.d=d;this.normal=f instanceof THREE.Vector3?f:new THREE.Vector3;this.vertexNormals=f instanceof Array?f:[];this.color=e instanceof THREE.Color?e:new THREE.Color;this.vertexColors=e instanceof Array?e:[];this.vertexTangents=[];this.materialIndex=g;this.centroid=new THREE.Vector3};THREE.UV=function(a,b){this.u=a||0;this.v=b||0};
THREE.UV.prototype={constructor:THREE.UV,set:function(a,b){this.u=a;this.v=b;return this},copy:function(a){this.u=a.u;this.v=a.v;return this},clone:function(){return new THREE.UV(this.u,this.v)}};
THREE.Geometry=function(){this.id=THREE.GeometryCount++;this.vertices=[];this.colors=[];this.materials=[];this.faces=[];this.faceUvs=[[]];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphColors=[];this.skinWeights=[];this.skinIndices=[];this.boundingSphere=this.boundingBox=null;this.dynamic=this.hasTangents=!1};
THREE.Geometry.prototype={constructor:THREE.Geometry,applyMatrix:function(a){var b=new THREE.Matrix4;b.extractRotation(a,new THREE.Vector3(1,1,1));for(var c=0,d=this.vertices.length;c<d;c++)a.multiplyVector3(this.vertices[c].position);c=0;for(d=this.faces.length;c<d;c++){var f=this.faces[c];b.multiplyVector3(f.normal);for(var e=0,g=f.vertexNormals.length;e<g;e++)b.multiplyVector3(f.vertexNormals[e]);a.multiplyVector3(f.centroid)}},computeCentroids:function(){var a,b,c;a=0;for(b=this.faces.length;a<
b;a++)c=this.faces[a],c.centroid.set(0,0,0),c instanceof THREE.Face3?(c.centroid.addSelf(this.vertices[c.a].position),c.centroid.addSelf(this.vertices[c.b].position),c.centroid.addSelf(this.vertices[c.c].position),c.centroid.divideScalar(3)):c instanceof THREE.Face4&&(c.centroid.addSelf(this.vertices[c.a].position),c.centroid.addSelf(this.vertices[c.b].position),c.centroid.addSelf(this.vertices[c.c].position),c.centroid.addSelf(this.vertices[c.d].position),c.centroid.divideScalar(4))},computeFaceNormals:function(){var a,
b,c,d,f,e,g=new THREE.Vector3,h=new THREE.Vector3;a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],d=this.vertices[c.a],f=this.vertices[c.b],e=this.vertices[c.c],g.sub(e.position,f.position),h.sub(d.position,f.position),g.crossSelf(h),g.isZero()||g.normalize(),c.normal.copy(g)},computeVertexNormals:function(){var a,b,c,d;if(this.__tmpVertices===void 0){d=this.__tmpVertices=Array(this.vertices.length);a=0;for(b=this.vertices.length;a<b;a++)d[a]=new THREE.Vector3;a=0;for(b=this.faces.length;a<b;a++)if(c=
this.faces[a],c instanceof THREE.Face3)c.vertexNormals=[new THREE.Vector3,new THREE.Vector3,new THREE.Vector3];else if(c instanceof THREE.Face4)c.vertexNormals=[new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3]}else{d=this.__tmpVertices;a=0;for(b=this.vertices.length;a<b;a++)d[a].set(0,0,0)}a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],c instanceof THREE.Face3?(d[c.a].addSelf(c.normal),d[c.b].addSelf(c.normal),d[c.c].addSelf(c.normal)):c instanceof THREE.Face4&&(d[c.a].addSelf(c.normal),
d[c.b].addSelf(c.normal),d[c.c].addSelf(c.normal),d[c.d].addSelf(c.normal));a=0;for(b=this.vertices.length;a<b;a++)d[a].normalize();a=0;for(b=this.faces.length;a<b;a++)c=this.faces[a],c instanceof THREE.Face3?(c.vertexNormals[0].copy(d[c.a]),c.vertexNormals[1].copy(d[c.b]),c.vertexNormals[2].copy(d[c.c])):c instanceof THREE.Face4&&(c.vertexNormals[0].copy(d[c.a]),c.vertexNormals[1].copy(d[c.b]),c.vertexNormals[2].copy(d[c.c]),c.vertexNormals[3].copy(d[c.d]))},computeTangents:function(){function a(a,
b,c,d,e,f,D){h=a.vertices[b].position;m=a.vertices[c].position;l=a.vertices[d].position;j=g[e];i=g[f];n=g[D];o=m.x-h.x;p=l.x-h.x;k=m.y-h.y;s=l.y-h.y;K=m.z-h.z;C=l.z-h.z;Q=i.u-j.u;O=n.u-j.u;w=i.v-j.v;F=n.v-j.v;z=1/(Q*F-O*w);E.set((F*o-w*p)*z,(F*k-w*s)*z,(F*K-w*C)*z);N.set((Q*p-O*o)*z,(Q*s-O*k)*z,(Q*C-O*K)*z);u[b].addSelf(E);u[c].addSelf(E);u[d].addSelf(E);r[b].addSelf(N);r[c].addSelf(N);r[d].addSelf(N)}var b,c,d,f,e,g,h,m,l,j,i,n,o,p,k,s,K,C,Q,O,w,F,z,D,u=[],r=[],E=new THREE.Vector3,N=new THREE.Vector3,
W=new THREE.Vector3,da=new THREE.Vector3,G=new THREE.Vector3;b=0;for(c=this.vertices.length;b<c;b++)u[b]=new THREE.Vector3,r[b]=new THREE.Vector3;b=0;for(c=this.faces.length;b<c;b++)e=this.faces[b],g=this.faceVertexUvs[0][b],e instanceof THREE.Face3?a(this,e.a,e.b,e.c,0,1,2):e instanceof THREE.Face4&&(a(this,e.a,e.b,e.c,0,1,2),a(this,e.a,e.b,e.d,0,1,3));var H=["a","b","c","d"];b=0;for(c=this.faces.length;b<c;b++){e=this.faces[b];for(d=0;d<e.vertexNormals.length;d++)G.copy(e.vertexNormals[d]),f=e[H[d]],
D=u[f],W.copy(D),W.subSelf(G.multiplyScalar(G.dot(D))).normalize(),da.cross(e.vertexNormals[d],D),f=da.dot(r[f]),f=f<0?-1:1,e.vertexTangents[d]=new THREE.Vector4(W.x,W.y,W.z,f)}this.hasTangents=!0},computeBoundingBox:function(){var a;if(this.vertices.length>0){this.boundingBox={x:[this.vertices[0].position.x,this.vertices[0].position.x],y:[this.vertices[0].position.y,this.vertices[0].position.y],z:[this.vertices[0].position.z,this.vertices[0].position.z]};for(var b=1,c=this.vertices.length;b<c;b++){a=
this.vertices[b];if(a.position.x<this.boundingBox.x[0])this.boundingBox.x[0]=a.position.x;else if(a.position.x>this.boundingBox.x[1])this.boundingBox.x[1]=a.position.x;if(a.position.y<this.boundingBox.y[0])this.boundingBox.y[0]=a.position.y;else if(a.position.y>this.boundingBox.y[1])this.boundingBox.y[1]=a.position.y;if(a.position.z<this.boundingBox.z[0])this.boundingBox.z[0]=a.position.z;else if(a.position.z>this.boundingBox.z[1])this.boundingBox.z[1]=a.position.z}}},computeBoundingSphere:function(){for(var a=
0,b=0,c=this.vertices.length;b<c;b++)a=Math.max(a,this.vertices[b].position.length());this.boundingSphere={radius:a}},mergeVertices:function(){var a={},b=[],c=[],d,f=Math.pow(10,4),e,g;e=0;for(g=this.vertices.length;e<g;e++)d=this.vertices[e].position,d=[Math.round(d.x*f),Math.round(d.y*f),Math.round(d.z*f)].join("_"),a[d]===void 0?(a[d]=e,b.push(this.vertices[e]),c[e]=b.length-1):c[e]=c[a[d]];e=0;for(g=this.faces.length;e<g;e++)if(a=this.faces[e],a instanceof THREE.Face3)a.a=c[a.a],a.b=c[a.b],a.c=
c[a.c];else if(a instanceof THREE.Face4)a.a=c[a.a],a.b=c[a.b],a.c=c[a.c],a.d=c[a.d];this.vertices=b}};THREE.GeometryCount=0;THREE.Camera=function(){if(arguments.length)return console.warn("DEPRECATED: Camera() is now PerspectiveCamera() or OrthographicCamera()."),new THREE.PerspectiveCamera(arguments[0],arguments[1],arguments[2],arguments[3]);THREE.Object3D.call(this);this.matrixWorldInverse=new THREE.Matrix4;this.projectionMatrix=new THREE.Matrix4;this.projectionMatrixInverse=new THREE.Matrix4};
THREE.Camera.prototype=new THREE.Object3D;THREE.Camera.prototype.constructor=THREE.Camera;THREE.Camera.prototype.lookAt=function(a){this.matrix.lookAt(this.position,a,this.up);this.rotationAutoUpdate&&this.rotation.setRotationFromMatrix(this.matrix)};THREE.OrthographicCamera=function(a,b,c,d,f,e){THREE.Camera.call(this);this.left=a;this.right=b;this.top=c;this.bottom=d;this.near=f!==void 0?f:0.1;this.far=e!==void 0?e:2E3;this.updateProjectionMatrix()};THREE.OrthographicCamera.prototype=new THREE.Camera;
THREE.OrthographicCamera.prototype.constructor=THREE.OrthographicCamera;THREE.OrthographicCamera.prototype.updateProjectionMatrix=function(){this.projectionMatrix=THREE.Matrix4.makeOrtho(this.left,this.right,this.top,this.bottom,this.near,this.far)};THREE.PerspectiveCamera=function(a,b,c,d){THREE.Camera.call(this);this.fov=a!==void 0?a:50;this.aspect=b!==void 0?b:1;this.near=c!==void 0?c:0.1;this.far=d!==void 0?d:2E3;this.updateProjectionMatrix()};THREE.PerspectiveCamera.prototype=new THREE.Camera;
THREE.PerspectiveCamera.prototype.constructor=THREE.PerspectiveCamera;THREE.PerspectiveCamera.prototype.setLens=function(a,b){this.fov=2*Math.atan((b!==void 0?b:43.25)/(a*2));this.fov*=180/Math.PI;this.updateProjectionMatrix()};THREE.PerspectiveCamera.prototype.setViewOffset=function(a,b,c,d,f,e){this.fullWidth=a;this.fullHeight=b;this.x=c;this.y=d;this.width=f;this.height=e;this.updateProjectionMatrix()};
THREE.PerspectiveCamera.prototype.updateProjectionMatrix=function(){if(this.fullWidth){var a=this.fullWidth/this.fullHeight,b=Math.tan(this.fov*Math.PI/360)*this.near,c=-b,d=a*c,a=Math.abs(a*b-d),c=Math.abs(b-c);this.projectionMatrix=THREE.Matrix4.makeFrustum(d+this.x*a/this.fullWidth,d+(this.x+this.width)*a/this.fullWidth,b-(this.y+this.height)*c/this.fullHeight,b-this.y*c/this.fullHeight,this.near,this.far)}else this.projectionMatrix=THREE.Matrix4.makePerspective(this.fov,this.aspect,this.near,
this.far)};THREE.Light=function(a){THREE.Object3D.call(this);this.color=new THREE.Color(a)};THREE.Light.prototype=new THREE.Object3D;THREE.Light.prototype.constructor=THREE.Light;THREE.Light.prototype.supr=THREE.Object3D.prototype;THREE.AmbientLight=function(a){THREE.Light.call(this,a)};THREE.AmbientLight.prototype=new THREE.Light;THREE.AmbientLight.prototype.constructor=THREE.AmbientLight;
THREE.DirectionalLight=function(a,b,c){THREE.Light.call(this,a);this.position=new THREE.Vector3(0,1,0);this.intensity=b!==void 0?b:1;this.distance=c!==void 0?c:0};THREE.DirectionalLight.prototype=new THREE.Light;THREE.DirectionalLight.prototype.constructor=THREE.DirectionalLight;THREE.PointLight=function(a,b,c){THREE.Light.call(this,a);this.position=new THREE.Vector3(0,0,0);this.intensity=b!==void 0?b:1;this.distance=c!==void 0?c:0};THREE.PointLight.prototype=new THREE.Light;
THREE.PointLight.prototype.constructor=THREE.PointLight;
THREE.Material=function(a){this.name="";this.id=THREE.MaterialCount++;a=a||{};this.opacity=a.opacity!==void 0?a.opacity:1;this.transparent=a.transparent!==void 0?a.transparent:!1;this.blending=a.blending!==void 0?a.blending:THREE.NormalBlending;this.depthTest=a.depthTest!==void 0?a.depthTest:!0;this.depthWrite=a.depthWrite!==void 0?a.depthWrite:!0;this.polygonOffset=a.polygonOffset!==void 0?a.polygonOffset:!1;this.polygonOffsetFactor=a.polygonOffsetFactor!==void 0?a.polygonOffsetFactor:0;this.polygonOffsetUnits=
a.polygonOffsetUnits!==void 0?a.polygonOffsetUnits:0;this.alphaTest=a.alphaTest!==void 0?a.alphaTest:0;this.overdraw=a.overdraw!==void 0?a.overdraw:!1};THREE.MaterialCount=0;THREE.NoShading=0;THREE.FlatShading=1;THREE.SmoothShading=2;THREE.NoColors=0;THREE.FaceColors=1;THREE.VertexColors=2;THREE.NormalBlending=0;THREE.AdditiveBlending=1;THREE.SubtractiveBlending=2;THREE.MultiplyBlending=3;THREE.AdditiveAlphaBlending=4;
THREE.LineBasicMaterial=function(a){THREE.Material.call(this,a);a=a||{};this.color=a.color!==void 0?new THREE.Color(a.color):new THREE.Color(16777215);this.linewidth=a.linewidth!==void 0?a.linewidth:1;this.linecap=a.linecap!==void 0?a.linecap:"round";this.linejoin=a.linejoin!==void 0?a.linejoin:"round";this.vertexColors=a.vertexColors?a.vertexColors:!1;this.fog=a.fog!==void 0?a.fog:!0};THREE.LineBasicMaterial.prototype=new THREE.Material;THREE.LineBasicMaterial.prototype.constructor=THREE.LineBasicMaterial;
THREE.MeshBasicMaterial=function(a){THREE.Material.call(this,a);a=a||{};this.color=a.color!==void 0?new THREE.Color(a.color):new THREE.Color(16777215);this.map=a.map!==void 0?a.map:null;this.lightMap=a.lightMap!==void 0?a.lightMap:null;this.envMap=a.envMap!==void 0?a.envMap:null;this.combine=a.combine!==void 0?a.combine:THREE.MultiplyOperation;this.reflectivity=a.reflectivity!==void 0?a.reflectivity:1;this.refractionRatio=a.refractionRatio!==void 0?a.refractionRatio:0.98;this.fog=a.fog!==void 0?a.fog:
!0;this.shading=a.shading!==void 0?a.shading:THREE.SmoothShading;this.wireframe=a.wireframe!==void 0?a.wireframe:!1;this.wireframeLinewidth=a.wireframeLinewidth!==void 0?a.wireframeLinewidth:1;this.wireframeLinecap=a.wireframeLinecap!==void 0?a.wireframeLinecap:"round";this.wireframeLinejoin=a.wireframeLinejoin!==void 0?a.wireframeLinejoin:"round";this.vertexColors=a.vertexColors!==void 0?a.vertexColors:!1;this.skinning=a.skinning!==void 0?a.skinning:!1;this.morphTargets=a.morphTargets!==void 0?a.morphTargets:
!1};THREE.MeshBasicMaterial.prototype=new THREE.Material;THREE.MeshBasicMaterial.prototype.constructor=THREE.MeshBasicMaterial;
THREE.MeshLambertMaterial=function(a){THREE.Material.call(this,a);a=a||{};this.color=a.color!==void 0?new THREE.Color(a.color):new THREE.Color(16777215);this.ambient=a.ambient!==void 0?new THREE.Color(a.ambient):new THREE.Color(328965);this.map=a.map!==void 0?a.map:null;this.lightMap=a.lightMap!==void 0?a.lightMap:null;this.envMap=a.envMap!==void 0?a.envMap:null;this.combine=a.combine!==void 0?a.combine:THREE.MultiplyOperation;this.reflectivity=a.reflectivity!==void 0?a.reflectivity:1;this.refractionRatio=
a.refractionRatio!==void 0?a.refractionRatio:0.98;this.fog=a.fog!==void 0?a.fog:!0;this.shading=a.shading!==void 0?a.shading:THREE.SmoothShading;this.wireframe=a.wireframe!==void 0?a.wireframe:!1;this.wireframeLinewidth=a.wireframeLinewidth!==void 0?a.wireframeLinewidth:1;this.wireframeLinecap=a.wireframeLinecap!==void 0?a.wireframeLinecap:"round";this.wireframeLinejoin=a.wireframeLinejoin!==void 0?a.wireframeLinejoin:"round";this.vertexColors=a.vertexColors!==void 0?a.vertexColors:!1;this.skinning=
a.skinning!==void 0?a.skinning:!1;this.morphTargets=a.morphTargets!==void 0?a.morphTargets:!1};THREE.MeshLambertMaterial.prototype=new THREE.Material;THREE.MeshLambertMaterial.prototype.constructor=THREE.MeshLambertMaterial;
THREE.MeshPhongMaterial=function(a){THREE.Material.call(this,a);a=a||{};this.color=a.color!==void 0?new THREE.Color(a.color):new THREE.Color(16777215);this.ambient=a.ambient!==void 0?new THREE.Color(a.ambient):new THREE.Color(328965);this.specular=a.specular!==void 0?new THREE.Color(a.specular):new THREE.Color(1118481);this.shininess=a.shininess!==void 0?a.shininess:30;this.metal=a.metal!==void 0?a.metal:!1;this.perPixel=a.perPixel!==void 0?a.perPixel:!1;this.map=a.map!==void 0?a.map:null;this.lightMap=
a.lightMap!==void 0?a.lightMap:null;this.envMap=a.envMap!==void 0?a.envMap:null;this.combine=a.combine!==void 0?a.combine:THREE.MultiplyOperation;this.reflectivity=a.reflectivity!==void 0?a.reflectivity:1;this.refractionRatio=a.refractionRatio!==void 0?a.refractionRatio:0.98;this.fog=a.fog!==void 0?a.fog:!0;this.shading=a.shading!==void 0?a.shading:THREE.SmoothShading;this.wireframe=a.wireframe!==void 0?a.wireframe:!1;this.wireframeLinewidth=a.wireframeLinewidth!==void 0?a.wireframeLinewidth:1;this.wireframeLinecap=
a.wireframeLinecap!==void 0?a.wireframeLinecap:"round";this.wireframeLinejoin=a.wireframeLinejoin!==void 0?a.wireframeLinejoin:"round";this.vertexColors=a.vertexColors!==void 0?a.vertexColors:!1;this.skinning=a.skinning!==void 0?a.skinning:!1;this.morphTargets=a.morphTargets!==void 0?a.morphTargets:!1};THREE.MeshPhongMaterial.prototype=new THREE.Material;THREE.MeshPhongMaterial.prototype.constructor=THREE.MeshPhongMaterial;
THREE.MeshDepthMaterial=function(a){THREE.Material.call(this,a);a=a||{};this.shading=a.shading!==void 0?a.shading:THREE.SmoothShading;this.wireframe=a.wireframe!==void 0?a.wireframe:!1;this.wireframeLinewidth=a.wireframeLinewidth!==void 0?a.wireframeLinewidth:1};THREE.MeshDepthMaterial.prototype=new THREE.Material;THREE.MeshDepthMaterial.prototype.constructor=THREE.MeshDepthMaterial;
THREE.MeshNormalMaterial=function(a){THREE.Material.call(this,a);a=a||{};this.shading=a.shading?a.shading:THREE.FlatShading;this.wireframe=a.wireframe?a.wireframe:!1;this.wireframeLinewidth=a.wireframeLinewidth?a.wireframeLinewidth:1};THREE.MeshNormalMaterial.prototype=new THREE.Material;THREE.MeshNormalMaterial.prototype.constructor=THREE.MeshNormalMaterial;THREE.MeshFaceMaterial=function(){};
THREE.ParticleBasicMaterial=function(a){THREE.Material.call(this,a);a=a||{};this.color=a.color!==void 0?new THREE.Color(a.color):new THREE.Color(16777215);this.map=a.map!==void 0?a.map:null;this.size=a.size!==void 0?a.size:1;this.sizeAttenuation=a.sizeAttenuation!==void 0?a.sizeAttenuation:!0;this.vertexColors=a.vertexColors!==void 0?a.vertexColors:!1;this.fog=a.fog!==void 0?a.fog:!0};THREE.ParticleBasicMaterial.prototype=new THREE.Material;THREE.ParticleBasicMaterial.prototype.constructor=THREE.ParticleBasicMaterial;
THREE.ParticleCanvasMaterial=function(a){THREE.Material.call(this,a);a=a||{};this.color=a.color!==void 0?new THREE.Color(a.color):new THREE.Color(16777215);this.program=a.program!==void 0?a.program:function(){}};THREE.ParticleCanvasMaterial.prototype=new THREE.Material;THREE.ParticleCanvasMaterial.prototype.constructor=THREE.ParticleCanvasMaterial;
THREE.Texture=function(a,b,c,d,f,e){this.id=THREE.TextureCount++;this.image=a;this.mapping=b!==void 0?b:new THREE.UVMapping;this.wrapS=c!==void 0?c:THREE.ClampToEdgeWrapping;this.wrapT=d!==void 0?d:THREE.ClampToEdgeWrapping;this.magFilter=f!==void 0?f:THREE.LinearFilter;this.minFilter=e!==void 0?e:THREE.LinearMipMapLinearFilter;this.offset=new THREE.Vector2(0,0);this.repeat=new THREE.Vector2(1,1);this.needsUpdate=!1;this.onUpdate=null};
THREE.Texture.prototype={constructor:THREE.Texture,clone:function(){var a=new THREE.Texture(this.image,this.mapping,this.wrapS,this.wrapT,this.magFilter,this.minFilter);a.offset.copy(this.offset);a.repeat.copy(this.repeat);return a}};THREE.TextureCount=0;THREE.MultiplyOperation=0;THREE.MixOperation=1;THREE.CubeReflectionMapping=function(){};THREE.CubeRefractionMapping=function(){};THREE.LatitudeReflectionMapping=function(){};THREE.LatitudeRefractionMapping=function(){};
THREE.SphericalReflectionMapping=function(){};THREE.SphericalRefractionMapping=function(){};THREE.UVMapping=function(){};THREE.RepeatWrapping=0;THREE.ClampToEdgeWrapping=1;THREE.MirroredRepeatWrapping=2;THREE.NearestFilter=3;THREE.NearestMipMapNearestFilter=4;THREE.NearestMipMapLinearFilter=5;THREE.LinearFilter=6;THREE.LinearMipMapNearestFilter=7;THREE.LinearMipMapLinearFilter=8;THREE.ByteType=9;THREE.UnsignedByteType=10;THREE.ShortType=11;THREE.UnsignedShortType=12;THREE.IntType=13;
THREE.UnsignedIntType=14;THREE.FloatType=15;THREE.AlphaFormat=16;THREE.RGBFormat=17;THREE.RGBAFormat=18;THREE.LuminanceFormat=19;THREE.LuminanceAlphaFormat=20;THREE.Particle=function(a){THREE.Object3D.call(this);this.material=a};THREE.Particle.prototype=new THREE.Object3D;THREE.Particle.prototype.constructor=THREE.Particle;THREE.Line=function(a,b,c){THREE.Object3D.call(this);this.geometry=a;this.material=b;this.type=c!==void 0?c:THREE.LineStrip;this.geometry&&(this.geometry.boundingSphere||this.geometry.computeBoundingSphere())};
THREE.LineStrip=0;THREE.LinePieces=1;THREE.Line.prototype=new THREE.Object3D;THREE.Line.prototype.constructor=THREE.Line;
THREE.Mesh=function(a,b){THREE.Object3D.call(this);this.geometry=a;this.material=b;if(b instanceof Array)console.warn("DEPRECATED: Mesh material can no longer be an Array. Using material at index 0..."),this.material=b[0];if(this.geometry&&(this.geometry.boundingSphere||this.geometry.computeBoundingSphere(),this.boundRadius=a.boundingSphere.radius,this.geometry.morphTargets.length)){this.morphTargetBase=-1;this.morphTargetForcedOrder=[];this.morphTargetInfluences=[];this.morphTargetDictionary={};
for(var c=0;c<this.geometry.morphTargets.length;c++)this.morphTargetInfluences.push(0),this.morphTargetDictionary[this.geometry.morphTargets[c].name]=c}};THREE.Mesh.prototype=new THREE.Object3D;THREE.Mesh.prototype.constructor=THREE.Mesh;THREE.Mesh.prototype.supr=THREE.Object3D.prototype;
THREE.Mesh.prototype.getMorphTargetIndexByName=function(a){if(this.morphTargetDictionary[a]!==void 0)return this.morphTargetDictionary[a];console.log("THREE.Mesh.getMorphTargetIndexByName: morph target "+a+" does not exist. Returning 0.");return 0};THREE.Bone=function(a){THREE.Object3D.call(this);this.skin=a;this.skinMatrix=new THREE.Matrix4};THREE.Bone.prototype=new THREE.Object3D;THREE.Bone.prototype.constructor=THREE.Bone;THREE.Bone.prototype.supr=THREE.Object3D.prototype;
THREE.Bone.prototype.update=function(a,b){this.matrixAutoUpdate&&(b|=this.updateMatrix());if(b||this.matrixWorldNeedsUpdate)a?this.skinMatrix.multiply(a,this.matrix):this.skinMatrix.copy(this.matrix),this.matrixWorldNeedsUpdate=!1,b=!0;var c,d=this.children.length;for(c=0;c<d;c++)this.children[c].update(this.skinMatrix,b)};
THREE.Sprite=function(a){THREE.Object3D.call(this);this.color=a.color!==void 0?new THREE.Color(a.color):new THREE.Color(16777215);this.map=a.map instanceof THREE.Texture?a.map:THREE.ImageUtils.loadTexture(a.map);this.blending=a.blending!==void 0?a.blending:THREE.NormalBlending;this.useScreenCoordinates=a.useScreenCoordinates!==void 0?a.useScreenCoordinates:!0;this.mergeWith3D=a.mergeWith3D!==void 0?a.mergeWith3D:!this.useScreenCoordinates;this.affectedByDistance=a.affectedByDistance!==void 0?a.affectedByDistance:
!this.useScreenCoordinates;this.scaleByViewport=a.scaleByViewport!==void 0?a.scaleByViewport:!this.affectedByDistance;this.alignment=a.alignment instanceof THREE.Vector2?a.alignment:THREE.SpriteAlignment.center;this.rotation3d=this.rotation;this.rotation=0;this.opacity=1;this.uvOffset=new THREE.Vector2(0,0);this.uvScale=new THREE.Vector2(1,1)};THREE.Sprite.prototype=new THREE.Object3D;THREE.Sprite.prototype.constructor=THREE.Sprite;
THREE.Sprite.prototype.updateMatrix=function(){this.matrix.setPosition(this.position);this.rotation3d.set(0,0,this.rotation);this.matrix.setRotationFromEuler(this.rotation3d);if(this.scale.x!==1||this.scale.y!==1)this.matrix.scale(this.scale),this.boundRadiusScale=Math.max(this.scale.x,this.scale.y);this.matrixWorldNeedsUpdate=!0};THREE.SpriteAlignment={};THREE.SpriteAlignment.topLeft=new THREE.Vector2(1,-1);THREE.SpriteAlignment.topCenter=new THREE.Vector2(0,-1);
THREE.SpriteAlignment.topRight=new THREE.Vector2(-1,-1);THREE.SpriteAlignment.centerLeft=new THREE.Vector2(1,0);THREE.SpriteAlignment.center=new THREE.Vector2(0,0);THREE.SpriteAlignment.centerRight=new THREE.Vector2(-1,0);THREE.SpriteAlignment.bottomLeft=new THREE.Vector2(1,1);THREE.SpriteAlignment.bottomCenter=new THREE.Vector2(0,1);THREE.SpriteAlignment.bottomRight=new THREE.Vector2(-1,1);
THREE.Scene=function(){THREE.Object3D.call(this);this.overrideMaterial=this.fog=null;this.matrixAutoUpdate=!1;this.objects=[];this.lights=[];this.__objectsAdded=[];this.__objectsRemoved=[]};THREE.Scene.prototype=new THREE.Object3D;THREE.Scene.prototype.constructor=THREE.Scene;
THREE.Scene.prototype.addObject=function(a){if(a instanceof THREE.Light)this.lights.indexOf(a)===-1&&this.lights.push(a);else if(!(a instanceof THREE.Camera||a instanceof THREE.Bone)&&this.objects.indexOf(a)===-1){this.objects.push(a);this.__objectsAdded.push(a);var b=this.__objectsRemoved.indexOf(a);b!==-1&&this.__objectsRemoved.splice(b,1)}for(b=0;b<a.children.length;b++)this.addObject(a.children[b])};
THREE.Scene.prototype.removeObject=function(a){if(a instanceof THREE.Light){var b=this.lights.indexOf(a);b!==-1&&this.lights.splice(b,1)}else a instanceof THREE.Camera||(b=this.objects.indexOf(a),b!==-1&&(this.objects.splice(b,1),this.__objectsRemoved.push(a),b=this.__objectsAdded.indexOf(a),b!==-1&&this.__objectsAdded.splice(b,1)));for(b=0;b<a.children.length;b++)this.removeObject(a.children[b])};
THREE.CanvasRenderer=function(a){function b(a){if(C!=a)k.globalAlpha=C=a}function c(a){if(Q!=a){switch(a){case THREE.NormalBlending:k.globalCompositeOperation="source-over";break;case THREE.AdditiveBlending:k.globalCompositeOperation="lighter";break;case THREE.SubtractiveBlending:k.globalCompositeOperation="darker"}Q=a}}function d(a){if(O!=a)k.strokeStyle=O=a}function f(a){if(w!=a)k.fillStyle=w=a}var e=this,g,h,m,l=new THREE.Projector,a=a||{},j=a.canvas!==void 0?a.canvas:document.createElement("canvas"),
i,n,o,p,k=j.getContext("2d"),s=new THREE.Color(0),K=0,C=1,Q=0,O=null,w=null,F=null,z=null,D=null,u,r,E,N,W=new THREE.RenderableVertex,da=new THREE.RenderableVertex,G,H,I,Y,L,B,S,v,R,P,V,J,t=new THREE.Color,A=new THREE.Color,x=new THREE.Color,y=new THREE.Color,M=new THREE.Color,la=[],fa=[],ga,ha,ea,aa,Ba,Ca,Da,Ea,Fa,Ga,ma=new THREE.Rectangle,Z=new THREE.Rectangle,X=new THREE.Rectangle,ya=!1,$=new THREE.Color,ta=new THREE.Color,ua=new THREE.Color,T=new THREE.Vector3,qa,ra,za,ba,sa,va,a=16;qa=document.createElement("canvas");
qa.width=qa.height=2;ra=qa.getContext("2d");ra.fillStyle="rgba(0,0,0,1)";ra.fillRect(0,0,2,2);za=ra.getImageData(0,0,2,2);ba=za.data;sa=document.createElement("canvas");sa.width=sa.height=a;va=sa.getContext("2d");va.translate(-a/2,-a/2);va.scale(a,a);a--;this.domElement=j;this.sortElements=this.sortObjects=this.autoClear=!0;this.info={render:{vertices:0,faces:0}};this.setSize=function(a,b){i=a;n=b;o=Math.floor(i/2);p=Math.floor(n/2);j.width=i;j.height=n;ma.set(-o,-p,o,p);Z.set(-o,-p,o,p);C=1;Q=0;
D=z=F=w=O=null};this.setClearColor=function(a,b){s.copy(a);K=b;Z.set(-o,-p,o,p)};this.setClearColorHex=function(a,b){s.setHex(a);K=b;Z.set(-o,-p,o,p)};this.clear=function(){k.setTransform(1,0,0,-1,o,p);Z.isEmpty()||(Z.minSelf(ma),Z.inflate(2),K<1&&k.clearRect(Math.floor(Z.getX()),Math.floor(Z.getY()),Math.floor(Z.getWidth()),Math.floor(Z.getHeight())),K>0&&(c(THREE.NormalBlending),b(1),f("rgba("+Math.floor(s.r*255)+","+Math.floor(s.g*255)+","+Math.floor(s.b*255)+","+K+")"),k.fillRect(Math.floor(Z.getX()),
Math.floor(Z.getY()),Math.floor(Z.getWidth()),Math.floor(Z.getHeight()))),Z.empty())};this.render=function(a,j){function i(a){var b,c,d,e;$.setRGB(0,0,0);ta.setRGB(0,0,0);ua.setRGB(0,0,0);b=0;for(c=a.length;b<c;b++)d=a[b],e=d.color,d instanceof THREE.AmbientLight?($.r+=e.r,$.g+=e.g,$.b+=e.b):d instanceof THREE.DirectionalLight?(ta.r+=e.r,ta.g+=e.g,ta.b+=e.b):d instanceof THREE.PointLight&&(ua.r+=e.r,ua.g+=e.g,ua.b+=e.b)}function n(a,b,c,d){var e,f,g,h,k,j;e=0;for(f=a.length;e<f;e++)g=a[e],h=g.color,
g instanceof THREE.DirectionalLight?(k=g.matrixWorld.getPosition(),j=c.dot(k),j<=0||(j*=g.intensity,d.r+=h.r*j,d.g+=h.g*j,d.b+=h.b*j)):g instanceof THREE.PointLight&&(k=g.matrixWorld.getPosition(),j=c.dot(T.sub(k,b).normalize()),j<=0||(j*=g.distance==0?1:1-Math.min(b.distanceTo(k)/g.distance,1),j!=0&&(j*=g.intensity,d.r+=h.r*j,d.g+=h.g*j,d.b+=h.b*j)))}function s(a,e,g){b(g.opacity);c(g.blending);var h,j,i,m,q,n;if(g instanceof THREE.ParticleBasicMaterial){if(g.map)m=g.map.image,q=m.width>>1,n=m.height>>
1,g=e.scale.x*o,i=e.scale.y*p,h=g*q,j=i*n,X.set(a.x-h,a.y-j,a.x+h,a.y+j),ma.intersects(X)&&(k.save(),k.translate(a.x,a.y),k.rotate(-e.rotation),k.scale(g,-i),k.translate(-q,-n),k.drawImage(m,0,0),k.restore())}else g instanceof THREE.ParticleCanvasMaterial&&(h=e.scale.x*o,j=e.scale.y*p,X.set(a.x-h,a.y-j,a.x+h,a.y+j),ma.intersects(X)&&(d(g.color.getContextStyle()),f(g.color.getContextStyle()),k.save(),k.translate(a.x,a.y),k.rotate(-e.rotation),k.scale(h,j),g.program(k),k.restore()))}function w(a,e,
f,g){b(g.opacity);c(g.blending);k.beginPath();k.moveTo(a.positionScreen.x,a.positionScreen.y);k.lineTo(e.positionScreen.x,e.positionScreen.y);k.closePath();if(g instanceof THREE.LineBasicMaterial){a=g.linewidth;if(F!=a)k.lineWidth=F=a;a=g.linecap;if(z!=a)k.lineCap=z=a;a=g.linejoin;if(D!=a)k.lineJoin=D=a;d(g.color.getContextStyle());k.stroke();X.inflate(g.linewidth*2)}}function C(a,d,f,g,h,k,i,q){e.info.render.vertices+=3;e.info.render.faces++;b(q.opacity);c(q.blending);G=a.positionScreen.x;H=a.positionScreen.y;
I=d.positionScreen.x;Y=d.positionScreen.y;L=f.positionScreen.x;B=f.positionScreen.y;K(G,H,I,Y,L,B);if(q instanceof THREE.MeshBasicMaterial)if(q.map)q.map.mapping instanceof THREE.UVMapping&&(aa=i.uvs[0],Aa(G,H,I,Y,L,B,aa[g].u,aa[g].v,aa[h].u,aa[h].v,aa[k].u,aa[k].v,q.map));else if(q.envMap){if(q.envMap.mapping instanceof THREE.SphericalReflectionMapping)a=j.matrixWorldInverse,T.copy(i.vertexNormalsWorld[g]),Ba=(T.x*a.n11+T.y*a.n12+T.z*a.n13)*0.5+0.5,Ca=-(T.x*a.n21+T.y*a.n22+T.z*a.n23)*0.5+0.5,T.copy(i.vertexNormalsWorld[h]),
Da=(T.x*a.n11+T.y*a.n12+T.z*a.n13)*0.5+0.5,Ea=-(T.x*a.n21+T.y*a.n22+T.z*a.n23)*0.5+0.5,T.copy(i.vertexNormalsWorld[k]),Fa=(T.x*a.n11+T.y*a.n12+T.z*a.n13)*0.5+0.5,Ga=-(T.x*a.n21+T.y*a.n22+T.z*a.n23)*0.5+0.5,Aa(G,H,I,Y,L,B,Ba,Ca,Da,Ea,Fa,Ga,q.envMap)}else q.wireframe?ja(q.color,q.wireframeLinewidth,q.wireframeLinecap,q.wireframeLinejoin):ia(q.color);else if(q instanceof THREE.MeshLambertMaterial)q.map&&!q.wireframe&&(q.map.mapping instanceof THREE.UVMapping&&(aa=i.uvs[0],Aa(G,H,I,Y,L,B,aa[g].u,aa[g].v,
aa[h].u,aa[h].v,aa[k].u,aa[k].v,q.map)),c(THREE.SubtractiveBlending)),ya?!q.wireframe&&q.shading==THREE.SmoothShading&&i.vertexNormalsWorld.length==3?(A.r=x.r=y.r=$.r,A.g=x.g=y.g=$.g,A.b=x.b=y.b=$.b,n(m,i.v1.positionWorld,i.vertexNormalsWorld[0],A),n(m,i.v2.positionWorld,i.vertexNormalsWorld[1],x),n(m,i.v3.positionWorld,i.vertexNormalsWorld[2],y),A.r=Math.max(0,Math.min(q.color.r*A.r,1)),A.g=Math.max(0,Math.min(q.color.g*A.g,1)),A.b=Math.max(0,Math.min(q.color.b*A.b,1)),x.r=Math.max(0,Math.min(q.color.r*
x.r,1)),x.g=Math.max(0,Math.min(q.color.g*x.g,1)),x.b=Math.max(0,Math.min(q.color.b*x.b,1)),y.r=Math.max(0,Math.min(q.color.r*y.r,1)),y.g=Math.max(0,Math.min(q.color.g*y.g,1)),y.b=Math.max(0,Math.min(q.color.b*y.b,1)),M.r=(x.r+y.r)*0.5,M.g=(x.g+y.g)*0.5,M.b=(x.b+y.b)*0.5,ea=wa(A,x,y,M),oa(G,H,I,Y,L,B,0,0,1,0,0,1,ea)):(t.r=$.r,t.g=$.g,t.b=$.b,n(m,i.centroidWorld,i.normalWorld,t),t.r=Math.max(0,Math.min(q.color.r*t.r,1)),t.g=Math.max(0,Math.min(q.color.g*t.g,1)),t.b=Math.max(0,Math.min(q.color.b*t.b,
1)),q.wireframe?ja(t,q.wireframeLinewidth,q.wireframeLinecap,q.wireframeLinejoin):ia(t)):q.wireframe?ja(q.color,q.wireframeLinewidth,q.wireframeLinecap,q.wireframeLinejoin):ia(q.color);else if(q instanceof THREE.MeshDepthMaterial)ga=j.near,ha=j.far,A.r=A.g=A.b=1-na(a.positionScreen.z,ga,ha),x.r=x.g=x.b=1-na(d.positionScreen.z,ga,ha),y.r=y.g=y.b=1-na(f.positionScreen.z,ga,ha),M.r=(x.r+y.r)*0.5,M.g=(x.g+y.g)*0.5,M.b=(x.b+y.b)*0.5,ea=wa(A,x,y,M),oa(G,H,I,Y,L,B,0,0,1,0,0,1,ea);else if(q instanceof THREE.MeshNormalMaterial)t.r=
pa(i.normalWorld.x),t.g=pa(i.normalWorld.y),t.b=pa(i.normalWorld.z),q.wireframe?ja(t,q.wireframeLinewidth,q.wireframeLinecap,q.wireframeLinejoin):ia(t)}function Q(a,d,f,g,h,k,i,q,o){e.info.render.vertices+=4;e.info.render.faces++;b(q.opacity);c(q.blending);if(q.map||q.envMap)C(a,d,g,0,1,3,i,q,o),C(h,f,k,1,2,3,i,q,o);else if(G=a.positionScreen.x,H=a.positionScreen.y,I=d.positionScreen.x,Y=d.positionScreen.y,L=f.positionScreen.x,B=f.positionScreen.y,S=g.positionScreen.x,v=g.positionScreen.y,R=h.positionScreen.x,
P=h.positionScreen.y,V=k.positionScreen.x,J=k.positionScreen.y,q instanceof THREE.MeshBasicMaterial)O(G,H,I,Y,L,B,S,v),q.wireframe?ja(q.color,q.wireframeLinewidth,q.wireframeLinecap,q.wireframeLinejoin):ia(q.color);else if(q instanceof THREE.MeshLambertMaterial)ya?!q.wireframe&&q.shading==THREE.SmoothShading&&i.vertexNormalsWorld.length==4?(A.r=x.r=y.r=M.r=$.r,A.g=x.g=y.g=M.g=$.g,A.b=x.b=y.b=M.b=$.b,n(m,i.v1.positionWorld,i.vertexNormalsWorld[0],A),n(m,i.v2.positionWorld,i.vertexNormalsWorld[1],x),
n(m,i.v4.positionWorld,i.vertexNormalsWorld[3],y),n(m,i.v3.positionWorld,i.vertexNormalsWorld[2],M),A.r=Math.max(0,Math.min(q.color.r*A.r,1)),A.g=Math.max(0,Math.min(q.color.g*A.g,1)),A.b=Math.max(0,Math.min(q.color.b*A.b,1)),x.r=Math.max(0,Math.min(q.color.r*x.r,1)),x.g=Math.max(0,Math.min(q.color.g*x.g,1)),x.b=Math.max(0,Math.min(q.color.b*x.b,1)),y.r=Math.max(0,Math.min(q.color.r*y.r,1)),y.g=Math.max(0,Math.min(q.color.g*y.g,1)),y.b=Math.max(0,Math.min(q.color.b*y.b,1)),M.r=Math.max(0,Math.min(q.color.r*
M.r,1)),M.g=Math.max(0,Math.min(q.color.g*M.g,1)),M.b=Math.max(0,Math.min(q.color.b*M.b,1)),ea=wa(A,x,y,M),K(G,H,I,Y,S,v),oa(G,H,I,Y,S,v,0,0,1,0,0,1,ea),K(R,P,L,B,V,J),oa(R,P,L,B,V,J,1,0,1,1,0,1,ea)):(t.r=$.r,t.g=$.g,t.b=$.b,n(m,i.centroidWorld,i.normalWorld,t),t.r=Math.max(0,Math.min(q.color.r*t.r,1)),t.g=Math.max(0,Math.min(q.color.g*t.g,1)),t.b=Math.max(0,Math.min(q.color.b*t.b,1)),O(G,H,I,Y,L,B,S,v),q.wireframe?ja(t,q.wireframeLinewidth,q.wireframeLinecap,q.wireframeLinejoin):ia(t)):(O(G,H,I,
Y,L,B,S,v),q.wireframe?ja(q.color,q.wireframeLinewidth,q.wireframeLinecap,q.wireframeLinejoin):ia(q.color));else if(q instanceof THREE.MeshNormalMaterial)t.r=pa(i.normalWorld.x),t.g=pa(i.normalWorld.y),t.b=pa(i.normalWorld.z),O(G,H,I,Y,L,B,S,v),q.wireframe?ja(t,q.wireframeLinewidth,q.wireframeLinecap,q.wireframeLinejoin):ia(t);else if(q instanceof THREE.MeshDepthMaterial)ga=j.near,ha=j.far,A.r=A.g=A.b=1-na(a.positionScreen.z,ga,ha),x.r=x.g=x.b=1-na(d.positionScreen.z,ga,ha),y.r=y.g=y.b=1-na(g.positionScreen.z,
ga,ha),M.r=M.g=M.b=1-na(f.positionScreen.z,ga,ha),ea=wa(A,x,y,M),K(G,H,I,Y,S,v),oa(G,H,I,Y,S,v,0,0,1,0,0,1,ea),K(R,P,L,B,V,J),oa(R,P,L,B,V,J,1,0,1,1,0,1,ea)}function K(a,b,c,d,e,f){k.beginPath();k.moveTo(a,b);k.lineTo(c,d);k.lineTo(e,f);k.lineTo(a,b);k.closePath()}function O(a,b,c,d,e,f,g,h){k.beginPath();k.moveTo(a,b);k.lineTo(c,d);k.lineTo(e,f);k.lineTo(g,h);k.lineTo(a,b);k.closePath()}function ja(a,b,c,e){if(F!=b)k.lineWidth=F=b;if(z!=c)k.lineCap=z=c;if(D!=e)k.lineJoin=D=e;d(a.getContextStyle());
k.stroke();X.inflate(b*2)}function ia(a){f(a.getContextStyle());k.fill()}function Aa(a,b,c,d,e,g,h,i,j,m,o,n,l){if(l.image.width!=0){if(l.needsUpdate==!0||la[l.id]==void 0){var p=l.wrapS==THREE.RepeatWrapping,r=l.wrapT==THREE.RepeatWrapping;la[l.id]=k.createPattern(l.image,p&&r?"repeat":p&&!r?"repeat-x":!p&&r?"repeat-y":"no-repeat");l.needsUpdate=!1}f(la[l.id]);var p=l.offset.x/l.repeat.x,r=l.offset.y/l.repeat.y,s=l.image.width*l.repeat.x,u=l.image.height*l.repeat.y,h=(h+p)*s,i=(i+r)*u,j=(j+p)*s,
m=(m+r)*u,o=(o+p)*s,n=(n+r)*u;c-=a;d-=b;e-=a;g-=b;j-=h;m-=i;o-=h;n-=i;p=j*n-o*m;if(p==0){if(fa[l.id]==void 0)b=document.createElement("canvas"),b.width=l.image.width,b.height=l.image.height,a=b.getContext("2d"),a.drawImage(l.image,0,0),fa[l.id]=a.getImageData(0,0,l.image.width,l.image.height).data,delete b;b=fa[l.id];h=(Math.floor(h)+Math.floor(i)*l.image.width)*4;t.setRGB(b[h]/255,b[h+1]/255,b[h+2]/255);ia(t)}else p=1/p,l=(n*c-m*e)*p,m=(n*d-m*g)*p,c=(j*e-o*c)*p,d=(j*g-o*d)*p,a=a-l*h-c*i,h=b-m*h-
d*i,k.save(),k.transform(l,m,c,d,a,h),k.fill(),k.restore()}}function oa(a,b,c,d,e,f,g,h,i,j,l,m,o){var n,p;n=o.width-1;p=o.height-1;g*=n;h*=p;i*=n;j*=p;l*=n;m*=p;c-=a;d-=b;e-=a;f-=b;i-=g;j-=h;l-=g;m-=h;p=1/(i*m-l*j);n=(m*c-j*e)*p;j=(m*d-j*f)*p;c=(i*e-l*c)*p;d=(i*f-l*d)*p;a=a-n*g-c*h;b=b-j*g-d*h;k.save();k.transform(n,j,c,d,a,b);k.clip();k.drawImage(o,0,0);k.restore()}function wa(a,b,c,d){var e=~~(a.r*255),f=~~(a.g*255),a=~~(a.b*255),g=~~(b.r*255),h=~~(b.g*255),b=~~(b.b*255),i=~~(c.r*255),j=~~(c.g*
255),c=~~(c.b*255),k=~~(d.r*255),l=~~(d.g*255),d=~~(d.b*255);ba[0]=e<0?0:e>255?255:e;ba[1]=f<0?0:f>255?255:f;ba[2]=a<0?0:a>255?255:a;ba[4]=g<0?0:g>255?255:g;ba[5]=h<0?0:h>255?255:h;ba[6]=b<0?0:b>255?255:b;ba[8]=i<0?0:i>255?255:i;ba[9]=j<0?0:j>255?255:j;ba[10]=c<0?0:c>255?255:c;ba[12]=k<0?0:k>255?255:k;ba[13]=l<0?0:l>255?255:l;ba[14]=d<0?0:d>255?255:d;ra.putImageData(za,0,0);va.drawImage(qa,0,0);return sa}function na(a,b,c){a=(a-b)/(c-b);return a*a*(3-2*a)}function pa(a){a=(a+1)*0.5;return a<0?0:a>
1?1:a}function ka(a,b){var c=b.x-a.x,d=b.y-a.y,e=c*c+d*d;e!=0&&(e=1/Math.sqrt(e),c*=e,d*=e,b.x+=c,b.y+=d,a.x-=c,a.y-=d)}var xa,Ha,U,ca;this.autoClear?this.clear():k.setTransform(1,0,0,-1,o,p);e.info.render.vertices=0;e.info.render.faces=0;g=l.projectScene(a,j,this.sortElements);h=g.elements;m=g.lights;(ya=m.length>0)&&i(m);xa=0;for(Ha=h.length;xa<Ha;xa++)if(U=h[xa],ca=U.material,ca=ca instanceof THREE.MeshFaceMaterial?U.faceMaterial:ca,!(ca==null||ca.opacity==0)){X.empty();if(U instanceof THREE.RenderableParticle)u=
U,u.x*=o,u.y*=p,s(u,U,ca,a);else if(U instanceof THREE.RenderableLine)u=U.v1,r=U.v2,u.positionScreen.x*=o,u.positionScreen.y*=p,r.positionScreen.x*=o,r.positionScreen.y*=p,X.addPoint(u.positionScreen.x,u.positionScreen.y),X.addPoint(r.positionScreen.x,r.positionScreen.y),ma.intersects(X)&&w(u,r,U,ca,a);else if(U instanceof THREE.RenderableFace3)u=U.v1,r=U.v2,E=U.v3,u.positionScreen.x*=o,u.positionScreen.y*=p,r.positionScreen.x*=o,r.positionScreen.y*=p,E.positionScreen.x*=o,E.positionScreen.y*=p,ca.overdraw&&
(ka(u.positionScreen,r.positionScreen),ka(r.positionScreen,E.positionScreen),ka(E.positionScreen,u.positionScreen)),X.add3Points(u.positionScreen.x,u.positionScreen.y,r.positionScreen.x,r.positionScreen.y,E.positionScreen.x,E.positionScreen.y),ma.intersects(X)&&C(u,r,E,0,1,2,U,ca,a);else if(U instanceof THREE.RenderableFace4)u=U.v1,r=U.v2,E=U.v3,N=U.v4,u.positionScreen.x*=o,u.positionScreen.y*=p,r.positionScreen.x*=o,r.positionScreen.y*=p,E.positionScreen.x*=o,E.positionScreen.y*=p,N.positionScreen.x*=
o,N.positionScreen.y*=p,W.positionScreen.copy(r.positionScreen),da.positionScreen.copy(N.positionScreen),ca.overdraw&&(ka(u.positionScreen,r.positionScreen),ka(r.positionScreen,N.positionScreen),ka(N.positionScreen,u.positionScreen),ka(E.positionScreen,W.positionScreen),ka(E.positionScreen,da.positionScreen)),X.addPoint(u.positionScreen.x,u.positionScreen.y),X.addPoint(r.positionScreen.x,r.positionScreen.y),X.addPoint(E.positionScreen.x,E.positionScreen.y),X.addPoint(N.positionScreen.x,N.positionScreen.y),
ma.intersects(X)&&Q(u,r,E,N,W,da,U,ca,a);Z.addRectangle(X)}k.setTransform(1,0,0,1,0,0)}};THREE.RenderableVertex=function(){this.positionWorld=new THREE.Vector3;this.positionScreen=new THREE.Vector4;this.visible=!0};THREE.RenderableVertex.prototype.copy=function(a){this.positionWorld.copy(a.positionWorld);this.positionScreen.copy(a.positionScreen)};
THREE.RenderableFace3=function(){this.v1=new THREE.RenderableVertex;this.v2=new THREE.RenderableVertex;this.v3=new THREE.RenderableVertex;this.centroidWorld=new THREE.Vector3;this.centroidScreen=new THREE.Vector3;this.normalWorld=new THREE.Vector3;this.vertexNormalsWorld=[new THREE.Vector3,new THREE.Vector3,new THREE.Vector3];this.faceMaterial=this.material=null;this.uvs=[[]];this.z=null};
THREE.RenderableFace4=function(){this.v1=new THREE.RenderableVertex;this.v2=new THREE.RenderableVertex;this.v3=new THREE.RenderableVertex;this.v4=new THREE.RenderableVertex;this.centroidWorld=new THREE.Vector3;this.centroidScreen=new THREE.Vector3;this.normalWorld=new THREE.Vector3;this.vertexNormalsWorld=[new THREE.Vector3,new THREE.Vector3,new THREE.Vector3,new THREE.Vector3];this.faceMaterial=this.material=null;this.uvs=[[]];this.z=null};THREE.RenderableObject=function(){this.z=this.object=null};
THREE.RenderableParticle=function(){this.rotation=this.z=this.y=this.x=null;this.scale=new THREE.Vector2;this.material=null};THREE.RenderableLine=function(){this.z=null;this.v1=new THREE.RenderableVertex;this.v2=new THREE.RenderableVertex;this.material=null};
| 74,750
| 37,414
|
const BudgetType = require('./BudgetType');
class SplitBudget extends BudgetType {
get priority() {
return this.config.priority || 200;
}
run(runningBalance) {
if (runningBalance <= 0) {
this.addDebugMessage('We have no running balance to use!');
return this.setValue(0, (this.config.failOnEmpty === false) ? 'warning' : 'failed');
}
return this.setValue(runningBalance, 'success');
}
}
module.exports = SplitBudget;
| 458
| 155
|
import React from 'react'
import {connect} from 'react-redux'
import {fetchProducts} from '../store/allProducts'
import ProductView from './ProductView'
export class AllProducts extends React.Component {
constructor() {
super()
this.state = {sort: 'random', filter: 'all'}
this.handleChange = this.handleChange.bind(this)
this.handleFilter = this.handleFilter.bind(this)
}
componentDidMount() {
if (this.props.loadProducts) this.props.loadProducts()
}
handleChange(event) {
this.setState({sort: event.target.value})
}
handleFilter(event) {
this.setState({filter: event.target.value})
}
render() {
let filteredProducts = this.props.products
//Logic for filtering and sorting below
if (this.state.filter === 'rats') {
filteredProducts = filteredProducts.filter(p => {
return p.sex
})
}
if (this.state.filter === 'accessories') {
filteredProducts = filteredProducts.filter(p => {
return !p.sex
})
}
if (this.state.sort === 'highLow') {
filteredProducts.sort((a, b) => {
return a.price < b.price ? 1 : -1
})
}
if (this.state.sort === 'lowHigh') {
filteredProducts.sort((a, b) => {
return a.price > b.price ? 1 : -1
})
}
return (
<div className="allProducts">
<div id="productViews">
{filteredProducts
? filteredProducts.map(product => {
return (
<ProductView
product={product}
key={product.id}
isAdmin={this.props.user.isAdmin}
/>
)
})
: ''}
</div>
<div id="sortFilter">
<div>
<h3>Sort:</h3>
<select value={this.state.sort} onChange={this.handleChange}>
<option value="random">Any order</option>
<option value="highLow">Price (high-low)</option>
<option value="lowHigh">Price (low-high)</option>
</select>
</div>
<div>
<h3>Filter:</h3>
<select value={this.state.filter} onChange={this.handleFilter}>
<option value="all">All products</option>
<option value="rats">Rats for adoption</option>
<option value="accessories">Rat accessories</option>
</select>
</div>
</div>
</div>
)
}
}
const mapState = state => {
return {
products: state.products,
user: state.user
}
}
const mapDispatch = dispatch => {
return {
loadProducts: () => {
dispatch(fetchProducts())
}
}
}
export default connect(mapState, mapDispatch)(AllProducts)
| 2,750
| 810
|
/*!
* jQuery JavaScript Library v2.1.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-05-01T17:11Z
*/
(function (global, factory) {
if (typeof module === "object" && typeof module.exports === "object") {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory(global, true) :
function (w) {
if (!w.document) {
throw new Error("jQuery requires a window with a document");
}
return factory(w);
};
} else {
factory(global);
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var arr = [];
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.1",
// Define a local copy of jQuery
jQuery = function (selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init(selector, context);
},
// Support: Android<4.1
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function (all, letter) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function () {
return slice.call(this);
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function (num) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[num + this.length] : this[num] ) :
// Return all the elements in a clean array
slice.call(this);
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function (elems) {
// Build a new jQuery matched element set
var ret = jQuery.merge(this.constructor(), elems);
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function (callback, args) {
return jQuery.each(this, callback, args);
},
map: function (callback) {
return this.pushStack(jQuery.map(this, function (elem, i) {
return callback.call(elem, i, elem);
}));
},
slice: function () {
return this.pushStack(slice.apply(this, arguments));
},
first: function () {
return this.eq(0);
},
last: function () {
return this.eq(-1);
},
eq: function (i) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack(j >= 0 && j < len ? [this[j]] : []);
},
end: function () {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function () {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
// skip the boolean and the target
target = arguments[i] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !jQuery.isFunction(target)) {
target = {};
}
// extend jQuery itself if only one argument is passed
if (i === length) {
target = this;
i--;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging plain objects or arrays
if (deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) )) {
if (copyIsArray) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = jQuery.extend(deep, clone, copy);
// Don't bring in undefined values
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace(/\D/g, ""),
// Assume jQuery is ready without the ready module
isReady: true,
error: function (msg) {
throw new Error(msg);
},
noop: function () {
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function (obj) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function (obj) {
return obj != null && obj === obj.window;
},
isNumeric: function (obj) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return !jQuery.isArray(obj) && obj - parseFloat(obj) >= 0;
},
isPlainObject: function (obj) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if (jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
return false;
}
if (obj.constructor && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function (obj) {
var name;
for (name in obj) {
return false;
}
return true;
},
type: function (obj) {
if (obj == null) {
return obj + "";
}
// Support: Android < 4.0, iOS < 6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[toString.call(obj)] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function (code) {
var script,
indirect = eval;
code = jQuery.trim(code);
if (code) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if (code.indexOf("use strict") === 1) {
script = document.createElement("script");
script.text = code;
document.head.appendChild(script).parentNode.removeChild(script);
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect(code);
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function (string) {
return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
},
nodeName: function (elem, name) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
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;
}
}
}
// A special, fast, case for the most common use of each
} 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;
},
// Support: Android<4.1
trim: function (text) {
return text == null ?
"" :
( text + "" ).replace(rtrim, "");
},
// results is for internal usage only
makeArray: function (arr, results) {
var ret = results || [];
if (arr != null) {
if (isArraylike(Object(arr))) {
jQuery.merge(ret,
typeof arr === "string" ?
[arr] : arr
);
} else {
push.call(ret, arr);
}
}
return ret;
},
inArray: function (elem, arr, i) {
return arr == null ? -1 : indexOf.call(arr, elem, i);
},
merge: function (first, second) {
var len = +second.length,
j = 0,
i = first.length;
for (; j < len; j++) {
first[i++] = second[j];
}
first.length = i;
return first;
},
grep: function (elems, callback, invert) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for (; i < length; i++) {
callbackInverse = !callback(elems[i], i);
if (callbackInverse !== callbackExpect) {
matches.push(elems[i]);
}
}
return matches;
},
// arg is for internal usage only
map: function (elems, callback, arg) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike(elems),
ret = [];
// Go through the array, translating each of the items to their new values
if (isArray) {
for (; i < length; i++) {
value = callback(elems[i], i, arg);
if (value != null) {
ret.push(value);
}
}
// Go through every key on the object,
} else {
for (i in elems) {
value = callback(elems[i], i, arg);
if (value != null) {
ret.push(value);
}
}
}
// Flatten any nested arrays
return concat.apply([], ret);
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function (fn, context) {
var tmp, args, proxy;
if (typeof context === "string") {
tmp = fn[context];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if (!jQuery.isFunction(fn)) {
return undefined;
}
// Simulated bind
args = slice.call(arguments, 2);
proxy = function () {
return fn.apply(context || this, args.concat(slice.call(arguments)));
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (i, name) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
function isArraylike(obj) {
var length = obj.length,
type = jQuery.type(obj);
if (type === "function" || jQuery.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;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.19
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-04-18
*/
(function (window) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function (a, b) {
if (a === b) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function (elem) {
var i = 0,
len = this.length;
for (; i < len; i++) {
if (this[i] === elem) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace("w", "w#"),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),
rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),
rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"),
rattributeQuotes = new RegExp("=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g"),
rpseudo = new RegExp(pseudos),
ridentifier = new RegExp("^" + identifier + "$"),
matchExpr = {
"ID": new RegExp("^#(" + characterEncoding + ")"),
"CLASS": new RegExp("^\\.(" + characterEncoding + ")"),
"TAG": new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"),
"ATTR": new RegExp("^" + attributes),
"PSEUDO": new RegExp("^" + pseudos),
"CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i"),
"bool": new RegExp("^(?:" + booleans + ")$", "i"),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp("\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig"),
funescape = function (_, escaped, escapedWhitespace) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode(high + 0x10000) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call(preferredDoc.childNodes)),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[preferredDoc.childNodes.length].nodeType;
} catch (e) {
push = {
apply: arr.length ?
// Leverage slice if possible
function (target, els) {
push_native.apply(target, slice.call(els));
} :
// Support: IE<9
// Otherwise append directly
function (target, els) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ((target[j++] = els[i++])) {
}
target.length = j - 1;
}
};
}
function Sizzle(selector, context, results, seed) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if (( context ? context.ownerDocument || context : preferredDoc ) !== document) {
setDocument(context);
}
context = context || document;
results = results || [];
if (!selector || typeof selector !== "string") {
return results;
}
if ((nodeType = context.nodeType) !== 1 && nodeType !== 9) {
return [];
}
if (documentIsHTML && !seed) {
// Shortcuts
if ((match = rquickExpr.exec(selector))) {
// Speed-up: Sizzle("#ID")
if ((m = match[1])) {
if (nodeType === 9) {
elem = context.getElementById(m);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if (elem && elem.parentNode) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if (elem.id === m) {
results.push(elem);
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) &&
contains(context, elem) && elem.id === m) {
results.push(elem);
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if (match[2]) {
push.apply(results, context.getElementsByTagName(selector));
return results;
// Speed-up: Sizzle(".CLASS")
} else if ((m = match[3]) && support.getElementsByClassName && context.getElementsByClassName) {
push.apply(results, context.getElementsByClassName(m));
return results;
}
}
// QSA path
if (support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if (nodeType === 1 && context.nodeName.toLowerCase() !== "object") {
groups = tokenize(selector);
if ((old = context.getAttribute("id"))) {
nid = old.replace(rescape, "\\$&");
} else {
context.setAttribute("id", nid);
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while (i--) {
groups[i] = nid + toSelector(groups[i]);
}
newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
newSelector = groups.join(",");
}
if (newSelector) {
try {
push.apply(results,
newContext.querySelectorAll(newSelector)
);
return results;
} catch (qsaError) {
} finally {
if (!old) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select(selector.replace(rtrim, "$1"), context, results, seed);
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache(key, value) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if (keys.push(key + " ") > Expr.cacheLength) {
// Only keep the most recent entries
delete cache[keys.shift()];
}
return (cache[key + " "] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction(fn) {
fn[expando] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert(fn) {
var div = document.createElement("div");
try {
return !!fn(div);
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if (div.parentNode) {
div.parentNode.removeChild(div);
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle(attrs, handler) {
var arr = attrs.split("|"),
i = attrs.length;
while (i--) {
Expr.attrHandle[arr[i]] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck(a, b) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if (diff) {
return diff;
}
// Check if b follows a
if (cur) {
while ((cur = cur.nextSibling)) {
if (cur === b) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo(type) {
return function (elem) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo(type) {
return function (elem) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo(fn) {
return markFunction(function (argument) {
argument = +argument;
return markFunction(function (seed, matches) {
var j,
matchIndexes = fn([], seed.length, argument),
i = matchIndexes.length;
// Match elements found at the specified indexes
while (i--) {
if (seed[(j = matchIndexes[i])]) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext(context) {
return context && typeof context.getElementsByTagName !== strundefined && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function (elem) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function (node) {
var hasCompare,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if (doc === document || doc.nodeType !== 9 || !doc.documentElement) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML(doc);
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if (parent && parent !== parent.top) {
// IE11 does not have attachEvent, so all must suffer
if (parent.addEventListener) {
parent.addEventListener("unload", function () {
setDocument();
}, false);
} else if (parent.attachEvent) {
parent.attachEvent("onunload", function () {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function (div) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function (div) {
div.appendChild(doc.createComment(""));
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test(doc.getElementsByClassName) && assert(function (div) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function (div) {
docElem.appendChild(div).id = expando;
return !doc.getElementsByName || !doc.getElementsByName(expando).length;
});
// ID find and filter
if (support.getById) {
Expr.find["ID"] = function (id, context) {
if (typeof context.getElementById !== strundefined && documentIsHTML) {
var m = context.getElementById(id);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function (id) {
var attrId = id.replace(runescape, funescape);
return function (elem) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function (id) {
var attrId = id.replace(runescape, funescape);
return function (elem) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function (tag, context) {
if (typeof context.getElementsByTagName !== strundefined) {
return context.getElementsByTagName(tag);
}
} :
function (tag, context) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName(tag);
// Filter out possible comments
if (tag === "*") {
while ((elem = results[i++])) {
if (elem.nodeType === 1) {
tmp.push(elem);
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function (className, context) {
if (typeof context.getElementsByClassName !== strundefined && documentIsHTML) {
return context.getElementsByClassName(className);
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ((support.qsa = rnative.test(doc.querySelectorAll))) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function (div) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select msallowclip=''><option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if (div.querySelectorAll("[msallowclip^='']").length) {
rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")");
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if (!div.querySelectorAll("[selected]").length) {
rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if (!div.querySelectorAll(":checked").length) {
rbuggyQSA.push(":checked");
}
});
assert(function (div) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute("type", "hidden");
div.appendChild(input).setAttribute("name", "D");
// Support: IE8
// Enforce case-sensitivity of name attribute
if (div.querySelectorAll("[name=d]").length) {
rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?=");
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if (!div.querySelectorAll(":enabled").length) {
rbuggyQSA.push(":enabled", ":disabled");
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ((support.matchesSelector = rnative.test((matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector)))) {
assert(function (div) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call(div, "div");
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call(div, "[s!='']:x");
rbuggyMatches.push("!=", pseudos);
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test(docElem.compareDocumentPosition);
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test(docElem.contains) ?
function (a, b) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains(bup) :
a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16
));
} :
function (a, b) {
if (b) {
while ((b = b.parentNode)) {
if (b === a) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function (a, b) {
// Flag for duplicate removal
if (a === b) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if (compare) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition(b) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if (compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition(a) === compare)) {
// Choose the first element that is related to our preferred document
if (a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a)) {
return -1;
}
if (b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b)) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call(sortInput, a) - indexOf.call(sortInput, b) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function (a, b) {
// Exit early if the nodes are identical
if (a === b) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [a],
bp = [b];
// Parentless nodes are either documents or disconnected
if (!aup || !bup) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call(sortInput, a) - indexOf.call(sortInput, b) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if (aup === bup) {
return siblingCheck(a, b);
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ((cur = cur.parentNode)) {
ap.unshift(cur);
}
cur = b;
while ((cur = cur.parentNode)) {
bp.unshift(cur);
}
// Walk down the tree looking for a discrepancy
while (ap[i] === bp[i]) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck(ap[i], bp[i]) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function (expr, elements) {
return Sizzle(expr, null, null, elements);
};
Sizzle.matchesSelector = function (elem, expr) {
// Set document vars if needed
if (( elem.ownerDocument || elem ) !== document) {
setDocument(elem);
}
// Make sure that attribute selectors are quoted
expr = expr.replace(rattributeQuotes, "='$1']");
if (support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test(expr) ) &&
( !rbuggyQSA || !rbuggyQSA.test(expr) )) {
try {
var ret = matches.call(elem, expr);
// IE 9's matchesSelector returns false on disconnected nodes
if (ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11) {
return ret;
}
} catch (e) {
}
}
return Sizzle(expr, document, null, [elem]).length > 0;
};
Sizzle.contains = function (context, elem) {
// Set document vars if needed
if (( context.ownerDocument || context ) !== document) {
setDocument(context);
}
return contains(context, elem);
};
Sizzle.attr = function (elem, name) {
// Set document vars if needed
if (( elem.ownerDocument || elem ) !== document) {
setDocument(elem);
}
var fn = Expr.attrHandle[name.toLowerCase()],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ?
fn(elem, name, !documentIsHTML) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute(name) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function (msg) {
throw new Error("Syntax error, unrecognized expression: " + msg);
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function (results) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice(0);
results.sort(sortOrder);
if (hasDuplicate) {
while ((elem = results[i++])) {
if (elem === results[i]) {
j = duplicates.push(i);
}
}
while (j--) {
results.splice(duplicates[j], 1);
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function (elem) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if (!nodeType) {
// If no nodeType, this is expected to be an array
while ((node = elem[i++])) {
// Do not traverse comment nodes
ret += getText(node);
}
} else if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if (typeof elem.textContent === "string") {
return elem.textContent;
} else {
// Traverse its children
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText(elem);
}
}
} else if (nodeType === 3 || nodeType === 4) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": {dir: "parentNode", first: true},
" ": {dir: "parentNode"},
"+": {dir: "previousSibling", first: true},
"~": {dir: "previousSibling"}
},
preFilter: {
"ATTR": function (match) {
match[1] = match[1].replace(runescape, funescape);
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace(runescape, funescape);
if (match[2] === "~=") {
match[3] = " " + match[3] + " ";
}
return match.slice(0, 4);
},
"CHILD": function (match) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if (match[1].slice(0, 3) === "nth") {
// nth-* requires argument
if (!match[3]) {
Sizzle.error(match[0]);
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if (match[3]) {
Sizzle.error(match[0]);
}
return match;
},
"PSEUDO": function (match) {
var excess,
unquoted = !match[6] && match[2];
if (matchExpr["CHILD"].test(match[0])) {
return null;
}
// Accept quoted arguments as-is
if (match[3]) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if (unquoted && rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize(unquoted, true)) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
// excess is a negative index
match[0] = match[0].slice(0, excess);
match[2] = unquoted.slice(0, excess);
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice(0, 3);
}
},
filter: {
"TAG": function (nodeNameSelector) {
var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
return nodeNameSelector === "*" ?
function () {
return true;
} :
function (elem) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function (className) {
var pattern = classCache[className + " "];
return pattern ||
(pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) &&
classCache(className, function (elem) {
return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "");
});
},
"ATTR": function (name, operator, check) {
return function (elem) {
var result = Sizzle.attr(elem, name);
if (result == null) {
return operator === "!=";
}
if (!operator) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf(check) === 0 :
operator === "*=" ? check && result.indexOf(check) > -1 :
operator === "$=" ? check && result.slice(-check.length) === check :
operator === "~=" ? ( " " + result + " " ).indexOf(check) > -1 :
operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" :
false;
};
},
"CHILD": function (type, what, argument, first, last) {
var simple = type.slice(0, 3) !== "nth",
forward = type.slice(-4) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function (elem) {
return !!elem.parentNode;
} :
function (elem, context, xml) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if (parent) {
// :(first|last|only)-(child|of-type)
if (simple) {
while (dir) {
node = elem;
while ((node = node[dir])) {
if (ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [forward ? parent.firstChild : parent.lastChild];
// non-xml :nth-child(...) stores cache data on `parent`
if (forward && useCache) {
// Seek `elem` from a previously-cached index
outerCache = parent[expando] || (parent[expando] = {});
cache = outerCache[type] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[nodeIndex];
while ((node = ++nodeIndex && node && node[dir] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop())) {
// When found, cache indexes on `parent` and break
if (node.nodeType === 1 && ++diff && node === elem) {
outerCache[type] = [dirruns, nodeIndex, diff];
break;
}
}
// Use previously-cached element index if available
} else if (useCache && (cache = (elem[expando] || (elem[expando] = {}))[type]) && cache[0] === dirruns) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ((node = ++nodeIndex && node && node[dir] ||
(diff = nodeIndex = 0) || start.pop())) {
if (( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff) {
// Cache the index of each encountered element
if (useCache) {
(node[expando] || (node[expando] = {}))[type] = [dirruns, diff];
}
if (node === elem) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function (pseudo, argument) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] ||
Sizzle.error("unsupported pseudo: " + pseudo);
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if (fn[expando]) {
return fn(argument);
}
// But maintain support for old signatures
if (fn.length > 1) {
args = [pseudo, pseudo, "", argument];
return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ?
markFunction(function (seed, matches) {
var idx,
matched = fn(seed, argument),
i = matched.length;
while (i--) {
idx = indexOf.call(seed, matched[i]);
seed[idx] = !( matches[idx] = matched[i] );
}
}) :
function (elem) {
return fn(elem, 0, args);
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function (selector) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile(selector.replace(rtrim, "$1"));
return matcher[expando] ?
markFunction(function (seed, matches, context, xml) {
var elem,
unmatched = matcher(seed, null, xml, []),
i = seed.length;
// Match elements unmatched by `matcher`
while (i--) {
if ((elem = unmatched[i])) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function (elem, context, xml) {
input[0] = elem;
matcher(input, null, xml, results);
return !results.pop();
};
}),
"has": markFunction(function (selector) {
return function (elem) {
return Sizzle(selector, elem).length > 0;
};
}),
"contains": markFunction(function (text) {
return function (elem) {
return ( elem.textContent || elem.innerText || getText(elem) ).indexOf(text) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction(function (lang) {
// lang value must be a valid identifier
if (!ridentifier.test(lang || "")) {
Sizzle.error("unsupported lang: " + lang);
}
lang = lang.replace(runescape, funescape).toLowerCase();
return function (elem) {
var elemLang;
do {
if ((elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang"))) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
}
} while ((elem = elem.parentNode) && elem.nodeType === 1);
return false;
};
}),
// Miscellaneous
"target": function (elem) {
var hash = window.location && window.location.hash;
return hash && hash.slice(1) === elem.id;
},
"root": function (elem) {
return elem === docElem;
},
"focus": function (elem) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function (elem) {
return elem.disabled === false;
},
"disabled": function (elem) {
return elem.disabled === true;
},
"checked": function (elem) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function (elem) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if (elem.parentNode) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function (elem) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
if (elem.nodeType < 6) {
return false;
}
}
return true;
},
"parent": function (elem) {
return !Expr.pseudos["empty"](elem);
},
// Element/input types
"header": function (elem) {
return rheader.test(elem.nodeName);
},
"input": function (elem) {
return rinputs.test(elem.nodeName);
},
"button": function (elem) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function (elem) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function () {
return [0];
}),
"last": createPositionalPseudo(function (matchIndexes, length) {
return [length - 1];
}),
"eq": createPositionalPseudo(function (matchIndexes, length, argument) {
return [argument < 0 ? argument + length : argument];
}),
"even": createPositionalPseudo(function (matchIndexes, length) {
var i = 0;
for (; i < length; i += 2) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function (matchIndexes, length) {
var i = 1;
for (; i < length; i += 2) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function (matchIndexes, length, argument) {
var i = argument < 0 ? argument + length : argument;
for (; --i >= 0;) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function (matchIndexes, length, argument) {
var i = argument < 0 ? argument + length : argument;
for (; ++i < length;) {
matchIndexes.push(i);
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for (i in {
radio: true,
checkbox: true,
file: true,
password: true,
image: true
}) {
Expr.pseudos[i] = createInputPseudo(i);
}
for (i in {submit: true, reset: true}) {
Expr.pseudos[i] = createButtonPseudo(i);
}
// Easy API for creating new setFilters
function setFilters() {
}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function (selector, parseOnly) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[selector + " "];
if (cached) {
return parseOnly ? 0 : cached.slice(0);
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while (soFar) {
// Comma and first run
if (!matched || (match = rcomma.exec(soFar))) {
if (match) {
// Don't consume trailing commas as valid
soFar = soFar.slice(match[0].length) || soFar;
}
groups.push((tokens = []));
}
matched = false;
// Combinators
if ((match = rcombinators.exec(soFar))) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace(rtrim, " ")
});
soFar = soFar.slice(matched.length);
}
// Filters
for (type in Expr.filter) {
if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] ||
(match = preFilters[type](match)))) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice(matched.length);
}
}
if (!matched) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error(selector) :
// Cache the tokens
tokenCache(selector, groups).slice(0);
};
function toSelector(tokens) {
var i = 0,
len = tokens.length,
selector = "";
for (; i < len; i++) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator(matcher, combinator, base) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function (elem, context, xml) {
while ((elem = elem[dir])) {
if (elem.nodeType === 1 || checkNonElements) {
return matcher(elem, context, xml);
}
}
} :
// Check against all ancestor/preceding elements
function (elem, context, xml) {
var oldCache, outerCache,
newCache = [dirruns, doneName];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if (xml) {
while ((elem = elem[dir])) {
if (elem.nodeType === 1 || checkNonElements) {
if (matcher(elem, context, xml)) {
return true;
}
}
}
} else {
while ((elem = elem[dir])) {
if (elem.nodeType === 1 || checkNonElements) {
outerCache = elem[expando] || (elem[expando] = {});
if ((oldCache = outerCache[dir]) &&
oldCache[0] === dirruns && oldCache[1] === doneName) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[2] = oldCache[2]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[dir] = newCache;
// A match means we're done; a fail means we have to keep checking
if ((newCache[2] = matcher(elem, context, xml))) {
return true;
}
}
}
}
}
};
}
function elementMatcher(matchers) {
return matchers.length > 1 ?
function (elem, context, xml) {
var i = matchers.length;
while (i--) {
if (!matchers[i](elem, context, xml)) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts(selector, contexts, results) {
var i = 0,
len = contexts.length;
for (; i < len; i++) {
Sizzle(selector, contexts[i], results);
}
return results;
}
function condense(unmatched, map, filter, context, xml) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for (; i < len; i++) {
if ((elem = unmatched[i])) {
if (!filter || filter(elem, context, xml)) {
newUnmatched.push(elem);
if (mapped) {
map.push(i);
}
}
}
}
return newUnmatched;
}
function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
if (postFilter && !postFilter[expando]) {
postFilter = setMatcher(postFilter);
}
if (postFinder && !postFinder[expando]) {
postFinder = setMatcher(postFinder, postSelector);
}
return markFunction(function (seed, results, context, xml) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, []),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense(elems, preMap, preFilter, context, xml) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if (matcher) {
matcher(matcherIn, matcherOut, context, xml);
}
// Apply postFilter
if (postFilter) {
temp = condense(matcherOut, postMap);
postFilter(temp, [], context, xml);
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while (i--) {
if ((elem = temp[i])) {
matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
}
}
}
if (seed) {
if (postFinder || preFilter) {
if (postFinder) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while (i--) {
if ((elem = matcherOut[i])) {
// Restore matcherIn since elem is not yet a final match
temp.push((matcherIn[i] = elem));
}
}
postFinder(null, (matcherOut = []), temp, xml);
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while (i--) {
if ((elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice(preexisting, matcherOut.length) :
matcherOut
);
if (postFinder) {
postFinder(null, results, matcherOut, xml);
} else {
push.apply(results, matcherOut);
}
}
});
}
function matcherFromTokens(tokens) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[tokens[0].type],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator(function (elem) {
return elem === checkContext;
}, implicitRelative, true),
matchAnyContext = addCombinator(function (elem) {
return indexOf.call(checkContext, elem) > -1;
}, implicitRelative, true),
matchers = [function (elem, context, xml) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext(elem, context, xml) :
matchAnyContext(elem, context, xml) );
}];
for (; i < len; i++) {
if ((matcher = Expr.relative[tokens[i].type])) {
matchers = [addCombinator(elementMatcher(matchers), matcher)];
} else {
matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches);
// Return special upon seeing a positional matcher
if (matcher[expando]) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for (; j < len; j++) {
if (Expr.relative[tokens[j].type]) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher(matchers),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice(0, i - 1).concat({value: tokens[i - 2].type === " " ? "*" : ""})
).replace(rtrim, "$1"),
matcher,
i < j && matcherFromTokens(tokens.slice(i, j)),
j < len && matcherFromTokens((tokens = tokens.slice(j))),
j < len && toSelector(tokens)
);
}
matchers.push(matcher);
}
}
return elementMatcher(matchers);
}
function matcherFromGroupMatchers(elementMatchers, setMatchers) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function (seed, context, xml, results, outermost) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]("*", outermost),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if (outermost) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for (; i !== len && (elem = elems[i]) != null; i++) {
if (byElement && elem) {
j = 0;
while ((matcher = elementMatchers[j++])) {
if (matcher(elem, context, xml)) {
results.push(elem);
break;
}
}
if (outermost) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if (bySet) {
// They will have gone through all possible matchers
if ((elem = !matcher && elem)) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if (seed) {
unmatched.push(elem);
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if (bySet && i !== matchedCount) {
j = 0;
while ((matcher = setMatchers[j++])) {
matcher(unmatched, setMatched, context, xml);
}
if (seed) {
// Reintegrate element matches to eliminate the need for sorting
if (matchedCount > 0) {
while (i--) {
if (!(unmatched[i] || setMatched[i])) {
setMatched[i] = pop.call(results);
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense(setMatched);
}
// Add matches to results
push.apply(results, setMatched);
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if (outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1) {
Sizzle.uniqueSort(results);
}
}
// Override manipulation of globals by nested matchers
if (outermost) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction(superMatcher) :
superMatcher;
}
compile = Sizzle.compile = function (selector, match /* Internal Use Only */) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[selector + " "];
if (!cached) {
// Generate a function of recursive functions that can be used to check each element
if (!match) {
match = tokenize(selector);
}
i = match.length;
while (i--) {
cached = matcherFromTokens(match[i]);
if (cached[expando]) {
setMatchers.push(cached);
} else {
elementMatchers.push(cached);
}
}
// Cache the compiled function
cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function (selector, context, results, seed) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize((selector = compiled.selector || selector));
results = results || [];
// Try to minimize operations if there is no seed and only one group
if (match.length === 1) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice(0);
if (tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[tokens[1].type]) {
context = ( Expr.find["ID"](token.matches[0].replace(runescape, funescape), context) || [] )[0];
if (!context) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if (compiled) {
context = context.parentNode;
}
selector = selector.slice(tokens.shift().value.length);
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test(selector) ? 0 : tokens.length;
while (i--) {
token = tokens[i];
// Abort if we hit a combinator
if (Expr.relative[(type = token.type)]) {
break;
}
if ((find = Expr.find[type])) {
// Search, expanding context for leading sibling combinators
if ((seed = find(
token.matches[0].replace(runescape, funescape),
rsibling.test(tokens[0].type) && testContext(context.parentNode) || context
))) {
// If seed is empty or no tokens remain, we can return early
tokens.splice(i, 1);
selector = seed.length && toSelector(tokens);
if (!selector) {
push.apply(results, seed);
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile(selector, match) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test(selector) && testContext(context.parentNode) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort(sortOrder).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function (div1) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition(document.createElement("div")) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if (!assert(function (div) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#";
})) {
addHandle("type|href|height|width", function (elem, name, isXML) {
if (!isXML) {
return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2);
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if (!support.attributes || !assert(function (div) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute("value", "");
return div.firstChild.getAttribute("value") === "";
})) {
addHandle("value", function (elem, name, isXML) {
if (!isXML && elem.nodeName.toLowerCase() === "input") {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if (!assert(function (div) {
return div.getAttribute("disabled") == null;
})) {
addHandle(booleans, function (elem, name, isXML) {
var val;
if (!isXML) {
return elem[name] === true ? name.toLowerCase() :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})(window);
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow(elements, qualifier, not) {
if (jQuery.isFunction(qualifier)) {
return jQuery.grep(elements, function (elem, i) {
/* jshint -W018 */
return !!qualifier.call(elem, i, elem) !== not;
});
}
if (qualifier.nodeType) {
return jQuery.grep(elements, function (elem) {
return ( elem === qualifier ) !== not;
});
}
if (typeof qualifier === "string") {
if (risSimple.test(qualifier)) {
return jQuery.filter(qualifier, elements, not);
}
qualifier = jQuery.filter(qualifier, elements);
}
return jQuery.grep(elements, function (elem) {
return ( indexOf.call(qualifier, elem) >= 0 ) !== not;
});
}
jQuery.filter = function (expr, elems, not) {
var elem = elems[0];
if (not) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector(elem, expr) ? [elem] : [] :
jQuery.find.matches(expr, jQuery.grep(elems, function (elem) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function (selector) {
var i,
len = this.length,
ret = [],
self = this;
if (typeof selector !== "string") {
return this.pushStack(jQuery(selector).filter(function () {
for (i = 0; i < len; i++) {
if (jQuery.contains(self[i], this)) {
return true;
}
}
}));
}
for (i = 0; i < len; i++) {
jQuery.find(selector, self[i], ret);
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack(len > 1 ? jQuery.unique(ret) : ret);
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function (selector) {
return this.pushStack(winnow(this, selector || [], false));
},
not: function (selector) {
return this.pushStack(winnow(this, selector || [], true));
},
is: function (selector) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test(selector) ?
jQuery(selector) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function (selector, context) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if (!selector) {
return this;
}
// Handle HTML strings
if (typeof selector === "string") {
if (selector[0] === "<" && selector[selector.length - 1] === ">" && selector.length >= 3) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [null, selector, null];
} else {
match = rquickExpr.exec(selector);
}
// Match html or make sure no context is specified for #id
if (match && (match[1] || !context)) {
// HANDLE: $(html) -> $(array)
if (match[1]) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge(this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
));
// HANDLE: $(html, props)
if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
for (match in context) {
// Properties of context are called as methods if possible
if (jQuery.isFunction(this[match])) {
this[match](context[match]);
// ...and otherwise set as attributes
} else {
this.attr(match, context[match]);
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById(match[2]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if (elem && elem.parentNode) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if (!context || context.jquery) {
return ( context || rootjQuery ).find(selector);
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor(context).find(selector);
}
// HANDLE: $(DOMElement)
} else if (selector.nodeType) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if (jQuery.isFunction(selector)) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready(selector) :
// Execute immediately if ready is not present
selector(jQuery);
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray(selector, this);
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery(document);
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function (elem, dir, until) {
var matched = [],
truncate = until !== undefined;
while ((elem = elem[dir]) && elem.nodeType !== 9) {
if (elem.nodeType === 1) {
if (truncate && jQuery(elem).is(until)) {
break;
}
matched.push(elem);
}
}
return matched;
},
sibling: function (n, elem) {
var matched = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1 && n !== elem) {
matched.push(n);
}
}
return matched;
}
});
jQuery.fn.extend({
has: function (target) {
var targets = jQuery(target, this),
l = targets.length;
return this.filter(function () {
var i = 0;
for (; i < l; i++) {
if (jQuery.contains(this, targets[i])) {
return true;
}
}
});
},
closest: function (selectors, context) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test(selectors) || typeof selectors !== "string" ?
jQuery(selectors, context || this.context) :
0;
for (; i < l; i++) {
for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) {
// Always skip document fragments
if (cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors))) {
matched.push(cur);
break;
}
}
}
return this.pushStack(matched.length > 1 ? jQuery.unique(matched) : matched);
},
// Determine the position of an element within
// the matched set of elements
index: function (elem) {
// No argument, return index in parent
if (!elem) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if (typeof elem === "string") {
return indexOf.call(jQuery(elem), this[0]);
}
// Locate the position of the desired element
return indexOf.call(this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem
);
},
add: function (selector, context) {
return this.pushStack(
jQuery.unique(
jQuery.merge(this.get(), jQuery(selector, context))
)
);
},
addBack: function (selector) {
return this.add(selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling(cur, dir) {
while ((cur = cur[dir]) && cur.nodeType !== 1) {
}
return cur;
}
jQuery.each({
parent: function (elem) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function (elem) {
return jQuery.dir(elem, "parentNode");
},
parentsUntil: function (elem, i, until) {
return jQuery.dir(elem, "parentNode", until);
},
next: function (elem) {
return sibling(elem, "nextSibling");
},
prev: function (elem) {
return sibling(elem, "previousSibling");
},
nextAll: function (elem) {
return jQuery.dir(elem, "nextSibling");
},
prevAll: function (elem) {
return jQuery.dir(elem, "previousSibling");
},
nextUntil: function (elem, i, until) {
return jQuery.dir(elem, "nextSibling", until);
},
prevUntil: function (elem, i, until) {
return jQuery.dir(elem, "previousSibling", until);
},
siblings: function (elem) {
return jQuery.sibling(( elem.parentNode || {} ).firstChild, elem);
},
children: function (elem) {
return jQuery.sibling(elem.firstChild);
},
contents: function (elem) {
return elem.contentDocument || jQuery.merge([], elem.childNodes);
}
}, function (name, fn) {
jQuery.fn[name] = function (until, selector) {
var matched = jQuery.map(this, fn, until);
if (name.slice(-5) !== "Until") {
selector = until;
}
if (selector && typeof selector === "string") {
matched = jQuery.filter(selector, matched);
}
if (this.length > 1) {
// Remove duplicates
if (!guaranteedUnique[name]) {
jQuery.unique(matched);
}
// Reverse order for parents* and prev-derivatives
if (rparentsprev.test(name)) {
matched.reverse();
}
}
return this.pushStack(matched);
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions(options) {
var object = optionsCache[options] = {};
jQuery.each(options.match(rnotwhite) || [], function (_, flag) {
object[flag] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function (options) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[options] || createOptions(options) ) :
jQuery.extend({}, options);
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function (data) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for (; list && firingIndex < firingLength; firingIndex++) {
if (list[firingIndex].apply(data[0], data[1]) === false && options.stopOnFalse) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if (list) {
if (stack) {
if (stack.length) {
fire(stack.shift());
}
} else if (memory) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function () {
if (list) {
// First, we save the current length
var start = list.length;
(function add(args) {
jQuery.each(args, function (_, arg) {
var type = jQuery.type(arg);
if (type === "function") {
if (!options.unique || !self.has(arg)) {
list.push(arg);
}
} else if (arg && arg.length && type !== "string") {
// Inspect recursively
add(arg);
}
});
})(arguments);
// Do we need to add the callbacks to the
// current firing batch?
if (firing) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if (memory) {
firingStart = start;
fire(memory);
}
}
return this;
},
// Remove a callback from the list
remove: function () {
if (list) {
jQuery.each(arguments, function (_, arg) {
var index;
while (( index = jQuery.inArray(arg, list, index) ) > -1) {
list.splice(index, 1);
// Handle firing indexes
if (firing) {
if (index <= firingLength) {
firingLength--;
}
if (index <= firingIndex) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function (fn) {
return fn ? jQuery.inArray(fn, list) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function () {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function () {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function () {
return !list;
},
// Lock the list in its current state
lock: function () {
stack = undefined;
if (!memory) {
self.disable();
}
return this;
},
// Is it locked?
locked: function () {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function (context, args) {
if (list && ( !fired || stack )) {
args = args || [];
args = [context, args.slice ? args.slice() : args];
if (firing) {
stack.push(args);
} else {
fire(args);
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function () {
self.fireWith(this, arguments);
return this;
},
// To know if the callbacks have already been called at least once
fired: function () {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function (func) {
var tuples = [
// action, add listener, listener list, final state
["resolve", "done", jQuery.Callbacks("once memory"), "resolved"],
["reject", "fail", jQuery.Callbacks("once memory"), "rejected"],
["notify", "progress", jQuery.Callbacks("memory")]
],
state = "pending",
promise = {
state: function () {
return state;
},
always: function () {
deferred.done(arguments).fail(arguments);
return this;
},
then: function (/* fnDone, fnFail, fnProgress */) {
var fns = arguments;
return jQuery.Deferred(function (newDefer) {
jQuery.each(tuples, function (i, tuple) {
var fn = jQuery.isFunction(fns[i]) && fns[i];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[tuple[1]](function () {
var returned = fn && fn.apply(this, arguments);
if (returned && jQuery.isFunction(returned.promise)) {
returned.promise()
.done(newDefer.resolve)
.fail(newDefer.reject)
.progress(newDefer.notify);
} else {
newDefer[tuple[0] + "With"](this === promise ? newDefer.promise() : this, fn ? [returned] : arguments);
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function (obj) {
return obj != null ? jQuery.extend(obj, promise) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each(tuples, function (i, tuple) {
var list = tuple[2],
stateString = tuple[3];
// promise[ done | fail | progress ] = list.add
promise[tuple[1]] = list.add;
// Handle state
if (stateString) {
list.add(function () {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[i ^ 1][2].disable, tuples[2][2].lock);
}
// deferred[ resolve | reject | notify ]
deferred[tuple[0]] = function () {
deferred[tuple[0] + "With"](this === deferred ? promise : this, arguments);
return this;
};
deferred[tuple[0] + "With"] = list.fireWith;
});
// Make the deferred a promise
promise.promise(deferred);
// Call given func if any
if (func) {
func.call(deferred, deferred);
}
// All done!
return deferred;
},
// Deferred helper
when: function (subordinate /* , ..., subordinateN */) {
var i = 0,
resolveValues = slice.call(arguments),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction(subordinate.promise) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function (i, contexts, values) {
return function (value) {
contexts[i] = this;
values[i] = arguments.length > 1 ? slice.call(arguments) : value;
if (values === progressValues) {
deferred.notifyWith(contexts, values);
} else if (!( --remaining )) {
deferred.resolveWith(contexts, values);
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if (length > 1) {
progressValues = new Array(length);
progressContexts = new Array(length);
resolveContexts = new Array(length);
for (; i < length; i++) {
if (resolveValues[i] && jQuery.isFunction(resolveValues[i].promise)) {
resolveValues[i].promise()
.done(updateFunc(i, resolveContexts, resolveValues))
.fail(deferred.reject)
.progress(updateFunc(i, progressContexts, progressValues));
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if (!remaining) {
deferred.resolveWith(resolveContexts, resolveValues);
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function (fn) {
// Add the callback
jQuery.ready.promise().done(fn);
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function (hold) {
if (hold) {
jQuery.readyWait++;
} else {
jQuery.ready(true);
}
},
// Handle when the DOM is ready
ready: function (wait) {
// Abort if there are pending holds or we're already ready
if (wait === true ? --jQuery.readyWait : jQuery.isReady) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if (wait !== true && --jQuery.readyWait > 0) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith(document, [jQuery]);
// Trigger any bound ready events
if (jQuery.fn.triggerHandler) {
jQuery(document).triggerHandler("ready");
jQuery(document).off("ready");
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener("DOMContentLoaded", completed, false);
window.removeEventListener("load", completed, false);
jQuery.ready();
}
jQuery.ready.promise = function (obj) {
if (!readyList) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if (document.readyState === "complete") {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout(jQuery.ready);
} else {
// Use the handy event callback
document.addEventListener("DOMContentLoaded", completed, false);
// A fallback to window.onload, that will always work
window.addEventListener("load", completed, false);
}
}
return readyList.promise(obj);
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function (elems, fn, key, value, chainable, emptyGet, raw) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if (jQuery.type(key) === "object") {
chainable = true;
for (i in key) {
jQuery.access(elems, fn, i, key[i], true, emptyGet, raw);
}
// Sets one value
} else if (value !== undefined) {
chainable = true;
if (!jQuery.isFunction(value)) {
raw = true;
}
if (bulk) {
// Bulk operations run against the entire set
if (raw) {
fn.call(elems, value);
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function (elem, key, value) {
return bulk.call(jQuery(elem), value);
};
}
}
if (fn) {
for (; i < len; i++) {
fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)));
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call(elems) :
len ? fn(elems[0], key) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function (owner) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty(this.cache = {}, 0, {
get: function () {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function (owner) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if (!Data.accepts(owner)) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[this.expando];
// If not, create one
if (!unlock) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[this.expando] = {value: unlock};
Object.defineProperties(owner, descriptor);
// Support: Android < 4
// Fallback to a less secure definition
} catch (e) {
descriptor[this.expando] = unlock;
jQuery.extend(owner, descriptor);
}
}
// Ensure the cache object
if (!this.cache[unlock]) {
this.cache[unlock] = {};
}
return unlock;
},
set: function (owner, data, value) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key(owner),
cache = this.cache[unlock];
// Handle: [ owner, key, value ] args
if (typeof data === "string") {
cache[data] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if (jQuery.isEmptyObject(cache)) {
jQuery.extend(this.cache[unlock], data);
// Otherwise, copy the properties one-by-one to the cache object
} else {
for (prop in data) {
cache[prop] = data[prop];
}
}
}
return cache;
},
get: function (owner, key) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[this.key(owner)];
return key === undefined ?
cache : cache[key];
},
access: function (owner, key, value) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if (key === undefined ||
((key && typeof key === "string") && value === undefined)) {
stored = this.get(owner, key);
return stored !== undefined ?
stored : this.get(owner, jQuery.camelCase(key));
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set(owner, key, value);
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function (owner, key) {
var i, name, camel,
unlock = this.key(owner),
cache = this.cache[unlock];
if (key === undefined) {
this.cache[unlock] = {};
} else {
// Support array or space separated string of keys
if (jQuery.isArray(key)) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat(key.map(jQuery.camelCase));
} else {
camel = jQuery.camelCase(key);
// Try the string as a key before any manipulation
if (key in cache) {
name = [key, camel];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[name] : ( name.match(rnotwhite) || [] );
}
}
i = name.length;
while (i--) {
delete cache[name[i]];
}
}
},
hasData: function (owner) {
return !jQuery.isEmptyObject(
this.cache[owner[this.expando]] || {}
);
},
discard: function (owner) {
if (owner[this.expando]) {
delete this.cache[owner[this.expando]];
}
}
};
var data_priv = new Data();
var data_user = new Data();
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr(elem, key, data) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if (data === undefined && elem.nodeType === 1) {
name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase();
data = elem.getAttribute(name);
if (typeof data === "string") {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test(data) ? jQuery.parseJSON(data) :
data;
} catch (e) {
}
// Make sure we set the data so it isn't changed later
data_user.set(elem, key, data);
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function (elem) {
return data_user.hasData(elem) || data_priv.hasData(elem);
},
data: function (elem, name, data) {
return data_user.access(elem, name, data);
},
removeData: function (elem, name) {
data_user.remove(elem, name);
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function (elem, name, data) {
return data_priv.access(elem, name, data);
},
_removeData: function (elem, name) {
data_priv.remove(elem, name);
}
});
jQuery.fn.extend({
data: function (key, value) {
var i, name, data,
elem = this[0],
attrs = elem && elem.attributes;
// Gets all values
if (key === undefined) {
if (this.length) {
data = data_user.get(elem);
if (elem.nodeType === 1 && !data_priv.get(elem, "hasDataAttrs")) {
i = attrs.length;
while (i--) {
// Support: IE11+
// The attrs elements can be null (#14894)
if (attrs[i]) {
name = attrs[i].name;
if (name.indexOf("data-") === 0) {
name = jQuery.camelCase(name.slice(5));
dataAttr(elem, name, data[name]);
}
}
}
data_priv.set(elem, "hasDataAttrs", true);
}
}
return data;
}
// Sets multiple values
if (typeof key === "object") {
return this.each(function () {
data_user.set(this, key);
});
}
return access(this, function (value) {
var data,
camelKey = jQuery.camelCase(key);
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if (elem && value === undefined) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get(elem, key);
if (data !== undefined) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get(elem, camelKey);
if (data !== undefined) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr(elem, camelKey, undefined);
if (data !== undefined) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function () {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get(this, camelKey);
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set(this, camelKey, value);
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if (key.indexOf("-") !== -1 && data !== undefined) {
data_user.set(this, key, value);
}
});
}, null, value, arguments.length > 1, null, true);
},
removeData: function (key) {
return this.each(function () {
data_user.remove(this, key);
});
}
});
jQuery.extend({
queue: function (elem, type, data) {
var queue;
if (elem) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get(elem, type);
// Speed up dequeue by getting out quickly if this is just a lookup
if (data) {
if (!queue || jQuery.isArray(data)) {
queue = data_priv.access(elem, type, jQuery.makeArray(data));
} else {
queue.push(data);
}
}
return queue || [];
}
},
dequeue: function (elem, type) {
type = type || "fx";
var queue = jQuery.queue(elem, type),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks(elem, type),
next = function () {
jQuery.dequeue(elem, type);
};
// If the fx queue is dequeued, always remove the progress sentinel
if (fn === "inprogress") {
fn = queue.shift();
startLength--;
}
if (fn) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if (type === "fx") {
queue.unshift("inprogress");
}
// clear up the last queue stop function
delete hooks.stop;
fn.call(elem, next, hooks);
}
if (!startLength && hooks) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function (elem, type) {
var key = type + "queueHooks";
return data_priv.get(elem, key) || data_priv.access(elem, key, {
empty: jQuery.Callbacks("once memory").add(function () {
data_priv.remove(elem, [type + "queue", key]);
})
});
}
});
jQuery.fn.extend({
queue: function (type, data) {
var setter = 2;
if (typeof type !== "string") {
data = type;
type = "fx";
setter--;
}
if (arguments.length < setter) {
return jQuery.queue(this[0], type);
}
return data === undefined ?
this :
this.each(function () {
var queue = jQuery.queue(this, type, data);
// ensure a hooks for this queue
jQuery._queueHooks(this, type);
if (type === "fx" && queue[0] !== "inprogress") {
jQuery.dequeue(this, type);
}
});
},
dequeue: function (type) {
return this.each(function () {
jQuery.dequeue(this, type);
});
},
clearQueue: function (type) {
return this.queue(type || "fx", []);
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function (type, obj) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function () {
if (!( --count )) {
defer.resolveWith(elements, [elements]);
}
};
if (typeof type !== "string") {
obj = type;
type = undefined;
}
type = type || "fx";
while (i--) {
tmp = data_priv.get(elements[i], type + "queueHooks");
if (tmp && tmp.empty) {
count++;
tmp.empty.add(resolve);
}
}
resolve();
return defer.promise(obj);
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = ["Top", "Right", "Bottom", "Left"];
var isHidden = function (elem, el) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css(elem, "display") === "none" || !jQuery.contains(elem.ownerDocument, elem);
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function () {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild(document.createElement("div")),
input = document.createElement("input");
// #11217 - WebKit loses check when the name is after the checked attribute
// Support: Windows Web Apps (WWA)
// `name` and `type` need .setAttribute for WWA
input.setAttribute("type", "radio");
input.setAttribute("checked", "checked");
input.setAttribute("name", "t");
div.appendChild(input);
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode(true).cloneNode(true).lastChild.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE9-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch (err) {
}
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function (elem, types, handler, data, selector) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get(elem);
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if (!elemData) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if (handler.handler) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if (!handler.guid) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if (!(events = elemData.events)) {
events = elemData.events = {};
}
if (!(eventHandle = elemData.handle)) {
eventHandle = elemData.handle = function (e) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply(elem, arguments) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match(rnotwhite) || [""];
t = types.length;
while (t--) {
tmp = rtypenamespace.exec(types[t]) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split(".").sort();
// There *must* be a type, no attaching namespace-only handlers
if (!type) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[type] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[type] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test(selector),
namespace: namespaces.join(".")
}, handleObjIn);
// Init the event handler queue if we're the first
if (!(handlers = events[type])) {
handlers = events[type] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
if (elem.addEventListener) {
elem.addEventListener(type, eventHandle, false);
}
}
}
if (special.add) {
special.add.call(elem, handleObj);
if (!handleObj.handler.guid) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if (selector) {
handlers.splice(handlers.delegateCount++, 0, handleObj);
} else {
handlers.push(handleObj);
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[type] = true;
}
},
// Detach an event or set of events from an element
remove: function (elem, types, handler, selector, mappedTypes) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData(elem) && data_priv.get(elem);
if (!elemData || !(events = elemData.events)) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match(rnotwhite) || [""];
t = types.length;
while (t--) {
tmp = rtypenamespace.exec(types[t]) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split(".").sort();
// Unbind all events (on this namespace, if provided) for the element
if (!type) {
for (type in events) {
jQuery.event.remove(elem, type + types[t], handler, selector, true);
}
continue;
}
special = jQuery.event.special[type] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[type] || [];
tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");
// Remove matching events
origCount = j = handlers.length;
while (j--) {
handleObj = handlers[j];
if (( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test(handleObj.namespace) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector )) {
handlers.splice(j, 1);
if (handleObj.selector) {
handlers.delegateCount--;
}
if (special.remove) {
special.remove.call(elem, handleObj);
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if (origCount && !handlers.length) {
if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {
jQuery.removeEvent(elem, type, elemData.handle);
}
delete events[type];
}
}
// Remove the expando if it's no longer used
if (jQuery.isEmptyObject(events)) {
delete elemData.handle;
data_priv.remove(elem, "events");
}
},
trigger: function (event, data, elem, onlyHandlers) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [elem || document],
type = hasOwn.call(event, "type") ? event.type : event,
namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if (elem.nodeType === 3 || elem.nodeType === 8) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if (rfocusMorph.test(type + jQuery.event.triggered)) {
return;
}
if (type.indexOf(".") >= 0) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[jQuery.expando] ?
event :
new jQuery.Event(type, typeof event === "object" && event);
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if (!event.target) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[event] :
jQuery.makeArray(data, [event]);
// Allow special events to draw outside the lines
special = jQuery.event.special[type] || {};
if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {
bubbleType = special.delegateType || type;
if (!rfocusMorph.test(bubbleType + type)) {
cur = cur.parentNode;
}
for (; cur; cur = cur.parentNode) {
eventPath.push(cur);
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if (tmp === (elem.ownerDocument || document)) {
eventPath.push(tmp.defaultView || tmp.parentWindow || window);
}
}
// Fire handlers on the event path
i = 0;
while ((cur = eventPath[i++]) && !event.isPropagationStopped()) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get(cur, "events") || {} )[event.type] && data_priv.get(cur, "handle");
if (handle) {
handle.apply(cur, data);
}
// Native handler
handle = ontype && cur[ontype];
if (handle && handle.apply && jQuery.acceptData(cur)) {
event.result = handle.apply(cur, data);
if (event.result === false) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if (!onlyHandlers && !event.isDefaultPrevented()) {
if ((!special._default || special._default.apply(eventPath.pop(), data) === false) &&
jQuery.acceptData(elem)) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if (ontype && jQuery.isFunction(elem[type]) && !jQuery.isWindow(elem)) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ontype];
if (tmp) {
elem[ontype] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[type]();
jQuery.event.triggered = undefined;
if (tmp) {
elem[ontype] = tmp;
}
}
}
}
return event.result;
},
dispatch: function (event) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix(event);
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call(arguments),
handlers = ( data_priv.get(this, "events") || {} )[event.type] || [],
special = jQuery.event.special[event.type] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if (special.preDispatch && special.preDispatch.call(this, event) === false) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call(this, event, handlers);
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ((matched = handlerQueue[i++]) && !event.isPropagationStopped()) {
event.currentTarget = matched.elem;
j = 0;
while ((handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped()) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if (!event.namespace_re || event.namespace_re.test(handleObj.namespace)) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler )
.apply(matched.elem, args);
if (ret !== undefined) {
if ((event.result = ret) === false) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if (special.postDispatch) {
special.postDispatch.call(this, event);
}
return event.result;
},
handlers: function (event, handlers) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if (delegateCount && cur.nodeType && (!event.button || event.type !== "click")) {
for (; cur !== this; cur = cur.parentNode || this) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if (cur.disabled !== true || event.type !== "click") {
matches = [];
for (i = 0; i < delegateCount; i++) {
handleObj = handlers[i];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if (matches[sel] === undefined) {
matches[sel] = handleObj.needsContext ?
jQuery(sel, this).index(cur) >= 0 :
jQuery.find(sel, this, null, [cur]).length;
}
if (matches[sel]) {
matches.push(handleObj);
}
}
if (matches.length) {
handlerQueue.push({elem: cur, handlers: matches});
}
}
}
}
// Add the remaining (directly-bound) handlers
if (delegateCount < handlers.length) {
handlerQueue.push({
elem: this,
handlers: handlers.slice(delegateCount)
});
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function (event, original) {
// Add which for key events
if (event.which == null) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function (event, original) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if (event.pageX == null && original.clientX != null) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if (!event.which && button !== undefined) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function (event) {
if (event[jQuery.expando]) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[type];
if (!fixHook) {
this.fixHooks[type] = fixHook =
rmouseEvent.test(type) ? this.mouseHooks :
rkeyEvent.test(type) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat(fixHook.props) : this.props;
event = new jQuery.Event(originalEvent);
i = copy.length;
while (i--) {
prop = copy[i];
event[prop] = originalEvent[prop];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if (!event.target) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if (event.target.nodeType === 3) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter(event, originalEvent) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function () {
if (this !== safeActiveElement() && this.focus) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function () {
if (this === safeActiveElement() && this.blur) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function () {
if (this.type === "checkbox" && this.click && jQuery.nodeName(this, "input")) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function (event) {
return jQuery.nodeName(event.target, "a");
}
},
beforeunload: {
postDispatch: function (event) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if (event.result !== undefined && event.originalEvent) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function (type, elem, event, bubble) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if (bubble) {
jQuery.event.trigger(e, null, elem);
} else {
jQuery.event.dispatch.call(elem, e);
}
if (e.isDefaultPrevented()) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function (elem, type, handle) {
if (elem.removeEventListener) {
elem.removeEventListener(type, handle, false);
}
};
jQuery.Event = function (src, props) {
// Allow instantiation without the 'new' keyword
if (!(this instanceof jQuery.Event)) {
return new jQuery.Event(src, props);
}
// Event object
if (src && src.type) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if (props) {
jQuery.extend(this, props);
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[jQuery.expando] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function () {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if (e && e.preventDefault) {
e.preventDefault();
}
},
stopPropagation: function () {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if (e && e.stopPropagation) {
e.stopPropagation();
}
},
stopImmediatePropagation: function () {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if (e && e.stopImmediatePropagation) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function (orig, fix) {
jQuery.event.special[orig] = {
delegateType: fix,
bindType: fix,
handle: function (event) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if (!related || (related !== target && !jQuery.contains(target, related))) {
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if (!support.focusinBubbles) {
jQuery.each({focus: "focusin", blur: "focusout"}, function (orig, fix) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function (event) {
jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true);
};
jQuery.event.special[fix] = {
setup: function () {
var doc = this.ownerDocument || this,
attaches = data_priv.access(doc, fix);
if (!attaches) {
doc.addEventListener(orig, handler, true);
}
data_priv.access(doc, fix, ( attaches || 0 ) + 1);
},
teardown: function () {
var doc = this.ownerDocument || this,
attaches = data_priv.access(doc, fix) - 1;
if (!attaches) {
doc.removeEventListener(orig, handler, true);
data_priv.remove(doc, fix);
} else {
data_priv.access(doc, fix, attaches);
}
}
};
});
}
jQuery.fn.extend({
on: function (types, selector, data, fn, /*INTERNAL*/ one) {
var origFn, type;
// Types can be a map of types/handlers
if (typeof types === "object") {
// ( types-Object, selector, data )
if (typeof selector !== "string") {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for (type in types) {
this.on(type, selector, data, types[type], one);
}
return this;
}
if (data == null && fn == null) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if (fn == null) {
if (typeof selector === "string") {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if (fn === false) {
fn = returnFalse;
} else if (!fn) {
return this;
}
if (one === 1) {
origFn = fn;
fn = function (event) {
// Can use an empty set, since event contains the info
jQuery().off(event);
return origFn.apply(this, arguments);
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each(function () {
jQuery.event.add(this, types, fn, data, selector);
});
},
one: function (types, selector, data, fn) {
return this.on(types, selector, data, fn, 1);
},
off: function (types, selector, fn) {
var handleObj, type;
if (types && types.preventDefault && types.handleObj) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery(types.delegateTarget).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if (typeof types === "object") {
// ( types-object [, selector] )
for (type in types) {
this.off(type, selector, types[type]);
}
return this;
}
if (selector === false || typeof selector === "function") {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if (fn === false) {
fn = returnFalse;
}
return this.each(function () {
jQuery.event.remove(this, types, fn, selector);
});
},
trigger: function (type, data) {
return this.each(function () {
jQuery.event.trigger(type, data, this);
});
},
triggerHandler: function (type, data) {
var elem = this[0];
if (elem) {
return jQuery.event.trigger(type, data, elem, true);
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [1, "<select multiple='multiple'>", "</select>"],
thead: [1, "<table>", "</table>"],
col: [2, "<table><colgroup>", "</colgroup></table>"],
tr: [2, "<table><tbody>", "</tbody></table>"],
td: [3, "<table><tbody><tr>", "</tr></tbody></table>"],
_default: [0, "", ""]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget(elem, content) {
return jQuery.nodeName(elem, "table") &&
jQuery.nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr") ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody")) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript(elem) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript(elem) {
var match = rscriptTypeMasked.exec(elem.type);
if (match) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval(elems, refElements) {
var i = 0,
l = elems.length;
for (; i < l; i++) {
data_priv.set(
elems[i], "globalEval", !refElements || data_priv.get(refElements[i], "globalEval")
);
}
}
function cloneCopyEvent(src, dest) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if (dest.nodeType !== 1) {
return;
}
// 1. Copy private data: events, handlers, etc.
if (data_priv.hasData(src)) {
pdataOld = data_priv.access(src);
pdataCur = data_priv.set(dest, pdataOld);
events = pdataOld.events;
if (events) {
delete pdataCur.handle;
pdataCur.events = {};
for (type in events) {
for (i = 0, l = events[type].length; i < l; i++) {
jQuery.event.add(dest, type, events[type][i]);
}
}
}
}
// 2. Copy user data
if (data_user.hasData(src)) {
udataOld = data_user.access(src);
udataCur = jQuery.extend({}, udataOld);
data_user.set(dest, udataCur);
}
}
function getAll(context, tag) {
var ret = context.getElementsByTagName ? context.getElementsByTagName(tag || "*") :
context.querySelectorAll ? context.querySelectorAll(tag || "*") :
[];
return tag === undefined || tag && jQuery.nodeName(context, tag) ?
jQuery.merge([context], ret) :
ret;
}
// Support: IE >= 9
function fixInput(src, dest) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if (nodeName === "input" && rcheckableType.test(src.type)) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if (nodeName === "input" || nodeName === "textarea") {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function (elem, dataAndEvents, deepDataAndEvents) {
var i, l, srcElements, destElements,
clone = elem.cloneNode(true),
inPage = jQuery.contains(elem.ownerDocument, elem);
// Support: IE >= 9
// Fix Cloning issues
if (!support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc(elem)) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll(clone);
srcElements = getAll(elem);
for (i = 0, l = srcElements.length; i < l; i++) {
fixInput(srcElements[i], destElements[i]);
}
}
// Copy the events from the original to the clone
if (dataAndEvents) {
if (deepDataAndEvents) {
srcElements = srcElements || getAll(elem);
destElements = destElements || getAll(clone);
for (i = 0, l = srcElements.length; i < l; i++) {
cloneCopyEvent(srcElements[i], destElements[i]);
}
} else {
cloneCopyEvent(elem, clone);
}
}
// Preserve script evaluation history
destElements = getAll(clone, "script");
if (destElements.length > 0) {
setGlobalEval(destElements, !inPage && getAll(elem, "script"));
}
// Return the cloned set
return clone;
},
buildFragment: function (elems, context, scripts, selection) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for (; i < l; i++) {
elem = elems[i];
if (elem || elem === 0) {
// Add nodes directly
if (jQuery.type(elem) === "object") {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge(nodes, elem.nodeType ? [elem] : elem);
// Convert non-html into a text node
} else if (!rhtml.test(elem)) {
nodes.push(context.createTextNode(elem));
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild(context.createElement("div"));
// Deserialize a standard representation
tag = ( rtagName.exec(elem) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace(rxhtmlTag, "<$1></$2>") + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while (j--) {
tmp = tmp.lastChild;
}
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge(nodes, tmp.childNodes);
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ((elem = nodes[i++])) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if (selection && jQuery.inArray(elem, selection) !== -1) {
continue;
}
contains = jQuery.contains(elem.ownerDocument, elem);
// Append to fragment
tmp = getAll(fragment.appendChild(elem), "script");
// Preserve script evaluation history
if (contains) {
setGlobalEval(tmp);
}
// Capture executables
if (scripts) {
j = 0;
while ((elem = tmp[j++])) {
if (rscriptType.test(elem.type || "")) {
scripts.push(elem);
}
}
}
}
return fragment;
},
cleanData: function (elems) {
var data, elem, type, key,
special = jQuery.event.special,
i = 0;
for (; (elem = elems[i]) !== undefined; i++) {
if (jQuery.acceptData(elem)) {
key = elem[data_priv.expando];
if (key && (data = data_priv.cache[key])) {
if (data.events) {
for (type in data.events) {
if (special[type]) {
jQuery.event.remove(elem, type);
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent(elem, type, data.handle);
}
}
}
if (data_priv.cache[key]) {
// Discard any remaining `private` data
delete data_priv.cache[key];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[elem[data_user.expando]];
}
}
});
jQuery.fn.extend({
text: function (value) {
return access(this, function (value) {
return value === undefined ?
jQuery.text(this) :
this.empty().each(function () {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
this.textContent = value;
}
});
}, null, value, arguments.length);
},
append: function () {
return this.domManip(arguments, function (elem) {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
var target = manipulationTarget(this, elem);
target.appendChild(elem);
}
});
},
prepend: function () {
return this.domManip(arguments, function (elem) {
if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) {
var target = manipulationTarget(this, elem);
target.insertBefore(elem, target.firstChild);
}
});
},
before: function () {
return this.domManip(arguments, function (elem) {
if (this.parentNode) {
this.parentNode.insertBefore(elem, this);
}
});
},
after: function () {
return this.domManip(arguments, function (elem) {
if (this.parentNode) {
this.parentNode.insertBefore(elem, this.nextSibling);
}
});
},
remove: function (selector, keepData /* Internal Use Only */) {
var elem,
elems = selector ? jQuery.filter(selector, this) : this,
i = 0;
for (; (elem = elems[i]) != null; i++) {
if (!keepData && elem.nodeType === 1) {
jQuery.cleanData(getAll(elem));
}
if (elem.parentNode) {
if (keepData && jQuery.contains(elem.ownerDocument, elem)) {
setGlobalEval(getAll(elem, "script"));
}
elem.parentNode.removeChild(elem);
}
}
return this;
},
empty: function () {
var elem,
i = 0;
for (; (elem = this[i]) != null; i++) {
if (elem.nodeType === 1) {
// Prevent memory leaks
jQuery.cleanData(getAll(elem, false));
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function (dataAndEvents, deepDataAndEvents) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function () {
return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
});
},
html: function (value) {
return access(this, function (value) {
var elem = this[0] || {},
i = 0,
l = this.length;
if (value === undefined && elem.nodeType === 1) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if (typeof value === "string" && !rnoInnerhtml.test(value) && !wrapMap[( rtagName.exec(value) || ["", ""] )[1].toLowerCase()]) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for (; i < l; i++) {
elem = this[i] || {};
// Remove element nodes and prevent memory leaks
if (elem.nodeType === 1) {
jQuery.cleanData(getAll(elem, false));
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch (e) {
}
}
if (elem) {
this.empty().append(value);
}
}, null, value, arguments.length);
},
replaceWith: function () {
var arg = arguments[0];
// Make the changes, replacing each context element with the new content
this.domManip(arguments, function (elem) {
arg = this.parentNode;
jQuery.cleanData(getAll(this));
if (arg) {
arg.replaceChild(elem, this);
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function (selector) {
return this.remove(selector, true);
},
domManip: function (args, callback) {
// Flatten any nested arrays
args = concat.apply([], args);
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction(value);
// We can't cloneNode fragments that contain checked, in WebKit
if (isFunction ||
( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test(value) )) {
return this.each(function (index) {
var self = set.eq(index);
if (isFunction) {
args[0] = value.call(this, index, self.html());
}
self.domManip(args, callback);
});
}
if (l) {
fragment = jQuery.buildFragment(args, this[0].ownerDocument, false, this);
first = fragment.firstChild;
if (fragment.childNodes.length === 1) {
fragment = first;
}
if (first) {
scripts = jQuery.map(getAll(fragment, "script"), disableScript);
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for (; i < l; i++) {
node = fragment;
if (i !== iNoClone) {
node = jQuery.clone(node, true, true);
// Keep references to cloned scripts for later restoration
if (hasScripts) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge(scripts, getAll(node, "script"));
}
}
callback.call(this[i], node, i);
}
if (hasScripts) {
doc = scripts[scripts.length - 1].ownerDocument;
// Reenable scripts
jQuery.map(scripts, restoreScript);
// Evaluate executable scripts on first document insertion
for (i = 0; i < hasScripts; i++) {
node = scripts[i];
if (rscriptType.test(node.type || "") && !data_priv.access(node, "globalEval") && jQuery.contains(doc, node)) {
if (node.src) {
// Optional AJAX dependency, but won't run scripts if not present
if (jQuery._evalUrl) {
jQuery._evalUrl(node.src);
}
} else {
jQuery.globalEval(node.textContent.replace(rcleanScript, ""));
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function (name, original) {
jQuery.fn[name] = function (selector) {
var elems,
ret = [],
insert = jQuery(selector),
last = insert.length - 1,
i = 0;
for (; i <= last; i++) {
elems = i === last ? this : this.clone(true);
jQuery(insert[i])[original](elems);
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply(ret, elems.get());
}
return this.pushStack(ret);
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay(name, doc) {
var style,
elem = jQuery(doc.createElement(name)).appendTo(doc.body),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle(elem[0]) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css(elem[0], "display");
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay(nodeName) {
var doc = document,
display = elemdisplay[nodeName];
if (!display) {
display = actualDisplay(nodeName, doc);
// If the simple way fails, read from inside an iframe
if (display === "none" || !display) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>")).appendTo(doc.documentElement);
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[0].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay(nodeName, doc);
iframe.detach();
}
// Store the correct default display
elemdisplay[nodeName] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i");
var getStyles = function (elem) {
return elem.ownerDocument.defaultView.getComputedStyle(elem, null);
};
function curCSS(elem, name, computed) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles(elem);
// Support: IE9
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
if (computed) {
ret = computed.getPropertyValue(name) || computed[name];
}
if (computed) {
if (ret === "" && !jQuery.contains(elem.ownerDocument, elem)) {
ret = jQuery.style(elem, name);
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if (rnumnonpx.test(ret) && rmargin.test(name)) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf(conditionFn, hookFn) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function () {
if (conditionFn()) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply(this, arguments);
}
};
}
(function () {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement("div"),
div = document.createElement("div");
if (!div.style) {
return;
}
div.style.backgroundClip = "content-box";
div.cloneNode(true).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild(div);
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild(container);
var divStyle = window.getComputedStyle(div, null);
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild(container);
}
// Support: node.js jsdom
// Don't assume that getComputedStyle is a property of the global object
if (window.getComputedStyle) {
jQuery.extend(support, {
pixelPosition: function () {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function () {
if (boxSizingReliableVal == null) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function () {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild(document.createElement("div"));
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild(container);
ret = !parseFloat(window.getComputedStyle(marginDiv, null).marginRight);
docElem.removeChild(container);
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function (elem, options, callback, args) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for (name in options) {
old[name] = elem.style[name];
elem.style[name] = options[name];
}
ret = callback.apply(elem, args || []);
// Revert the old values
for (name in options) {
elem.style[name] = old[name];
}
return ret;
};
var
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp("^(" + pnum + ")(.*)$", "i"),
rrelNum = new RegExp("^([+-])=(" + pnum + ")", "i"),
cssShow = {position: "absolute", visibility: "hidden", display: "block"},
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = ["Webkit", "O", "Moz", "ms"];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName(style, name) {
// shortcut for names that are not vendor prefixed
if (name in style) {
return name;
}
// check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while (i--) {
name = cssPrefixes[i] + capName;
if (name in style) {
return name;
}
}
return origName;
}
function setPositiveNumber(elem, value, subtract) {
var matches = rnumsplit.exec(value);
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max(0, matches[1] - ( subtract || 0 )) + ( matches[2] || "px" ) :
value;
}
function augmentWidthOrHeight(elem, name, extra, isBorderBox, styles) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for (; i < 4; i += 2) {
// both box models exclude margin, so add it if we want it
if (extra === "margin") {
val += jQuery.css(elem, extra + cssExpand[i], true, styles);
}
if (isBorderBox) {
// border-box includes padding, so remove it if we want content
if (extra === "content") {
val -= jQuery.css(elem, "padding" + cssExpand[i], true, styles);
}
// at this point, extra isn't border nor margin, so remove border
if (extra !== "margin") {
val -= jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css(elem, "padding" + cssExpand[i], true, styles);
// at this point, extra isn't content nor padding, so add border
if (extra !== "padding") {
val += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles);
}
}
}
return val;
}
function getWidthOrHeight(elem, name, extra) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles(elem),
isBorderBox = jQuery.css(elem, "boxSizing", false, styles) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if (val <= 0 || val == null) {
// Fall back to computed then uncomputed css if necessary
val = curCSS(elem, name, styles);
if (val < 0 || val == null) {
val = elem.style[name];
}
// Computed unit is not pixels. Stop here and return.
if (rnumnonpx.test(val)) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[name] );
// Normalize "", auto, and prepare for extra
val = parseFloat(val) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
function showHide(elements, show) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for (; index < length; index++) {
elem = elements[index];
if (!elem.style) {
continue;
}
values[index] = data_priv.get(elem, "olddisplay");
display = elem.style.display;
if (show) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if (!values[index] && display === "none") {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if (elem.style.display === "" && isHidden(elem)) {
values[index] = data_priv.access(elem, "olddisplay", defaultDisplay(elem.nodeName));
}
} else {
hidden = isHidden(elem);
if (display !== "none" || !hidden) {
data_priv.set(elem, "olddisplay", hidden ? display : jQuery.css(elem, "display"));
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for (index = 0; index < length; index++) {
elem = elements[index];
if (!elem.style) {
continue;
}
if (!show || elem.style.display === "none" || elem.style.display === "") {
elem.style.display = show ? values[index] || "" : "none";
}
}
return elements;
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function (elem, computed) {
if (computed) {
// We should always get a number back from opacity
var ret = curCSS(elem, "opacity");
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function (elem, name, value, extra) {
// Don't set styles on text and comment nodes
if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase(name),
style = elem.style;
name = jQuery.cssProps[origName] || ( jQuery.cssProps[origName] = vendorPropName(style, origName) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];
// Check if we're setting a value
if (value !== undefined) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if (type === "string" && (ret = rrelNum.exec(value))) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat(jQuery.css(elem, name));
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if (value == null || value !== value) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if (type === "number" && !jQuery.cssNumber[origName]) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if (!support.clearCloneStyle && value === "" && name.indexOf("background") === 0) {
style[name] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) {
style[name] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) {
return ret;
}
// Otherwise just get the value from the style object
return style[name];
}
},
css: function (elem, name, extra, styles) {
var val, num, hooks,
origName = jQuery.camelCase(name);
// Make sure that we're working with the right name
name = jQuery.cssProps[origName] || ( jQuery.cssProps[origName] = vendorPropName(elem.style, origName) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];
// If a hook was provided get the computed value from there
if (hooks && "get" in hooks) {
val = hooks.get(elem, true, extra);
}
// Otherwise, if a way to get the computed value exists, use that
if (val === undefined) {
val = curCSS(elem, name, styles);
}
//convert "normal" to computed value
if (val === "normal" && name in cssNormalTransform) {
val = cssNormalTransform[name];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if (extra === "" || extra) {
num = parseFloat(val);
return extra === true || jQuery.isNumeric(num) ? num || 0 : val;
}
return val;
}
});
jQuery.each(["height", "width"], function (i, name) {
jQuery.cssHooks[name] = {
get: function (elem, computed, extra) {
if (computed) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test(jQuery.css(elem, "display")) && elem.offsetWidth === 0 ?
jQuery.swap(elem, cssShow, function () {
return getWidthOrHeight(elem, name, extra);
}) :
getWidthOrHeight(elem, name, extra);
}
},
set: function (elem, value, extra) {
var styles = extra && getStyles(elem);
return setPositiveNumber(elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css(elem, "boxSizing", false, styles) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf(support.reliableMarginRight,
function (elem, computed) {
if (computed) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap(elem, {"display": "inline-block"},
curCSS, [elem, "marginRight"]);
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function (prefix, suffix) {
jQuery.cssHooks[prefix + suffix] = {
expand: function (value) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [value];
for (; i < 4; i++) {
expanded[prefix + cssExpand[i] + suffix] =
parts[i] || parts[i - 2] || parts[0];
}
return expanded;
}
};
if (!rmargin.test(prefix)) {
jQuery.cssHooks[prefix + suffix].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function (name, value) {
return access(this, function (elem, name, value) {
var styles, len,
map = {},
i = 0;
if (jQuery.isArray(name)) {
styles = getStyles(elem);
len = name.length;
for (; i < len; i++) {
map[name[i]] = jQuery.css(elem, name[i], false, styles);
}
return map;
}
return value !== undefined ?
jQuery.style(elem, name, value) :
jQuery.css(elem, name);
}, name, value, arguments.length > 1);
},
show: function () {
return showHide(this, true);
},
hide: function () {
return showHide(this);
},
toggle: function (state) {
if (typeof state === "boolean") {
return state ? this.show() : this.hide();
}
return this.each(function () {
if (isHidden(this)) {
jQuery(this).show();
} else {
jQuery(this).hide();
}
});
}
});
function Tween(elem, options, prop, end, easing) {
return new Tween.prototype.init(elem, options, prop, end, easing);
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function (elem, options, prop, end, easing, unit) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[prop] ? "" : "px" );
},
cur: function () {
var hooks = Tween.propHooks[this.prop];
return hooks && hooks.get ?
hooks.get(this) :
Tween.propHooks._default.get(this);
},
run: function (percent) {
var eased,
hooks = Tween.propHooks[this.prop];
if (this.options.duration) {
this.pos = eased = jQuery.easing[this.easing](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if (this.options.step) {
this.options.step.call(this.elem, this.now, this);
}
if (hooks && hooks.set) {
hooks.set(this);
} else {
Tween.propHooks._default.set(this);
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function (tween) {
var result;
if (tween.elem[tween.prop] != null &&
(!tween.elem.style || tween.elem.style[tween.prop] == null)) {
return tween.elem[tween.prop];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css(tween.elem, tween.prop, "");
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function (tween) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if (jQuery.fx.step[tween.prop]) {
jQuery.fx.step[tween.prop](tween);
} else if (tween.elem.style && ( tween.elem.style[jQuery.cssProps[tween.prop]] != null || jQuery.cssHooks[tween.prop] )) {
jQuery.style(tween.elem, tween.prop, tween.now + tween.unit);
} else {
tween.elem[tween.prop] = tween.now;
}
}
}
};
// Support: IE9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function (tween) {
if (tween.elem.nodeType && tween.elem.parentNode) {
tween.elem[tween.prop] = tween.now;
}
}
};
jQuery.easing = {
linear: function (p) {
return p;
},
swing: function (p) {
return 0.5 - Math.cos(p * Math.PI) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp("^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i"),
rrun = /queueHooks$/,
animationPrefilters = [defaultPrefilter],
tweeners = {
"*": [function (prop, value) {
var tween = this.createTween(prop, value),
target = tween.cur(),
parts = rfxnum.exec(value),
unit = parts && parts[3] || ( jQuery.cssNumber[prop] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[prop] || unit !== "px" && +target ) &&
rfxnum.exec(jQuery.css(tween.elem, prop)),
scale = 1,
maxIterations = 20;
if (start && start[3] !== unit) {
// Trust units reported by jQuery.css
unit = unit || start[3];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style(tween.elem, prop, start + unit);
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while (scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations);
}
// Update tween properties
if (parts) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ?
start + ( parts[1] + 1 ) * parts[2] :
+parts[2];
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function () {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx(type, includeWidth) {
var which,
i = 0,
attrs = {height: type};
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for (; i < 4; i += 2 - includeWidth) {
which = cssExpand[i];
attrs["margin" + which] = attrs["padding" + which] = type;
}
if (includeWidth) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween(value, prop, animation) {
var tween,
collection = ( tweeners[prop] || [] ).concat(tweeners["*"]),
index = 0,
length = collection.length;
for (; index < length; index++) {
if ((tween = collection[index].call(animation, prop, value))) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter(elem, props, opts) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden(elem),
dataShow = data_priv.get(elem, "fxshow");
// handle queue: false promises
if (!opts.queue) {
hooks = jQuery._queueHooks(elem, "fx");
if (hooks.unqueued == null) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function () {
if (!hooks.unqueued) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function () {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function () {
hooks.unqueued--;
if (!jQuery.queue(elem, "fx").length) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if (elem.nodeType === 1 && ( "height" in props || "width" in props )) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE9-10 do not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [style.overflow, style.overflowX, style.overflowY];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css(elem, "display");
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
data_priv.get(elem, "olddisplay") || defaultDisplay(elem.nodeName) : display;
if (checkDisplay === "inline" && jQuery.css(elem, "float") === "none") {
style.display = "inline-block";
}
}
if (opts.overflow) {
style.overflow = "hidden";
anim.always(function () {
style.overflow = opts.overflow[0];
style.overflowX = opts.overflow[1];
style.overflowY = opts.overflow[2];
});
}
// show/hide pass
for (prop in props) {
value = props[prop];
if (rfxtypes.exec(value)) {
delete props[prop];
toggle = toggle || value === "toggle";
if (value === ( hidden ? "hide" : "show" )) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if (value === "show" && dataShow && dataShow[prop] !== undefined) {
hidden = true;
} else {
continue;
}
}
orig[prop] = dataShow && dataShow[prop] || jQuery.style(elem, prop);
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if (!jQuery.isEmptyObject(orig)) {
if (dataShow) {
if ("hidden" in dataShow) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access(elem, "fxshow", {});
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if (toggle) {
dataShow.hidden = !hidden;
}
if (hidden) {
jQuery(elem).show();
} else {
anim.done(function () {
jQuery(elem).hide();
});
}
anim.done(function () {
var prop;
data_priv.remove(elem, "fxshow");
for (prop in orig) {
jQuery.style(elem, prop, orig[prop]);
}
});
for (prop in orig) {
tween = createTween(hidden ? dataShow[prop] : 0, prop, anim);
if (!( prop in dataShow )) {
dataShow[prop] = tween.start;
if (hidden) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ((display === "none" ? defaultDisplay(elem.nodeName) : display) === "inline") {
style.display = display;
}
}
function propFilter(props, specialEasing) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for (index in props) {
name = jQuery.camelCase(index);
easing = specialEasing[name];
value = props[index];
if (jQuery.isArray(value)) {
easing = value[1];
value = props[index] = value[0];
}
if (index !== name) {
props[name] = value;
delete props[index];
}
hooks = jQuery.cssHooks[name];
if (hooks && "expand" in hooks) {
value = hooks.expand(value);
delete props[name];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for (index in value) {
if (!( index in props )) {
props[index] = value[index];
specialEasing[index] = easing;
}
}
} else {
specialEasing[name] = easing;
}
}
}
function Animation(elem, properties, options) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always(function () {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function () {
if (stopped) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max(0, animation.startTime + animation.duration - currentTime),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for (; index < length; index++) {
animation.tweens[index].run(percent);
}
deferred.notifyWith(elem, [animation, percent, remaining]);
if (percent < 1 && length) {
return remaining;
} else {
deferred.resolveWith(elem, [animation]);
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend({}, properties),
opts: jQuery.extend(true, {specialEasing: {}}, options),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function (prop, end) {
var tween = jQuery.Tween(elem, animation.opts, prop, end,
animation.opts.specialEasing[prop] || animation.opts.easing);
animation.tweens.push(tween);
return tween;
},
stop: function (gotoEnd) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if (stopped) {
return this;
}
stopped = true;
for (; index < length; index++) {
animation.tweens[index].run(1);
}
// resolve when we played the last frame
// otherwise, reject
if (gotoEnd) {
deferred.resolveWith(elem, [animation, gotoEnd]);
} else {
deferred.rejectWith(elem, [animation, gotoEnd]);
}
return this;
}
}),
props = animation.props;
propFilter(props, animation.opts.specialEasing);
for (; index < length; index++) {
result = animationPrefilters[index].call(animation, elem, props, animation.opts);
if (result) {
return result;
}
}
jQuery.map(props, createTween, animation);
if (jQuery.isFunction(animation.opts.start)) {
animation.opts.start.call(elem, animation);
}
jQuery.fx.timer(
jQuery.extend(tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress(animation.opts.progress)
.done(animation.opts.done, animation.opts.complete)
.fail(animation.opts.fail)
.always(animation.opts.always);
}
jQuery.Animation = jQuery.extend(Animation, {
tweener: function (props, callback) {
if (jQuery.isFunction(props)) {
callback = props;
props = ["*"];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for (; index < length; index++) {
prop = props[index];
tweeners[prop] = tweeners[prop] || [];
tweeners[prop].unshift(callback);
}
},
prefilter: function (callback, prepend) {
if (prepend) {
animationPrefilters.unshift(callback);
} else {
animationPrefilters.push(callback);
}
}
});
jQuery.speed = function (speed, easing, fn) {
var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing ||
jQuery.isFunction(speed) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[opt.duration] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if (opt.queue == null || opt.queue === true) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function () {
if (jQuery.isFunction(opt.old)) {
opt.old.call(this);
}
if (opt.queue) {
jQuery.dequeue(this, opt.queue);
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function (speed, to, easing, callback) {
// show any hidden elements after setting opacity to 0
return this.filter(isHidden).css("opacity", 0).show()
// animate to the value specified
.end().animate({opacity: to}, speed, easing, callback);
},
animate: function (prop, speed, easing, callback) {
var empty = jQuery.isEmptyObject(prop),
optall = jQuery.speed(speed, easing, callback),
doAnimation = function () {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation(this, jQuery.extend({}, prop), optall);
// Empty animations, or finishing resolves immediately
if (empty || data_priv.get(this, "finish")) {
anim.stop(true);
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each(doAnimation) :
this.queue(optall.queue, doAnimation);
},
stop: function (type, clearQueue, gotoEnd) {
var stopQueue = function (hooks) {
var stop = hooks.stop;
delete hooks.stop;
stop(gotoEnd);
};
if (typeof type !== "string") {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if (clearQueue && type !== false) {
this.queue(type || "fx", []);
}
return this.each(function () {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = data_priv.get(this);
if (index) {
if (data[index] && data[index].stop) {
stopQueue(data[index]);
}
} else {
for (index in data) {
if (data[index] && data[index].stop && rrun.test(index)) {
stopQueue(data[index]);
}
}
}
for (index = timers.length; index--;) {
if (timers[index].elem === this && (type == null || timers[index].queue === type)) {
timers[index].anim.stop(gotoEnd);
dequeue = false;
timers.splice(index, 1);
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if (dequeue || !gotoEnd) {
jQuery.dequeue(this, type);
}
});
},
finish: function (type) {
if (type !== false) {
type = type || "fx";
}
return this.each(function () {
var index,
data = data_priv.get(this),
queue = data[type + "queue"],
hooks = data[type + "queueHooks"],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue(this, type, []);
if (hooks && hooks.stop) {
hooks.stop.call(this, true);
}
// look for any active animations, and finish them
for (index = timers.length; index--;) {
if (timers[index].elem === this && timers[index].queue === type) {
timers[index].anim.stop(true);
timers.splice(index, 1);
}
}
// look for any animations in the old queue and finish them
for (index = 0; index < length; index++) {
if (queue[index] && queue[index].finish) {
queue[index].finish.call(this);
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each(["toggle", "show", "hide"], function (i, name) {
var cssFn = jQuery.fn[name];
jQuery.fn[name] = function (speed, easing, callback) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply(this, arguments) :
this.animate(genFx(name, true), speed, easing, callback);
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: {opacity: "show"},
fadeOut: {opacity: "hide"},
fadeToggle: {opacity: "toggle"}
}, function (name, props) {
jQuery.fn[name] = function (speed, easing, callback) {
return this.animate(props, speed, easing, callback);
};
});
jQuery.timers = [];
jQuery.fx.tick = function () {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for (; i < timers.length; i++) {
timer = timers[i];
// Checks the timer has not already been removed
if (!timer() && timers[i] === timer) {
timers.splice(i--, 1);
}
}
if (!timers.length) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function (timer) {
jQuery.timers.push(timer);
if (timer()) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function () {
if (!timerId) {
timerId = setInterval(jQuery.fx.tick, jQuery.fx.interval);
}
};
jQuery.fx.stop = function () {
clearInterval(timerId);
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function (time, type) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue(type, function (next, hooks) {
var timeout = setTimeout(next, time);
hooks.stop = function () {
clearTimeout(timeout);
};
});
};
(function () {
var input = document.createElement("input"),
select = document.createElement("select"),
opt = select.appendChild(document.createElement("option"));
input.type = "checkbox";
// Support: iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement("input");
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function (name, value) {
return access(this, jQuery.attr, name, value, arguments.length > 1);
},
removeAttr: function (name) {
return this.each(function () {
jQuery.removeAttr(this, name);
});
}
});
jQuery.extend({
attr: function (elem, name, value) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if (!elem || nType === 3 || nType === 8 || nType === 2) {
return;
}
// Fallback to prop when attributes are not supported
if (typeof elem.getAttribute === strundefined) {
return jQuery.prop(elem, name, value);
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if (nType !== 1 || !jQuery.isXMLDoc(elem)) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[name] ||
( jQuery.expr.match.bool.test(name) ? boolHook : nodeHook );
}
if (value !== undefined) {
if (value === null) {
jQuery.removeAttr(elem, name);
} else if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined) {
return ret;
} else {
elem.setAttribute(name, value + "");
return value;
}
} else if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) {
return ret;
} else {
ret = jQuery.find.attr(elem, name);
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function (elem, value) {
var name, propName,
i = 0,
attrNames = value && value.match(rnotwhite);
if (attrNames && elem.nodeType === 1) {
while ((name = attrNames[i++])) {
propName = jQuery.propFix[name] || name;
// Boolean attributes get special treatment (#10870)
if (jQuery.expr.match.bool.test(name)) {
// Set corresponding property to false
elem[propName] = false;
}
elem.removeAttribute(name);
}
}
},
attrHooks: {
type: {
set: function (elem, value) {
if (!support.radioValue && value === "radio" &&
jQuery.nodeName(elem, "input")) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute("type", value);
if (val) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function (elem, value, name) {
if (value === false) {
// Remove boolean attributes when set to false
jQuery.removeAttr(elem, name);
} else {
elem.setAttribute(name, name);
}
return name;
}
};
jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g), function (i, name) {
var getter = attrHandle[name] || jQuery.find.attr;
attrHandle[name] = function (elem, name, isXML) {
var ret, handle;
if (!isXML) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[name];
attrHandle[name] = ret;
ret = getter(elem, name, isXML) != null ?
name.toLowerCase() :
null;
attrHandle[name] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function (name, value) {
return access(this, jQuery.prop, name, value, arguments.length > 1);
},
removeProp: function (name) {
return this.each(function () {
delete this[jQuery.propFix[name] || name];
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function (elem, name, value) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if (!elem || nType === 3 || nType === 8 || nType === 2) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
if (notxml) {
// Fix name and attach hooks
name = jQuery.propFix[name] || name;
hooks = jQuery.propHooks[name];
}
if (value !== undefined) {
return hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined ?
ret :
( elem[name] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null ?
ret :
elem[name];
}
},
propHooks: {
tabIndex: {
get: function (elem) {
return elem.hasAttribute("tabindex") || rfocusable.test(elem.nodeName) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if (!support.optSelected) {
jQuery.propHooks.selected = {
get: function (elem) {
var parent = elem.parentNode;
if (parent && parent.parentNode) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function () {
jQuery.propFix[this.toLowerCase()] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function (value) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).addClass(value.call(this, j, this.className));
});
}
if (proceed) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match(rnotwhite) || [];
for (; i < len; i++) {
elem = this[i];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace(rclass, " ") :
" "
);
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
if (cur.indexOf(" " + clazz + " ") < 0) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim(cur);
if (elem.className !== finalValue) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function (value) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).removeClass(value.call(this, j, this.className));
});
}
if (proceed) {
classes = ( value || "" ).match(rnotwhite) || [];
for (; i < len; i++) {
elem = this[i];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace(rclass, " ") :
""
);
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
// Remove *all* instances
while (cur.indexOf(" " + clazz + " ") >= 0) {
cur = cur.replace(" " + clazz + " ", " ");
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim(cur) : "";
if (elem.className !== finalValue) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function (value, stateVal) {
var type = typeof value;
if (typeof stateVal === "boolean" && type === "string") {
return stateVal ? this.addClass(value) : this.removeClass(value);
}
if (jQuery.isFunction(value)) {
return this.each(function (i) {
jQuery(this).toggleClass(value.call(this, i, this.className, stateVal), stateVal);
});
}
return this.each(function () {
if (type === "string") {
// toggle individual class names
var className,
i = 0,
self = jQuery(this),
classNames = value.match(rnotwhite) || [];
while ((className = classNames[i++])) {
// check each className given, space separated list
if (self.hasClass(className)) {
self.removeClass(className);
} else {
self.addClass(className);
}
}
// Toggle whole class name
} else if (type === strundefined || type === "boolean") {
if (this.className) {
// store className if set
data_priv.set(this, "__className__", this.className);
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get(this, "__className__") || "";
}
});
},
hasClass: function (selector) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for (; i < l; i++) {
if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) >= 0) {
return true;
}
}
return false;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function (value) {
var hooks, ret, isFunction,
elem = this[0];
if (!arguments.length) {
if (elem) {
hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()];
if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== undefined) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction(value);
return this.each(function (i) {
var val;
if (this.nodeType !== 1) {
return;
}
if (isFunction) {
val = value.call(this, i, jQuery(this).val());
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if (val == null) {
val = "";
} else if (typeof val === "number") {
val += "";
} else if (jQuery.isArray(val)) {
val = jQuery.map(val, function (value) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()];
// If set returns undefined, fall back to normal setting
if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function (elem) {
var val = jQuery.find.attr(elem, "value");
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim(jQuery.text(elem));
}
},
select: {
get: function (elem) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for (; i < max; i++) {
option = options[i];
// IE6-9 doesn't update selected after form reset (#2551)
if (( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup") )) {
// Get the specific value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if (one) {
return value;
}
// Multi-Selects return an array
values.push(value);
}
}
return values;
},
set: function (elem, value) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray(value),
i = options.length;
while (i--) {
option = options[i];
if ((option.selected = jQuery.inArray(option.value, values) >= 0)) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if (!optionSet) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each(["radio", "checkbox"], function () {
jQuery.valHooks[this] = {
set: function (elem, value) {
if (jQuery.isArray(value)) {
return ( elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0 );
}
}
};
if (!support.checkOn) {
jQuery.valHooks[this].get = function (elem) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function (i, name) {
// Handle event binding
jQuery.fn[name] = function (data, fn) {
return arguments.length > 0 ?
this.on(name, null, data, fn) :
this.trigger(name);
};
});
jQuery.fn.extend({
hover: function (fnOver, fnOut) {
return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
},
bind: function (types, data, fn) {
return this.on(types, null, data, fn);
},
unbind: function (types, fn) {
return this.off(types, null, fn);
},
delegate: function (selector, types, data, fn) {
return this.on(types, selector, data, fn);
},
undelegate: function (selector, types, fn) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn);
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function (data) {
return JSON.parse(data + "");
};
// Cross-browser xml parsing
jQuery.parseXML = function (data) {
var xml, tmp;
if (!data || typeof data !== "string") {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString(data, "text/xml");
} catch (e) {
xml = undefined;
}
if (!xml || xml.getElementsByTagName("parsererror").length) {
jQuery.error("Invalid XML: " + data);
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch (e) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports(structure) {
// dataTypeExpression is optional and defaults to "*"
return function (dataTypeExpression, func) {
if (typeof dataTypeExpression !== "string") {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match(rnotwhite) || [];
if (jQuery.isFunction(func)) {
// For each dataType in the dataTypeExpression
while ((dataType = dataTypes[i++])) {
// Prepend if requested
if (dataType[0] === "+") {
dataType = dataType.slice(1) || "*";
(structure[dataType] = structure[dataType] || []).unshift(func);
// Otherwise append
} else {
(structure[dataType] = structure[dataType] || []).push(func);
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect(dataType) {
var selected;
inspected[dataType] = true;
jQuery.each(structure[dataType] || [], function (_, prefilterOrFactory) {
var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[dataTypeOrTransport]) {
options.dataTypes.unshift(dataTypeOrTransport);
inspect(dataTypeOrTransport);
return false;
} else if (seekingTransport) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*");
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend(target, src) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for (key in src) {
if (src[key] !== undefined) {
( flatOptions[key] ? target : ( deep || (deep = {}) ) )[key] = src[key];
}
}
if (deep) {
jQuery.extend(true, target, deep);
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses(s, jqXHR, responses) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while (dataTypes[0] === "*") {
dataTypes.shift();
if (ct === undefined) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if (ct) {
for (type in contents) {
if (contents[type] && contents[type].test(ct)) {
dataTypes.unshift(type);
break;
}
}
}
// Check to see if we have a response for the expected dataType
if (dataTypes[0] in responses) {
finalDataType = dataTypes[0];
} else {
// Try convertible dataTypes
for (type in responses) {
if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) {
finalDataType = type;
break;
}
if (!firstDataType) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if (finalDataType) {
if (finalDataType !== dataTypes[0]) {
dataTypes.unshift(finalDataType);
}
return responses[finalDataType];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert(s, response, jqXHR, isSuccess) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if (dataTypes[1]) {
for (conv in s.converters) {
converters[conv.toLowerCase()] = s.converters[conv];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while (current) {
if (s.responseFields[current]) {
jqXHR[s.responseFields[current]] = response;
}
// Apply the dataFilter if provided
if (!prev && isSuccess && s.dataFilter) {
response = s.dataFilter(response, s.dataType);
}
prev = current;
current = dataTypes.shift();
if (current) {
// There's only work to do if current dataType is non-auto
if (current === "*") {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if (prev !== "*" && prev !== current) {
// Seek a direct converter
conv = converters[prev + " " + current] || converters["* " + current];
// If none found, seek a pair
if (!conv) {
for (conv2 in converters) {
// If conv2 outputs current
tmp = conv2.split(" ");
if (tmp[1] === current) {
// If prev can be converted to accepted input
conv = converters[prev + " " + tmp[0]] ||
converters["* " + tmp[0]];
if (conv) {
// Condense equivalence converters
if (conv === true) {
conv = converters[conv2];
// Otherwise, insert the intermediate dataType
} else if (converters[conv2] !== true) {
current = tmp[0];
dataTypes.unshift(tmp[1]);
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if (conv !== true) {
// Unless errors are allowed to bubble, catch and return them
if (conv && s["throws"]) {
response = conv(response);
} else {
try {
response = conv(response);
} catch (e) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return {state: "success", data: response};
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test(ajaxLocParts[1]),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function (target, settings) {
return settings ?
// Building a settings object
ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) :
// Extending ajaxSettings
ajaxExtend(jQuery.ajaxSettings, target);
},
ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
ajaxTransport: addToPrefiltersOrTransports(transports),
// Main method
ajax: function (url, options) {
// If url is an object, simulate pre-1.5 signature
if (typeof url === "object") {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup({}, options),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery(callbackContext) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function (key) {
var match;
if (state === 2) {
if (!responseHeaders) {
responseHeaders = {};
while ((match = rheaders.exec(responseHeadersString))) {
responseHeaders[match[1].toLowerCase()] = match[2];
}
}
match = responseHeaders[key.toLowerCase()];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function () {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function (name, value) {
var lname = name.toLowerCase();
if (!state) {
name = requestHeadersNames[lname] = requestHeadersNames[lname] || name;
requestHeaders[name] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function (type) {
if (!state) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function (map) {
var code;
if (map) {
if (state < 2) {
for (code in map) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[code] = [statusCode[code], map[code]];
}
} else {
// Execute the appropriate callbacks
jqXHR.always(map[jqXHR.status]);
}
}
return this;
},
// Cancel the request
abort: function (statusText) {
var finalText = statusText || strAbort;
if (transport) {
transport.abort(finalText);
}
done(0, finalText);
return this;
}
};
// Attach deferreds
deferred.promise(jqXHR).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace(rhash, "")
.replace(rprotocol, ajaxLocParts[1] + "//");
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(rnotwhite) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if (s.crossDomain == null) {
parts = rurl.exec(s.url.toLowerCase());
s.crossDomain = !!( parts &&
( parts[1] !== ajaxLocParts[1] || parts[2] !== ajaxLocParts[2] ||
( parts[3] || ( parts[1] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[3] || ( ajaxLocParts[1] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if (s.data && s.processData && typeof s.data !== "string") {
s.data = jQuery.param(s.data, s.traditional);
}
// Apply prefilters
inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);
// If request was aborted inside a prefilter, stop there
if (state === 2) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if (fireGlobals && jQuery.active++ === 0) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test(s.type);
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if (!s.hasContent) {
// If data is available, append data to url
if (s.data) {
cacheURL = ( s.url += ( rquery.test(cacheURL) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if (s.cache === false) {
s.url = rts.test(cacheURL) ?
// If there is already a '_' parameter, set its value
cacheURL.replace(rts, "$1_=" + nonce++) :
// Otherwise add one to the end
cacheURL + ( rquery.test(cacheURL) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if (s.ifModified) {
if (jQuery.lastModified[cacheURL]) {
jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]);
}
if (jQuery.etag[cacheURL]) {
jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]);
}
}
// Set the correct header, if data is being sent
if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
jqXHR.setRequestHeader("Content-Type", s.contentType);
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[0] && s.accepts[s.dataTypes[0]] ?
s.accepts[s.dataTypes[0]] + ( s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts["*"]
);
// Check for headers option
for (i in s.headers) {
jqXHR.setRequestHeader(i, s.headers[i]);
}
// Allow custom headers/mimetypes and early abort
if (s.beforeSend && ( s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2 )) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for (i in {success: 1, error: 1, complete: 1}) {
jqXHR[i](s[i]);
}
// Get transport
transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);
// If no transport, we auto-abort
if (!transport) {
done(-1, "No Transport");
} else {
jqXHR.readyState = 1;
// Send global event
if (fireGlobals) {
globalEventContext.trigger("ajaxSend", [jqXHR, s]);
}
// Timeout
if (s.async && s.timeout > 0) {
timeoutTimer = setTimeout(function () {
jqXHR.abort("timeout");
}, s.timeout);
}
try {
state = 1;
transport.send(requestHeaders, done);
} catch (e) {
// Propagate exception as error if not done
if (state < 2) {
done(-1, e);
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done(status, nativeStatusText, responses, headers) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if (state === 2) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if (responses) {
response = ajaxHandleResponses(s, jqXHR, responses);
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert(s, response, jqXHR, isSuccess);
// If successful, handle type chaining
if (isSuccess) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if (s.ifModified) {
modified = jqXHR.getResponseHeader("Last-Modified");
if (modified) {
jQuery.lastModified[cacheURL] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if (modified) {
jQuery.etag[cacheURL] = modified;
}
}
// if no content
if (status === 204 || s.type === "HEAD") {
statusText = "nocontent";
// if not modified
} else if (status === 304) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if (status || !statusText) {
statusText = "error";
if (status < 0) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if (isSuccess) {
deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
} else {
deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
}
// Status-dependent callbacks
jqXHR.statusCode(statusCode);
statusCode = undefined;
if (fireGlobals) {
globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError",
[jqXHR, s, isSuccess ? success : error]);
}
// Complete
completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);
if (fireGlobals) {
globalEventContext.trigger("ajaxComplete", [jqXHR, s]);
// Handle the global AJAX counter
if (!( --jQuery.active )) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function (url, data, callback) {
return jQuery.get(url, data, callback, "json");
},
getScript: function (url, callback) {
return jQuery.get(url, undefined, callback, "script");
}
});
jQuery.each(["get", "post"], function (i, method) {
jQuery[method] = function (url, data, callback, type) {
// shift arguments if data argument was omitted
if (jQuery.isFunction(data)) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each(["ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend"], function (i, type) {
jQuery.fn[type] = function (fn) {
return this.on(type, fn);
};
});
jQuery._evalUrl = function (url) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function (html) {
var wrap;
if (jQuery.isFunction(html)) {
return this.each(function (i) {
jQuery(this).wrapAll(html.call(this, i));
});
}
if (this[0]) {
// The elements to wrap the target around
wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true);
if (this[0].parentNode) {
wrap.insertBefore(this[0]);
}
wrap.map(function () {
var elem = this;
while (elem.firstElementChild) {
elem = elem.firstElementChild;
}
return elem;
}).append(this);
}
return this;
},
wrapInner: function (html) {
if (jQuery.isFunction(html)) {
return this.each(function (i) {
jQuery(this).wrapInner(html.call(this, i));
});
}
return this.each(function () {
var self = jQuery(this),
contents = self.contents();
if (contents.length) {
contents.wrapAll(html);
} else {
self.append(html);
}
});
},
wrap: function (html) {
var isFunction = jQuery.isFunction(html);
return this.each(function (i) {
jQuery(this).wrapAll(isFunction ? html.call(this, i) : html);
});
},
unwrap: function () {
return this.parent().each(function () {
if (!jQuery.nodeName(this, "body")) {
jQuery(this).replaceWith(this.childNodes);
}
}).end();
}
});
jQuery.expr.filters.hidden = function (elem) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function (elem) {
return !jQuery.expr.filters.hidden(elem);
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams(prefix, obj, traditional, add) {
var name;
if (jQuery.isArray(obj)) {
// Serialize array item.
jQuery.each(obj, function (i, v) {
if (traditional || rbracket.test(prefix)) {
// Treat each array item as a scalar.
add(prefix, v);
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add);
}
});
} else if (!traditional && jQuery.type(obj) === "object") {
// Serialize object item.
for (name in obj) {
buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
}
} else {
// Serialize scalar item.
add(prefix, obj);
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function (a, traditional) {
var prefix,
s = [],
add = function (key, value) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction(value) ? value() : ( value == null ? "" : value );
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if (traditional === undefined) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if (jQuery.isArray(a) || ( a.jquery && !jQuery.isPlainObject(a) )) {
// Serialize the form elements
jQuery.each(a, function () {
add(this.name, this.value);
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for (prefix in a) {
buildParams(prefix, a[prefix], traditional, add);
}
}
// Return the resulting serialization
return s.join("&").replace(r20, "+");
};
jQuery.fn.extend({
serialize: function () {
return jQuery.param(this.serializeArray());
},
serializeArray: function () {
return this.map(function () {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop(this, "elements");
return elements ? jQuery.makeArray(elements) : this;
})
.filter(function () {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery(this).is(":disabled") &&
rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) &&
( this.checked || !rcheckableType.test(type) );
})
.map(function (i, elem) {
var val = jQuery(this).val();
return val == null ?
null :
jQuery.isArray(val) ?
jQuery.map(val, function (val) {
return {name: elem.name, value: val.replace(rCRLF, "\r\n")};
}) :
{name: elem.name, value: val.replace(rCRLF, "\r\n")};
}).get();
}
});
jQuery.ajaxSettings.xhr = function () {
try {
return new XMLHttpRequest();
} catch (e) {
}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open requests must be manually aborted on unload (#5280)
if (window.ActiveXObject) {
jQuery(window).on("unload", function () {
for (var key in xhrCallbacks) {
xhrCallbacks[key]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function (options) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if (support.cors || xhrSupported && !options.crossDomain) {
return {
send: function (headers, complete) {
var i,
xhr = options.xhr(),
id = ++xhrId;
xhr.open(options.type, options.url, options.async, options.username, options.password);
// Apply custom fields if provided
if (options.xhrFields) {
for (i in options.xhrFields) {
xhr[i] = options.xhrFields[i];
}
}
// Override mime type if needed
if (options.mimeType && xhr.overrideMimeType) {
xhr.overrideMimeType(options.mimeType);
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if (!options.crossDomain && !headers["X-Requested-With"]) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for (i in headers) {
xhr.setRequestHeader(i, headers[i]);
}
// Callback
callback = function (type) {
return function () {
if (callback) {
delete xhrCallbacks[id];
callback = xhr.onload = xhr.onerror = null;
if (type === "abort") {
xhr.abort();
} else if (type === "error") {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[xhr.status] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[id] = callback("abort");
try {
// Do send the request (this may raise an exception)
xhr.send(options.hasContent && options.data || null);
} catch (e) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if (callback) {
throw e;
}
}
},
abort: function () {
if (callback) {
callback();
}
}
};
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function (text) {
jQuery.globalEval(text);
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter("script", function (s) {
if (s.cache === undefined) {
s.cache = false;
}
if (s.crossDomain) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport("script", function (s) {
// This transport only deals with cross domain requests
if (s.crossDomain) {
var script, callback;
return {
send: function (_, complete) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function (evt) {
script.remove();
callback = null;
if (evt) {
complete(evt.type === "error" ? 404 : 200, evt.type);
}
}
);
document.head.appendChild(script[0]);
},
abort: function () {
if (callback) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function () {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[callback] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter("json jsonp", function (s, originalSettings, jqXHR) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test(s.url) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test(s.data) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if (jsonProp || s.dataTypes[0] === "jsonp") {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if (jsonProp) {
s[jsonProp] = s[jsonProp].replace(rjsonp, "$1" + callbackName);
} else if (s.jsonp !== false) {
s.url += ( rquery.test(s.url) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function () {
if (!responseContainer) {
jQuery.error(callbackName + " was not called");
}
return responseContainer[0];
};
// force json dataType
s.dataTypes[0] = "json";
// Install callback
overwritten = window[callbackName];
window[callbackName] = function () {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function () {
// Restore preexisting value
window[callbackName] = overwritten;
// Save back as free
if (s[callbackName]) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push(callbackName);
}
// Call if it was a function and we have a response
if (responseContainer && jQuery.isFunction(overwritten)) {
overwritten(responseContainer[0]);
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function (data, context, keepScripts) {
if (!data || typeof data !== "string") {
return null;
}
if (typeof context === "boolean") {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec(data),
scripts = !keepScripts && [];
// Single tag
if (parsed) {
return [context.createElement(parsed[1])];
}
parsed = jQuery.buildFragment([data], context, scripts);
if (scripts && scripts.length) {
jQuery(scripts).remove();
}
return jQuery.merge([], parsed.childNodes);
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function (url, params, callback) {
if (typeof url !== "string" && _load) {
return _load.apply(this, arguments);
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if (off >= 0) {
selector = jQuery.trim(url.slice(off));
url = url.slice(0, off);
}
// If it's a function
if (jQuery.isFunction(params)) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if (params && typeof params === "object") {
type = "POST";
}
// If we have elements to modify, make the request
if (self.length > 0) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function (responseText) {
// Save response for use in complete callback
response = arguments;
self.html(selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
// Otherwise use the full result
responseText);
}).complete(callback && function (jqXHR, status) {
self.each(callback, response || [jqXHR.responseText, status, jqXHR]);
});
}
return this;
};
jQuery.expr.filters.animated = function (elem) {
return jQuery.grep(jQuery.timers, function (fn) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow(elem) {
return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function (elem, options, i) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css(elem, "position"),
curElem = jQuery(elem),
props = {};
// Set position first, in-case top/left are set even on static elem
if (position === "static") {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css(elem, "top");
curCSSLeft = jQuery.css(elem, "left");
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if (calculatePosition) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat(curCSSTop) || 0;
curLeft = parseFloat(curCSSLeft) || 0;
}
if (jQuery.isFunction(options)) {
options = options.call(elem, i, curOffset);
}
if (options.top != null) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if (options.left != null) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ("using" in options) {
options.using.call(elem, props);
} else {
curElem.css(props);
}
}
};
jQuery.fn.extend({
offset: function (options) {
if (arguments.length) {
return options === undefined ?
this :
this.each(function (i) {
jQuery.offset.setOffset(this, options, i);
});
}
var docElem, win,
elem = this[0],
box = {top: 0, left: 0},
doc = elem && elem.ownerDocument;
if (!doc) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if (!jQuery.contains(docElem, elem)) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if (typeof elem.getBoundingClientRect !== strundefined) {
box = elem.getBoundingClientRect();
}
win = getWindow(doc);
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
},
position: function () {
if (!this[0]) {
return;
}
var offsetParent, offset,
elem = this[0],
parentOffset = {top: 0, left: 0};
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if (jQuery.css(elem, "position") === "fixed") {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if (!jQuery.nodeName(offsetParent[0], "html")) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css(offsetParent[0], "borderTopWidth", true);
parentOffset.left += jQuery.css(offsetParent[0], "borderLeftWidth", true);
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true),
left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true)
};
},
offsetParent: function () {
return this.map(function () {
var offsetParent = this.offsetParent || docElem;
while (offsetParent && ( !jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static" )) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function (method, prop) {
var top = "pageYOffset" === prop;
jQuery.fn[method] = function (val) {
return access(this, function (elem, method, val) {
var win = getWindow(elem);
if (val === undefined) {
return win ? win[prop] : elem[method];
}
if (win) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[method] = val;
}
}, method, val, arguments.length, null);
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each(["top", "left"], function (i, prop) {
jQuery.cssHooks[prop] = addGetHookIf(support.pixelPosition,
function (elem, computed) {
if (computed) {
computed = curCSS(elem, prop);
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test(computed) ?
jQuery(elem).position()[prop] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each({Height: "height", Width: "width"}, function (name, type) {
jQuery.each({
padding: "inner" + name,
content: type,
"": "outer" + name
}, function (defaultExtra, funcName) {
// margin is only for outerHeight, outerWidth
jQuery.fn[funcName] = function (margin, value) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access(this, function (elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement["client" + name];
}
// Get document width or height
if (elem.nodeType === 9) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body["scroll" + name], doc["scroll" + name],
elem.body["offset" + name], doc["offset" + name],
doc["client" + name]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) :
// Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function () {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if (typeof define === "function" && define.amd) {
define("jquery", [], function () {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function (deep) {
if (window.$ === jQuery) {
window.$ = _$;
}
if (deep && window.jQuery === jQuery) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if (typeof noGlobal === strundefined) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
/*!
* Bootstrap v3.2.0 (http://getbootstrap.com)
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
/* ========================================================================
* Bootstrap: transition.js v3.2.0
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition: 'webkitTransitionEnd',
MozTransition: 'transitionend',
OTransition: 'oTransitionEnd otransitionend',
transition: 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return {end: transEndEventNames[name]}
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () {
called = true
})
var callback = function () {
if (!called) $($el).trigger($.support.transition.end)
}
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.2.0
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.2.0'
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(150) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.2.0
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.2.0'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state = state + 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
$el[val](data[state] == null ? this.options[state] : data[state])
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
else $parent.find('.active').removeClass('active')
}
if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
}
if (changed) this.$element.toggleClass('active')
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document).on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
Plugin.call($btn, 'toggle')
e.preventDefault()
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.2.0
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused =
this.sliding =
this.interval =
this.$active =
this.$items = null
this.options.pause == 'hover' && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.2.0'
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true
}
Carousel.prototype.keydown = function (e) {
switch (e.which) {
case 37:
this.prev();
break
case 39:
this.next();
break
default:
return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () {
that.to(pos)
}) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || $active[type]()
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var fallback = type == 'next' ? 'first' : 'last'
var that = this
if (!$next.length) {
if (!this.options.wrap) return
$next = this.$element.find('.item')[fallback]()
}
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
}) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
$(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
})
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.2.0
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent) this.$parent = $(this.options.parent)
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.2.0'
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning) return
Plugin.call(actives, 'hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(350)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse')
.removeClass('in')
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(350)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && option == 'show') option = !option
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var href
var $this = $(this)
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
}
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.2.0
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.2.0'
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
}
var relatedTarget = {relatedTarget: this}
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.trigger('focus')
$parent
.toggleClass('open')
.trigger('shown.bs.dropdown', relatedTarget)
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27)/.test(e.keyCode)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.divider):visible a'
var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
if (!$items.length) return
var index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index-- // up
if (e.keyCode == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $parent = getParent($(this))
var relatedTarget = {relatedTarget: this}
if (!$parent.hasClass('open')) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
})
}
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) {
e.stopPropagation()
})
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle + ', [role="menu"], [role="listbox"]', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.2.0
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$backdrop =
this.isShown = null
this.scrollbarWidth = 0
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.2.0'
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', {relatedTarget: _relatedTarget})
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.$body.addClass('modal-open')
this.setScrollbar()
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', {relatedTarget: _relatedTarget})
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(300) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.$body.removeClass('modal-open')
this.resetScrollbar()
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(300) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(150) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(150) :
callbackRemove()
} else if (callback) {
callback()
}
}
Modal.prototype.checkScrollbar = function () {
if (document.body.clientWidth >= window.innerWidth) return
this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', '')
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({remote: !/#/.test(href) && href}, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.2.0
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.2.0'
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, {
trigger: 'manual',
selector: ''
})) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(document.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({top: 0, left: 0, display: 'block'})
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var $parent = this.$element.parent()
var parentDim = this.getPosition($parent)
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - parentDim.scroll > parentDim.height ? 'top' :
placement == 'top' && pos.top - parentDim.scroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < parentDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(150) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var arrowDelta = delta.left ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowPosition = delta.left ? 'left' : 'top'
var arrowOffsetPosition = delta.left ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function () {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
this.$element.removeAttr('aria-describedby')
function complete() {
if (that.hoverState != 'in') $tip.detach()
that.$element.trigger('hidden.bs.' + that.type)
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(150) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.fixTitle = function () {
var $e = this.$element
if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : null, {
scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop(),
width: isBody ? $(window).width() : $element.outerWidth(),
height: isBody ? $(window).height() : $element.outerHeight()
}, isBody ? {top: 0, left: 0} : $element.offset())
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? {
top: pos.top + pos.height,
left: pos.left + pos.width / 2 - actualWidth / 2
} :
placement == 'top' ? {
top: pos.top - actualHeight,
left: pos.left + pos.width / 2 - actualWidth / 2
} :
placement == 'left' ? {
top: pos.top + pos.height / 2 - actualHeight / 2,
left: pos.left - actualWidth
} :
/* placement == 'right' */ {
top: pos.top + pos.height / 2 - actualHeight / 2,
left: pos.left + pos.width
}
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = {top: 0, left: 0}
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
return (this.$tip = this.$tip || $(this.options.template))
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.validate = function () {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function () {
clearTimeout(this.timeout)
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.2.0
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.2.0'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').empty()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
Popover.prototype.tip = function () {
if (!this.$tip) this.$tip = $(this.options.template)
return this.$tip
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && option == 'destroy') return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.2.0
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this)
this.$body = $('body')
this.$scrollElement = $(element).is('body') ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', process)
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.2.0'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var offsetMethod = 'offset'
var offsetBase = 0
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
var self = this
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) {
return a[0] - b[0]
})
.each(function () {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop <= offsets[0]) {
return activeTarget != (i = targets[0]) && this.activate(i)
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.2.0
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
this.element = $(element)
}
Tab.VERSION = '3.2.0'
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: previous
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(150) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.2.0
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin =
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.2.0'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
if (this.affixed === affix) return
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger($.Event(affixType.replace('affix', 'affixed')))
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - this.$element.height() - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom) data.offset.bottom = data.offsetBottom
if (data.offsetTop) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
/*! DataTables 1.10.0-dev
* ©2008-2013 SpryMedia Ltd - datatables.net/license
*/
/**
* @summary DataTables
* @description Paginate, search and order HTML tables
* @version 1.10.0-dev
* @file jquery.dataTables.js
* @author SpryMedia Ltd (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
* @copyright Copyright 2008-2013 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license
*
* This source file 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 license files for details.
*
* For details please refer to: http://www.datatables.net
*/
/*jslint evil: true, undef: true, browser: true */
/*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_empty,_intVal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetRowData,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidateRow,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnScrollingWidthAdjust,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnScrollBarWidth,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/
(/** @lends <global> */function (window, document, $, undefined) {
(function (factory) {
"use strict";
// Define as an AMD module if possible
if (typeof define === 'function' && define.amd) {
define('datatables', ['jquery'], factory);
}
/* Define using browser globals otherwise
* Prevent multiple instantiations if the script is loaded twice
*/
else if (jQuery && !jQuery.fn.dataTable) {
factory(jQuery);
}
}
(/** @lends <global> */function ($) {
"use strict";
/**
* DataTables is a plug-in for the jQuery Javascript library. It is a highly
* flexible tool, based upon the foundations of progressive enhancement,
* which will add advanced interaction controls to any HTML table. For a
* full list of features please refer to
* [DataTables.net](href="http://datatables.net).
*
* Note that the `DataTable` object is not a global variable but is aliased
* to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may
* be accessed.
*
* @class
* @param {object} [init={}] Configuration object for DataTables. Options
* are defined by {@link DataTable.defaults}
* @requires jQuery 1.3+
*
* @example
* // Basic initialisation
* $(document).ready( function {
* $('#example').dataTable();
* } );
*
* @example
* // Initialisation with configuration options - in this case, disable
* // pagination and sorting.
* $(document).ready( function {
* $('#example').dataTable( {
* "paginate": false,
* "sort": false
* } );
* } );
*/
var DataTable;
/*
* It is useful to have variables which are scoped locally so only the
* DataTables functions can access them and they don't leak into global space.
* At the same time these functions are often useful over multiple files in the
* core and API, so we list, or at least document, all variables which are used
* by DataTables as private variables here. This also ensures that there is no
* clashing of variable names and that they can easily referenced for reuse.
*/
// Defined else where
// _selector_run
// _selector_opts
// _selector_first
// _selector_row_indexes
var _ext; // DataTable.ext
var _Api; // DataTable.Api
var _api_register; // DataTable.Api.register
var _api_registerPlural; // DataTable.Api.registerPlural
var _re_new_lines = /[\r\n]/g;
var _re_html = /<.*?>/g;
var _re_formatted_numeric = /[',$£€¥%]/g;
var _re_date_start = /^[\d\+\-a-zA-Z]/;
var _empty = function (d) {
return !d || d === '-' ? true : false;
};
var _intVal = function (s) {
var integer = parseInt(s, 10);
return !isNaN(integer) && isFinite(s) ? integer : null;
};
var _isNumber = function (d, formatted) {
if (formatted && typeof d === 'string') {
d = d.replace(_re_formatted_numeric, '');
}
return !d || d === '-' || (!isNaN(parseFloat(d)) && isFinite(d));
};
// A string without HTML in it can be considered to be HTML still
var _isHtml = function (d) {
return !d || typeof d === 'string';
};
var _htmlNumeric = function (d, formatted) {
if (_empty(d)) {
return true;
}
var html = _isHtml(d);
return !html ?
null :
_isNumber(_stripHtml(d), formatted) ?
true :
null;
};
var _pluck = function (a, prop, prop2) {
var out = [];
var i = 0, ien = a.length;
// Could have the test in the loop for slightly smaller code, but speed
// is essential here
if (prop2 !== undefined) {
for (; i < ien; i++) {
if (a[i] && a[i][prop]) {
out.push(a[i][prop][prop2]);
}
}
}
else {
for (; i < ien; i++) {
if (a[i]) {
out.push(a[i][prop]);
}
}
}
return out;
};
// Basically the same as _pluck, but rather than looping over `a` we use `order`
// as the indexes to pick from `a`
var _pluck_order = function (a, order, prop, prop2) {
var out = [];
var i = 0, ien = order.length;
// Could have the test in the loop for slightly smaller code, but speed
// is essential here
if (prop2 !== undefined) {
for (; i < ien; i++) {
out.push(a[order[i]][prop][prop2]);
}
}
else {
for (; i < ien; i++) {
out.push(a[order[i]][prop]);
}
}
return out;
};
var _range = function (len, start) {
var out = [];
var end;
if (start === undefined) {
start = 0;
end = len;
}
else {
end = start;
start = len;
}
for (var i = start; i < end; i++) {
out.push(i);
}
return out;
};
var _stripHtml = function (d) {
return d.replace(_re_html, '');
};
/**
* Find the unique elements in a source array.
*
* @param {array} src Source array
* @return {array} Array of unique items
* @ignore
*/
var _unique = function (src) {
// A faster unique method is to use object keys to identify used values,
// but this doesn't work with arrays or objects, which we must also
// consider. See jsperf.com/compare-array-unique-versions/4 for more
// information.
var
out = [],
val,
i, ien = src.length,
j, k = 0;
again: for (i = 0; i < ien; i++) {
val = src[i];
for (j = 0; j < k; j++) {
if (out[j] === val) {
continue again;
}
}
out.push(val);
k++;
}
return out;
};
/**
* Create a mapping object that allows camel case parameters to be looked up
* for their Hungarian counterparts. The mapping is stored in a private
* parameter called `_hungarianMap` which can be accessed on the source object.
* @param {object} o
* @memberof DataTable#oApi
*/
function _fnHungarianMap(o) {
var
hungarian = 'a aa ao as b fn i m o s ',
match,
newKey,
map = {};
$.each(o, function (key, val) {
match = key.match(/^([^A-Z]+?)([A-Z])/);
if (match && hungarian.indexOf(match[1] + ' ') !== -1) {
newKey = key.replace(match[0], match[2].toLowerCase());
map[newKey] = key;
if (match[1] === 'o') {
_fnHungarianMap(o[key]);
}
}
});
o._hungarianMap = map;
}
/**
* Convert from camel case parameters to Hungarian, based on a Hungarian map
* created by _fnHungarianMap.
* @param {object} src The model object which holds all parameters that can be
* mapped.
* @param {object} user The object to convert from camel case to Hungarian.
* @param {boolean} force When set to `true`, properties which already have a
* Hungarian value in the `user` object will be overwritten. Otherwise they
* won't be.
* @memberof DataTable#oApi
*/
function _fnCamelToHungarian(src, user, force) {
if (!src._hungarianMap) {
_fnHungarianMap(src);
}
var hungarianKey;
$.each(user, function (key, val) {
hungarianKey = src._hungarianMap[key];
if (hungarianKey !== undefined && (force || user[hungarianKey] === undefined)) {
user[hungarianKey] = user[key];
if (hungarianKey.charAt(0) === 'o') {
_fnCamelToHungarian(src[hungarianKey], user[key]);
}
}
});
}
/**
* Language compatibility - when certain options are given, and others aren't, we
* need to duplicate the values over, in order to provide backwards compatibility
* with older language files.
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnLanguageCompat(oLanguage) {
var oDefaults = DataTable.defaults.oLanguage;
var zeroRecords = oLanguage.sZeroRecords;
/* Backwards compatibility - if there is no sEmptyTable given, then use the same as
* sZeroRecords - assuming that is given.
*/
if (!oLanguage.sEmptyTable && zeroRecords &&
oDefaults.sEmptyTable === "No data available in table") {
_fnMap(oLanguage, oLanguage, 'sZeroRecords', 'sEmptyTable');
}
/* Likewise with loading records */
if (!oLanguage.sLoadingRecords && zeroRecords &&
oDefaults.sLoadingRecords === "Loading...") {
_fnMap(oLanguage, oLanguage, 'sZeroRecords', 'sLoadingRecords');
}
}
/**
* Map one parameter onto another
* @param {object} o Object to map
* @param {*} knew The new parameter name
* @param {*} old The old parameter name
*/
var _fnCompatMap = function (o, knew, old) {
if (o[knew] !== undefined) {
o[old] = o[knew];
}
};
/**
* Provide backwards compatibility for the main DT options. Note that the new
* options are mapped onto the old parameters, so this is an external interface
* change only.
* @param {object} init Object to map
*/
function _fnCompatOpts(init) {
_fnCompatMap(init, 'ordering', 'bSort');
_fnCompatMap(init, 'orderMulti', 'bSortMulti');
_fnCompatMap(init, 'orderClasses', 'bSortClasses');
_fnCompatMap(init, 'orderCellsTop', 'bSortCellsTop');
_fnCompatMap(init, 'order', 'aaSorting');
_fnCompatMap(init, 'orderFixed', 'aaSortingFixed');
_fnCompatMap(init, 'paging', 'bPaginate');
_fnCompatMap(init, 'pagingType', 'sPaginationType');
_fnCompatMap(init, 'pageLength', 'iDisplayLength');
_fnCompatMap(init, 'searching', 'bFilter');
}
/**
* Provide backwards compatibility for column options. Note that the new options
* are mapped onto the old parameters, so this is an external interface change
* only.
* @param {object} init Object to map
*/
function _fnCompatCols(init) {
_fnCompatMap(init, 'orderable', 'bSortable');
_fnCompatMap(init, 'orderData', 'aDataSort');
_fnCompatMap(init, 'orderSequence', 'asSorting');
_fnCompatMap(init, 'orderDataType', 'sortDataType');
}
/**
* Browser feature detection for capabilities, quirks
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnBrowserDetect(settings) {
var browser = settings.oBrowser;
// Scrolling feature / quirks detection
var n = $('<div/>')
.css({
position: 'absolute',
top: 0,
left: 0,
height: 1,
width: 1,
overflow: 'hidden'
})
.append(
$('<div/>')
.css({
position: 'absolute',
top: 1,
left: 1,
width: 100,
overflow: 'scroll'
})
.append(
$('<div class="test"/>')
.css({
width: '100%',
height: 10
})
)
)
.appendTo('body');
var test = n.find('.test');
// IE6/7 will oversize a width 100% element inside a scrolling element, to
// include the width of the scrollbar, while other browsers ensure the inner
// element is contained without forcing scrolling
browser.bScrollOversize = test[0].offsetWidth === 100;
// In rtl text layout, some browsers (most, but not all) will place the
// scrollbar on the left, rather than the right.
browser.bScrollbarLeft = test.offset().left !== 1;
n.remove();
}
/**
* Add a column to the list used for the table with default values
* @param {object} oSettings dataTables settings object
* @param {node} nTh The th element for this column
* @memberof DataTable#oApi
*/
function _fnAddColumn(oSettings, nTh) {
var oDefaults = DataTable.defaults.column;
var iCol = oSettings.aoColumns.length;
var oCol = $.extend({}, DataTable.models.oColumn, oDefaults, {
"sSortingClass": oSettings.oClasses.sSortable,
"sSortingClassJUI": oSettings.oClasses.sSortJUI,
"nTh": nTh ? nTh : document.createElement('th'),
"sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '',
"aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
"mData": oDefaults.mData ? oDefaults.mData : iCol
});
oSettings.aoColumns.push(oCol);
/* Add a column specific filter */
if (oSettings.aoPreSearchCols[iCol] === undefined || oSettings.aoPreSearchCols[iCol] === null) {
oSettings.aoPreSearchCols[iCol] = $.extend(true, {}, DataTable.models.oSearch);
}
else {
var oPre = oSettings.aoPreSearchCols[iCol];
/* Don't require that the user must specify bRegex, bSmart or bCaseInsensitive */
if (oPre.bRegex === undefined) {
oPre.bRegex = true;
}
if (oPre.bSmart === undefined) {
oPre.bSmart = true;
}
if (oPre.bCaseInsensitive === undefined) {
oPre.bCaseInsensitive = true;
}
}
/* Use the column options function to initialise classes etc */
_fnColumnOptions(oSettings, iCol, null);
}
/**
* Apply options for a column
* @param {object} oSettings dataTables settings object
* @param {int} iCol column index to consider
* @param {object} oOptions object with sType, bVisible and bSearchable etc
* @memberof DataTable#oApi
*/
function _fnColumnOptions(oSettings, iCol, oOptions) {
var oCol = oSettings.aoColumns[iCol];
var oClasses = oSettings.oClasses;
/* User specified column options */
if (oOptions !== undefined && oOptions !== null) {
// Backwards compatibility
_fnCompatCols(oOptions);
// Map camel case parameters to their Hungarian counterparts
_fnCamelToHungarian(DataTable.defaults.column, oOptions);
/* Backwards compatibility for mDataProp */
if (oOptions.mDataProp !== undefined && !oOptions.mData) {
oOptions.mData = oOptions.mDataProp;
}
oCol._sManualType = oOptions.sType;
// `class` is a reserved word in Javascript, so we need to provide
// the ability to use a valid name for the camel case input
if (oOptions.className && !oOptions.sClass) {
oOptions.sClass = oOptions.className;
}
$.extend(oCol, oOptions);
_fnMap(oCol, oOptions, "sWidth", "sWidthOrig");
/* iDataSort to be applied (backwards compatibility), but aDataSort will take
* priority if defined
*/
if (typeof oOptions.iDataSort === 'number') {
oCol.aDataSort = [oOptions.iDataSort];
}
_fnMap(oCol, oOptions, "aDataSort");
}
/* Cache the data get and set functions for speed */
var mDataSrc = oCol.mData;
var mData = _fnGetObjectDataFn(mDataSrc);
var mRender = oCol.mRender ? _fnGetObjectDataFn(oCol.mRender) : null;
var attrTest = function (src) {
return typeof src === 'string' && src.indexOf('@') !== -1;
};
oCol._bAttrSrc = $.isPlainObject(mDataSrc) && (
attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter)
);
oCol.fnGetData = function (oData, sSpecific) {
var innerData = mData(oData, sSpecific);
if (oCol.mRender && (sSpecific && sSpecific !== '')) {
return mRender(innerData, sSpecific, oData);
}
return innerData;
};
oCol.fnSetData = _fnSetObjectDataFn(mDataSrc);
/* Feature sorting overrides column specific when off */
if (!oSettings.oFeatures.bSort) {
oCol.bSortable = false;
}
/* Check that the class assignment is correct for sorting */
var bAsc = $.inArray('asc', oCol.asSorting) !== -1;
var bDesc = $.inArray('desc', oCol.asSorting) !== -1;
if (!oCol.bSortable || (!bAsc && !bDesc)) {
oCol.sSortingClass = oClasses.sSortableNone;
oCol.sSortingClassJUI = "";
}
else if (bAsc && !bDesc) {
oCol.sSortingClass = oClasses.sSortableAsc;
oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed;
}
else if (!bAsc && bDesc) {
oCol.sSortingClass = oClasses.sSortableDesc;
oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed;
}
}
/**
* Adjust the table column widths for new data. Note: you would probably want to
* do a redraw after calling this function!
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnAdjustColumnSizing(settings) {
/* Not interested in doing column width calculation if auto-width is disabled */
if (settings.oFeatures.bAutoWidth !== false) {
var columns = settings.aoColumns;
_fnCalculateColumnWidths(settings);
for (var i = 0, iLen = columns.length; i < iLen; i++) {
columns[i].nTh.style.width = columns[i].sWidth;
}
}
var scroll = settings.oScroll;
if (scroll.sY !== '' || scroll.sX !== '') {
_fnScrollDraw(settings);
}
_fnCallbackFire(settings, null, 'column-sizing', [settings]);
}
/**
* Covert the index of a visible column to the index in the data array (take account
* of hidden columns)
* @param {object} oSettings dataTables settings object
* @param {int} iMatch Visible column index to lookup
* @returns {int} i the data index
* @memberof DataTable#oApi
*/
function _fnVisibleToColumnIndex(oSettings, iMatch) {
var aiVis = _fnGetColumns(oSettings, 'bVisible');
return typeof aiVis[iMatch] === 'number' ?
aiVis[iMatch] :
null;
}
/**
* Covert the index of an index in the data array and convert it to the visible
* column index (take account of hidden columns)
* @param {int} iMatch Column index to lookup
* @param {object} oSettings dataTables settings object
* @returns {int} i the data index
* @memberof DataTable#oApi
*/
function _fnColumnIndexToVisible(oSettings, iMatch) {
var aiVis = _fnGetColumns(oSettings, 'bVisible');
var iPos = $.inArray(iMatch, aiVis);
return iPos !== -1 ? iPos : null;
}
/**
* Get the number of visible columns
* @param {object} oSettings dataTables settings object
* @returns {int} i the number of visible columns
* @memberof DataTable#oApi
*/
function _fnVisbleColumns(oSettings) {
return _fnGetColumns(oSettings, 'bVisible').length;
}
/**
* Get an array of column indexes that match a given property
* @param {object} oSettings dataTables settings object
* @param {string} sParam Parameter in aoColumns to look for - typically
* bVisible or bSearchable
* @returns {array} Array of indexes with matched properties
* @memberof DataTable#oApi
*/
function _fnGetColumns(oSettings, sParam) {
var a = [];
$.map(oSettings.aoColumns, function (val, i) {
if (val[sParam]) {
a.push(i);
}
});
return a;
}
function _fnColumnTypes(settings) {
var columns = settings.aoColumns;
var data = settings.aoData;
var types = DataTable.ext.type.detect;
var i, ien, j, jen, k, ken;
var col, cell, detectedType, cache;
// For each column, spin over the
for (i = 0, ien = columns.length; i < ien; i++) {
col = columns[i];
cache = [];
if (!col.sType && col._sManualType) {
col.sType = col._sManualType;
}
else if (!col.sType) {
for (j = 0, jen = types.length; j < jen; j++) {
for (k = 0, ken = data.length; k < ken; k++) {
// Use a cache array so we only need to get the type data
// from the formatter once (when using multiple detectors)
if (cache[k] === undefined) {
cache[k] = _fnGetCellData(settings, k, i, 'type');
}
detectedType = types[j](cache[k]);
// Doesn't match, so break early, since this type can't
// apply to this column. Also, HTML is a special case since
// it is so similar to `string`. Just a single match is
// needed for a column to be html type
if (!detectedType || detectedType === 'html') {
break;
}
}
// Type is valid for all data points in the column - use this
// type
if (detectedType) {
col.sType = detectedType;
break;
}
}
// Fall back - if no type was detected, always use string
if (!col.sType) {
col.sType = 'string';
}
}
}
}
/**
* Take the column definitions and static columns arrays and calculate how
* they relate to column indexes. The callback function will then apply the
* definition found for a column to a suitable configuration object.
* @param {object} oSettings dataTables settings object
* @param {array} aoColDefs The aoColumnDefs array that is to be applied
* @param {array} aoCols The aoColumns array that defines columns individually
* @param {function} fn Callback function - takes two parameters, the calculated
* column index and the definition for that column.
* @memberof DataTable#oApi
*/
function _fnApplyColumnDefs(oSettings, aoColDefs, aoCols, fn) {
var i, iLen, j, jLen, k, kLen, def;
// Column definitions with aTargets
if (aoColDefs) {
/* Loop over the definitions array - loop in reverse so first instance has priority */
for (i = aoColDefs.length - 1; i >= 0; i--) {
def = aoColDefs[i];
/* Each definition can target multiple columns, as it is an array */
var aTargets = def.targets !== undefined ?
def.targets :
def.aTargets;
if (!$.isArray(aTargets)) {
aTargets = [aTargets];
}
for (j = 0, jLen = aTargets.length; j < jLen; j++) {
if (typeof aTargets[j] === 'number' && aTargets[j] >= 0) {
/* Add columns that we don't yet know about */
while (oSettings.aoColumns.length <= aTargets[j]) {
_fnAddColumn(oSettings);
}
/* Integer, basic index */
fn(aTargets[j], def);
}
else if (typeof aTargets[j] === 'number' && aTargets[j] < 0) {
/* Negative integer, right to left column counting */
fn(oSettings.aoColumns.length + aTargets[j], def);
}
else if (typeof aTargets[j] === 'string') {
/* Class name matching on TH element */
for (k = 0, kLen = oSettings.aoColumns.length; k < kLen; k++) {
if (aTargets[j] == "_all" ||
$(oSettings.aoColumns[k].nTh).hasClass(aTargets[j])) {
fn(k, def);
}
}
}
}
}
}
// Statically defined columns array
if (aoCols) {
for (i = 0, iLen = aoCols.length; i < iLen; i++) {
fn(i, aoCols[i]);
}
}
}
/**
* Add a data array to the table, creating DOM node etc. This is the parallel to
* _fnGatherData, but for adding rows from a Javascript source, rather than a
* DOM source.
* @param {object} oSettings dataTables settings object
* @param {array} aData data array to be added
* @param {node} [nTr] TR element to add to the table - optional. If not given,
* DataTables will create a row automatically
* @param {array} [anTds] Array of TD|TH elements for the row - must be given
* if nTr is.
* @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
* @memberof DataTable#oApi
*/
function _fnAddData(oSettings, aDataIn, nTr, anTds) {
/* Create the object for storing information about this new row */
var iRow = oSettings.aoData.length;
var oData = $.extend(true, {}, DataTable.models.oRow, {
src: nTr ? 'dom' : 'data'
});
oData._aData = aDataIn;
oSettings.aoData.push(oData);
/* Create the cells */
var nTd, sThisType;
var columns = oSettings.aoColumns;
for (var i = 0, iLen = columns.length; i < iLen; i++) {
// When working with a row, the data source object must be populated. In
// all other cases, the data source object is already populated, so we
// don't overwrite it, which might break bindings etc
if (nTr) {
_fnSetCellData(oSettings, iRow, i, _fnGetCellData(oSettings, iRow, i));
}
columns[i].sType = null;
}
/* Add to the display array */
oSettings.aiDisplayMaster.push(iRow);
/* Create the DOM information */
if (!oSettings.oFeatures.bDeferRender) {
_fnCreateTr(oSettings, iRow, nTr, anTds);
}
return iRow;
}
/**
* Add one or more TR elements to the table. Generally we'd expect to
* use this for reading data from a DOM sourced table, but it could be
* used for an TR element. Note that if a TR is given, it is used (i.e.
* it is not cloned).
* @param {object} settings dataTables settings object
* @param {array|node|jQuery} trs The TR element(s) to add to the table
* @returns {array} Array of indexes for the added rows
* @memberof DataTable#oApi
*/
function _fnAddTr(settings, trs) {
var row;
// Allow an individual node to be passed in
if (!(trs instanceof $)) {
trs = $(trs);
}
return trs.map(function (i, el) {
row = _fnGetRowElements(settings, el);
return _fnAddData(settings, row.data, el, row.cells);
});
}
/**
* Take a TR element and convert it to an index in aoData
* @param {object} oSettings dataTables settings object
* @param {node} n the TR element to find
* @returns {int} index if the node is found, null if not
* @memberof DataTable#oApi
*/
function _fnNodeToDataIndex(oSettings, n) {
return (n._DT_RowIndex !== undefined) ? n._DT_RowIndex : null;
}
/**
* Take a TD element and convert it into a column data index (not the visible index)
* @param {object} oSettings dataTables settings object
* @param {int} iRow The row number the TD/TH can be found in
* @param {node} n The TD/TH element to find
* @returns {int} index if the node is found, -1 if not
* @memberof DataTable#oApi
*/
function _fnNodeToColumnIndex(oSettings, iRow, n) {
return $.inArray(n, oSettings.aoData[iRow].anCells);
}
/**
* Get an array of data for a given row from the internal data cache
* @param {object} oSettings dataTables settings object
* @param {int} iRow aoData row id
* @param {string} sSpecific data get type ('type' 'filter' 'sort')
* @param {array} aiColumns Array of column indexes to get data from
* @returns {array} Data array
* @memberof DataTable#oApi
*/
function _fnGetRowData(oSettings, iRow, sSpecific, aiColumns) {
var out = [];
for (var i = 0, iLen = aiColumns.length; i < iLen; i++) {
out.push(_fnGetCellData(oSettings, iRow, aiColumns[i], sSpecific));
}
return out;
}
/**
* Get the data for a given cell from the internal cache, taking into account data mapping
* @param {object} oSettings dataTables settings object
* @param {int} iRow aoData row id
* @param {int} iCol Column index
* @param {string} sSpecific data get type ('display', 'type' 'filter' 'sort')
* @returns {*} Cell data
* @memberof DataTable#oApi
*/
function _fnGetCellData(oSettings, iRow, iCol, sSpecific) {
var oCol = oSettings.aoColumns[iCol];
var oData = oSettings.aoData[iRow]._aData;
var sData = oCol.fnGetData(oData, sSpecific);
if (sData === undefined) {
if (oSettings.iDrawError != oSettings.iDraw && oCol.sDefaultContent === null) {
_fnLog(oSettings, 0, "Requested unknown parameter " +
(typeof oCol.mData == 'function' ? '{function}' : "'" + oCol.mData + "'") +
" for row " + iRow, 4);
oSettings.iDrawError = oSettings.iDraw;
}
return oCol.sDefaultContent;
}
/* When the data source is null, we can use default column data */
if ((sData === oData || sData === null) && oCol.sDefaultContent !== null) {
sData = oCol.sDefaultContent;
}
else if (typeof sData === 'function') {
// If the data source is a function, then we run it and use the return
return sData();
}
if (sData === null && sSpecific == 'display') {
return '';
}
return sData;
}
/**
* Set the value for a specific cell, into the internal data cache
* @param {object} oSettings dataTables settings object
* @param {int} iRow aoData row id
* @param {int} iCol Column index
* @param {*} val Value to set
* @memberof DataTable#oApi
*/
function _fnSetCellData(oSettings, iRow, iCol, val) {
var oCol = oSettings.aoColumns[iCol];
var oData = oSettings.aoData[iRow]._aData;
oCol.fnSetData(oData, val);
}
// Private variable that is used to match action syntax in the data property object
var __reArray = /\[.*?\]$/;
var __reFn = /\(\)$/;
/**
* Split string on periods, taking into account escaped periods
* @param {string} str String to split
* @return {array} Split string
*/
function _fnSplitObjNotation(str) {
return $.map(str.match(/(\\.|[^\.])+/g), function (s) {
return s.replace('\\.', '.');
});
}
/**
* Return a function that can be used to get data from a source object, taking
* into account the ability to use nested objects as a source
* @param {string|int|function} mSource The data source for the object
* @returns {function} Data get function
* @memberof DataTable#oApi
*/
function _fnGetObjectDataFn(mSource) {
if ($.isPlainObject(mSource)) {
/* Build an object of get functions, and wrap them in a single call */
var o = {};
$.each(mSource, function (key, val) {
if (val) {
o[key] = _fnGetObjectDataFn(val);
}
});
return function (data, type, extra) {
return o[o[type] !== undefined ? type : '_'](data, type, extra);
};
}
else if (mSource === null) {
/* Give an empty string for rendering / sorting etc */
return function (data, type) {
return data;
};
}
else if (typeof mSource === 'function') {
return function (data, type, extra) {
return mSource(data, type, extra);
};
}
else if (typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1)) {
/* If there is a . in the source string then the data source is in a
* nested object so we loop over the data for each level to get the next
* level down. On each loop we test for undefined, and if found immediately
* return. This allows entire objects to be missing and sDefaultContent to
* be used if defined, rather than throwing an error
*/
var fetchData = function (data, type, src) {
var arrayNotation, funcNotation, out, innerSrc;
if (src !== "") {
var a = _fnSplitObjNotation(src);
for (var i = 0, iLen = a.length; i < iLen; i++) {
// Check if we are dealing with special notation
arrayNotation = a[i].match(__reArray);
funcNotation = a[i].match(__reFn);
if (arrayNotation) {
// Array notation
a[i] = a[i].replace(__reArray, '');
// Condition allows simply [] to be passed in
if (a[i] !== "") {
data = data[a[i]];
}
out = [];
// Get the remainder of the nested object to get
a.splice(0, i + 1);
innerSrc = a.join('.');
// Traverse each entry in the array getting the properties requested
for (var j = 0, jLen = data.length; j < jLen; j++) {
out.push(fetchData(data[j], type, innerSrc));
}
// If a string is given in between the array notation indicators, that
// is used to join the strings together, otherwise an array is returned
var join = arrayNotation[0].substring(1, arrayNotation[0].length - 1);
data = (join === "") ? out : out.join(join);
// The inner call to fetchData has already traversed through the remainder
// of the source requested, so we exit from the loop
break;
}
else if (funcNotation) {
// Function call
a[i] = a[i].replace(__reFn, '');
data = data[a[i]]();
continue;
}
if (data === null || data[a[i]] === undefined) {
return undefined;
}
data = data[a[i]];
}
}
return data;
};
return function (data, type) {
return fetchData(data, type, mSource);
};
}
else {
/* Array or flat object mapping */
return function (data, type) {
return data[mSource];
};
}
}
/**
* Return a function that can be used to set data from a source object, taking
* into account the ability to use nested objects as a source
* @param {string|int|function} mSource The data source for the object
* @returns {function} Data set function
* @memberof DataTable#oApi
*/
function _fnSetObjectDataFn(mSource) {
if ($.isPlainObject(mSource)) {
/* Unlike get, only the underscore (global) option is used for for
* setting data since we don't know the type here. This is why an object
* option is not documented for `mData` (which is read/write), but it is
* for `mRender` which is read only.
*/
return _fnSetObjectDataFn(mSource._);
}
else if (mSource === null) {
/* Nothing to do when the data source is null */
return function (data, val) {
};
}
else if (typeof mSource === 'function') {
return function (data, val) {
mSource(data, 'set', val);
};
}
else if (typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1)) {
/* Like the get, we need to get data from a nested object */
var setData = function (data, val, src) {
var a = _fnSplitObjNotation(src), b;
var aLast = a[a.length - 1];
var arrayNotation, funcNotation, o, innerSrc;
for (var i = 0, iLen = a.length - 1; i < iLen; i++) {
// Check if we are dealing with an array notation request
arrayNotation = a[i].match(__reArray);
funcNotation = a[i].match(__reFn);
if (arrayNotation) {
a[i] = a[i].replace(__reArray, '');
data[a[i]] = [];
// Get the remainder of the nested object to set so we can recurse
b = a.slice();
b.splice(0, i + 1);
innerSrc = b.join('.');
// Traverse each entry in the array setting the properties requested
for (var j = 0, jLen = val.length; j < jLen; j++) {
o = {};
setData(o, val[j], innerSrc);
data[a[i]].push(o);
}
// The inner call to setData has already traversed through the remainder
// of the source and has set the data, thus we can exit here
return;
}
else if (funcNotation) {
// Function call
a[i] = a[i].replace(__reFn, '');
data = data[a[i]](val);
}
// If the nested object doesn't currently exist - since we are
// trying to set the value - create it
if (data[a[i]] === null || data[a[i]] === undefined) {
data[a[i]] = {};
}
data = data[a[i]];
}
// Last item in the input - i.e, the actual set
if (aLast.match(__reFn)) {
// Function call
data = data[aLast.replace(__reFn, '')](val);
}
else {
// If array notation is used, we just want to strip it and use the property name
// and assign the value. If it isn't used, then we get the result we want anyway
data[aLast.replace(__reArray, '')] = val;
}
};
return function (data, val) {
return setData(data, val, mSource);
};
}
else {
/* Array or flat object mapping */
return function (data, val) {
data[mSource] = val;
};
}
}
/**
* Return an array with the full table data
* @param {object} oSettings dataTables settings object
* @returns array {array} aData Master data array
* @memberof DataTable#oApi
*/
function _fnGetDataMaster(settings) {
return _pluck(settings.aoData, '_aData');
}
/**
* Nuke the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnClearTable(settings) {
settings.aoData.length = 0;
settings.aiDisplayMaster.length = 0;
settings.aiDisplay.length = 0;
}
/**
* Take an array of integers (index array) and remove a target integer (value - not
* the key!)
* @param {array} a Index array to target
* @param {int} iTarget value to find
* @memberof DataTable#oApi
*/
function _fnDeleteIndex(a, iTarget, splice) {
var iTargetIndex = -1;
for (var i = 0, iLen = a.length; i < iLen; i++) {
if (a[i] == iTarget) {
iTargetIndex = i;
}
else if (a[i] > iTarget) {
a[i]--;
}
}
if (iTargetIndex != -1 && splice === undefined) {
a.splice(iTargetIndex, 1);
}
}
/**
* Mark cached data as invalid such that a re-read of the data will occur when
* the cached data is next requested. Also update from the data source object.
*
* @param {object} settings DataTables settings object
* @param {int} rowIdx Row index to invalidate
* @memberof DataTable#oApi
*
* @todo For the modularisation of v1.11 this will need to become a callback, so
* the sort and filter methods can subscribe to it. That will required
* initialisation options for sorting, which is why it is not already baked in
*/
function _fnInvalidateRow(settings, rowIdx, src, column) {
var row = settings.aoData[rowIdx];
var i, ien;
// Are we reading last data from DOM or the data object?
if (src === 'dom' || ((!src || src === 'auto') && row.src === 'dom')) {
// Read the data from the DOM
row._aData = _fnGetRowElements(settings, row.nTr).data;
}
else {
// Reading from data object, update the DOM
var cells = row.anCells;
for (i = 0, ien = cells.length; i < ien; i++) {
cells[i].innerHTML = _fnGetCellData(settings, rowIdx, i, 'display');
}
}
row._aSortData = null;
row._aFilterData = null;
// Invalidate the type for a specific column (if given) or all columns since
// the data might have changed
var cols = settings.aoColumns;
if (column !== undefined) {
cols[column].sType = null;
}
else {
for (i = 0, ien = cols.length; i < ien; i++) {
cols[i].sType = null;
}
}
// Update DataTables special `DT_*` attributes for the row
_fnRowAttributes(row);
}
/**
* Build a data source object from an HTML row, reading the contents of the
* cells that are in the row.
*
* @param {object} settings DataTables settings object
* @param {node} TR element from which to read data
* @returns {object} Object with two parameters: `data` the data read, in
* document order, and `cells` and array of nodes (they can be useful to the
* caller, so rather than needing a second traversal to get them, just return
* them from here).
* @memberof DataTable#oApi
*/
function _fnGetRowElements(settings, row) {
var
d = [],
tds = [],
td = row.firstChild,
name, col, o, i = 0, contents,
columns = settings.aoColumns;
var attr = function (str, data, td) {
if (typeof str === 'string') {
var idx = str.indexOf('@');
if (idx !== -1) {
var src = str.substring(idx + 1);
o['@' + src] = td.getAttribute(src);
}
}
};
while (td) {
name = td.nodeName.toUpperCase();
if (name == "TD" || name == "TH") {
col = columns[i];
contents = $.trim(td.innerHTML);
if (col && col._bAttrSrc) {
o = {
display: contents
};
attr(col.mData.sort, o, td);
attr(col.mData.type, o, td);
attr(col.mData.filter, o, td);
d.push(o);
}
else {
d.push(contents);
}
tds.push(td);
i++;
}
td = td.nextSibling;
}
return {
data: d,
cells: tds
};
}
/**
* Create a new TR element (and it's TD children) for a row
* @param {object} oSettings dataTables settings object
* @param {int} iRow Row to consider
* @param {node} [nTrIn] TR element to add to the table - optional. If not given,
* DataTables will create a row automatically
* @param {array} [anTds] Array of TD|TH elements for the row - must be given
* if nTr is.
* @memberof DataTable#oApi
*/
function _fnCreateTr(oSettings, iRow, nTrIn, anTds) {
var
row = oSettings.aoData[iRow],
rowData = row._aData,
cells = [],
nTr, nTd, oCol,
i, iLen;
if (row.nTr === null) {
nTr = nTrIn || document.createElement('tr');
row.nTr = nTr;
row.anCells = cells;
/* Use a private property on the node to allow reserve mapping from the node
* to the aoData array for fast look up
*/
nTr._DT_RowIndex = iRow;
/* Special parameters can be given by the data source to be used on the row */
_fnRowAttributes(row);
/* Process each column */
for (i = 0, iLen = oSettings.aoColumns.length; i < iLen; i++) {
oCol = oSettings.aoColumns[i];
nTd = nTrIn ? anTds[i] : document.createElement(oCol.sCellType);
cells.push(nTd);
// Need to create the HTML if new, or if a rendering function is defined
if (!nTrIn || oCol.mRender || oCol.mData !== i) {
nTd.innerHTML = _fnGetCellData(oSettings, iRow, i, 'display');
}
/* Add user defined class */
if (oCol.sClass !== null) {
nTd.className += ' ' + oCol.sClass;
}
// Visibility - add or remove as required
if (oCol.bVisible && !nTrIn) {
nTr.appendChild(nTd);
}
else if (!oCol.bVisible && nTrIn) {
nTd.parentNode.removeChild(nTd);
}
if (oCol.fnCreatedCell) {
oCol.fnCreatedCell.call(oSettings.oInstance,
nTd, _fnGetCellData(oSettings, iRow, i, 'display'), rowData, iRow, i
);
}
}
_fnCallbackFire(oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow]);
}
}
/**
* Add attributes to a row based on the special `DT_*` parameters in a data
* source object.
* @param {object} DataTables row object for the row to be modified
* @memberof DataTable#oApi
*/
function _fnRowAttributes(row) {
var tr = row.nTr;
var data = row._aData;
if (tr) {
if (data.DT_RowId) {
tr.id = data.DT_RowId;
}
if (data.DT_RowClass) {
// Remove any classes added by DT_RowClass before
var a = data.DT_RowClass.split(' ');
row.__rowc = row.__rowc ?
_unique(row.__rowc.concat(a)) :
a;
$(tr)
.removeClass(row.__rowc.join(' '))
.addClass(data.DT_RowClass);
}
if (data.DT_RowData) {
$(tr).data(data.DT_RowData);
}
}
}
/**
* Create the HTML header for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnBuildHead(oSettings) {
var i, ien, cell, row, column;
var thead = oSettings.nTHead;
var tfoot = oSettings.nTFoot;
var createHeader = $('th, td', thead).length === 0;
var classes = oSettings.oClasses;
var columns = oSettings.aoColumns;
if (createHeader) {
row = $('<tr/>').appendTo(thead);
}
for (i = 0, ien = columns.length; i < ien; i++) {
column = columns[i];
cell = $(column.nTh).addClass(column.sClass);
if (createHeader) {
cell.appendTo(row);
}
// 1.11 move into sorting
if (oSettings.oFeatures.bSort) {
cell.addClass(column.sSortingClass);
if (column.bSortable !== false) {
cell
.attr('tabindex', oSettings.iTabIndex)
.attr('aria-controls', oSettings.sTableId);
_fnSortAttachListener(oSettings, column.nTh, i);
}
}
if (column.sTitle != cell.html()) {
cell.html(column.sTitle);
}
_fnRenderer(oSettings, 'header')(
oSettings, cell, column, i, classes
);
}
if (createHeader) {
_fnDetectHeader(oSettings.aoHeader, thead);
}
/* ARIA role for the rows */
$(thead).find('>tr').attr('role', 'row');
/* Deal with the footer - add classes if required */
$(thead).find('>tr>th, >tr>td').addClass(classes.sHeaderTH);
$(tfoot).find('>tr>th, >tr>td').addClass(classes.sFooterTH);
// Cache the footer cells. Note that we only take the cells from the first
// row in the footer. If there is more than one row the user wants to
// interact with, they need to use the table().foot() method. Note also this
// allows cells to be used for multiple columns using colspan
if (tfoot !== null) {
var cells = oSettings.aoFooter[0];
for (i = 0, ien = cells.length; i < ien; i++) {
column = columns[i];
column.nTf = cells[i].cell;
if (column.sClass) {
$(column.nTf).addClass(column.sClass);
}
}
}
}
/**
* Draw the header (or footer) element based on the column visibility states. The
* methodology here is to use the layout array from _fnDetectHeader, modified for
* the instantaneous column visibility, to construct the new layout. The grid is
* traversed over cell at a time in a rows x columns grid fashion, although each
* cell insert can cover multiple elements in the grid - which is tracks using the
* aApplied array. Cell inserts in the grid will only occur where there isn't
* already a cell in that position.
* @param {object} oSettings dataTables settings object
* @param array {objects} aoSource Layout array from _fnDetectHeader
* @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
* @memberof DataTable#oApi
*/
function _fnDrawHead(oSettings, aoSource, bIncludeHidden) {
var i, iLen, j, jLen, k, kLen, n, nLocalTr;
var aoLocal = [];
var aApplied = [];
var iColumns = oSettings.aoColumns.length;
var iRowspan, iColspan;
if (!aoSource) {
return;
}
if (bIncludeHidden === undefined) {
bIncludeHidden = false;
}
/* Make a copy of the master layout array, but without the visible columns in it */
for (i = 0, iLen = aoSource.length; i < iLen; i++) {
aoLocal[i] = aoSource[i].slice();
aoLocal[i].nTr = aoSource[i].nTr;
/* Remove any columns which are currently hidden */
for (j = iColumns - 1; j >= 0; j--) {
if (!oSettings.aoColumns[j].bVisible && !bIncludeHidden) {
aoLocal[i].splice(j, 1);
}
}
/* Prep the applied array - it needs an element for each row */
aApplied.push([]);
}
for (i = 0, iLen = aoLocal.length; i < iLen; i++) {
nLocalTr = aoLocal[i].nTr;
/* All cells are going to be replaced, so empty out the row */
if (nLocalTr) {
while ((n = nLocalTr.firstChild)) {
nLocalTr.removeChild(n);
}
}
for (j = 0, jLen = aoLocal[i].length; j < jLen; j++) {
iRowspan = 1;
iColspan = 1;
/* Check to see if there is already a cell (row/colspan) covering our target
* insert point. If there is, then there is nothing to do.
*/
if (aApplied[i][j] === undefined) {
nLocalTr.appendChild(aoLocal[i][j].cell);
aApplied[i][j] = 1;
/* Expand the cell to cover as many rows as needed */
while (aoLocal[i + iRowspan] !== undefined &&
aoLocal[i][j].cell == aoLocal[i + iRowspan][j].cell) {
aApplied[i + iRowspan][j] = 1;
iRowspan++;
}
/* Expand the cell to cover as many columns as needed */
while (aoLocal[i][j + iColspan] !== undefined &&
aoLocal[i][j].cell == aoLocal[i][j + iColspan].cell) {
/* Must update the applied array over the rows for the columns */
for (k = 0; k < iRowspan; k++) {
aApplied[i + k][j + iColspan] = 1;
}
iColspan++;
}
/* Do the actual expansion in the DOM */
aoLocal[i][j].cell.rowSpan = iRowspan;
aoLocal[i][j].cell.colSpan = iColspan;
}
}
}
}
/**
* Insert the required TR nodes into the table for display
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnDraw(oSettings) {
/* Provide a pre-callback function which can be used to cancel the draw is false is returned */
var aPreDraw = _fnCallbackFire(oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings]);
if ($.inArray(false, aPreDraw) !== -1) {
_fnProcessingDisplay(oSettings, false);
return;
}
var i, iLen, n;
var anRows = [];
var iRowCount = 0;
var asStripeClasses = oSettings.asStripeClasses;
var iStripes = asStripeClasses.length;
var iOpenRows = oSettings.aoOpenRows.length;
var oLang = oSettings.oLanguage;
var iInitDisplayStart = oSettings.iInitDisplayStart;
var bServerSide = _fnDataSource(oSettings) == 'ssp';
var aiDisplay = oSettings.aiDisplay;
oSettings.bDrawing = true;
/* Check and see if we have an initial draw position from state saving */
if (iInitDisplayStart !== undefined && iInitDisplayStart !== -1) {
oSettings._iDisplayStart = bServerSide ?
iInitDisplayStart :
iInitDisplayStart >= oSettings.fnRecordsDisplay() ?
0 :
iInitDisplayStart;
oSettings.iInitDisplayStart = -1;
}
var iDisplayStart = oSettings._iDisplayStart;
var iDisplayEnd = oSettings.fnDisplayEnd();
/* Server-side processing draw intercept */
if (oSettings.bDeferLoading) {
oSettings.bDeferLoading = false;
oSettings.iDraw++;
_fnProcessingDisplay(oSettings, false);
}
else if (!bServerSide) {
oSettings.iDraw++;
}
else if (!oSettings.bDestroying && !_fnAjaxUpdate(oSettings)) {
return;
}
if (aiDisplay.length !== 0) {
var iStart = bServerSide ? 0 : iDisplayStart;
var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd;
for (var j = iStart; j < iEnd; j++) {
var iDataIndex = aiDisplay[j];
var aoData = oSettings.aoData[iDataIndex];
if (aoData.nTr === null) {
_fnCreateTr(oSettings, iDataIndex);
}
var nRow = aoData.nTr;
/* Remove the old striping classes and then add the new one */
if (iStripes !== 0) {
var sStripe = asStripeClasses[iRowCount % iStripes];
if (aoData._sRowStripe != sStripe) {
$(nRow).removeClass(aoData._sRowStripe).addClass(sStripe);
aoData._sRowStripe = sStripe;
}
}
/* Row callback functions - might want to manipulate the row */
_fnCallbackFire(oSettings, 'aoRowCallback', null,
[nRow, aoData._aData, iRowCount, j]);
anRows.push(nRow);
iRowCount++;
}
}
else {
/* Table is empty - create a row with an empty message in it */
var sZero = oLang.sZeroRecords;
if (oSettings.iDraw == 1 && _fnDataSource(oSettings) == 'ajax') {
sZero = oLang.sLoadingRecords;
}
else if (oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0) {
sZero = oLang.sEmptyTable;
}
anRows[0] = $('<tr/>', {'class': iStripes ? asStripeClasses[0] : ''})
.append($('<td />', {
'valign': 'top',
'colSpan': _fnVisbleColumns(oSettings),
'class': oSettings.oClasses.sRowEmpty
}).html(sZero))[0];
}
/* Header and footer callbacks */
_fnCallbackFire(oSettings, 'aoHeaderCallback', 'header', [$(oSettings.nTHead).children('tr')[0],
_fnGetDataMaster(oSettings), iDisplayStart, iDisplayEnd, aiDisplay]);
_fnCallbackFire(oSettings, 'aoFooterCallback', 'footer', [$(oSettings.nTFoot).children('tr')[0],
_fnGetDataMaster(oSettings), iDisplayStart, iDisplayEnd, aiDisplay]);
var body = $(oSettings.nTBody);
body.children().detach();
body.append($(anRows));
/* Call all required callback functions for the end of a draw */
_fnCallbackFire(oSettings, 'aoDrawCallback', 'draw', [oSettings]);
/* Draw is complete, sorting and filtering must be as well */
oSettings.bSorted = false;
oSettings.bFiltered = false;
oSettings.bDrawing = false;
}
/**
* Redraw the table - taking account of the various features which are enabled
* @param {object} oSettings dataTables settings object
* @param {boolean} [holdPosition] Keep the current paging position. By default
* the paging is reset to the first page
* @memberof DataTable#oApi
*/
function _fnReDraw(settings, holdPosition) {
var
features = settings.oFeatures,
sort = features.bSort,
filter = features.bFilter;
if (sort) {
_fnSort(settings);
}
if (filter) {
_fnFilterComplete(settings, settings.oPreviousSearch);
}
else {
// No filtering, so we want to just use the display master
settings.aiDisplay = settings.aiDisplayMaster.slice();
}
if (holdPosition !== true) {
settings._iDisplayStart = 0;
}
_fnDraw(settings);
}
/**
* Add the options to the page HTML for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnAddOptionsHtml(oSettings) {
/*
* Create a temporary, empty, div which we can later on replace with what we have generated
* we do it this way to rendering the 'options' html offline - speed :-)
*/
var nHolding = $('<div></div>')[0];
oSettings.nTable.parentNode.insertBefore(nHolding, oSettings.nTable);
/*
* All DataTables are wrapped in a div
*/
oSettings.nTableWrapper = $('<div id="' + oSettings.sTableId + '_wrapper" class="' + oSettings.oClasses.sWrapper + '" role="grid"></div>')[0];
oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;
/* Track where we want to insert the option */
var nInsertNode = oSettings.nTableWrapper;
/* Loop over the user set positioning and place the elements as needed */
var aDom = oSettings.sDom.split('');
var nTmp, iPushFeature, cOption, nNewNode, cNext, sAttr, j;
for (var i = 0; i < aDom.length; i++) {
iPushFeature = 0;
cOption = aDom[i];
if (cOption == '<') {
/* New container div */
nNewNode = $('<div></div>')[0];
/* Check to see if we should append an id and/or a class name to the container */
cNext = aDom[i + 1];
if (cNext == "'" || cNext == '"') {
sAttr = "";
j = 2;
while (aDom[i + j] != cNext) {
sAttr += aDom[i + j];
j++;
}
/* Replace jQuery UI constants @todo depreciated */
if (sAttr == "H") {
sAttr = oSettings.oClasses.sJUIHeader;
}
else if (sAttr == "F") {
sAttr = oSettings.oClasses.sJUIFooter;
}
/* The attribute can be in the format of "#id.class", "#id" or "class" This logic
* breaks the string into parts and applies them as needed
*/
if (sAttr.indexOf('.') != -1) {
var aSplit = sAttr.split('.');
nNewNode.id = aSplit[0].substr(1, aSplit[0].length - 1);
nNewNode.className = aSplit[1];
}
else if (sAttr.charAt(0) == "#") {
nNewNode.id = sAttr.substr(1, sAttr.length - 1);
}
else {
nNewNode.className = sAttr;
}
i += j;
/* Move along the position array */
}
nInsertNode.appendChild(nNewNode);
nInsertNode = nNewNode;
}
else if (cOption == '>') {
/* End container div */
nInsertNode = nInsertNode.parentNode;
}
// @todo Move options into their own plugins?
else if (cOption == 'l' && oSettings.oFeatures.bPaginate && oSettings.oFeatures.bLengthChange) {
/* Length */
nTmp = _fnFeatureHtmlLength(oSettings);
iPushFeature = 1;
}
else if (cOption == 'f' && oSettings.oFeatures.bFilter) {
/* Filter */
nTmp = _fnFeatureHtmlFilter(oSettings);
iPushFeature = 1;
}
else if (cOption == 'r' && oSettings.oFeatures.bProcessing) {
/* pRocessing */
nTmp = _fnFeatureHtmlProcessing(oSettings);
iPushFeature = 1;
}
else if (cOption == 't') {
/* Table */
nTmp = _fnFeatureHtmlTable(oSettings);
iPushFeature = 1;
}
else if (cOption == 'i' && oSettings.oFeatures.bInfo) {
/* Info */
nTmp = _fnFeatureHtmlInfo(oSettings);
iPushFeature = 1;
}
else if (cOption == 'p' && oSettings.oFeatures.bPaginate) {
/* Pagination */
nTmp = _fnFeatureHtmlPaginate(oSettings);
iPushFeature = 1;
}
else if (DataTable.ext.feature.length !== 0) {
/* Plug-in features */
var aoFeatures = DataTable.ext.feature;
for (var k = 0, kLen = aoFeatures.length; k < kLen; k++) {
if (cOption == aoFeatures[k].cFeature) {
nTmp = aoFeatures[k].fnInit(oSettings);
if (nTmp) {
iPushFeature = 1;
}
break;
}
}
}
/* Add to the 2D features array */
if (iPushFeature == 1 && nTmp !== null) {
if (typeof oSettings.aanFeatures[cOption] !== 'object') {
oSettings.aanFeatures[cOption] = [];
}
oSettings.aanFeatures[cOption].push(nTmp);
nInsertNode.appendChild(nTmp);
}
}
/* Built our DOM structure - replace the holding div with what we want */
nHolding.parentNode.replaceChild(oSettings.nTableWrapper, nHolding);
}
/**
* Use the DOM source to create up an array of header cells. The idea here is to
* create a layout grid (array) of rows x columns, which contains a reference
* to the cell that that point in the grid (regardless of col/rowspan), such that
* any column / row could be removed and the new grid constructed
* @param array {object} aLayout Array to store the calculated layout in
* @param {node} nThead The header/footer element for the table
* @memberof DataTable#oApi
*/
function _fnDetectHeader(aLayout, nThead) {
var nTrs = $(nThead).children('tr');
var nTr, nCell;
var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
var bUnique;
var fnShiftCol = function (a, i, j) {
var k = a[i];
while (k[j]) {
j++;
}
return j;
};
aLayout.splice(0, aLayout.length);
/* We know how many rows there are in the layout - so prep it */
for (i = 0, iLen = nTrs.length; i < iLen; i++) {
aLayout.push([]);
}
/* Calculate a layout array */
for (i = 0, iLen = nTrs.length; i < iLen; i++) {
nTr = nTrs[i];
iColumn = 0;
/* For every cell in the row... */
nCell = nTr.firstChild;
while (nCell) {
if (nCell.nodeName.toUpperCase() == "TD" ||
nCell.nodeName.toUpperCase() == "TH") {
/* Get the col and rowspan attributes from the DOM and sanitise them */
iColspan = nCell.getAttribute('colspan') * 1;
iRowspan = nCell.getAttribute('rowspan') * 1;
iColspan = (!iColspan || iColspan === 0 || iColspan === 1) ? 1 : iColspan;
iRowspan = (!iRowspan || iRowspan === 0 || iRowspan === 1) ? 1 : iRowspan;
/* There might be colspan cells already in this row, so shift our target
* accordingly
*/
iColShifted = fnShiftCol(aLayout, i, iColumn);
/* Cache calculation for unique columns */
bUnique = iColspan === 1 ? true : false;
/* If there is col / rowspan, copy the information into the layout grid */
for (l = 0; l < iColspan; l++) {
for (k = 0; k < iRowspan; k++) {
aLayout[i + k][iColShifted + l] = {
"cell": nCell,
"unique": bUnique
};
aLayout[i + k].nTr = nTr;
}
}
}
nCell = nCell.nextSibling;
}
}
}
/**
* Get an array of unique th elements, one for each column
* @param {object} oSettings dataTables settings object
* @param {node} nHeader automatically detect the layout from this node - optional
* @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
* @returns array {node} aReturn list of unique th's
* @memberof DataTable#oApi
*/
function _fnGetUniqueThs(oSettings, nHeader, aLayout) {
var aReturn = [];
if (!aLayout) {
aLayout = oSettings.aoHeader;
if (nHeader) {
aLayout = [];
_fnDetectHeader(aLayout, nHeader);
}
}
for (var i = 0, iLen = aLayout.length; i < iLen; i++) {
for (var j = 0, jLen = aLayout[i].length; j < jLen; j++) {
if (aLayout[i][j].unique &&
(!aReturn[j] || !oSettings.bSortCellsTop)) {
aReturn[j] = aLayout[i][j].cell;
}
}
}
return aReturn;
}
/**
* Create an Ajax call based on the table's settings, taking into account that
* parameters can have multiple forms, and backwards compatibility.
*
* @param {object} oSettings dataTables settings object
* @param {array} data Data to send to the server, required by
* DataTables - may be augmented by developer callbacks
* @param {function} fn Callback function to run when data is obtained
*/
function _fnBuildAjax(oSettings, data, fn) {
// Compatibility with 1.9-, allow fnServerData and event to manipulate
_fnCallbackFire(oSettings, 'aoServerParams', 'serverParams', [data]);
// Convert to object based for 1.10+ if using the old scheme
if (data && data.__legacy) {
var tmp = {};
var rbracket = /(.*?)\[\]$/;
$.each(data, function (key, val) {
var match = val.name.match(rbracket);
if (match) {
// Support for arrays
var name = match[0];
if (!tmp[name]) {
tmp[name] = [];
}
tmp[name].push(val.value);
}
else {
tmp[val.name] = val.value;
}
});
data = tmp;
}
var ajaxData;
var ajax = oSettings.ajax;
var instance = oSettings.oInstance;
if ($.isPlainObject(ajax) && ajax.data) {
ajaxData = ajax.data;
var newData = $.isFunction(ajaxData) ?
ajaxData(data) : // fn can manipulate data or return an object
ajaxData; // object or array to merge
// If the function returned an object, use that alone
data = $.isFunction(ajaxData) && newData ?
newData :
$.extend(true, data, newData);
// Remove the data property as we've resolved it already and don't want
// jQuery to do it again (it is restored at the end of the function)
delete ajax.data;
}
var baseAjax = {
"data": data,
"success": function (json) {
var error = json.error || json.sError;
if (error) {
oSettings.oApi._fnLog(oSettings, 0, error);
}
oSettings.json = json;
_fnCallbackFire(oSettings, null, 'xhr', [oSettings, json]);
fn(json);
},
"dataType": "json",
"cache": false,
"type": oSettings.sServerMethod,
"error": function (xhr, error, thrown) {
var log = oSettings.oApi._fnLog;
if (error == "parsererror") {
log(oSettings, 0, 'Invalid JSON response', 1);
}
else {
log(oSettings, 0, 'Ajax error', 7);
}
}
};
if (oSettings.fnServerData) {
// DataTables 1.9- compatibility
oSettings.fnServerData.call(instance,
oSettings.sAjaxSource, data, fn, oSettings
);
}
else if (oSettings.sAjaxSource || typeof ajax === 'string') {
// DataTables 1.9- compatibility
oSettings.jqXHR = $.ajax($.extend(baseAjax, {
url: ajax || oSettings.sAjaxSource
}));
}
else if ($.isFunction(ajax)) {
// Is a function - let the caller define what needs to be done
oSettings.jqXHR = ajax.call(instance, data, fn, oSettings);
}
else {
// Object to extend the base settings
oSettings.jqXHR = $.ajax($.extend(baseAjax, ajax));
// Restore for next time around
ajax.data = ajaxData;
}
}
/**
* Update the table using an Ajax call
* @param {object} oSettings dataTables settings object
* @returns {boolean} Block the table drawing or not
* @memberof DataTable#oApi
*/
function _fnAjaxUpdate(oSettings) {
if (oSettings.bAjaxDataGet) {
oSettings.iDraw++;
_fnProcessingDisplay(oSettings, true);
var iColumns = oSettings.aoColumns.length;
var aoData = _fnAjaxParameters(oSettings);
_fnBuildAjax(oSettings, aoData, function (json) {
_fnAjaxUpdateDraw(oSettings, json);
}, oSettings);
return false;
}
return true;
}
/**
* Build up the parameters in an object needed for a server-side processing
* request. Note that this is basically done twice, is different ways - a modern
* method which is used by default in DataTables 1.10 which uses objects and
* arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if
* the sAjaxSource option is used in the initialisation, or the legacyAjax
* option is set.
* @param {object} oSettings dataTables settings object
* @returns {bool} block the table drawing or not
* @memberof DataTable#oApi
*/
function _fnAjaxParameters(settings) {
var
columns = settings.aoColumns,
columnCount = columns.length,
features = settings.oFeatures,
preSearch = settings.oPreviousSearch,
preColSearch = settings.aoPreSearchCols,
i, data = [], dataProp, column, columnSearch,
sort = _fnSortFlatten(settings),
displayStart = settings._iDisplayStart,
displayLength = features.bPaginate !== false ?
settings._iDisplayLength :
-1;
var param = function (name, value) {
data.push({'name': name, 'value': value});
};
// DataTables 1.9- compatible method
param('sEcho', settings.iDraw);
param('iColumns', columnCount);
param('sColumns', _pluck(columns, 'sName').join(','));
param('iDisplayStart', displayStart);
param('iDisplayLength', displayLength);
// DataTables 1.10+ method
var d = {
draw: settings.iDraw,
columns: [],
order: [],
start: displayStart,
length: displayLength,
search: {
value: preSearch.sSearch,
regex: preSearch.bRegex
}
};
for (i = 0; i < columnCount; i++) {
column = columns[i];
columnSearch = preColSearch[i];
dataProp = typeof column.mData == "function" ? 'function' : column.mData;
d.columns.push({
data: dataProp,
name: column.sName,
searchable: column.bSearchable,
orderable: column.bSortable,
search: {
value: columnSearch.sSearch,
regex: columnSearch.bRegex
}
});
param("mDataProp_" + i, dataProp);
if (features.bFilter) {
param('sSearch_' + i, columnSearch.sSearch);
param('bRegex_' + i, columnSearch.bRegex);
param('bSearchable_' + i, column.bSearchable);
}
if (features.bSort) {
param('bSortable_' + i, column.bSortable);
}
}
$.each(sort, function (i, val) {
d.order.push({column: val.col, dir: val.dir});
param('iSortCol_' + i, val.col);
param('sSortDir_' + i, val.dir);
});
if (features.bFilter) {
param('sSearch', preSearch.sSearch);
param('bRegex', preSearch.bRegex);
}
if (features.bSort) {
param('iSortingCols', sort.length);
}
data.__legacy = true;
return settings.sAjaxSource || DataTable.ext.legacy.ajax ?
data : d;
}
/**
* Data the data from the server (nuking the old) and redraw the table
* @param {object} oSettings dataTables settings object
* @param {object} json json data return from the server.
* @param {string} json.sEcho Tracking flag for DataTables to match requests
* @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
* @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
* @param {array} json.aaData The data to display on this page
* @param {string} [json.sColumns] Column ordering (sName, comma separated)
* @memberof DataTable#oApi
*/
function _fnAjaxUpdateDraw(settings, json) {
// v1.10 uses camelCase variables, while 1.9 uses Hungarian notation.
// Support both
var compat = function (old, modern) {
return json[old] !== undefined ? json[old] : json[modern];
};
var draw = compat('sEcho', 'draw');
var recordsTotal = compat('iTotalRecords', 'recordsTotal');
var rocordsFiltered = compat('iTotalDisplayRecords', 'recordsFiltered');
if (draw) {
// Protect against out of sequence returns
if (draw * 1 < settings.iDraw) {
return;
}
settings.iDraw = draw * 1;
}
_fnClearTable(settings);
settings._iRecordsTotal = parseInt(recordsTotal, 10);
settings._iRecordsDisplay = parseInt(rocordsFiltered, 10);
var data = _fnAjaxDataSrc(settings, json);
for (var i = 0, ien = data.length; i < ien; i++) {
_fnAddData(settings, data[i]);
}
settings.aiDisplay = settings.aiDisplayMaster.slice();
settings.bAjaxDataGet = false;
_fnDraw(settings);
if (!settings._bInitComplete) {
_fnInitComplete(settings, json);
}
settings.bAjaxDataGet = true;
_fnProcessingDisplay(settings, false);
}
/**
* Get the data from the JSON data source to use for drawing a table. Using
* `_fnGetObjectDataFn` allows the data to be sourced from a property of the
* source object, or from a processing function.
* @param {object} oSettings dataTables settings object
* @param {object} json Data source object / array from the server
* @return {array} Array of data to use
*/
function _fnAjaxDataSrc(oSettings, json) {
var dataSrc = $.isPlainObject(oSettings.ajax) && oSettings.ajax.dataSrc !== undefined ?
oSettings.ajax.dataSrc :
oSettings.sAjaxDataProp; // Compatibility with 1.9-.
// Compatibility with 1.9-. In order to read from aaData, check if the
// default has been changed, if not, check for aaData
if (dataSrc === 'data') {
return json.aaData || json[dataSrc];
}
return dataSrc !== "" ?
_fnGetObjectDataFn(dataSrc)(json) :
json;
}
/**
* Generate the node required for filtering text
* @returns {node} Filter control element
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlFilter(settings) {
var classes = settings.oClasses;
var tableId = settings.sTableId;
var previousSearch = settings.oPreviousSearch;
var features = settings.aanFeatures;
var input = '<input type="search" class="' + classes.sFilterInput + '"/>';
var str = settings.oLanguage.sSearch;
str = str.match(/_INPUT_/) ?
str.replace('_INPUT_', input) :
str + input;
var filter = $('<div/>', {
'id': !features.f ? tableId + '_filter' : null,
'class': classes.sFilter
})
.append($('<label/>').append(str));
var jqFilter = $('input[type="search"]', filter)
.val(previousSearch.sSearch.replace('"', '"'))
.bind('keyup.DT search.DT input.DT paste.DT cut.DT', function (e) {
/* Update all other filter input elements for the new display */
var n = features.f;
var val = !this.value ? "" : this.value; // mental IE8 fix :-(
/* Now do the filter */
if (val != previousSearch.sSearch) {
_fnFilterComplete(settings, {
"sSearch": val,
"bRegex": previousSearch.bRegex,
"bSmart": previousSearch.bSmart,
"bCaseInsensitive": previousSearch.bCaseInsensitive
});
// Need to redraw, without resorting
settings._iDisplayStart = 0;
_fnDraw(settings);
}
})
.bind('keypress.DT', function (e) {
/* Prevent form submission */
if (e.keyCode == 13) {
return false;
}
})
.attr('aria-controls', tableId);
// Update the input elements whenever the table is filtered
$(settings.nTable).on('filter.DT', function () {
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame...
try {
if (jqFilter[0] !== document.activeElement) {
jqFilter.val(previousSearch.sSearch);
}
}
catch (e) {
}
});
return filter[0];
}
/**
* Filter the table using both the global filter and column based filtering
* @param {object} oSettings dataTables settings object
* @param {object} oSearch search information
* @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
* @memberof DataTable#oApi
*/
function _fnFilterComplete(oSettings, oInput, iForce) {
var oPrevSearch = oSettings.oPreviousSearch;
var aoPrevSearch = oSettings.aoPreSearchCols;
var fnSaveFilter = function (oFilter) {
/* Save the filtering values */
oPrevSearch.sSearch = oFilter.sSearch;
oPrevSearch.bRegex = oFilter.bRegex;
oPrevSearch.bSmart = oFilter.bSmart;
oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
};
// Resolve any column types that are unknown due to addition or invalidation
// @todo As per sort - can this be moved into an event handler?
_fnColumnTypes(oSettings);
/* In server-side processing all filtering is done by the server, so no point hanging around here */
if (_fnDataSource(oSettings) != 'ssp') {
/* Global filter */
_fnFilter(oSettings, oInput.sSearch, iForce, oInput.bRegex, oInput.bSmart, oInput.bCaseInsensitive);
fnSaveFilter(oInput);
/* Now do the individual column filter */
for (var i = 0; i < aoPrevSearch.length; i++) {
_fnFilterColumn(oSettings, aoPrevSearch[i].sSearch, i, aoPrevSearch[i].bRegex,
aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive);
}
/* Custom filtering */
_fnFilterCustom(oSettings);
}
else {
fnSaveFilter(oInput);
}
/* Tell the draw function we have been filtering */
oSettings.bFiltered = true;
_fnCallbackFire(oSettings, null, 'search', [oSettings]);
}
/**
* Apply custom filtering functions
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnFilterCustom(oSettings) {
var afnFilters = DataTable.ext.search;
var aiFilterColumns = _fnGetColumns(oSettings, 'bSearchable');
for (var i = 0, iLen = afnFilters.length; i < iLen; i++) {
var iCorrector = 0;
for (var j = 0, jLen = oSettings.aiDisplay.length; j < jLen; j++) {
var iDisIndex = oSettings.aiDisplay[j - iCorrector];
var bTest = afnFilters[i](
oSettings,
_fnGetRowData(oSettings, iDisIndex, 'filter', aiFilterColumns),
iDisIndex
);
/* Check if we should use this row based on the filtering function */
if (!bTest) {
oSettings.aiDisplay.splice(j - iCorrector, 1);
iCorrector++;
}
}
}
}
/**
* Filter the table on a per-column basis
* @param {object} oSettings dataTables settings object
* @param {string} sInput string to filter on
* @param {int} iColumn column to filter
* @param {bool} bRegex treat search string as a regular expression or not
* @param {bool} bSmart use smart filtering or not
* @param {bool} bCaseInsensitive Do case insenstive matching or not
* @memberof DataTable#oApi
*/
function _fnFilterColumn(settings, searchStr, colIdx, regex, smart, caseInsensitive) {
if (searchStr === '') {
return;
}
var data;
var display = settings.aiDisplay;
var rpSearch = _fnFilterCreateSearch(searchStr, regex, smart, caseInsensitive);
for (var i = display.length - 1; i >= 0; i--) {
data = settings.aoData[display[i]]._aFilterData[colIdx];
if (!rpSearch.test(data)) {
display.splice(i, 1);
}
}
}
/**
* Filter the data table based on user input and draw the table
* @param {object} settings dataTables settings object
* @param {string} input string to filter on
* @param {int} force optional - force a research of the master array (1) or not (undefined or 0)
* @param {bool} regex treat as a regular expression or not
* @param {bool} smart perform smart filtering or not
* @param {bool} caseInsensitive Do case insenstive matching or not
* @memberof DataTable#oApi
*/
function _fnFilter(settings, input, force, regex, smart, caseInsensitive) {
var rpSearch = _fnFilterCreateSearch(input, regex, smart, caseInsensitive);
var prevSearch = settings.oPreviousSearch.sSearch;
var displayMaster = settings.aiDisplayMaster;
var display, invalidated, i;
// Need to take account of custom filtering functions - always filter
if (DataTable.ext.search.length !== 0) {
force = true;
}
// Check if any of the rows were invalidated
invalidated = _fnFilterData(settings);
// If the input is blank - we just want the full data set
if (input.length <= 0) {
settings.aiDisplay = displayMaster.slice();
}
else {
// New search - start from the master array
if (invalidated ||
force ||
prevSearch.length > input.length ||
input.indexOf(prevSearch) !== 0 ||
settings.bSorted // On resort, the display master needs to be
// re-filtered since indexes will have changed
) {
settings.aiDisplay = displayMaster.slice();
}
// Search the display array
display = settings.aiDisplay;
for (i = display.length - 1; i >= 0; i--) {
if (!rpSearch.test(settings.aoData[display[i]]._sFilterRow)) {
display.splice(i, 1);
}
}
}
}
/**
* Build a regular expression object suitable for searching a table
* @param {string} sSearch string to search for
* @param {bool} bRegex treat as a regular expression or not
* @param {bool} bSmart perform smart filtering or not
* @param {bool} bCaseInsensitive Do case insensitive matching or not
* @returns {RegExp} constructed object
* @memberof DataTable#oApi
*/
function _fnFilterCreateSearch(sSearch, bRegex, bSmart, bCaseInsensitive) {
var asSearch,
sRegExpString = bRegex ? sSearch : _fnEscapeRegex(sSearch);
if (bSmart) {
/* Generate the regular expression to use. Something along the lines of:
* ^(?=.*?\bone\b)(?=.*?\btwo\b)(?=.*?\bthree\b).*$
*/
asSearch = sRegExpString.split(' ');
sRegExpString = '^(?=.*?' + asSearch.join(')(?=.*?') + ').*$';
}
return new RegExp(sRegExpString, bCaseInsensitive ? "i" : "");
}
/**
* scape a string such that it can be used in a regular expression
* @param {string} sVal string to escape
* @returns {string} escaped string
* @memberof DataTable#oApi
*/
function _fnEscapeRegex(sVal) {
var acEscape = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-'];
var reReplace = new RegExp('(\\' + acEscape.join('|\\') + ')', 'g');
return sVal.replace(reReplace, '\\$1');
}
var __filter_div = $('<div>')[0];
var __filter_div_textContent = __filter_div.textContent !== undefined;
// Update the filtering data for each row if needed (by invalidation or first run)
function _fnFilterData(settings) {
var columns = settings.aoColumns;
var column;
var i, j, ien, jen, filterData, cellData, row;
var fomatters = DataTable.ext.type.search;
var wasInvalidated = false;
for (i = 0, ien = settings.aoData.length; i < ien; i++) {
row = settings.aoData[i];
if (!row._aFilterData) {
filterData = [];
for (j = 0, jen = columns.length; j < jen; j++) {
column = columns[j];
if (column.bSearchable) {
cellData = _fnGetCellData(settings, i, j, 'filter');
cellData = fomatters[column.sType] ?
fomatters[column.sType](cellData) :
cellData !== null ?
cellData :
'';
}
else {
cellData = '';
}
// If it looks like there is an HTML entity in the string,
// attempt to decode it so sorting works as expected. Note that
// we could use a single line of jQuery to do this, but the DOM
// method used here is much faster http://jsperf.com/html-decode
if (cellData.indexOf && cellData.indexOf('&') !== -1) {
__filter_div.innerHTML = cellData;
cellData = __filter_div_textContent ?
__filter_div.textContent :
__filter_div.innerText;
cellData = cellData.replace(/[\r\n]/g, '');
}
filterData.push(cellData);
}
row._aFilterData = filterData;
row._sFilterRow = filterData.join(' ');
wasInvalidated = true;
}
}
return wasInvalidated;
}
/**
* Generate the node required for the info display
* @param {object} oSettings dataTables settings object
* @returns {node} Information element
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlInfo(settings) {
var
tid = settings.sTableId,
nodes = settings.aanFeatures.i,
n = $('<div/>', {
'class': settings.oClasses.sInfo,
'id': !nodes ? tid + '_info' : null
});
if (!nodes) {
// Update display on each draw
settings.aoDrawCallback.push({
"fn": _fnUpdateInfo,
"sName": "information"
});
n
.attr('role', 'alert')
.attr('aria-live', 'polite')
.attr('aria-relevant', 'all');
// Table is described by our info div
$(settings.nTable).attr('aria-describedby', tid + '_info');
}
return n[0];
}
/**
* Update the information elements in the display
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnUpdateInfo(settings) {
/* Show information about the table */
var nodes = settings.aanFeatures.i;
if (nodes.length === 0) {
return;
}
var
lang = settings.oLanguage,
start = settings._iDisplayStart + 1,
end = settings.fnDisplayEnd(),
max = settings.fnRecordsTotal(),
total = settings.fnRecordsDisplay(),
out = total ?
lang.sInfo :
lang.sInfoEmpty;
if (total !== max) {
/* Record set after filtering */
out += ' ' + lang.sInfoFiltered;
}
// Convert the macros
out += lang.sInfoPostFix;
out = _fnInfoMacros(settings, out);
var callback = lang.fnInfoCallback;
if (callback !== null) {
out = callback.call(settings.oInstance,
settings, start, end, max, total, out
);
}
$(nodes).html(out);
}
function _fnInfoMacros(settings, str) {
// When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
// internally
var
formatter = settings.fnFormatNumber,
start = settings._iDisplayStart + 1,
len = settings._iDisplayLength,
vis = settings.fnRecordsDisplay(),
all = len === -1;
return str.
replace(/_START_/g, formatter.call(settings, start)).
replace(/_END_/g, formatter.call(settings, settings.fnDisplayEnd())).
replace(/_MAX_/g, formatter.call(settings, settings.fnRecordsTotal())).
replace(/_TOTAL_/g, formatter.call(settings, vis)).
replace(/_PAGE_/g, formatter.call(settings, all ? 1 : Math.ceil(start / len))).
replace(/_PAGES_/g, formatter.call(settings, all ? 1 : Math.ceil(vis / len)));
}
/**
* Draw the table for the first time, adding all required features
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnInitialise(settings) {
var i, iLen, iAjaxStart = settings.iInitDisplayStart;
var columns = settings.aoColumns, column;
var features = settings.oFeatures;
/* Ensure that the table data is fully initialised */
if (!settings.bInitialised) {
setTimeout(function () {
_fnInitialise(settings);
}, 200);
return;
}
/* Show the display HTML options */
_fnAddOptionsHtml(settings);
/* Build and draw the header / footer for the table */
_fnBuildHead(settings);
_fnDrawHead(settings, settings.aoHeader);
_fnDrawHead(settings, settings.aoFooter);
/* Okay to show that something is going on now */
_fnProcessingDisplay(settings, true);
/* Calculate sizes for columns */
if (features.bAutoWidth) {
_fnCalculateColumnWidths(settings);
}
for (i = 0, iLen = columns.length; i < iLen; i++) {
column = columns[i];
if (column.sWidth) {
column.nTh.style.width = _fnStringToCss(column.sWidth);
}
}
// If there is default sorting required - let's do it. The sort function
// will do the drawing for us. Otherwise we draw the table regardless of the
// Ajax source - this allows the table to look initialised for Ajax sourcing
// data (show 'loading' message possibly)
_fnReDraw(settings);
// Server-side processing init complete is done by _fnAjaxUpdateDraw
var dataSrc = _fnDataSource(settings);
if (dataSrc != 'ssp') {
// if there is an ajax source load the data
if (dataSrc == 'ajax') {
_fnBuildAjax(settings, [], function (json) {
var aData = _fnAjaxDataSrc(settings, json);
// Got the data - add it to the table
for (i = 0; i < aData.length; i++) {
_fnAddData(settings, aData[i]);
}
// Reset the init display for cookie saving. We've already done
// a filter, and therefore cleared it before. So we need to make
// it appear 'fresh'
settings.iInitDisplayStart = iAjaxStart;
_fnReDraw(settings);
_fnProcessingDisplay(settings, false);
_fnInitComplete(settings, json);
}, settings);
}
else {
_fnProcessingDisplay(settings, false);
_fnInitComplete(settings);
}
}
}
/**
* Draw the table for the first time, adding all required features
* @param {object} oSettings dataTables settings object
* @param {object} [json] JSON from the server that completed the table, if using Ajax source
* with client-side processing (optional)
* @memberof DataTable#oApi
*/
function _fnInitComplete(settings, json) {
settings._bInitComplete = true;
// On an Ajax load we now have data and therefore want to apply the column
// sizing
if (json) {
_fnAdjustColumnSizing(settings);
}
_fnCallbackFire(settings, 'aoInitComplete', 'init', [settings, json]);
}
function _fnLengthChange(settings, val) {
var len = parseInt(val, 10);
settings._iDisplayLength = len;
_fnLengthOverflow(settings);
// Fire length change event
_fnCallbackFire(settings, null, 'length', [settings, len]);
}
/**
* Generate the node required for user display length changing
* @param {object} settings dataTables settings object
* @returns {node} Display length feature node
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlLength(settings) {
var
classes = settings.oClasses,
tableId = settings.sTableId,
menu = settings.aLengthMenu,
d2 = $.isArray(menu[0]),
lengths = d2 ? menu[0] : menu,
language = d2 ? menu[1] : menu;
var select = $('<select/>', {
'name': tableId + '_length',
'aria-controls': tableId,
'class': classes.sLengthSelect
});
for (var i = 0, ien = lengths.length; i < ien; i++) {
select[0][i] = new Option(language[i], lengths[i]);
}
var div = $('<div><label/></div>').addClass(classes.sLength);
if (!settings.aanFeatures.l) {
div[0].id = tableId + '_length';
}
// This split doesn't matter where _MENU_ is, we get three items back from it
var a = settings.oLanguage.sLengthMenu.split(/(_MENU_)/);
div.children()
.append(a[0])
.append(select)
.append(a[2]);
select
.val(settings._iDisplayLength)
.bind('change.DT', function (e) {
_fnLengthChange(settings, $(this).val());
_fnDraw(settings);
});
// Update node value whenever anything changes the table's length
$(settings.nTable).bind('length', function (e, s, len) {
select.val(len);
});
return div[0];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Note that most of the paging logic is done in
* DataTable.ext.pager
*/
/**
* Generate the node required for default pagination
* @param {object} oSettings dataTables settings object
* @returns {node} Pagination feature node
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlPaginate(settings) {
var
type = settings.sPaginationType,
plugin = DataTable.ext.pager[type],
modern = typeof plugin === 'function',
redraw = function (settings) {
_fnDraw(settings);
},
node = $('<div/>').addClass(settings.oClasses.sPaging + type)[0],
features = settings.aanFeatures;
if (!modern) {
plugin.fnInit(settings, node, redraw);
}
/* Add a draw callback for the pagination on first instance, to update the paging display */
if (!features.p) {
node.id = settings.sTableId + '_paginate';
settings.aoDrawCallback.push({
"fn": function (settings) {
if (modern) {
var
start = settings._iDisplayStart,
len = settings._iDisplayLength,
visRecords = settings.fnRecordsDisplay(),
all = len === -1,
page = all ? 0 : Math.ceil(start / len),
pages = all ? 1 : Math.ceil(visRecords / len),
buttons = plugin(page, pages),
i, ien;
for (i = 0, ien = features.p.length; i < ien; i++) {
_fnRenderer(settings, 'pageButton')(
settings, features.p[i], i, buttons, page, pages
);
}
}
else {
plugin.fnUpdate(settings, redraw);
}
},
"sName": "pagination"
});
}
return node;
}
/**
* Alter the display settings to change the page
* @param {object} settings DataTables settings object
* @param {string|int} action Paging action to take: "first", "previous",
* "next" or "last" or page number to jump to (integer)
* @param [bool] redraw Automatically draw the update or not
* @returns {bool} true page has changed, false - no change
* @memberof DataTable#oApi
*/
function _fnPageChange(settings, action, redraw) {
var
start = settings._iDisplayStart,
len = settings._iDisplayLength,
records = settings.fnRecordsDisplay();
if (records === 0 || len === -1) {
start = 0;
}
else if (typeof action === "number") {
start = action * len;
if (start > records) {
start = 0;
}
}
else if (action == "first") {
start = 0;
}
else if (action == "previous") {
start = len >= 0 ?
start - len :
0;
if (start < 0) {
start = 0;
}
}
else if (action == "next") {
if (start + len < records) {
start += len;
}
}
else if (action == "last") {
start = Math.floor((records - 1) / len) * len;
}
else {
_fnLog(settings, 0, "Unknown paging action: " + action, 5);
}
var changed = settings._iDisplayStart !== start;
settings._iDisplayStart = start;
_fnCallbackFire(settings, null, 'page', [settings]);
if (redraw) {
_fnDraw(settings);
}
return changed;
}
/**
* Generate the node required for the processing node
* @param {object} settings dataTables settings object
* @returns {node} Processing element
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlProcessing(settings) {
return $('<div/>', {
'id': !settings.aanFeatures.r ? settings.sTableId + '_processing' : null,
'class': settings.oClasses.sProcessing
})
.html(settings.oLanguage.sProcessing)
.insertBefore(settings.nTable)[0];
}
/**
* Display or hide the processing indicator
* @param {object} settings dataTables settings object
* @param {bool} show Show the processing indicator (true) or not (false)
* @memberof DataTable#oApi
*/
function _fnProcessingDisplay(settings, show) {
if (settings.oFeatures.bProcessing) {
$(settings.aanFeatures.r).css('visibility', show ? 'visible' : 'hidden');
}
_fnCallbackFire(settings, null, 'processing', [settings, show]);
}
/**
* Add any control elements for the table - specifically scrolling
* @param {object} settings dataTables settings object
* @returns {node} Node to add to the DOM
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlTable(settings) {
var scroll = settings.oScroll;
if (scroll.sX === '' && scroll.sY === '') {
return settings.nTable;
}
var scrollX = scroll.sX;
var scrollY = scroll.sY;
var classes = settings.oClasses;
var table = $(settings.nTable);
var caption = table.children('caption');
var captionSide = caption.length ? caption[0]._captionSide : null;
var headerClone = $(table[0].cloneNode(false));
var footerClone = $(table[0].cloneNode(false));
var footer = table.children('tfoot');
var _div = '<div/>';
var size = function (s) {
return !s ? null : _fnStringToCss(s);
};
if (!footer.length) {
footer = null;
}
/*
* The HTML structure that we want to generate in this function is:
* div - scroller
* div - scroll head
* div - scroll head inner
* table - scroll head table
* thead - thead
* div - scroll body
* table - table (master table)
* thead - thead clone for sizing
* tbody - tbody
* div - scroll foot
* div - scroll foot inner
* table - scroll foot table
* tfoot - tfoot
*/
var scroller = $(_div, {'class': classes.sScrollWrapper})
.append(
$(_div, {'class': classes.sScrollHead})
.css({
overflow: 'hidden',
position: 'relative',
border: 0,
width: scrollX ? size(scrollX) : '100%'
})
.append(
$(_div, {'class': classes.sScrollHeadInner})
.css({
'box-sizing': 'content-box',
width: scroll.sXInner || '100%'
})
.append(
headerClone
.removeAttr('id')
.css('margin-left', 0)
.append(
table.children('thead')
)
)
)
.append(captionSide === 'top' ? caption : null)
)
.append(
$(_div, {'class': classes.sScrollBody})
.css({
overflow: 'auto',
height: size(scrollY),
width: size(scrollX)
})
.append(table)
);
if (footer) {
scroller.append(
$(_div, {'class': classes.sScrollFoot})
.css({
overflow: 'hidden',
border: 0,
width: scrollX ? size(scrollX) : '100%'
})
.append(
$(_div, {'class': classes.sScrollFootInner})
.append(
footerClone
.removeAttr('id')
.css('margin-left', 0)
.append(
table.children('tfoot')
)
)
)
.append(captionSide === 'bottom' ? caption : null)
);
}
var children = scroller.children();
var scrollHead = children[0];
var scrollBody = children[1];
var scrollFoot = footer ? children[2] : null;
// When the body is scrolled, then we also want to scroll the headers
if (scrollX) {
$(scrollBody).scroll(function (e) {
var scrollLeft = this.scrollLeft;
scrollHead.scrollLeft = scrollLeft;
if (footer) {
scrollFoot.scrollLeft = scrollLeft;
}
});
}
settings.nScrollHead = scrollHead;
settings.nScrollBody = scrollBody;
settings.nScrollFoot = scrollFoot;
// On redraw - align columns
settings.aoDrawCallback.push({
"fn": _fnScrollDraw,
"sName": "scrolling"
});
return scroller[0];
}
/**
* Update the header, footer and body tables for resizing - i.e. column
* alignment.
*
* Welcome to the most horrible function DataTables. The process that this
* function follows is basically:
* 1. Re-create the table inside the scrolling div
* 2. Take live measurements from the DOM
* 3. Apply the measurements to align the columns
* 4. Clean up
*
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnScrollDraw(settings) {
// Given that this is such a monster function, a lot of variables are use
// to try and keep the minimised size as small as possible
var
scroll = settings.oScroll,
scrollX = scroll.sX,
scrollXInner = scroll.sXInner,
scrollY = scroll.sY,
barWidth = scroll.iBarWidth,
divHeader = $(settings.nScrollHead),
divHeaderStyle = divHeader[0].style,
divHeaderInner = divHeader.children('div'),
divHeaderInnerStyle = divHeaderInner[0].style,
divHeaderTable = divHeaderInner.children('table'),
divBodyEl = settings.nScrollBody,
divBody = $(divBodyEl),
divBodyStyle = divBodyEl.style,
divFooter = $(settings.nScrollFoot),
divFooterInner = divFooter.children('div'),
divFooterTable = divFooterInner.children('table'),
header = $(settings.nTHead),
table = $(settings.nTable),
tableEl = table[0],
tableStyle = tableEl.style,
footer = settings.nTFoot ? $(settings.nTFoot) : null,
browser = settings.oBrowser,
ie67 = browser.bScrollOversize,
headerTrgEls, footerTrgEls,
headerSrcEls, footerSrcEls,
headerCopy, footerCopy,
headerWidths = [], footerWidths = [],
idx, correction, sanityWidth,
zeroOut = function (nSizer) {
var style = nSizer.style;
style.paddingTop = "0";
style.paddingBottom = "0";
style.borderTopWidth = "0";
style.borderBottomWidth = "0";
style.height = 0;
};
/*
* 1. Re-create the table inside the scrolling div
*/
// Remove the old minimised thead and tfoot elements in the inner table
table.children('thead, tfoot').remove();
// Clone the current header and footer elements and then place it into the inner table
headerCopy = header.clone().prependTo(table);
headerTrgEls = header.find('tr'); // original header is in its own table
headerSrcEls = headerCopy.find('tr');
headerCopy.find('th, td').removeAttr('tabindex');
if (footer) {
footerCopy = footer.clone().prependTo(table);
footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized
footerSrcEls = footerCopy.find('tr');
}
/*
* 2. Take live measurements from the DOM - do not alter the DOM itself!
*/
// Remove old sizing and apply the calculated column widths
// Get the unique column headers in the newly created (cloned) header. We want to apply the
// calculated sizes to this header
if (!scrollX) {
divBodyStyle.width = '100%';
divHeader[0].style.width = '100%';
}
$.each(_fnGetUniqueThs(settings, headerCopy), function (i, el) {
idx = _fnVisibleToColumnIndex(settings, i);
el.style.width = settings.aoColumns[idx].sWidth;
});
if (footer) {
_fnApplyToChildren(function (n) {
n.style.width = "";
}, footerSrcEls);
}
// If scroll collapse is enabled, when we put the headers back into the body for sizing, we
// will end up forcing the scrollbar to appear, making our measurements wrong for when we
// then hide it (end of this function), so add the header height to the body scroller.
if (scroll.bCollapse && scrollY !== "") {
divBodyStyle.height = (divBody.offsetHeight + header[0].offsetHeight) + "px";
}
// Size the table as a whole
sanityWidth = table.outerWidth();
if (scrollX === "") {
// No x scrolling
tableStyle.width = "100%";
// IE7 will make the width of the table when 100% include the scrollbar
// - which is shouldn't. When there is a scrollbar we need to take this
// into account.
if (ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight ||
divBody.css('overflow-y') == "scroll")
) {
tableStyle.width = _fnStringToCss(table.outerWidth() - barWidth);
}
}
else {
// x scrolling
if (scrollXInner !== "") {
// x scroll inner has been given - use it
tableStyle.width = _fnStringToCss(scrollXInner);
}
else if (sanityWidth == divBody.width() && divBody.height() < table.height()) {
// There is y-scrolling - try to take account of the y scroll bar
tableStyle.width = _fnStringToCss(sanityWidth - barWidth);
if (table.outerWidth() > sanityWidth - barWidth) {
// Not possible to take account of it
tableStyle.width = _fnStringToCss(sanityWidth);
}
}
else {
// When all else fails
tableStyle.width = _fnStringToCss(sanityWidth);
}
}
// Recalculate the sanity width - now that we've applied the required width,
// before it was a temporary variable. This is required because the column
// width calculation is done before this table DOM is created.
sanityWidth = table.outerWidth();
// Hidden header should have zero height, so remove padding and borders. Then
// set the width based on the real headers
// Apply all styles in one pass
_fnApplyToChildren(zeroOut, headerSrcEls);
// Read all widths in next pass
_fnApplyToChildren(function (nSizer) {
headerWidths.push(_fnStringToCss($(nSizer).css('width')));
}, headerSrcEls);
// Apply all widths in final pass
_fnApplyToChildren(function (nToSize, i) {
nToSize.style.width = headerWidths[i];
}, headerTrgEls);
$(headerSrcEls).height(0);
/* Same again with the footer if we have one */
if (footer) {
_fnApplyToChildren(zeroOut, footerSrcEls);
_fnApplyToChildren(function (nSizer) {
footerWidths.push(_fnStringToCss($(nSizer).css('width')));
}, footerSrcEls);
_fnApplyToChildren(function (nToSize, i) {
nToSize.style.width = footerWidths[i];
}, footerTrgEls);
$(footerSrcEls).height(0);
}
/*
* 3. Apply the measurements
*/
// "Hide" the header and footer that we used for the sizing. We want to also fix their width
// to what they currently are
_fnApplyToChildren(function (nSizer, i) {
nSizer.innerHTML = "";
nSizer.style.width = headerWidths[i];
}, headerSrcEls);
if (footer) {
_fnApplyToChildren(function (nSizer, i) {
nSizer.innerHTML = "";
nSizer.style.width = footerWidths[i];
}, footerSrcEls);
}
// Sanity check that the table is of a sensible width. If not then we are going to get
// misalignment - try to prevent this by not allowing the table to shrink below its min width
if (table.outerWidth() < sanityWidth) {
// The min width depends upon if we have a vertical scrollbar visible or not */
correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight ||
divBody.css('overflow-y') == "scroll")) ?
sanityWidth + barWidth :
sanityWidth;
// IE6/7 are a law unto themselves...
if (ie67 && (divBodyEl.scrollHeight >
divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")
) {
tableStyle.width = _fnStringToCss(correction - barWidth);
}
// And give the user a warning that we've stopped the table getting too small
if (scrollX === "" || scrollXInner !== "") {
_fnLog(settings, 1, 'Possible column misalignment', 6);
}
}
else {
correction = '100%';
}
// Apply to the container elements
divBodyStyle.width = _fnStringToCss(correction);
divHeaderStyle.width = _fnStringToCss(correction);
if (footer) {
settings.nScrollFoot.style.width = _fnStringToCss(correction);
}
/*
* 4. Clean up
*/
if (!scrollY) {
/* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
* the scrollbar height from the visible display, rather than adding it on. We need to
* set the height in order to sort this. Don't want to do it in any other browsers.
*/
if (ie67) {
divBodyStyle.height = _fnStringToCss(tableEl.offsetHeight + barWidth);
}
}
if (scrollY && scroll.bCollapse) {
divBodyStyle.height = _fnStringToCss(scrollY);
var iExtra = (scrollX && tableEl.offsetWidth > divBodyEl.offsetWidth) ?
barWidth :
0;
if (tableEl.offsetHeight < divBodyEl.offsetHeight) {
divBodyStyle.height = _fnStringToCss(tableEl.offsetHeight + iExtra);
}
}
/* Finally set the width's of the header and footer tables */
var iOuterWidth = table.outerWidth();
divHeaderTable[0].style.width = _fnStringToCss(iOuterWidth);
divHeaderInnerStyle.width = _fnStringToCss(iOuterWidth);
// Figure out if there are scrollbar present - if so then we need a the header and footer to
// provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll";
var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right' );
divHeaderInnerStyle[padding] = bScrolling ? barWidth + "px" : "0px";
if (footer) {
divFooterTable[0].style.width = _fnStringToCss(iOuterWidth);
divFooterInner[0].style.width = _fnStringToCss(iOuterWidth);
divFooterInner[0].style[padding] = bScrolling ? barWidth + "px" : "0px";
}
/* Adjust the position of the header in case we loose the y-scrollbar */
divBody.scroll();
/* If sorting or filtering has occurred, jump the scrolling back to the top */
if (settings.bSorted || settings.bFiltered) {
divBodyEl.scrollTop = 0;
}
}
/**
* Apply a given function to the display child nodes of an element array (typically
* TD children of TR rows
* @param {function} fn Method to apply to the objects
* @param array {nodes} an1 List of elements to look through for display children
* @param array {nodes} an2 Another list (identical structure to the first) - optional
* @memberof DataTable#oApi
*/
function _fnApplyToChildren(fn, an1, an2) {
var index = 0, i = 0, iLen = an1.length;
var nNode1, nNode2;
while (i < iLen) {
nNode1 = an1[i].firstChild;
nNode2 = an2 ? an2[i].firstChild : null;
while (nNode1) {
if (nNode1.nodeType === 1) {
if (an2) {
fn(nNode1, nNode2, index);
}
else {
fn(nNode1, index);
}
index++;
}
nNode1 = nNode1.nextSibling;
nNode2 = an2 ? nNode2.nextSibling : null;
}
i++;
}
}
var __re_html_remove = /<.*?>/g;
/**
* Calculate the width of columns for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnCalculateColumnWidths(oSettings) {
var
table = oSettings.nTable,
columns = oSettings.aoColumns,
scroll = oSettings.oScroll,
scrollY = scroll.sY,
scrollX = scroll.sX,
scrollXInner = scroll.sXInner,
columnCount = columns.length,
visibleColumns = _fnGetColumns(oSettings, 'bVisible'),
headerCells = $('th', oSettings.nTHead),
tableWidthAttr = table.getAttribute('width'),
tableContainer = table.parentNode,
userInputs = false,
i, column, columnIdx, width, outerWidth;
/* Convert any user input sizes into pixel sizes */
for (i = 0; i < visibleColumns.length; i++) {
column = columns[visibleColumns[i]];
if (column.sWidth !== null) {
column.sWidth = _fnConvertToWidth(column.sWidthOrig, tableContainer);
userInputs = true;
}
}
/* If the number of columns in the DOM equals the number that we have to
* process in DataTables, then we can use the offsets that are created by
* the web- browser. No custom sizes can be set in order for this to happen,
* nor scrolling used
*/
if (!userInputs && !scrollX && !scrollY &&
columnCount == _fnVisbleColumns(oSettings) &&
columnCount == headerCells.length
) {
for (i = 0; i < columnCount; i++) {
columns[i].sWidth = _fnStringToCss(headerCells.eq(i).width());
}
}
else {
// Otherwise construct a single row table with the widest node in the
// data, assign any user defined widths, then insert it into the DOM and
// allow the browser to do all the hard work of calculating table widths
var tmpTable = $(table.cloneNode(false))
.css('visibility', 'hidden')
.removeAttr('id')
.append($(oSettings.nTHead).clone(false))
.append($(oSettings.nTFoot).clone(false))
.append($('<tbody><tr/></tbody>'));
// Remove any assigned widths from the footer (from scrolling)
tmpTable.find('tfoot th, tfoot td').css('width', '');
var tr = tmpTable.find('tbody tr');
// Apply custom sizing to the cloned header
headerCells = _fnGetUniqueThs(oSettings, tmpTable.find('thead')[0]);
for (i = 0; i < visibleColumns.length; i++) {
column = columns[visibleColumns[i]];
headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
_fnStringToCss(column.sWidthOrig) :
'';
}
// Find the widest cell for each column and put it into the table
if (oSettings.aoData.length) {
for (i = 0; i < visibleColumns.length; i++) {
columnIdx = visibleColumns[i];
column = columns[columnIdx];
$(_fnGetWidestNode(oSettings, columnIdx))
.clone(false)
.append(column.sContentPadding)
.appendTo(tr);
}
}
// Table has been built, attach to the document so we can work with it
tmpTable.appendTo(tableContainer);
// When scrolling (X or Y) we want to set the width of the table as
// appropriate. However, when not scrolling leave the table width as it
// is. This results in slightly different, but I think correct behaviour
if (scrollX && scrollXInner) {
tmpTable.width(scrollXInner);
}
else if (scrollX) {
tmpTable.css('width', 'auto');
if (tmpTable.width() < tableContainer.offsetWidth) {
tmpTable.width(tableContainer.offsetWidth);
}
}
else if (scrollY) {
tmpTable.width(tableContainer.offsetWidth);
}
else if (tableWidthAttr) {
tmpTable.width(tableWidthAttr);
}
// Take into account the y scrollbar
_fnScrollingWidthAdjust(oSettings, tmpTable[0]);
// Browsers need a bit of a hand when a width is assigned to any columns
// when x-scrolling as they tend to collapse the table to the min-width,
// even if we sent the column widths. So we need to keep track of what
// the table width should be by summing the user given values, and the
// automatic values
if (scrollX) {
var total = 0;
for (i = 0; i < visibleColumns.length; i++) {
column = columns[visibleColumns[i]];
outerWidth = $(headerCells[i]).outerWidth();
total += column.sWidthOrig === null ?
outerWidth :
parseInt(column.sWidth, 10) + outerWidth - $(headerCells[i]).width();
}
tmpTable.width(_fnStringToCss(total));
table.style.width = _fnStringToCss(total);
}
// Get the width of each column in the constructed table
for (i = 0; i < visibleColumns.length; i++) {
column = columns[visibleColumns[i]];
width = $(headerCells[i]).width();
if (width) {
column.sWidth = _fnStringToCss(width);
}
}
table.style.width = _fnStringToCss(tmpTable.css('width'));
// Finished with the table - ditch it
tmpTable.remove();
}
// If there is a width attr, we want to attach an event listener which
// allows the table sizing to automatically adjust when the window is
// resized. Use the width attr rather than CSS, since we can't know if the
// CSS is a relative value or absolute - DOM read is always px.
if (tableWidthAttr) {
table.style.width = _fnStringToCss(tableWidthAttr);
if (!oSettings._reszEvt) {
$(window).bind('resize.DT-' + oSettings.sInstance, _fnThrottle(function () {
_fnAdjustColumnSizing(oSettings);
}));
oSettings._reszEvt = true;
}
}
}
function _fnThrottle(fn) {
var
frequency = 200,
last,
timer;
return function () {
var
now = +new Date(),
args = arguments;
if (last && now < last + frequency) {
clearTimeout(timer);
timer = setTimeout(function () {
last = now;
fn();
}, frequency);
}
else {
last = now;
fn();
}
};
}
/**
* Convert a CSS unit width to pixels (e.g. 2em)
* @param {string} width width to be converted
* @param {node} parent parent to get the with for (required for relative widths) - optional
* @returns {int} width in pixels
* @memberof DataTable#oApi
*/
function _fnConvertToWidth(width, parent) {
if (!width) {
return 0;
}
var n = $('<div/>')
.css('width', _fnStringToCss(width))
.appendTo(parent || document.body);
var val = n[0].offsetWidth;
n.remove();
return val;
}
/**
* Adjust a table's width to take account of vertical scroll bar
* @param {object} oSettings dataTables settings object
* @param {node} n table node
* @memberof DataTable#oApi
*/
function _fnScrollingWidthAdjust(settings, n) {
var scroll = settings.oScroll;
if (scroll.sX || scroll.sY) {
// When y-scrolling only, we want to remove the width of the scroll bar
// so the table + scroll bar will fit into the area available, otherwise
// we fix the table at its current size with no adjustment
var correction = !scroll.sX ? scroll.iBarWidth : 0;
n.style.width = _fnStringToCss($(n).outerWidth() - correction);
}
}
/**
* Get the widest node
* @param {object} settings dataTables settings object
* @param {int} colIdx column of interest
* @returns {node} widest table node
* @memberof DataTable#oApi
*/
function _fnGetWidestNode(settings, colIdx) {
var idx = _fnGetMaxLenString(settings, colIdx);
if (idx < 0) {
return null;
}
var data = settings.aoData[idx];
return !data.nTr ? // Might not have been created when deferred rendering
$('<td/>').html(_fnGetCellData(settings, idx, colIdx, 'display'))[0] :
data.anCells[colIdx];
}
/**
* Get the maximum strlen for each data column
* @param {object} settings dataTables settings object
* @param {int} colIdx column of interest
* @returns {string} max string length for each column
* @memberof DataTable#oApi
*/
function _fnGetMaxLenString(settings, colIdx) {
var s, max = -1, maxIdx = -1;
for (var i = 0, ien = settings.aoData.length; i < ien; i++) {
s = _fnGetCellData(settings, i, colIdx, 'display') + '';
s = s.replace(__re_html_remove, '');
if (s.length > max) {
max = s.length;
maxIdx = i;
}
}
return maxIdx;
}
/**
* Append a CSS unit (only if required) to a string
* @param {string} value to css-ify
* @returns {string} value with css unit
* @memberof DataTable#oApi
*/
function _fnStringToCss(s) {
if (s === null) {
return '0px';
}
if (typeof s == 'number') {
return s < 0 ?
'0px' :
s + 'px';
}
// Check it has a unit character already
return s.match(/\d$/) ?
s + 'px' :
s;
}
/**
* Get the width of a scroll bar in this browser being used
* @returns {int} width in pixels
* @memberof DataTable#oApi
*/
function _fnScrollBarWidth() {
// On first run a static variable is set, since this is only needed once.
// Subsequent runs will just use the previously calculated value
if (!DataTable.__scrollbarWidth) {
var inner = $('<p/>').css({
width: '100%',
height: 200,
padding: 0
})[0];
var outer = $('<div/>')
.css({
position: 'absolute',
top: 0,
left: 0,
width: 200,
height: 150,
padding: 0,
overflow: 'hidden',
visibility: 'hidden'
})
.append(inner)
.appendTo('body');
var w1 = inner.offsetWidth;
outer.css('overflow', 'scroll');
var w2 = inner.offsetWidth;
if (w1 === w2) {
w2 = outer[0].clientWidth;
}
outer.remove();
DataTable.__scrollbarWidth = w1 - w2;
}
return DataTable.__scrollbarWidth;
}
function _fnSortFlatten(settings) {
var
i, iLen, k, kLen,
aSort = [],
aiOrig = [],
aoColumns = settings.aoColumns,
aDataSort, iCol, sType, srcCol,
fixed = settings.aaSortingFixed,
fixedObj = $.isPlainObject(fixed),
nestedSort = [],
add = function (a) {
if (a.length && !$.isArray(a[0])) {
// 1D array
nestedSort.push(a);
}
else {
// 2D array
nestedSort.push.apply(nestedSort, a);
}
};
// Build the sort array, with pre-fix and post-fix options if they have been
// specified
if ($.isArray(fixed)) {
add(fixed);
}
if (fixedObj && fixed.pre) {
add(fixed.pre);
}
add(settings.aaSorting);
if (fixedObj && fixed.post) {
add(fixed.post);
}
for (i = 0; i < nestedSort.length; i++) {
srcCol = nestedSort[i][0];
aDataSort = aoColumns[srcCol].aDataSort;
for (k = 0, kLen = aDataSort.length; k < kLen; k++) {
iCol = aDataSort[k];
sType = aoColumns[iCol].sType || 'string';
aSort.push({
src: srcCol,
col: iCol,
dir: nestedSort[i][1],
index: nestedSort[i][2],
type: sType,
formatter: DataTable.ext.type.order[sType + "-pre"]
});
}
}
return aSort;
}
/**
* Change the order of the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
* @todo This really needs split up!
*/
function _fnSort(oSettings) {
var
i, ien, iLen, j, jLen, k, kLen,
sDataType, nTh,
aiOrig = [],
oExtSort = DataTable.ext.type.order,
aoData = oSettings.aoData,
aoColumns = oSettings.aoColumns,
aDataSort, data, iCol, sType, oSort,
formatters = 0,
sortCol,
displayMaster = oSettings.aiDisplayMaster,
aSort = _fnSortFlatten(oSettings);
// Resolve any column types that are unknown due to addition or invalidation
// @todo Can this be moved into a 'data-ready' handler which is called when
// data is going to be used in the table?
_fnColumnTypes(oSettings);
for (i = 0, ien = aSort.length; i < ien; i++) {
sortCol = aSort[i];
// Track if we can use the fast sort algorithm
if (sortCol.formatter) {
formatters++;
}
// Load the data needed for the sort, for each cell
_fnSortData(oSettings, sortCol.col);
}
/* No sorting required if server-side or no sorting array */
if (_fnDataSource(oSettings) != 'ssp' && aSort.length !== 0) {
// Create a value - key array of the current row positions such that we can use their
// current position during the sort, if values match, in order to perform stable sorting
for (i = 0, iLen = displayMaster.length; i < iLen; i++) {
aiOrig[displayMaster[i]] = i;
}
/* Do the sort - here we want multi-column sorting based on a given data source (column)
* and sorting function (from oSort) in a certain direction. It's reasonably complex to
* follow on it's own, but this is what we want (example two column sorting):
* fnLocalSorting = function(a,b){
* var iTest;
* iTest = oSort['string-asc']('data11', 'data12');
* if (iTest !== 0)
* return iTest;
* iTest = oSort['numeric-desc']('data21', 'data22');
* if (iTest !== 0)
* return iTest;
* return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
* }
* Basically we have a test for each sorting column, if the data in that column is equal,
* test the next column. If all columns match, then we use a numeric sort on the row
* positions in the original data array to provide a stable sort.
*
* Note - I know it seems excessive to have two sorting methods, but the first is around
* 15% faster, so the second is only maintained for backwards compatibility with sorting
* methods which do not have a pre-sort formatting function.
*/
if (formatters === aSort.length) {
// All sort types have formatting functions
displayMaster.sort(function (a, b) {
var
x, y, k, test, sort,
len = aSort.length,
dataA = aoData[a]._aSortData,
dataB = aoData[b]._aSortData;
for (k = 0; k < len; k++) {
sort = aSort[k];
x = dataA[sort.col];
y = dataB[sort.col];
test = x < y ? -1 : x > y ? 1 : 0;
if (test !== 0) {
return sort.dir === 'asc' ? test : -test;
}
}
x = aiOrig[a];
y = aiOrig[b];
return x < y ? -1 : x > y ? 1 : 0;
});
}
else {
// Depreciated - remove in 1.11 (providing a plug-in option)
// Not all sort types have formatting methods, so we have to call their sorting
// methods.
displayMaster.sort(function (a, b) {
var
x, y, k, l, test, sort, fn,
len = aSort.length,
dataA = aoData[a]._aSortData,
dataB = aoData[b]._aSortData;
for (k = 0; k < len; k++) {
sort = aSort[k];
x = dataA[sort.col];
y = dataB[sort.col];
fn = oExtSort[sort.type + "-" + sort.dir] || oExtSort["string-" + sort.dir];
test = fn(x, y);
if (test !== 0) {
return test;
}
}
x = aiOrig[a];
y = aiOrig[b];
return x < y ? -1 : x > y ? 1 : 0;
});
}
}
/* Tell the draw function that we have sorted the data */
oSettings.bSorted = true;
}
function _fnSortAria(settings) {
var label;
var nextSort;
var columns = settings.aoColumns;
var aSort = _fnSortFlatten(settings);
var oAria = settings.oLanguage.oAria;
// ARIA attributes - need to loop all columns, to update all (removing old
// attributes as needed)
for (var i = 0, iLen = columns.length; i < iLen; i++) {
var col = columns[i];
var asSorting = col.asSorting;
var sTitle = col.sTitle.replace(/<.*?>/g, "");
var jqTh = $(col.nTh).removeAttr('aria-sort');
/* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
if (col.bSortable) {
if (aSort.length > 0 && aSort[0].col == i) {
jqTh.attr('aria-sort', aSort[0].dir == "asc" ? "ascending" : "descending");
nextSort = asSorting[aSort[0].index + 1] || asSorting[0];
}
else {
nextSort = asSorting[0];
}
label = sTitle + ( nextSort === "asc" ?
oAria.sSortAscending :
oAria.sSortDescending
);
}
else {
label = sTitle;
}
jqTh.attr('aria-label', label);
}
}
/**
* Function to run on user sort request
* @param {object} settings dataTables settings object
* @param {node} attachTo node to attach the handler to
* @param {int} colIdx column sorting index
* @param {boolean} [append=false] Append the requested sort to the existing
* sort if true (i.e. multi-column sort)
* @param {function} [callback] callback function
* @memberof DataTable#oApi
*/
function _fnSortListener(settings, colIdx, append, callback) {
var col = settings.aoColumns[colIdx];
var sorting = settings.aaSorting;
var asSorting = col.asSorting;
var nextSortIdx;
var next = function (a) {
var idx = a._idx;
if (idx === undefined) {
idx = $.inArray(a[1], asSorting);
}
return idx + 1 >= asSorting.length ? 0 : idx + 1;
};
// If appending the sort then we are multi-column sorting
if (append && settings.oFeatures.bSortMulti) {
// Are we already doing some kind of sort on this column?
var sortIdx = $.inArray(colIdx, _pluck(sorting, '0'));
if (sortIdx !== -1) {
// Yes, modify the sort
nextSortIdx = next(sorting[sortIdx]);
sorting[sortIdx][1] = asSorting[nextSortIdx];
sorting[sortIdx]._idx = nextSortIdx;
}
else {
// No sort on this column yet
sorting.push([colIdx, asSorting[0], 0]);
sorting[sorting.length - 1]._idx = 0;
}
}
else if (sorting.length && sorting[0][0] == colIdx) {
// Single column - already sorting on this column, modify the sort
nextSortIdx = next(sorting[0]);
sorting.length = 1;
sorting[0][1] = asSorting[nextSortIdx];
sorting[0]._idx = nextSortIdx;
}
else {
// Single column - sort only on this column
sorting.length = 0;
sorting.push([colIdx, asSorting[0]]);
sorting[0]._idx = 0;
}
// Run the sort by calling a full redraw
_fnReDraw(settings);
// callback used for async user interaction
if (typeof callback == 'function') {
callback(settings);
}
}
/**
* Attach a sort handler (click) to a node
* @param {object} settings dataTables settings object
* @param {node} attachTo node to attach the handler to
* @param {int} colIdx column sorting index
* @param {function} [callback] callback function
* @memberof DataTable#oApi
*/
function _fnSortAttachListener(settings, attachTo, colIdx, callback) {
var col = settings.aoColumns[colIdx];
_fnBindAction(attachTo, {}, function (e) {
/* If the column is not sortable - don't to anything */
if (col.bSortable === false) {
return;
}
_fnProcessingDisplay(settings, true);
// Use a timeout to allow the processing display to be shown.
setTimeout(function () {
_fnSortListener(settings, colIdx, e.shiftKey, callback);
// In server-side processing, the draw callback will remove the
// processing display
if (_fnDataSource(settings) !== 'ssp') {
_fnProcessingDisplay(settings, false);
}
}, 0);
});
}
/**
* Set the sorting classes on table's body, Note: it is safe to call this function
* when bSort and bSortClasses are false
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnSortingClasses(settings) {
var oldSort = settings.aLastSort;
var sortClass = settings.oClasses.sSortColumn;
var sort = _fnSortFlatten(settings);
var features = settings.oFeatures;
var i, ien, colIdx;
if (features.bSort && features.bSortClasses) {
// Remove old sorting classes
for (i = 0, ien = oldSort.length; i < ien; i++) {
colIdx = oldSort[i].src;
// Remove column sorting
$(_pluck(settings.aoData, 'anCells', colIdx))
.removeClass(sortClass + (i < 2 ? i + 1 : 3));
}
// Add new column sorting
for (i = 0, ien = sort.length; i < ien; i++) {
colIdx = sort[i].src;
$(_pluck(settings.aoData, 'anCells', colIdx))
.addClass(sortClass + (i < 2 ? i + 1 : 3));
}
}
settings.aLastSort = sort;
}
// Get the data to sort a column, be it from cache, fresh (populating the
// cache), or from a sort formatter
function _fnSortData(settings, idx) {
// Custom sorting function - provided by the sort data type
var column = settings.aoColumns[idx];
var customSort = DataTable.ext.order[column.sSortDataType];
var customData;
if (customSort) {
customData = customSort.call(settings.oInstance, settings, idx,
_fnColumnIndexToVisible(settings, idx)
);
}
// Use / populate cache
var row, cellData;
var formatter = DataTable.ext.type.order[column.sType + "-pre"];
for (var i = 0, ien = settings.aoData.length; i < ien; i++) {
row = settings.aoData[i];
if (!row._aSortData) {
row._aSortData = [];
}
if (!row._aSortData[idx] || customSort) {
cellData = customSort ?
customData[i] : // If there was a custom sort function, use data from there
_fnGetCellData(settings, i, idx, 'sort');
row._aSortData[idx] = formatter ?
formatter(cellData) :
cellData;
}
}
}
/**
* Save the state of a table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnSaveState(oSettings) {
if (!oSettings.oFeatures.bStateSave || oSettings.bDestroying) {
return;
}
/* Store the interesting variables */
var i, iLen;
var oState = {
"iCreate": new Date().getTime(),
"iStart": oSettings._iDisplayStart,
"iLength": oSettings._iDisplayLength,
"aaSorting": $.extend(true, [], oSettings.aaSorting),
"oSearch": $.extend(true, {}, oSettings.oPreviousSearch),
"aoSearchCols": $.extend(true, [], oSettings.aoPreSearchCols),
"abVisCols": []
};
for (i = 0, iLen = oSettings.aoColumns.length; i < iLen; i++) {
oState.abVisCols.push(oSettings.aoColumns[i].bVisible);
}
_fnCallbackFire(oSettings, "aoStateSaveParams", 'stateSaveParams', [oSettings, oState]);
oSettings.fnStateSaveCallback.call(oSettings.oInstance, oSettings, oState);
}
/**
* Attempt to load a saved table state
* @param {object} oSettings dataTables settings object
* @param {object} oInit DataTables init object so we can override settings
* @memberof DataTable#oApi
*/
function _fnLoadState(oSettings, oInit) {
var i, ien;
var columns = oSettings.aoColumns;
if (!oSettings.oFeatures.bStateSave) {
return;
}
var oData = oSettings.fnStateLoadCallback.call(oSettings.oInstance, oSettings);
if (!oData) {
return;
}
/* Allow custom and plug-in manipulation functions to alter the saved data set and
* cancelling of loading by returning false
*/
var abStateLoad = _fnCallbackFire(oSettings, 'aoStateLoadParams', 'stateLoadParams', [oSettings, oData]);
if ($.inArray(false, abStateLoad) !== -1) {
return;
}
/* Reject old data */
if (oData.iCreate < new Date().getTime() - (oSettings.iStateDuration * 1000)) {
return;
}
// Number of columns have changed - all bets are off, no restore of settings
if (columns.length !== oData.aoSearchCols.length) {
return;
}
/* Store the saved state so it might be accessed at any time */
oSettings.oLoadedState = $.extend(true, {}, oData);
/* Restore key features */
oSettings._iDisplayStart = oData.iStart;
oSettings.iInitDisplayStart = oData.iStart;
oSettings._iDisplayLength = oData.iLength;
oSettings.aaSorting = [];
var savedSort = oData.aaSorting;
for (i = 0, ien = savedSort.length; i < ien; i++) {
oSettings.aaSorting.push(savedSort[i][0] >= columns.length ?
[0, savedSort[i][1]] :
savedSort[i]
);
}
/* Search filtering */
$.extend(oSettings.oPreviousSearch, oData.oSearch);
$.extend(true, oSettings.aoPreSearchCols, oData.aoSearchCols);
/* Column visibility state */
for (i = 0, ien = oData.abVisCols.length; i < ien; i++) {
columns[i].bVisible = oData.abVisCols[i];
}
_fnCallbackFire(oSettings, 'aoStateLoaded', 'stateLoaded', [oSettings, oData]);
}
/**
* Return the settings object for a particular table
* @param {node} table table we are using as a dataTable
* @returns {object} Settings object - or null if not found
* @memberof DataTable#oApi
*/
function _fnSettingsFromNode(table) {
var settings = DataTable.settings;
var idx = $.inArray(table, _pluck(settings, 'nTable'));
return idx !== -1 ?
settings[idx] :
null;
}
/**
* Log an error message
* @param {object} settings dataTables settings object
* @param {int} level log error messages, or display them to the user
* @param {string} msg error message
* @param {int} tn Technical note id to get more information about the error.
* @memberof DataTable#oApi
*/
function _fnLog(settings, level, msg, tn) {
msg = 'DataTables warning: ' +
(settings !== null ? 'table id=' + settings.sTableId + ' - ' : '') + msg;
if (tn) {
msg += '. For more information about this error, please see ' +
'http://datatables.net/tn/' + tn;
}
if (!level) {
// Backwards compatibility pre 1.10
var ext = DataTable.ext;
var type = ext.sErrMode || ext.errMode;
if (type == 'alert') {
alert(msg);
}
else {
throw new Error(msg);
}
}
else if (window.console && console.log) {
console.log(msg);
}
}
/**
* See if a property is defined on one object, if so assign it to the other object
* @param {object} ret target object
* @param {object} src source object
* @param {string} name property
* @param {string} [mappedName] name to map too - optional, name used if not given
* @memberof DataTable#oApi
*/
function _fnMap(ret, src, name, mappedName) {
if ($.isArray(name)) {
$.each(name, function (i, val) {
if ($.isArray(val)) {
_fnMap(ret, src, val[0], val[1]);
}
else {
_fnMap(ret, src, val);
}
});
return;
}
if (mappedName === undefined) {
mappedName = name;
}
if (src[name] !== undefined) {
ret[mappedName] = src[name];
}
}
/**
* Extend objects - very similar to jQuery.extend, but deep copy objects, and
* shallow copy arrays. The reason we need to do this, is that we don't want to
* deep copy array init values (such as aaSorting) since the dev wouldn't be
* able to override them, but we do want to deep copy arrays.
* @param {object} out Object to extend
* @param {object} extender Object from which the properties will be applied to
* out
* @param {boolean} breakRefs If true, then arrays will be sliced to take an
* independent copy with the exception of the `data` or `aaData` parameters
* if they are present. This is so you can pass in a collection to
* DataTables and have that used as your data source without breaking the
* references
* @returns {object} out Reference, just for convenience - out === the return.
* @memberof DataTable#oApi
* @todo This doesn't take account of arrays inside the deep copied objects.
*/
function _fnExtend(out, extender, breakRefs) {
var val;
for (var prop in extender) {
if (extender.hasOwnProperty(prop)) {
val = extender[prop];
if ($.isPlainObject(val)) {
if (!$.isPlainObject(out[prop])) {
out[prop] = {};
}
$.extend(true, out[prop], val);
}
else if (breakRefs && prop !== 'data' && prop !== 'aaData' && $.isArray(val)) {
out[prop] = val.slice();
}
else {
out[prop] = val;
}
}
}
return out;
}
/**
* Bind an event handers to allow a click or return key to activate the callback.
* This is good for accessibility since a return on the keyboard will have the
* same effect as a click, if the element has focus.
* @param {element} n Element to bind the action to
* @param {object} oData Data object to pass to the triggered function
* @param {function} fn Callback function for when the event is triggered
* @memberof DataTable#oApi
*/
function _fnBindAction(n, oData, fn) {
$(n)
.bind('click.DT', oData, function (e) {
n.blur(); // Remove focus outline for mouse user
fn(e);
})
.bind('keypress.DT', oData, function (e) {
if (e.which === 13) {
fn(e);
}
})
.bind('selectstart.DT', function () {
/* Take the brutal approach to cancelling text selection */
return false;
});
}
/**
* Register a callback function. Easily allows a callback function to be added to
* an array store of callback functions that can then all be called together.
* @param {object} oSettings dataTables settings object
* @param {string} sStore Name of the array storage for the callbacks in oSettings
* @param {function} fn Function to be called back
* @param {string} sName Identifying name for the callback (i.e. a label)
* @memberof DataTable#oApi
*/
function _fnCallbackReg(oSettings, sStore, fn, sName) {
if (fn) {
oSettings[sStore].push({
"fn": fn,
"sName": sName
});
}
}
/**
* Fire callback functions and trigger events. Note that the loop over the
* callback array store is done backwards! Further note that you do not want to
* fire off triggers in time sensitive applications (for example cell creation)
* as its slow.
* @param {object} settings dataTables settings object
* @param {string} callbackArr Name of the array storage for the callbacks in
* oSettings
* @param {string} event Name of the jQuery custom event to trigger. If null no
* trigger is fired
* @param {array} args Array of arguments to pass to the callback function /
* trigger
* @memberof DataTable#oApi
*/
function _fnCallbackFire(settings, callbackArr, event, args) {
var ret = [];
if (callbackArr) {
ret = $.map(settings[callbackArr].slice().reverse(), function (val, i) {
return val.fn.apply(settings.oInstance, args);
});
}
if (event !== null) {
$(settings.nTable).trigger(event + '.dt', args);
}
return ret;
}
function _fnLengthOverflow(settings) {
var
start = settings._iDisplayStart,
end = settings.fnDisplayEnd(),
len = settings._iDisplayLength;
/* If we have space to show extra rows (backing up from the end point - then do so */
if (end === settings.fnRecordsDisplay()) {
start = end - len;
}
if (len === -1 || start < 0) {
start = 0;
}
settings._iDisplayStart = start;
}
function _fnRenderer(settings, type) {
var renderer = settings.renderer;
var host = DataTable.ext.renderer[type];
if ($.isPlainObject(renderer) && renderer[type]) {
// Specific renderer for this type. If available use it, otherwise use
// the default.
return host[renderer[type]] || host._;
}
else if (typeof renderer === 'string') {
// Common renderer - if there is one available for this type use it,
// otherwise use the default
return host[renderer] || host._;
}
// Use the default
return host._;
}
/**
* Detect the data source being used for the table. Used to simplify the code
* a little (ajax) and to make it compress a little smaller.
*
* @param {object} settings dataTables settings object
* @returns {string} Data source
* @memberof DataTable#oApi
*/
function _fnDataSource(settings) {
if (settings.oFeatures.bServerSide) {
return 'ssp';
}
else if (settings.ajax || settings.sAjaxSource) {
return 'ajax';
}
return 'dom';
}
DataTable = function (options) {
/**
* Perform a jQuery selector action on the table's TR elements (from the tbody) and
* return the resulting jQuery object.
* @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
* @param {object} [oOpts] Optional parameters for modifying the rows to be included
* @param {string} [oOpts.filter=none] Select TR elements that meet the current filter
* criterion ("applied") or all TR elements (i.e. no filter).
* @param {string} [oOpts.order=current] Order of the TR elements in the processed array.
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
* ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {object} jQuery object, filtered by the given selector.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Highlight every second row
* oTable.$('tr:odd').css('backgroundColor', 'blue');
* } );
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Filter to rows with 'Webkit' in them, add a background colour and then
* // remove the filter, thus highlighting the 'Webkit' rows only.
* oTable.fnFilter('Webkit');
* oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue');
* oTable.fnFilter('');
* } );
*/
this.$ = function (sSelector, oOpts) {
return this.api(true).$(sSelector, oOpts);
};
/**
* Almost identical to $ in operation, but in this case returns the data for the matched
* rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
* rather than any descendants, so the data can be obtained for the row/cell. If matching
* rows are found, the data returned is the original data array/object that was used to
* create the row (or a generated array if from a DOM source).
*
* This method is often useful in-combination with $ where both functions are given the
* same parameters and the array indexes will match identically.
* @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
* @param {object} [oOpts] Optional parameters for modifying the rows to be included
* @param {string} [oOpts.filter=none] Select elements that meet the current filter
* criterion ("applied") or all elements (i.e. no filter).
* @param {string} [oOpts.order=current] Order of the data in the processed array.
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
* ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {array} Data for the matched elements. If any elements, as a result of the
* selector, were not TR, TD or TH elements in the DataTable, they will have a null
* entry in the array.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Get the data from the first row in the table
* var data = oTable._('tr:first');
*
* // Do something useful with the data
* alert( "First cell is: "+data[0] );
* } );
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Filter to 'Webkit' and get all data for
* oTable.fnFilter('Webkit');
* var data = oTable._('tr', {"search": "applied"});
*
* // Do something with the data
* alert( data.length+" rows matched the search" );
* } );
*/
this._ = function (sSelector, oOpts) {
return this.api(true).rows(sSelector, oOpts).data();
};
/**
* Create a DataTables Api instance, with the currently selected tables for
* the Api's context.
* @param {boolean} [traditional=false] Set the API instance's context to be
* only the table referred to by the `DataTable.ext.iApiIndex` option, as was
* used in the API presented by DataTables 1.9- (i.e. the traditional mode),
* or if all tables captured in the jQuery object should be used.
* @return {DataTables.Api}
*/
this.api = function (traditional) {
return traditional ?
new _Api(
_fnSettingsFromNode(this[_ext.iApiIndex])
) :
new _Api(this);
};
/**
* Add a single new row or multiple rows of data to the table. Please note
* that this is suitable for client-side processing only - if you are using
* server-side processing (i.e. "bServerSide": true), then to add data, you
* must add it to the data source, i.e. the server-side, through an Ajax call.
* @param {array|object} data The data to be added to the table. This can be:
* <ul>
* <li>1D array of data - add a single row with the data provided</li>
* <li>2D array of arrays - add multiple rows in a single call</li>
* <li>object - data object when using <i>mData</i></li>
* <li>array of objects - multiple data objects when using <i>mData</i></li>
* </ul>
* @param {bool} [redraw=true] redraw the table or not
* @returns {array} An array of integers, representing the list of indexes in
* <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
* the table.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* // Global var for counter
* var giCount = 2;
*
* $(document).ready(function() {
* $('#example').dataTable();
* } );
*
* function fnClickAddRow() {
* $('#example').dataTable().fnAddData( [
* giCount+".1",
* giCount+".2",
* giCount+".3",
* giCount+".4" ]
* );
*
* giCount++;
* }
*/
this.fnAddData = function (data, redraw) {
var api = this.api(true);
/* Check if we want to add multiple rows or not */
var rows = $.isArray(data) && ( $.isArray(data[0]) || $.isPlainObject(data[0]) ) ?
api.rows.add(data) :
api.row.add(data);
if (redraw === undefined || redraw) {
api.draw();
}
return rows.flatten().toArray();
};
/**
* This function will make DataTables recalculate the column sizes, based on the data
* contained in the table and the sizes applied to the columns (in the DOM, CSS or
* through the sWidth parameter). This can be useful when the width of the table's
* parent element changes (for example a window resize).
* @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable( {
* "sScrollY": "200px",
* "bPaginate": false
* } );
*
* $(window).bind('resize', function () {
* oTable.fnAdjustColumnSizing();
* } );
* } );
*/
this.fnAdjustColumnSizing = function (bRedraw) {
var api = this.api(true).columns.adjust();
var settings = api.settings()[0];
var scroll = settings.oScroll;
if (bRedraw === undefined || bRedraw) {
api.draw(false);
}
else if (scroll.sX !== "" || scroll.sY !== "") {
/* If not redrawing, but scrolling, we want to apply the new column sizes anyway */
_fnScrollDraw(settings);
}
};
/**
* Quickly and simply clear a table
* @param {bool} [bRedraw=true] redraw the table or not
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...)
* oTable.fnClearTable();
* } );
*/
this.fnClearTable = function (bRedraw) {
var api = this.api(true).clear();
if (bRedraw === undefined || bRedraw) {
api.draw();
}
};
/**
* The exact opposite of 'opening' a row, this function will close any rows which
* are currently 'open'.
* @param {node} nTr the table row to 'close'
* @returns {int} 0 on success, or 1 if failed (can't find the row)
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnClose = function (nTr) {
this.api(true).row(nTr).child.hide();
};
/**
* Remove a row for the table
* @param {mixed} target The index of the row from aoData to be deleted, or
* the TR element you want to delete
* @param {function|null} [callBack] Callback function
* @param {bool} [redraw=true] Redraw the table or not
* @returns {array} The row that was deleted
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Immediately remove the first row
* oTable.fnDeleteRow( 0 );
* } );
*/
this.fnDeleteRow = function (target, callback, redraw) {
var api = this.api(true);
var rows = api.rows(target);
var settings = rows.settings()[0];
var data = settings.aoData[rows[0][0]];
rows.remove();
if (callback) {
callback.call(this, settings, data);
}
if (redraw === undefined || redraw) {
api.draw();
}
return data;
};
/**
* Restore the table to it's original state in the DOM by removing all of DataTables
* enhancements, alterations to the DOM structure of the table and event listeners.
* @param {boolean} [remove=false] Completely remove the table from the DOM
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* // This example is fairly pointless in reality, but shows how fnDestroy can be used
* var oTable = $('#example').dataTable();
* oTable.fnDestroy();
* } );
*/
this.fnDestroy = function (remove) {
this.api(true).destroy(remove);
};
/**
* Redraw the table
* @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Re-draw the table - you wouldn't want to do it here, but it's an example :-)
* oTable.fnDraw();
* } );
*/
this.fnDraw = function (complete) {
// Note that this isn't an exact match to the old call to _fnDraw - it takes
// into account the new data, but can old position.
this.api(true).draw(!complete);
};
/**
* Filter the input based on data
* @param {string} sInput String to filter the table on
* @param {int|null} [iColumn] Column to limit filtering to
* @param {bool} [bRegex=false] Treat as regular expression or not
* @param {bool} [bSmart=true] Perform smart filtering or not
* @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es)
* @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false)
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sometime later - filter...
* oTable.fnFilter( 'test string' );
* } );
*/
this.fnFilter = function (sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive) {
var api = this.api(true);
if (iColumn === null || iColumn === undefined) {
api.search(sInput, bRegex, bSmart, bCaseInsensitive);
}
else {
api.column(iColumn).search(sInput, bRegex, bSmart, bCaseInsensitive);
}
api.draw();
};
/**
* Get the data for the whole table, an individual row or an individual cell based on the
* provided parameters.
* @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as
* a TR node then the data source for the whole row will be returned. If given as a
* TD/TH cell node then iCol will be automatically calculated and the data for the
* cell returned. If given as an integer, then this is treated as the aoData internal
* data index for the row (see fnGetPosition) and the data for that row used.
* @param {int} [col] Optional column index that you want the data of.
* @returns {array|object|string} If mRow is undefined, then the data for all rows is
* returned. If mRow is defined, just data for that row, and is iCol is
* defined, only data for the designated cell is returned.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* // Row data
* $(document).ready(function() {
* oTable = $('#example').dataTable();
*
* oTable.$('tr').click( function () {
* var data = oTable.fnGetData( this );
* // ... do something with the array / object of data for the row
* } );
* } );
*
* @example
* // Individual cell data
* $(document).ready(function() {
* oTable = $('#example').dataTable();
*
* oTable.$('td').click( function () {
* var sData = oTable.fnGetData( this );
* alert( 'The cell clicked on had the value of '+sData );
* } );
* } );
*/
this.fnGetData = function (src, col) {
var api = this.api(true);
if (src !== undefined) {
var type = src.nodeName ? src.nodeName.toLowerCase() : '';
return col !== undefined || type == 'td' || type == 'th' ?
api.cell(src, col).data() :
api.row(src).data();
}
return api.data().toArray();
};
/**
* Get an array of the TR nodes that are used in the table's body. Note that you will
* typically want to use the '$' API method in preference to this as it is more
* flexible.
* @param {int} [iRow] Optional row index for the TR element you want
* @returns {array|node} If iRow is undefined, returns an array of all TR elements
* in the table's body, or iRow is defined, just the TR element requested.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Get the nodes from the table
* var nNodes = oTable.fnGetNodes( );
* } );
*/
this.fnGetNodes = function (iRow) {
var api = this.api(true);
return iRow !== undefined ?
api.row(iRow).node() :
api.rows().nodes().toArray();
};
/**
* Get the array indexes of a particular cell from it's DOM element
* and column index including hidden columns
* @param {node} node this can either be a TR, TD or TH in the table's body
* @returns {int} If nNode is given as a TR, then a single index is returned, or
* if given as a cell, an array of [row index, column index (visible),
* column index (all)] is given.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* $('#example tbody td').click( function () {
* // Get the position of the current data from the node
* var aPos = oTable.fnGetPosition( this );
*
* // Get the data array for this row
* var aData = oTable.fnGetData( aPos[0] );
*
* // Update the data array and return the value
* aData[ aPos[1] ] = 'clicked';
* this.innerHTML = 'clicked';
* } );
*
* // Init DataTables
* oTable = $('#example').dataTable();
* } );
*/
this.fnGetPosition = function (node) {
var api = this.api(true);
var nodeName = node.nodeName.toUpperCase();
if (nodeName == 'TR') {
return api.row(node).index();
}
else if (nodeName == 'TD' || nodeName == 'TH') {
var cell = api.cell(node).index();
return [
cell.row,
cell.columnVisible,
cell.column
];
}
return null;
};
/**
* Check to see if a row is 'open' or not.
* @param {node} nTr the table row to check
* @returns {boolean} true if the row is currently open, false otherwise
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnIsOpen = function (nTr) {
return this.api(true).row(nTr).child.isShown();
};
/**
* This function will place a new row directly after a row which is currently
* on display on the page, with the HTML contents that is passed into the
* function. This can be used, for example, to ask for confirmation that a
* particular record should be deleted.
* @param {node} nTr The table row to 'open'
* @param {string|node|jQuery} mHtml The HTML to put into the row
* @param {string} sClass Class to give the new TD cell
* @returns {node} The row opened. Note that if the table row passed in as the
* first parameter, is not found in the table, this method will silently
* return.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnOpen = function (nTr, mHtml, sClass) {
return this.api(true).row(nTr).child(mHtml, sClass).show();
};
/**
* Change the pagination - provides the internal logic for pagination in a simple API
* function. With this function you can have a DataTables table go to the next,
* previous, first or last pages.
* @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
* or page number to jump to (integer), note that page 0 is the first page.
* @param {bool} [bRedraw=true] Redraw the table or not
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* oTable.fnPageChange( 'next' );
* } );
*/
this.fnPageChange = function (mAction, bRedraw) {
var api = this.api(true).page(mAction);
if (bRedraw === undefined || bRedraw) {
api.draw(false);
}
};
/**
* Show a particular column
* @param {int} iCol The column whose display should be changed
* @param {bool} bShow Show (true) or hide (false) the column
* @param {bool} [bRedraw=true] Redraw the table or not
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Hide the second column after initialisation
* oTable.fnSetColumnVis( 1, false );
* } );
*/
this.fnSetColumnVis = function (iCol, bShow, bRedraw) {
var api = this.api(true).column(iCol).visible(bShow);
if (bRedraw === undefined || bRedraw) {
api.columns.adjust().draw();
}
};
/**
* Get the settings for a particular table for external manipulation
* @returns {object} DataTables settings object. See
* {@link DataTable.models.oSettings}
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* var oSettings = oTable.fnSettings();
*
* // Show an example parameter from the settings
* alert( oSettings._iDisplayStart );
* } );
*/
this.fnSettings = function () {
return _fnSettingsFromNode(this[_ext.iApiIndex]);
};
/**
* Sort the table by a particular column
* @param {int} iCol the data index to sort on. Note that this will not match the
* 'display index' if you have hidden data entries
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sort immediately with columns 0 and 1
* oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
* } );
*/
this.fnSort = function (aaSort) {
this.api(true).order(aaSort).draw();
};
/**
* Attach a sort listener to an element for a given column
* @param {node} nNode the element to attach the sort listener to
* @param {int} iColumn the column that a click on this node will sort on
* @param {function} [fnCallback] callback function when sort is run
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sort on column 1, when 'sorter' is clicked on
* oTable.fnSortListener( document.getElementById('sorter'), 1 );
* } );
*/
this.fnSortListener = function (nNode, iColumn, fnCallback) {
this.api(true).order.listener(nNode, iColumn, fnCallback);
};
/**
* Update a table cell or row - this method will accept either a single value to
* update the cell with, an array of values with one element for each column or
* an object in the same format as the original data source. The function is
* self-referencing in order to make the multi column updates easier.
* @param {object|array|string} mData Data to update the cell/row with
* @param {node|int} mRow TR element you want to update or the aoData index
* @param {int} [iColumn] The column to update, give as null or undefined to
* update a whole row.
* @param {bool} [bRedraw=true] Redraw the table or not
* @param {bool} [bAction=true] Perform pre-draw actions or not
* @returns {int} 0 on success, 1 on error
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell
* oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row
* } );
*/
this.fnUpdate = function (mData, mRow, iColumn, bRedraw, bAction) {
var api = this.api(true);
if (iColumn === undefined || iColumn === null) {
api.row(mRow).data(mData);
}
else {
api.cell(mRow, iColumn).data(mData);
}
if (bAction === undefined || bAction) {
api.columns.adjust();
}
if (bRedraw === undefined || bRedraw) {
api.draw();
}
return 0;
};
/**
* Provide a common method for plug-ins to check the version of DataTables being used, in order
* to ensure compatibility.
* @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
* formats "X" and "X.Y" are also acceptable.
* @returns {boolean} true if this version of DataTables is greater or equal to the required
* version, or false if this version of DataTales is not suitable
* @method
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* alert( oTable.fnVersionCheck( '1.9.0' ) );
* } );
*/
this.fnVersionCheck = _ext.fnVersionCheck;
/*
* This is really a good bit rubbish this method of exposing the internal methods
* publicly... - To be fixed in 2.0 using methods on the prototype
*/
/**
* Create a wrapper function for exporting an internal functions to an external API.
* @param {string} fn API function name
* @returns {function} wrapped function
* @memberof DataTable#internal
*/
function _fnExternApiFunc(fn) {
return function () {
var args = [_fnSettingsFromNode(this[DataTable.ext.iApiIndex])].concat(
Array.prototype.slice.call(arguments)
);
return DataTable.ext.internal[fn].apply(this, args);
};
}
/**
* Reference to internal functions for use by plug-in developers. Note that
* these methods are references to internal functions and are considered to be
* private. If you use these methods, be aware that they are liable to change
* between versions.
* @namespace
*/
this.oApi = this.internal = {
_fnExternApiFunc: _fnExternApiFunc,
_fnBuildAjax: _fnBuildAjax,
_fnAjaxUpdate: _fnAjaxUpdate,
_fnAjaxParameters: _fnAjaxParameters,
_fnAjaxUpdateDraw: _fnAjaxUpdateDraw,
_fnAjaxDataSrc: _fnAjaxDataSrc,
_fnAddColumn: _fnAddColumn,
_fnColumnOptions: _fnColumnOptions,
_fnAdjustColumnSizing: _fnAdjustColumnSizing,
_fnVisibleToColumnIndex: _fnVisibleToColumnIndex,
_fnColumnIndexToVisible: _fnColumnIndexToVisible,
_fnVisbleColumns: _fnVisbleColumns,
_fnGetColumns: _fnGetColumns,
_fnColumnTypes: _fnColumnTypes,
_fnApplyColumnDefs: _fnApplyColumnDefs,
_fnHungarianMap: _fnHungarianMap,
_fnCamelToHungarian: _fnCamelToHungarian,
_fnLanguageCompat: _fnLanguageCompat,
_fnBrowserDetect: _fnBrowserDetect,
_fnAddData: _fnAddData,
_fnAddTr: _fnAddTr,
_fnNodeToDataIndex: _fnNodeToDataIndex,
_fnNodeToColumnIndex: _fnNodeToColumnIndex,
_fnGetRowData: _fnGetRowData,
_fnGetCellData: _fnGetCellData,
_fnSetCellData: _fnSetCellData,
_fnSplitObjNotation: _fnSplitObjNotation,
_fnGetObjectDataFn: _fnGetObjectDataFn,
_fnSetObjectDataFn: _fnSetObjectDataFn,
_fnGetDataMaster: _fnGetDataMaster,
_fnClearTable: _fnClearTable,
_fnDeleteIndex: _fnDeleteIndex,
_fnInvalidateRow: _fnInvalidateRow,
_fnGetRowElements: _fnGetRowElements,
_fnCreateTr: _fnCreateTr,
_fnBuildHead: _fnBuildHead,
_fnDrawHead: _fnDrawHead,
_fnDraw: _fnDraw,
_fnReDraw: _fnReDraw,
_fnAddOptionsHtml: _fnAddOptionsHtml,
_fnDetectHeader: _fnDetectHeader,
_fnGetUniqueThs: _fnGetUniqueThs,
_fnFeatureHtmlFilter: _fnFeatureHtmlFilter,
_fnFilterComplete: _fnFilterComplete,
_fnFilterCustom: _fnFilterCustom,
_fnFilterColumn: _fnFilterColumn,
_fnFilter: _fnFilter,
_fnFilterCreateSearch: _fnFilterCreateSearch,
_fnEscapeRegex: _fnEscapeRegex,
_fnFilterData: _fnFilterData,
_fnFeatureHtmlInfo: _fnFeatureHtmlInfo,
_fnUpdateInfo: _fnUpdateInfo,
_fnInfoMacros: _fnInfoMacros,
_fnInitialise: _fnInitialise,
_fnInitComplete: _fnInitComplete,
_fnLengthChange: _fnLengthChange,
_fnFeatureHtmlLength: _fnFeatureHtmlLength,
_fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate,
_fnPageChange: _fnPageChange,
_fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing,
_fnProcessingDisplay: _fnProcessingDisplay,
_fnFeatureHtmlTable: _fnFeatureHtmlTable,
_fnScrollDraw: _fnScrollDraw,
_fnApplyToChildren: _fnApplyToChildren,
_fnCalculateColumnWidths: _fnCalculateColumnWidths,
_fnThrottle: _fnThrottle,
_fnConvertToWidth: _fnConvertToWidth,
_fnScrollingWidthAdjust: _fnScrollingWidthAdjust,
_fnGetWidestNode: _fnGetWidestNode,
_fnGetMaxLenString: _fnGetMaxLenString,
_fnStringToCss: _fnStringToCss,
_fnScrollBarWidth: _fnScrollBarWidth,
_fnSortFlatten: _fnSortFlatten,
_fnSort: _fnSort,
_fnSortAria: _fnSortAria,
_fnSortListener: _fnSortListener,
_fnSortAttachListener: _fnSortAttachListener,
_fnSortingClasses: _fnSortingClasses,
_fnSortData: _fnSortData,
_fnSaveState: _fnSaveState,
_fnLoadState: _fnLoadState,
_fnSettingsFromNode: _fnSettingsFromNode,
_fnLog: _fnLog,
_fnMap: _fnMap,
_fnBindAction: _fnBindAction,
_fnCallbackReg: _fnCallbackReg,
_fnCallbackFire: _fnCallbackFire,
_fnLengthOverflow: _fnLengthOverflow,
_fnRenderer: _fnRenderer,
_fnDataSource: _fnDataSource,
_fnRowAttributes: _fnRowAttributes
};
$.extend(DataTable.ext.internal, this.internal);
for (var fn in DataTable.ext.internal) {
if (fn) {
this[fn] = _fnExternApiFunc(fn);
}
}
var _that = this;
var emptyInit = options === undefined;
var len = this.length;
if (emptyInit) {
options = {};
}
this.each(function () {
// For each initialisation we want to give it a clean initialisation
// object that can be bashed around
var o = {};
var oInit = len > 1 ? // optimisation for single table case
_fnExtend(o, options, true) :
options;
/*global oInit,_that,emptyInit*/
var i = 0, iLen, j, jLen, k, kLen;
var sId = this.getAttribute('id');
var bInitHandedOff = false;
var defaults = DataTable.defaults;
/* Sanity check */
if (this.nodeName.toLowerCase() != 'table') {
_fnLog(null, 0, 'Non-table node initialisation (' + this.nodeName + ')', 2);
return;
}
/* Backwards compatibility for the defaults */
_fnCompatOpts(defaults);
_fnCompatCols(defaults.column);
/* Convert the camel-case defaults to Hungarian */
_fnCamelToHungarian(defaults, defaults, true);
_fnCamelToHungarian(defaults.column, defaults.column, true);
/* Setting up the initialisation object */
_fnCamelToHungarian(defaults, oInit);
/* Check to see if we are re-initialising a table */
var allSettings = DataTable.settings;
for (i = 0, iLen = allSettings.length; i < iLen; i++) {
/* Base check on table node */
if (allSettings[i].nTable == this) {
var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve;
var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy;
if (emptyInit || bRetrieve) {
return allSettings[i].oInstance;
}
else if (bDestroy) {
allSettings[i].oInstance.fnDestroy();
break;
}
else {
_fnLog(allSettings[i], 0, 'Cannot reinitialise DataTable', 3);
return;
}
}
/* If the element we are initialising has the same ID as a table which was previously
* initialised, but the table nodes don't match (from before) then we destroy the old
* instance by simply deleting it. This is under the assumption that the table has been
* destroyed by other methods. Anyone using non-id selectors will need to do this manually
*/
if (allSettings[i].sTableId == this.id) {
allSettings.splice(i, 1);
break;
}
}
/* Ensure the table has an ID - required for accessibility */
if (sId === null || sId === "") {
sId = "DataTables_Table_" + (DataTable.ext._unique++);
this.id = sId;
}
/* Create the settings object for this table and set some of the default parameters */
var oSettings = $.extend(true, {}, DataTable.models.oSettings, {
"nTable": this,
"oApi": _that.internal,
"oInit": oInit,
"sDestroyWidth": $(this)[0].style.width,
"sInstance": sId,
"sTableId": sId
});
allSettings.push(oSettings);
// Need to add the instance after the instance after the settings object has been added
// to the settings array, so we can self reference the table instance if more than one
oSettings.oInstance = (_that.length === 1) ? _that : $(this).dataTable();
// Backwards compatibility, before we apply all the defaults
_fnCompatOpts(oInit);
if (oInit.oLanguage) {
_fnLanguageCompat(oInit.oLanguage);
}
// If the length menu is given, but the init display length is not, use the length menu
if (oInit.aLengthMenu && !oInit.iDisplayLength) {
oInit.iDisplayLength = $.isArray(oInit.aLengthMenu[0]) ?
oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0];
}
// Apply the defaults and init options to make a single init object will all
// options defined from defaults and instance options.
oInit = _fnExtend($.extend(true, {}, defaults), oInit);
// Map the initialisation options onto the settings object
_fnMap(oSettings.oFeatures, oInit, [
"bPaginate",
"bLengthChange",
"bFilter",
"bSort",
"bSortMulti",
"bInfo",
"bProcessing",
"bAutoWidth",
"bSortClasses",
"bServerSide",
"bDeferRender"
]);
_fnMap(oSettings, oInit, [
"asStripeClasses",
"ajax",
"fnServerData",
"fnFormatNumber",
"sServerMethod",
"aaSorting",
"aaSortingFixed",
"aLengthMenu",
"sPaginationType",
"sAjaxSource",
"sAjaxDataProp",
"iStateDuration",
"sDom",
"bSortCellsTop",
"iTabIndex",
"fnStateLoadCallback",
"fnStateSaveCallback",
"renderer",
["iCookieDuration", "iStateDuration"], // backwards compat
["oSearch", "oPreviousSearch"],
["aoSearchCols", "aoPreSearchCols"],
["iDisplayLength", "_iDisplayLength"],
["bJQueryUI", "bJUI"]
]);
_fnMap(oSettings.oScroll, oInit, [
["sScrollX", "sX"],
["sScrollXInner", "sXInner"],
["sScrollY", "sY"],
["bScrollCollapse", "bCollapse"]
]);
_fnMap(oSettings.oLanguage, oInit, "fnInfoCallback");
/* Callback functions which are array driven */
_fnCallbackReg(oSettings, 'aoDrawCallback', oInit.fnDrawCallback, 'user');
_fnCallbackReg(oSettings, 'aoServerParams', oInit.fnServerParams, 'user');
_fnCallbackReg(oSettings, 'aoStateSaveParams', oInit.fnStateSaveParams, 'user');
_fnCallbackReg(oSettings, 'aoStateLoadParams', oInit.fnStateLoadParams, 'user');
_fnCallbackReg(oSettings, 'aoStateLoaded', oInit.fnStateLoaded, 'user');
_fnCallbackReg(oSettings, 'aoRowCallback', oInit.fnRowCallback, 'user');
_fnCallbackReg(oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow, 'user');
_fnCallbackReg(oSettings, 'aoHeaderCallback', oInit.fnHeaderCallback, 'user');
_fnCallbackReg(oSettings, 'aoFooterCallback', oInit.fnFooterCallback, 'user');
_fnCallbackReg(oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user');
_fnCallbackReg(oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user');
// @todo Remove in 1.11
if (oInit.bJQueryUI) {
/* Use the JUI classes object for display. You could clone the oStdClasses object if
* you want to have multiple tables with multiple independent classes
*/
$.extend(oSettings.oClasses, DataTable.ext.oJUIClasses, oInit.oClasses);
if (oInit.sDom === defaults.sDom && defaults.sDom === "lfrtip") {
/* Set the DOM to use a layout suitable for jQuery UI's theming */
oSettings.sDom = '<"H"lfr>t<"F"ip>';
}
if (!oSettings.renderer) {
oSettings.renderer = 'jqueryui';
}
else if ($.isPlainObject(oSettings.renderer) && !oSettings.renderer.header) {
oSettings.renderer.header = 'jqueryui';
}
}
else {
$.extend(oSettings.oClasses, DataTable.ext.classes, oInit.oClasses);
}
$(this).addClass(oSettings.oClasses.sTable);
/* Calculate the scroll bar width and cache it for use later on */
if (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") {
oSettings.oScroll.iBarWidth = _fnScrollBarWidth();
}
if (oSettings.oScroll.sX === true) { // Easy initialisation of x-scrolling
oSettings.oScroll.sX = '100%';
}
if (oSettings.iInitDisplayStart === undefined) {
/* Display start point, taking into account the save saving */
oSettings.iInitDisplayStart = oInit.iDisplayStart;
oSettings._iDisplayStart = oInit.iDisplayStart;
}
if (oInit.iDeferLoading !== null) {
oSettings.bDeferLoading = true;
var tmp = $.isArray(oInit.iDeferLoading);
oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading;
oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading;
}
/* Language definitions */
if (oInit.oLanguage.sUrl !== "") {
/* Get the language definitions from a file - because this Ajax call makes the language
* get async to the remainder of this function we use bInitHandedOff to indicate that
* _fnInitialise will be fired by the returned Ajax handler, rather than the constructor
*/
oSettings.oLanguage.sUrl = oInit.oLanguage.sUrl;
$.getJSON(oSettings.oLanguage.sUrl, null, function (json) {
_fnLanguageCompat(json);
_fnCamelToHungarian(defaults.oLanguage, json);
$.extend(true, oSettings.oLanguage, oInit.oLanguage, json);
_fnInitialise(oSettings);
});
bInitHandedOff = true;
}
else {
$.extend(true, oSettings.oLanguage, oInit.oLanguage);
}
/*
* Stripes
*/
if (oInit.asStripeClasses === null) {
oSettings.asStripeClasses = [
oSettings.oClasses.sStripeOdd,
oSettings.oClasses.sStripeEven
];
}
/* Remove row stripe classes if they are already on the table row */
var stripeClasses = oSettings.asStripeClasses;
var rowOne = $('tbody tr:eq(0)', this);
if ($.inArray(true, $.map(stripeClasses, function (el, i) {
return rowOne.hasClass(el);
})) !== -1) {
$('tbody tr', this).removeClass(stripeClasses.join(' '));
oSettings.asDestroyStripes = stripeClasses.slice();
}
/*
* Columns
* See if we should load columns automatically or use defined ones
*/
var anThs = [];
var aoColumnsInit;
var nThead = this.getElementsByTagName('thead');
if (nThead.length !== 0) {
_fnDetectHeader(oSettings.aoHeader, nThead[0]);
anThs = _fnGetUniqueThs(oSettings);
}
/* If not given a column array, generate one with nulls */
if (oInit.aoColumns === null) {
aoColumnsInit = [];
for (i = 0, iLen = anThs.length; i < iLen; i++) {
aoColumnsInit.push(null);
}
}
else {
aoColumnsInit = oInit.aoColumns;
}
/* Add the columns */
for (i = 0, iLen = aoColumnsInit.length; i < iLen; i++) {
_fnAddColumn(oSettings, anThs ? anThs[i] : null);
}
/* Apply the column definitions */
_fnApplyColumnDefs(oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) {
_fnColumnOptions(oSettings, iCol, oDef);
});
/* HTML5 attribute detection - build an mData object automatically if the
* attributes are found
*/
if (rowOne.length) {
var a = function (cell, name) {
return cell.getAttribute('data-' + name) ? name : null;
};
$.each(_fnGetRowElements(oSettings, rowOne[0]).cells, function (i, cell) {
var col = oSettings.aoColumns[i];
if (col.mData === i) {
var sort = a(cell, 'sort') || a(cell, 'order');
var filter = a(cell, 'filter') || a(cell, 'search');
if (sort !== null || filter !== null) {
col.mData = {
_: i + '.display',
sort: sort !== null ? i + '.@data-' + sort : undefined,
type: sort !== null ? i + '.@data-' + sort : undefined,
filter: filter !== null ? i + '.@data-' + filter : undefined
};
_fnColumnOptions(oSettings, i);
}
}
});
}
/* Must be done after everything which can be overridden by the state saving! */
if (oInit.bStateSave) {
oSettings.oFeatures.bStateSave = true;
_fnLoadState(oSettings, oInit);
_fnCallbackReg(oSettings, 'aoDrawCallback', _fnSaveState, 'state_save');
}
/*
* Sorting
* @todo For modularisation (1.11) this needs to do into a sort start up handler
*/
// If aaSorting is not defined, then we use the first indicator in asSorting
// in case that has been altered, so the default sort reflects that option
if (oInit.aaSorting === undefined) {
for (i = 0, iLen = oSettings.aaSorting.length; i < iLen; i++) {
oSettings.aaSorting[i][1] = oSettings.aoColumns[i].asSorting[0];
}
}
/* Do a first pass on the sorting classes (allows any size changes to be taken into
* account, and also will apply sorting disabled classes if disabled
*/
_fnSortingClasses(oSettings);
if (oSettings.oFeatures.bSort) {
_fnCallbackReg(oSettings, 'aoDrawCallback', function () {
if (oSettings.bSorted) {
var aSort = _fnSortFlatten(oSettings);
var sortedColumns = {};
$.each(aSort, function (i, val) {
sortedColumns[val.src] = val.dir;
});
_fnCallbackFire(oSettings, null, 'order', [oSettings, aSort, sortedColumns]);
_fnSortingClasses(oSettings);
_fnSortAria(oSettings);
}
});
}
/*
* Final init
* Cache the header, body and footer as required, creating them if needed
*/
/* Browser support detection */
_fnBrowserDetect(oSettings);
// Work around for Webkit bug 83867 - store the caption-side before removing from doc
var captions = $(this).children('caption').each(function () {
this._captionSide = $(this).css('caption-side');
});
var thead = $(this).children('thead');
if (thead.length === 0) {
thead = $('<thead/>').appendTo(this);
}
oSettings.nTHead = thead[0];
var tbody = $(this).children('tbody');
if (tbody.length === 0) {
tbody = $('<tbody/>').appendTo(this);
}
oSettings.nTBody = tbody[0];
var tfoot = $(this).children('tfoot');
if (tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "")) {
// If we are a scrolling table, and no footer has been given, then we need to create
// a tfoot element for the caption element to be appended to
tfoot = $('<tfoot/>').appendTo(this);
}
if (tfoot.length === 0 || tfoot.children().length === 0) {
$(this).addClass(oSettings.oClasses.sNoFooter);
}
else if (tfoot.length > 0) {
oSettings.nTFoot = tfoot[0];
_fnDetectHeader(oSettings.aoFooter, oSettings.nTFoot);
}
/* Check if there is data passing into the constructor */
if (oInit.aaData) {
for (i = 0; i < oInit.aaData.length; i++) {
_fnAddData(oSettings, oInit.aaData[i]);
}
}
else if (oSettings.bDeferLoading || _fnDataSource(oSettings) == 'dom') {
/* Grab the data from the page - only do this when deferred loading or no Ajax
* source since there is no point in reading the DOM data if we are then going
* to replace it with Ajax data
*/
_fnAddTr(oSettings, $(oSettings.nTBody).children('tr'));
}
/* Copy the data index array */
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
/* Initialisation complete - table can be drawn */
oSettings.bInitialised = true;
/* Check if we need to initialise the table (it might not have been handed off to the
* language processor)
*/
if (bInitHandedOff === false) {
_fnInitialise(oSettings);
}
});
_that = null;
return this;
};
/**
* Computed structure of the DataTables API, defined by the options passed to
* `DataTable.Api.register()` when building the API.
*
* The structure is built in order to speed creation and extension of the Api
* objects since the extensions are effectively pre-parsed.
*
* The array is an array of objects with the following structure, where this
* base array represents the Api prototype base:
*
* [
* {
* name: 'data' -- string - Property name
* val: function () {}, -- function - Api method (or undefined if just an object
* methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result
* propExt: [ ... ] -- array - Array of Api object definitions to extend the property
* },
* {
* name: 'row'
* val: {},
* methodExt: [ ... ],
* propExt: [
* {
* name: 'data'
* val: function () {},
* methodExt: [ ... ],
* propExt: [ ... ]
* },
* ...
* ]
* }
* ]
*
* @type {Array}
* @ignore
*/
var __apiStruct = [];
/**
* `Array.prototype` reference.
*
* @type object
* @ignore
*/
var __arrayProto = Array.prototype;
/**
* Abstraction for `context` parameter of the `Api` constructor to allow it to
* take several different forms for ease of use.
*
* Each of the input parameter types will be converted to a DataTables settings
* object where possible.
*
* @param {string|node|jQuery|object} mixed DataTable identifier. Can be one
* of:
*
* * `string` - jQuery selector. Any DataTables' matching the given selector
* with be found and used.
* * `node` - `TABLE` node which has already been formed into a DataTable.
* * `jQuery` - A jQuery object of `TABLE` nodes.
* * `object` - DataTables settings object
* @return {array|null} Matching DataTables settings objects. `null` or
* `undefined` is returned if no matching DataTable is found.
* @ignore
*/
var _toSettings = function (mixed) {
var idx, jq;
var settings = DataTable.settings;
var tables = $.map(settings, function (el, i) {
return el.nTable;
});
if (mixed.nTable && mixed.oApi) {
// DataTables settings object
return [mixed];
}
else if (mixed.nodeName && mixed.nodeName.toLowerCase() === 'table') {
// Table node
idx = $.inArray(mixed, tables);
return idx !== -1 ? [settings[idx]] : null;
}
else if (typeof mixed === 'string') {
// jQuery selector
jq = $(mixed);
}
else if (mixed instanceof $) {
// jQuery object (also DataTables instance)
jq = mixed;
}
if (jq) {
return jq.map(function (i) {
idx = $.inArray(this, tables);
return idx !== -1 ? settings[idx] : null;
});
}
};
/**
* DataTables API class - used to control and interface with one or more
* DataTables enhanced tables.
*
* The API class is heavily based on jQuery, presenting a chainable interface
* that you can use to interact with tables. Each instance of the API class has
* a "context" - i.e. the tables that it will operate on. This could be a single
* table, all tables on a page or a sub-set thereof.
*
* Additionally the API is designed to allow you to easily work with the data in
* the tables, retrieving and manipulating it as required. This is done by
* presenting the API class as an array like interface. The contents of the
* array depend upon the actions requested by each method (for example
* `rows().nodes()` will return an array of nodes, while `rows().data()` will
* return an array of objects or arrays depending upon your table's
* configuration). The API object has a number of array like methods (`push`,
* `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`,
* `unique` etc) to assist your working with the data held in a table.
*
* Most methods (those which return an Api instance) are chainable, which means
* the return from a method call also has all of the methods available that the
* top level object had. For example, these two calls are equivalent:
*
* // Not chained
* api.row.add( {...} );
* api.draw();
*
* // Chained
* api.row.add( {...} ).draw();
*
* @class DataTable.Api
* @param {array|object|string|jQuery} context DataTable identifier. This is
* used to define which DataTables enhanced tables this API will operate on.
* Can be one of:
*
* * `string` - jQuery selector. Any DataTables' matching the given selector
* with be found and used.
* * `node` - `TABLE` node which has already been formed into a DataTable.
* * `jQuery` - A jQuery object of `TABLE` nodes.
* * `object` - DataTables settings object
* @param {array} [data] Data to initialise the Api instance with.
*
* @example
* // Direct initialisation during DataTables construction
* var api = $('#example').DataTable();
*
* @example
* // Initialisation using a DataTables jQuery object
* var api = $('#example').dataTable().api();
*
* @example
* // Initialisation as a constructor
* var api = new $.fn.DataTable.Api( 'table.dataTable' );
*/
DataTable.Api = _Api = function (context, data) {
if (!this instanceof _Api) {
throw 'DT API must be constructed as a new object';
// or should it do the 'new' for the caller?
// return new _Api.apply( this, arguments );
}
var settings = [];
var ctxSettings = function (o) {
var a = _toSettings(o);
if (a) {
settings.push.apply(settings, a);
}
};
if ($.isArray(context)) {
for (var i = 0, ien = context.length; i < ien; i++) {
ctxSettings(context[i]);
}
}
else {
ctxSettings(context);
}
// Remove duplicates
this.context = _unique(settings);
// Initial data
if (data) {
this.push.apply(this, data);
}
// selector
this.selector = {
rows: null,
cols: null,
opts: null
};
_Api.extend(this, this, __apiStruct);
};
_Api.prototype = /** @lends DataTables.Api */{
/**
* Return a new Api instance, comprised of the data held in the current
* instance, join with the other array(s) and/or value(s).
*
* An alias for `Array.prototype.concat`.
*
* @type method
* @param {*} value1 Arrays and/or values to concatenate.
* @param {*} [...] Additional arrays and/or values to concatenate.
* @returns {DataTables.Api} New API instance, comprising of the combined
* array.
*/
concat: __arrayProto.concat,
context: [], // array of table settings objects
each: function (fn) {
if (__arrayProto.forEach) {
// Where possible, use the built-in forEach
__arrayProto.forEach.call(this, fn, this);
}
else {
// Compatibility for browsers without EMCA-252-5 (JS 1.6)
for (var i = 0, ien = this.length; i < ien; i++) {
// In strict mode the execution scope is the passed value
fn.call(this, this[i], i, this);
}
}
return this;
},
filter: function (fn) {
var a = [];
if (__arrayProto.filter) {
a = __arrayProto.filter.call(this, fn, this);
}
else {
// Compatibility for browsers without EMCA-252-5 (JS 1.6)
for (var i = 0, ien = this.length; i < ien; i++) {
if (fn.call(this, this[i], i, this)) {
a.push(this[i]);
}
}
}
return new _Api(this.context, a);
},
flatten: function () {
var a = [];
return new _Api(this.context, a.concat.apply(a, this));
},
join: __arrayProto.join,
indexOf: __arrayProto.indexOf || function (obj, start) {
for (var i = (start || 0), ien = this.length; i < ien; i++) {
if (this[i] === obj) {
return i;
}
}
return -1;
},
// Internal only at the moment - relax?
iterator: function (flatten, type, fn) {
var
a = [], ret,
i, ien, j, jen,
context = this.context,
rows, items, item,
selector = this.selector;
// Argument shifting
if (typeof flatten === 'string') {
fn = type;
type = flatten;
flatten = false;
}
for (i = 0, ien = context.length; i < ien; i++) {
if (type === 'table') {
ret = fn(context[i], i);
if (ret !== undefined) {
a.push(ret);
}
}
else if (type === 'columns' || type === 'rows') {
// this has same length as context - one entry for each table
ret = fn(context[i], this[i], i);
if (ret !== undefined) {
a.push(ret);
}
}
else if (type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell') {
// columns and rows share the same structure.
// 'this' is an array of column indexes for each context
items = this[i];
if (type === 'column-rows') {
rows = _selector_row_indexes(context[i], selector.opts);
}
for (j = 0, jen = items.length; j < jen; j++) {
item = items[j];
if (type === 'cell') {
ret = fn(context[i], item.row, item.column, i, j);
}
else {
ret = fn(context[i], item, i, j, rows);
}
if (ret !== undefined) {
a.push(ret);
}
}
}
}
if (a.length) {
var api = new _Api(context, flatten ? a.concat.apply([], a) : a);
var apiSelector = api.selector;
apiSelector.rows = selector.rows;
apiSelector.cols = selector.cols;
apiSelector.opts = selector.opts;
return api;
}
return this;
},
lastIndexOf: __arrayProto.lastIndexOf || function (obj, start) {
// Bit cheeky...
return this.indexOf.apply(this.toArray.reverse(), arguments);
},
length: 0,
map: function (fn) {
var a = [];
if (__arrayProto.map) {
a = __arrayProto.map.call(this, fn, this);
}
else {
// Compatibility for browsers without EMCA-252-5 (JS 1.6)
for (var i = 0, ien = this.length; i < ien; i++) {
a.push(fn.call(this, this[i], i));
}
}
return new _Api(this.context, a);
},
pluck: function (prop) {
return this.map(function (el) {
return el[prop];
});
},
pop: __arrayProto.pop,
push: __arrayProto.push,
// Does not return an API instance
reduce: __arrayProto.reduce || function (fn, init) {
var
value,
isSet = false;
if (arguments.length > 1) {
value = init;
isSet = true;
}
for (var i = 0, ien = this.length; i < ien; i++) {
if (!this.hasOwnProperty(i)) {
continue;
}
value = isSet ?
fn(value, this[i], i, this) :
this[i];
isSet = true;
}
return value;
},
reduceRight: __arrayProto.reduceRight || function (fn, init) {
var
value,
isSet = false;
if (arguments.length > 1) {
value = init;
isSet = true;
}
for (var i = this.length - 1; i >= 0; i--) {
if (!this.hasOwnProperty(i)) {
continue;
}
value = isSet ?
fn(value, this[i], i, this) :
this[i];
isSet = true;
}
return value;
},
reverse: __arrayProto.reverse,
// Object with rows, columns and opts
selector: null,
shift: __arrayProto.shift,
sort: __arrayProto.sort, // ? name - order?
splice: __arrayProto.splice,
toArray: function () {
return __arrayProto.slice.call(this);
},
to$: function () {
return $(this);
},
toJQuery: function () {
return $(this);
},
unique: function () {
return new _Api(this.context, _unique(this));
},
unshift: __arrayProto.unshift
};
_Api.extend = function (scope, obj, ext) {
// Only extend API instances and static properties of the API
if (!obj || ( !(obj instanceof _Api) && !obj.__dt_wrapper )) {
return;
}
var
i, ien,
j, jen,
struct, inner,
methodScoping = function (fn, struc) {
return function () {
var ret = fn.apply(scope, arguments);
// Method extension
_Api.extend(ret, ret, struc.methodExt);
return ret;
};
};
for (i = 0, ien = ext.length; i < ien; i++) {
struct = ext[i];
// Value
obj[struct.name] = typeof struct.val === 'function' ?
methodScoping(struct.val, struct) :
struct.val;
obj[struct.name].__dt_wrapper = true;
// Property extension
_Api.extend(scope, obj[struct.name], struct.propExt);
}
};
// @todo - Is there need for an augment function?
// _Api.augment = function ( inst, name )
// {
// // Find src object in the structure from the name
// var parts = name.split('.');
// _Api.extend( inst, obj );
// };
// [
// {
// name: 'data' -- string - Property name
// val: function () {}, -- function - Api method (or undefined if just an object
// methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result
// propExt: [ ... ] -- array - Array of Api object definitions to extend the property
// },
// {
// name: 'row'
// val: {},
// methodExt: [ ... ],
// propExt: [
// {
// name: 'data'
// val: function () {},
// methodExt: [ ... ],
// propExt: [ ... ]
// },
// ...
// ]
// }
// ]
_Api.register = _api_register = function (name, val) {
if ($.isArray(name)) {
for (var j = 0, jen = name.length; j < jen; j++) {
_Api.register(name[j], val);
}
return;
}
var
i, ien,
heir = name.split('.'),
struct = __apiStruct,
key, method;
var find = function (src, name) {
for (var i = 0, ien = src.length; i < ien; i++) {
if (src[i].name === name) {
return src[i];
}
}
return null;
};
for (i = 0, ien = heir.length; i < ien; i++) {
method = heir[i].indexOf('()') !== -1;
key = method ?
heir[i].replace('()', '') :
heir[i];
var src = find(struct, key);
if (!src) {
src = {
name: key,
val: {},
methodExt: [],
propExt: []
};
struct.push(src);
}
if (i === ien - 1) {
src.val = val;
}
else {
struct = method ?
src.methodExt :
src.propExt;
}
}
// Rebuild the API with the new construct
if (_Api.ready) {
DataTable.api.build();
}
};
_Api.registerPlural = _api_registerPlural = function (pluralName, singularName, val) {
_Api.register(pluralName, val);
_Api.register(singularName, function () {
var ret = val.apply(this, arguments);
if (ret === this) {
// Returned item is the API instance that was passed in, return it
return this;
}
else if (ret instanceof _Api) {
// New API instance returned, want the value from the first item
// in the returned array for the singular result.
return ret.length ?
$.isArray(ret[0]) ?
new _Api(ret.context, ret[0]) : // Array results are 'enhanced'
ret[0] :
undefined;
}
// Non-API return - just fire it back
return ret;
});
};
/**
* Selector for HTML tables. Apply the given selector to the give array of
* DataTables settings objects.
*
* @param {string|integer} [selector] jQuery selector string or integer
* @param {array} Array of DataTables settings objects to be filtered
* @return {array}
* @ignore
*/
var __table_selector = function (selector, a) {
// Integer is used to pick out a table by index
if (typeof selector === 'number') {
return [a[selector]];
}
// Perform a jQuery selector on the table nodes
var nodes = $.map(a, function (el, i) {
return el.nTable;
});
return $(nodes)
.filter(selector)
.map(function (i) {
// Need to translate back from the table node to the settings
var idx = $.inArray(this, nodes);
return a[idx];
})
.toArray();
};
/**
* Context selector for the API's context (i.e. the tables the API instance
* refers to.
*
* @name DataTable.Api#tables
* @param {string|integer} [selector] Selector to pick which tables the iterator
* should operate on. If not given, all tables in the current context are
* used. This can be given as a jQuery selector (for example `':gt(0)'`) to
* select multiple tables or as an integer to select a single table.
* @returns {DataTable.Api} Returns a new API instance if a selector is given.
*/
_api_register('tables()', function (selector) {
// A new instance is created if there was a selector specified
return selector ?
new _Api(__table_selector(selector, this.context)) :
this;
});
_api_register('table()', function (selector) {
var tables = this.tables(selector);
var ctx = tables.context;
// Truncate to the first matched table
if (ctx.length) {
ctx.length = 1;
}
return tables;
});
_api_registerPlural('tables().nodes()', 'table().node()', function () {
return this.iterator('table', function (ctx) {
return ctx.nTable;
});
});
_api_registerPlural('tables().body()', 'table().body()', function () {
return this.iterator('table', function (ctx) {
return ctx.nTBody;
});
});
_api_registerPlural('tables().header()', 'table().header()', function () {
return this.iterator('table', function (ctx) {
return ctx.nTHead;
});
});
_api_registerPlural('tables().footer()', 'table().footer()', function () {
return this.iterator('table', function (ctx) {
return ctx.nTFoot;
});
});
/**
* Redraw the tables in the current context.
*
* @param {boolean} [reset=true] Reset (default) or hold the current paging
* position. A full re-sort and re-filter is performed when this method is
* called, which is why the pagination reset is the default action.
* @returns {DataTables.Api} this
*/
_api_register('draw()', function (resetPaging) {
return this.iterator('table', function (settings) {
_fnReDraw(settings, resetPaging === false);
});
});
/**
* Get the current page index.
*
* @return {integer} Current page index (zero based)
*/
/**
* Set the current page.
*
* Note that if you attempt to show a page which does not exist, DataTables will
* not throw an error, but rather reset the paging.
*
* @param {integer|string} action The paging action to take. This can be one of:
* * `integer` - The page index to jump to
* * `string` - An action to take:
* * `first` - Jump to first page.
* * `next` - Jump to the next page
* * `previous` - Jump to previous page
* * `last` - Jump to the last page.
* @returns {DataTables.Api} this
*/
_api_register('page()', function (action) {
if (action === undefined) {
return this.page.info().page; // not an expensive call
}
// else, have an action to take on all tables
return this.iterator('table', function (settings) {
_fnPageChange(settings, action);
});
});
/**
* Paging information for the first table in the current context.
*
* If you require paging information for another table, use the `table()` method
* with a suitable selector.
*
* @return {object} Object with the following properties set:
* * `page` - Current page index (zero based - i.e. the first page is `0`)
* * `pages` - Total number of pages
* * `start` - Display index for the first record shown on the current page
* * `end` - Display index for the last record shown on the current page
* * `length` - Display length (number of records). Note that generally `start
* + length = end`, but this is not always true, for example if there are
* only 2 records to show on the final page, with a length of 10.
* * `recordsTotal` - Full data set length
* * `recordsDisplay` - Data set length once the current filtering criterion
* are applied.
*/
_api_register('page.info()', function (action) {
if (this.context.length === 0) {
return undefined;
}
var
settings = this.context[0],
start = settings._iDisplayStart,
len = settings._iDisplayLength,
visRecords = settings.fnRecordsDisplay(),
all = len === -1;
return {
"page": all ? 0 : Math.floor(start / len),
"pages": all ? 1 : Math.ceil(visRecords / len),
"start": start,
"end": settings.fnDisplayEnd(),
"length": len,
"recordsTotal": settings.fnRecordsTotal(),
"recordsDisplay": visRecords
};
});
/**
* Get the current page length.
*
* @return {integer} Current page length. Note `-1` indicates that all records
* are to be shown.
*/
/**
* Set the current page length.
*
* @param {integer} Page length to set. Use `-1` to show all records.
* @returns {DataTables.Api} this
*/
_api_register('page.len()', function (len) {
// Note that we can't call this function 'length()' because `length`
// is a Javascript property of functions which defines how many arguments
// the function expects.
if (len === undefined) {
return this.context.length !== 0 ?
this.context[0]._iDisplayLength :
undefined;
}
// else, set the page length
return this.iterator('table', function (settings) {
_fnLengthChange(settings, len);
});
});
var __reload = function (settings, holdPosition, callback) {
if (_fnDataSource(settings) == 'ssp') {
_fnReDraw(settings, holdPosition);
}
else {
// Trigger xhr
_fnBuildAjax(settings, [], function (json) {
// xxx can this be reduced?
_fnClearTable(settings);
var data = _fnAjaxDataSrc(settings, json);
for (var i = 0, ien = data.length; i < ien; i++) {
_fnAddData(settings, data[i]);
}
_fnReDraw(settings, holdPosition);
if (callback) {
callback(json);
}
});
}
};
/**
* Get the JSON response from the last Ajax request that DataTables made to the
* server. Note that this returns the JSON from the first table in the current
* context.
*
* @return {object} JSON received from the server.
*/
_api_register('ajax.json()', function () {
var ctx = this.context;
if (ctx.length > 0) {
return ctx[0].json;
}
// else return undefined;
});
/**
* Reload tables from the Ajax data source. Note that this function will
* automatically re-draw the table when the remote data has been loaded.
*
* @param {boolean} [reset=true] Reset (default) or hold the current paging
* position. A full re-sort and re-filter is performed when this method is
* called, which is why the pagination reset is the default action.
* @returns {DataTables.Api} this
*/
_api_register('ajax.reload()', function (callback, resetPaging) {
return this.iterator('table', function (settings) {
__reload(settings, resetPaging === false, callback);
});
});
/**
* Get the current Ajax URL. Note that this returns the URL from the first
* table in the current context.
*
* @return {string} Current Ajax source URL
*/
/**
* Set the Ajax URL. Note that this will set the URL for all tables in the
* current context.
*
* @param {string} url URL to set.
* @returns {DataTables.Api} this
*/
_api_register('ajax.url()', function (url) {
var ctx = this.context;
if (url === undefined) {
// get
if (ctx.length === 0) {
return undefined;
}
ctx = ctx[0];
return ctx.ajax ?
$.isPlainObject(ctx.ajax) ?
ctx.ajax.url :
ctx.ajax :
ctx.sAjaxSource;
}
// set
return this.iterator('table', function (settings) {
if ($.isPlainObject(settings.ajax)) {
settings.ajax.url = url;
}
else {
settings.ajax = url;
}
// No need to consider sAjaxSource here since DataTables gives priority
// to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any
// value of `sAjaxSource` redundant.
});
});
/**
* Load data from the newly set Ajax URL. Note that this method is only
* available when `ajax.url()` is used to set a URL. Additionally, this method
* has the same effect as calling `ajax.reload()` but is provided for
* convenience when setting a new URL. Like `ajax.reload()` it will
* automatically redraw the table once the remote data has been loaded.
*
* @returns {DataTables.Api} this
*/
_api_register('ajax.url().load()', function (callback, resetPaging) {
// Same as a reload, but makes sense to present it for easy access after a
// url change
return this.iterator('table', function (ctx) {
__reload(ctx, resetPaging === false, callback);
});
});
var _selector_run = function (selector, select) {
var
out = [], res,
a, i, ien, j, jen;
if (!$.isArray(selector)) {
selector = [selector];
}
for (i = 0, ien = selector.length; i < ien; i++) {
a = selector[i] && selector[i].split ?
selector[i].split(',') :
[selector[i]];
for (j = 0, jen = a.length; j < jen; j++) {
res = select(typeof a[j] === 'string' ? $.trim(a[j]) : a[j]);
if (res && res.length) {
out.push.apply(out, res);
}
}
}
return out;
};
var _selector_opts = function (opts) {
if (!opts) {
opts = {};
}
// Backwards compatibility for 1.9- which used the terminology filter rather
// than search
if (opts.filter && !opts.search) {
opts.search = opts.filter;
}
return {
search: opts.search || 'none',
order: opts.order || 'current',
page: opts.page || 'all'
};
};
var _selector_first = function (inst) {
// Reduce the API instance to the first item found
for (var i = 0, ien = inst.length; i < ien; i++) {
if (inst[i].length > 0) {
// Assign the first element to the first item in the instance
// and truncate the instance and context
inst[0] = inst[i];
inst.length = 1;
inst.context = [inst.context[i]];
return inst;
}
}
// Not found - return an empty instance
inst.length = 0;
return inst;
};
var _selector_row_indexes = function (settings, opts) {
var
i, ien, tmp, a = [],
displayFiltered = settings.aiDisplay,
displayMaster = settings.aiDisplayMaster;
var
search = opts.search, // none, applied, removed
order = opts.order, // applied, current, index (original - compatibility with 1.9)
page = opts.page; // all, current
// Current page implies that order=current and fitler=applied, since it is
// fairly senseless otherwise, regardless of what order and search actually
// are
if (page == 'current') {
for (i = settings._iDisplayStart, ien = settings.fnDisplayEnd(); i < ien; i++) {
a.push(displayFiltered[i]);
}
}
else if (order == 'current' || order == 'applied') {
a = search == 'none' ?
displayMaster.slice() : // no search
search == 'applied' ?
displayFiltered.slice() : // applied search
$.map(displayMaster, function (el, i) { // removed search
return $.inArray(el, displayFiltered) === -1 ? el : null;
});
}
else if (order == 'index' || order == 'original') {
for (i = 0, ien = settings.aoData.length; i < ien; i++) {
if (search == 'none') {
a.push(i);
}
else { // applied | removed
tmp = $.inArray(i, displayFiltered);
if ((tmp === -1 && search == 'removed') ||
(tmp === 1 && search == 'applied')) {
a.push(i);
}
}
}
}
return a;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Rows
*
* {} - no selector - use all available rows
* {integer} - row aoData index
* {node} - TR node
* {string} - jQuery selector to apply to the TR elements
* {array} - jQuery array of nodes, or simply an array of TR nodes
*
*/
var __row_selector = function (settings, selector, opts) {
return _selector_run(selector, function (sel) {
var selInt = _intVal(sel);
// Short cut - selector is a number and no options provided (default is
// all records, so no need to check if the index is in there, since it
// must be - dev error if the index doesn't exist).
if (selInt !== null && !opts) {
return [selInt];
}
var rows = _selector_row_indexes(settings, opts);
if (selInt !== null && $.inArray(selInt, rows) !== -1) {
// Selector - integer
return [selInt];
}
else if (!sel) {
// Selector - none
return rows;
}
// Get nodes in the order from the `rows` array (can't use `pluck`) @todo - use pluck_order
var nodes = [];
for (var i = 0, ien = rows.length; i < ien; i++) {
nodes.push(settings.aoData[rows[i]].nTr);
}
if (sel.nodeName) {
// Selector - node
if ($.inArray(sel, nodes) !== -1) {
return [sel._DT_RowIndex];// sel is a TR node that is in the table
// and DataTables adds a prop for fast lookup
}
}
// Selector - jQuery selector string, array of nodes or jQuery object/
// As jQuery's .filter() allows jQuery objects to be passed in filter,
// it also allows arrays, so this will cope with all three options
return $(nodes)
.filter(sel)
.map(function () {
return this._DT_RowIndex;
})
.toArray();
});
};
/**
*
*/
_api_register('rows()', function (selector, opts) {
// argument shifting
if (selector === undefined) {
selector = '';
}
else if ($.isPlainObject(selector)) {
opts = selector;
selector = '';
}
opts = _selector_opts(opts);
var inst = this.iterator('table', function (settings) {
return __row_selector(settings, selector, opts);
});
// Want argument shifting here and in __row_selector?
inst.selector.rows = selector;
inst.selector.opts = opts;
return inst;
});
_api_registerPlural('rows().nodes()', 'row().node()', function () {
return this.iterator('row', function (settings, row) {
// use pluck order on an array rather - rows gives an array, row gives it individually
return settings.aoData[row].nTr || undefined;
});
});
_api_register('rows().data()', function () {
return this.iterator(true, 'rows', function (settings, rows) {
return _pluck_order(settings.aoData, rows, '_aData');
});
});
_api_registerPlural('rows().cache()', 'row().cache()', function (type) {
return this.iterator('row', function (settings, row) {
var r = settings.aoData[row];
return type === 'search' ? r._aFilterData : r._aSortData;
});
});
_api_registerPlural('rows().invalidate()', 'row().invalidate()', function (src) {
return this.iterator('row', function (settings, row) {
_fnInvalidateRow(settings, row, src);
});
});
_api_registerPlural('rows().indexes()', 'row().index()', function () {
return this.iterator('row', function (settings, row) {
return row;
});
});
_api_registerPlural('rows().remove()', 'row().remove()', function () {
var that = this;
return this.iterator('row', function (settings, row, thatIdx) {
var data = settings.aoData;
data.splice(row, 1);
// Update the _DT_RowIndex parameter on all rows in the table
for (var i = 0, ien = data.length; i < ien; i++) {
if (data[i].nTr !== null) {
data[i].nTr._DT_RowIndex = i;
}
}
// Remove the target row from the search array
var displayIndex = $.inArray(row, settings.aiDisplay);
// Delete from the display arrays
_fnDeleteIndex(settings.aiDisplayMaster, row);
_fnDeleteIndex(settings.aiDisplay, row);
_fnDeleteIndex(that[thatIdx], row, false); // maintain local indexes
// Check for an 'overflow' they case for displaying the table
_fnLengthOverflow(settings);
});
});
_api_register('rows.add()', function (rows) {
var newRows = this.iterator('table', function (settings) {
var row, i, ien;
var out = [];
for (i = 0, ien = rows.length; i < ien; i++) {
row = rows[i];
if (row.nodeName && row.nodeName.toUpperCase() === 'TR') {
out.push(_fnAddTr(settings, row)[0]);
}
else {
out.push(_fnAddData(settings, row));
}
}
return out;
});
// Return an Api.rows() extended instance, so rows().nodes() etc can be used
var modRows = this.rows(-1);
modRows.pop();
modRows.push.apply(modRows, newRows);
return modRows;
});
/**
*
*/
_api_register('row()', function (selector, opts) {
return _selector_first(this.rows(selector, opts));
});
_api_register('row().data()', function (data) {
var ctx = this.context;
if (data === undefined) {
// Get
return ctx.length && this.length ?
ctx[0].aoData[this[0]]._aData :
undefined;
}
// Set
ctx[0].aoData[this[0]]._aData = data;
// Automatically invalidate
_fnInvalidateRow(ctx[0], this[0], 'data');
return this;
});
_api_register('row.add()', function (row) {
// Allow a jQuery object to be passed in - only a single row is added from
// it though - the first element in the set
if (row instanceof $ && row.length) {
row = row[0];
}
var rows = this.iterator('table', function (settings) {
if (row.nodeName && row.nodeName.toUpperCase() === 'TR') {
return _fnAddTr(settings, row)[0];
}
return _fnAddData(settings, row);
});
// Return an Api.rows() extended instance, with the newly added row selected
return this.row(rows[0]);
});
var __details_add = function (ctx, row, data, klass) {
// Convert to array of TR elements
var rows = [];
var addRow = function (r, k) {
if (!r.nodeName || r.nodeName.toUpperCase() !== 'tr') {
r = $('<tr><td></td></tr>').find('td').html(r).parent();
}
$('td', r).addClass(k)[0].colSpan = _fnVisbleColumns(ctx);
rows.push(r[0]);
};
if ($.isArray(data) || data instanceof $) {
for (var i = 0, ien = data.length; i < ien; i++) {
addRow(data[i], klass);
}
}
else {
addRow(data, klass);
}
if (row._details) {
row._details.remove();
}
row._details = $(rows);
// If the children were already shown, that state should be retained
if (row._detailsShow) {
row._details.insertAfter(row.nTr);
}
};
var __details_display = function (show) {
var ctx = this.context;
if (ctx.length && this.length) {
var row = ctx[0].aoData[this[0]];
if (row._details) {
row._detailsShow = show;
if (show) {
row._details.insertAfter(row.nTr);
}
else {
row._details.remove();
}
__details_events(ctx[0]);
}
}
return this;
};
var __details_events = function (settings) {
var table = $(settings.nTable);
table.off('draw.DT_details');
table.off('column-visibility.DT_details');
if (_pluck(settings.aoData, '_details').length > 0) {
// On each draw, insert the required elements into the document
table.on('draw.DT_details', function () {
table.find('tbody tr').each(function () {
// Look up the row index for each row and append open row
var rowIdx = _fnNodeToDataIndex(settings, this);
var row = settings.aoData[rowIdx];
if (row._detailsShow) {
row._details.insertAfter(this);
}
});
});
// Column visibility change - update the colspan
table.on('column-visibility.DT_details', function (e, settings, idx, vis) {
// Update the colspan for the details rows (note, only if it already has
// a colspan)
var row, visible = _fnVisbleColumns(settings);
for (var i = 0, ien = settings.aoData.length; i < ien; i++) {
row = settings.aoData[i];
if (row._details) {
row._details.children('td[colspan]').attr('colspan', visible);
}
}
});
}
};
// data can be:
// tr
// string
// jQuery or array of any of the above
_api_register('row().child()', function (data, klass) {
var ctx = this.context;
if (data === undefined) {
// get
return ctx.length && this.length ?
ctx[0].aoData[this[0]]._details :
undefined;
}
else if (ctx.length && this.length) {
// set
__details_add(ctx[0], ctx[0].aoData[this[0]], data, klass);
}
return this;
});
_api_register([
'row().child.show()',
'row().child().show()'
], function () {
__details_display.call(this, true);
});
_api_register([
'row().child.hide()',
'row().child().hide()'
], function () {
__details_display.call(this, false);
});
_api_register('row().child.isShown()', function () {
var ctx = this.context;
if (ctx.length && this.length) {
// _detailsShown as false or undefined will fall through to return false
return ctx[0].aoData[this[0]]._detailsShow || false;
}
return false;
});
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Columns
*
* {integer} - column index (>=0 count from left, <0 count from right)
* "{integer}:visIdx" - visible column index (i.e. translate to column index) (>=0 count from left, <0 count from right)
* "{integer}:visible" - alias for {integer}:visIdx (>=0 count from left, <0 count from right)
* "{string}:name" - column name
* "{string}" - jQuery selector on column header nodes
*
*/
// can be an array of these items, comma separated list, or an array of comma
// separated lists
var __re_column_selector = /^(.*):(name|visIdx|visible)$/;
var __column_selector = function (settings, selector, opts) {
var
columns = settings.aoColumns,
names = _pluck(columns, 'sName'),
nodes = _pluck(columns, 'nTh');
return _selector_run(selector, function (s) {
var selInt = _intVal(s);
if (s === '') {
// All columns
return _range(settings.aoColumns.length);
}
else if (selInt !== null) {
// Integer selector
return [selInt >= 0 ?
selInt : // Count from left
columns.length + selInt // Count from right (+ because its a negative value)
];
}
else {
var match = s.match(__re_column_selector);
if (match) {
switch (match[2]) {
case 'visIdx':
case 'visible':
var idx = parseInt(match[1], 10);
// Visible index given, convert to column index
if (idx < 0) {
// Counting from the right
var visColumns = $.map(columns, function (col, i) {
return col.bVisible ? i : null;
});
return [visColumns[visColumns.length + idx]];
}
// Counting from the left
return [_fnVisibleToColumnIndex(settings, idx)];
case 'name':
// match by name. `names` is column index complete and in order
return $.map(names, function (name, i) {
return name === match[1] ? i : null;
});
}
}
else {
// jQuery selector on the TH elements for the columns
return $(nodes)
.filter(s)
.map(function () {
return $.inArray(this, nodes); // `nodes` is column index complete and in order
})
.toArray();
}
}
});
};
var __setColumnVis = function (settings, column, vis) {
var
cols = settings.aoColumns,
col = cols[column],
data = settings.aoData,
row, cells, i, ien, tr;
// Get
if (vis === undefined) {
return col.bVisible;
}
// Set
// No change
if (col.bVisible === vis) {
return;
}
if (vis) {
// Insert column
// Need to decide if we should use appendChild or insertBefore
var insertBefore = $.inArray(true, _pluck(cols, 'bVisible'), column + 1);
for (i = 0, ien = data.length; i < ien; i++) {
tr = data[i].nTr;
cells = data[i].anCells;
if (tr) {
// insertBefore can act like appendChild if 2nd arg is null
tr.insertBefore(cells[column], cells[insertBefore] || null);
}
}
}
else {
// Remove column
$(_pluck(settings.aoData, 'anCells', column)).remove();
col.bVisible = false;
_fnDrawHead(settings, settings.aoHeader);
_fnDrawHead(settings, settings.aoFooter);
_fnSaveState(settings);
}
// Common actions
col.bVisible = vis;
_fnDrawHead(settings, settings.aoHeader);
_fnDrawHead(settings, settings.aoFooter);
// Automatically adjust column sizing
_fnAdjustColumnSizing(settings);
// Realign columns for scrolling
if (settings.oScroll.sX || settings.oScroll.sY) {
_fnScrollDraw(settings);
}
_fnCallbackFire(settings, null, 'column-visibility', [settings, column, vis]);
_fnSaveState(settings);
};
/**
*
*/
_api_register('columns()', function (selector, opts) {
// argument shifting
if (selector === undefined) {
selector = '';
}
else if ($.isPlainObject(selector)) {
opts = selector;
selector = '';
}
opts = _selector_opts(opts);
var inst = this.iterator('table', function (settings) {
return __column_selector(settings, selector, opts);
});
// Want argument shifting here and in _row_selector?
inst.selector.cols = selector;
inst.selector.opts = opts;
return inst;
});
/**
*
*/
_api_registerPlural('columns().header()', 'column().header()', function (selector, opts) {
return this.iterator('column', function (settings, column) {
return settings.aoColumns[column].nTh;
});
});
/**
*
*/
_api_registerPlural('columns().footer()', 'column().footer()', function (selector, opts) {
return this.iterator('column', function (settings, column) {
return settings.aoColumns[column].nTf;
});
});
/**
*
*/
_api_registerPlural('columns().data()', 'column().data()', function () {
return this.iterator('column-rows', function (settings, column, i, j, rows) {
var a = [];
for (var row = 0, ien = rows.length; row < ien; row++) {
a.push(_fnGetCellData(settings, rows[row], column, ''));
}
return a;
});
});
_api_registerPlural('columns().cache()', 'column().cache()', function (type) {
return this.iterator('column-rows', function (settings, column, i, j, rows) {
return _pluck_order(settings.aoData, rows,
type === 'search' ? '_aFilterData' : '_aSortData', column
);
});
});
_api_registerPlural('columns().nodes()', 'column().nodes()', function () {
return this.iterator('column-rows', function (settings, column, i, j, rows) {
return _pluck_order(settings.aoData, rows, 'anCells', column);
});
});
_api_registerPlural('columns().visible()', 'column().visible()', function (vis) {
return this.iterator('column', function (settings, column) {
return __setColumnVis(settings, column, vis);
});
});
_api_registerPlural('columns().indexes()', 'column().index()', function (type) {
return this.iterator('column', function (settings, column) {
return type === 'visible' ?
_fnColumnIndexToVisible(settings, column) :
column;
});
});
// _api_register( 'columns().show()', function () {
// var selector = this.selector;
// return this.columns( selector.cols, selector.opts ).visible( true );
// } );
// _api_register( 'columns().hide()', function () {
// var selector = this.selector;
// return this.columns( selector.cols, selector.opts ).visible( false );
// } );
_api_register('columns.adjust()', function () {
return this.iterator('table', function (settings) {
_fnAdjustColumnSizing(settings);
});
});
// Convert from one column index type, to another type
_api_register('column.index()', function (type, idx) {
if (this.context.length !== 0) {
var ctx = this.context[0];
if (type === 'fromVisible' || type === 'toData') {
return _fnColumnIndexToVisible(ctx, idx);
}
else if (type === 'fromData' || type === 'toVisible') {
return _fnVisibleToColumnIndex(ctx, idx);
}
}
});
_api_register('column()', function (selector, opts) {
return _selector_first(this.columns(selector, opts));
});
var __cell_selector = function (settings, selector, opts) {
var data = settings.aoData;
var rows = _selector_row_indexes(settings, opts);
var cells = _pluck_order(data, rows, 'anCells');
var allCells = $([].concat.apply([], cells));
var row;
var columns = settings.aoColumns.length;
var a, i, ien, j;
return _selector_run(selector, function (s) {
if (!s) {
// All cells
a = [];
for (i = 0, ien = rows.length; i < ien; i++) {
row = rows[i];
for (j = 0; j < columns; j++) {
a.push({
row: row,
column: j
});
}
}
return a;
}
// jQuery filtered cells
return allCells.filter(s).map(function (i, el) {
row = el.parentNode._DT_RowIndex;
return {
row: row,
column: $.inArray(el, data[row].anCells)
};
});
});
};
_api_register('cells()', function (rowSelector, columnSelector, opts) {
// Argument shifting
if ($.isPlainObject(rowSelector)) {
opts = rowSelector;
rowSelector = null;
}
if ($.isPlainObject(columnSelector)) {
opts = columnSelector;
columnSelector = null;
}
// Cell selector
if (columnSelector === null || columnSelector === undefined) {
return this.iterator('table', function (settings) {
return __cell_selector(settings, rowSelector, _selector_opts(opts));
});
}
// Row + column selector
var columns = this.columns(columnSelector, opts);
var rows = this.rows(rowSelector, opts);
var a, i, ien, j, jen;
var cells = this.iterator('table', function (settings, idx) {
a = [];
for (i = 0, ien = rows[idx].length; i < ien; i++) {
for (j = 0, jen = columns[idx].length; j < jen; j++) {
a.push({
row: rows[idx][i],
column: columns[idx][j]
});
}
}
return a;
});
$.extend(cells.selector, {
cols: columnSelector,
rows: rowSelector,
opts: opts
});
return cells;
});
_api_registerPlural('cells().nodes()', 'cell().node()', function () {
return this.iterator('cell', function (settings, row, column) {
return settings.aoData[row].anCells[column];
});
});
_api_register('cells().data()', function () {
return this.iterator('cell', function (settings, row, column) {
return _fnGetCellData(settings, row, column);
});
});
_api_registerPlural('cells().cache()', 'cell().cache()', function (type) {
type = type === 'search' ? '_aFilterData' : '_aSortData';
return this.iterator('cell', function (settings, row, column) {
return settings.aoData[row][type][column];
});
});
_api_registerPlural('cells().indexes()', 'cell().index()', function () {
return this.iterator('cell', function (settings, row, column) {
return {
row: row,
column: column,
columnVisible: _fnColumnIndexToVisible(settings, column)
};
});
});
_api_register([
'cells().invalidate()',
'cell().invalidate()'
], function (src) {
var selector = this.selector;
// Use the rows method of the instance to perform the invalidation, rather
// than doing it here. This avoids needing to handle duplicate rows from
// the cells.
this.rows(selector.rows, selector.opts).invalidate(src);
return this;
});
_api_register('cell()', function (rowSelector, columnSelector, opts) {
return _selector_first(this.cells(rowSelector, columnSelector, opts));
});
_api_register('cell().data()', function (data) {
var ctx = this.context;
var cell = this[0];
if (data === undefined) {
// Get
return ctx.length && cell.length ?
_fnGetCellData(ctx[0], cell[0].row, cell[0].column) :
undefined;
}
// Set
_fnSetCellData(ctx[0], cell[0].row, cell[0].column, data);
_fnInvalidateRow(ctx[0], cell[0].row, 'data', cell[0].column);
return this;
});
/**
* Get current ordering (sorting) that has been applied to the table.
*
* @returns {array} 2D array containing the sorting information for the first
* table in the current context. Each element in the parent array represents
* a column being sorted upon (i.e. multi-sorting with two columns would have
* 2 inner arrays). The inner arrays may have 2 or 3 elements. The first is
* the column index that the sorting condition applies to, the second is the
* direction of the sort (`desc` or `asc`) and, optionally, the third is the
* index of the sorting order from the `column.sorting` initialisation array.
*/
/**
* Set the ordering for the table.
*
* @param {integer} order Column index to sort upon.
* @param {string} direction Direction of the sort to be applied (`asc` or `desc`)
* @returns {DataTables.Api} this
*/
/**
* Set the ordering for the table.
*
* @param {array} order 1D array of sorting information to be applied.
* @param {array} [...] Optional additional sorting conditions
* @returns {DataTables.Api} this
*/
/**
* Set the ordering for the table.
*
* @param {array} order 2D array of sorting information to be applied.
* @returns {DataTables.Api} this
*/
_api_register('order()', function (order, dir) {
var ctx = this.context;
if (order === undefined) {
// get
return ctx.length !== 0 ?
ctx[0].aaSorting :
undefined;
}
// set
if (typeof order === 'number') {
// Simple column / direction passed in
order = [[order, dir]];
}
else if (!$.isArray(order[0])) {
// Arguments passed in (list of 1D arrays)
order = Array.prototype.slice.call(arguments);
}
// otherwise a 2D array was passed in
return this.iterator('table', function (settings) {
settings.aaSorting = order.slice();
});
});
/**
* Attach a sort listener to an element for a given column
*
* @param {node|jQuery|string} node Identifier for the element(s) to attach the
* listener to. This can take the form of a single DOM node, a jQuery
* collection of nodes or a jQuery selector which will identify the node(s).
* @param {integer} column the column that a click on this node will sort on
* @param {function} [callback] callback function when sort is run
* @returns {DataTables.Api} this
*/
_api_register('order.listener()', function (node, column, callback) {
return this.iterator('table', function (settings) {
_fnSortAttachListener(settings, node, column, callback);
});
});
// Order by the selected column(s)
_api_register([
'columns().order()',
'column().order()'
], function (dir) {
var that = this;
return this.iterator('table', function (settings, i) {
var sort = [];
$.each(that[i], function (j, col) {
sort.push([col, dir]);
});
settings.aaSorting = sort;
});
});
_api_register('search()', function (input, regex, smart, caseInsen) {
var ctx = this.context;
if (input === undefined) {
// get
return ctx.length !== 0 ?
ctx[0].oPreviousSearch.sSearch :
undefined;
}
// set
return this.iterator('table', function (settings) {
if (!settings.oFeatures.bFilter) {
return;
}
_fnFilterComplete(settings, $.extend({}, settings.oPreviousSearch, {
"sSearch": input + "",
"bRegex": regex === null ? false : regex,
"bSmart": smart === null ? true : smart,
"bCaseInsensitive": caseInsen === null ? true : caseInsen
}), 1);
});
});
_api_register([
'columns().search()',
'column().search()'
], function (input, regex, smart, caseInsen) {
return this.iterator('column', function (settings, column) {
var preSearch = settings.aoPreSearchCols;
if (input === undefined) {
// get
return preSearch[column].sSearch;
}
// set
if (!settings.oFeatures.bFilter) {
return;
}
$.extend(preSearch[column], {
"sSearch": input + "",
"bRegex": regex === null ? false : regex,
"bSmart": smart === null ? true : smart,
"bCaseInsensitive": caseInsen === null ? true : caseInsen
});
_fnFilterComplete(settings, settings.oPreviousSearch, 1);
});
});
/**
* Provide a common method for plug-ins to check the version of DataTables being
* used, in order to ensure compatibility.
*
* @param {string} version Version string to check for, in the format "X.Y.Z".
* Note that the formats "X" and "X.Y" are also acceptable.
* @returns {boolean} true if this version of DataTables is greater or equal to
* the required version, or false if this version of DataTales is not
* suitable
* @static
* @dtopt API-Static
*
* @example
* alert( $.fn.dataTable.versionCheck( '1.9.0' ) );
*/
DataTable.versionCheck = DataTable.fnVersionCheck = function (version) {
var aThis = DataTable.version.split('.');
var aThat = version.split('.');
var iThis, iThat;
for (var i = 0, iLen = aThat.length; i < iLen; i++) {
iThis = parseInt(aThis[i], 10) || 0;
iThat = parseInt(aThat[i], 10) || 0;
// Parts are the same, keep comparing
if (iThis === iThat) {
continue;
}
// Parts are different, return immediately
return iThis > iThat;
}
return true;
};
/**
* Check if a `<table>` node is a DataTable table already or not.
*
* @param {node|jquery|string} table Table node, jQuery object or jQuery
* selector for the table to test. Note that if more than more than one
* table is passed on, only the first will be checked
* @returns {boolean} true the table given is a DataTable, or false otherwise
* @static
* @dtopt API-Static
*
* @example
* if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
* $('#example').dataTable();
* }
*/
DataTable.isDataTable = DataTable.fnIsDataTable = function (table) {
var t = $(table).get(0);
var is = false;
$.each(DataTable.settings, function (i, o) {
if (o.nTable === t || o.nScrollHead === t || o.nScrollFoot === t) {
is = true;
}
});
return is;
};
/**
* Get all DataTable tables that have been initialised - optionally you can
* select to get only currently visible tables.
*
* @param {boolean} [visible=false] Flag to indicate if you want all (default)
* or visible tables only.
* @returns {array} Array of `table` nodes (not DataTable instances) which are
* DataTables
* @static
* @dtopt API-Static
*
* @example
* $.each( $.fn.dataTable.tables(true), function () {
* $(table).DataTable().columns.adjust();
* } );
*/
DataTable.tables = DataTable.fnTables = function (visible) {
return jQuery.map(DataTable.settings, function (o) {
if (!visible || (visible && $(o.nTable).is(':visible'))) {
return o.nTable;
}
});
};
/**
*
*/
_api_register('$()', function (selector, opts) {
var
rows = this.rows(opts).nodes(), // Get all rows
jqRows = $(rows);
return $([].concat(
jqRows.filter(selector).toArray(),
jqRows.find(selector).toArray()
));
});
// jQuery functions to operate on the tables
$.each(['on', 'one', 'off'], function (i, key) {
_api_register(key + '()', function (/* event, handler */) {
var args = Array.prototype.slice.call(arguments);
// Add the `dt` namespace automatically if it isn't already present
if (args[0].indexOf('.dt') === -1) {
args[0] += '.dt';
}
var inst = $(this.tables().nodes());
inst[key].apply(inst, args);
return this;
});
});
_api_register('clear()', function () {
return this.iterator('table', function (settings) {
_fnClearTable(settings);
});
});
_api_register('settings()', function () {
return new _Api(this.context, this.context);
});
_api_register('data()', function () {
return this.iterator('table', function (settings) {
return _pluck(settings.aoData, '_aData');
}).flatten();
});
_api_register('destroy()', function (remove) {
remove = remove || false;
return this.iterator('table', function (settings) {
var orig = settings.nTableWrapper.parentNode;
var classes = settings.oClasses;
var table = settings.nTable;
var tbody = settings.nTBody;
var thead = settings.nTHead;
var tfoot = settings.nTFoot;
var jqTable = $(table);
var jqTbody = $(tbody);
var jqWrapper = $(settings.nTableWrapper);
var rows = $.map(settings.aoData, function (r) {
return r.nTr;
});
var i, ien;
// Flag to note that the table is currently being destroyed - no action
// should be taken
settings.bDestroying = true;
// Fire off the destroy callbacks for plug-ins etc
_fnCallbackFire(settings, "aoDestroyCallback", "destroy", [settings]);
// If not being removed from the document, make all columns visible
if (!remove) {
new _Api(settings).columns().visible(true);
}
// Blitz all DT events
jqWrapper.unbind('.DT').find(':not(tbody *)').unbind('.DT');
$(window).unbind('.DT-' + settings.sInstance);
// When scrolling we had to break the table up - restore it
if (table != thead.parentNode) {
jqTable.children('thead').remove();
jqTable.append(thead);
}
if (tfoot && table != tfoot.parentNode) {
jqTable.children('tfoot').remove();
jqTable.append(tfoot);
}
// Remove the DataTables generated nodes, events and classes
jqTable.remove();
jqWrapper.remove();
settings.aaSorting = [];
settings.aaSortingFixed = [];
_fnSortingClasses(settings);
$(rows).removeClass(settings.asStripeClasses.join(' '));
$('th, td', thead).removeClass(classes.sSortable + ' ' +
classes.sSortableAsc + ' ' + classes.sSortableDesc + ' ' + classes.sSortableNone
);
if (settings.bJUI) {
$('th span.' + classes.sSortIcon + ', td span.' + classes.sSortIcon, thead).remove();
$('th, td', thead).each(function () {
var wrapper = $('div.' + classes.sSortJUIWrapper, this);
$(this).append(wrapper.contents());
wrapper.remove();
});
}
if (!remove) {
// insertBefore acts like appendChild if !arg[1]
orig.insertBefore(table, settings.nTableReinsertBefore);
}
// Add the TR elements back into the table in their original order
jqTbody.children().detach();
jqTbody.append(rows);
// Restore the width of the original table - was read from the style property,
// so we can restore directly to that
jqTable
.css('width', settings.sDestroyWidth)
.removeClass(classes.sTable);
// If the were originally stripe classes - then we add them back here.
// Note this is not fool proof (for example if not all rows had stripe
// classes - but it's a good effort without getting carried away
ien = settings.asDestroyStripes.length;
if (ien) {
jqTbody.children().each(function (i) {
$(this).addClass(settings.asDestroyStripes[i % ien]);
});
}
/* Remove the settings object from the settings array */
var idx = $.inArray(settings, DataTable.settings);
if (idx !== -1) {
DataTable.settings.splice(idx, 1);
}
});
});
/**
* Version string for plug-ins to check compatibility. Allowed format is
* `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used
* only for non-release builds. See http://semver.org/ for more information.
* @member
* @type string
* @default Version number
*/
DataTable.version = "1.10.0-dev";
/**
* Private data store, containing all of the settings objects that are
* created for the tables on a given page.
*
* Note that the `DataTable.settings` object is aliased to
* `jQuery.fn.dataTableExt` through which it may be accessed and
* manipulated, or `jQuery.fn.dataTable.settings`.
* @member
* @type array
* @default []
* @private
*/
DataTable.settings = [];
/**
* Object models container, for the various models that DataTables has
* available to it. These models define the objects that are used to hold
* the active state and configuration of the table.
* @namespace
*/
DataTable.models = {};
/**
* Template object for the way in which DataTables holds information about
* search information for the global filter and individual column filters.
* @namespace
*/
DataTable.models.oSearch = {
/**
* Flag to indicate if the filtering should be case insensitive or not
* @type boolean
* @default true
*/
"bCaseInsensitive": true,
/**
* Applied search term
* @type string
* @default <i>Empty string</i>
*/
"sSearch": "",
/**
* Flag to indicate if the search term should be interpreted as a
* regular expression (true) or not (false) and therefore and special
* regex characters escaped.
* @type boolean
* @default false
*/
"bRegex": false,
/**
* Flag to indicate if DataTables is to use its smart filtering or not.
* @type boolean
* @default true
*/
"bSmart": true
};
/**
* Template object for the way in which DataTables holds information about
* each individual row. This is the object format used for the settings
* aoData array.
* @namespace
*/
DataTable.models.oRow = {
/**
* TR element for the row
* @type node
* @default null
*/
"nTr": null,
/**
* Array of TD elements for each row. This is null until the row has been
* created.
* @type array nodes
* @default []
*/
"anCells": null,
/**
* Data object from the original data source for the row. This is either
* an array if using the traditional form of DataTables, or an object if
* using mData options. The exact type will depend on the passed in
* data from the data source, or will be an array if using DOM a data
* source.
* @type array|object
* @default []
*/
"_aData": [],
/**
* Sorting data cache - this array is ostensibly the same length as the
* number of columns (although each index is generated only as it is
* needed), and holds the data that is used for sorting each column in the
* row. We do this cache generation at the start of the sort in order that
* the formatting of the sort data need be done only once for each cell
* per sort. This array should not be read from or written to by anything
* other than the master sorting methods.
* @type array
* @default null
* @private
*/
"_aSortData": null,
/**
* Per cell filtering data cache. As per the sort data cache, used to
* increase the performance of the filtering in DataTables
* @type array
* @default null
* @private
*/
"_aFilterData": null,
/**
* Filtering data cache. This is the same as the cell filtering cache, but
* in this case a string rather than an array. This is easily computed with
* a join on `_aFilterData`, but is provided as a cache so the join isn't
* needed on every search (memory traded for performance)
* @type array
* @default null
* @private
*/
"_sFilterRow": null,
/**
* Cache of the class name that DataTables has applied to the row, so we
* can quickly look at this variable rather than needing to do a DOM check
* on className for the nTr property.
* @type string
* @default <i>Empty string</i>
* @private
*/
"_sRowStripe": "",
/**
* Denote if the original data source was from the DOM, or the data source
* object. This is used for invalidating data, so DataTables can
* automatically read data from the original source, unless uninstructed
* otherwise.
* @type string
* @default null
* @private
*/
"src": null
};
/**
* Template object for the column information object in DataTables. This object
* is held in the settings aoColumns array and contains all the information that
* DataTables needs about each individual column.
*
* Note that this object is related to {@link DataTable.defaults.column}
* but this one is the internal data store for DataTables's cache of columns.
* It should NOT be manipulated outside of DataTables. Any configuration should
* be done through the initialisation options.
* @namespace
*/
DataTable.models.oColumn = {
/**
* A list of the columns that sorting should occur on when this column
* is sorted. That this property is an array allows multi-column sorting
* to be defined for a column (for example first name / last name columns
* would benefit from this). The values are integers pointing to the
* columns to be sorted on (typically it will be a single integer pointing
* at itself, but that doesn't need to be the case).
* @type array
*/
"aDataSort": null,
/**
* Define the sorting directions that are applied to the column, in sequence
* as the column is repeatedly sorted upon - i.e. the first value is used
* as the sorting direction when the column if first sorted (clicked on).
* Sort it again (click again) and it will move on to the next index.
* Repeat until loop.
* @type array
*/
"asSorting": null,
/**
* Flag to indicate if the column is searchable, and thus should be included
* in the filtering or not.
* @type boolean
*/
"bSearchable": null,
/**
* Flag to indicate if the column is sortable or not.
* @type boolean
*/
"bSortable": null,
/**
* Flag to indicate if the column is currently visible in the table or not
* @type boolean
*/
"bVisible": null,
/**
* Store for manual type assignment using the `column.type` option. This
* is held in store so we can manipulate the column's `sType` property.
* @type string
* @default null
* @private
*/
"_sManualType": null,
/**
* Flag to indicate if HTML5 data attributes should be used as the data
* source for filtering or sorting. True is either are.
* @type boolean
* @default false
* @private
*/
"_bAttrSrc": false,
/**
* Developer definable function that is called whenever a cell is created (Ajax source,
* etc) or processed for input (DOM source). This can be used as a compliment to mRender
* allowing you to modify the DOM element (add background colour for example) when the
* element is available.
* @type function
* @param {element} nTd The TD node that has been created
* @param {*} sData The Data for the cell
* @param {array|object} oData The data for the whole row
* @param {int} iRow The row index for the aoData data store
* @default null
*/
"fnCreatedCell": null,
/**
* Function to get data from a cell in a column. You should <b>never</b>
* access data directly through _aData internally in DataTables - always use
* the method attached to this property. It allows mData to function as
* required. This function is automatically assigned by the column
* initialisation method
* @type function
* @param {array|object} oData The data array/object for the array
* (i.e. aoData[]._aData)
* @param {string} sSpecific The specific data type you want to get -
* 'display', 'type' 'filter' 'sort'
* @returns {*} The data for the cell from the given row's data
* @default null
*/
"fnGetData": null,
/**
* Function to set data for a cell in the column. You should <b>never</b>
* set the data directly to _aData internally in DataTables - always use
* this method. It allows mData to function as required. This function
* is automatically assigned by the column initialisation method
* @type function
* @param {array|object} oData The data array/object for the array
* (i.e. aoData[]._aData)
* @param {*} sValue Value to set
* @default null
*/
"fnSetData": null,
/**
* Property to read the value for the cells in the column from the data
* source array / object. If null, then the default content is used, if a
* function is given then the return from the function is used.
* @type function|int|string|null
* @default null
*/
"mData": null,
/**
* Partner property to mData which is used (only when defined) to get
* the data - i.e. it is basically the same as mData, but without the
* 'set' option, and also the data fed to it is the result from mData.
* This is the rendering method to match the data method of mData.
* @type function|int|string|null
* @default null
*/
"mRender": null,
/**
* Unique header TH/TD element for this column - this is what the sorting
* listener is attached to (if sorting is enabled.)
* @type node
* @default null
*/
"nTh": null,
/**
* Unique footer TH/TD element for this column (if there is one). Not used
* in DataTables as such, but can be used for plug-ins to reference the
* footer for each column.
* @type node
* @default null
*/
"nTf": null,
/**
* The class to apply to all TD elements in the table's TBODY for the column
* @type string
* @default null
*/
"sClass": null,
/**
* When DataTables calculates the column widths to assign to each column,
* it finds the longest string in each column and then constructs a
* temporary table and reads the widths from that. The problem with this
* is that "mmm" is much wider then "iiii", but the latter is a longer
* string - thus the calculation can go wrong (doing it properly and putting
* it into an DOM object and measuring that is horribly(!) slow). Thus as
* a "work around" we provide this option. It will append its value to the
* text that is found to be the longest string for the column - i.e. padding.
* @type string
*/
"sContentPadding": null,
/**
* Allows a default value to be given for a column's data, and will be used
* whenever a null data source is encountered (this can be because mData
* is set to null, or because the data source itself is null).
* @type string
* @default null
*/
"sDefaultContent": null,
/**
* Name for the column, allowing reference to the column by name as well as
* by index (needs a lookup to work by name).
* @type string
*/
"sName": null,
/**
* Custom sorting data type - defines which of the available plug-ins in
* afnSortData the custom sorting will use - if any is defined.
* @type string
* @default std
*/
"sSortDataType": 'std',
/**
* Class to be applied to the header element when sorting on this column
* @type string
* @default null
*/
"sSortingClass": null,
/**
* Class to be applied to the header element when sorting on this column -
* when jQuery UI theming is used.
* @type string
* @default null
*/
"sSortingClassJUI": null,
/**
* Title of the column - what is seen in the TH element (nTh).
* @type string
*/
"sTitle": null,
/**
* Column sorting and filtering type
* @type string
* @default null
*/
"sType": null,
/**
* Width of the column
* @type string
* @default null
*/
"sWidth": null,
/**
* Width of the column when it was first "encountered"
* @type string
* @default null
*/
"sWidthOrig": null
};
/*
* Developer note: The properties of the object below are given in Hungarian
* notation, that was used as the interface for DataTables prior to v1.10, however
* from v1.10 onwards the primary interface is camel case. In order to avoid
* breaking backwards compatibility utterly with this change, the Hungarian
* version is still, internally the primary interface, but is is not documented
* - hence the @name tags in each doc comment. This allows a Javascript function
* to create a map from Hungarian notation to camel case (going the other direction
* would require each property to be listed, which would at around 3K to the size
* of DataTables, while this method is about a 0.5K hit.
*
* Ultimately this does pave the way for Hungarian notation to be dropped
* completely, but that is a massive amount of work and will break current
* installs (therefore is on-hold until v2).
*/
/**
* Initialisation options that can be given to DataTables at initialisation
* time.
* @namespace
*/
DataTable.defaults = {
/**
* An array of data to use for the table, passed in at initialisation which
* will be used in preference to any data which is already in the DOM. This is
* particularly useful for constructing tables purely in Javascript, for
* example with a custom Ajax call.
* @type array
* @default null
*
* @dtopt Option
* @name DataTable.defaults.data
*
* @example
* // Using a 2D array data source
* $(document).ready( function () {
* $('#example').dataTable( {
* "data": [
* ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'],
* ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'],
* ],
* "columns": [
* { "title": "Engine" },
* { "title": "Browser" },
* { "title": "Platform" },
* { "title": "Version" },
* { "title": "Grade" }
* ]
* } );
* } );
*
* @example
* // Using an array of objects as a data source (`data`)
* $(document).ready( function () {
* $('#example').dataTable( {
* "data": [
* {
* "engine": "Trident",
* "browser": "Internet Explorer 4.0",
* "platform": "Win 95+",
* "version": 4,
* "grade": "X"
* },
* {
* "engine": "Trident",
* "browser": "Internet Explorer 5.0",
* "platform": "Win 95+",
* "version": 5,
* "grade": "C"
* }
* ],
* "columns": [
* { "title": "Engine", "data": "engine" },
* { "title": "Browser", "data": "browser" },
* { "title": "Platform", "data": "platform" },
* { "title": "Version", "data": "version" },
* { "title": "Grade", "data": "grade" }
* ]
* } );
* } );
*/
"aaData": null,
/**
* If ordering is enabled, then DataTables will perform a first pass sort on
* initialisation. You can define which column(s) the sort is performed
* upon, and the sorting direction, with this variable. The `sorting` array
* should contain an array for each column to be sorted initially containing
* the column's index and a direction string ('asc' or 'desc').
* @type array
* @default [[0,'asc']]
*
* @dtopt Option
* @name DataTable.defaults.order
*
* @example
* // Sort by 3rd column first, and then 4th column
* $(document).ready( function() {
* $('#example').dataTable( {
* "order": [[2,'asc'], [3,'desc']]
* } );
* } );
*
* // No initial sorting
* $(document).ready( function() {
* $('#example').dataTable( {
* "order": []
* } );
* } );
*/
"aaSorting": [[0, 'asc']],
/**
* This parameter is basically identical to the `sorting` parameter, but
* cannot be overridden by user interaction with the table. What this means
* is that you could have a column (visible or hidden) which the sorting
* will always be forced on first - any sorting after that (from the user)
* will then be performed as required. This can be useful for grouping rows
* together.
* @type array
* @default null
*
* @dtopt Option
* @name DataTable.defaults.orderFixed
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "orderFixed": [[0,'asc']]
* } );
* } )
*/
"aaSortingFixed": [],
/**
* DataTables can be instructed to load data to display in the table from a
* Ajax source. This option defines how that Ajax call is made and where to.
*
* The `ajax` property has three different modes of operation, depending on
* how it is defined. These are:
*
* * `string` - Set the URL from where the data should be loaded from.
* * `object` - Define properties for `jQuery.ajax`.
* * `function` - Custom data get function
*
* `string`
* --------
*
* As a string, the `ajax` property simply defines the URL from which
* DataTables will load data.
*
* `object`
* --------
*
* As an object, the parameters in the object are passed to
* [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control
* of the Ajax request. DataTables has a number of default parameters which
* you can override using this option. Please refer to the jQuery
* documentation for a full description of the options available, although
* the following parameters provide additional options in DataTables or
* require special consideration:
*
* * `data` - As with jQuery, `data` can be provided as an object, but it
* can also be used as a function to manipulate the data DataTables sends
* to the server. The function takes a single parameter, an object of
* parameters with the values that DataTables has readied for sending. An
* object may be returned which will be merged into the DataTables
* defaults, or you can add the items to the object that was passed in and
* not return anything from the function. This supersedes `fnServerParams`
* from DataTables 1.9-.
*
* * `dataSrc` - By default DataTables will look for the property `data` (or
* `aaData` for compatibility with DataTables 1.9-) when obtaining data
* from an Ajax source or for server-side processing - this parameter
* allows that property to be changed. You can use Javascript dotted
* object notation to get a data source for multiple levels of nesting, or
* it my be used as a function. As a function it takes a single parameter,
* the JSON returned from the server, which can be manipulated as
* required, with the returned value being that used by DataTables as the
* data source for the table. This supersedes `sAjaxDataProp` from
* DataTables 1.9-.
*
* * `success` - Should not be overridden it is used internally in
* DataTables. To manipulate / transform the data returned by the server
* use `ajax.dataSrc`, or use `ajax` as a function (see below).
*
* `function`
* ----------
*
* As a function, making the Ajax call is left up to yourself allowing
* complete control of the Ajax request. Indeed, if desired, a method other
* than Ajax could be used to obtain the required data, such as Web storage
* or an AIR database.
*
* The function is given four parameters and no return is required. The
* parameters are:
*
* 1. _object_ - Data to send to the server
* 2. _function_ - Callback function that must be executed when the required
* data has been obtained. That data should be passed into the callback
* as the only parameter
* 3. _object_ - DataTables settings object for the table
*
* Note that this supersedes `fnServerData` from DataTables 1.9-.
*
* @type string|object|function
* @default null
*
* @dtopt Option
* @name DataTable.defaults.ajax
* @since 1.10.0
*
* @example
* // Get JSON data from a file via Ajax.
* // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default).
* $('#example').dataTable( {
* "ajax": "data.json"
* } );
*
* @example
* // Get JSON data from a file via Ajax, using `dataSrc` to change
* // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`)
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "dataSrc": "tableData"
* }
* } );
*
* @example
* // Get JSON data from a file via Ajax, using `dataSrc` to read data
* // from a plain array rather than an array in an object
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "dataSrc": ""
* }
* } );
*
* @example
* // Manipulate the data returned from the server - add a link to data
* // (note this can, should, be done using `render` for the column - this
* // is just a simple example of how the data can be manipulated).
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "dataSrc": function ( json ) {
* for ( var i=0, ien=json.length ; i<ien ; i++ ) {
* json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>';
* }
* return json;
* }
* }
* } );
*
* @example
* // Add data to the request
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "data": function ( d ) {
* return {
* "extra_search": $('#extra').val()
* };
* }
* }
* } );
*
* @example
* // Send request as POST
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "type": "POST"
* }
* } );
*
* @example
* // Get the data from localStorage (could interface with a form for
* // adding, editing and removing rows).
* $('#example').dataTable( {
* "ajax": function (data, callback, settings) {
* callback(
* JSON.parse( localStorage.getItem('dataTablesData') )
* );
* }
* } );
*/
"ajax": null,
/**
* This parameter allows you to readily specify the entries in the length drop
* down menu that DataTables shows when pagination is enabled. It can be
* either a 1D array of options which will be used for both the displayed
* option and the value, or a 2D array which will use the array in the first
* position as the value, and the array in the second position as the
* displayed options (useful for language strings such as 'All').
*
* Note that the `pageLength` property will be automatically set to the
* first value given in this array, unless `pageLength` is also provided.
* @type array
* @default [ 10, 25, 50, 100 ]
*
* @dtopt Option
* @name DataTable.defaults.lengthMenu
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
* } );
* } );
*/
"aLengthMenu": [10, 25, 50, 100],
/**
* The `columns` option in the initialisation parameter allows you to define
* details about the way individual columns behave. For a full list of
* column options that can be set, please see
* {@link DataTable.defaults.column}. Note that if you use `columns` to
* define your columns, you must have an entry in the array for every single
* column that you have in your table (these can be null if you don't which
* to specify any options).
* @member
*
* @name DataTable.defaults.column
*/
"aoColumns": null,
/**
* Very similar to `columns`, `columnDefs` allows you to target a specific
* column, multiple columns, or all columns, using the `targets` property of
* each object in the array. This allows great flexibility when creating
* tables, as the `columnDefs` arrays can be of any length, targeting the
* columns you specifically want. `columnDefs` may use any of the column
* options available: {@link DataTable.defaults.column}, but it _must_
* have `targets` defined in each object in the array. Values in the `targets`
* array may be:
* <ul>
* <li>a string - class name will be matched on the TH for the column</li>
* <li>0 or a positive integer - column index counting from the left</li>
* <li>a negative integer - column index counting from the right</li>
* <li>the string "_all" - all columns (i.e. assign a default)</li>
* </ul>
* @member
*
* @name DataTable.defaults.columnDefs
*/
"aoColumnDefs": null,
/**
* Basically the same as `search`, this parameter defines the individual column
* filtering state at initialisation time. The array must be of the same size
* as the number of columns, and each element be an object with the parameters
* `search` and `escapeRegex` (the latter is optional). 'null' is also
* accepted and the default will be used.
* @type array
* @default []
*
* @dtopt Option
* @name DataTable.defaults.searchCols
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "searchCols": [
* null,
* { "search": "My filter" },
* null,
* { "search": "^[0-9]", "escapeRegex": false }
* ]
* } );
* } )
*/
"aoSearchCols": [],
/**
* An array of CSS classes that should be applied to displayed rows. This
* array may be of any length, and DataTables will apply each class
* sequentially, looping when required.
* @type array
* @default null <i>Will take the values determined by the `oClasses.stripe*`
* options</i>
*
* @dtopt Option
* @name DataTable.defaults.stripeClasses
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "stripeClasses": [ 'strip1', 'strip2', 'strip3' ]
* } );
* } )
*/
"asStripeClasses": null,
/**
* Enable or disable automatic column width calculation. This can be disabled
* as an optimisation (it takes some time to calculate the widths) if the
* tables widths are passed in using `columns`.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.autoWidth
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "autoWidth": false
* } );
* } );
*/
"bAutoWidth": true,
/**
* Deferred rendering can provide DataTables with a huge speed boost when you
* are using an Ajax or JS data source for the table. This option, when set to
* true, will cause DataTables to defer the creation of the table elements for
* each row until they are needed for a draw - saving a significant amount of
* time.
* @type boolean
* @default false
*
* @dtopt Features
* @name DataTable.defaults.deferRender
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "ajax": "sources/arrays.txt",
* "deferRender": true
* } );
* } );
*/
"bDeferRender": false,
/**
* Replace a DataTable which matches the given selector and replace it with
* one which has the properties of the new initialisation object passed. If no
* table matches the selector, then the new DataTable will be constructed as
* per normal.
* @type boolean
* @default false
*
* @dtopt Options
* @name DataTable.defaults.destroy
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "srollY": "200px",
* "paginate": false
* } );
*
* // Some time later....
* $('#example').dataTable( {
* "filter": false,
* "destroy": true
* } );
* } );
*/
"bDestroy": false,
/**
* Enable or disable filtering of data. Filtering in DataTables is "smart" in
* that it allows the end user to input multiple words (space separated) and
* will match a row containing those words, even if not in the order that was
* specified (this allow matching across multiple columns). Note that if you
* wish to use filtering in DataTables this must remain 'true' - to remove the
* default filtering input box and retain filtering abilities, please use
* {@link DataTable.defaults.dom}.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.searching
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "searching": false
* } );
* } );
*/
"bFilter": true,
/**
* Enable or disable the table information display. This shows information
* about the data that is currently visible on the page, including information
* about filtered data if that action is being performed.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.info
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "info": false
* } );
* } );
*/
"bInfo": true,
/**
* Enable jQuery UI ThemeRoller support (required as ThemeRoller requires some
* slightly different and additional mark-up from what DataTables has
* traditionally used).
* @type boolean
* @default false
*
* @dtopt Features
* @name DataTable.defaults.jQueryUI
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "jQueryUI": true
* } );
* } );
*/
"bJQueryUI": false,
/**
* Allows the end user to select the size of a formatted page from a select
* menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`).
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.lengthChange
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "lengthChange": false
* } );
* } );
*/
"bLengthChange": true,
/**
* Enable or disable pagination.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.paging
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "paging": false
* } );
* } );
*/
"bPaginate": true,
/**
* Enable or disable the display of a 'processing' indicator when the table is
* being processed (e.g. a sort). This is particularly useful for tables with
* large amounts of data where it can take a noticeable amount of time to sort
* the entries.
* @type boolean
* @default false
*
* @dtopt Features
* @name DataTable.defaults.processing
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "processing": true
* } );
* } );
*/
"bProcessing": false,
/**
* Retrieve the DataTables object for the given selector. Note that if the
* table has already been initialised, this parameter will cause DataTables
* to simply return the object that has already been set up - it will not take
* account of any changes you might have made to the initialisation object
* passed to DataTables (setting this parameter to true is an acknowledgement
* that you understand this). `destroy` can be used to reinitialise a table if
* you need.
* @type boolean
* @default false
*
* @dtopt Options
* @name DataTable.defaults.retrieve
*
* @example
* $(document).ready( function() {
* initTable();
* tableActions();
* } );
*
* function initTable ()
* {
* return $('#example').dataTable( {
* "scrollY": "200px",
* "paginate": false,
* "retrieve": true
* } );
* }
*
* function tableActions ()
* {
* var table = initTable();
* // perform API operations with oTable
* }
*/
"bRetrieve": false,
/**
* When vertical (y) scrolling is enabled, DataTables will force the height of
* the table's viewport to the given height at all times (useful for layout).
* However, this can look odd when filtering data down to a small data set,
* and the footer is left "floating" further down. This parameter (when
* enabled) will cause DataTables to collapse the table's viewport down when
* the result set will fit within the given Y height.
* @type boolean
* @default false
*
* @dtopt Options
* @name DataTable.defaults.scrollCollapse
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "scrollY": "200",
* "scrollCollapse": true
* } );
* } );
*/
"bScrollCollapse": false,
/**
* Configure DataTables to use server-side processing. Note that the
* `ajax` parameter must also be given in order to give DataTables a
* source to obtain the required data for each draw.
* @type boolean
* @default false
*
* @dtopt Features
* @dtopt Server-side
* @name DataTable.defaults.serverSide
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "serverSide": true,
* "ajax": "xhr.php"
* } );
* } );
*/
"bServerSide": false,
/**
* Enable or disable sorting of columns. Sorting of individual columns can be
* disabled by the `sortable` option for each column.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.ordering
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "ordering": false
* } );
* } );
*/
"bSort": true,
/**
* Enable or display DataTables' ability to sort multiple columns at the
* same time (activated by shift-click by the user).
* @type boolean
* @default true
*
* @dtopt Options
* @name DataTable.defaults.orderMulti
*
* @example
* // Disable multiple column sorting ability
* $(document).ready( function () {
* $('#example').dataTable( {
* "orderMulti": false
* } );
* } );
*/
"bSortMulti": true,
/**
* Allows control over whether DataTables should use the top (true) unique
* cell that is found for a single column, or the bottom (false - default).
* This is useful when using complex headers.
* @type boolean
* @default false
*
* @dtopt Options
* @name DataTable.defaults.orderCellsTop
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "orderCellsTop": true
* } );
* } );
*/
"bSortCellsTop": false,
/**
* Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and
* `sorting\_3` to the columns which are currently being sorted on. This is
* presented as a feature switch as it can increase processing time (while
* classes are removed and added) so for large data sets you might want to
* turn this off.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.orderClasses
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "orderClasses": false
* } );
* } );
*/
"bSortClasses": true,
/**
* Enable or disable state saving. When enabled HTML5 `localStorage` will be
* used to save table display information such as pagination information,
* display length, filtering and sorting. As such when the end user reloads
* the page the display display will match what thy had previously set up.
*
* Due to the use of `localStorage` the default state saving is not supported
* in IE6 or 7. If state saving is required in those browsers, use
* `stateSaveCallback` to provide a storage solution such as cookies.
* @type boolean
* @default false
*
* @dtopt Features
* @name DataTable.defaults.stateSave
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "stateSave": true
* } );
* } );
*/
"bStateSave": false,
/**
* This function is called when a TR element is created (and all TD child
* elements have been inserted), or registered if using a DOM source, allowing
* manipulation of the TR element (adding classes etc).
* @type function
* @param {node} row "TR" element for the current row
* @param {array} data Raw data array for this row
* @param {int} dataIndex The index of this row in the internal aoData array
*
* @dtopt Callbacks
* @name DataTable.defaults.createdRow
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "createdRow": function( row, data, dataIndex ) {
* // Bold the grade for all 'A' grade browsers
* if ( data[4] == "A" )
* {
* $('td:eq(4)', row).html( '<b>A</b>' );
* }
* }
* } );
* } );
*/
"fnCreatedRow": null,
/**
* This function is called on every 'draw' event, and allows you to
* dynamically modify any aspect you want about the created DOM.
* @type function
* @param {object} settings DataTables settings object
*
* @dtopt Callbacks
* @name DataTable.defaults.drawCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "drawCallback": function( settings ) {
* alert( 'DataTables has redrawn the table' );
* }
* } );
* } );
*/
"fnDrawCallback": null,
/**
* Identical to fnHeaderCallback() but for the table footer this function
* allows you to modify the table footer on every 'draw' event.
* @type function
* @param {node} foot "TR" element for the footer
* @param {array} data Full table data (as derived from the original HTML)
* @param {int} start Index for the current display starting point in the
* display array
* @param {int} end Index for the current display ending point in the
* display array
* @param {array int} display Index array to translate the visual position
* to the full data array
*
* @dtopt Callbacks
* @name DataTable.defaults.footerCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "footerCallback": function( tfoot, data, start, end, display ) {
* tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start;
* }
* } );
* } )
*/
"fnFooterCallback": null,
/**
* When rendering large numbers in the information element for the table
* (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers
* to have a comma separator for the 'thousands' units (e.g. 1 million is
* rendered as "1,000,000") to help readability for the end user. This
* function will override the default method DataTables uses.
* @type function
* @member
* @param {int} toFormat number to be formatted
* @returns {string} formatted string for DataTables to show the number
*
* @dtopt Callbacks
* @name DataTable.defaults.formatNumber
*
* @example
* // Format a number using a single quote for the separator (note that
* // this can also be done with the language.infoThousands option)
* $(document).ready( function() {
* $('#example').dataTable( {
* "formatNumber": function ( toFormat ) {
* return toFormat.toString().replace(
* /\B(?=(\d{3})+(?!\d))/g, "'"
* );
* };
* } );
* } );
*/
"fnFormatNumber": function (toFormat) {
return toFormat.toString().replace(
/\B(?=(\d{3})+(?!\d))/g,
this.oLanguage.sInfoThousands
);
},
/**
* This function is called on every 'draw' event, and allows you to
* dynamically modify the header row. This can be used to calculate and
* display useful information about the table.
* @type function
* @param {node} head "TR" element for the header
* @param {array} data Full table data (as derived from the original HTML)
* @param {int} start Index for the current display starting point in the
* display array
* @param {int} end Index for the current display ending point in the
* display array
* @param {array int} display Index array to translate the visual position
* to the full data array
*
* @dtopt Callbacks
* @name DataTable.defaults.headerCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fheaderCallback": function( head, data, start, end, display ) {
* head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records";
* }
* } );
* } )
*/
"fnHeaderCallback": null,
/**
* The information element can be used to convey information about the current
* state of the table. Although the internationalisation options presented by
* DataTables are quite capable of dealing with most customisations, there may
* be times where you wish to customise the string further. This callback
* allows you to do exactly that.
* @type function
* @param {object} oSettings DataTables settings object
* @param {int} start Starting position in data for the draw
* @param {int} end End position in data for the draw
* @param {int} max Total number of rows in the table (regardless of
* filtering)
* @param {int} total Total number of rows in the data set, after filtering
* @param {string} pre The string that DataTables has formatted using it's
* own rules
* @returns {string} The string to be displayed in the information element.
*
* @dtopt Callbacks
* @name DataTable.defaults.infoCallback
*
* @example
* $('#example').dataTable( {
* "infoCallback": function( settings, start, end, max, total, pre ) {
* return start +" to "+ end;
* }
* } );
*/
"fnInfoCallback": null,
/**
* Called when the table has been initialised. Normally DataTables will
* initialise sequentially and there will be no need for this function,
* however, this does not hold true when using external language information
* since that is obtained using an async XHR call.
* @type function
* @param {object} settings DataTables settings object
* @param {object} json The JSON object request from the server - only
* present if client-side Ajax sourced data is used
*
* @dtopt Callbacks
* @name DataTable.defaults.initComplete
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "initComplete": function(settings, json) {
* alert( 'DataTables has finished its initialisation.' );
* }
* } );
* } )
*/
"fnInitComplete": null,
/**
* Called at the very start of each table draw and can be used to cancel the
* draw by returning false, any other return (including undefined) results in
* the full draw occurring).
* @type function
* @param {object} settings DataTables settings object
* @returns {boolean} False will cancel the draw, anything else (including no
* return) will allow it to complete.
*
* @dtopt Callbacks
* @name DataTable.defaults.preDrawCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "preDrawCallback": function( settings ) {
* if ( $('#test').val() == 1 ) {
* return false;
* }
* }
* } );
* } );
*/
"fnPreDrawCallback": null,
/**
* This function allows you to 'post process' each row after it have been
* generated for each table draw, but before it is rendered on screen. This
* function might be used for setting the row class name etc.
* @type function
* @param {node} row "TR" element for the current row
* @param {array} data Raw data array for this row
* @param {int} displayIndex The display index for the current table draw
* @param {int} displayIndexFull The index of the data in the full list of
* rows (after filtering)
*
* @dtopt Callbacks
* @name DataTable.defaults.rowCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "rowCallback": function( row, data, displayIndex, displayIndexFull ) {
* // Bold the grade for all 'A' grade browsers
* if ( data[4] == "A" ) {
* $('td:eq(4)', row).html( '<b>A</b>' );
* }
* }
* } );
* } );
*/
"fnRowCallback": null,
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* This parameter allows you to override the default function which obtains
* the data from the server so something more suitable for your application.
* For example you could use POST data, or pull information from a Gears or
* AIR database.
* @type function
* @member
* @param {string} source HTTP source to obtain the data from (`ajax`)
* @param {array} data A key/value pair object containing the data to send
* to the server
* @param {function} callback to be called on completion of the data get
* process that will draw the data on the page.
* @param {object} settings DataTables settings object
*
* @dtopt Callbacks
* @dtopt Server-side
* @name DataTable.defaults.serverData
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"fnServerData": null,
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* It is often useful to send extra data to the server when making an Ajax
* request - for example custom filtering information, and this callback
* function makes it trivial to send extra information to the server. The
* passed in parameter is the data set that has been constructed by
* DataTables, and you can add to this or modify it as you require.
* @type function
* @param {array} data Data array (array of objects which are name/value
* pairs) that has been constructed by DataTables and will be sent to the
* server. In the case of Ajax sourced data with server-side processing
* this will be an empty array, for server-side processing there will be a
* significant number of parameters!
* @returns {undefined} Ensure that you modify the data array passed in,
* as this is passed by reference.
*
* @dtopt Callbacks
* @dtopt Server-side
* @name DataTable.defaults.serverParams
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"fnServerParams": null,
/**
* Load the table state. With this function you can define from where, and how, the
* state of a table is loaded. By default DataTables will load from `localStorage`
* but you might wish to use a server-side database or cookies.
* @type function
* @member
* @param {object} settings DataTables settings object
* @return {object} The DataTables state object to be loaded
*
* @dtopt Callbacks
* @name DataTable.defaults.stateLoadCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateLoadCallback": function (settings) {
* var o;
*
* // Send an Ajax request to the server to get the data. Note that
* // this is a synchronous request.
* $.ajax( {
* "url": "/state_load",
* "async": false,
* "dataType": "json",
* "success": function (json) {
* o = json;
* }
* } );
*
* return o;
* }
* } );
* } );
*/
"fnStateLoadCallback": function (settings) {
try {
return JSON.parse(
localStorage.getItem('DataTables_' + settings.sInstance + '_' + window.location.pathname)
);
} catch (e) {
}
},
/**
* Callback which allows modification of the saved state prior to loading that state.
* This callback is called when the table is loading state from the stored data, but
* prior to the settings object being modified by the saved state. Note that for
* plug-in authors, you should use the `stateLoadParams` event to load parameters for
* a plug-in.
* @type function
* @param {object} settings DataTables settings object
* @param {object} data The state object that is to be loaded
*
* @dtopt Callbacks
* @name DataTable.defaults.stateLoadParams
*
* @example
* // Remove a saved filter, so filtering is never loaded
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateLoadParams": function (settings, data) {
* data.oSearch.sSearch = "";
* }
* } );
* } );
*
* @example
* // Disallow state loading by returning false
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateLoadParams": function (settings, data) {
* return false;
* }
* } );
* } );
*/
"fnStateLoadParams": null,
/**
* Callback that is called when the state has been loaded from the state saving method
* and the DataTables settings object has been modified as a result of the loaded state.
* @type function
* @param {object} settings DataTables settings object
* @param {object} data The state object that was loaded
*
* @dtopt Callbacks
* @name DataTable.defaults.stateLoaded
*
* @example
* // Show an alert with the filtering value that was saved
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateLoaded": function (settings, data) {
* alert( 'Saved filter was: '+data.oSearch.sSearch );
* }
* } );
* } );
*/
"fnStateLoaded": null,
/**
* Save the table state. This function allows you to define where and how the state
* information for the table is stored By default DataTables will use `localStorage`
* but you might wish to use a server-side database or cookies.
* @type function
* @member
* @param {object} settings DataTables settings object
* @param {object} data The state object to be saved
*
* @dtopt Callbacks
* @name DataTable.defaults.stateSaveCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateSaveCallback": function (settings, data) {
* // Send an Ajax request to the server with the state object
* $.ajax( {
* "url": "/state_save",
* "data": data,
* "dataType": "json",
* "method": "POST"
* "success": function () {}
* } );
* }
* } );
* } );
*/
"fnStateSaveCallback": function (settings, data) {
try {
localStorage.setItem(
'DataTables_' + settings.sInstance + '_' + window.location.pathname,
JSON.stringify(data)
);
} catch (e) {
}
},
/**
* Callback which allows modification of the state to be saved. Called when the table
* has changed state a new state save is required. This method allows modification of
* the state saving object prior to actually doing the save, including addition or
* other state properties or modification. Note that for plug-in authors, you should
* use the `stateSaveParams` event to save parameters for a plug-in.
* @type function
* @param {object} settings DataTables settings object
* @param {object} data The state object to be saved
*
* @dtopt Callbacks
* @name DataTable.defaults.stateSaveParams
*
* @example
* // Remove a saved filter, so filtering is never saved
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateSaveParams": function (settings, data) {
* data.oSearch.sSearch = "";
* }
* } );
* } );
*/
"fnStateSaveParams": null,
/**
* Duration for which the saved state information is considered valid. After this period
* has elapsed the state will be returned to the default.
* Value is given in seconds.
* @type int
* @default 7200 <i>(2 hours)</i>
*
* @dtopt Options
* @name DataTable.defaults.stateDuration
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateDuration": 60*60*24; // 1 day
* } );
* } )
*/
"iStateDuration": 7200,
/**
* When enabled DataTables will not make a request to the server for the first
* page draw - rather it will use the data already on the page (no sorting etc
* will be applied to it), thus saving on an XHR at load time. `deferLoading`
* is used to indicate that deferred loading is required, but it is also used
* to tell DataTables how many records there are in the full table (allowing
* the information element and pagination to be displayed correctly). In the case
* where a filtering is applied to the table on initial load, this can be
* indicated by giving the parameter as an array, where the first element is
* the number of records available after filtering and the second element is the
* number of records without filtering (allowing the table information element
* to be shown correctly).
* @type int | array
* @default null
*
* @dtopt Options
* @name DataTable.defaults.deferLoading
*
* @example
* // 57 records available in the table, no filtering applied
* $(document).ready( function() {
* $('#example').dataTable( {
* "serverSide": true,
* "ajax": "scripts/server_processing.php",
* "deferLoading": 57
* } );
* } );
*
* @example
* // 57 records after filtering, 100 without filtering (an initial filter applied)
* $(document).ready( function() {
* $('#example').dataTable( {
* "serverSide": true,
* "ajax": "scripts/server_processing.php",
* "deferLoading": [ 57, 100 ],
* "search": {
* "search": "my_filter"
* }
* } );
* } );
*/
"iDeferLoading": null,
/**
* Number of rows to display on a single page when using pagination. If
* feature enabled (`lengthChange`) then the end user will be able to override
* this to a custom setting using a pop-up menu.
* @type int
* @default 10
*
* @dtopt Options
* @name DataTable.defaults.pageLength
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "pageLength": 50
* } );
* } )
*/
"iDisplayLength": 10,
/**
* Define the starting point for data display when using DataTables with
* pagination. Note that this parameter is the number of records, rather than
* the page number, so if you have 10 records per page and want to start on
* the third page, it should be "20".
* @type int
* @default 0
*
* @dtopt Options
* @name DataTable.defaults.displayStart
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "displayStart": 20
* } );
* } )
*/
"iDisplayStart": 0,
/**
* By default DataTables allows keyboard navigation of the table (sorting, paging,
* and filtering) by adding a `tabindex` attribute to the required elements. This
* allows you to tab through the controls and press the enter key to activate them.
* The tabindex is default 0, meaning that the tab follows the flow of the document.
* You can overrule this using this parameter if you wish. Use a value of -1 to
* disable built-in keyboard navigation.
* @type int
* @default 0
*
* @dtopt Options
* @name DataTable.defaults.tabIndex
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "tabIndex": 1
* } );
* } );
*/
"iTabIndex": 0,
/**
* Classes that DataTables assigns to the various components and features
* that it adds to the HTML table. This allows classes to be configured
* during initialisation in addition to through the static
* {@link DataTable.ext.oStdClasses} object).
* @namespace
* @name DataTable.defaults.classes
*/
"oClasses": {},
/**
* All strings that DataTables uses in the user interface that it creates
* are defined in this object, allowing you to modified them individually or
* completely replace them all as required.
* @namespace
* @name DataTable.defaults.language
*/
"oLanguage": {
/**
* Strings that are used for WAI-ARIA labels and controls only (these are not
* actually visible on the page, but will be read by screenreaders, and thus
* must be internationalised as well).
* @namespace
* @name DataTable.defaults.language.aria
*/
"oAria": {
/**
* ARIA label that is added to the table headers when the column may be
* sorted ascending by activing the column (click or return when focused).
* Note that the column header is prefixed to this string.
* @type string
* @default : activate to sort column ascending
*
* @dtopt Language
* @name DataTable.defaults.language.aria.sortAscending
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "aria": {
* "sortAscending": " - click/return to sort ascending"
* }
* }
* } );
* } );
*/
"sSortAscending": ": activate to sort column ascending",
/**
* ARIA label that is added to the table headers when the column may be
* sorted descending by activing the column (click or return when focused).
* Note that the column header is prefixed to this string.
* @type string
* @default : activate to sort column ascending
*
* @dtopt Language
* @name DataTable.defaults.language.aria.sortDescending
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "aria": {
* "sortDescending": " - click/return to sort descending"
* }
* }
* } );
* } );
*/
"sSortDescending": ": activate to sort column descending"
},
/**
* Pagination string used by DataTables for the built-in pagination
* control types.
* @namespace
* @name DataTable.defaults.language.paginate
*/
"oPaginate": {
/**
* Text to use when using the 'full_numbers' type of pagination for the
* button to take the user to the first page.
* @type string
* @default First
*
* @dtopt Language
* @name DataTable.defaults.language.paginate.first
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "paginate": {
* "first": "First page"
* }
* }
* } );
* } );
*/
"sFirst": "First",
/**
* Text to use when using the 'full_numbers' type of pagination for the
* button to take the user to the last page.
* @type string
* @default Last
*
* @dtopt Language
* @name DataTable.defaults.language.paginate.last
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "paginate": {
* "last": "Last page"
* }
* }
* } );
* } );
*/
"sLast": "Last",
/**
* Text to use for the 'next' pagination button (to take the user to the
* next page).
* @type string
* @default Next
*
* @dtopt Language
* @name DataTable.defaults.language.paginate.next
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "paginate": {
* "next": "Next page"
* }
* }
* } );
* } );
*/
"sNext": "Next",
/**
* Text to use for the 'previous' pagination button (to take the user to
* the previous page).
* @type string
* @default Previous
*
* @dtopt Language
* @name DataTable.defaults.language.paginate.previous
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "paginate": {
* "previous": "Previous page"
* }
* }
* } );
* } );
*/
"sPrevious": "Previous"
},
/**
* This string is shown in preference to `zeroRecords` when the table is
* empty of data (regardless of filtering). Note that this is an optional
* parameter - if it is not given, the value of `zeroRecords` will be used
* instead (either the default or given value).
* @type string
* @default No data available in table
*
* @dtopt Language
* @name DataTable.defaults.language.emptyTable
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "emptyTable": "No data available in table"
* }
* } );
* } );
*/
"sEmptyTable": "No data available in table",
/**
* This string gives information to the end user about the information
* that is current on display on the page. The following tokens can be
* used in the string and will be dynamically replaced as the table
* display updates. This tokens can be placed anywhere in the string, or
* removed as needed by the language requires:
*
* * `\_START\_` - Display index of the first record on the current page
* * `\_END\_` - Display index of the last record on the current page
* * `\_TOTAL\_` - Number of records in the table after filtering
* * `\_MAX\_` - Number of records in the table without filtering
* * `\_PAGE\_` - Current page number
* * `\_PAGES\_` - Total number of pages of data in the table
*
* @type string
* @default Showing _START_ to _END_ of _TOTAL_ entries
*
* @dtopt Language
* @name DataTable.defaults.language.info
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "info": "Showing page _PAGE_ of _PAGES_"
* }
* } );
* } );
*/
"sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
/**
* Display information string for when the table is empty. Typically the
* format of this string should match `info`.
* @type string
* @default Showing 0 to 0 of 0 entries
*
* @dtopt Language
* @name DataTable.defaults.language.infoEmpty
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "infoEmpty": "No entries to show"
* }
* } );
* } );
*/
"sInfoEmpty": "Showing 0 to 0 of 0 entries",
/**
* When a user filters the information in a table, this string is appended
* to the information (`info`) to give an idea of how strong the filtering
* is. The variable _MAX_ is dynamically updated.
* @type string
* @default (filtered from _MAX_ total entries)
*
* @dtopt Language
* @name DataTable.defaults.language.infoFiltered
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "infoFiltered": " - filtering from _MAX_ records"
* }
* } );
* } );
*/
"sInfoFiltered": "(filtered from _MAX_ total entries)",
/**
* If can be useful to append extra information to the info string at times,
* and this variable does exactly that. This information will be appended to
* the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are
* being used) at all times.
* @type string
* @default <i>Empty string</i>
*
* @dtopt Language
* @name DataTable.defaults.language.infoPostFix
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "infoPostFix": "All records shown are derived from real information."
* }
* } );
* } );
*/
"sInfoPostFix": "",
/**
* DataTables has a build in number formatter (`formatNumber`) which is used
* to format large numbers that are used in the table information. By
* default a comma is used, but this can be trivially changed to any
* character you wish with this parameter.
* @type string
* @default ,
*
* @dtopt Language
* @name DataTable.defaults.language.infoThousands
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "infoThousands": "'"
* }
* } );
* } );
*/
"sInfoThousands": ",",
/**
* Detail the action that will be taken when the drop down menu for the
* pagination length option is changed. The '_MENU_' variable is replaced
* with a default select list of 10, 25, 50 and 100, and can be replaced
* with a custom select box if required.
* @type string
* @default Show _MENU_ entries
*
* @dtopt Language
* @name DataTable.defaults.language.lengthMenu
*
* @example
* // Language change only
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "lengthMenu": "Display _MENU_ records"
* }
* } );
* } );
*
* @example
* // Language and options change
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "lengthMenu": 'Display <select>'+
* '<option value="10">10</option>'+
* '<option value="20">20</option>'+
* '<option value="30">30</option>'+
* '<option value="40">40</option>'+
* '<option value="50">50</option>'+
* '<option value="-1">All</option>'+
* '</select> records'
* }
* } );
* } );
*/
"sLengthMenu": "Show _MENU_ entries",
/**
* When using Ajax sourced data and during the first draw when DataTables is
* gathering the data, this message is shown in an empty row in the table to
* indicate to the end user the the data is being loaded. Note that this
* parameter is not used when loading data by server-side processing, just
* Ajax sourced data with client-side processing.
* @type string
* @default Loading...
*
* @dtopt Language
* @name DataTable.defaults.language.loadingRecords
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "loadingRecords": "Please wait - loading..."
* }
* } );
* } );
*/
"sLoadingRecords": "Loading...",
/**
* Text which is displayed when the table is processing a user action
* (usually a sort command or similar).
* @type string
* @default Processing...
*
* @dtopt Language
* @name DataTable.defaults.language.processing
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "processing": "DataTables is currently busy"
* }
* } );
* } );
*/
"sProcessing": "Processing...",
/**
* Details the actions that will be taken when the user types into the
* filtering input text box. The variable "_INPUT_", if used in the string,
* is replaced with the HTML text box for the filtering input allowing
* control over where it appears in the string. If "_INPUT_" is not given
* then the input box is appended to the string automatically.
* @type string
* @default Search:
*
* @dtopt Language
* @name DataTable.defaults.language.search
*
* @example
* // Input text box will be appended at the end automatically
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "search": "Filter records:"
* }
* } );
* } );
*
* @example
* // Specify where the filter should appear
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "search": "Apply filter _INPUT_ to table"
* }
* } );
* } );
*/
"sSearch": "Search:",
/**
* All of the language information can be stored in a file on the
* server-side, which DataTables will look up if this parameter is passed.
* It must store the URL of the language file, which is in a JSON format,
* and the object has the same properties as the oLanguage object in the
* initialiser object (i.e. the above parameters). Please refer to one of
* the example language files to see how this works in action.
* @type string
* @default <i>Empty string - i.e. disabled</i>
*
* @dtopt Language
* @name DataTable.defaults.language.url
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "url": "http://www.sprymedia.co.uk/dataTables/lang.txt"
* }
* } );
* } );
*/
"sUrl": "",
/**
* Text shown inside the table records when the is no information to be
* displayed after filtering. `emptyTable` is shown when there is simply no
* information in the table at all (regardless of filtering).
* @type string
* @default No matching records found
*
* @dtopt Language
* @name DataTable.defaults.language.zeroRecords
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "zeroRecords": "No records to display"
* }
* } );
* } );
*/
"sZeroRecords": "No matching records found"
},
/**
* This parameter allows you to have define the global filtering state at
* initialisation time. As an object the `search` parameter must be
* defined, but all other parameters are optional. When `regex` is true,
* the search string will be treated as a regular expression, when false
* (default) it will be treated as a straight string. When `smart`
* DataTables will use it's smart filtering methods (to word match at
* any point in the data), when false this will not be done.
* @namespace
* @extends DataTable.models.oSearch
*
* @dtopt Options
* @name DataTable.defaults.search
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "search": {"search": "Initial search"}
* } );
* } )
*/
"oSearch": $.extend({}, DataTable.models.oSearch),
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* By default DataTables will look for the property `data` (or `aaData` for
* compatibility with DataTables 1.9-) when obtaining data from an Ajax
* source or for server-side processing - this parameter allows that
* property to be changed. You can use Javascript dotted object notation to
* get a data source for multiple levels of nesting.
* @type string
* @default data
*
* @dtopt Options
* @dtopt Server-side
* @name DataTable.defaults.ajaxDataProp
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"sAjaxDataProp": "data",
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* You can instruct DataTables to load data from an external
* source using this parameter (use aData if you want to pass data in you
* already have). Simply provide a url a JSON object can be obtained from.
* @type string
* @default null
*
* @dtopt Options
* @dtopt Server-side
* @name DataTable.defaults.ajaxSource
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"sAjaxSource": null,
/**
* This initialisation variable allows you to specify exactly where in the
* DOM you want DataTables to inject the various controls it adds to the page
* (for example you might want the pagination controls at the top of the
* table). DIV elements (with or without a custom class) can also be added to
* aid styling. The follow syntax is used:
* <ul>
* <li>The following options are allowed:
* <ul>
* <li>'l' - Length changing</li>
* <li>'f' - Filtering input</li>
* <li>'t' - The table!</li>
* <li>'i' - Information</li>
* <li>'p' - Pagination</li>
* <li>'r' - pRocessing</li>
* </ul>
* </li>
* <li>The following constants are allowed:
* <ul>
* <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li>
* <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li>
* </ul>
* </li>
* <li>The following syntax is expected:
* <ul>
* <li>'<' and '>' - div elements</li>
* <li>'<"class" and '>' - div with a class</li>
* <li>'<"#id" and '>' - div with an ID</li>
* </ul>
* </li>
* <li>Examples:
* <ul>
* <li>'<"wrapper"flipt>'</li>
* <li>'<lf<t>ip>'</li>
* </ul>
* </li>
* </ul>
* @type string
* @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b>
* <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i>
*
* @dtopt Options
* @name DataTable.defaults.dom
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "dom": '<"top"i>rt<"bottom"flp><"clear">'
* } );
* } );
*/
"sDom": "lfrtip",
/**
* DataTables features four different built-in options for the buttons to
* display for pagination control:
*
* * `simple` - 'Previous' and 'Next' buttons only
* * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers
* * `full` - 'First', 'Previous', 'Next' and 'Last' buttons
* * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus
* page numbers
*
* Further methods can be added using {@link DataTable.ext.oPagination}.
* @type string
* @default simple_numbers
*
* @dtopt Options
* @name DataTable.defaults.pagingType
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "pagingType": "full_numbers"
* } );
* } )
*/
"sPaginationType": "simple_numbers",
/**
* Enable horizontal scrolling. When a table is too wide to fit into a
* certain layout, or you have a large number of columns in the table, you
* can enable x-scrolling to show the table in a viewport, which can be
* scrolled. This property can be `true` which will allow the table to
* scroll horizontally when needed, or any CSS unit, or a number (in which
* case it will be treated as a pixel measurement). Setting as simply `true`
* is recommended.
* @type boolean|string
* @default <i>blank string - i.e. disabled</i>
*
* @dtopt Features
* @name DataTable.defaults.scrollX
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "scrollX": true,
* "scrollCollapse": true
* } );
* } );
*/
"sScrollX": "",
/**
* This property can be used to force a DataTable to use more width than it
* might otherwise do when x-scrolling is enabled. For example if you have a
* table which requires to be well spaced, this parameter is useful for
* "over-sizing" the table, and thus forcing scrolling. This property can by
* any CSS unit, or a number (in which case it will be treated as a pixel
* measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
*
* @dtopt Options
* @name DataTable.defaults.scrollXInner
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "scrollX": "100%",
* "scrollXInner": "110%"
* } );
* } );
*/
"sScrollXInner": "",
/**
* Enable vertical scrolling. Vertical scrolling will constrain the DataTable
* to the given height, and enable scrolling for any data which overflows the
* current viewport. This can be used as an alternative to paging to display
* a lot of data in a small area (although paging and scrolling can both be
* enabled at the same time). This property can be any CSS unit, or a number
* (in which case it will be treated as a pixel measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
*
* @dtopt Features
* @name DataTable.defaults.scrollY
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "scrollY": "200px",
* "paginate": false
* } );
* } );
*/
"sScrollY": "",
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* Set the HTTP method that is used to make the Ajax call for server-side
* processing or Ajax sourced data.
* @type string
* @default GET
*
* @dtopt Options
* @dtopt Server-side
* @name DataTable.defaults.serverMethod
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"sServerMethod": "GET",
/**
* DataTables makes use of renderers when displaying HTML elements for
* a table. These renderers can be added or modified by plug-ins to
* generate suitable mark-up for a site. For example the Bootstrap
* integration plug-in for DataTables uses a paging button renderer to
* display pagination buttons in the mark-up required by Bootstrap.
*
* For further information about the renderers available see
* DataTable.ext.renderer
* @type string|object
* @default null
*
* @name DataTable.defaults.renderer
*
*/
"renderer": null
};
_fnHungarianMap(DataTable.defaults);
/*
* Developer note - See note in model.defaults.js about the use of Hungarian
* notation and camel case.
*/
/**
* Column options that can be given to DataTables at initialisation time.
* @namespace
*/
DataTable.defaults.column = {
/**
* Define which column(s) an order will occur on for this column. This
* allows a column's ordering to take multiple columns into account when
* doing a sort or use the data from a different column. For example first
* name / last name columns make sense to do a multi-column sort over the
* two columns.
* @type array|int
* @default null <i>Takes the value of the column index automatically</i>
*
* @name DataTable.defaults.column.orderData
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "orderData": [ 0, 1 ], "targets": [ 0 ] },
* { "orderData": [ 1, 0 ], "targets": [ 1 ] },
* { "orderData": 2, "targets": [ 2 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "orderData": [ 0, 1 ] },
* { "orderData": [ 1, 0 ] },
* { "orderData": 2 },
* null,
* null
* ]
* } );
* } );
*/
"aDataSort": null,
"iDataSort": -1,
/**
* You can control the default ordering direction, and even alter the
* behaviour of the sort handler (i.e. only allow ascending ordering etc)
* using this parameter.
* @type array
* @default [ 'asc', 'desc' ]
*
* @name DataTable.defaults.column.orderSequence
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "orderSequence": [ "asc" ], "targets": [ 1 ] },
* { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] },
* { "orderSequence": [ "desc" ], "targets": [ 3 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* null,
* { "orderSequence": [ "asc" ] },
* { "orderSequence": [ "desc", "asc", "asc" ] },
* { "orderSequence": [ "desc" ] },
* null
* ]
* } );
* } );
*/
"asSorting": ['asc', 'desc'],
/**
* Enable or disable filtering on the data in this column.
* @type boolean
* @default true
*
* @name DataTable.defaults.column.searchable
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "searchable": false, "targets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "searchable": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bSearchable": true,
/**
* Enable or disable ordering on this column.
* @type boolean
* @default true
*
* @name DataTable.defaults.column.orderable
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "orderable": false, "targets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "orderable": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bSortable": true,
/**
* Enable or disable the display of this column.
* @type boolean
* @default true
*
* @name DataTable.defaults.column.visible
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "visible": false, "targets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "visible": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bVisible": true,
/**
* Developer definable function that is called whenever a cell is created (Ajax source,
* etc) or processed for input (DOM source). This can be used as a compliment to mRender
* allowing you to modify the DOM element (add background colour for example) when the
* element is available.
* @type function
* @param {element} td The TD node that has been created
* @param {*} cellData The Data for the cell
* @param {array|object} rowData The data for the whole row
* @param {int} row The row index for the aoData data store
* @param {int} col The column index for aoColumns
*
* @name DataTable.defaults.column.createdCell
* @dtopt Columns
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [3],
* "createdCell": function (td, cellData, rowData, row, col) {
* if ( cellData == "1.7" ) {
* $(td).css('color', 'blue')
* }
* }
* } ]
* });
* } );
*/
"fnCreatedCell": null,
/**
* This parameter has been replaced by `data` in DataTables to ensure naming
* consistency. `dataProp` can still be used, as there is backwards
* compatibility in DataTables for this option, but it is strongly
* recommended that you use `data` in preference to `dataProp`.
* @name DataTable.defaults.column.dataProp
*/
/**
* This property can be used to read data from any data source property,
* including deeply nested objects / properties. `data` can be given in a
* number of different ways which effect its behaviour:
*
* * `integer` - treated as an array index for the data source. This is the
* default that DataTables uses (incrementally increased for each column).
* * `string` - read an object property from the data source. There are
* three 'special' options that can be used in the string to alter how
* DataTables reads the data from the source object:
* * `.` - Dotted Javascript notation. Just as you use a `.` in
* Javascript to read from nested objects, so to can the options
* specified in `data`. For example: `browser.version` or
* `browser.name`. If your object parameter name contains a period, use
* `\\` to escape it - i.e. `first\\.name`.
* * `[]` - Array notation. DataTables can automatically combine data
* from and array source, joining the data with the characters provided
* between the two brackets. For example: `name[, ]` would provide a
* comma-space separated list from the source array. If no characters
* are provided between the brackets, the original array source is
* returned.
* * `()` - Function notation. Adding `()` to the end of a parameter will
* execute a function of the name given. For example: `browser()` for a
* simple function on the data source, `browser.version()` for a
* function in a nested property or even `browser().version` to get an
* object property if the function called returns an object. Note that
* function notation is recommended for use in `render` rather than
* `data` as it is much simpler to use as a renderer.
* * `null` - use the original data source for the row rather than plucking
* data directly from it. This action has effects on two other
* initialisation options:
* * `defaultContent` - When null is given as the `data` option and
* `defaultContent` is specified for the column, the value defined by
* `defaultContent` will be used for the cell.
* * `render` - When null is used for the `data` option and the `render`
* option is specified for the column, the whole data source for the
* row is used for the renderer.
* * `function` - the function given will be executed whenever DataTables
* needs to set or get the data for a cell in the column. The function
* takes three parameters:
* * Parameters:
* * `{array|object}` The data source for the row
* * `{string}` The type call data requested - this will be 'set' when
* setting data or 'filter', 'display', 'type', 'sort' or undefined
* when gathering data. Note that when `undefined` is given for the
* type DataTables expects to get the raw data for the object back<
* * `{*}` Data to set when the second parameter is 'set'.
* * Return:
* * The return value from the function is not required when 'set' is
* the type of call, but otherwise the return is what will be used
* for the data requested.
*
* Note that `data` is a getter and setter option. If you just require
* formatting of data for output, you will likely want to use `render` which
* is simply a getter and thus simpler to use.
*
* Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The
* name change reflects the flexibility of this property and is consistent
* with the naming of mRender. If 'mDataProp' is given, then it will still
* be used by DataTables, as it automatically maps the old name to the new
* if required.
*
* @type string|int|function|null
* @default null <i>Use automatically calculated column index</i>
*
* @name DataTable.defaults.column.data
* @dtopt Columns
*
* @example
* // Read table data from objects
* // JSON structure for each row:
* // {
* // "engine": {value},
* // "browser": {value},
* // "platform": {value},
* // "version": {value},
* // "grade": {value}
* // }
* $(document).ready( function() {
* $('#example').dataTable( {
* "ajaxSource": "sources/objects.txt",
* "columns": [
* { "data": "engine" },
* { "data": "browser" },
* { "data": "platform" },
* { "data": "version" },
* { "data": "grade" }
* ]
* } );
* } );
*
* @example
* // Read information from deeply nested objects
* // JSON structure for each row:
* // {
* // "engine": {value},
* // "browser": {value},
* // "platform": {
* // "inner": {value}
* // },
* // "details": [
* // {value}, {value}
* // ]
* // }
* $(document).ready( function() {
* $('#example').dataTable( {
* "ajaxSource": "sources/deep.txt",
* "columns": [
* { "data": "engine" },
* { "data": "browser" },
* { "data": "platform.inner" },
* { "data": "platform.details.0" },
* { "data": "platform.details.1" }
* ]
* } );
* } );
*
* @example
* // Using `data` as a function to provide different information for
* // sorting, filtering and display. In this case, currency (price)
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": function ( source, type, val ) {
* if (type === 'set') {
* source.price = val;
* // Store the computed dislay and filter values for efficiency
* source.price_display = val=="" ? "" : "$"+numberFormat(val);
* source.price_filter = val=="" ? "" : "$"+numberFormat(val)+" "+val;
* return;
* }
* else if (type === 'display') {
* return source.price_display;
* }
* else if (type === 'filter') {
* return source.price_filter;
* }
* // 'sort', 'type' and undefined all just use the integer
* return source.price;
* }
* } ]
* } );
* } );
*
* @example
* // Using default content
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": null,
* "defaultContent": "Click to edit"
* } ]
* } );
* } );
*
* @example
* // Using array notation - outputting a list from an array
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": "name[, ]"
* } ]
* } );
* } );
*
*/
"mData": null,
/**
* This property is the rendering partner to `data` and it is suggested that
* when you want to manipulate data for display (including filtering,
* sorting etc) without altering the underlying data for the table, use this
* property. `render` can be considered to be the the read only companion to
* `data` which is read / write (then as such more complex). Like `data`
* this option can be given in a number of different ways to effect its
* behaviour:
*
* * `integer` - treated as an array index for the data source. This is the
* default that DataTables uses (incrementally increased for each column).
* * `string` - read an object property from the data source. There are
* three 'special' options that can be used in the string to alter how
* DataTables reads the data from the source object:
* * `.` - Dotted Javascript notation. Just as you use a `.` in
* Javascript to read from nested objects, so to can the options
* specified in `data`. For example: `browser.version` or
* `browser.name`. If your object parameter name contains a period, use
* `\\` to escape it - i.e. `first\\.name`.
* * `[]` - Array notation. DataTables can automatically combine data
* from and array source, joining the data with the characters provided
* between the two brackets. For example: `name[, ]` would provide a
* comma-space separated list from the source array. If no characters
* are provided between the brackets, the original array source is
* returned.
* * `()` - Function notation. Adding `()` to the end of a parameter will
* execute a function of the name given. For example: `browser()` for a
* simple function on the data source, `browser.version()` for a
* function in a nested property or even `browser().version` to get an
* object property if the function called returns an object.
* * `object` - use different data for the different data types requested by
* DataTables ('filter', 'display', 'type' or 'sort'). The property names
* of the object is the data type the property refers to and the value can
* defined using an integer, string or function using the same rules as
* `render` normally does. Note that an `_` option _must_ be specified.
* This is the default value to use if you haven't specified a value for
* the data type requested by DataTables.
* * `function` - the function given will be executed whenever DataTables
* needs to set or get the data for a cell in the column. The function
* takes three parameters:
* * Parameters:
* * {array|object} The data source for the row (based on `data`)
* * {string} The type call data requested - this will be 'filter',
* 'display', 'type' or 'sort'.
* * {array|object} The full data source for the row (not based on
* `data`)
* * Return:
* * The return value from the function is what will be used for the
* data requested.
*
* @type string|int|function|object|null
* @default null Use the data source value.
*
* @name DataTable.defaults.column.render
* @dtopt Columns
*
* @example
* // Create a comma separated list from an array of objects
* $(document).ready( function() {
* $('#example').dataTable( {
* "ajaxSource": "sources/deep.txt",
* "columns": [
* { "data": "engine" },
* { "data": "browser" },
* {
* "data": "platform",
* "render": "[, ].name"
* }
* ]
* } );
* } );
*
* @example
* // Execute a function to obtain data
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": null, // Use the full data source object for the renderer's source
* "render": "browserName()"
* } ]
* } );
* } );
*
* @example
* // As an object, extracting different data for the different types
* // This would be used with a data source such as:
* // { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" }
* // Here the `phone` integer is used for sorting and type detection, while `phone_filter`
* // (which has both forms) is used for filtering for if a user inputs either format, while
* // the formatted phone number is the one that is shown in the table.
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": null, // Use the full data source object for the renderer's source
* "render": {
* "_": "phone",
* "filter": "phone_filter",
* "display": "phone_display"
* }
* } ]
* } );
* } );
*
* @example
* // Use as a function to create a link from the data source
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": "download_link",
* "render": function ( data, type, full ) {
* return '<a href="'+data+'">Download</a>';
* }
* } ]
* } );
* } );
*/
"mRender": null,
/**
* Change the cell type created for the column - either TD cells or TH cells. This
* can be useful as TH cells have semantic meaning in the table body, allowing them
* to act as a header for a row (you may wish to add scope='row' to the TH elements).
* @type string
* @default td
*
* @name DataTable.defaults.column.cellType
* @dtopt Columns
*
* @example
* // Make the first column use TH cells
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "cellType": "th"
* } ]
* } );
* } );
*/
"sCellType": "td",
/**
* Class to give to each cell in this column.
* @type string
* @default <i>Empty string</i>
*
* @name DataTable.defaults.column.class
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "class": "my_class", "targets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "class": "my_class" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sClass": "",
/**
* When DataTables calculates the column widths to assign to each column,
* it finds the longest string in each column and then constructs a
* temporary table and reads the widths from that. The problem with this
* is that "mmm" is much wider then "iiii", but the latter is a longer
* string - thus the calculation can go wrong (doing it properly and putting
* it into an DOM object and measuring that is horribly(!) slow). Thus as
* a "work around" we provide this option. It will append its value to the
* text that is found to be the longest string for the column - i.e. padding.
* Generally you shouldn't need this!
* @type string
* @default <i>Empty string<i>
*
* @name DataTable.defaults.column.contentPadding
* @dtopt Columns
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* null,
* null,
* null,
* {
* "contentPadding": "mmm"
* }
* ]
* } );
* } );
*/
"sContentPadding": "",
/**
* Allows a default value to be given for a column's data, and will be used
* whenever a null data source is encountered (this can be because `data`
* is set to null, or because the data source itself is null).
* @type string
* @default null
*
* @name DataTable.defaults.column.defaultContent
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* {
* "data": null,
* "defaultContent": "Edit",
* "targets": [ -1 ]
* }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* null,
* null,
* null,
* {
* "data": null,
* "defaultContent": "Edit"
* }
* ]
* } );
* } );
*/
"sDefaultContent": null,
/**
* This parameter is only used in DataTables' server-side processing. It can
* be exceptionally useful to know what columns are being displayed on the
* client side, and to map these to database fields. When defined, the names
* also allow DataTables to reorder information from the server if it comes
* back in an unexpected order (i.e. if you switch your columns around on the
* client-side, your server-side code does not also need updating).
* @type string
* @default <i>Empty string</i>
*
* @name DataTable.defaults.column.name
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "name": "engine", "targets": [ 0 ] },
* { "name": "browser", "targets": [ 1 ] },
* { "name": "platform", "targets": [ 2 ] },
* { "name": "version", "targets": [ 3 ] },
* { "name": "grade", "targets": [ 4 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "name": "engine" },
* { "name": "browser" },
* { "name": "platform" },
* { "name": "version" },
* { "name": "grade" }
* ]
* } );
* } );
*/
"sName": "",
/**
* Defines a data source type for the ordering which can be used to read
* real-time information from the table (updating the internally cached
* version) prior to ordering. This allows ordering to occur on user
* editable elements such as form inputs.
* @type string
* @default std
*
* @name DataTable.defaults.column.orderDataType
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "orderDataType": "dom-text", "targets": [ 2, 3 ] },
* { "type": "numeric", "targets": [ 3 ] },
* { "orderDataType": "dom-select", "targets": [ 4 ] },
* { "orderDataType": "dom-checkbox", "targets": [ 5 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* null,
* null,
* { "orderDataType": "dom-text" },
* { "orderDataType": "dom-text", "type": "numeric" },
* { "orderDataType": "dom-select" },
* { "orderDataType": "dom-checkbox" }
* ]
* } );
* } );
*/
"sSortDataType": "std",
/**
* The title of this column.
* @type string
* @default null <i>Derived from the 'TH' value for this column in the
* original HTML table.</i>
*
* @name DataTable.defaults.column.title
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "title": "My column title", "targets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "title": "My column title" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sTitle": null,
/**
* The type allows you to specify how the data for this column will be
* ordered. Four types (string, numeric, date and html (which will strip
* HTML tags before ordering)) are currently available. Note that only date
* formats understood by Javascript's Date() object will be accepted as type
* date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string',
* 'numeric', 'date' or 'html' (by default). Further types can be adding
* through plug-ins.
* @type string
* @default null <i>Auto-detected from raw data</i>
*
* @name DataTable.defaults.column.type
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "type": "html", "targets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "type": "html" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sType": null,
/**
* Defining the width of the column, this parameter may take any CSS value
* (3em, 20px etc). DataTables applies 'smart' widths to columns which have not
* been given a specific width through this interface ensuring that the table
* remains readable.
* @type string
* @default null <i>Automatic</i>
*
* @name DataTable.defaults.column.width
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "width": "20%", "targets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "width": "20%" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sWidth": null
};
_fnHungarianMap(DataTable.defaults.column);
/**
* DataTables settings object - this holds all the information needed for a
* given table, including configuration, data and current application of the
* table options. DataTables does not have a single instance for each DataTable
* with the settings attached to that instance, but rather instances of the
* DataTable "class" are created on-the-fly as needed (typically by a
* $().dataTable() call) and the settings object is then applied to that
* instance.
*
* Note that this object is related to {@link DataTable.defaults} but this
* one is the internal data store for DataTables's cache of columns. It should
* NOT be manipulated outside of DataTables. Any configuration should be done
* through the initialisation options.
* @namespace
* @todo Really should attach the settings object to individual instances so we
* don't need to create new instances on each $().dataTable() call (if the
* table already exists). It would also save passing oSettings around and
* into every single function. However, this is a very significant
* architecture change for DataTables and will almost certainly break
* backwards compatibility with older installations. This is something that
* will be done in 2.0.
*/
DataTable.models.oSettings = {
/**
* Primary features of DataTables and their enablement state.
* @namespace
*/
"oFeatures": {
/**
* Flag to say if DataTables should automatically try to calculate the
* optimum table and columns widths (true) or not (false).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bAutoWidth": null,
/**
* Delay the creation of TR and TD elements until they are actually
* needed by a driven page draw. This can give a significant speed
* increase for Ajax source and Javascript source data, but makes no
* difference at all fro DOM and server-side processing tables.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bDeferRender": null,
/**
* Enable filtering on the table or not. Note that if this is disabled
* then there is no filtering at all on the table, including fnFilter.
* To just remove the filtering input use sDom and remove the 'f' option.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bFilter": null,
/**
* Table information element (the 'Showing x of y records' div) enable
* flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bInfo": null,
/**
* Present a user control allowing the end user to change the page size
* when pagination is enabled.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bLengthChange": null,
/**
* Pagination enabled or not. Note that if this is disabled then length
* changing must also be disabled.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bPaginate": null,
/**
* Processing indicator enable flag whenever DataTables is enacting a
* user request - typically an Ajax request for server-side processing.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bProcessing": null,
/**
* Server-side processing enabled flag - when enabled DataTables will
* get all data from the server for every draw - there is no filtering,
* sorting or paging done on the client-side.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bServerSide": null,
/**
* Sorting enablement flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSort": null,
/**
* Multi-column sorting
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortMulti": null,
/**
* Apply a class to the columns which are being sorted to provide a
* visual highlight or not. This can slow things down when enabled since
* there is a lot of DOM interaction.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortClasses": null,
/**
* State saving enablement flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bStateSave": null
},
/**
* Scrolling settings for a table.
* @namespace
*/
"oScroll": {
/**
* When the table is shorter in height than sScrollY, collapse the
* table container down to the height of the table (when true).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bCollapse": null,
/**
* Width of the scrollbar for the web-browser's platform. Calculated
* during table initialisation.
* @type int
* @default 0
*/
"iBarWidth": 0,
/**
* Viewport width for horizontal scrolling. Horizontal scrolling is
* disabled if an empty string.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sX": null,
/**
* Width to expand the table to when using x-scrolling. Typically you
* should not need to use this.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @deprecated
*/
"sXInner": null,
/**
* Viewport height for vertical scrolling. Vertical scrolling is disabled
* if an empty string.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sY": null
},
/**
* Language information for the table.
* @namespace
* @extends DataTable.defaults.oLanguage
*/
"oLanguage": {
/**
* Information callback function. See
* {@link DataTable.defaults.fnInfoCallback}
* @type function
* @default null
*/
"fnInfoCallback": null
},
/**
* Browser support parameters
* @namespace
*/
"oBrowser": {
/**
* Indicate if the browser incorrectly calculates width:100% inside a
* scrolling element (IE6/7)
* @type boolean
* @default false
*/
"bScrollOversize": false,
/**
* Determine if the vertical scrollbar is on the right or left of the
* scrolling container - needed for rtl language layout, although not
* all browsers move the scrollbar (Safari).
* @type boolean
* @default false
*/
"bScrollbarLeft": false
},
"ajax": null,
/**
* Array referencing the nodes which are used for the features. The
* parameters of this object match what is allowed by sDom - i.e.
* <ul>
* <li>'l' - Length changing</li>
* <li>'f' - Filtering input</li>
* <li>'t' - The table!</li>
* <li>'i' - Information</li>
* <li>'p' - Pagination</li>
* <li>'r' - pRocessing</li>
* </ul>
* @type array
* @default []
*/
"aanFeatures": [],
/**
* Store data information - see {@link DataTable.models.oRow} for detailed
* information.
* @type array
* @default []
*/
"aoData": [],
/**
* Array of indexes which are in the current display (after filtering etc)
* @type array
* @default []
*/
"aiDisplay": [],
/**
* Array of indexes for display - no filtering
* @type array
* @default []
*/
"aiDisplayMaster": [],
/**
* Store information about each column that is in use
* @type array
* @default []
*/
"aoColumns": [],
/**
* Store information about the table's header
* @type array
* @default []
*/
"aoHeader": [],
/**
* Store information about the table's footer
* @type array
* @default []
*/
"aoFooter": [],
/**
* Store the applied global search information in case we want to force a
* research or compare the old search to a new one.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @namespace
* @extends DataTable.models.oSearch
*/
"oPreviousSearch": {},
/**
* Store the applied search for each column - see
* {@link DataTable.models.oSearch} for the format that is used for the
* filtering information for each column.
* @type array
* @default []
*/
"aoPreSearchCols": [],
/**
* Sorting that is applied to the table. Note that the inner arrays are
* used in the following manner:
* <ul>
* <li>Index 0 - column number</li>
* <li>Index 1 - current sorting direction</li>
* </ul>
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @todo These inner arrays should really be objects
*/
"aaSorting": null,
/**
* Sorting that is always applied to the table (i.e. prefixed in front of
* aaSorting).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @default []
*/
"aaSortingFixed": [],
/**
* Classes to use for the striping of a table.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @default []
*/
"asStripeClasses": null,
/**
* If restoring a table - we should restore its striping classes as well
* @type array
* @default []
*/
"asDestroyStripes": [],
/**
* If restoring a table - we should restore its width
* @type int
* @default 0
*/
"sDestroyWidth": 0,
/**
* Callback functions array for every time a row is inserted (i.e. on a draw).
* @type array
* @default []
*/
"aoRowCallback": [],
/**
* Callback functions for the header on each draw.
* @type array
* @default []
*/
"aoHeaderCallback": [],
/**
* Callback function for the footer on each draw.
* @type array
* @default []
*/
"aoFooterCallback": [],
/**
* Array of callback functions for draw callback functions
* @type array
* @default []
*/
"aoDrawCallback": [],
/**
* Array of callback functions for row created function
* @type array
* @default []
*/
"aoRowCreatedCallback": [],
/**
* Callback functions for just before the table is redrawn. A return of
* false will be used to cancel the draw.
* @type array
* @default []
*/
"aoPreDrawCallback": [],
/**
* Callback functions for when the table has been initialised.
* @type array
* @default []
*/
"aoInitComplete": [],
/**
* Callbacks for modifying the settings to be stored for state saving, prior to
* saving state.
* @type array
* @default []
*/
"aoStateSaveParams": [],
/**
* Callbacks for modifying the settings that have been stored for state saving
* prior to using the stored values to restore the state.
* @type array
* @default []
*/
"aoStateLoadParams": [],
/**
* Callbacks for operating on the settings object once the saved state has been
* loaded
* @type array
* @default []
*/
"aoStateLoaded": [],
/**
* Cache the table ID for quick access
* @type string
* @default <i>Empty string</i>
*/
"sTableId": "",
/**
* The TABLE node for the main table
* @type node
* @default null
*/
"nTable": null,
/**
* Permanent ref to the thead element
* @type node
* @default null
*/
"nTHead": null,
/**
* Permanent ref to the tfoot element - if it exists
* @type node
* @default null
*/
"nTFoot": null,
/**
* Permanent ref to the tbody element
* @type node
* @default null
*/
"nTBody": null,
/**
* Cache the wrapper node (contains all DataTables controlled elements)
* @type node
* @default null
*/
"nTableWrapper": null,
/**
* Indicate if when using server-side processing the loading of data
* should be deferred until the second draw.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
* @default false
*/
"bDeferLoading": false,
/**
* Indicate if all required information has been read in
* @type boolean
* @default false
*/
"bInitialised": false,
/**
* Information about open rows. Each object in the array has the parameters
* 'nTr' and 'nParent'
* @type array
* @default []
*/
"aoOpenRows": [],
/**
* Dictate the positioning of DataTables' control elements - see
* {@link DataTable.model.oInit.sDom}.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default null
*/
"sDom": null,
/**
* Which type of pagination should be used.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default two_button
*/
"sPaginationType": "two_button",
/**
* The state duration (for `stateSave`) in seconds.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type int
* @default 0
*/
"iStateDuration": 0,
/**
* Array of callback functions for state saving. Each array element is an
* object with the following parameters:
* <ul>
* <li>function:fn - function to call. Takes two parameters, oSettings
* and the JSON string to save that has been thus far created. Returns
* a JSON string to be inserted into a json object
* (i.e. '"param": [ 0, 1, 2]')</li>
* <li>string:sName - name of callback</li>
* </ul>
* @type array
* @default []
*/
"aoStateSave": [],
/**
* Array of callback functions for state loading. Each array element is an
* object with the following parameters:
* <ul>
* <li>function:fn - function to call. Takes two parameters, oSettings
* and the object stored. May return false to cancel state loading</li>
* <li>string:sName - name of callback</li>
* </ul>
* @type array
* @default []
*/
"aoStateLoad": [],
/**
* State that was loaded. Useful for back reference
* @type object
* @default null
*/
"oLoadedState": null,
/**
* Source url for AJAX data for the table.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default null
*/
"sAjaxSource": null,
/**
* Property from a given object from which to read the table data from. This
* can be an empty string (when not server-side processing), in which case
* it is assumed an an array is given directly.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sAjaxDataProp": null,
/**
* Note if draw should be blocked while getting data
* @type boolean
* @default true
*/
"bAjaxDataGet": true,
/**
* The last jQuery XHR object that was used for server-side data gathering.
* This can be used for working with the XHR information in one of the
* callbacks
* @type object
* @default null
*/
"jqXHR": null,
/**
* JSON returned from the server in the last Ajax request
* @type object
* @default undefined
*/
"json": undefined,
/**
* Function to get the server-side data.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type function
*/
"fnServerData": null,
/**
* Functions which are called prior to sending an Ajax request so extra
* parameters can easily be sent to the server
* @type array
* @default []
*/
"aoServerParams": [],
/**
* Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
* required).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sServerMethod": null,
/**
* Format numbers for display.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type function
*/
"fnFormatNumber": null,
/**
* List of options that can be used for the user selectable length menu.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @default []
*/
"aLengthMenu": null,
/**
* Counter for the draws that the table does. Also used as a tracker for
* server-side processing
* @type int
* @default 0
*/
"iDraw": 0,
/**
* Indicate if a redraw is being done - useful for Ajax
* @type boolean
* @default false
*/
"bDrawing": false,
/**
* Draw index (iDraw) of the last error when parsing the returned data
* @type int
* @default -1
*/
"iDrawError": -1,
/**
* Paging display length
* @type int
* @default 10
*/
"_iDisplayLength": 10,
/**
* Paging start point - aiDisplay index
* @type int
* @default 0
*/
"_iDisplayStart": 0,
/**
* Server-side processing - number of records in the result set
* (i.e. before filtering), Use fnRecordsTotal rather than
* this property to get the value of the number of records, regardless of
* the server-side processing setting.
* @type int
* @default 0
* @private
*/
"_iRecordsTotal": 0,
/**
* Server-side processing - number of records in the current display set
* (i.e. after filtering). Use fnRecordsDisplay rather than
* this property to get the value of the number of records, regardless of
* the server-side processing setting.
* @type boolean
* @default 0
* @private
*/
"_iRecordsDisplay": 0,
/**
* Flag to indicate if jQuery UI marking and classes should be used.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bJUI": null,
/**
* The classes to use for the table
* @type object
* @default {}
*/
"oClasses": {},
/**
* Flag attached to the settings object so you can check in the draw
* callback if filtering has been done in the draw. Deprecated in favour of
* events.
* @type boolean
* @default false
* @deprecated
*/
"bFiltered": false,
/**
* Flag attached to the settings object so you can check in the draw
* callback if sorting has been done in the draw. Deprecated in favour of
* events.
* @type boolean
* @default false
* @deprecated
*/
"bSorted": false,
/**
* Indicate that if multiple rows are in the header and there is more than
* one unique cell per column, if the top one (true) or bottom one (false)
* should be used for sorting / title by DataTables.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortCellsTop": null,
/**
* Initialisation object that is used for the table
* @type object
* @default null
*/
"oInit": null,
/**
* Destroy callback functions - for plug-ins to attach themselves to the
* destroy so they can clean up markup and events.
* @type array
* @default []
*/
"aoDestroyCallback": [],
/**
* Get the number of records in the current record set, before filtering
* @type function
*/
"fnRecordsTotal": function () {
return _fnDataSource(this) == 'ssp' ?
this._iRecordsTotal * 1 :
this.aiDisplayMaster.length;
},
/**
* Get the number of records in the current record set, after filtering
* @type function
*/
"fnRecordsDisplay": function () {
return _fnDataSource(this) == 'ssp' ?
this._iRecordsDisplay * 1 :
this.aiDisplay.length;
},
/**
* Get the display end point - aiDisplay index
* @type function
*/
"fnDisplayEnd": function () {
var
len = this._iDisplayLength,
start = this._iDisplayStart,
calc = start + len,
records = this.aiDisplay.length,
features = this.oFeatures,
paginate = features.bPaginate;
if (features.bServerSide) {
return paginate === false || len === -1 ?
start + records :
Math.min(start + len, this._iRecordsDisplay);
}
else {
return !paginate || calc > records || len === -1 ?
records :
calc;
}
},
/**
* The DataTables object for this table
* @type object
* @default null
*/
"oInstance": null,
/**
* Unique identifier for each instance of the DataTables object. If there
* is an ID on the table node, then it takes that value, otherwise an
* incrementing internal counter is used.
* @type string
* @default null
*/
"sInstance": null,
/**
* tabindex attribute value that is added to DataTables control elements, allowing
* keyboard navigation of the table and its controls.
*/
"iTabIndex": 0,
/**
* DIV container for the footer scrolling table if scrolling
*/
"nScrollHead": null,
/**
* DIV container for the footer scrolling table if scrolling
*/
"nScrollFoot": null,
/**
* Last applied sort
* @type array
* @default []
*/
"aLastSort": [],
/**
* Stored plug-in instances
* @type object
* @default {}
*/
"oPlugins": {}
};
/**
* Extension object for DataTables that is used to provide all extension
* options.
*
* Note that the `DataTable.ext` object is available through
* `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is
* also aliased to `jQuery.fn.dataTableExt` for historic reasons.
* @namespace
* @extends DataTable.models.ext
*/
/**
* DataTables extensions
*
* This namespace acts as a collection area for plug-ins that can be used to
* extend DataTables capabilities. Indeed many of the build in methods
* use this method to provide their own capabilities (sorting methods for
* example).
*
* Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy
* reasons
*
* @namespace
*/
DataTable.ext = _ext = {
/**
* Element class names
*
* @type object
* @default {}
*/
classes: {},
/**
* Error reporting.
*
* How should DataTables report an error. Can take the value 'alert' or
* 'throw'
*
* @type string
* @default alert
*/
errMode: "alert",
/**
* Feature plug-ins.
*
* This is an array of objects which describe the feature plug-ins that are
* available to DataTables. These feature plug-ins are then available for
* use through the `dom` initialisation option.
*
* Each feature plug-in is described by an object which must have the
* following properties:
*
* * `fnInit` - function that is used to initialise the plug-in,
* * `cFeature` - a character so the feature can be enabled by the `dom`
* instillation option. This is case sensitive.
*
* The `fnInit` function has the following input parameters:
*
* 1. `{object}` DataTables settings object: see
* {@link DataTable.models.oSettings}
*
* And the following return is expected:
*
* * {node|null} The element which contains your feature. Note that the
* return may also be void if your plug-in does not require to inject any
* DOM elements into DataTables control (`dom`) - for example this might
* be useful when developing a plug-in which allows table control via
* keyboard entry
*
* @type array
*
* @example
* $.fn.dataTable.ext.features.push( {
* "fnInit": function( oSettings ) {
* return new TableTools( { "oDTSettings": oSettings } );
* },
* "cFeature": "T"
* } );
*/
feature: [],
/**
* Row searching.
*
* This method of searching is complimentary to the default type based
* searching, and a lot more comprehensive as it allows you complete control
* over the searching logic. Each element in this array is a function
* (parameters described below) that is called for every row in the table,
* and your logic decides if it should be included in the searching data set
* or not.
*
* Searching functions have the following input parameters:
*
* 1. `{object}` DataTables settings object: see
* {@link DataTable.models.oSettings}
* 2. `{array|object}` Data for the row to be processed (same as the
* original format that was passed in as the data source, or an array
* from a DOM data source
* 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which
* can be useful to retrieve the `TR` element if you need DOM interaction.
*
* And the following return is expected:
*
* * {boolean} Include the row in the searched result set (true) or not
* (false)
*
* Note that as with the main search ability in DataTables, technically this
* is "filtering", since it is subtractive. However, for consistency in
* naming we call it searching here.
*
* @type array
* @default []
*
* @example
* // The following example shows custom search being applied to the
* // fourth column (i.e. the data[3] index) based on two input values
* // from the end-user, matching the data in a certain range.
* $.fn.dataTable.ext.search.push(
* function( settings, data, dataIndex ) {
* var min = document.getElementById('min').value * 1;
* var max = document.getElementById('max').value * 1;
* var version = data[3] == "-" ? 0 : data[3]*1;
*
* if ( min == "" && max == "" ) {
* return true;
* }
* else if ( min == "" && version < max ) {
* return true;
* }
* else if ( min < version && "" == max ) {
* return true;
* }
* else if ( min < version && version < max ) {
* return true;
* }
* return false;
* }
* );
*/
search: [],
/**
* Internal functions, exposed for used in plug-ins.
*
* Please note that you should not need to use the internal methods for
* anything other than a plug-in (and even then, try to avoid if possible).
* The internal function may change between releases.
*
* @type object
* @default {}
*/
internal: {},
/**
* Legacy configuration options. Enable and disable legacy options that
* are available in DataTables.
*
* @type object
*/
legacy: {
/**
* Enable / disable DataTables 1.9 compatible server-side processing
* requests
*
* @type boolean
* @default false
*/
ajax: false
},
/**
* Pagination plug-in methods.
*
* Each entry in this object is a function and defines which buttons should
* be shown by the pagination rendering method that is used for the table:
* {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the
* buttons are displayed in the document, while the functions here tell it
* what buttons to display. This is done by returning an array of button
* descriptions (what each button will do).
*
* Pagination types (the four built in options and any additional plug-in
* options defined here) can be used through the `paginationType`
* initialisation parameter.
*
* The functions defined take two parameters:
*
* 1. `{int} page` The current page index
* 2. `{int} pages` The number of pages in the table
*
* Each function is expected to return an array where each element of the
* array can be one of:
*
* * `first` - Jump to first page when activated
* * `last` - Jump to last page when activated
* * `previous` - Show previous page when activated
* * `next` - Show next page when activated
* * `{int}` - Show page of the index given
* * `{array}` - A nested array containing the above elements to add a
* containing 'DIV' element (might be useful for styling).
*
* Note that DataTables v1.9- used this object slightly differently whereby
* an object with two functions would be defined for each plug-in. That
* ability is still supported by DataTables 1.10+ to provide backwards
* compatibility, but this option of use is now decremented and no longer
* documented in DataTables 1.10+.
*
* @type object
* @default {}
*
* @example
* // Show previous, next and current page buttons only
* $.fn.dataTableExt.oPagination.current = function ( page, pages ) {
* return [ 'previous', page, 'next' ];
* };
*/
pager: {},
renderer: {
pageButton: {},
header: {}
},
/**
* Ordering plug-ins - custom data source
*
* The extension options for ordering of data available here is complimentary
* to the default type based ordering that DataTables typically uses. It
* allows much greater control over the the data that is being used to
* order a column, but is necessarily therefore more complex.
*
* This type of ordering is useful if you want to do ordering based on data
* live from the DOM (for example the contents of an 'input' element) rather
* than just the static string that DataTables knows of.
*
* The way these plug-ins work is that you create an array of the values you
* wish to be ordering for the column in question and then return that
* array. The data in the array much be in the index order of the rows in
* the table (not the currently ordering order!). Which order data gathering
* function is run here depends on the `dt-init columns.orderDataType`
* parameter that is used for the column (if any).
*
* The functions defined take two parameters:
*
* 1. `{object}` DataTables settings object: see
* {@link DataTable.models.oSettings}
* 2. `{int}` Target column index
*
* Each function is expected to return an array:
*
* * `{array}` Data for the column to be ordering upon
*
* @type array
*
* @example
* // Ordering using `input` node values
* $.fn.dataTable.ext.order['dom-text'] = function ( settings, col )
* {
* return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
* return $('input', td).val();
* } );
* }
*/
order: {},
/**
* Type based plug-ins.
*
* Each column in DataTables has a type assigned to it, either by automatic
* detection or by direct assignment using the `type` option for the column.
* The type of a column will effect how it is ordering and search (plug-ins
* can also make use of the column type if required).
*
* @namespace
*/
type: {
/**
* Type detection functions.
*
* The functions defined in this object are used to automatically detect
* a column's type, making initialisation of DataTables super easy, even
* when complex data is in the table.
*
* The functions defined take a single parameter:
*
* 1. `{*}` Data from the column cell to be analysed
*
* Each function is expected to return:
*
* * `{string|null}` Data type detected, or null if unknown (and thus
* pass it on to the other type detection functions.
*
* @type array
*
* @example
* // Currency type detection plug-in:
* $.fn.dataTable.ext.type.detect.push(
* function ( data ) {
* // Check the numeric part
* if ( ! $.isNumeric( data.substring(1) ) ) {
* return null;
* }
*
* // Check prefixed by currency
* if ( data.charAt(0) == '$' || data.charAt(0) == '£' ) {
* return 'currency';
* }
* return null;
* }
* );
*/
detect: [],
/**
* Type based search formatting.
*
* The type based searching functions can be used to pre-format the
* data to be search on. For example, it can be used to strip HTML
* tags or to de-format telephone numbers for numeric only searching.
*
* Note that is a search is not defined for a column of a given type,
* no search formatting will be performed.
*
* Pre-processing of searching data plug-ins - When you assign the sType
* for a column (or have it automatically detected for you by DataTables
* or a type detection plug-in), you will typically be using this for
* custom sorting, but it can also be used to provide custom searching
* by allowing you to pre-processing the data and returning the data in
* the format that should be searched upon. This is done by adding
* functions this object with a parameter name which matches the sType
* for that target column. This is the corollary of <i>afnSortData</i>
* for searching data.
*
* The functions defined take a single parameter:
*
* 1. `{*}` Data from the column cell to be prepared for searching
*
* Each function is expected to return:
*
* * `{string|null}` Formatted string that will be used for the searching.
*
* @type object
* @default {}
*
* @example
* $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
* return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
* }
*/
search: {},
/**
* Type based ordering.
*
* The column type tells DataTables what ordering to apply to the table
* when a column is sorted upon. The order for each type that is defined,
* is defined by the functions available in this object.
*
* Each ordering option can be described by three properties added to
* this object:
*
* * `{type}-pre` - Pre-formatting function
* * `{type}-asc` - Ascending order function
* * `{type}-desc` - Descending order function
*
* All three can be used together, only `{type}-pre` or only
* `{type}-asc` and `{type}-desc` together. It is generally recommended
* that only `{type}-pre` is used, as this provides the optimal
* implementation in terms of speed, although the others are provided
* for compatibility with existing Javascript sort functions.
*
* `{type}-pre`: Functions defined take a single parameter:
*
* 1. `{*}` Data from the column cell to be prepared for ordering
*
* And return:
*
* * `{*}` Data to be sorted upon
*
* `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort
* functions, taking two parameters:
*
* 1. `{*}` Data to compare to the second parameter
* 2. `{*}` Data to compare to the first parameter
*
* And returning:
*
* * `{*}` Ordering match: <0 if first parameter should be sorted lower
* than the second parameter, ===0 if the two parameters are equal and
* >0 if the first parameter should be sorted height than the second
* parameter.
*
* @type object
* @default {}
*
* @example
* // Numeric ordering of formatted numbers with a pre-formatter
* $.extend( $.fn.dataTable.ext.type.order, {
* "string-pre": function(x) {
* a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" );
* return parseFloat( a );
* }
* } );
*
* @example
* // Case-sensitive string ordering, with no pre-formatting method
* $.extend( $.fn.dataTable.ext.order, {
* "string-case-asc": function(x,y) {
* return ((x < y) ? -1 : ((x > y) ? 1 : 0));
* },
* "string-case-desc": function(x,y) {
* return ((x < y) ? 1 : ((x > y) ? -1 : 0));
* }
* } );
*/
order: {}
},
/**
* Unique DataTables instance counter
*
* @type int
* @private
*/
_unique: 0,
//
// Depreciated
// The following properties are retained for backwards compatiblity only.
// The should not be used in new projects and will be removed in a future
// version
//
/**
* Version check function.
* @type function
* @depreciated Since 1.10
*/
fnVersionCheck: DataTable.fnVersionCheck,
/**
* Index for what 'this' index API functions should use
* @type int
* @deprecated Since v1.10
*/
iApiIndex: 0,
/**
* jQuery UI class container
* @type object
* @deprecated Since v1.10
*/
oJUIClasses: {},
/**
* Software version
* @type string
* @deprecated Since v1.10
*/
sVersion: DataTable.version
};
//
// Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts
//
$.extend(_ext, {
afnFiltering: _ext.filter,
aTypes: _ext.type.detect,
ofnSearch: _ext.type.search,
oSort: _ext.type.order,
afnSortData: _ext.order,
aoFeatures: _ext.feature,
oApi: _ext.internal,
oStdClasses: _ext.classes,
oPagination: _ext.pager
});
$.extend(DataTable.ext.classes, {
"sTable": "dataTable",
"sNoFooter": "no-footer",
/* Paging buttons */
"sPageButton": "paginate_button",
"sPageButtonActive": "current",
"sPageButtonDisabled": "disabled",
/* Striping classes */
"sStripeOdd": "odd",
"sStripeEven": "even",
/* Empty row */
"sRowEmpty": "dataTables_empty",
/* Features */
"sWrapper": "dataTables_wrapper",
"sFilter": "dataTables_filter",
"sInfo": "dataTables_info",
"sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */
"sLength": "dataTables_length",
"sProcessing": "dataTables_processing",
/* Sorting */
"sSortAsc": "sorting_asc",
"sSortDesc": "sorting_desc",
"sSortable": "sorting", /* Sortable in both directions */
"sSortableAsc": "sorting_asc_disabled",
"sSortableDesc": "sorting_desc_disabled",
"sSortableNone": "sorting_disabled",
"sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */
/* Filtering */
"sFilterInput": "",
/* Page length */
"sLengthSelect": "",
/* Scrolling */
"sScrollWrapper": "dataTables_scroll",
"sScrollHead": "dataTables_scrollHead",
"sScrollHeadInner": "dataTables_scrollHeadInner",
"sScrollBody": "dataTables_scrollBody",
"sScrollFoot": "dataTables_scrollFoot",
"sScrollFootInner": "dataTables_scrollFootInner",
/* Misc */
"sHeaderTH": "",
"sFooterTH": "",
// Deprecated
"sSortJUIAsc": "",
"sSortJUIDesc": "",
"sSortJUI": "",
"sSortJUIAscAllowed": "",
"sSortJUIDescAllowed": "",
"sSortJUIWrapper": "",
"sSortIcon": "",
"sJUIHeader": "",
"sJUIFooter": ""
});
(function () {
// Reused strings for better compression. Closure compiler appears to have a
// weird edge case where it is trying to expand strings rather than use the
// variable version. This results in about 200 bytes being added, for very
// little preference benefit since it this run on script load only.
var _empty = '';
_empty = '';
var _stateDefault = _empty + 'ui-state-default';
var _sortIcon = _empty + 'css_right ui-icon ui-icon-';
var _headerFooter = _empty + 'fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix';
$.extend(DataTable.ext.oJUIClasses, DataTable.ext.classes, {
/* Full numbers paging buttons */
"sPageButton": "fg-button ui-button " + _stateDefault,
"sPageButtonActive": "ui-state-disabled",
"sPageButtonDisabled": "ui-state-disabled",
/* Features */
"sPaging": "dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi " +
"ui-buttonset-multi paging_", /* Note that the type is postfixed */
/* Sorting */
"sSortAsc": _stateDefault + " sorting_asc",
"sSortDesc": _stateDefault + " sorting_desc",
"sSortable": _stateDefault + " sorting",
"sSortableAsc": _stateDefault + " sorting_asc_disabled",
"sSortableDesc": _stateDefault + " sorting_desc_disabled",
"sSortableNone": _stateDefault + " sorting_disabled",
"sSortJUIAsc": _sortIcon + "triangle-1-n",
"sSortJUIDesc": _sortIcon + "triangle-1-s",
"sSortJUI": _sortIcon + "carat-2-n-s",
"sSortJUIAscAllowed": _sortIcon + "carat-1-n",
"sSortJUIDescAllowed": _sortIcon + "carat-1-s",
"sSortJUIWrapper": "DataTables_sort_wrapper",
"sSortIcon": "DataTables_sort_icon",
/* Scrolling */
"sScrollHead": "dataTables_scrollHead " + _stateDefault,
"sScrollFoot": "dataTables_scrollFoot " + _stateDefault,
/* Misc */
"sHeaderTH": _stateDefault,
"sFooterTH": _stateDefault,
"sJUIHeader": _headerFooter + " ui-corner-tl ui-corner-tr",
"sJUIFooter": _headerFooter + " ui-corner-bl ui-corner-br"
});
}());
var extPagination = DataTable.ext.pager;
function _numbers(page, pages) {
var
numbers = [],
buttons = extPagination.numbers_length,
half = Math.floor(buttons / 2),
i = 1;
if (pages <= buttons) {
numbers = _range(0, pages);
}
else if (page <= half) {
numbers = _range(0, buttons - 2);
numbers.push('ellipsis');
numbers.push(pages - 1);
}
else if (page >= pages - 1 - half) {
numbers = _range(pages - (buttons - 2), pages);
numbers.splice(0, 0, 'ellipsis'); // no unshift in ie6
numbers.splice(0, 0, 0);
}
else {
numbers = _range(page - 1, page + 2);
numbers.push('ellipsis');
numbers.push(pages - 1);
numbers.splice(0, 0, 'ellipsis');
numbers.splice(0, 0, 0);
}
numbers.DT_el = 'span';
return numbers;
}
$.extend(extPagination, {
simple: function (page, pages) {
return ['previous', 'next'];
},
full: function (page, pages) {
return ['first', 'previous', 'next', 'last'];
},
simple_numbers: function (page, pages) {
return ['previous', _numbers(page, pages), 'next'];
},
full_numbers: function (page, pages) {
return ['first', 'previous', _numbers(page, pages), 'next', 'last'];
},
// For testing and plug-ins to use
_numbers: _numbers,
numbers_length: 7
});
$.extend(true, DataTable.ext.renderer, {
pageButton: {
_: function (settings, host, idx, buttons, page, pages) {
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass;
var attach = function (container, buttons) {
var i, ien, node, button;
var clickHandler = function (e) {
_fnPageChange(settings, e.data.action, true);
};
for (i = 0, ien = buttons.length; i < ien; i++) {
button = buttons[i];
if ($.isArray(button)) {
var inner = $('<' + (button.DT_el || 'div') + '/>')
.appendTo(container);
attach(inner, button);
}
else {
btnDisplay = '';
btnClass = '';
switch (button) {
case 'ellipsis':
container.append('<span>…</span>');
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ?
'' : ' ' + classes.sPageButtonDisabled);
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ?
'' : ' ' + classes.sPageButtonDisabled);
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages - 1 ?
'' : ' ' + classes.sPageButtonDisabled);
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages - 1 ?
'' : ' ' + classes.sPageButtonDisabled);
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
classes.sPageButtonActive : '';
break;
}
if (btnDisplay) {
node = $('<a>', {
'class': classes.sPageButton + ' ' + btnClass,
'aria-controls': settings.sTableId,
'tabindex': settings.iTabIndex,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId + '_' + button :
null
})
.html(btnDisplay)
.appendTo(container);
_fnBindAction(
node, {action: button}, clickHandler
);
}
}
}
};
attach($(host).empty(), buttons);
}
}
});
var __numericReplace = function (d, re1, re2) {
if (!d || d === '-') {
return -Infinity;
}
if (d.replace) {
if (re1) {
d = d.replace(re1, '');
}
if (re2) {
d = d.replace(re2, '');
}
}
return d * 1;
};
$.extend(DataTable.ext.type.order, {
// Dates
"date-pre": function (d) {
return Date.parse(d) || 0;
},
// Plain numbers
"numeric-pre": function (d) {
return __numericReplace(d);
},
// Formatted numbers
"numeric-fmt-pre": function (d) {
return __numericReplace(d, _re_formatted_numeric);
},
// HTML numeric
"html-numeric-pre": function (d) {
return __numericReplace(d, _re_html);
},
// HTML numeric, formatted
"html-numeric-fmt-pre": function (d) {
return __numericReplace(d, _re_html, _re_formatted_numeric);
},
// html
"html-pre": function (a) {
return a.replace ?
a.replace(/<.*?>/g, "").toLowerCase() :
a + '';
},
// string
"string-pre": function (a) {
return typeof a === 'string' ?
a.toLowerCase() :
!a || !a.toString ?
'' :
a.toString();
},
// string-asc and -desc are retained only for compatibility with the old
// sort methods
"string-asc": function (x, y) {
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
},
"string-desc": function (x, y) {
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}
});
// Built in type detection. See model.ext.aTypes for information about
// what is required from this methods.
$.extend(DataTable.ext.type.detect, [
// Plain numbers - first since V8 detects some plain numbers as dates
// e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...).
function (d) {
return _isNumber(d) ? 'numeric' : null;
},
// Dates (only those recognised by the browser's Date.parse)
function (d) {
// V8 will remove any unknown characters at the start of the expression,
// leading to false matches such as `$245.12` being a valid date. See
// forum thread 18941 for detail.
if (d && !_re_date_start.test(d)) {
return null;
}
var parsed = Date.parse(d);
return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null;
},
// Formatted numbers
function (d) {
return _isNumber(d, true) ? 'numeric-fmt' : null;
},
// HTML numeric
function (d) {
return _htmlNumeric(d) ? 'html-numeric' : null;
},
// HTML numeric, formatted
function (d) {
return _htmlNumeric(d, true) ? 'html-numeric-fmt' : null;
},
// HTML (this is strict checking - there much be html)
function (d) {
return _empty(d) || (typeof d === 'string' && d.indexOf('<') !== -1) ?
'html' : null;
}
]);
// Filter formatting functions. See model.ext.ofnSearch for information about
// what is required from these methods.
$.extend(DataTable.ext.type.search, {
html: function (data) {
return _empty(data) ?
'' :
typeof data === 'string' ?
data
.replace(_re_new_lines, " ")
.replace(_re_html, "") :
'';
},
string: function (data) {
return _empty(data) ?
'' :
typeof data === 'string' ?
data.replace(_re_new_lines, " ") :
data;
}
});
$.extend(true, DataTable.ext.renderer, {
header: {
_: function (settings, cell, column, idx, classes) {
// No additional mark-up required
// Attach a sort listener to update on sort
$(settings.nTable).on('order.dt', function (e, settings, sorting, columns) {
cell
.removeClass(
column.sSortingClass + ' ' +
classes.sSortAsc + ' ' +
classes.sSortDesc
)
.addClass(columns[idx] == 'asc' ?
classes.sSortAsc : columns[idx] == 'desc' ?
classes.sSortDesc :
column.sSortingClass
);
});
},
jqueryui: function (settings, cell, column, idx, classes) {
$('<div/>')
.addClass(classes.sSortJUIWrapper)
.append(cell.contents())
.append($('<span/>')
.addClass(classes.sSortIcon + ' ' + column.sSortingClassJUI)
)
.appendTo(cell);
// Attach a sort listener to update on sort
$(settings.nTable).on('order.dt', function (e, settings, sorting, columns) {
cell
.removeClass(classes.sSortAsc + " " + classes.sSortDesc)
.addClass(columns[idx] == 'asc' ?
classes.sSortAsc : columns[idx] == 'desc' ?
classes.sSortDesc :
column.sSortingClass
);
cell
.find('span')
.removeClass(
classes.sSortJUIAsc + " " +
classes.sSortJUIDesc + " " +
classes.sSortJUI + " " +
classes.sSortJUIAscAllowed + " " +
classes.sSortJUIDescAllowed
)
.addClass(columns[idx] == 'asc' ?
classes.sSortJUIAsc : columns[idx] == 'desc' ?
classes.sSortJUIDesc :
column.sSortingClassJUI
);
});
}
}
});
// jQuery access
$.fn.dataTable = DataTable;
// Legacy aliases
$.fn.dataTableSettings = DataTable.settings;
$.fn.dataTableExt = DataTable.ext;
// With a capital `D` we return a DataTables API instance rather than a
// jQuery object
$.fn.DataTable = function (opts) {
return $(this).dataTable(opts).api();
};
// All properties that are available to $.fn.dataTable should also be
// available on $.fn.DataTable
$.each(DataTable, function (prop, val) {
$.fn.DataTable[prop] = val;
});
// Information about events fired by DataTables - for documentation.
/**
* Draw event, fired whenever the table is redrawn on the page, at the same
* point as fnDrawCallback. This may be useful for binding events or
* performing calculations when the table is altered at all.
* @name DataTable#draw.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Search event, fired when the searching applied to the table (using the
* built-in global search, or column filters) is altered.
* @name DataTable#search.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Page change event, fired when the paging of the table is altered.
* @name DataTable#page.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Order event, fired when the ordering applied to the table is altered.
* @name DataTable#order.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* DataTables initialisation complete event, fired when the table is fully
* drawn, including Ajax data loaded, if Ajax data is required.
* @name DataTable#init.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The JSON object request from the server - only
* present if client-side Ajax sourced data is used</li></ol>
*/
/**
* State save event, fired when the table has changed state a new state save
* is required. This event allows modification of the state saving object
* prior to actually doing the save, including addition or other state
* properties (for plug-ins) or modification of a DataTables core property.
* @name DataTable#stateSaveParams.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The state information to be saved
*/
/**
* State load event, fired when the table is loading state from the stored
* data, but prior to the settings object being modified by the saved state
* - allowing modification of the saved state is required or loading of
* state for a plug-in.
* @name DataTable#stateLoadParams.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The saved state information
*/
/**
* State loaded event, fired when state has been loaded from stored data and
* the settings object has been modified by the loaded data.
* @name DataTable#stateLoaded.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The saved state information
*/
/**
* Processing event, fired when DataTables is doing some kind of processing
* (be it, order, searcg or anything else). It can be used to indicate to
* the end user that there is something happening, or that something has
* finished.
* @name DataTable#processing.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {boolean} bShow Flag for if DataTables is doing processing or not
*/
/**
* Ajax (XHR) event, fired whenever an Ajax request is completed from a
* request to made to the server for new data. This event is called before
* DataTables processed the returned data, so it can also be used to pre-
* process the data returned from the server, if needed.
*
* Note that this trigger is called in `fnServerData`, if you override
* `fnServerData` and which to use this event, you need to trigger it in you
* success function.
* @name DataTable#xhr.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
* @param {object} json JSON returned from the server
*
* @example
* // Use a custom property returned from the server in another DOM element
* $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
* $('#status').html( json.status );
* } );
*
* @example
* // Pre-process the data returned from the server
* $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
* for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) {
* json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;
* }
* // Note no return - manipulate the data directly in the JSON object.
* } );
*/
/**
* Destroy event, fired when the DataTable is destroyed by calling fnDestroy
* or passing the bDestroy:true parameter in the initialisation object. This
* can be used to remove bound events, added DOM nodes, etc.
* @name DataTable#destroy.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Page length change event, fired when number of records to show on each
* page (the length) is changed.
* @name DataTable#length.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
* @param {integer} len New length
*/
/**
* Column sizing has changed.
* @name DataTable#column-sizing.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Column visibility has changed.
* @name DataTable#column-visibility.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
* @param {int} column Column index
* @param {bool} vis `false` if column now hidden, or `true` if visible
*/
}));
}(window, document, jQuery));
/* Set the defaults for DataTables initialisation */
$.extend(true, $.fn.dataTable.defaults, {
"sDom": "<'row'<'col-sm-6'l><'col-sm-6'f>r>" + "t" + "<'row'<'col-sm-6'i><'col-sm-6'p>>",
"oLanguage": {
"sLengthMenu": "_MENU_ records per page"
}
});
/* Default class modification */
$.extend($.fn.dataTableExt.oStdClasses, {
"sWrapper": "dataTables_wrapper form-inline",
"sFilterInput": "form-control input-sm",
"sLengthSelect": "form-control input-sm"
});
// In 1.10 we use the pagination renderers to draw the Bootstrap paging,
// rather than custom plug-in
if ($.fn.dataTable.Api) {
$.fn.dataTable.defaults.renderer = 'bootstrap';
$.fn.dataTable.ext.renderer.pageButton.bootstrap = function (settings, host, idx, buttons, page, pages) {
var api = new $.fn.dataTable.Api(settings);
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var btnDisplay, btnClass;
var attach = function (container, buttons) {
var i, ien, node, button;
var clickHandler = function (e) {
e.preventDefault();
if (e.data.action !== 'ellipsis') {
api.page(e.data.action).draw(false);
}
};
for (i = 0, ien = buttons.length; i < ien; i++) {
button = buttons[i];
if ($.isArray(button)) {
attach(container, button);
} else {
btnDisplay = '';
btnClass = '';
switch (button) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages - 1 ?
'' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages - 1 ?
'' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if (btnDisplay) {
node = $('<li>', {
'class': classes.sPageButton + ' ' + btnClass,
'aria-controls': settings.sTableId,
'tabindex': settings.iTabIndex,
'id': idx === 0 && typeof button === 'string' ? settings.sTableId + '_' + button : null
})
.append($('<a>', {
'href': '#'
})
.html(btnDisplay)
)
.appendTo(container);
settings.oApi._fnBindAction(
node, {
action: button
}, clickHandler
);
}
}
}
};
attach(
$(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
}
} else {
// Integration for 1.9-
$.fn.dataTable.defaults.sPaginationType = 'bootstrap';
/* API method to get paging information */
$.fn.dataTableExt.oApi.fnPagingInfo = function (oSettings) {
return {
"iStart": oSettings._iDisplayStart,
"iEnd": oSettings.fnDisplayEnd(),
"iLength": oSettings._iDisplayLength,
"iTotal": oSettings.fnRecordsTotal(),
"iFilteredTotal": oSettings.fnRecordsDisplay(),
"iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength),
"iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength)
};
};
/* Bootstrap style pagination control */
$.extend($.fn.dataTableExt.oPagination, {
"bootstrap": {
"fnInit": function (oSettings, nPaging, fnDraw) {
var oLang = oSettings.oLanguage.oPaginate;
var fnClickHandler = function (e) {
e.preventDefault();
if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) {
fnDraw(oSettings);
}
};
$(nPaging).append(
'<ul class="pagination">' +
'<li class="prev disabled"><a href="#">← ' + oLang.sPrevious + '</a></li>' +
'<li class="next disabled"><a href="#">' + oLang.sNext + ' → </a></li>' +
'</ul>'
);
var els = $('a', nPaging);
$(els[0]).bind('click.DT', {
action: "previous"
}, fnClickHandler);
$(els[1]).bind('click.DT', {
action: "next"
}, fnClickHandler);
},
"fnUpdate": function (oSettings, fnDraw) {
var iListLength = 5;
var oPaging = oSettings.oInstance.fnPagingInfo();
var an = oSettings.aanFeatures.p;
var i, ien, j, sClass, iStart, iEnd, iHalf = Math.floor(iListLength / 2);
if (oPaging.iTotalPages < iListLength) {
iStart = 1;
iEnd = oPaging.iTotalPages;
} else if (oPaging.iPage <= iHalf) {
iStart = 1;
iEnd = iListLength;
} else if (oPaging.iPage >= (oPaging.iTotalPages - iHalf)) {
iStart = oPaging.iTotalPages - iListLength + 1;
iEnd = oPaging.iTotalPages;
} else {
iStart = oPaging.iPage - iHalf + 1;
iEnd = iStart + iListLength - 1;
}
for (i = 0, ien = an.length; i < ien; i++) {
// Remove the middle elements
$('li:gt(0)', an[i]).filter(':not(:last)').remove();
// Add the new list items and their event handlers
for (j = iStart; j <= iEnd; j++) {
sClass = (j == oPaging.iPage + 1) ? 'class="active"' : '';
$('<li ' + sClass + '><a href="#">' + j + '</a></li>')
.insertBefore($('li:last', an[i])[0])
.bind('click', function (e) {
e.preventDefault();
oSettings._iDisplayStart = (parseInt($('a', this).text(), 10) - 1) * oPaging.iLength;
fnDraw(oSettings);
});
}
// Add / remove disabled classes from the static elements
if (oPaging.iPage === 0) {
$('li:first', an[i]).addClass('disabled');
} else {
$('li:first', an[i]).removeClass('disabled');
}
if (oPaging.iPage === oPaging.iTotalPages - 1 || oPaging.iTotalPages === 0) {
$('li:last', an[i]).addClass('disabled');
} else {
$('li:last', an[i]).removeClass('disabled');
}
}
}
}
});
}
/*
* TableTools Bootstrap compatibility
* Required TableTools 2.1+
*/
if ($.fn.DataTable.TableTools) {
// Set the classes that TableTools uses to something suitable for Bootstrap
$.extend(true, $.fn.DataTable.TableTools.classes, {
"container": "DTTT btn-group",
"buttons": {
"normal": "btn btn-default",
"disabled": "disabled"
},
"collection": {
"container": "DTTT_dropdown dropdown-menu",
"buttons": {
"normal": "",
"disabled": "disabled"
}
},
"print": {
"info": "DTTT_print_info modal"
},
"select": {
"row": "active"
}
});
// Have the collection use a bootstrap compatible dropdown
$.extend(true, $.fn.DataTable.TableTools.DEFAULTS.oTags, {
"collection": {
"container": "ul",
"button": "li",
"liner": "a"
}
});
}
/*! TableTools 2.2.3
* 2009-2014 SpryMedia Ltd - datatables.net/license
*
* ZeroClipboard 1.0.4
* Author: Joseph Huckaby - MIT licensed
*/
/**
* @summary TableTools
* @description Tools and buttons for DataTables
* @version 2.2.3
* @file dataTables.tableTools.js
* @author SpryMedia Ltd (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
* @copyright Copyright 2009-2014 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license/mit
*
* This source file 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 license files for details.
*
* For details please refer to: http://www.datatables.net
*/
/* Global scope for TableTools for backwards compatibility.
* Will be removed in 2.3
*/
var TableTools;
(function (window, document, undefined) {
var factory = function ($, DataTable) {
"use strict";
//include ZeroClipboard.js
/* ZeroClipboard 1.0.4
* Author: Joseph Huckaby
*/
var ZeroClipboard_TableTools = {
version: "1.0.4-TableTools2",
clients: {}, // registered upload clients on page, indexed by id
moviePath: '', // URL to movie
nextId: 1, // ID of next movie
$: function (thingy) {
// simple DOM lookup utility function
if (typeof(thingy) == 'string') {
thingy = document.getElementById(thingy);
}
if (!thingy.addClass) {
// extend element with a few useful methods
thingy.hide = function () {
this.style.display = 'none';
};
thingy.show = function () {
this.style.display = '';
};
thingy.addClass = function (name) {
this.removeClass(name);
this.className += ' ' + name;
};
thingy.removeClass = function (name) {
this.className = this.className.replace(new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, '');
};
thingy.hasClass = function (name) {
return !!this.className.match(new RegExp("\\s*" + name + "\\s*"));
};
}
return thingy;
},
setMoviePath: function (path) {
// set path to ZeroClipboard.swf
this.moviePath = path;
},
dispatch: function (id, eventName, args) {
// receive event from flash movie, send to client
var client = this.clients[id];
if (client) {
client.receiveEvent(eventName, args);
}
},
register: function (id, client) {
// register new client to receive events
this.clients[id] = client;
},
getDOMObjectPosition: function (obj) {
// get absolute coordinates for dom element
var info = {
left: 0,
top: 0,
width: obj.width ? obj.width : obj.offsetWidth,
height: obj.height ? obj.height : obj.offsetHeight
};
if (obj.style.width !== "") {
info.width = obj.style.width.replace("px", "");
}
if (obj.style.height !== "") {
info.height = obj.style.height.replace("px", "");
}
while (obj) {
info.left += obj.offsetLeft;
info.top += obj.offsetTop;
obj = obj.offsetParent;
}
return info;
},
Client: function (elem) {
// constructor for new simple upload client
this.handlers = {};
// unique ID
this.id = ZeroClipboard_TableTools.nextId++;
this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id;
// register client with singleton to receive flash events
ZeroClipboard_TableTools.register(this.id, this);
// create movie
if (elem) {
this.glue(elem);
}
}
};
ZeroClipboard_TableTools.Client.prototype = {
id: 0, // unique ID for us
ready: false, // whether movie is ready to receive events or not
movie: null, // reference to movie object
clipText: '', // text to copy to clipboard
fileName: '', // default file save name
action: 'copy', // action to perform
handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
cssEffects: true, // enable CSS mouse effects on dom container
handlers: null, // user event handlers
sized: false,
glue: function (elem, title) {
// glue to DOM element
// elem can be ID or actual DOM element object
this.domElement = ZeroClipboard_TableTools.$(elem);
// float just above object, or zIndex 99 if dom element isn't set
var zIndex = 99;
if (this.domElement.style.zIndex) {
zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
}
// find X/Y position of domElement
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
// create floating DIV above element
this.div = document.createElement('div');
var style = this.div.style;
style.position = 'absolute';
style.left = '0px';
style.top = '0px';
style.width = (box.width) + 'px';
style.height = box.height + 'px';
style.zIndex = zIndex;
if (typeof title != "undefined" && title !== "") {
this.div.title = title;
}
if (box.width !== 0 && box.height !== 0) {
this.sized = true;
}
// style.backgroundColor = '#f00'; // debug
if (this.domElement) {
this.domElement.appendChild(this.div);
this.div.innerHTML = this.getHTML(box.width, box.height).replace(/&/g, '&');
}
},
positionElement: function () {
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.position = 'absolute';
//style.left = (this.domElement.offsetLeft)+'px';
//style.top = this.domElement.offsetTop+'px';
style.width = box.width + 'px';
style.height = box.height + 'px';
if (box.width !== 0 && box.height !== 0) {
this.sized = true;
} else {
return;
}
var flash = this.div.childNodes[0];
flash.width = box.width;
flash.height = box.height;
},
getHTML: function (width, height) {
// return HTML for movie
var html = '';
var flashvars = 'id=' + this.id +
'&width=' + width +
'&height=' + height;
if (navigator.userAgent.match(/MSIE/)) {
// IE gets an OBJECT tag
var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + protocol + 'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="' + width + '" height="' + height + '" id="' + this.movieId + '" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="' + ZeroClipboard_TableTools.moviePath + '" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="' + flashvars + '"/><param name="wmode" value="transparent"/></object>';
}
else {
// all other browsers get an EMBED tag
html += '<embed id="' + this.movieId + '" src="' + ZeroClipboard_TableTools.moviePath + '" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="' + width + '" height="' + height + '" name="' + this.movieId + '" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="' + flashvars + '" wmode="transparent" />';
}
return html;
},
hide: function () {
// temporarily hide floater offscreen
if (this.div) {
this.div.style.left = '-2000px';
}
},
show: function () {
// show ourselves after a call to hide()
this.reposition();
},
destroy: function () {
// destroy control and floater
if (this.domElement && this.div) {
this.hide();
this.div.innerHTML = '';
var body = document.getElementsByTagName('body')[0];
try {
body.removeChild(this.div);
} catch (e) {
}
this.domElement = null;
this.div = null;
}
},
reposition: function (elem) {
// reposition our floating div, optionally to new container
// warning: container CANNOT change size, only position
if (elem) {
this.domElement = ZeroClipboard_TableTools.$(elem);
if (!this.domElement) {
this.hide();
}
}
if (this.domElement && this.div) {
var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement);
var style = this.div.style;
style.left = '' + box.left + 'px';
style.top = '' + box.top + 'px';
}
},
clearText: function () {
// clear the text to be copy / saved
this.clipText = '';
if (this.ready) {
this.movie.clearText();
}
},
appendText: function (newText) {
// append text to that which is to be copied / saved
this.clipText += newText;
if (this.ready) {
this.movie.appendText(newText);
}
},
setText: function (newText) {
// set text to be copied to be copied / saved
this.clipText = newText;
if (this.ready) {
this.movie.setText(newText);
}
},
setCharSet: function (charSet) {
// set the character set (UTF16LE or UTF8)
this.charSet = charSet;
if (this.ready) {
this.movie.setCharSet(charSet);
}
},
setBomInc: function (bomInc) {
// set if the BOM should be included or not
this.incBom = bomInc;
if (this.ready) {
this.movie.setBomInc(bomInc);
}
},
setFileName: function (newText) {
// set the file name
this.fileName = newText;
if (this.ready) {
this.movie.setFileName(newText);
}
},
setAction: function (newText) {
// set action (save or copy)
this.action = newText;
if (this.ready) {
this.movie.setAction(newText);
}
},
addEventListener: function (eventName, func) {
// add user event listener for event
// event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
if (!this.handlers[eventName]) {
this.handlers[eventName] = [];
}
this.handlers[eventName].push(func);
},
setHandCursor: function (enabled) {
// enable hand cursor (true), or default arrow cursor (false)
this.handCursorEnabled = enabled;
if (this.ready) {
this.movie.setHandCursor(enabled);
}
},
setCSSEffects: function (enabled) {
// enable or disable CSS effects on DOM container
this.cssEffects = !!enabled;
},
receiveEvent: function (eventName, args) {
var self;
// receive event from flash
eventName = eventName.toString().toLowerCase().replace(/^on/, '');
// special behavior for certain events
switch (eventName) {
case 'load':
// movie claims it is ready, but in IE this isn't always the case...
// bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
this.movie = document.getElementById(this.movieId);
if (!this.movie) {
self = this;
setTimeout(function () {
self.receiveEvent('load', null);
}, 1);
return;
}
// firefox on pc needs a "kick" in order to set these in certain cases
if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
self = this;
setTimeout(function () {
self.receiveEvent('load', null);
}, 100);
this.ready = true;
return;
}
this.ready = true;
this.movie.clearText();
this.movie.appendText(this.clipText);
this.movie.setFileName(this.fileName);
this.movie.setAction(this.action);
this.movie.setCharSet(this.charSet);
this.movie.setBomInc(this.incBom);
this.movie.setHandCursor(this.handCursorEnabled);
break;
case 'mouseover':
if (this.domElement && this.cssEffects) {
//this.domElement.addClass('hover');
if (this.recoverActive) {
this.domElement.addClass('active');
}
}
break;
case 'mouseout':
if (this.domElement && this.cssEffects) {
this.recoverActive = false;
if (this.domElement.hasClass('active')) {
this.domElement.removeClass('active');
this.recoverActive = true;
}
//this.domElement.removeClass('hover');
}
break;
case 'mousedown':
if (this.domElement && this.cssEffects) {
this.domElement.addClass('active');
}
break;
case 'mouseup':
if (this.domElement && this.cssEffects) {
this.domElement.removeClass('active');
this.recoverActive = false;
}
break;
} // switch eventName
if (this.handlers[eventName]) {
for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
var func = this.handlers[eventName][idx];
if (typeof(func) == 'function') {
// actual function reference
func(this, args);
}
else if ((typeof(func) == 'object') && (func.length == 2)) {
// PHP style object + method, i.e. [myObject, 'myMethod']
func[0][func[1]](this, args);
}
else if (typeof(func) == 'string') {
// name of function
window[func](this, args);
}
} // foreach event handler defined
} // user defined handler for event
}
};
// For the Flash binding to work, ZeroClipboard_TableTools must be on the global
// object list
window.ZeroClipboard_TableTools = ZeroClipboard_TableTools;
//include TableTools.js
/* TableTools
* 2009-2014 SpryMedia Ltd - datatables.net/license
*/
/*globals TableTools,ZeroClipboard_TableTools*/
(function ($, window, document) {
/**
* TableTools provides flexible buttons and other tools for a DataTables enhanced table
* @class TableTools
* @constructor
* @param {Object} oDT DataTables instance. When using DataTables 1.10 this can
* also be a jQuery collection, jQuery selector, table node, DataTables API
* instance or DataTables settings object.
* @param {Object} oOpts TableTools options
* @param {String} oOpts.sSwfPath ZeroClipboard SWF path
* @param {String} oOpts.sRowSelect Row selection options - 'none', 'single', 'multi' or 'os'
* @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection
* @param {Function} oOpts.fnRowSelected Callback function just after row selection
* @param {Function} oOpts.fnRowDeselected Callback function when row is deselected
* @param {Array} oOpts.aButtons List of buttons to be used
*/
TableTools = function (oDT, oOpts) {
/* Santiy check that we are a new instance */
if (!this instanceof TableTools) {
alert("Warning: TableTools must be initialised with the keyword 'new'");
}
// In 1.10 we can use the API to get the settings object from a number of
// sources
var dtSettings = $.fn.dataTable.Api ?
new $.fn.dataTable.Api(oDT).settings()[0] :
oDT.fnSettings();
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class variables
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* @namespace Settings object which contains customisable information for TableTools instance
*/
this.s = {
/**
* Store 'this' so the instance can be retrieved from the settings object
* @property that
* @type object
* @default this
*/
"that": this,
/**
* DataTables settings objects
* @property dt
* @type object
* @default <i>From the oDT init option</i>
*/
"dt": dtSettings,
/**
* @namespace Print specific information
*/
"print": {
/**
* DataTables draw 'start' point before the printing display was shown
* @property saveStart
* @type int
* @default -1
*/
"saveStart": -1,
/**
* DataTables draw 'length' point before the printing display was shown
* @property saveLength
* @type int
* @default -1
*/
"saveLength": -1,
/**
* Page scrolling point before the printing display was shown so it can be restored
* @property saveScroll
* @type int
* @default -1
*/
"saveScroll": -1,
/**
* Wrapped function to end the print display (to maintain scope)
* @property funcEnd
* @type Function
* @default function () {}
*/
"funcEnd": function () {
}
},
/**
* A unique ID is assigned to each button in each instance
* @property buttonCounter
* @type int
* @default 0
*/
"buttonCounter": 0,
/**
* @namespace Select rows specific information
*/
"select": {
/**
* Select type - can be 'none', 'single' or 'multi'
* @property type
* @type string
* @default ""
*/
"type": "",
/**
* Array of nodes which are currently selected
* @property selected
* @type array
* @default []
*/
"selected": [],
/**
* Function to run before the selection can take place. Will cancel the select if the
* function returns false
* @property preRowSelect
* @type Function
* @default null
*/
"preRowSelect": null,
/**
* Function to run when a row is selected
* @property postSelected
* @type Function
* @default null
*/
"postSelected": null,
/**
* Function to run when a row is deselected
* @property postDeselected
* @type Function
* @default null
*/
"postDeselected": null,
/**
* Indicate if all rows are selected (needed for server-side processing)
* @property all
* @type boolean
* @default false
*/
"all": false,
/**
* Class name to add to selected TR nodes
* @property selectedClass
* @type String
* @default ""
*/
"selectedClass": ""
},
/**
* Store of the user input customisation object
* @property custom
* @type object
* @default {}
*/
"custom": {},
/**
* SWF movie path
* @property swfPath
* @type string
* @default ""
*/
"swfPath": "",
/**
* Default button set
* @property buttonSet
* @type array
* @default []
*/
"buttonSet": [],
/**
* When there is more than one TableTools instance for a DataTable, there must be a
* master which controls events (row selection etc)
* @property master
* @type boolean
* @default false
*/
"master": false,
/**
* Tag names that are used for creating collections and buttons
* @namesapce
*/
"tags": {}
};
/**
* @namespace Common and useful DOM elements for the class instance
*/
this.dom = {
/**
* DIV element that is create and all TableTools buttons (and their children) put into
* @property container
* @type node
* @default null
*/
"container": null,
/**
* The table node to which TableTools will be applied
* @property table
* @type node
* @default null
*/
"table": null,
/**
* @namespace Nodes used for the print display
*/
"print": {
/**
* Nodes which have been removed from the display by setting them to display none
* @property hidden
* @type array
* @default []
*/
"hidden": [],
/**
* The information display saying telling the user about the print display
* @property message
* @type node
* @default null
*/
"message": null
},
/**
* @namespace Nodes used for a collection display. This contains the currently used collection
*/
"collection": {
/**
* The div wrapper containing the buttons in the collection (i.e. the menu)
* @property collection
* @type node
* @default null
*/
"collection": null,
/**
* Background display to provide focus and capture events
* @property background
* @type node
* @default null
*/
"background": null
}
};
/**
* @namespace Name space for the classes that this TableTools instance will use
* @extends TableTools.classes
*/
this.classes = $.extend(true, {}, TableTools.classes);
if (this.s.dt.bJUI) {
$.extend(true, this.classes, TableTools.classes_themeroller);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public class methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Retreieve the settings object from an instance
* @method fnSettings
* @returns {object} TableTools settings object
*/
this.fnSettings = function () {
return this.s;
};
/* Constructor logic */
if (typeof oOpts == 'undefined') {
oOpts = {};
}
TableTools._aInstances.push(this);
this._fnConstruct(oOpts);
return this;
};
TableTools.prototype = {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Public methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Retreieve the settings object from an instance
* @returns {array} List of TR nodes which are currently selected
* @param {boolean} [filtered=false] Get only selected rows which are
* available given the filtering applied to the table. By default
* this is false - i.e. all rows, regardless of filtering are
selected.
*/
"fnGetSelected": function (filtered) {
var
out = [],
data = this.s.dt.aoData,
displayed = this.s.dt.aiDisplay,
i, iLen;
if (filtered) {
// Only consider filtered rows
for (i = 0, iLen = displayed.length; i < iLen; i++) {
if (data[displayed[i]]._DTTT_selected) {
out.push(data[displayed[i]].nTr);
}
}
}
else {
// Use all rows
for (i = 0, iLen = data.length; i < iLen; i++) {
if (data[i]._DTTT_selected) {
out.push(data[i].nTr);
}
}
}
return out;
},
/**
* Get the data source objects/arrays from DataTables for the selected rows (same as
* fnGetSelected followed by fnGetData on each row from the table)
* @returns {array} Data from the TR nodes which are currently selected
*/
"fnGetSelectedData": function () {
var out = [];
var data = this.s.dt.aoData;
var i, iLen;
for (i = 0, iLen = data.length; i < iLen; i++) {
if (data[i]._DTTT_selected) {
out.push(this.s.dt.oInstance.fnGetData(i));
}
}
return out;
},
/**
* Get the indexes of the selected rows
* @returns {array} List of row indexes
* @param {boolean} [filtered=false] Get only selected rows which are
* available given the filtering applied to the table. By default
* this is false - i.e. all rows, regardless of filtering are
selected.
*/
"fnGetSelectedIndexes": function (filtered) {
var
out = [],
data = this.s.dt.aoData,
displayed = this.s.dt.aiDisplay,
i, iLen;
if (filtered) {
// Only consider filtered rows
for (i = 0, iLen = displayed.length; i < iLen; i++) {
if (data[displayed[i]]._DTTT_selected) {
out.push(displayed[i]);
}
}
}
else {
// Use all rows
for (i = 0, iLen = data.length; i < iLen; i++) {
if (data[i]._DTTT_selected) {
out.push(i);
}
}
}
return out;
},
/**
* Check to see if a current row is selected or not
* @param {Node} n TR node to check if it is currently selected or not
* @returns {Boolean} true if select, false otherwise
*/
"fnIsSelected": function (n) {
var pos = this.s.dt.oInstance.fnGetPosition(n);
return (this.s.dt.aoData[pos]._DTTT_selected === true) ? true : false;
},
/**
* Select all rows in the table
* @param {boolean} [filtered=false] Select only rows which are available
* given the filtering applied to the table. By default this is false -
* i.e. all rows, regardless of filtering are selected.
*/
"fnSelectAll": function (filtered) {
this._fnRowSelect(filtered ?
this.s.dt.aiDisplay :
this.s.dt.aoData
);
},
/**
* Deselect all rows in the table
* @param {boolean} [filtered=false] Deselect only rows which are available
* given the filtering applied to the table. By default this is false -
* i.e. all rows, regardless of filtering are deselected.
*/
"fnSelectNone": function (filtered) {
this._fnRowDeselect(this.fnGetSelectedIndexes(filtered));
},
/**
* Select row(s)
* @param {node|object|array} n The row(s) to select. Can be a single DOM
* TR node, an array of TR nodes or a jQuery object.
*/
"fnSelect": function (n) {
if (this.s.select.type == "single") {
this.fnSelectNone();
this._fnRowSelect(n);
}
else {
this._fnRowSelect(n);
}
},
/**
* Deselect row(s)
* @param {node|object|array} n The row(s) to deselect. Can be a single DOM
* TR node, an array of TR nodes or a jQuery object.
*/
"fnDeselect": function (n) {
this._fnRowDeselect(n);
},
/**
* Get the title of the document - useful for file names. The title is retrieved from either
* the configuration object's 'title' parameter, or the HTML document title
* @param {Object} oConfig Button configuration object
* @returns {String} Button title
*/
"fnGetTitle": function (oConfig) {
var sTitle = "";
if (typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "") {
sTitle = oConfig.sTitle;
} else {
var anTitle = document.getElementsByTagName('title');
if (anTitle.length > 0) {
sTitle = anTitle[0].innerHTML;
}
}
/* Strip characters which the OS will object to - checking for UTF8 support in the scripting
* engine
*/
if ("\u00A1".toString().length < 4) {
return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, "");
} else {
return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, "");
}
},
/**
* Calculate a unity array with the column width by proportion for a set of columns to be
* included for a button. This is particularly useful for PDF creation, where we can use the
* column widths calculated by the browser to size the columns in the PDF.
* @param {Object} oConfig Button configuration object
* @returns {Array} Unity array of column ratios
*/
"fnCalcColRatios": function (oConfig) {
var
aoCols = this.s.dt.aoColumns,
aColumnsInc = this._fnColumnTargets(oConfig.mColumns),
aColWidths = [],
iWidth = 0, iTotal = 0, i, iLen;
for (i = 0, iLen = aColumnsInc.length; i < iLen; i++) {
if (aColumnsInc[i]) {
iWidth = aoCols[i].nTh.offsetWidth;
iTotal += iWidth;
aColWidths.push(iWidth);
}
}
for (i = 0, iLen = aColWidths.length; i < iLen; i++) {
aColWidths[i] = aColWidths[i] / iTotal;
}
return aColWidths.join('\t');
},
/**
* Get the information contained in a table as a string
* @param {Object} oConfig Button configuration object
* @returns {String} Table data as a string
*/
"fnGetTableData": function (oConfig) {
/* In future this could be used to get data from a plain HTML source as well as DataTables */
if (this.s.dt) {
return this._fnGetDataTablesData(oConfig);
}
},
/**
* Pass text to a flash button instance, which will be used on the button's click handler
* @param {Object} clip Flash button object
* @param {String} text Text to set
*/
"fnSetText": function (clip, text) {
this._fnFlashSetText(clip, text);
},
/**
* Resize the flash elements of the buttons attached to this TableTools instance - this is
* useful for when initialising TableTools when it is hidden (display:none) since sizes can't
* be calculated at that time.
*/
"fnResizeButtons": function () {
for (var cli in ZeroClipboard_TableTools.clients) {
if (cli) {
var client = ZeroClipboard_TableTools.clients[cli];
if (typeof client.domElement != 'undefined' &&
client.domElement.parentNode) {
client.positionElement();
}
}
}
},
/**
* Check to see if any of the ZeroClipboard client's attached need to be resized
*/
"fnResizeRequired": function () {
for (var cli in ZeroClipboard_TableTools.clients) {
if (cli) {
var client = ZeroClipboard_TableTools.clients[cli];
if (typeof client.domElement != 'undefined' &&
client.domElement.parentNode == this.dom.container &&
client.sized === false) {
return true;
}
}
}
return false;
},
/**
* Programmatically enable or disable the print view
* @param {boolean} [bView=true] Show the print view if true or not given. If false, then
* terminate the print view and return to normal.
* @param {object} [oConfig={}] Configuration for the print view
* @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true
* @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the
* user to let them know what the print view is.
* @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will
* be included in the printed document.
*/
"fnPrint": function (bView, oConfig) {
if (oConfig === undefined) {
oConfig = {};
}
if (bView === undefined || bView) {
this._fnPrintStart(oConfig);
}
else {
this._fnPrintEnd();
}
},
/**
* Show a message to the end user which is nicely styled
* @param {string} message The HTML string to show to the user
* @param {int} time The duration the message is to be shown on screen for (mS)
*/
"fnInfo": function (message, time) {
var info = $('<div/>')
.addClass(this.classes.print.info)
.html(message)
.appendTo('body');
setTimeout(function () {
info.fadeOut("normal", function () {
info.remove();
});
}, time);
},
/**
* Get the container element of the instance for attaching to the DOM
* @returns {node} DOM node
*/
"fnContainer": function () {
return this.dom.container;
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods (they are of course public in JS, but recommended as private)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Constructor logic
* @method _fnConstruct
* @param {Object} oOpts Same as TableTools constructor
* @returns void
* @private
*/
"_fnConstruct": function (oOpts) {
var that = this;
this._fnCustomiseSettings(oOpts);
/* Container element */
this.dom.container = document.createElement(this.s.tags.container);
this.dom.container.className = this.classes.container;
/* Row selection config */
if (this.s.select.type != 'none') {
this._fnRowSelectConfig();
}
/* Buttons */
this._fnButtonDefinations(this.s.buttonSet, this.dom.container);
/* Destructor */
this.s.dt.aoDestroyCallback.push({
"sName": "TableTools",
"fn": function () {
$(that.s.dt.nTBody).off('click.DTTT_Select', 'tr');
$(that.dom.container).empty();
// Remove the instance
var idx = $.inArray(that, TableTools._aInstances);
if (idx !== -1) {
TableTools._aInstances.splice(idx, 1);
}
}
});
},
/**
* Take the user defined settings and the default settings and combine them.
* @method _fnCustomiseSettings
* @param {Object} oOpts Same as TableTools constructor
* @returns void
* @private
*/
"_fnCustomiseSettings": function (oOpts) {
/* Is this the master control instance or not? */
if (typeof this.s.dt._TableToolsInit == 'undefined') {
this.s.master = true;
this.s.dt._TableToolsInit = true;
}
/* We can use the table node from comparisons to group controls */
this.dom.table = this.s.dt.nTable;
/* Clone the defaults and then the user options */
this.s.custom = $.extend({}, TableTools.DEFAULTS, oOpts);
/* Flash file location */
this.s.swfPath = this.s.custom.sSwfPath;
if (typeof ZeroClipboard_TableTools != 'undefined') {
ZeroClipboard_TableTools.moviePath = this.s.swfPath;
}
/* Table row selecting */
this.s.select.type = this.s.custom.sRowSelect;
this.s.select.preRowSelect = this.s.custom.fnPreRowSelect;
this.s.select.postSelected = this.s.custom.fnRowSelected;
this.s.select.postDeselected = this.s.custom.fnRowDeselected;
// Backwards compatibility - allow the user to specify a custom class in the initialiser
if (this.s.custom.sSelectedClass) {
this.classes.select.row = this.s.custom.sSelectedClass;
}
this.s.tags = this.s.custom.oTags;
/* Button set */
this.s.buttonSet = this.s.custom.aButtons;
},
/**
* Take the user input arrays and expand them to be fully defined, and then add them to a given
* DOM element
* @method _fnButtonDefinations
* @param {array} buttonSet Set of user defined buttons
* @param {node} wrapper Node to add the created buttons to
* @returns void
* @private
*/
"_fnButtonDefinations": function (buttonSet, wrapper) {
var buttonDef;
for (var i = 0, iLen = buttonSet.length; i < iLen; i++) {
if (typeof buttonSet[i] == "string") {
if (typeof TableTools.BUTTONS[buttonSet[i]] == 'undefined') {
alert("TableTools: Warning - unknown button type: " + buttonSet[i]);
continue;
}
buttonDef = $.extend({}, TableTools.BUTTONS[buttonSet[i]], true);
}
else {
if (typeof TableTools.BUTTONS[buttonSet[i].sExtends] == 'undefined') {
alert("TableTools: Warning - unknown button type: " + buttonSet[i].sExtends);
continue;
}
var o = $.extend({}, TableTools.BUTTONS[buttonSet[i].sExtends], true);
buttonDef = $.extend(o, buttonSet[i], true);
}
var button = this._fnCreateButton(
buttonDef,
$(wrapper).hasClass(this.classes.collection.container)
);
if (button) {
wrapper.appendChild(button);
}
}
},
/**
* Create and configure a TableTools button
* @method _fnCreateButton
* @param {Object} oConfig Button configuration object
* @returns {Node} Button element
* @private
*/
"_fnCreateButton": function (oConfig, bCollectionButton) {
var nButton = this._fnButtonBase(oConfig, bCollectionButton);
if (oConfig.sAction.match(/flash/)) {
if (!this._fnHasFlash()) {
return false;
}
this._fnFlashConfig(nButton, oConfig);
}
else if (oConfig.sAction == "text") {
this._fnTextConfig(nButton, oConfig);
}
else if (oConfig.sAction == "div") {
this._fnTextConfig(nButton, oConfig);
}
else if (oConfig.sAction == "collection") {
this._fnTextConfig(nButton, oConfig);
this._fnCollectionConfig(nButton, oConfig);
}
if (this.s.dt.iTabIndex !== -1) {
$(nButton)
.attr('tabindex', this.s.dt.iTabIndex)
.attr('aria-controls', this.s.dt.sTableId)
.on('keyup.DTTT', function (e) {
// Trigger the click event on return key when focused.
// Note that for Flash buttons this has no effect since we
// can't programmatically trigger the Flash export
if (e.keyCode === 13) {
e.stopPropagation();
$(this).trigger('click');
}
})
.on('mousedown.DTTT', function (e) {
// On mousedown we want to stop the focus occurring on the
// button, focus is used only for the keyboard navigation.
// But using preventDefault for the flash buttons stops the
// flash action. However, it is not the button that gets
// focused but the flash element for flash buttons, so this
// works
if (!oConfig.sAction.match(/flash/)) {
e.preventDefault();
}
});
}
return nButton;
},
/**
* Create the DOM needed for the button and apply some base properties. All buttons start here
* @method _fnButtonBase
* @param {o} oConfig Button configuration object
* @returns {Node} DIV element for the button
* @private
*/
"_fnButtonBase": function (o, bCollectionButton) {
var sTag, sLiner, sClass;
if (bCollectionButton) {
sTag = o.sTag && o.sTag !== "default" ? o.sTag : this.s.tags.collection.button;
sLiner = o.sLinerTag && o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner;
sClass = this.classes.collection.buttons.normal;
}
else {
sTag = o.sTag && o.sTag !== "default" ? o.sTag : this.s.tags.button;
sLiner = o.sLinerTag && o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner;
sClass = this.classes.buttons.normal;
}
var
nButton = document.createElement(sTag),
nSpan = document.createElement(sLiner),
masterS = this._fnGetMasterSettings();
nButton.className = sClass + " " + o.sButtonClass;
nButton.setAttribute('id', "ToolTables_" + this.s.dt.sInstance + "_" + masterS.buttonCounter);
nButton.appendChild(nSpan);
nSpan.innerHTML = o.sButtonText;
masterS.buttonCounter++;
return nButton;
},
/**
* Get the settings object for the master instance. When more than one TableTools instance is
* assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such,
* we will typically want to interact with that master for global properties.
* @method _fnGetMasterSettings
* @returns {Object} TableTools settings object
* @private
*/
"_fnGetMasterSettings": function () {
if (this.s.master) {
return this.s;
}
else {
/* Look for the master which has the same DT as this one */
var instances = TableTools._aInstances;
for (var i = 0, iLen = instances.length; i < iLen; i++) {
if (this.dom.table == instances[i].s.dt.nTable) {
return instances[i].s;
}
}
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Button collection functions
*/
/**
* Create a collection button, when activated will present a drop down list of other buttons
* @param {Node} nButton Button to use for the collection activation
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionConfig": function (nButton, oConfig) {
var nHidden = document.createElement(this.s.tags.collection.container);
nHidden.style.display = "none";
nHidden.className = this.classes.collection.container;
oConfig._collection = nHidden;
document.body.appendChild(nHidden);
this._fnButtonDefinations(oConfig.aButtons, nHidden);
},
/**
* Show a button collection
* @param {Node} nButton Button to use for the collection
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionShow": function (nButton, oConfig) {
var
that = this,
oPos = $(nButton).offset(),
nHidden = oConfig._collection,
iDivX = oPos.left,
iDivY = oPos.top + $(nButton).outerHeight(),
iWinHeight = $(window).height(), iDocHeight = $(document).height(),
iWinWidth = $(window).width(), iDocWidth = $(document).width();
nHidden.style.position = "absolute";
nHidden.style.left = iDivX + "px";
nHidden.style.top = iDivY + "px";
nHidden.style.display = "block";
$(nHidden).css('opacity', 0);
var nBackground = document.createElement('div');
nBackground.style.position = "absolute";
nBackground.style.left = "0px";
nBackground.style.top = "0px";
nBackground.style.height = ((iWinHeight > iDocHeight) ? iWinHeight : iDocHeight) + "px";
nBackground.style.width = ((iWinWidth > iDocWidth) ? iWinWidth : iDocWidth) + "px";
nBackground.className = this.classes.collection.background;
$(nBackground).css('opacity', 0);
document.body.appendChild(nBackground);
document.body.appendChild(nHidden);
/* Visual corrections to try and keep the collection visible */
var iDivWidth = $(nHidden).outerWidth();
var iDivHeight = $(nHidden).outerHeight();
if (iDivX + iDivWidth > iDocWidth) {
nHidden.style.left = (iDocWidth - iDivWidth) + "px";
}
if (iDivY + iDivHeight > iDocHeight) {
nHidden.style.top = (iDivY - iDivHeight - $(nButton).outerHeight()) + "px";
}
this.dom.collection.collection = nHidden;
this.dom.collection.background = nBackground;
/* This results in a very small delay for the end user but it allows the animation to be
* much smoother. If you don't want the animation, then the setTimeout can be removed
*/
setTimeout(function () {
$(nHidden).animate({"opacity": 1}, 500);
$(nBackground).animate({"opacity": 0.25}, 500);
}, 10);
/* Resize the buttons to the Flash contents fit */
this.fnResizeButtons();
/* Event handler to remove the collection display */
$(nBackground).click(function () {
that._fnCollectionHide.call(that, null, null);
});
},
/**
* Hide a button collection
* @param {Node} nButton Button to use for the collection
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnCollectionHide": function (nButton, oConfig) {
if (oConfig !== null && oConfig.sExtends == 'collection') {
return;
}
if (this.dom.collection.collection !== null) {
$(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) {
this.style.display = "none";
});
$(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) {
this.parentNode.removeChild(this);
});
this.dom.collection.collection = null;
this.dom.collection.background = null;
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Row selection functions
*/
/**
* Add event handlers to a table to allow for row selection
* @method _fnRowSelectConfig
* @returns void
* @private
*/
"_fnRowSelectConfig": function () {
if (this.s.master) {
var
that = this,
i, iLen,
dt = this.s.dt,
aoOpenRows = this.s.dt.aoOpenRows;
$(dt.nTable).addClass(this.classes.select.table);
// When using OS style selection, we want to cancel the shift text
// selection, but only when the shift key is used (so you can
// actually still select text in the table)
if (this.s.select.type === 'os') {
$(dt.nTBody).on('mousedown.DTTT_Select', 'tr', function (e) {
if (e.shiftKey) {
$(dt.nTBody)
.css('-moz-user-select', 'none')
.one('selectstart.DTTT_Select', 'tr', function () {
return false;
});
}
});
$(dt.nTBody).on('mouseup.DTTT_Select', 'tr', function (e) {
$(dt.nTBody).css('-moz-user-select', '');
});
}
// Row selection
$(dt.nTBody).on('click.DTTT_Select', this.s.custom.sRowSelector, function (e) {
var row = this.nodeName.toLowerCase() === 'tr' ?
this :
$(this).parents('tr')[0];
var select = that.s.select;
var pos = that.s.dt.oInstance.fnGetPosition(row);
/* Sub-table must be ignored (odd that the selector won't do this with >) */
if (row.parentNode != dt.nTBody) {
return;
}
/* Check that we are actually working with a DataTables controlled row */
if (dt.oInstance.fnGetData(row) === null) {
return;
}
// Shift click, ctrl click and simple click handling to make
// row selection a lot like a file system in desktop OSs
if (select.type == 'os') {
if (e.ctrlKey || e.metaKey) {
// Add or remove from the selection
if (that.fnIsSelected(row)) {
that._fnRowDeselect(row, e);
}
else {
that._fnRowSelect(row, e);
}
}
else if (e.shiftKey) {
// Add a range of rows, from the last selected row to
// this one
var rowIdxs = that.s.dt.aiDisplay.slice(); // visible rows
var idx1 = $.inArray(select.lastRow, rowIdxs);
var idx2 = $.inArray(pos, rowIdxs);
if (that.fnGetSelected().length === 0 || idx1 === -1) {
// select from top to here - slightly odd, but both
// Windows and Mac OS do this
rowIdxs.splice($.inArray(pos, rowIdxs) + 1, rowIdxs.length);
}
else {
// reverse so we can shift click 'up' as well as down
if (idx1 > idx2) {
var tmp = idx2;
idx2 = idx1;
idx1 = tmp;
}
rowIdxs.splice(idx2 + 1, rowIdxs.length);
rowIdxs.splice(0, idx1);
}
if (!that.fnIsSelected(row)) {
// Select range
that._fnRowSelect(rowIdxs, e);
}
else {
// Deselect range - need to keep the clicked on row selected
rowIdxs.splice($.inArray(pos, rowIdxs), 1);
that._fnRowDeselect(rowIdxs, e);
}
}
else {
// No cmd or shift click. Deselect current if selected,
// or select this row only
if (that.fnIsSelected(row) && that.fnGetSelected().length === 1) {
that._fnRowDeselect(row, e);
}
else {
that.fnSelectNone();
that._fnRowSelect(row, e);
}
}
}
else if (that.fnIsSelected(row)) {
that._fnRowDeselect(row, e);
}
else if (select.type == "single") {
that.fnSelectNone();
that._fnRowSelect(row, e);
}
else if (select.type == "multi") {
that._fnRowSelect(row, e);
}
select.lastRow = pos;
});//.on('selectstart', function () { return false; } );
// Bind a listener to the DataTable for when new rows are created.
// This allows rows to be visually selected when they should be and
// deferred rendering is used.
dt.oApi._fnCallbackReg(dt, 'aoRowCreatedCallback', function (tr, data, index) {
if (dt.aoData[index]._DTTT_selected) {
$(tr).addClass(that.classes.select.row);
}
}, 'TableTools-SelectAll');
}
},
/**
* Select rows
* @param {*} src Rows to select - see _fnSelectData for a description of valid inputs
* @private
*/
"_fnRowSelect": function (src, e) {
var
that = this,
data = this._fnSelectData(src),
firstTr = data.length === 0 ? null : data[0].nTr,
anSelected = [],
i, len;
// Get all the rows that will be selected
for (i = 0, len = data.length; i < len; i++) {
if (data[i].nTr) {
anSelected.push(data[i].nTr);
}
}
// User defined pre-selection function
if (this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true)) {
return;
}
// Mark them as selected
for (i = 0, len = data.length; i < len; i++) {
data[i]._DTTT_selected = true;
if (data[i].nTr) {
$(data[i].nTr).addClass(that.classes.select.row);
}
}
// Post-selection function
if (this.s.select.postSelected !== null) {
this.s.select.postSelected.call(this, anSelected);
}
TableTools._fnEventDispatch(this, 'select', anSelected, true);
},
/**
* Deselect rows
* @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs
* @private
*/
"_fnRowDeselect": function (src, e) {
var
that = this,
data = this._fnSelectData(src),
firstTr = data.length === 0 ? null : data[0].nTr,
anDeselectedTrs = [],
i, len;
// Get all the rows that will be deselected
for (i = 0, len = data.length; i < len; i++) {
if (data[i].nTr) {
anDeselectedTrs.push(data[i].nTr);
}
}
// User defined pre-selection function
if (this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false)) {
return;
}
// Mark them as deselected
for (i = 0, len = data.length; i < len; i++) {
data[i]._DTTT_selected = false;
if (data[i].nTr) {
$(data[i].nTr).removeClass(that.classes.select.row);
}
}
// Post-deselection function
if (this.s.select.postDeselected !== null) {
this.s.select.postDeselected.call(this, anDeselectedTrs);
}
TableTools._fnEventDispatch(this, 'select', anDeselectedTrs, false);
},
/**
* Take a data source for row selection and convert it into aoData points for the DT
* @param {*} src Can be a single DOM TR node, an array of TR nodes (including a
* a jQuery object), a single aoData point from DataTables, an array of aoData
* points or an array of aoData indexes
* @returns {array} An array of aoData points
*/
"_fnSelectData": function (src) {
var out = [], pos, i, iLen;
if (src.nodeName) {
// Single node
pos = this.s.dt.oInstance.fnGetPosition(src);
out.push(this.s.dt.aoData[pos]);
}
else if (typeof src.length !== 'undefined') {
// jQuery object or an array of nodes, or aoData points
for (i = 0, iLen = src.length; i < iLen; i++) {
if (src[i].nodeName) {
pos = this.s.dt.oInstance.fnGetPosition(src[i]);
out.push(this.s.dt.aoData[pos]);
}
else if (typeof src[i] === 'number') {
out.push(this.s.dt.aoData[src[i]]);
}
else {
out.push(src[i]);
}
}
return out;
}
else {
// A single aoData point
out.push(src);
}
return out;
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Text button functions
*/
/**
* Configure a text based button for interaction events
* @method _fnTextConfig
* @param {Node} nButton Button element which is being considered
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnTextConfig": function (nButton, oConfig) {
var that = this;
if (oConfig.fnInit !== null) {
oConfig.fnInit.call(this, nButton, oConfig);
}
if (oConfig.sToolTip !== "") {
nButton.title = oConfig.sToolTip;
}
$(nButton).hover(function () {
if (oConfig.fnMouseover !== null) {
oConfig.fnMouseover.call(this, nButton, oConfig, null);
}
}, function () {
if (oConfig.fnMouseout !== null) {
oConfig.fnMouseout.call(this, nButton, oConfig, null);
}
});
if (oConfig.fnSelect !== null) {
TableTools._fnEventListen(this, 'select', function (n) {
oConfig.fnSelect.call(that, nButton, oConfig, n);
});
}
$(nButton).click(function (e) {
//e.preventDefault();
if (oConfig.fnClick !== null) {
oConfig.fnClick.call(that, nButton, oConfig, null, e);
}
/* Provide a complete function to match the behaviour of the flash elements */
if (oConfig.fnComplete !== null) {
oConfig.fnComplete.call(that, nButton, oConfig, null, null);
}
that._fnCollectionHide(nButton, oConfig);
});
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Flash button functions
*/
/**
* Check if the Flash plug-in is available
* @method _fnHasFlash
* @returns {boolean} `true` if Flash available, `false` otherwise
* @private
*/
"_fnHasFlash": function () {
try {
var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
if (fo) {
return true;
}
}
catch (e) {
if (
navigator.mimeTypes &&
navigator.mimeTypes['application/x-shockwave-flash'] !== undefined &&
navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin
) {
return true;
}
}
return false;
},
/**
* Configure a flash based button for interaction events
* @method _fnFlashConfig
* @param {Node} nButton Button element which is being considered
* @param {o} oConfig Button configuration object
* @returns void
* @private
*/
"_fnFlashConfig": function (nButton, oConfig) {
var that = this;
var flash = new ZeroClipboard_TableTools.Client();
if (oConfig.fnInit !== null) {
oConfig.fnInit.call(this, nButton, oConfig);
}
flash.setHandCursor(true);
if (oConfig.sAction == "flash_save") {
flash.setAction('save');
flash.setCharSet((oConfig.sCharSet == "utf16le") ? 'UTF16LE' : 'UTF8');
flash.setBomInc(oConfig.bBomInc);
flash.setFileName(oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)));
}
else if (oConfig.sAction == "flash_pdf") {
flash.setAction('pdf');
flash.setFileName(oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)));
}
else {
flash.setAction('copy');
}
flash.addEventListener('mouseOver', function (client) {
if (oConfig.fnMouseover !== null) {
oConfig.fnMouseover.call(that, nButton, oConfig, flash);
}
});
flash.addEventListener('mouseOut', function (client) {
if (oConfig.fnMouseout !== null) {
oConfig.fnMouseout.call(that, nButton, oConfig, flash);
}
});
flash.addEventListener('mouseDown', function (client) {
if (oConfig.fnClick !== null) {
oConfig.fnClick.call(that, nButton, oConfig, flash);
}
});
flash.addEventListener('complete', function (client, text) {
if (oConfig.fnComplete !== null) {
oConfig.fnComplete.call(that, nButton, oConfig, flash, text);
}
that._fnCollectionHide(nButton, oConfig);
});
this._fnFlashGlue(flash, nButton, oConfig.sToolTip);
},
/**
* Wait until the id is in the DOM before we "glue" the swf. Note that this function will call
* itself (using setTimeout) until it completes successfully
* @method _fnFlashGlue
* @param {Object} clip Zero clipboard object
* @param {Node} node node to glue swf to
* @param {String} text title of the flash movie
* @returns void
* @private
*/
"_fnFlashGlue": function (flash, node, text) {
var that = this;
var id = node.getAttribute('id');
if (document.getElementById(id)) {
flash.glue(node, text);
}
else {
setTimeout(function () {
that._fnFlashGlue(flash, node, text);
}, 100);
}
},
/**
* Set the text for the flash clip to deal with
*
* This function is required for large information sets. There is a limit on the
* amount of data that can be transferred between Javascript and Flash in a single call, so
* we use this method to build up the text in Flash by sending over chunks. It is estimated
* that the data limit is around 64k, although it is undocumented, and appears to be different
* between different flash versions. We chunk at 8KiB.
* @method _fnFlashSetText
* @param {Object} clip the ZeroClipboard object
* @param {String} sData the data to be set
* @returns void
* @private
*/
"_fnFlashSetText": function (clip, sData) {
var asData = this._fnChunkData(sData, 8192);
clip.clearText();
for (var i = 0, iLen = asData.length; i < iLen; i++) {
clip.appendText(asData[i]);
}
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Data retrieval functions
*/
/**
* Convert the mixed columns variable into a boolean array the same size as the columns, which
* indicates which columns we want to include
* @method _fnColumnTargets
* @param {String|Array} mColumns The columns to be included in data retrieval. If a string
* then it can take the value of "visible" or "hidden" (to include all visible or
* hidden columns respectively). Or an array of column indexes
* @returns {Array} A boolean array the length of the columns of the table, which each value
* indicating if the column is to be included or not
* @private
*/
"_fnColumnTargets": function (mColumns) {
var aColumns = [];
var dt = this.s.dt;
var i, iLen;
var columns = dt.aoColumns;
var columnCount = columns.length;
if (typeof mColumns == "function") {
var a = mColumns.call(this, dt);
for (i = 0, iLen = columnCount; i < iLen; i++) {
aColumns.push($.inArray(i, a) !== -1 ? true : false);
}
}
else if (typeof mColumns == "object") {
for (i = 0, iLen = columnCount; i < iLen; i++) {
aColumns.push(false);
}
for (i = 0, iLen = mColumns.length; i < iLen; i++) {
aColumns[mColumns[i]] = true;
}
}
else if (mColumns == "visible") {
for (i = 0, iLen = columnCount; i < iLen; i++) {
aColumns.push(columns[i].bVisible ? true : false);
}
}
else if (mColumns == "hidden") {
for (i = 0, iLen = columnCount; i < iLen; i++) {
aColumns.push(columns[i].bVisible ? false : true);
}
}
else if (mColumns == "sortable") {
for (i = 0, iLen = columnCount; i < iLen; i++) {
aColumns.push(columns[i].bSortable ? true : false);
}
}
else /* all */
{
for (i = 0, iLen = columnCount; i < iLen; i++) {
aColumns.push(true);
}
}
return aColumns;
},
/**
* New line character(s) depend on the platforms
* @method method
* @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine
* @returns {String} Newline character
*/
"_fnNewline": function (oConfig) {
if (oConfig.sNewLine == "auto") {
return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n";
}
else {
return oConfig.sNewLine;
}
},
/**
* Get data from DataTables' internals and format it for output
* @method _fnGetDataTablesData
* @param {Object} oConfig Button configuration object
* @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string
* @param {String} oConfig.sFieldSeperator Field separator for the data cells
* @param {String} oConfig.sNewline New line options
* @param {Mixed} oConfig.mColumns Which columns should be included in the output
* @param {Boolean} oConfig.bHeader Include the header
* @param {Boolean} oConfig.bFooter Include the footer
* @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output
* @returns {String} Concatenated string of data
* @private
*/
"_fnGetDataTablesData": function (oConfig) {
var i, iLen, j, jLen;
var aRow, aData = [], sLoopData = '', arr;
var dt = this.s.dt, tr, child;
var regex = new RegExp(oConfig.sFieldBoundary, "g");
/* Do it here for speed */
var aColumnsInc = this._fnColumnTargets(oConfig.mColumns);
var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false;
/*
* Header
*/
if (oConfig.bHeader) {
aRow = [];
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
if (aColumnsInc[i]) {
sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g, " ").replace(/<.*?>/g, "").replace(/^\s+|\s+$/g, "");
sLoopData = this._fnHtmlDecode(sLoopData);
aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
}
}
aData.push(aRow.join(oConfig.sFieldSeperator));
}
bSelectedOnly = true;
/*
* Body
*/
var aDataIndex;
var aSelected = this.fnGetSelectedIndexes();
bSelectedOnly = this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0;
if (bSelectedOnly) {
// Use the selected indexes
aDataIndex = aSelected;
}
else if (DataTable.Api) {
// 1.10+ style
aDataIndex = new DataTable.Api(dt)
.rows(oConfig.oSelectorOpts)
.indexes()
.flatten()
.toArray();
}
else {
// 1.9- style
aDataIndex = dt.oInstance
.$('tr', oConfig.oSelectorOpts)
.map(function (id, row) {
return dt.oInstance.fnGetPosition(row);
})
.get();
}
for (j = 0, jLen = aDataIndex.length; j < jLen; j++) {
tr = dt.aoData[aDataIndex[j]].nTr;
aRow = [];
/* Columns */
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
if (aColumnsInc[i]) {
/* Convert to strings (with small optimisation) */
var mTypeData = dt.oApi._fnGetCellData(dt, aDataIndex[j], i, 'display');
if (oConfig.fnCellRender) {
sLoopData = oConfig.fnCellRender(mTypeData, i, tr, aDataIndex[j]) + "";
}
else if (typeof mTypeData == "string") {
/* Strip newlines, replace img tags with alt attr. and finally strip html... */
sLoopData = mTypeData.replace(/\n/g, " ");
sLoopData =
sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi,
'$1$2$3');
sLoopData = sLoopData.replace(/<.*?>/g, "");
}
else {
sLoopData = mTypeData + "";
}
/* Trim and clean the data */
sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, '');
sLoopData = this._fnHtmlDecode(sLoopData);
/* Bound it and add it to the total data */
aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
}
}
aData.push(aRow.join(oConfig.sFieldSeperator));
/* Details rows from fnOpen */
if (oConfig.bOpenRows) {
arr = $.grep(dt.aoOpenRows, function (o) {
return o.nParent === tr;
});
if (arr.length === 1) {
sLoopData = this._fnBoundData($('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex);
aData.push(sLoopData);
}
}
}
/*
* Footer
*/
if (oConfig.bFooter && dt.nTFoot !== null) {
aRow = [];
for (i = 0, iLen = dt.aoColumns.length; i < iLen; i++) {
if (aColumnsInc[i] && dt.aoColumns[i].nTf !== null) {
sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g, " ").replace(/<.*?>/g, "");
sLoopData = this._fnHtmlDecode(sLoopData);
aRow.push(this._fnBoundData(sLoopData, oConfig.sFieldBoundary, regex));
}
}
aData.push(aRow.join(oConfig.sFieldSeperator));
}
var _sLastData = aData.join(this._fnNewline(oConfig));
return _sLastData;
},
/**
* Wrap data up with a boundary string
* @method _fnBoundData
* @param {String} sData data to bound
* @param {String} sBoundary bounding char(s)
* @param {RegExp} regex search for the bounding chars - constructed outside for efficiency
* in the loop
* @returns {String} bound data
* @private
*/
"_fnBoundData": function (sData, sBoundary, regex) {
if (sBoundary === "") {
return sData;
}
else {
return sBoundary + sData.replace(regex, sBoundary + sBoundary) + sBoundary;
}
},
/**
* Break a string up into an array of smaller strings
* @method _fnChunkData
* @param {String} sData data to be broken up
* @param {Int} iSize chunk size
* @returns {Array} String array of broken up text
* @private
*/
"_fnChunkData": function (sData, iSize) {
var asReturn = [];
var iStrlen = sData.length;
for (var i = 0; i < iStrlen; i += iSize) {
if (i + iSize < iStrlen) {
asReturn.push(sData.substring(i, i + iSize));
}
else {
asReturn.push(sData.substring(i, iStrlen));
}
}
return asReturn;
},
/**
* Decode HTML entities
* @method _fnHtmlDecode
* @param {String} sData encoded string
* @returns {String} decoded string
* @private
*/
"_fnHtmlDecode": function (sData) {
if (sData.indexOf('&') === -1) {
return sData;
}
var n = document.createElement('div');
return sData.replace(/&([^\s]*?);/g, function (match, match2) {
if (match.substr(1, 1) === '#') {
return String.fromCharCode(Number(match2.substr(1)));
}
else {
n.innerHTML = match;
return n.childNodes[0].nodeValue;
}
});
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Printing functions
*/
/**
* Show print display
* @method _fnPrintStart
* @param {Event} e Event object
* @param {Object} oConfig Button configuration object
* @returns void
* @private
*/
"_fnPrintStart": function (oConfig) {
var that = this;
var oSetDT = this.s.dt;
/* Parse through the DOM hiding everything that isn't needed for the table */
this._fnPrintHideNodes(oSetDT.nTable);
/* Show the whole table */
this.s.print.saveStart = oSetDT._iDisplayStart;
this.s.print.saveLength = oSetDT._iDisplayLength;
if (oConfig.bShowAll) {
oSetDT._iDisplayStart = 0;
oSetDT._iDisplayLength = -1;
if (oSetDT.oApi._fnCalculateEnd) {
oSetDT.oApi._fnCalculateEnd(oSetDT);
}
oSetDT.oApi._fnDraw(oSetDT);
}
/* Adjust the display for scrolling which might be done by DataTables */
if (oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "") {
this._fnPrintScrollStart(oSetDT);
// If the table redraws while in print view, the DataTables scrolling
// setup would hide the header, so we need to readd it on draw
$(this.s.dt.nTable).bind('draw.DTTT_Print', function () {
that._fnPrintScrollStart(oSetDT);
});
}
/* Remove the other DataTables feature nodes - but leave the table! and info div */
var anFeature = oSetDT.aanFeatures;
for (var cFeature in anFeature) {
if (cFeature != 'i' && cFeature != 't' && cFeature.length == 1) {
for (var i = 0, iLen = anFeature[cFeature].length; i < iLen; i++) {
this.dom.print.hidden.push({
"node": anFeature[cFeature][i],
"display": "block"
});
anFeature[cFeature][i].style.display = "none";
}
}
}
/* Print class can be used for styling */
$(document.body).addClass(this.classes.print.body);
/* Show information message to let the user know what is happening */
if (oConfig.sInfo !== "") {
this.fnInfo(oConfig.sInfo, 3000);
}
/* Add a message at the top of the page */
if (oConfig.sMessage) {
$('<div/>')
.addClass(this.classes.print.message)
.html(oConfig.sMessage)
.prependTo('body');
}
/* Cache the scrolling and the jump to the top of the page */
this.s.print.saveScroll = $(window).scrollTop();
window.scrollTo(0, 0);
/* Bind a key event listener to the document for the escape key -
* it is removed in the callback
*/
$(document).bind("keydown.DTTT", function (e) {
/* Only interested in the escape key */
if (e.keyCode == 27) {
e.preventDefault();
that._fnPrintEnd.call(that, e);
}
});
},
/**
* Printing is finished, resume normal display
* @method _fnPrintEnd
* @param {Event} e Event object
* @returns void
* @private
*/
"_fnPrintEnd": function (e) {
var that = this;
var oSetDT = this.s.dt;
var oSetPrint = this.s.print;
var oDomPrint = this.dom.print;
/* Show all hidden nodes */
this._fnPrintShowNodes();
/* Restore DataTables' scrolling */
if (oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "") {
$(this.s.dt.nTable).unbind('draw.DTTT_Print');
this._fnPrintScrollEnd();
}
/* Restore the scroll */
window.scrollTo(0, oSetPrint.saveScroll);
/* Drop the print message */
$('div.' + this.classes.print.message).remove();
/* Styling class */
$(document.body).removeClass('DTTT_Print');
/* Restore the table length */
oSetDT._iDisplayStart = oSetPrint.saveStart;
oSetDT._iDisplayLength = oSetPrint.saveLength;
if (oSetDT.oApi._fnCalculateEnd) {
oSetDT.oApi._fnCalculateEnd(oSetDT);
}
oSetDT.oApi._fnDraw(oSetDT);
$(document).unbind("keydown.DTTT");
},
/**
* Take account of scrolling in DataTables by showing the full table
* @returns void
* @private
*/
"_fnPrintScrollStart": function () {
var
oSetDT = this.s.dt,
nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0],
nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0],
nScrollBody = oSetDT.nTable.parentNode,
nTheadSize, nTfootSize;
/* Copy the header in the thead in the body table, this way we show one single table when
* in print view. Note that this section of code is more or less verbatim from DT 1.7.0
*/
nTheadSize = oSetDT.nTable.getElementsByTagName('thead');
if (nTheadSize.length > 0) {
oSetDT.nTable.removeChild(nTheadSize[0]);
}
if (oSetDT.nTFoot !== null) {
nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot');
if (nTfootSize.length > 0) {
oSetDT.nTable.removeChild(nTfootSize[0]);
}
}
nTheadSize = oSetDT.nTHead.cloneNode(true);
oSetDT.nTable.insertBefore(nTheadSize, oSetDT.nTable.childNodes[0]);
if (oSetDT.nTFoot !== null) {
nTfootSize = oSetDT.nTFoot.cloneNode(true);
oSetDT.nTable.insertBefore(nTfootSize, oSetDT.nTable.childNodes[1]);
}
/* Now adjust the table's viewport so we can actually see it */
if (oSetDT.oScroll.sX !== "") {
oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth() + "px";
nScrollBody.style.width = $(oSetDT.nTable).outerWidth() + "px";
nScrollBody.style.overflow = "visible";
}
if (oSetDT.oScroll.sY !== "") {
nScrollBody.style.height = $(oSetDT.nTable).outerHeight() + "px";
nScrollBody.style.overflow = "visible";
}
},
/**
* Take account of scrolling in DataTables by showing the full table. Note that the redraw of
* the DataTable that we do will actually deal with the majority of the hard work here
* @returns void
* @private
*/
"_fnPrintScrollEnd": function () {
var
oSetDT = this.s.dt,
nScrollBody = oSetDT.nTable.parentNode;
if (oSetDT.oScroll.sX !== "") {
nScrollBody.style.width = oSetDT.oApi._fnStringToCss(oSetDT.oScroll.sX);
nScrollBody.style.overflow = "auto";
}
if (oSetDT.oScroll.sY !== "") {
nScrollBody.style.height = oSetDT.oApi._fnStringToCss(oSetDT.oScroll.sY);
nScrollBody.style.overflow = "auto";
}
},
/**
* Resume the display of all TableTools hidden nodes
* @method _fnPrintShowNodes
* @returns void
* @private
*/
"_fnPrintShowNodes": function () {
var anHidden = this.dom.print.hidden;
for (var i = 0, iLen = anHidden.length; i < iLen; i++) {
anHidden[i].node.style.display = anHidden[i].display;
}
anHidden.splice(0, anHidden.length);
},
/**
* Hide nodes which are not needed in order to display the table. Note that this function is
* recursive
* @method _fnPrintHideNodes
* @param {Node} nNode Element which should be showing in a 'print' display
* @returns void
* @private
*/
"_fnPrintHideNodes": function (nNode) {
var anHidden = this.dom.print.hidden;
var nParent = nNode.parentNode;
var nChildren = nParent.childNodes;
for (var i = 0, iLen = nChildren.length; i < iLen; i++) {
if (nChildren[i] != nNode && nChildren[i].nodeType == 1) {
/* If our node is shown (don't want to show nodes which were previously hidden) */
var sDisplay = $(nChildren[i]).css("display");
if (sDisplay != "none") {
/* Cache the node and it's previous state so we can restore it */
anHidden.push({
"node": nChildren[i],
"display": sDisplay
});
nChildren[i].style.display = "none";
}
}
}
if (nParent.nodeName.toUpperCase() != "BODY") {
this._fnPrintHideNodes(nParent);
}
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static variables
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Store of all instances that have been created of TableTools, so one can look up other (when
* there is need of a master)
* @property _aInstances
* @type Array
* @default []
* @private
*/
TableTools._aInstances = [];
/**
* Store of all listeners and their callback functions
* @property _aListeners
* @type Array
* @default []
*/
TableTools._aListeners = [];
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Static methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Get an array of all the master instances
* @method fnGetMasters
* @returns {Array} List of master TableTools instances
* @static
*/
TableTools.fnGetMasters = function () {
var a = [];
for (var i = 0, iLen = TableTools._aInstances.length; i < iLen; i++) {
if (TableTools._aInstances[i].s.master) {
a.push(TableTools._aInstances[i]);
}
}
return a;
};
/**
* Get the master instance for a table node (or id if a string is given)
* @method fnGetInstance
* @returns {Object} ID of table OR table node, for which we want the TableTools instance
* @static
*/
TableTools.fnGetInstance = function (node) {
if (typeof node != 'object') {
node = document.getElementById(node);
}
for (var i = 0, iLen = TableTools._aInstances.length; i < iLen; i++) {
if (TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node) {
return TableTools._aInstances[i];
}
}
return null;
};
/**
* Add a listener for a specific event
* @method _fnEventListen
* @param {Object} that Scope of the listening function (i.e. 'this' in the caller)
* @param {String} type Event type
* @param {Function} fn Function
* @returns void
* @private
* @static
*/
TableTools._fnEventListen = function (that, type, fn) {
TableTools._aListeners.push({
"that": that,
"type": type,
"fn": fn
});
};
/**
* An event has occurred - look up every listener and fire it off. We check that the event we are
* going to fire is attached to the same table (using the table node as reference) before firing
* @method _fnEventDispatch
* @param {Object} that Scope of the listening function (i.e. 'this' in the caller)
* @param {String} type Event type
* @param {Node} node Element that the event occurred on (may be null)
* @param {boolean} [selected] Indicate if the node was selected (true) or deselected (false)
* @returns void
* @private
* @static
*/
TableTools._fnEventDispatch = function (that, type, node, selected) {
var listeners = TableTools._aListeners;
for (var i = 0, iLen = listeners.length; i < iLen; i++) {
if (that.dom.table == listeners[i].that.dom.table && listeners[i].type == type) {
listeners[i].fn(node, selected);
}
}
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constants
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
TableTools.buttonBase = {
// Button base
"sAction": "text",
"sTag": "default",
"sLinerTag": "default",
"sButtonClass": "DTTT_button_text",
"sButtonText": "Button text",
"sTitle": "",
"sToolTip": "",
// Common button specific options
"sCharSet": "utf8",
"bBomInc": false,
"sFileName": "*.csv",
"sFieldBoundary": "",
"sFieldSeperator": "\t",
"sNewLine": "auto",
"mColumns": "all", /* "all", "visible", "hidden" or array of column integers */
"bHeader": true,
"bFooter": true,
"bOpenRows": false,
"bSelectedOnly": false,
"oSelectorOpts": undefined, // See http://datatables.net/docs/DataTables/1.9.4/#$ for full options
// Callbacks
"fnMouseover": null,
"fnMouseout": null,
"fnClick": null,
"fnSelect": null,
"fnComplete": null,
"fnInit": null,
"fnCellRender": null
};
/**
* @namespace Default button configurations
*/
TableTools.BUTTONS = {
"csv": $.extend({}, TableTools.buttonBase, {
"sAction": "flash_save",
"sButtonClass": "DTTT_button_csv",
"sButtonText": "CSV",
"sFieldBoundary": '"',
"sFieldSeperator": ",",
"fnClick": function (nButton, oConfig, flash) {
this.fnSetText(flash, this.fnGetTableData(oConfig));
}
}),
"xls": $.extend({}, TableTools.buttonBase, {
"sAction": "flash_save",
"sCharSet": "utf16le",
"bBomInc": true,
"sButtonClass": "DTTT_button_xls",
"sButtonText": "Excel",
"fnClick": function (nButton, oConfig, flash) {
this.fnSetText(flash, this.fnGetTableData(oConfig));
}
}),
"copy": $.extend({}, TableTools.buttonBase, {
"sAction": "flash_copy",
"sButtonClass": "DTTT_button_copy",
"sButtonText": "Copy",
"fnClick": function (nButton, oConfig, flash) {
this.fnSetText(flash, this.fnGetTableData(oConfig));
},
"fnComplete": function (nButton, oConfig, flash, text) {
var lines = text.split('\n').length;
if (oConfig.bHeader) lines--;
if (this.s.dt.nTFoot !== null && oConfig.bFooter) lines--;
var plural = (lines == 1) ? "" : "s";
this.fnInfo('<h6>Table copied</h6>' +
'<p>Copied ' + lines + ' row' + plural + ' to the clipboard.</p>',
1500
);
}
}),
"pdf": $.extend({}, TableTools.buttonBase, {
"sAction": "flash_pdf",
"sNewLine": "\n",
"sFileName": "*.pdf",
"sButtonClass": "DTTT_button_pdf",
"sButtonText": "PDF",
"sPdfOrientation": "portrait",
"sPdfSize": "A4",
"sPdfMessage": "",
"fnClick": function (nButton, oConfig, flash) {
this.fnSetText(flash,
"title:" + this.fnGetTitle(oConfig) + "\n" +
"message:" + oConfig.sPdfMessage + "\n" +
"colWidth:" + this.fnCalcColRatios(oConfig) + "\n" +
"orientation:" + oConfig.sPdfOrientation + "\n" +
"size:" + oConfig.sPdfSize + "\n" +
"--/TableToolsOpts--\n" +
this.fnGetTableData(oConfig)
);
}
}),
"print": $.extend({}, TableTools.buttonBase, {
"sInfo": "<h6>Print view</h6><p>Please use your browser's print function to " +
"print this table. Press escape when finished.</p>",
"sMessage": null,
"bShowAll": true,
"sToolTip": "View print view",
"sButtonClass": "DTTT_button_print",
"sButtonText": "Print",
"fnClick": function (nButton, oConfig) {
this.fnPrint(true, oConfig);
}
}),
"text": $.extend({}, TableTools.buttonBase),
"select": $.extend({}, TableTools.buttonBase, {
"sButtonText": "Select button",
"fnSelect": function (nButton, oConfig) {
if (this.fnGetSelected().length !== 0) {
$(nButton).removeClass(this.classes.buttons.disabled);
} else {
$(nButton).addClass(this.classes.buttons.disabled);
}
},
"fnInit": function (nButton, oConfig) {
$(nButton).addClass(this.classes.buttons.disabled);
}
}),
"select_single": $.extend({}, TableTools.buttonBase, {
"sButtonText": "Select button",
"fnSelect": function (nButton, oConfig) {
var iSelected = this.fnGetSelected().length;
if (iSelected == 1) {
$(nButton).removeClass(this.classes.buttons.disabled);
} else {
$(nButton).addClass(this.classes.buttons.disabled);
}
},
"fnInit": function (nButton, oConfig) {
$(nButton).addClass(this.classes.buttons.disabled);
}
}),
"select_all": $.extend({}, TableTools.buttonBase, {
"sButtonText": "Select all",
"fnClick": function (nButton, oConfig) {
this.fnSelectAll();
},
"fnSelect": function (nButton, oConfig) {
if (this.fnGetSelected().length == this.s.dt.fnRecordsDisplay()) {
$(nButton).addClass(this.classes.buttons.disabled);
} else {
$(nButton).removeClass(this.classes.buttons.disabled);
}
}
}),
"select_none": $.extend({}, TableTools.buttonBase, {
"sButtonText": "Deselect all",
"fnClick": function (nButton, oConfig) {
this.fnSelectNone();
},
"fnSelect": function (nButton, oConfig) {
if (this.fnGetSelected().length !== 0) {
$(nButton).removeClass(this.classes.buttons.disabled);
} else {
$(nButton).addClass(this.classes.buttons.disabled);
}
},
"fnInit": function (nButton, oConfig) {
$(nButton).addClass(this.classes.buttons.disabled);
}
}),
"ajax": $.extend({}, TableTools.buttonBase, {
"sAjaxUrl": "/xhr.php",
"sButtonText": "Ajax button",
"fnClick": function (nButton, oConfig) {
var sData = this.fnGetTableData(oConfig);
$.ajax({
"url": oConfig.sAjaxUrl,
"data": [
{"name": "tableData", "value": sData}
],
"success": oConfig.fnAjaxComplete,
"dataType": "json",
"type": "POST",
"cache": false,
"error": function () {
alert("Error detected when sending table data to server");
}
});
},
"fnAjaxComplete": function (json) {
alert('Ajax complete');
}
}),
"div": $.extend({}, TableTools.buttonBase, {
"sAction": "div",
"sTag": "div",
"sButtonClass": "DTTT_nonbutton",
"sButtonText": "Text button"
}),
"collection": $.extend({}, TableTools.buttonBase, {
"sAction": "collection",
"sButtonClass": "DTTT_button_collection",
"sButtonText": "Collection",
"fnClick": function (nButton, oConfig) {
this._fnCollectionShow(nButton, oConfig);
}
})
};
/*
* on* callback parameters:
* 1. node - button element
* 2. object - configuration object for this button
* 3. object - ZeroClipboard reference (flash button only)
* 4. string - Returned string from Flash (flash button only - and only on 'complete')
*/
// Alias to match the other plug-ins styling
TableTools.buttons = TableTools.BUTTONS;
/**
* @namespace Classes used by TableTools - allows the styles to be override easily.
* Note that when TableTools initialises it will take a copy of the classes object
* and will use its internal copy for the remainder of its run time.
*/
TableTools.classes = {
"container": "DTTT_container",
"buttons": {
"normal": "DTTT_button",
"disabled": "DTTT_disabled"
},
"collection": {
"container": "DTTT_collection",
"background": "DTTT_collection_background",
"buttons": {
"normal": "DTTT_button",
"disabled": "DTTT_disabled"
}
},
"select": {
"table": "DTTT_selectable",
"row": "DTTT_selected selected"
},
"print": {
"body": "DTTT_Print",
"info": "DTTT_print_info",
"message": "DTTT_PrintMessage"
}
};
/**
* @namespace ThemeRoller classes - built in for compatibility with DataTables'
* bJQueryUI option.
*/
TableTools.classes_themeroller = {
"container": "DTTT_container ui-buttonset ui-buttonset-multi",
"buttons": {
"normal": "DTTT_button ui-button ui-state-default"
},
"collection": {
"container": "DTTT_collection ui-buttonset ui-buttonset-multi"
}
};
/**
* @namespace TableTools default settings for initialisation
*/
TableTools.DEFAULTS = {
"sSwfPath": "../swf/copy_csv_xls_pdf.swf",
"sRowSelect": "none",
"sRowSelector": "tr",
"sSelectedClass": null,
"fnPreRowSelect": null,
"fnRowSelected": null,
"fnRowDeselected": null,
"aButtons": ["copy", "csv", "xls", "pdf", "print"],
"oTags": {
"container": "div",
"button": "a", // We really want to use buttons here, but Firefox and IE ignore the
// click on the Flash element in the button (but not mouse[in|out]).
"liner": "span",
"collection": {
"container": "div",
"button": "a",
"liner": "span"
}
}
};
// Alias to match the other plug-ins
TableTools.defaults = TableTools.DEFAULTS;
/**
* Name of this class
* @constant CLASS
* @type String
* @default TableTools
*/
TableTools.prototype.CLASS = "TableTools";
/**
* TableTools version
* @constant VERSION
* @type String
* @default See code
*/
TableTools.version = "2.2.3";
// DataTables 1.10 API
//
// This will be extended in a big way in in TableTools 3 to provide API methods
// such as rows().select() and rows.selected() etc, but for the moment the
// tabletools() method simply returns the instance.
if ($.fn.dataTable.Api) {
$.fn.dataTable.Api.register('tabletools()', function () {
var tt = null;
if (this.context.length > 0) {
tt = TableTools.fnGetInstance(this.context[0].nTable);
}
return tt;
});
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Initialisation
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*
* Register a new feature with DataTables
*/
if (typeof $.fn.dataTable == "function" &&
typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
$.fn.dataTableExt.fnVersionCheck('1.9.0')) {
$.fn.dataTableExt.aoFeatures.push({
"fnInit": function (oDTSettings) {
var init = oDTSettings.oInit;
var opts = init ?
init.tableTools || init.oTableTools || {} :
{};
return new TableTools(oDTSettings.oInstance, opts).dom.container;
},
"cFeature": "T",
"sFeature": "TableTools"
});
}
else {
alert("Warning: TableTools requires DataTables 1.9.0 or newer - www.datatables.net/download");
}
$.fn.DataTable.TableTools = TableTools;
})(jQuery, window, document);
/*
* Register a new feature with DataTables
*/
if (typeof $.fn.dataTable == "function" &&
typeof $.fn.dataTableExt.fnVersionCheck == "function" &&
$.fn.dataTableExt.fnVersionCheck('1.9.0')) {
$.fn.dataTableExt.aoFeatures.push({
"fnInit": function (oDTSettings) {
var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ?
oDTSettings.oInit.oTableTools : {};
var oTT = new TableTools(oDTSettings.oInstance, oOpts);
TableTools._aInstances.push(oTT);
return oTT.dom.container;
},
"cFeature": "T",
"sFeature": "TableTools"
});
}
else {
alert("Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download");
}
$.fn.dataTable.TableTools = TableTools;
$.fn.DataTable.TableTools = TableTools;
return TableTools;
}; // /factory
// Define as an AMD module if possible
if (typeof define === 'function' && define.amd) {
define(['jquery', 'datatables'], factory);
}
else if (typeof exports === 'object') {
// Node/CommonJS
factory(require('jquery'), require('datatables'));
}
else if (jQuery && !jQuery.fn.dataTable.TableTools) {
// Otherwise simply initialise as normal, stopping multiple evaluation
factory(jQuery, jQuery.fn.dataTable);
}
})(window, document);
/* =========================================================
* bootstrap-datepicker.js
* Repo: https://github.com/eternicode/bootstrap-datepicker/
* Demo: http://eternicode.github.io/bootstrap-datepicker/
* Docs: http://bootstrap-datepicker.readthedocs.org/
* Forked from http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Started by Stefan Petre; improvements by Andrew Rowls + contributors
*
* 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.
* ========================================================= */
(function ($, undefined) {
var $window = $(window);
function UTCDate() {
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday() {
var today = new Date();
return UTCDate(today.getFullYear(), today.getMonth(), today.getDate());
}
function alias(method) {
return function () {
return this[method].apply(this, arguments);
};
}
var DateArray = (function () {
var extras = {
get: function (i) {
return this.slice(i)[0];
},
contains: function (d) {
// Array.indexOf is not cross-browser;
// $.inArray doesn't work with Dates
var val = d && d.valueOf();
for (var i = 0, l = this.length; i < l; i++)
if (this[i].valueOf() === val)
return i;
return -1;
},
remove: function (i) {
this.splice(i, 1);
},
replace: function (new_array) {
if (!new_array)
return;
if (!$.isArray(new_array))
new_array = [new_array];
this.clear();
this.push.apply(this, new_array);
},
clear: function () {
this.splice(0);
},
copy: function () {
var a = new DateArray();
a.replace(this);
return a;
}
};
return function () {
var a = [];
a.push.apply(a, arguments);
$.extend(a, extras);
return a;
};
})();
// Picker object
var Datepicker = function (element, options) {
this.dates = new DateArray();
this.viewDate = UTCToday();
this.focusDate = null;
this._process_options(options);
this.element = $(element);
this.isInline = false;
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on, .input-group-addon, .btn') : false;
this.hasInput = this.component && this.element.find('input').length;
if (this.component && this.component.length === 0)
this.component = false;
this.picker = $(DPGlobal.template);
this._buildEvents();
this._attachEvents();
if (this.isInline) {
this.picker.addClass('datepicker-inline').appendTo(this.element);
}
else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.o.rtl) {
this.picker.addClass('datepicker-rtl');
}
this.viewMode = this.o.startView;
if (this.o.calendarWeeks)
this.picker.find('tfoot th.today')
.attr('colspan', function (i, val) {
return parseInt(val) + 1;
});
this._allow_update = false;
this.setStartDate(this._o.startDate);
this.setEndDate(this._o.endDate);
this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled);
this.fillDow();
this.fillMonths();
this._allow_update = true;
this.update();
this.showMode();
if (this.isInline) {
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_process_options: function (opts) {
// Store raw options for reference
this._o = $.extend({}, this._o, opts);
// Processed options
var o = this.o = $.extend({}, this._o);
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
var lang = o.language;
if (!dates[lang]) {
lang = lang.split('-')[0];
if (!dates[lang])
lang = defaults.language;
}
o.language = lang;
switch (o.startView) {
case 2:
case 'decade':
o.startView = 2;
break;
case 1:
case 'year':
o.startView = 1;
break;
default:
o.startView = 0;
}
switch (o.minViewMode) {
case 1:
case 'months':
o.minViewMode = 1;
break;
case 2:
case 'years':
o.minViewMode = 2;
break;
default:
o.minViewMode = 0;
}
o.startView = Math.max(o.startView, o.minViewMode);
// true, false, or Number > 0
if (o.multidate !== true) {
o.multidate = Number(o.multidate) || false;
if (o.multidate !== false)
o.multidate = Math.max(0, o.multidate);
else
o.multidate = 1;
}
o.multidateSeparator = String(o.multidateSeparator);
o.weekStart %= 7;
o.weekEnd = ((o.weekStart + 6) % 7);
var format = DPGlobal.parseFormat(o.format);
if (o.startDate !== -Infinity) {
if (!!o.startDate) {
if (o.startDate instanceof Date)
o.startDate = this._local_to_utc(this._zero_time(o.startDate));
else
o.startDate = DPGlobal.parseDate(o.startDate, format, o.language);
}
else {
o.startDate = -Infinity;
}
}
if (o.endDate !== Infinity) {
if (!!o.endDate) {
if (o.endDate instanceof Date)
o.endDate = this._local_to_utc(this._zero_time(o.endDate));
else
o.endDate = DPGlobal.parseDate(o.endDate, format, o.language);
}
else {
o.endDate = Infinity;
}
}
o.daysOfWeekDisabled = o.daysOfWeekDisabled || [];
if (!$.isArray(o.daysOfWeekDisabled))
o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/);
o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) {
return parseInt(d, 10);
});
var plc = String(o.orientation).toLowerCase().split(/\s+/g),
_plc = o.orientation.toLowerCase();
plc = $.grep(plc, function (word) {
return (/^auto|left|right|top|bottom$/).test(word);
});
o.orientation = {x: 'auto', y: 'auto'};
if (!_plc || _plc === 'auto')
; // no action
else if (plc.length === 1) {
switch (plc[0]) {
case 'top':
case 'bottom':
o.orientation.y = plc[0];
break;
case 'left':
case 'right':
o.orientation.x = plc[0];
break;
}
}
else {
_plc = $.grep(plc, function (word) {
return (/^left|right$/).test(word);
});
o.orientation.x = _plc[0] || 'auto';
_plc = $.grep(plc, function (word) {
return (/^top|bottom$/).test(word);
});
o.orientation.y = _plc[0] || 'auto';
}
},
_events: [],
_secondaryEvents: [],
_applyEvents: function (evs) {
for (var i = 0, el, ch, ev; i < evs.length; i++) {
el = evs[i][0];
if (evs[i].length === 2) {
ch = undefined;
ev = evs[i][1];
}
else if (evs[i].length === 3) {
ch = evs[i][1];
ev = evs[i][2];
}
el.on(ev, ch);
}
},
_unapplyEvents: function (evs) {
for (var i = 0, el, ev, ch; i < evs.length; i++) {
el = evs[i][0];
if (evs[i].length === 2) {
ch = undefined;
ev = evs[i][1];
}
else if (evs[i].length === 3) {
ch = evs[i][1];
ev = evs[i][2];
}
el.off(ev, ch);
}
},
_buildEvents: function () {
if (this.isInput) { // single input
this._events = [
[this.element, {
focus: $.proxy(this.show, this),
keyup: $.proxy(function (e) {
if ($.inArray(e.keyCode, [27, 37, 39, 38, 40, 32, 13, 9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this)
}]
];
}
else if (this.component && this.hasInput) { // component: input + button
this._events = [
// For components that are not readonly, allow keyboard nav
[this.element.find('input'), {
focus: $.proxy(this.show, this),
keyup: $.proxy(function (e) {
if ($.inArray(e.keyCode, [27, 37, 39, 38, 40, 32, 13, 9]) === -1)
this.update();
}, this),
keydown: $.proxy(this.keydown, this)
}],
[this.component, {
click: $.proxy(this.show, this)
}]
];
}
else if (this.element.is('div')) { // inline datepicker
this.isInline = true;
}
else {
this._events = [
[this.element, {
click: $.proxy(this.show, this)
}]
];
}
this._events.push(
// Component: listen for blur on element descendants
[this.element, '*', {
blur: $.proxy(function (e) {
this._focused_from = e.target;
}, this)
}],
// Input: listen for blur on element
[this.element, {
blur: $.proxy(function (e) {
this._focused_from = e.target;
}, this)
}]
);
this._secondaryEvents = [
[this.picker, {
click: $.proxy(this.click, this)
}],
[$(window), {
resize: $.proxy(this.place, this)
}],
[$(document), {
'mousedown touchstart': $.proxy(function (e) {
// Clicked outside the datepicker, hide it
if (!(
this.element.is(e.target) ||
this.element.find(e.target).length ||
this.picker.is(e.target) ||
this.picker.find(e.target).length
)) {
this.hide();
}
}, this)
}]
];
},
_attachEvents: function () {
this._detachEvents();
this._applyEvents(this._events);
},
_detachEvents: function () {
this._unapplyEvents(this._events);
},
_attachSecondaryEvents: function () {
this._detachSecondaryEvents();
this._applyEvents(this._secondaryEvents);
},
_detachSecondaryEvents: function () {
this._unapplyEvents(this._secondaryEvents);
},
_trigger: function (event, altdate) {
var date = altdate || this.dates.get(-1),
local_date = this._utc_to_local(date);
this.element.trigger({
type: event,
date: local_date,
dates: $.map(this.dates, this._utc_to_local),
format: $.proxy(function (ix, format) {
if (arguments.length === 0) {
ix = this.dates.length - 1;
format = this.o.format;
}
else if (typeof ix === 'string') {
format = ix;
ix = this.dates.length - 1;
}
format = format || this.o.format;
var date = this.dates.get(ix);
return DPGlobal.formatDate(date, format, this.o.language);
}, this)
});
},
show: function () {
if (!this.isInline)
this.picker.appendTo('body');
this.picker.show();
this.place();
this._attachSecondaryEvents();
this._trigger('show');
},
hide: function () {
if (this.isInline)
return;
if (!this.picker.is(':visible'))
return;
this.focusDate = null;
this.picker.hide().detach();
this._detachSecondaryEvents();
this.viewMode = this.o.startView;
this.showMode();
if (
this.o.forceParse &&
(
this.isInput && this.element.val() ||
this.hasInput && this.element.find('input').val()
)
)
this.setValue();
this._trigger('hide');
},
remove: function () {
this.hide();
this._detachEvents();
this._detachSecondaryEvents();
this.picker.remove();
delete this.element.data().datepicker;
if (!this.isInput) {
delete this.element.data().date;
}
},
_utc_to_local: function (utc) {
return utc && new Date(utc.getTime() + (utc.getTimezoneOffset() * 60000));
},
_local_to_utc: function (local) {
return local && new Date(local.getTime() - (local.getTimezoneOffset() * 60000));
},
_zero_time: function (local) {
return local && new Date(local.getFullYear(), local.getMonth(), local.getDate());
},
_zero_utc_time: function (utc) {
return utc && new Date(Date.UTC(utc.getUTCFullYear(), utc.getUTCMonth(), utc.getUTCDate()));
},
getDates: function () {
return $.map(this.dates, this._utc_to_local);
},
getUTCDates: function () {
return $.map(this.dates, function (d) {
return new Date(d);
});
},
getDate: function () {
return this._utc_to_local(this.getUTCDate());
},
getUTCDate: function () {
return new Date(this.dates.get(-1));
},
setDates: function () {
var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
this.update.apply(this, args);
this._trigger('changeDate');
this.setValue();
},
setUTCDates: function () {
var args = $.isArray(arguments[0]) ? arguments[0] : arguments;
this.update.apply(this, $.map(args, this._utc_to_local));
this._trigger('changeDate');
this.setValue();
},
setDate: alias('setDates'),
setUTCDate: alias('setUTCDates'),
setValue: function () {
var formatted = this.getFormattedDate();
if (!this.isInput) {
if (this.component) {
this.element.find('input').val(formatted).change();
}
}
else {
this.element.val(formatted).change();
}
},
getFormattedDate: function (format) {
if (format === undefined)
format = this.o.format;
var lang = this.o.language;
return $.map(this.dates, function (d) {
return DPGlobal.formatDate(d, format, lang);
}).join(this.o.multidateSeparator);
},
setStartDate: function (startDate) {
this._process_options({startDate: startDate});
this.update();
this.updateNavArrows();
},
setEndDate: function (endDate) {
this._process_options({endDate: endDate});
this.update();
this.updateNavArrows();
},
setDaysOfWeekDisabled: function (daysOfWeekDisabled) {
this._process_options({daysOfWeekDisabled: daysOfWeekDisabled});
this.update();
this.updateNavArrows();
},
place: function () {
if (this.isInline)
return;
var calendarWidth = this.picker.outerWidth(),
calendarHeight = this.picker.outerHeight(),
visualPadding = 10,
windowWidth = $window.width(),
windowHeight = $window.height(),
scrollTop = $window.scrollTop();
var zIndex = parseInt(this.element.parents().filter(function () {
return $(this).css('z-index') !== 'auto';
}).first().css('z-index')) + 10;
var offset = this.component ? this.component.parent().offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(false);
var width = this.component ? this.component.outerWidth(true) : this.element.outerWidth(false);
var left = offset.left,
top = offset.top;
this.picker.removeClass(
'datepicker-orient-top datepicker-orient-bottom ' +
'datepicker-orient-right datepicker-orient-left'
);
if (this.o.orientation.x !== 'auto') {
this.picker.addClass('datepicker-orient-' + this.o.orientation.x);
if (this.o.orientation.x === 'right')
left -= calendarWidth - width;
}
// auto x orientation is best-placement: if it crosses a window
// edge, fudge it sideways
else {
// Default to left
this.picker.addClass('datepicker-orient-left');
if (offset.left < 0)
left -= offset.left - visualPadding;
else if (offset.left + calendarWidth > windowWidth)
left = windowWidth - calendarWidth - visualPadding;
}
// auto y orientation is best-situation: top or bottom, no fudging,
// decision based on which shows more of the calendar
var yorient = this.o.orientation.y,
top_overflow, bottom_overflow;
if (yorient === 'auto') {
top_overflow = -scrollTop + offset.top - calendarHeight;
bottom_overflow = scrollTop + windowHeight - (offset.top + height + calendarHeight);
if (Math.max(top_overflow, bottom_overflow) === bottom_overflow)
yorient = 'top';
else
yorient = 'bottom';
}
this.picker.addClass('datepicker-orient-' + yorient);
if (yorient === 'top')
top += height;
else
top -= calendarHeight + parseInt(this.picker.css('padding-top'));
this.picker.css({
top: top,
left: left,
zIndex: zIndex
});
},
_allow_update: true,
update: function () {
if (!this._allow_update)
return;
var oldDates = this.dates.copy(),
dates = [],
fromArgs = false;
if (arguments.length) {
$.each(arguments, $.proxy(function (i, date) {
if (date instanceof Date)
date = this._local_to_utc(date);
dates.push(date);
}, this));
fromArgs = true;
}
else {
dates = this.isInput
? this.element.val()
: this.element.data('date') || this.element.find('input').val();
if (dates && this.o.multidate)
dates = dates.split(this.o.multidateSeparator);
else
dates = [dates];
delete this.element.data().date;
}
dates = $.map(dates, $.proxy(function (date) {
return DPGlobal.parseDate(date, this.o.format, this.o.language);
}, this));
dates = $.grep(dates, $.proxy(function (date) {
return (
date < this.o.startDate ||
date > this.o.endDate || !date
);
}, this), true);
this.dates.replace(dates);
if (this.dates.length)
this.viewDate = new Date(this.dates.get(-1));
else if (this.viewDate < this.o.startDate)
this.viewDate = new Date(this.o.startDate);
else if (this.viewDate > this.o.endDate)
this.viewDate = new Date(this.o.endDate);
if (fromArgs) {
// setting date by clicking
this.setValue();
}
else if (dates.length) {
// setting date by typing
if (String(oldDates) !== String(this.dates))
this._trigger('changeDate');
}
if (!this.dates.length && oldDates.length)
this._trigger('clearDate');
this.fill();
},
fillDow: function () {
var dowCnt = this.o.weekStart,
html = '<tr>';
if (this.o.calendarWeeks) {
var cell = '<th class="cw"> </th>';
html += cell;
this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
}
while (dowCnt < this.o.weekStart + 7) {
html += '<th class="dow">' + dates[this.o.language].daysMin[(dowCnt++) % 7] + '</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function () {
var html = '',
i = 0;
while (i < 12) {
html += '<span class="month">' + dates[this.o.language].monthsShort[i++] + '</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
setRange: function (range) {
if (!range || !range.length)
delete this.range;
else
this.range = $.map(range, function (d) {
return d.valueOf();
});
this.fill();
},
getClassNames: function (date) {
var cls = [],
year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth(),
today = new Date();
if (date.getUTCFullYear() < year || (date.getUTCFullYear() === year && date.getUTCMonth() < month)) {
cls.push('old');
}
else if (date.getUTCFullYear() > year || (date.getUTCFullYear() === year && date.getUTCMonth() > month)) {
cls.push('new');
}
if (this.focusDate && date.valueOf() === this.focusDate.valueOf())
cls.push('focused');
// Compare internal UTC date with local today, not UTC today
if (this.o.todayHighlight &&
date.getUTCFullYear() === today.getFullYear() &&
date.getUTCMonth() === today.getMonth() &&
date.getUTCDate() === today.getDate()) {
cls.push('today');
}
if (this.dates.contains(date) !== -1)
cls.push('active');
if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate ||
$.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) {
cls.push('disabled');
}
if (this.range) {
if (date > this.range[0] && date < this.range[this.range.length - 1]) {
cls.push('range');
}
if ($.inArray(date.valueOf(), this.range) !== -1) {
cls.push('selected');
}
}
return cls;
},
fill: function () {
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity,
startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity,
endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity,
endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity,
todaytxt = dates[this.o.language].today || dates['en'].today || '',
cleartxt = dates[this.o.language].clear || dates['en'].clear || '',
tooltip;
this.picker.find('.datepicker-days thead th.datepicker-switch')
.text(dates[this.o.language].months[month] + ' ' + year);
this.picker.find('tfoot th.today')
.text(todaytxt)
.toggle(this.o.todayBtn !== false);
this.picker.find('tfoot th.clear')
.text(cleartxt)
.toggle(this.o.clearBtn !== false);
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month - 1, 28),
day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7) % 7);
var nextMonth = new Date(prevMonth);
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName;
while (prevMonth.valueOf() < nextMonth) {
if (prevMonth.getUTCDay() === this.o.weekStart) {
html.push('<tr>');
if (this.o.calendarWeeks) {
// ISO 8601: First week contains first thursday.
// ISO also states week starts on Monday, but we can be more abstract here.
var
// Start of current week: based on weekstart/current date
ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5),
// Thursday of this week
th = new Date(Number(ws) + (7 + 4 - ws.getUTCDay()) % 7 * 864e5),
// First Thursday of year, year from thursday
yth = new Date(Number(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay()) % 7 * 864e5),
// Calendar week: ms between thursdays, div ms per day, div 7 days
calWeek = (th - yth) / 864e5 / 7 + 1;
html.push('<td class="cw">' + calWeek + '</td>');
}
}
clsName = this.getClassNames(prevMonth);
clsName.push('day');
if (this.o.beforeShowDay !== $.noop) {
var before = this.o.beforeShowDay(this._utc_to_local(prevMonth));
if (before === undefined)
before = {};
else if (typeof(before) === 'boolean')
before = {enabled: before};
else if (typeof(before) === 'string')
before = {classes: before};
if (before.enabled === false)
clsName.push('disabled');
if (before.classes)
clsName = clsName.concat(before.classes.split(/\s+/));
if (before.tooltip)
tooltip = before.tooltip;
}
clsName = $.unique(clsName);
html.push('<td class="' + clsName.join(' ') + '"' + (tooltip ? ' title="' + tooltip + '"' : '') + '>' + prevMonth.getUTCDate() + '</td>');
if (prevMonth.getUTCDay() === this.o.weekEnd) {
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate() + 1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
$.each(this.dates, function (i, d) {
if (d.getUTCFullYear() === year)
months.eq(d.getUTCMonth()).addClass('active');
});
if (year < startYear || year > endYear) {
months.addClass('disabled');
}
if (year === startYear) {
months.slice(0, startMonth).addClass('disabled');
}
if (year === endYear) {
months.slice(endMonth + 1).addClass('disabled');
}
html = '';
year = parseInt(year / 10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
var years = $.map(this.dates, function (d) {
return d.getUTCFullYear();
}),
classes;
for (var i = -1; i < 11; i++) {
classes = ['year'];
if (i === -1)
classes.push('old');
else if (i === 10)
classes.push('new');
if ($.inArray(year, years) !== -1)
classes.push('active');
if (year < startYear || year > endYear)
classes.push('disabled');
html += '<span class="' + classes.join(' ') + '">' + year + '</span>';
year += 1;
}
yearCont.html(html);
},
updateNavArrows: function () {
if (!this._allow_update)
return;
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth();
switch (this.viewMode) {
case 0:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) {
this.picker.find('.prev').css({visibility: 'hidden'});
}
else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) {
this.picker.find('.next').css({visibility: 'hidden'});
}
else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
case 1:
case 2:
if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) {
this.picker.find('.prev').css({visibility: 'hidden'});
}
else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) {
this.picker.find('.next').css({visibility: 'hidden'});
}
else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
}
},
click: function (e) {
e.preventDefault();
var target = $(e.target).closest('span, td, th'),
year, month, day;
if (target.length === 1) {
switch (target[0].nodeName.toLowerCase()) {
case 'th':
switch (target[0].className) {
case 'datepicker-switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1);
switch (this.viewMode) {
case 0:
this.viewDate = this.moveMonth(this.viewDate, dir);
this._trigger('changeMonth', this.viewDate);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, dir);
if (this.viewMode === 1)
this._trigger('changeYear', this.viewDate);
break;
}
this.fill();
break;
case 'today':
var date = new Date();
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
this.showMode(-2);
var which = this.o.todayBtn === 'linked' ? null : 'view';
this._setDate(date, which);
break;
case 'clear':
var element;
if (this.isInput)
element = this.element;
else if (this.component)
element = this.element.find('input');
if (element)
element.val("").change();
this.update();
this._trigger('changeDate');
if (this.o.autoclose)
this.hide();
break;
}
break;
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
day = 1;
month = target.parent().find('span').index(target);
year = this.viewDate.getUTCFullYear();
this.viewDate.setUTCMonth(month);
this._trigger('changeMonth', this.viewDate);
if (this.o.minViewMode === 1) {
this._setDate(UTCDate(year, month, day));
}
}
else {
day = 1;
month = 0;
year = parseInt(target.text(), 10) || 0;
this.viewDate.setUTCFullYear(year);
this._trigger('changeYear', this.viewDate);
if (this.o.minViewMode === 2) {
this._setDate(UTCDate(year, month, day));
}
}
this.showMode(-1);
this.fill();
}
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')) {
day = parseInt(target.text(), 10) || 1;
year = this.viewDate.getUTCFullYear();
month = this.viewDate.getUTCMonth();
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;
}
}
this._setDate(UTCDate(year, month, day));
}
break;
}
}
if (this.picker.is(':visible') && this._focused_from) {
$(this._focused_from).focus();
}
delete this._focused_from;
},
_toggle_multidate: function (date) {
var ix = this.dates.contains(date);
if (!date) {
this.dates.clear();
}
else if (ix !== -1) {
this.dates.remove(ix);
}
else {
this.dates.push(date);
}
if (typeof this.o.multidate === 'number')
while (this.dates.length > this.o.multidate)
this.dates.remove(0);
},
_setDate: function (date, which) {
if (!which || which === 'date')
this._toggle_multidate(date && new Date(date));
if (!which || which === 'view')
this.viewDate = date && new Date(date);
this.fill();
this.setValue();
this._trigger('changeDate');
var element;
if (this.isInput) {
element = this.element;
}
else if (this.component) {
element = this.element.find('input');
}
if (element) {
element.change();
}
if (this.o.autoclose && (!which || which === 'date')) {
this.hide();
}
},
moveMonth: function (date, dir) {
if (!date)
return undefined;
if (!dir)
return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag === 1) {
test = dir === -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function () {
return new_date.getUTCMonth() === month;
}
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function () {
return new_date.getUTCMonth() !== new_month;
};
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
if (new_month < 0 || new_month > 11)
new_month = (new_month + 12) % 12;
}
else {
// For magnitudes >1, move one month at a time...
for (var i = 0; i < mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function () {
return new_month !== new_date.getUTCMonth();
};
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()) {
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function (date, dir) {
return this.moveMonth(date, dir * 12);
},
dateWithinRange: function (date) {
return date >= this.o.startDate && date <= this.o.endDate;
},
keydown: function (e) {
if (this.picker.is(':not(:visible)')) {
if (e.keyCode === 27) // allow escape to hide and re-show picker
this.show();
return;
}
var dateChanged = false,
dir, newDate, newViewDate,
focusDate = this.focusDate || this.viewDate;
switch (e.keyCode) {
case 27: // escape
if (this.focusDate) {
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
}
else
this.hide();
e.preventDefault();
break;
case 37: // left
case 39: // right
if (!this.o.keyboardNavigation)
break;
dir = e.keyCode === 37 ? -1 : 1;
if (e.ctrlKey) {
newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveYear(focusDate, dir);
this._trigger('changeYear', this.viewDate);
}
else if (e.shiftKey) {
newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveMonth(focusDate, dir);
this._trigger('changeMonth', this.viewDate);
}
else {
newDate = new Date(this.dates.get(-1) || UTCToday());
newDate.setUTCDate(newDate.getUTCDate() + dir);
newViewDate = new Date(focusDate);
newViewDate.setUTCDate(focusDate.getUTCDate() + dir);
}
if (this.dateWithinRange(newDate)) {
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 38: // up
case 40: // down
if (!this.o.keyboardNavigation)
break;
dir = e.keyCode === 38 ? -1 : 1;
if (e.ctrlKey) {
newDate = this.moveYear(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveYear(focusDate, dir);
this._trigger('changeYear', this.viewDate);
}
else if (e.shiftKey) {
newDate = this.moveMonth(this.dates.get(-1) || UTCToday(), dir);
newViewDate = this.moveMonth(focusDate, dir);
this._trigger('changeMonth', this.viewDate);
}
else {
newDate = new Date(this.dates.get(-1) || UTCToday());
newDate.setUTCDate(newDate.getUTCDate() + dir * 7);
newViewDate = new Date(focusDate);
newViewDate.setUTCDate(focusDate.getUTCDate() + dir * 7);
}
if (this.dateWithinRange(newDate)) {
this.focusDate = this.viewDate = newViewDate;
this.setValue();
this.fill();
e.preventDefault();
}
break;
case 32: // spacebar
// Spacebar is used in manually typing dates in some formats.
// As such, its behavior should not be hijacked.
break;
case 13: // enter
focusDate = this.focusDate || this.dates.get(-1) || this.viewDate;
this._toggle_multidate(focusDate);
dateChanged = true;
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.setValue();
this.fill();
if (this.picker.is(':visible')) {
e.preventDefault();
if (this.o.autoclose)
this.hide();
}
break;
case 9: // tab
this.focusDate = null;
this.viewDate = this.dates.get(-1) || this.viewDate;
this.fill();
this.hide();
break;
}
if (dateChanged) {
if (this.dates.length)
this._trigger('changeDate');
else
this._trigger('clearDate');
var element;
if (this.isInput) {
element = this.element;
}
else if (this.component) {
element = this.element.find('input');
}
if (element) {
element.change();
}
}
},
showMode: function (dir) {
if (dir) {
this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir));
}
this.picker
.find('>div')
.hide()
.filter('.datepicker-' + DPGlobal.modes[this.viewMode].clsName)
.css('display', 'block');
this.updateNavArrows();
}
};
var DateRangePicker = function (element, options) {
this.element = $(element);
this.inputs = $.map(options.inputs, function (i) {
return i.jquery ? i[0] : i;
});
delete options.inputs;
$(this.inputs)
.datepicker(options)
.bind('changeDate', $.proxy(this.dateUpdated, this));
this.pickers = $.map(this.inputs, function (i) {
return $(i).data('datepicker');
});
this.updateDates();
};
DateRangePicker.prototype = {
updateDates: function () {
this.dates = $.map(this.pickers, function (i) {
return i.getUTCDate();
});
this.updateRanges();
},
updateRanges: function () {
var range = $.map(this.dates, function (d) {
return d.valueOf();
});
$.each(this.pickers, function (i, p) {
p.setRange(range);
});
},
dateUpdated: function (e) {
// `this.updating` is a workaround for preventing infinite recursion
// between `changeDate` triggering and `setUTCDate` calling. Until
// there is a better mechanism.
if (this.updating)
return;
this.updating = true;
var dp = $(e.target).data('datepicker'),
new_date = dp.getUTCDate(),
i = $.inArray(e.target, this.inputs),
l = this.inputs.length;
if (i === -1)
return;
$.each(this.pickers, function (i, p) {
if (!p.getUTCDate())
p.setUTCDate(new_date);
});
if (new_date < this.dates[i]) {
// Date being moved earlier/left
while (i >= 0 && new_date < this.dates[i]) {
this.pickers[i--].setUTCDate(new_date);
}
}
else if (new_date > this.dates[i]) {
// Date being moved later/right
while (i < l && new_date > this.dates[i]) {
this.pickers[i++].setUTCDate(new_date);
}
}
this.updateDates();
delete this.updating;
},
remove: function () {
$.map(this.pickers, function (p) {
p.remove();
});
delete this.element.data().datepicker;
}
};
function opts_from_el(el, prefix) {
// Derive options from element data-attrs
var data = $(el).data(),
out = {}, inkey,
replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])');
prefix = new RegExp('^' + prefix.toLowerCase());
function re_lower(_, a) {
return a.toLowerCase();
}
for (var key in data)
if (prefix.test(key)) {
inkey = key.replace(replace, re_lower);
out[inkey] = data[key];
}
return out;
}
function opts_from_locale(lang) {
// Derive options from locale plugins
var out = {};
// Check if "de-DE" style date is available, if not language should
// fallback to 2 letter code eg "de"
if (!dates[lang]) {
lang = lang.split('-')[0];
if (!dates[lang])
return;
}
var d = dates[lang];
$.each(locale_opts, function (i, k) {
if (k in d)
out[k] = d[k];
});
return out;
}
var old = $.fn.datepicker;
$.fn.datepicker = function (option) {
var args = Array.apply(null, arguments);
args.shift();
var internal_return;
this.each(function () {
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option === 'object' && option;
if (!data) {
var elopts = opts_from_el(this, 'date'),
// Preliminary otions
xopts = $.extend({}, defaults, elopts, options),
locopts = opts_from_locale(xopts.language),
// Options priority: js args, data-attrs, locales, defaults
opts = $.extend({}, defaults, locopts, elopts, options);
if ($this.is('.input-daterange') || opts.inputs) {
var ropts = {
inputs: opts.inputs || $this.find('input').toArray()
};
$this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts))));
}
else {
$this.data('datepicker', (data = new Datepicker(this, opts)));
}
}
if (typeof option === 'string' && typeof data[option] === 'function') {
internal_return = data[option].apply(data, args);
if (internal_return !== undefined)
return false;
}
});
if (internal_return !== undefined)
return internal_return;
else
return this;
};
var defaults = $.fn.datepicker.defaults = {
autoclose: false,
beforeShowDay: $.noop,
calendarWeeks: false,
clearBtn: false,
daysOfWeekDisabled: [],
endDate: Infinity,
forceParse: true,
format: 'mm/dd/yyyy',
keyboardNavigation: true,
language: 'en',
minViewMode: 0,
multidate: false,
multidateSeparator: ',',
orientation: "auto",
rtl: false,
startDate: -Infinity,
startView: 0,
todayBtn: false,
todayHighlight: false,
weekStart: 0
};
var locale_opts = $.fn.datepicker.locale_opts = [
'format',
'rtl',
'weekStart'
];
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today",
clear: "Clear"
}
};
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function (format) {
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0) {
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function (date, format, language) {
if (!date)
return undefined;
if (date instanceof Date)
return date;
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var part_re = /([\-+]\d+)([dmwy])/,
parts = date.match(/([\-+]\d+)([dmwy])/g),
part, dir, i;
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
date = new Date();
for (i = 0; i < parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch (part[2]) {
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
}
parts = date && date.match(this.nonpunctuation) || [];
date = new Date();
var parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function (d, v) {
return d.setUTCFullYear(v);
},
yy: function (d, v) {
return d.setUTCFullYear(2000 + v);
},
m: function (d, v) {
if (isNaN(d))
return d;
v -= 1;
while (v < 0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() !== v)
d.setUTCDate(d.getUTCDate() - 1);
return d;
},
d: function (d, v) {
return d.setUTCDate(v);
}
},
val, filtered;
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length !== fparts.length) {
fparts = $(fparts).filter(function (i, p) {
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
function match_part() {
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m === p;
}
if (parts.length === fparts.length) {
var cnt;
for (i = 0, cnt = fparts.length; i < cnt; i++) {
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)) {
switch (part) {
case 'MM':
filtered = $(dates[language].months).filter(match_part);
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(match_part);
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
var _date, s;
for (i = 0; i < setters_order.length; i++) {
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s])) {
_date = new Date(date);
setters_map[s](_date, parsed[s]);
if (!isNaN(_date))
date = _date;
}
}
}
return date;
},
formatDate: function (date, format, language) {
if (!date)
return '';
if (typeof format === 'string')
format = DPGlobal.parseFormat(format);
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
date = [];
var seps = $.extend([], format.separators);
for (var i = 0, cnt = format.parts.length; i <= cnt; i++) {
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>' +
'<tr>' +
'<th class="prev">«</th>' +
'<th colspan="5" class="datepicker-switch"></th>' +
'<th class="next">»</th>' +
'</tr>' +
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot>' +
'<tr>' +
'<th colspan="7" class="today"></th>' +
'</tr>' +
'<tr>' +
'<th colspan="7" class="clear"></th>' +
'</tr>' +
'</tfoot>'
};
DPGlobal.template = '<div class="datepicker">' +
'<div class="datepicker-days">' +
'<table class=" table-condensed">' +
DPGlobal.headTemplate +
'<tbody></tbody>' +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'<div class="datepicker-months">' +
'<table class="table-condensed">' +
DPGlobal.headTemplate +
DPGlobal.contTemplate +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'<div class="datepicker-years">' +
'<table class="table-condensed">' +
DPGlobal.headTemplate +
DPGlobal.contTemplate +
DPGlobal.footTemplate +
'</table>' +
'</div>' +
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
/* DATEPICKER NO CONFLICT
* =================== */
$.fn.datepicker.noConflict = function () {
$.fn.datepicker = old;
return this;
};
/* DATEPICKER DATA-API
* ================== */
$(document).on(
'focus.datepicker.data-api click.datepicker.data-api',
'[data-provide="datepicker"]',
function (e) {
var $this = $(this);
if ($this.data('datepicker'))
return;
e.preventDefault();
// component click requires us to explicitly show it
$this.datepicker('show');
}
);
$(function () {
$('[data-provide="datepicker-inline"]').datepicker();
});
}(window.jQuery));
(function ($) {
"use strict";
var defaultOptions = {
tagClass: function (item) {
return 'label label-info';
},
itemValue: function (item) {
return item ? item.toString() : item;
},
itemText: function (item) {
return this.itemValue(item);
},
freeInput: true,
addOnBlur: true,
maxTags: undefined,
maxChars: undefined,
confirmKeys: [13, 44],
onTagExists: function (item, $tag) {
$tag.hide().fadeIn();
},
trimValue: false,
allowDuplicates: false
};
/**
* Constructor function
*/
function TagsInput(element, options) {
this.itemsArray = [];
this.$element = $(element);
this.$element.hide();
this.isSelect = (element.tagName === 'SELECT');
this.multiple = (this.isSelect && element.hasAttribute('multiple'));
this.objectItems = options && options.itemValue;
this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : '';
this.inputSize = Math.max(1, this.placeholderText.length);
this.$container = $('<div class="bootstrap-tagsinput"></div>');
this.$input = $('<input type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container);
this.$element.after(this.$container);
this.build(options);
}
TagsInput.prototype = {
constructor: TagsInput,
/**
* Adds the given item as a new tag. Pass true to dontPushVal to prevent
* updating the elements val()
*/
add: function (item, dontPushVal) {
var self = this;
if (self.options.maxTags && self.itemsArray.length >= self.options.maxTags)
return;
// Ignore falsey values, except false
if (item !== false && !item)
return;
// Trim value
if (typeof item === "string" && self.options.trimValue) {
item = $.trim(item);
}
// Throw an error when trying to add an object while the itemValue option was not set
if (typeof item === "object" && !self.objectItems)
throw("Can't add objects when itemValue option is not set");
// Ignore strings only containg whitespace
if (item.toString().match(/^\s*$/))
return;
// If SELECT but not multiple, remove current tag
if (self.isSelect && !self.multiple && self.itemsArray.length > 0)
self.remove(self.itemsArray[0]);
if (typeof item === "string" && this.$element[0].tagName === 'INPUT') {
var items = item.split(',');
if (items.length > 1) {
for (var i = 0; i < items.length; i++) {
this.add(items[i], true);
}
if (!dontPushVal)
self.pushVal();
return;
}
}
var itemValue = self.options.itemValue(item),
itemText = self.options.itemText(item),
tagClass = self.options.tagClass(item);
// Ignore items allready added
var existing = $.grep(self.itemsArray, function (item) {
return self.options.itemValue(item) === itemValue;
})[0];
if (existing && !self.options.allowDuplicates) {
// Invoke onTagExists
if (self.options.onTagExists) {
var $existingTag = $(".tag", self.$container).filter(function () {
return $(this).data("item") === existing;
});
self.options.onTagExists(item, $existingTag);
}
return;
}
// if length greater than limit
if (self.items().toString().length + item.length + 1 > self.options.maxInputLength)
return;
// raise beforeItemAdd arg
var beforeItemAddEvent = $.Event('beforeItemAdd', {
item: item,
cancel: false
});
self.$element.trigger(beforeItemAddEvent);
if (beforeItemAddEvent.cancel)
return;
// register item in internal array and map
self.itemsArray.push(item);
// add a tag element
var $tag = $('<span class="tag ' + htmlEncode(tagClass) + '">' + htmlEncode(itemText) + '<span data-role="remove"></span></span>');
$tag.data('item', item);
self.findInputWrapper().before($tag);
$tag.after(' ');
// add <option /> if item represents a value not present in one of the <select />'s options
if (self.isSelect && !$('option[value="' + encodeURIComponent(itemValue) + '"]', self.$element)[0]) {
var $option = $('<option selected>' + htmlEncode(itemText) + '</option>');
$option.data('item', item);
$option.attr('value', itemValue);
self.$element.append($option);
}
if (!dontPushVal)
self.pushVal();
// Add class when reached maxTags
if (self.options.maxTags === self.itemsArray.length || self.items().toString().length === self.options.maxInputLength)
self.$container.addClass('bootstrap-tagsinput-max');
self.$element.trigger($.Event('itemAdded', {item: item}));
self.$input.typeahead('val', '');
},
/**
* Removes the given item. Pass true to dontPushVal to prevent updating the
* elements val()
*/
remove: function (item, dontPushVal) {
var self = this;
if (self.objectItems) {
if (typeof item === "object")
item = $.grep(self.itemsArray, function (other) {
return self.options.itemValue(other) == self.options.itemValue(item);
});
else
item = $.grep(self.itemsArray, function (other) {
return self.options.itemValue(other) == item;
});
item = item[item.length - 1];
}
if (item) {
var beforeItemRemoveEvent = $.Event('beforeItemRemove', {
item: item,
cancel: false
});
self.$element.trigger(beforeItemRemoveEvent);
if (beforeItemRemoveEvent.cancel)
return;
$('.tag', self.$container).filter(function () {
return $(this).data('item') === item;
}).remove();
$('option', self.$element).filter(function () {
return $(this).data('item') === item;
}).remove();
if ($.inArray(item, self.itemsArray) !== -1)
self.itemsArray.splice($.inArray(item, self.itemsArray), 1);
}
if (!dontPushVal)
self.pushVal();
// Remove class when reached maxTags
if (self.options.maxTags > self.itemsArray.length)
self.$container.removeClass('bootstrap-tagsinput-max');
self.$element.trigger($.Event('itemRemoved', {item: item}));
},
/**
* Removes all items
*/
removeAll: function () {
var self = this;
$('.tag', self.$container).remove();
$('option', self.$element).remove();
while (self.itemsArray.length > 0)
self.itemsArray.pop();
self.pushVal();
},
/**
* Refreshes the tags so they match the text/value of their corresponding
* item.
*/
refresh: function () {
var self = this;
$('.tag', self.$container).each(function () {
var $tag = $(this),
item = $tag.data('item'),
itemValue = self.options.itemValue(item),
itemText = self.options.itemText(item),
tagClass = self.options.tagClass(item);
// Update tag's class and inner text
$tag.attr('class', null);
$tag.addClass('tag ' + htmlEncode(tagClass));
$tag.contents().filter(function () {
return this.nodeType == 3;
})[0].nodeValue = htmlEncode(itemText);
if (self.isSelect) {
var option = $('option', self.$element).filter(function () {
return $(this).data('item') === item;
});
option.attr('value', itemValue);
}
});
},
/**
* Returns the items added as tags
*/
items: function () {
return this.itemsArray;
},
/**
* Assembly value by retrieving the value of each item, and set it on the
* element.
*/
pushVal: function () {
var self = this,
val = $.map(self.items(), function (item) {
return self.options.itemValue(item).toString();
});
self.$element.val(val, true).trigger('change');
},
/**
* Initializes the tags input behaviour on the element
*/
build: function (options) {
var self = this;
self.options = $.extend({}, defaultOptions, options);
// When itemValue is set, freeInput should always be false
if (self.objectItems)
self.options.freeInput = false;
makeOptionItemFunction(self.options, 'itemValue');
makeOptionItemFunction(self.options, 'itemText');
makeOptionFunction(self.options, 'tagClass');
// Typeahead Bootstrap version 2.3.2
if (self.options.typeahead) {
var typeahead = self.options.typeahead || {};
makeOptionFunction(typeahead, 'source');
self.$input.typeahead($.extend({}, typeahead, {
source: function (query, process) {
function processItems(items) {
var texts = [];
for (var i = 0; i < items.length; i++) {
var text = self.options.itemText(items[i]);
map[text] = items[i];
texts.push(text);
}
process(texts);
}
this.map = {};
var map = this.map,
data = typeahead.source(query);
if ($.isFunction(data.success)) {
// support for Angular callbacks
data.success(processItems);
} else if ($.isFunction(data.then)) {
// support for Angular promises
data.then(processItems);
} else {
// support for functions and jquery promises
$.when(data)
.then(processItems);
}
},
updater: function (text) {
self.add(this.map[text]);
},
matcher: function (text) {
return (text.toLowerCase().indexOf(this.query.trim().toLowerCase()) !== -1);
},
sorter: function (texts) {
return texts.sort();
},
highlighter: function (text) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return text.replace(regex, "<strong>$1</strong>");
}
}));
}
// typeahead.js
if (self.options.typeaheadjs) {
var typeaheadjs = self.options.typeaheadjs || {};
self.$input.typeahead(null, typeaheadjs).on('typeahead:selected', $.proxy(function (obj, datum) {
if (typeaheadjs.valueKey)
self.add(datum[typeaheadjs.valueKey]);
else
self.add(datum);
self.$input.typeahead('val', '');
}, self));
}
self.$container.on('click', $.proxy(function (event) {
if (!self.$element.attr('disabled')) {
self.$input.removeAttr('disabled');
}
self.$input.focus();
}, self));
if (self.options.addOnBlur && self.options.freeInput) {
self.$input.on('focusout', $.proxy(function (event) {
// HACK: only process on focusout when no typeahead opened, to
// avoid adding the typeahead text as tag
if ($('.typeahead, .twitter-typeahead', self.$container).length === 0) {
self.add(self.$input.val());
self.$input.val('');
}
}, self));
}
self.$container.on('keydown', 'input', $.proxy(function (event) {
var $input = $(event.target),
$inputWrapper = self.findInputWrapper();
if (self.$element.attr('disabled')) {
self.$input.attr('disabled', 'disabled');
return;
}
switch (event.which) {
// BACKSPACE
case 8:
if (doGetCaretPosition($input[0]) === 0) {
var prev = $inputWrapper.prev();
if (prev) {
self.remove(prev.data('item'));
}
}
break;
// DELETE
case 46:
if (doGetCaretPosition($input[0]) === 0) {
var next = $inputWrapper.next();
if (next) {
self.remove(next.data('item'));
}
}
break;
// LEFT ARROW
case 37:
// Try to move the input before the previous tag
var $prevTag = $inputWrapper.prev();
if ($input.val().length === 0 && $prevTag[0]) {
$prevTag.before($inputWrapper);
$input.focus();
}
break;
// RIGHT ARROW
case 39:
// Try to move the input after the next tag
var $nextTag = $inputWrapper.next();
if ($input.val().length === 0 && $nextTag[0]) {
$nextTag.after($inputWrapper);
$input.focus();
}
break;
default:
// ignore
}
// Reset internal input's size
var textLength = $input.val().length,
wordSpace = Math.ceil(textLength / 5),
size = textLength + wordSpace + 1;
$input.attr('size', Math.max(this.inputSize, $input.val().length));
}, self));
self.$container.on('keypress', 'input', $.proxy(function (event) {
var $input = $(event.target);
if (self.$element.attr('disabled')) {
self.$input.attr('disabled', 'disabled');
return;
}
var text = $input.val(),
maxLengthReached = self.options.maxChars && text.length >= self.options.maxChars;
if (self.options.freeInput && (keyCombinationInList(event, self.options.confirmKeys) || maxLengthReached)) {
self.add(maxLengthReached ? text.substr(0, self.options.maxChars) : text);
$input.val('');
event.preventDefault();
}
// Reset internal input's size
var textLength = $input.val().length,
wordSpace = Math.ceil(textLength / 5),
size = textLength + wordSpace + 1;
$input.attr('size', Math.max(this.inputSize, $input.val().length));
}, self));
// Remove icon clicked
self.$container.on('click', '[data-role=remove]', $.proxy(function (event) {
if (self.$element.attr('disabled')) {
return;
}
self.remove($(event.target).closest('.tag').data('item'));
}, self));
// Only add existing value as tags when using strings as tags
if (self.options.itemValue === defaultOptions.itemValue) {
if (self.$element[0].tagName === 'INPUT') {
self.add(self.$element.val());
} else {
$('option', self.$element).each(function () {
self.add($(this).attr('value'), true);
});
}
}
},
/**
* Removes all tagsinput behaviour and unregsiter all event handlers
*/
destroy: function () {
var self = this;
// Unbind events
self.$container.off('keypress', 'input');
self.$container.off('click', '[role=remove]');
self.$container.remove();
self.$element.removeData('tagsinput');
self.$element.show();
},
/**
* Sets focus on the tagsinput
*/
focus: function () {
this.$input.focus();
},
/**
* Returns the internal input element
*/
input: function () {
return this.$input;
},
/**
* Returns the element which is wrapped around the internal input. This
* is normally the $container, but typeahead.js moves the $input element.
*/
findInputWrapper: function () {
var elt = this.$input[0],
container = this.$container[0];
while (elt && elt.parentNode !== container)
elt = elt.parentNode;
return $(elt);
}
};
/**
* Register JQuery plugin
*/
$.fn.tagsinput = function (arg1, arg2) {
var results = [];
this.each(function () {
var tagsinput = $(this).data('tagsinput');
// Initialize a new tags input
if (!tagsinput) {
tagsinput = new TagsInput(this, arg1);
$(this).data('tagsinput', tagsinput);
results.push(tagsinput);
if (this.tagName === 'SELECT') {
$('option', $(this)).attr('selected', 'selected');
}
// Init tags from $(this).val()
$(this).val($(this).val());
} else if (!arg1 && !arg2) {
// tagsinput already exists
// no function, trying to init
results.push(tagsinput);
} else if (tagsinput[arg1] !== undefined) {
// Invoke function on existing tags input
var retVal = tagsinput[arg1](arg2);
if (retVal !== undefined)
results.push(retVal);
}
});
if (typeof arg1 == 'string') {
// Return the results from the invoked function calls
return results.length > 1 ? results : results[0];
} else {
return results;
}
};
$.fn.tagsinput.Constructor = TagsInput;
/**
* Most options support both a string or number as well as a function as
* option value. This function makes sure that the option with the given
* key in the given options is wrapped in a function
*/
function makeOptionItemFunction(options, key) {
if (typeof options[key] !== 'function') {
var propertyName = options[key];
options[key] = function (item) {
return item[propertyName];
};
}
}
function makeOptionFunction(options, key) {
if (typeof options[key] !== 'function') {
var value = options[key];
options[key] = function () {
return value;
};
}
}
/**
* HtmlEncodes the given value
*/
var htmlEncodeContainer = $('<div />');
function htmlEncode(value) {
if (value) {
return htmlEncodeContainer.text(value).html();
} else {
return '';
}
}
/**
* Returns the position of the caret in the given input field
* http://flightschool.acylt.com/devnotes/caret-position-woes/
*/
function doGetCaretPosition(oField) {
var iCaretPos = 0;
if (document.selection) {
oField.focus();
var oSel = document.selection.createRange();
oSel.moveStart('character', -oField.value.length);
iCaretPos = oSel.text.length;
} else if (oField.selectionStart || oField.selectionStart == '0') {
iCaretPos = oField.selectionStart;
}
return (iCaretPos);
}
/**
* Returns boolean indicates whether user has pressed an expected key combination.
* @param object keyPressEvent: JavaScript event object, refer
* http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
* @param object lookupList: expected key combinations, as in:
* [13, {which: 188, shiftKey: true}]
*/
function keyCombinationInList(keyPressEvent, lookupList) {
var found = false;
$.each(lookupList, function (index, keyCombination) {
if (typeof (keyCombination) === 'number' && keyPressEvent.which === keyCombination) {
found = true;
return false;
}
if (keyPressEvent.which === keyCombination.which) {
var alt = !keyCombination.hasOwnProperty('altKey') || keyPressEvent.altKey === keyCombination.altKey,
shift = !keyCombination.hasOwnProperty('shiftKey') || keyPressEvent.shiftKey === keyCombination.shiftKey,
ctrl = !keyCombination.hasOwnProperty('ctrlKey') || keyPressEvent.ctrlKey === keyCombination.ctrlKey;
if (alt && shift && ctrl) {
found = true;
return false;
}
}
});
return found;
}
/**
* Initialize tagsinput behaviour on inputs and selects which have
* data-role=tagsinput
*/
$(function () {
$("input[data-role=tagsinput], select[multiple][data-role=tagsinput]").tagsinput();
});
})(window.jQuery);
/*!
* typeahead.js 0.10.5
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/
(function ($) {
var _ = function () {
"use strict";
return {
isMsie: function () {
return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
},
isBlankString: function (str) {
return !str || /^\s*$/.test(str);
},
escapeRegExChars: function (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
isString: function (obj) {
return typeof obj === "string";
},
isNumber: function (obj) {
return typeof obj === "number";
},
isArray: $.isArray,
isFunction: $.isFunction,
isObject: $.isPlainObject,
isUndefined: function (obj) {
return typeof obj === "undefined";
},
toStr: function toStr(s) {
return _.isUndefined(s) || s === null ? "" : s + "";
},
bind: $.proxy,
each: function (collection, cb) {
$.each(collection, reverseArgs);
function reverseArgs(index, value) {
return cb(value, index);
}
},
map: $.map,
filter: $.grep,
every: function (obj, test) {
var result = true;
if (!obj) {
return result;
}
$.each(obj, function (key, val) {
if (!(result = test.call(null, val, key, obj))) {
return false;
}
});
return !!result;
},
some: function (obj, test) {
var result = false;
if (!obj) {
return result;
}
$.each(obj, function (key, val) {
if (result = test.call(null, val, key, obj)) {
return false;
}
});
return !!result;
},
mixin: $.extend,
getUniqueId: function () {
var counter = 0;
return function () {
return counter++;
};
}(),
templatify: function templatify(obj) {
return $.isFunction(obj) ? obj : template;
function template() {
return String(obj);
}
},
defer: function (fn) {
setTimeout(fn, 0);
},
debounce: function (func, wait, immediate) {
var timeout, result;
return function () {
var context = this, args = arguments, later, callNow;
later = function () {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
throttle: function (func, wait) {
var context, args, timeout, result, previous, later;
previous = 0;
later = function () {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function () {
var now = new Date(), remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
noop: function () {
}
};
}();
var VERSION = "0.10.5";
var tokenizers = function () {
"use strict";
return {
nonword: nonword,
whitespace: whitespace,
obj: {
nonword: getObjTokenizer(nonword),
whitespace: getObjTokenizer(whitespace)
}
};
function whitespace(str) {
str = _.toStr(str);
return str ? str.split(/\s+/) : [];
}
function nonword(str) {
str = _.toStr(str);
return str ? str.split(/\W+/) : [];
}
function getObjTokenizer(tokenizer) {
return function setKey() {
var args = [].slice.call(arguments, 0);
return function tokenize(o) {
var tokens = [];
_.each(args, function (k) {
tokens = tokens.concat(tokenizer(_.toStr(o[k])));
});
return tokens;
};
};
}
}();
var LruCache = function () {
"use strict";
function LruCache(maxSize) {
this.maxSize = _.isNumber(maxSize) ? maxSize : 100;
this.reset();
if (this.maxSize <= 0) {
this.set = this.get = $.noop;
}
}
_.mixin(LruCache.prototype, {
set: function set(key, val) {
var tailItem = this.list.tail, node;
if (this.size >= this.maxSize) {
this.list.remove(tailItem);
delete this.hash[tailItem.key];
}
if (node = this.hash[key]) {
node.val = val;
this.list.moveToFront(node);
} else {
node = new Node(key, val);
this.list.add(node);
this.hash[key] = node;
this.size++;
}
},
get: function get(key) {
var node = this.hash[key];
if (node) {
this.list.moveToFront(node);
return node.val;
}
},
reset: function reset() {
this.size = 0;
this.hash = {};
this.list = new List();
}
});
function List() {
this.head = this.tail = null;
}
_.mixin(List.prototype, {
add: function add(node) {
if (this.head) {
node.next = this.head;
this.head.prev = node;
}
this.head = node;
this.tail = this.tail || node;
},
remove: function remove(node) {
node.prev ? node.prev.next = node.next : this.head = node.next;
node.next ? node.next.prev = node.prev : this.tail = node.prev;
},
moveToFront: function (node) {
this.remove(node);
this.add(node);
}
});
function Node(key, val) {
this.key = key;
this.val = val;
this.prev = this.next = null;
}
return LruCache;
}();
var PersistentStorage = function () {
"use strict";
var ls, methods;
try {
ls = window.localStorage;
ls.setItem("~~~", "!");
ls.removeItem("~~~");
} catch (err) {
ls = null;
}
function PersistentStorage(namespace) {
this.prefix = ["__", namespace, "__"].join("");
this.ttlKey = "__ttl__";
this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix));
}
if (ls && window.JSON) {
methods = {
_prefix: function (key) {
return this.prefix + key;
},
_ttlKey: function (key) {
return this._prefix(key) + this.ttlKey;
},
get: function (key) {
if (this.isExpired(key)) {
this.remove(key);
}
return decode(ls.getItem(this._prefix(key)));
},
set: function (key, val, ttl) {
if (_.isNumber(ttl)) {
ls.setItem(this._ttlKey(key), encode(now() + ttl));
} else {
ls.removeItem(this._ttlKey(key));
}
return ls.setItem(this._prefix(key), encode(val));
},
remove: function (key) {
ls.removeItem(this._ttlKey(key));
ls.removeItem(this._prefix(key));
return this;
},
clear: function () {
var i, key, keys = [], len = ls.length;
for (i = 0; i < len; i++) {
if ((key = ls.key(i)).match(this.keyMatcher)) {
keys.push(key.replace(this.keyMatcher, ""));
}
}
for (i = keys.length; i--;) {
this.remove(keys[i]);
}
return this;
},
isExpired: function (key) {
var ttl = decode(ls.getItem(this._ttlKey(key)));
return _.isNumber(ttl) && now() > ttl ? true : false;
}
};
} else {
methods = {
get: _.noop,
set: _.noop,
remove: _.noop,
clear: _.noop,
isExpired: _.noop
};
}
_.mixin(PersistentStorage.prototype, methods);
return PersistentStorage;
function now() {
return new Date().getTime();
}
function encode(val) {
return JSON.stringify(_.isUndefined(val) ? null : val);
}
function decode(val) {
return JSON.parse(val);
}
}();
var Transport = function () {
"use strict";
var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, sharedCache = new LruCache(10);
function Transport(o) {
o = o || {};
this.cancelled = false;
this.lastUrl = null;
this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax;
this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get;
this._cache = o.cache === false ? new LruCache(0) : sharedCache;
}
Transport.setMaxPendingRequests = function setMaxPendingRequests(num) {
maxPendingRequests = num;
};
Transport.resetCache = function resetCache() {
sharedCache.reset();
};
_.mixin(Transport.prototype, {
_get: function (url, o, cb) {
var that = this, jqXhr;
if (this.cancelled || url !== this.lastUrl) {
return;
}
if (jqXhr = pendingRequests[url]) {
jqXhr.done(done).fail(fail);
} else if (pendingRequestsCount < maxPendingRequests) {
pendingRequestsCount++;
pendingRequests[url] = this._send(url, o).done(done).fail(fail).always(always);
} else {
this.onDeckRequestArgs = [].slice.call(arguments, 0);
}
function done(resp) {
cb && cb(null, resp);
that._cache.set(url, resp);
}
function fail() {
cb && cb(true);
}
function always() {
pendingRequestsCount--;
delete pendingRequests[url];
if (that.onDeckRequestArgs) {
that._get.apply(that, that.onDeckRequestArgs);
that.onDeckRequestArgs = null;
}
}
},
get: function (url, o, cb) {
var resp;
if (_.isFunction(o)) {
cb = o;
o = {};
}
this.cancelled = false;
this.lastUrl = url;
if (resp = this._cache.get(url)) {
_.defer(function () {
cb && cb(null, resp);
});
} else {
this._get(url, o, cb);
}
return !!resp;
},
cancel: function () {
this.cancelled = true;
}
});
return Transport;
function callbackToDeferred(fn) {
return function customSendWrapper(url, o) {
var deferred = $.Deferred();
fn(url, o, onSuccess, onError);
return deferred;
function onSuccess(resp) {
_.defer(function () {
deferred.resolve(resp);
});
}
function onError(err) {
_.defer(function () {
deferred.reject(err);
});
}
};
}
}();
var SearchIndex = function () {
"use strict";
function SearchIndex(o) {
o = o || {};
if (!o.datumTokenizer || !o.queryTokenizer) {
$.error("datumTokenizer and queryTokenizer are both required");
}
this.datumTokenizer = o.datumTokenizer;
this.queryTokenizer = o.queryTokenizer;
this.reset();
}
_.mixin(SearchIndex.prototype, {
bootstrap: function bootstrap(o) {
this.datums = o.datums;
this.trie = o.trie;
},
add: function (data) {
var that = this;
data = _.isArray(data) ? data : [data];
_.each(data, function (datum) {
var id, tokens;
id = that.datums.push(datum) - 1;
tokens = normalizeTokens(that.datumTokenizer(datum));
_.each(tokens, function (token) {
var node, chars, ch;
node = that.trie;
chars = token.split("");
while (ch = chars.shift()) {
node = node.children[ch] || (node.children[ch] = newNode());
node.ids.push(id);
}
});
});
},
get: function get(query) {
var that = this, tokens, matches;
tokens = normalizeTokens(this.queryTokenizer(query));
_.each(tokens, function (token) {
var node, chars, ch, ids;
if (matches && matches.length === 0) {
return false;
}
node = that.trie;
chars = token.split("");
while (node && (ch = chars.shift())) {
node = node.children[ch];
}
if (node && chars.length === 0) {
ids = node.ids.slice(0);
matches = matches ? getIntersection(matches, ids) : ids;
} else {
matches = [];
return false;
}
});
return matches ? _.map(unique(matches), function (id) {
return that.datums[id];
}) : [];
},
reset: function reset() {
this.datums = [];
this.trie = newNode();
},
serialize: function serialize() {
return {
datums: this.datums,
trie: this.trie
};
}
});
return SearchIndex;
function normalizeTokens(tokens) {
tokens = _.filter(tokens, function (token) {
return !!token;
});
tokens = _.map(tokens, function (token) {
return token.toLowerCase();
});
return tokens;
}
function newNode() {
return {
ids: [],
children: {}
};
}
function unique(array) {
var seen = {}, uniques = [];
for (var i = 0, len = array.length; i < len; i++) {
if (!seen[array[i]]) {
seen[array[i]] = true;
uniques.push(array[i]);
}
}
return uniques;
}
function getIntersection(arrayA, arrayB) {
var ai = 0, bi = 0, intersection = [];
arrayA = arrayA.sort(compare);
arrayB = arrayB.sort(compare);
var lenArrayA = arrayA.length, lenArrayB = arrayB.length;
while (ai < lenArrayA && bi < lenArrayB) {
if (arrayA[ai] < arrayB[bi]) {
ai++;
} else if (arrayA[ai] > arrayB[bi]) {
bi++;
} else {
intersection.push(arrayA[ai]);
ai++;
bi++;
}
}
return intersection;
function compare(a, b) {
return a - b;
}
}
}();
var oParser = function () {
"use strict";
return {
local: getLocal,
prefetch: getPrefetch,
remote: getRemote
};
function getLocal(o) {
return o.local || null;
}
function getPrefetch(o) {
var prefetch, defaults;
defaults = {
url: null,
thumbprint: "",
ttl: 24 * 60 * 60 * 1e3,
filter: null,
ajax: {}
};
if (prefetch = o.prefetch || null) {
prefetch = _.isString(prefetch) ? {
url: prefetch
} : prefetch;
prefetch = _.mixin(defaults, prefetch);
prefetch.thumbprint = VERSION + prefetch.thumbprint;
prefetch.ajax.type = prefetch.ajax.type || "GET";
prefetch.ajax.dataType = prefetch.ajax.dataType || "json";
!prefetch.url && $.error("prefetch requires url to be set");
}
return prefetch;
}
function getRemote(o) {
var remote, defaults;
defaults = {
url: null,
cache: true,
wildcard: "%QUERY",
replace: null,
rateLimitBy: "debounce",
rateLimitWait: 300,
send: null,
filter: null,
ajax: {}
};
if (remote = o.remote || null) {
remote = _.isString(remote) ? {
url: remote
} : remote;
remote = _.mixin(defaults, remote);
remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ? byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait);
remote.ajax.type = remote.ajax.type || "GET";
remote.ajax.dataType = remote.ajax.dataType || "json";
delete remote.rateLimitBy;
delete remote.rateLimitWait;
!remote.url && $.error("remote requires url to be set");
}
return remote;
function byDebounce(wait) {
return function (fn) {
return _.debounce(fn, wait);
};
}
function byThrottle(wait) {
return function (fn) {
return _.throttle(fn, wait);
};
}
}
}();
(function (root) {
"use strict";
var old, keys;
old = root.Bloodhound;
keys = {
data: "data",
protocol: "protocol",
thumbprint: "thumbprint"
};
root.Bloodhound = Bloodhound;
function Bloodhound(o) {
if (!o || !o.local && !o.prefetch && !o.remote) {
$.error("one of local, prefetch, or remote is required");
}
this.limit = o.limit || 5;
this.sorter = getSorter(o.sorter);
this.dupDetector = o.dupDetector || ignoreDuplicates;
this.local = oParser.local(o);
this.prefetch = oParser.prefetch(o);
this.remote = oParser.remote(o);
this.cacheKey = this.prefetch ? this.prefetch.cacheKey || this.prefetch.url : null;
this.index = new SearchIndex({
datumTokenizer: o.datumTokenizer,
queryTokenizer: o.queryTokenizer
});
this.storage = this.cacheKey ? new PersistentStorage(this.cacheKey) : null;
}
Bloodhound.noConflict = function noConflict() {
root.Bloodhound = old;
return Bloodhound;
};
Bloodhound.tokenizers = tokenizers;
_.mixin(Bloodhound.prototype, {
_loadPrefetch: function loadPrefetch(o) {
var that = this, serialized, deferred;
if (serialized = this._readFromStorage(o.thumbprint)) {
this.index.bootstrap(serialized);
deferred = $.Deferred().resolve();
} else {
deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse);
}
return deferred;
function handlePrefetchResponse(resp) {
that.clear();
that.add(o.filter ? o.filter(resp) : resp);
that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl);
}
},
_getFromRemote: function getFromRemote(query, cb) {
var that = this, url, uriEncodedQuery;
if (!this.transport) {
return;
}
query = query || "";
uriEncodedQuery = encodeURIComponent(query);
url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);
return this.transport.get(url, this.remote.ajax, handleRemoteResponse);
function handleRemoteResponse(err, resp) {
err ? cb([]) : cb(that.remote.filter ? that.remote.filter(resp) : resp);
}
},
_cancelLastRemoteRequest: function cancelLastRemoteRequest() {
this.transport && this.transport.cancel();
},
_saveToStorage: function saveToStorage(data, thumbprint, ttl) {
if (this.storage) {
this.storage.set(keys.data, data, ttl);
this.storage.set(keys.protocol, location.protocol, ttl);
this.storage.set(keys.thumbprint, thumbprint, ttl);
}
},
_readFromStorage: function readFromStorage(thumbprint) {
var stored = {}, isExpired;
if (this.storage) {
stored.data = this.storage.get(keys.data);
stored.protocol = this.storage.get(keys.protocol);
stored.thumbprint = this.storage.get(keys.thumbprint);
}
isExpired = stored.thumbprint !== thumbprint || stored.protocol !== location.protocol;
return stored.data && !isExpired ? stored.data : null;
},
_initialize: function initialize() {
var that = this, local = this.local, deferred;
deferred = this.prefetch ? this._loadPrefetch(this.prefetch) : $.Deferred().resolve();
local && deferred.done(addLocalToIndex);
this.transport = this.remote ? new Transport(this.remote) : null;
return this.initPromise = deferred.promise();
function addLocalToIndex() {
that.add(_.isFunction(local) ? local() : local);
}
},
initialize: function initialize(force) {
return !this.initPromise || force ? this._initialize() : this.initPromise;
},
add: function add(data) {
this.index.add(data);
},
get: function get(query, cb) {
var that = this, matches = [], cacheHit = false;
matches = this.index.get(query);
matches = this.sorter(matches).slice(0, this.limit);
matches.length < this.limit ? cacheHit = this._getFromRemote(query, returnRemoteMatches) : this._cancelLastRemoteRequest();
if (!cacheHit) {
(matches.length > 0 || !this.transport) && cb && cb(matches);
}
function returnRemoteMatches(remoteMatches) {
var matchesWithBackfill = matches.slice(0);
_.each(remoteMatches, function (remoteMatch) {
var isDuplicate;
isDuplicate = _.some(matchesWithBackfill, function (match) {
return that.dupDetector(remoteMatch, match);
});
!isDuplicate && matchesWithBackfill.push(remoteMatch);
return matchesWithBackfill.length < that.limit;
});
cb && cb(that.sorter(matchesWithBackfill));
}
},
clear: function clear() {
this.index.reset();
},
clearPrefetchCache: function clearPrefetchCache() {
this.storage && this.storage.clear();
},
clearRemoteCache: function clearRemoteCache() {
this.transport && Transport.resetCache();
},
ttAdapter: function ttAdapter() {
return _.bind(this.get, this);
}
});
return Bloodhound;
function getSorter(sortFn) {
return _.isFunction(sortFn) ? sort : noSort;
function sort(array) {
return array.sort(sortFn);
}
function noSort(array) {
return array;
}
}
function ignoreDuplicates() {
return false;
}
})(this);
var html = function () {
return {
wrapper: '<span class="twitter-typeahead"></span>',
dropdown: '<span class="tt-dropdown-menu"></span>',
dataset: '<div class="tt-dataset-%CLASS%"></div>',
suggestions: '<span class="tt-suggestions"></span>',
suggestion: '<div class="tt-suggestion"></div>'
};
}();
var css = function () {
"use strict";
var css = {
wrapper: {
position: "relative",
display: "inline-block"
},
hint: {
position: "absolute",
top: "0",
left: "0",
borderColor: "transparent",
boxShadow: "none",
opacity: "1"
},
input: {
position: "relative",
verticalAlign: "top",
backgroundColor: "transparent"
},
inputWithNoHint: {
position: "relative",
verticalAlign: "top"
},
dropdown: {
position: "absolute",
top: "100%",
left: "0",
zIndex: "100",
display: "none"
},
suggestions: {
display: "block"
},
suggestion: {
whiteSpace: "nowrap",
cursor: "pointer"
},
suggestionChild: {
whiteSpace: "normal"
},
ltr: {
left: "0",
right: "auto"
},
rtl: {
left: "auto",
right: " 0"
}
};
if (_.isMsie()) {
_.mixin(css.input, {
backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
});
}
if (_.isMsie() && _.isMsie() <= 7) {
_.mixin(css.input, {
marginTop: "-1px"
});
}
return css;
}();
var EventBus = function () {
"use strict";
var namespace = "typeahead:";
function EventBus(o) {
if (!o || !o.el) {
$.error("EventBus initialized without el");
}
this.$el = $(o.el);
}
_.mixin(EventBus.prototype, {
trigger: function (type) {
var args = [].slice.call(arguments, 1);
this.$el.trigger(namespace + type, args);
}
});
return EventBus;
}();
var EventEmitter = function () {
"use strict";
var splitter = /\s+/, nextTick = getNextTick();
return {
onSync: onSync,
onAsync: onAsync,
off: off,
trigger: trigger
};
function on(method, types, cb, context) {
var type;
if (!cb) {
return this;
}
types = types.split(splitter);
cb = context ? bindContext(cb, context) : cb;
this._callbacks = this._callbacks || {};
while (type = types.shift()) {
this._callbacks[type] = this._callbacks[type] || {
sync: [],
async: []
};
this._callbacks[type][method].push(cb);
}
return this;
}
function onAsync(types, cb, context) {
return on.call(this, "async", types, cb, context);
}
function onSync(types, cb, context) {
return on.call(this, "sync", types, cb, context);
}
function off(types) {
var type;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
while (type = types.shift()) {
delete this._callbacks[type];
}
return this;
}
function trigger(types) {
var type, callbacks, args, syncFlush, asyncFlush;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
args = [].slice.call(arguments, 1);
while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
syncFlush = getFlush(callbacks.sync, this, [type].concat(args));
asyncFlush = getFlush(callbacks.async, this, [type].concat(args));
syncFlush() && nextTick(asyncFlush);
}
return this;
}
function getFlush(callbacks, context, args) {
return flush;
function flush() {
var cancelled;
for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
cancelled = callbacks[i].apply(context, args) === false;
}
return !cancelled;
}
}
function getNextTick() {
var nextTickFn;
if (window.setImmediate) {
nextTickFn = function nextTickSetImmediate(fn) {
setImmediate(function () {
fn();
});
};
} else {
nextTickFn = function nextTickSetTimeout(fn) {
setTimeout(function () {
fn();
}, 0);
};
}
return nextTickFn;
}
function bindContext(fn, context) {
return fn.bind ? fn.bind(context) : function () {
fn.apply(context, [].slice.call(arguments, 0));
};
}
}();
var highlight = function (doc) {
"use strict";
var defaults = {
node: null,
pattern: null,
tagName: "strong",
className: null,
wordsOnly: false,
caseSensitive: false
};
return function hightlight(o) {
var regex;
o = _.mixin({}, defaults, o);
if (!o.node || !o.pattern) {
return;
}
o.pattern = _.isArray(o.pattern) ? o.pattern : [o.pattern];
regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
traverse(o.node, hightlightTextNode);
function hightlightTextNode(textNode) {
var match, patternNode, wrapperNode;
if (match = regex.exec(textNode.data)) {
wrapperNode = doc.createElement(o.tagName);
o.className && (wrapperNode.className = o.className);
patternNode = textNode.splitText(match.index);
patternNode.splitText(match[0].length);
wrapperNode.appendChild(patternNode.cloneNode(true));
textNode.parentNode.replaceChild(wrapperNode, patternNode);
}
return !!match;
}
function traverse(el, hightlightTextNode) {
var childNode, TEXT_NODE_TYPE = 3;
for (var i = 0; i < el.childNodes.length; i++) {
childNode = el.childNodes[i];
if (childNode.nodeType === TEXT_NODE_TYPE) {
i += hightlightTextNode(childNode) ? 1 : 0;
} else {
traverse(childNode, hightlightTextNode);
}
}
}
};
function getRegex(patterns, caseSensitive, wordsOnly) {
var escapedPatterns = [], regexStr;
for (var i = 0, len = patterns.length; i < len; i++) {
escapedPatterns.push(_.escapeRegExChars(patterns[i]));
}
regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
}
}(window.document);
var Input = function () {
"use strict";
var specialKeyCodeMap;
specialKeyCodeMap = {
9: "tab",
27: "esc",
37: "left",
39: "right",
13: "enter",
38: "up",
40: "down"
};
function Input(o) {
var that = this, onBlur, onFocus, onKeydown, onInput;
o = o || {};
if (!o.input) {
$.error("input is missing");
}
onBlur = _.bind(this._onBlur, this);
onFocus = _.bind(this._onFocus, this);
onKeydown = _.bind(this._onKeydown, this);
onInput = _.bind(this._onInput, this);
this.$hint = $(o.hint);
this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
if (this.$hint.length === 0) {
this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
}
if (!_.isMsie()) {
this.$input.on("input.tt", onInput);
} else {
this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function ($e) {
if (specialKeyCodeMap[$e.which || $e.keyCode]) {
return;
}
_.defer(_.bind(that._onInput, that, $e));
});
}
this.query = this.$input.val();
this.$overflowHelper = buildOverflowHelper(this.$input);
}
Input.normalizeQuery = function (str) {
return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
};
_.mixin(Input.prototype, EventEmitter, {
_onBlur: function onBlur() {
this.resetInputValue();
this.trigger("blurred");
},
_onFocus: function onFocus() {
this.trigger("focused");
},
_onKeydown: function onKeydown($e) {
var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
this._managePreventDefault(keyName, $e);
if (keyName && this._shouldTrigger(keyName, $e)) {
this.trigger(keyName + "Keyed", $e);
}
},
_onInput: function onInput() {
this._checkInputValue();
},
_managePreventDefault: function managePreventDefault(keyName, $e) {
var preventDefault, hintValue, inputValue;
switch (keyName) {
case "tab":
hintValue = this.getHint();
inputValue = this.getInputValue();
preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
break;
case "up":
case "down":
preventDefault = !withModifier($e);
break;
default:
preventDefault = false;
}
preventDefault && $e.preventDefault();
},
_shouldTrigger: function shouldTrigger(keyName, $e) {
var trigger;
switch (keyName) {
case "tab":
trigger = !withModifier($e);
break;
default:
trigger = true;
}
return trigger;
},
_checkInputValue: function checkInputValue() {
var inputValue, areEquivalent, hasDifferentWhitespace;
inputValue = this.getInputValue();
areEquivalent = areQueriesEquivalent(inputValue, this.query);
hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
this.query = inputValue;
if (!areEquivalent) {
this.trigger("queryChanged", this.query);
} else if (hasDifferentWhitespace) {
this.trigger("whitespaceChanged", this.query);
}
},
focus: function focus() {
this.$input.focus();
},
blur: function blur() {
this.$input.blur();
},
getQuery: function getQuery() {
return this.query;
},
setQuery: function setQuery(query) {
this.query = query;
},
getInputValue: function getInputValue() {
return this.$input.val();
},
setInputValue: function setInputValue(value, silent) {
this.$input.val(value);
silent ? this.clearHint() : this._checkInputValue();
},
resetInputValue: function resetInputValue() {
this.setInputValue(this.query, true);
},
getHint: function getHint() {
return this.$hint.val();
},
setHint: function setHint(value) {
this.$hint.val(value);
},
clearHint: function clearHint() {
this.setHint("");
},
clearHintIfInvalid: function clearHintIfInvalid() {
var val, hint, valIsPrefixOfHint, isValid;
val = this.getInputValue();
hint = this.getHint();
valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
!isValid && this.clearHint();
},
getLanguageDirection: function getLanguageDirection() {
return (this.$input.css("direction") || "ltr").toLowerCase();
},
hasOverflow: function hasOverflow() {
var constraint = this.$input.width() - 2;
this.$overflowHelper.text(this.getInputValue());
return this.$overflowHelper.width() >= constraint;
},
isCursorAtEnd: function () {
var valueLength, selectionStart, range;
valueLength = this.$input.val().length;
selectionStart = this.$input[0].selectionStart;
if (_.isNumber(selectionStart)) {
return selectionStart === valueLength;
} else if (document.selection) {
range = document.selection.createRange();
range.moveStart("character", -valueLength);
return valueLength === range.text.length;
}
return true;
},
destroy: function destroy() {
this.$hint.off(".tt");
this.$input.off(".tt");
this.$hint = this.$input = this.$overflowHelper = null;
}
});
return Input;
function buildOverflowHelper($input) {
return $('<pre aria-hidden="true"></pre>').css({
position: "absolute",
visibility: "hidden",
whiteSpace: "pre",
fontFamily: $input.css("font-family"),
fontSize: $input.css("font-size"),
fontStyle: $input.css("font-style"),
fontVariant: $input.css("font-variant"),
fontWeight: $input.css("font-weight"),
wordSpacing: $input.css("word-spacing"),
letterSpacing: $input.css("letter-spacing"),
textIndent: $input.css("text-indent"),
textRendering: $input.css("text-rendering"),
textTransform: $input.css("text-transform")
}).insertAfter($input);
}
function areQueriesEquivalent(a, b) {
return Input.normalizeQuery(a) === Input.normalizeQuery(b);
}
function withModifier($e) {
return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
}
}();
var Dataset = function () {
"use strict";
var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
function Dataset(o) {
o = o || {};
o.templates = o.templates || {};
if (!o.source) {
$.error("missing source");
}
if (o.name && !isValidName(o.name)) {
$.error("invalid dataset name: " + o.name);
}
this.query = null;
this.highlight = !!o.highlight;
this.name = o.name || _.getUniqueId();
this.source = o.source;
this.displayFn = getDisplayFn(o.display || o.displayKey);
this.templates = getTemplates(o.templates, this.displayFn);
this.$el = $(html.dataset.replace("%CLASS%", this.name));
}
Dataset.extractDatasetName = function extractDatasetName(el) {
return $(el).data(datasetKey);
};
Dataset.extractValue = function extractDatum(el) {
return $(el).data(valueKey);
};
Dataset.extractDatum = function extractDatum(el) {
return $(el).data(datumKey);
};
_.mixin(Dataset.prototype, EventEmitter, {
_render: function render(query, suggestions) {
if (!this.$el) {
return;
}
var that = this, hasSuggestions;
this.$el.empty();
hasSuggestions = suggestions && suggestions.length;
if (!hasSuggestions && this.templates.empty) {
this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
} else if (hasSuggestions) {
this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
}
this.trigger("rendered");
function getEmptyHtml() {
return that.templates.empty({
query: query,
isEmpty: true
});
}
function getSuggestionsHtml() {
var $suggestions, nodes;
$suggestions = $(html.suggestions).css(css.suggestions);
nodes = _.map(suggestions, getSuggestionNode);
$suggestions.append.apply($suggestions, nodes);
that.highlight && highlight({
className: "tt-highlight",
node: $suggestions[0],
pattern: query
});
return $suggestions;
function getSuggestionNode(suggestion) {
var $el;
$el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
$el.children().each(function () {
$(this).css(css.suggestionChild);
});
return $el;
}
}
function getHeaderHtml() {
return that.templates.header({
query: query,
isEmpty: !hasSuggestions
});
}
function getFooterHtml() {
return that.templates.footer({
query: query,
isEmpty: !hasSuggestions
});
}
},
getRoot: function getRoot() {
return this.$el;
},
update: function update(query) {
var that = this;
this.query = query;
this.canceled = false;
this.source(query, render);
function render(suggestions) {
if (!that.canceled && query === that.query) {
that._render(query, suggestions);
}
}
},
cancel: function cancel() {
this.canceled = true;
},
clear: function clear() {
this.cancel();
this.$el.empty();
this.trigger("rendered");
},
isEmpty: function isEmpty() {
return this.$el.is(":empty");
},
destroy: function destroy() {
this.$el = null;
}
});
return Dataset;
function getDisplayFn(display) {
display = display || "value";
return _.isFunction(display) ? display : displayFn;
function displayFn(obj) {
return obj[display];
}
}
function getTemplates(templates, displayFn) {
return {
empty: templates.empty && _.templatify(templates.empty),
header: templates.header && _.templatify(templates.header),
footer: templates.footer && _.templatify(templates.footer),
suggestion: templates.suggestion || suggestionTemplate
};
function suggestionTemplate(context) {
return "<p>" + displayFn(context) + "</p>";
}
}
function isValidName(str) {
return /^[_a-zA-Z0-9-]+$/.test(str);
}
}();
var Dropdown = function () {
"use strict";
function Dropdown(o) {
var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
o = o || {};
if (!o.menu) {
$.error("menu is required");
}
this.isOpen = false;
this.isEmpty = true;
this.datasets = _.map(o.datasets, initializeDataset);
onSuggestionClick = _.bind(this._onSuggestionClick, this);
onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
_.each(this.datasets, function (dataset) {
that.$menu.append(dataset.getRoot());
dataset.onSync("rendered", that._onRendered, that);
});
}
_.mixin(Dropdown.prototype, EventEmitter, {
_onSuggestionClick: function onSuggestionClick($e) {
this.trigger("suggestionClicked", $($e.currentTarget));
},
_onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
this._removeCursor();
this._setCursor($($e.currentTarget), true);
},
_onSuggestionMouseLeave: function onSuggestionMouseLeave() {
this._removeCursor();
},
_onRendered: function onRendered() {
this.isEmpty = _.every(this.datasets, isDatasetEmpty);
this.isEmpty ? this._hide() : this.isOpen && this._show();
this.trigger("datasetRendered");
function isDatasetEmpty(dataset) {
return dataset.isEmpty();
}
},
_hide: function () {
this.$menu.hide();
},
_show: function () {
this.$menu.css("display", "block");
},
_getSuggestions: function getSuggestions() {
return this.$menu.find(".tt-suggestion");
},
_getCursor: function getCursor() {
return this.$menu.find(".tt-cursor").first();
},
_setCursor: function setCursor($el, silent) {
$el.first().addClass("tt-cursor");
!silent && this.trigger("cursorMoved");
},
_removeCursor: function removeCursor() {
this._getCursor().removeClass("tt-cursor");
},
_moveCursor: function moveCursor(increment) {
var $suggestions, $oldCursor, newCursorIndex, $newCursor;
if (!this.isOpen) {
return;
}
$oldCursor = this._getCursor();
$suggestions = this._getSuggestions();
this._removeCursor();
newCursorIndex = $suggestions.index($oldCursor) + increment;
newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
if (newCursorIndex === -1) {
this.trigger("cursorRemoved");
return;
} else if (newCursorIndex < -1) {
newCursorIndex = $suggestions.length - 1;
}
this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
this._ensureVisible($newCursor);
},
_ensureVisible: function ensureVisible($el) {
var elTop, elBottom, menuScrollTop, menuHeight;
elTop = $el.position().top;
elBottom = elTop + $el.outerHeight(true);
menuScrollTop = this.$menu.scrollTop();
menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
if (elTop < 0) {
this.$menu.scrollTop(menuScrollTop + elTop);
} else if (menuHeight < elBottom) {
this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
}
},
close: function close() {
if (this.isOpen) {
this.isOpen = false;
this._removeCursor();
this._hide();
this.trigger("closed");
}
},
open: function open() {
if (!this.isOpen) {
this.isOpen = true;
!this.isEmpty && this._show();
this.trigger("opened");
}
},
setLanguageDirection: function setLanguageDirection(dir) {
this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
},
moveCursorUp: function moveCursorUp() {
this._moveCursor(-1);
},
moveCursorDown: function moveCursorDown() {
this._moveCursor(+1);
},
getDatumForSuggestion: function getDatumForSuggestion($el) {
var datum = null;
if ($el.length) {
datum = {
raw: Dataset.extractDatum($el),
value: Dataset.extractValue($el),
datasetName: Dataset.extractDatasetName($el)
};
}
return datum;
},
getDatumForCursor: function getDatumForCursor() {
return this.getDatumForSuggestion(this._getCursor().first());
},
getDatumForTopSuggestion: function getDatumForTopSuggestion() {
return this.getDatumForSuggestion(this._getSuggestions().first());
},
update: function update(query) {
_.each(this.datasets, updateDataset);
function updateDataset(dataset) {
dataset.update(query);
}
},
empty: function empty() {
_.each(this.datasets, clearDataset);
this.isEmpty = true;
function clearDataset(dataset) {
dataset.clear();
}
},
isVisible: function isVisible() {
return this.isOpen && !this.isEmpty;
},
destroy: function destroy() {
this.$menu.off(".tt");
this.$menu = null;
_.each(this.datasets, destroyDataset);
function destroyDataset(dataset) {
dataset.destroy();
}
}
});
return Dropdown;
function initializeDataset(oDataset) {
return new Dataset(oDataset);
}
}();
var Typeahead = function () {
"use strict";
var attrsKey = "ttAttrs";
function Typeahead(o) {
var $menu, $input, $hint;
o = o || {};
if (!o.input) {
$.error("missing input");
}
this.isActivated = false;
this.autoselect = !!o.autoselect;
this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
this.$node = buildDom(o.input, o.withHint);
$menu = this.$node.find(".tt-dropdown-menu");
$input = this.$node.find(".tt-input");
$hint = this.$node.find(".tt-hint");
$input.on("blur.tt", function ($e) {
var active, isActive, hasActive;
active = document.activeElement;
isActive = $menu.is(active);
hasActive = $menu.has(active).length > 0;
if (_.isMsie() && (isActive || hasActive)) {
$e.preventDefault();
$e.stopImmediatePropagation();
_.defer(function () {
$input.focus();
});
}
});
$menu.on("mousedown.tt", function ($e) {
$e.preventDefault();
});
this.eventBus = o.eventBus || new EventBus({
el: $input
});
this.dropdown = new Dropdown({
menu: $menu,
datasets: o.datasets
}).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
this.input = new Input({
input: $input,
hint: $hint
}).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
this._setLanguageDirection();
}
_.mixin(Typeahead.prototype, {
_onSuggestionClicked: function onSuggestionClicked(type, $el) {
var datum;
if (datum = this.dropdown.getDatumForSuggestion($el)) {
this._select(datum);
}
},
_onCursorMoved: function onCursorMoved() {
var datum = this.dropdown.getDatumForCursor();
this.input.setInputValue(datum.value, true);
this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
},
_onCursorRemoved: function onCursorRemoved() {
this.input.resetInputValue();
this._updateHint();
},
_onDatasetRendered: function onDatasetRendered() {
this._updateHint();
},
_onOpened: function onOpened() {
this._updateHint();
this.eventBus.trigger("opened");
},
_onClosed: function onClosed() {
this.input.clearHint();
this.eventBus.trigger("closed");
},
_onFocused: function onFocused() {
this.isActivated = true;
this.dropdown.open();
},
_onBlurred: function onBlurred() {
this.isActivated = false;
this.dropdown.empty();
this.dropdown.close();
},
_onEnterKeyed: function onEnterKeyed(type, $e) {
var cursorDatum, topSuggestionDatum;
cursorDatum = this.dropdown.getDatumForCursor();
topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
if (cursorDatum) {
this._select(cursorDatum);
$e.preventDefault();
} else if (this.autoselect && topSuggestionDatum) {
this._select(topSuggestionDatum);
$e.preventDefault();
}
},
_onTabKeyed: function onTabKeyed(type, $e) {
var datum;
if (datum = this.dropdown.getDatumForCursor()) {
this._select(datum);
$e.preventDefault();
} else {
this._autocomplete(true);
}
},
_onEscKeyed: function onEscKeyed() {
this.dropdown.close();
this.input.resetInputValue();
},
_onUpKeyed: function onUpKeyed() {
var query = this.input.getQuery();
this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
this.dropdown.open();
},
_onDownKeyed: function onDownKeyed() {
var query = this.input.getQuery();
this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
this.dropdown.open();
},
_onLeftKeyed: function onLeftKeyed() {
this.dir === "rtl" && this._autocomplete();
},
_onRightKeyed: function onRightKeyed() {
this.dir === "ltr" && this._autocomplete();
},
_onQueryChanged: function onQueryChanged(e, query) {
this.input.clearHintIfInvalid();
query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
this.dropdown.open();
this._setLanguageDirection();
},
_onWhitespaceChanged: function onWhitespaceChanged() {
this._updateHint();
this.dropdown.open();
},
_setLanguageDirection: function setLanguageDirection() {
var dir;
if (this.dir !== (dir = this.input.getLanguageDirection())) {
this.dir = dir;
this.$node.css("direction", dir);
this.dropdown.setLanguageDirection(dir);
}
},
_updateHint: function updateHint() {
var datum, val, query, escapedQuery, frontMatchRegEx, match;
datum = this.dropdown.getDatumForTopSuggestion();
if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
val = this.input.getInputValue();
query = Input.normalizeQuery(val);
escapedQuery = _.escapeRegExChars(query);
frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
match = frontMatchRegEx.exec(datum.value);
match ? this.input.setHint(val + match[1]) : this.input.clearHint();
} else {
this.input.clearHint();
}
},
_autocomplete: function autocomplete(laxCursor) {
var hint, query, isCursorAtEnd, datum;
hint = this.input.getHint();
query = this.input.getQuery();
isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
if (hint && query !== hint && isCursorAtEnd) {
datum = this.dropdown.getDatumForTopSuggestion();
datum && this.input.setInputValue(datum.value);
this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
}
},
_select: function select(datum) {
this.input.setQuery(datum.value);
this.input.setInputValue(datum.value, true);
this._setLanguageDirection();
this.eventBus.trigger("selected", datum.raw, datum.datasetName);
this.dropdown.close();
_.defer(_.bind(this.dropdown.empty, this.dropdown));
},
open: function open() {
this.dropdown.open();
},
close: function close() {
this.dropdown.close();
},
setVal: function setVal(val) {
val = _.toStr(val);
if (this.isActivated) {
this.input.setInputValue(val);
} else {
this.input.setQuery(val);
this.input.setInputValue(val, true);
}
this._setLanguageDirection();
},
getVal: function getVal() {
return this.input.getQuery();
},
destroy: function destroy() {
this.input.destroy();
this.dropdown.destroy();
destroyDomStructure(this.$node);
this.$node = null;
}
});
return Typeahead;
function buildDom(input, withHint) {
var $input, $wrapper, $dropdown, $hint;
$input = $(input);
$wrapper = $(html.wrapper).css(css.wrapper);
$dropdown = $(html.dropdown).css(css.dropdown);
$hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
$hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly", true).attr({
autocomplete: "off",
spellcheck: "false",
tabindex: -1
});
$input.data(attrsKey, {
dir: $input.attr("dir"),
autocomplete: $input.attr("autocomplete"),
spellcheck: $input.attr("spellcheck"),
style: $input.attr("style")
});
$input.addClass("tt-input").attr({
autocomplete: "off",
spellcheck: false
}).css(withHint ? css.input : css.inputWithNoHint);
try {
!$input.attr("dir") && $input.attr("dir", "auto");
} catch (e) {
}
return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
}
function getBackgroundStyles($el) {
return {
backgroundAttachment: $el.css("background-attachment"),
backgroundClip: $el.css("background-clip"),
backgroundColor: $el.css("background-color"),
backgroundImage: $el.css("background-image"),
backgroundOrigin: $el.css("background-origin"),
backgroundPosition: $el.css("background-position"),
backgroundRepeat: $el.css("background-repeat"),
backgroundSize: $el.css("background-size")
};
}
function destroyDomStructure($node) {
var $input = $node.find(".tt-input");
_.each($input.data(attrsKey), function (val, key) {
_.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
});
$input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
$node.remove();
}
}();
(function () {
"use strict";
var old, typeaheadKey, methods;
old = $.fn.typeahead;
typeaheadKey = "ttTypeahead";
methods = {
initialize: function initialize(o, datasets) {
datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
o = o || {};
return this.each(attach);
function attach() {
var $input = $(this), eventBus, typeahead;
_.each(datasets, function (d) {
d.highlight = !!o.highlight;
});
typeahead = new Typeahead({
input: $input,
eventBus: eventBus = new EventBus({
el: $input
}),
withHint: _.isUndefined(o.hint) ? true : !!o.hint,
minLength: o.minLength,
autoselect: o.autoselect,
datasets: datasets
});
$input.data(typeaheadKey, typeahead);
}
},
open: function open() {
return this.each(openTypeahead);
function openTypeahead() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.open();
}
}
},
close: function close() {
return this.each(closeTypeahead);
function closeTypeahead() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.close();
}
}
},
val: function val(newVal) {
return !arguments.length ? getVal(this.first()) : this.each(setVal);
function setVal() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.setVal(newVal);
}
}
function getVal($input) {
var typeahead, query;
if (typeahead = $input.data(typeaheadKey)) {
query = typeahead.getVal();
}
return query;
}
},
destroy: function destroy() {
return this.each(unattach);
function unattach() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.destroy();
$input.removeData(typeaheadKey);
}
}
}
};
$.fn.typeahead = function (method) {
var tts;
if (methods[method] && method !== "initialize") {
tts = this.filter(function () {
return !!$(this).data(typeaheadKey);
});
return methods[method].apply(tts, [].slice.call(arguments, 1));
} else {
return methods.initialize.apply(this, arguments);
}
};
$.fn.typeahead.noConflict = function noConflict() {
$.fn.typeahead = old;
return this;
};
})();
})(window.jQuery);
// place any jQuery/helper plugins in here, instead of separate, slower script files.
| 1,036,270
| 304,416
|
import * as React from 'react';
import SearchOutlined from "@ant-design/icons/es/icons/SearchOutlined";
import Input from '../input';
export default function Search(props) {
var _props$placeholder = props.placeholder,
placeholder = _props$placeholder === void 0 ? '' : _props$placeholder,
value = props.value,
prefixCls = props.prefixCls,
disabled = props.disabled,
onChange = props.onChange,
handleClear = props.handleClear;
var handleChange = React.useCallback(function (e) {
onChange === null || onChange === void 0 ? void 0 : onChange(e);
if (e.target.value === '') {
handleClear === null || handleClear === void 0 ? void 0 : handleClear();
}
}, [onChange]);
return /*#__PURE__*/React.createElement(Input, {
placeholder: placeholder,
className: prefixCls,
value: value,
onChange: handleChange,
disabled: disabled,
allowClear: true,
prefix: /*#__PURE__*/React.createElement(SearchOutlined, null)
});
}
| 997
| 296
|
import createTheme from "spectacle/lib/themes/default"
const brand = {
// black and its tints:
black: "#242121", // black
darkerGray: "#373534",
darkGray: "#5f5c5b",
gray: '#949BA6',
lightGray: "#e8e8e9",
white: '#F6F3F3', // lightest gray
// purple
// darkPurple: '#000326',
purple: '#2C2853',
lightPurple: '#8588AD',
// blue
blue: "#2D45A3",
lightBlue: "#C2DCF2",
// red and its tints:
red: "#c43a31", // brand red
darkestRed: "#cd5244",
darkerRed: "#d56557",
darkRed: "#dc7a6b",
lightred: "#e58c7d",
lighterRed: "#eb9f92",
lightestRed: "#efb3a7",
paleRed: "#f5c5bc",
palerRed: "#f8d9d2",
palestRed: "#f6ebe7" // palest red
}
const colors = {
logo: brand.lightPurple,
ctaPrimary: brand.blue,
ctaSecondary: brand.lightBlue,
primary: brand.white,
secondary: brand.purple,
tertiary: brand.gray,
quarternary: brand.lightPurple,
}
const fonts = {
// heading: "'Poppins', 'Century Gothic', 'Helvetica Neue', Helvetica, sans-serif",
// body: "'Source Serif Pro', serif",
// monospace: "'akkurta', 'Inconsolata', Consolas, 'Lucida Console', 'Lucida Sans Typewriter', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Liberation Mono', Monaco, Courier, monospace"
// primary: { name: "Open Sans Condensed", googleFont: true, styles: [ "400", "700" ] },
primary: "Roboto, 'Open Sans Condensed'",
secondary: "Roboto, 'Open Sans Condensed'",
tertiary: "'Helvetica Neue', Helvetica, 'sans serif'",
}
const theme = createTheme(colors, fonts)
export {
colors,
fonts,
theme
}
| 1,555
| 665
|
import Image from 'next/image'
import { Grid } from 'theme-ui'
import { MDXProvider } from '@mdx-js/react'
const Layout = ({ compact, ...props }) => (
<Grid
columns={['64px 1fr', compact ? 'repeat(2, 96px 1fr)' : '96px 1fr']}
gap={3}
sx={{
py: [3, 4],
alignItems: compact ? 'center' : 'start',
img: { borderRadius: 'circle' },
'> p': { my: 0 },
'p > div': { verticalAlign: 'middle' },
a: { whiteSpace: 'nowrap' }
}}
{...props}
/>
)
const Avatar = props => <Image width={512} height={512} {...props} />
const Team = props => (
<Layout compact={props.compact}>
<MDXProvider components={{ img: Avatar }} {...props} />
</Layout>
)
export default Team
| 719
| 269
|
import { inspect } from 'util';
// Server side redux action logger
export default function createLogger() {
return store => next => action => { // eslint-disable-line no-unused-vars
const formattedPayload = inspect(action.payload, {
colors: true,
});
console.log(` * ${action.type}: ${formattedPayload}`); // eslint-disable-line no-console
return next(action);
};
}
| 393
| 114
|
import React from 'react';
import propy from '../assets/images/propy.png';
const Propy = () => (
<div style={{"border-style":"solid","border-color":"#00ff00","width":"95%", "height":"250px"}}>
<img src={propy} style={{"width":"200px","height":"200px",}} />
</div>
);
export default Propy;
| 300
| 117
|
var digits = [];
var drawTimeout;
var fontName="";
var settings = require('Storage').readJSON("contourclock.json", true) || {};
if (settings.fontIndex==undefined) {
settings.fontIndex=0;
require('Storage').writeJSON("myapp.json", settings);
}
function draw() {
var date = new Date();
// Draw day of the week
g.reset();
g.setFont("Teletext10x18Ascii");
g.clearRect(0,138,g.getWidth()-1,176);
g.setFontAlign(0,1).drawString(require("locale").dow(date).toUpperCase(),g.getWidth()/2,g.getHeight()-18);
// Draw Date
g.setFontAlign(0,1).drawString(require('locale').date(new Date(),1),g.getWidth()/2,g.getHeight());
require('contourclock').drawClock(settings.fontIndex);
}
require("FontTeletext10x18Ascii").add(Graphics);
Bangle.setUI("clock");
g.clear();
Bangle.loadWidgets();
Bangle.drawWidgets();
draw();
setTimeout(function() {
setInterval(draw,60000);
}, 60000 - Date.now() % 60000);
| 909
| 351
|
/*
AngularJS v1.6.5-build.5390+sha.a86a319
(c) 2010-2017 Google, Inc. http://angularjs.org
License: MIT
*/
(function(J,d){'use strict';function A(d){k&&d.get("$route")}function B(t,u,g){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,f,b,c,m){function v(){l&&(g.cancel(l),l=null);n&&(n.$destroy(),n=null);p&&(l=g.leave(p),l.done(function(a){!1!==a&&(l=null)}),p=null)}function E(){var b=t.current&&t.current.locals;if(d.isDefined(b&&b.$template)){var b=a.$new(),c=t.current;p=m(b,function(b){g.enter(b,null,p||f).done(function(b){!1===b||!d.isDefined(w)||w&&!a.$eval(w)||u()});
v()});n=c.scope=b;n.$emit("$viewContentLoaded");n.$eval(k)}else v()}var n,p,l,w=b.autoscroll,k=b.onload||"";a.$on("$routeChangeSuccess",E);E()}}}function C(d,k,g){return{restrict:"ECA",priority:-400,link:function(a,f){var b=g.current,c=b.locals;f.html(c.$template);var m=d(f.contents());if(b.controller){c.$scope=a;var v=k(b.controller,c);b.controllerAs&&(a[b.controllerAs]=v);f.data("$ngControllerController",v);f.children().data("$ngControllerController",v)}a[b.resolveAs||"$resolve"]=c;m(a)}}}var x,
y,F,G,z=d.module("ngRoute",[]).info({angularVersion:"1.6.5-build.5390+sha.a86a319"}).provider("$route",function(){function t(a,f){return d.extend(Object.create(a),f)}function u(a,d){var b=d.caseInsensitiveMatch,c={originalPath:a,regexp:a},g=c.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)(\*\?|[?*])?/g,function(a,b,d,c){a="?"===c||"*?"===c?"?":null;c="*"===c||"*?"===c?"*":null;g.push({name:d,optional:!!a});b=b||"";return""+(a?"":b)+"(?:"+(a?b:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||
"")}).replace(/([/$*])/g,"\\$1");c.regexp=new RegExp("^"+a+"$",b?"i":"");return c}x=d.isArray;y=d.isObject;F=d.isDefined;G=d.noop;var g={};this.when=function(a,f){var b;b=void 0;if(x(f)){b=b||[];for(var c=0,m=f.length;c<m;c++)b[c]=f[c]}else if(y(f))for(c in b=b||{},f)if("$"!==c.charAt(0)||"$"!==c.charAt(1))b[c]=f[c];b=b||f;d.isUndefined(b.reloadOnSearch)&&(b.reloadOnSearch=!0);d.isUndefined(b.caseInsensitiveMatch)&&(b.caseInsensitiveMatch=this.caseInsensitiveMatch);g[a]=d.extend(b,a&&u(a,b));a&&(c=
"/"===a[a.length-1]?a.substr(0,a.length-1):a+"/",g[c]=d.extend({redirectTo:a},u(c,b)));return this};this.caseInsensitiveMatch=!1;this.otherwise=function(a){"string"===typeof a&&(a={redirectTo:a});this.when(null,a);return this};k=!0;this.eagerInstantiationEnabled=function(a){return F(a)?(k=a,this):k};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$templateRequest","$sce","$browser",function(a,f,b,c,m,k,u,n){function p(e){var h=q.current;(y=(s=C())&&h&&s.$$route===h.$$route&&d.equals(s.pathParams,
h.pathParams)&&!s.reloadOnSearch&&!D)||!h&&!s||a.$broadcast("$routeChangeStart",s,h).defaultPrevented&&e&&e.preventDefault()}function l(){var e=q.current,h=s;if(y)e.params=h.params,d.copy(e.params,b),a.$broadcast("$routeUpdate",e);else if(h||e){D=!1;q.current=h;var H=c.resolve(h);n.$$incOutstandingRequestCount();H.then(w).then(z).then(function(c){return c&&H.then(A).then(function(c){h===q.current&&(h&&(h.locals=c,d.copy(h.params,b)),a.$broadcast("$routeChangeSuccess",h,e))})}).catch(function(b){h===
q.current&&a.$broadcast("$routeChangeError",h,e,b)}).finally(function(){n.$$completeOutstandingRequest(G)})}}function w(e){var a={route:e,hasRedirection:!1};if(e)if(e.redirectTo)if(d.isString(e.redirectTo))a.path=x(e.redirectTo,e.params),a.search=e.params,a.hasRedirection=!0;else{var b=f.path(),g=f.search();e=e.redirectTo(e.pathParams,b,g);d.isDefined(e)&&(a.url=e,a.hasRedirection=!0)}else if(e.resolveRedirectTo)return c.resolve(m.invoke(e.resolveRedirectTo)).then(function(e){d.isDefined(e)&&(a.url=
e,a.hasRedirection=!0);return a});return a}function z(a){var b=!0;if(a.route!==q.current)b=!1;else if(a.hasRedirection){var d=f.url(),c=a.url;c?f.url(c).replace():c=f.path(a.path).search(a.search).replace().url();c!==d&&(b=!1)}return b}function A(a){if(a){var b=d.extend({},a.resolve);d.forEach(b,function(a,e){b[e]=d.isString(a)?m.get(a):m.invoke(a,null,null,e)});a=B(a);d.isDefined(a)&&(b.$template=a);return c.all(b)}}function B(a){var b,c;d.isDefined(b=a.template)?d.isFunction(b)&&(b=b(a.params)):
d.isDefined(c=a.templateUrl)&&(d.isFunction(c)&&(c=c(a.params)),d.isDefined(c)&&(a.loadedTemplateUrl=u.valueOf(c),b=k(c)));return b}function C(){var a,b;d.forEach(g,function(c,g){var r;if(r=!b){var k=f.path();r=c.keys;var m={};if(c.regexp)if(k=c.regexp.exec(k)){for(var l=1,n=k.length;l<n;++l){var p=r[l-1],q=k[l];p&&q&&(m[p.name]=q)}r=m}else r=null;else r=null;r=a=r}r&&(b=t(c,{params:d.extend({},f.search(),a),pathParams:a}),b.$$route=c)});return b||g[null]&&t(g[null],{params:{},pathParams:{}})}function x(a,
b){var c=[];d.forEach((a||"").split(":"),function(a,d){if(0===d)c.push(a);else{var e=a.match(/(\w+)(?:[?*])?(.*)/),f=e[1];c.push(b[f]);c.push(e[2]||"");delete b[f]}});return c.join("")}var D=!1,s,y,q={routes:g,reload:function(){D=!0;var b={defaultPrevented:!1,preventDefault:function(){this.defaultPrevented=!0;D=!1}};a.$evalAsync(function(){p(b);b.defaultPrevented||l()})},updateParams:function(a){if(this.current&&this.current.$$route)a=d.extend({},this.current.params,a),f.path(x(this.current.$$route.originalPath,
a)),f.search(a);else throw I("norout");}};a.$on("$locationChangeStart",p);a.$on("$locationChangeSuccess",l);return q}]}).run(A),I=d.$$minErr("ngRoute"),k;A.$inject=["$injector"];z.provider("$routeParams",function(){this.$get=function(){return{}}});z.directive("ngView",B);z.directive("ngView",C);B.$inject=["$route","$anchorScroll","$animate"];C.$inject=["$compile","$controller","$route"]})(window,window.angular);
//# sourceMappingURL=angular-route.min.js.map
| 5,657
| 2,571
|
const { ChatReply } = require("../Models/ChatReply");
module.exports = {
IgnoreChatAction: function(reason){
const self = this;
self.executeAsync = async function(){
return new ChatReply(false, undefined, undefined, undefined, undefined, reason);
}
}
}
| 298
| 85
|
var tops = [
{"segment":1,
"top": [
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
]},
{"segment":2,
"top": [
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":3,
"top": [
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":4,
"top": [
{
"code": "Empire State Building",
"count": "7"
},
{
"code": "New York City Pass",
"count": "5"
},
{
"code": "Misa Harlem",
"count": "5"
},
{
"code": "Estatua de la Libertad",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":5,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":6,
"top": [
{
"code": "Empire State Building",
"count": "18"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
]},
{"segment":7,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
]},
{"segment":8,
"top": [
{
"code": "Empire State Building",
"count": "13"
},
{
"code": "Tour Gran Manzana",
"count": "6"
},
{
"code": "Cataratas del Niagara",
"count": "4"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
]},
{"segment":9,
"top": [
{
"code": "Empire State Building",
"count": "306"
},
{
"code": "Explora Nueva York",
"count": "38"
},
{
"code": "Tour 11S",
"count": "25"
},
{
"code": "Tour Gran Manzana",
"count": "23"
},
{
"code": "AllStar Basket NY",
"count": "19"
},
{
"code": "Top Of The Rock",
"count": "14"
},
{
"code": "Cataratas del Niagara",
"count": "12"
},
{
"code": "Visita Washington",
"count": "11"
},
{
"code": "Museo 11S",
"count": "10"
},
{
"code": "Fantasma de la Opera",
"count": "8"
},
{
"code": "Helicoptero NY",
"count": "7"
},
{
"code": "Visita Harlem guiada",
"count": "6"
},
{
"code": "Tour Completo de 3 dias",
"count": "4"
},
{
"code": "Ferry en NY",
"count": "3"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Bus Hopin Hopoff",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "Rey Leon ",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":10,
"top": [
{
"code": "Empire State Building",
"count": "110"
},
{
"code": "Tour Gran Manzana",
"count": "22"
},
{
"code": "Estatua de la Libertad",
"count": "7"
},
{
"code": "Tour 11S",
"count": "6"
},
{
"code": "Cataratas del Niagara",
"count": "5"
},
{
"code": "Museo 11S",
"count": "5"
},
{
"code": "Helicoptero NY",
"count": "3"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":11,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":12,
"top": [
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":13,
"top": [
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
]},
{"segment":14,
"top": [
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":15,
"top": [
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Chicago Musical",
"count": "1"
},
]},
{"segment":16,
"top": [
{
"code": "Tour Gran Manzana",
"count": "2"
},
]},
{"segment":17,
"top": [
{
"code": "Explora Nueva York",
"count": "8"
},
{
"code": "Empire State Building",
"count": "5"
},
{
"code": "Bus Hopin Hopoff",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
]},
{"segment":18,
"top": [
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":19,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":20,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
]},
{"segment":21,
"top": [
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":22,
"top": [
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
]},
{"segment":23,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":24,
"top": [
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
]},
{"segment":25,
"top": [
{
"code": "Empire State Building",
"count": "5"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":26,
"top": [
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":27,
"top": [
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
]},
{"segment":28,
"top": [
{
"code": "Tour Gran Manzana",
"count": "4"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":29,
"top": [
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
]},
{"segment":30,
"top": [
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
]},
{"segment":31,
"top": [
{
"code": "Empire State Building",
"count": "5"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":32,
"top": [
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Explora Nueva York",
"count": "3"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":33,
"top": [
{
"code": "Tour Gran Manzana",
"count": "80"
},
{
"code": "Tour Completo de 3 dias",
"count": "4"
},
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Visita Harlem guiada",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":34,
"top": [
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":35,
"top": [
{
"code": "Empire State Building",
"count": "7"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":36,
"top": [
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":37,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
]},
{"segment":38,
"top": [
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":39,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":40,
"top": [
{
"code": "New York City Pass",
"count": "21"
},
{
"code": "Tour Gran Manzana",
"count": "14"
},
{
"code": "Empire State Building",
"count": "12"
},
{
"code": "AllStar Basket NY",
"count": "9"
},
{
"code": "Tour Completo de 3 dias",
"count": "7"
},
{
"code": "Excursion Contrastes NY",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "Visita Harlem guiada",
"count": "3"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Alto y Bajo Manhattan",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
]},
{"segment":41,
"top": [
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":42,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
]},
{"segment":43,
"top": [
{
"code": "Empire State Building",
"count": "50"
},
{
"code": "Tour Gran Manzana",
"count": "16"
},
{
"code": "Ferry en NY",
"count": "14"
},
{
"code": "Fantasma de la Opera",
"count": "11"
},
{
"code": "Misa Harlem",
"count": "9"
},
{
"code": "Alto y Bajo Manhattan",
"count": "8"
},
{
"code": "Cataratas del Niagara",
"count": "5"
},
{
"code": "AllStar Basket NY",
"count": "4"
},
{
"code": "Tour Completo de 3 dias",
"count": "4"
},
{
"code": "Musical Mamma Mia",
"count": "4"
},
{
"code": "Explora Nueva York",
"count": "3"
},
{
"code": "Visita Washington",
"count": "3"
},
{
"code": "Top Of The Rock",
"count": "3"
},
{
"code": "Visita Harlem guiada",
"count": "3"
},
{
"code": "Museo 11S",
"count": "3"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":44,
"top": [
{
"code": "Empire State Building",
"count": "10"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":45,
"top": [
{
"code": "Empire State Building",
"count": "14"
},
{
"code": "Tour Gran Manzana",
"count": "12"
},
{
"code": "Musical Mamma Mia",
"count": "6"
},
{
"code": "Tour Completo de 3 dias",
"count": "6"
},
{
"code": "Excursion Contrastes NY",
"count": "4"
},
{
"code": "Visita Harlem guiada",
"count": "4"
},
{
"code": "Tour 11S",
"count": "4"
},
{
"code": "AllStar Basket NY",
"count": "4"
},
{
"code": "Rey Leon ",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
]},
{"segment":46,
"top": [
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":47,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":48,
"top": [
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "1"
},
]},
{"segment":49,
"top": [
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":50,
"top": [
{
"code": "New York City Pass",
"count": "5"
},
{
"code": "Tour Gran Manzana",
"count": "4"
},
{
"code": "Rey Leon ",
"count": "3"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":51,
"top": [
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":52,
"top": [
{
"code": "New York City Pass",
"count": "7"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
]},
{"segment":53,
"top": [
{
"code": "Empire State Building",
"count": "7"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
]},
{"segment":54,
"top": [
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":55,
"top": [
{
"code": "Tour Gran Manzana",
"count": "6"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
]},
{"segment":56,
"top": [
{
"code": "Empire State Building",
"count": "8"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":57,
"top": [
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":58,
"top": [
{
"code": "Tour Gran Manzana",
"count": "5"
},
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "Rey Leon ",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
]},
{"segment":59,
"top": [
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
]},
{"segment":60,
"top": [
{
"code": "Tour Gran Manzana",
"count": "4"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":61,
"top": [
{
"code": "Empire State Building",
"count": "15"
},
{
"code": "New York City Pass",
"count": "10"
},
{
"code": "Misa Harlem",
"count": "8"
},
{
"code": "Tour 11S",
"count": "4"
},
{
"code": "Explora Nueva York",
"count": "3"
},
{
"code": "Visita Washington",
"count": "3"
},
{
"code": "Nueva York Nocturno",
"count": "3"
},
{
"code": "Bus Hopin Hopoff",
"count": "3"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":62,
"top": [
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":63,
"top": [
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":64,
"top": [
{
"code": "Empire State Building",
"count": "51"
},
{
"code": "Tour Gran Manzana",
"count": "8"
},
{
"code": "Tour 11S",
"count": "4"
},
{
"code": "Estatua de la Libertad",
"count": "3"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":65,
"top": [
{
"code": "Empire State Building",
"count": "27"
},
{
"code": "Misa Harlem",
"count": "9"
},
{
"code": "Explora Nueva York",
"count": "3"
},
{
"code": "Bus Hopin Hopoff",
"count": "3"
},
{
"code": "Tour 11S",
"count": "3"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
]},
{"segment":66,
"top": [
{
"code": "Empire State Building",
"count": "40"
},
{
"code": "New York City Pass",
"count": "6"
},
{
"code": "Tour 11S",
"count": "5"
},
{
"code": "AllStar Basket NY",
"count": "4"
},
{
"code": "Bus Hopin Hopoff",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "Excursion Contrastes NY",
"count": "3"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "2"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":67,
"top": [
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":68,
"top": [
{
"code": "Helicoptero NY",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":69,
"top": [
{
"code": "Chicago Musical",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
]},
{"segment":70,
"top": [
{
"code": "Tour Gran Manzana",
"count": "14"
},
]},
{"segment":71,
"top": [
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
]},
{"segment":72,
"top": [
{
"code": "Empire State Building",
"count": "106"
},
{
"code": "Musical Mamma Mia",
"count": "16"
},
{
"code": "Cataratas del Niagara",
"count": "11"
},
{
"code": "Tour Gran Manzana",
"count": "10"
},
{
"code": "AllStar Basket NY",
"count": "10"
},
{
"code": "Top Of The Rock",
"count": "9"
},
{
"code": "Alto y Bajo Manhattan",
"count": "8"
},
{
"code": "New York City Pass",
"count": "7"
},
{
"code": "Estatua de la Libertad",
"count": "5"
},
{
"code": "Excursion Contrastes NY",
"count": "5"
},
{
"code": "Tour Completo de 3 dias",
"count": "4"
},
{
"code": "Fantasma de la Opera",
"count": "3"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
]},
{"segment":73,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":74,
"top": [
{
"code": "Empire State Building",
"count": "29"
},
{
"code": "New York City Pass",
"count": "10"
},
{
"code": "Misa Harlem",
"count": "4"
},
{
"code": "Helicoptero NY",
"count": "4"
},
{
"code": "Tour 11S",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
]},
{"segment":75,
"top": [
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
]},
{"segment":76,
"top": [
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":77,
"top": [
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":78,
"top": [
{
"code": "Empire State Building",
"count": "12"
},
{
"code": "Misa Harlem",
"count": "3"
},
{
"code": "Tour 11S",
"count": "3"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Cena en el Hardrock",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
]},
{"segment":79,
"top": [
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":80,
"top": [
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":81,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Chicago Musical",
"count": "1"
},
]},
{"segment":82,
"top": [
{
"code": "Musical Mamma Mia",
"count": "4"
},
{
"code": "Chicago Musical",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":83,
"top": [
{
"code": "Ferry en NY",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":84,
"top": [
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":85,
"top": [
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":86,
"top": [
{
"code": "Empire State Building",
"count": "13"
},
{
"code": "Explora Nueva York",
"count": "9"
},
{
"code": "Estatua de la Libertad",
"count": "6"
},
{
"code": "Misa Harlem",
"count": "4"
},
{
"code": "New York City Pass",
"count": "4"
},
{
"code": "Helicoptero NY",
"count": "4"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Ferry en NY",
"count": "2"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":87,
"top": [
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
]},
{"segment":88,
"top": [
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":89,
"top": [
{
"code": "Chicago Musical",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":90,
"top": [
{
"code": "Empire State Building",
"count": "28"
},
{
"code": "AllStar Basket NY",
"count": "7"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "2"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":91,
"top": [
{
"code": "New York City Pass",
"count": "5"
},
{
"code": "Estatua de la Libertad",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":92,
"top": [
{
"code": "Chicago Musical",
"count": "153"
},
{
"code": "Misa Harlem",
"count": "52"
},
{
"code": "Empire State Building",
"count": "52"
},
{
"code": "Bus Hopin Hopoff",
"count": "49"
},
{
"code": "Tour Gran Manzana",
"count": "27"
},
{
"code": "AllStar Basket NY",
"count": "20"
},
{
"code": "Musical Mamma Mia",
"count": "20"
},
{
"code": "Cena en el Hardrock",
"count": "19"
},
{
"code": "Tour Completo de 3 dias",
"count": "17"
},
{
"code": "Helicoptero NY",
"count": "14"
},
{
"code": "Tour 11S",
"count": "11"
},
{
"code": "Museo de Cera",
"count": "10"
},
{
"code": "Nueva York Nocturno",
"count": "10"
},
{
"code": "Alto y Bajo Manhattan",
"count": "8"
},
{
"code": "New York City Pass",
"count": "6"
},
{
"code": "Explora Nueva York",
"count": "4"
},
{
"code": "Excursion Contrastes NY",
"count": "4"
},
{
"code": "Top Of The Rock",
"count": "4"
},
{
"code": "Visita Harlem guiada",
"count": "4"
},
{
"code": "Visita Washington",
"count": "3"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
]},
{"segment":93,
"top": [
{
"code": "Helicoptero NY",
"count": "3"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":94,
"top": [
{
"code": "Estatua de la Libertad",
"count": "3"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":95,
"top": [
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":96,
"top": [
{
"code": "New York City Pass",
"count": "8"
},
{
"code": "Bus Hopin Hopoff",
"count": "6"
},
{
"code": "Empire State Building",
"count": "5"
},
{
"code": "Ferry en NY",
"count": "3"
},
{
"code": "Explora Nueva York",
"count": "3"
},
{
"code": "Misa Harlem",
"count": "3"
},
{
"code": "Helicoptero NY",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "2"
},
{
"code": "Chicago Musical",
"count": "2"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
]},
{"segment":97,
"top": [
{
"code": "De tiendas en NY",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
]},
{"segment":98,
"top": [
{
"code": "Tour Gran Manzana",
"count": "2"
},
]},
{"segment":99,
"top": [
{
"code": "Empire State Building",
"count": "14"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Chicago Musical",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":100,
"top": [
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":101,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":102,
"top": [
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":103,
"top": [
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":104,
"top": [
{
"code": "Empire State Building",
"count": "8"
},
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":105,
"top": [
{
"code": "Empire State Building",
"count": "8"
},
{
"code": "New York City Pass",
"count": "6"
},
{
"code": "Estatua de la Libertad",
"count": "4"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":106,
"top": [
{
"code": "Empire State Building",
"count": "609"
},
{
"code": "AllStar Basket NY",
"count": "159"
},
{
"code": "Musical Mamma Mia",
"count": "101"
},
{
"code": "Cataratas del Niagara",
"count": "60"
},
{
"code": "Top Of The Rock",
"count": "51"
},
{
"code": "New York City Pass",
"count": "44"
},
{
"code": "Alto y Bajo Manhattan",
"count": "43"
},
{
"code": "Tour Gran Manzana",
"count": "33"
},
{
"code": "Excursion Contrastes NY",
"count": "26"
},
{
"code": "Tour Completo de 3 dias",
"count": "23"
},
{
"code": "Visita Washington",
"count": "18"
},
{
"code": "Museo 11S",
"count": "17"
},
{
"code": "Tour 11S",
"count": "17"
},
{
"code": "Misa Harlem",
"count": "15"
},
{
"code": "Ferry en NY",
"count": "12"
},
{
"code": "De tiendas en NY",
"count": "8"
},
{
"code": "Visita Harlem guiada",
"count": "7"
},
{
"code": "Helicoptero NY",
"count": "6"
},
{
"code": "Estatua de la Libertad",
"count": "6"
},
{
"code": "Rey Leon ",
"count": "6"
},
{
"code": "Museo de Cera",
"count": "6"
},
{
"code": "Fantasma de la Opera",
"count": "5"
},
{
"code": "Explora Nueva York",
"count": "4"
},
{
"code": "Nueva York Nocturno",
"count": "4"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":107,
"top": [
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":108,
"top": [
{
"code": "Empire State Building",
"count": "148"
},
{
"code": "AllStar Basket NY",
"count": "18"
},
{
"code": "Musical Mamma Mia",
"count": "16"
},
{
"code": "Cataratas del Niagara",
"count": "14"
},
{
"code": "Top Of The Rock",
"count": "9"
},
{
"code": "Alto y Bajo Manhattan",
"count": "9"
},
{
"code": "Tour 11S",
"count": "6"
},
{
"code": "New York City Pass",
"count": "6"
},
{
"code": "Fantasma de la Opera",
"count": "5"
},
{
"code": "Tour Completo de 3 dias",
"count": "5"
},
{
"code": "Misa Harlem",
"count": "5"
},
{
"code": "Estatua de la Libertad",
"count": "4"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Museo 11S",
"count": "3"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
]},
{"segment":109,
"top": [
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
]},
{"segment":110,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":111,
"top": [
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":112,
"top": [
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":113,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":114,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
]},
{"segment":115,
"top": [
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":116,
"top": [
{
"code": "Estatua de la Libertad",
"count": "5"
},
{
"code": "Fantasma de la Opera",
"count": "3"
},
{
"code": "Nueva York Nocturno",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":117,
"top": [
{
"code": "Empire State Building",
"count": "59"
},
{
"code": "AllStar Basket NY",
"count": "12"
},
{
"code": "Top Of The Rock",
"count": "8"
},
{
"code": "Excursion Contrastes NY",
"count": "7"
},
{
"code": "New York City Pass",
"count": "7"
},
{
"code": "Musical Mamma Mia",
"count": "7"
},
{
"code": "Cataratas del Niagara",
"count": "5"
},
{
"code": "Tour Completo de 3 dias",
"count": "4"
},
{
"code": "Tour Gran Manzana",
"count": "4"
},
{
"code": "Alto y Bajo Manhattan",
"count": "3"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
]},
{"segment":118,
"top": [
{
"code": "Chicago Musical",
"count": "37"
},
{
"code": "Misa Harlem",
"count": "14"
},
{
"code": "Bus Hopin Hopoff",
"count": "14"
},
{
"code": "Musical Mamma Mia",
"count": "8"
},
{
"code": "Empire State Building",
"count": "8"
},
{
"code": "AllStar Basket NY",
"count": "7"
},
{
"code": "Cena en el Hardrock",
"count": "5"
},
{
"code": "Tour Completo de 3 dias",
"count": "5"
},
{
"code": "Helicoptero NY",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "Tour 11S",
"count": "3"
},
{
"code": "Museo de Cera",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
]},
{"segment":119,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Chicago Musical",
"count": "2"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
]},
{"segment":120,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Alto y Bajo Manhattan",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":121,
"top": [
{
"code": "Tour Gran Manzana",
"count": "9"
},
{
"code": "Tour Completo de 3 dias",
"count": "5"
},
{
"code": "Fantasma de la Opera",
"count": "3"
},
{
"code": "De tiendas en NY",
"count": "3"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
]},
{"segment":122,
"top": [
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":123,
"top": [
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
]},
{"segment":124,
"top": [
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":125,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":126,
"top": [
{
"code": "Empire State Building",
"count": "15"
},
{
"code": "Explora Nueva York",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "Bus Hopin Hopoff",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
]},
{"segment":127,
"top": [
{
"code": "Empire State Building",
"count": "25"
},
{
"code": "Misa Harlem",
"count": "24"
},
{
"code": "AllStar Basket NY",
"count": "20"
},
{
"code": "Tour Gran Manzana",
"count": "15"
},
{
"code": "Tour Completo de 3 dias",
"count": "7"
},
{
"code": "Musical Mamma Mia",
"count": "5"
},
{
"code": "Chicago Musical",
"count": "4"
},
{
"code": "Excursion Contrastes NY",
"count": "4"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
]},
{"segment":128,
"top": [
{
"code": "Empire State Building",
"count": "5"
},
{
"code": "Explora Nueva York",
"count": "1"
},
]},
{"segment":129,
"top": [
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
]},
{"segment":130,
"top": [
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
]},
{"segment":131,
"top": [
{
"code": "Empire State Building",
"count": "141"
},
{
"code": "Explora Nueva York",
"count": "36"
},
{
"code": "Tour Gran Manzana",
"count": "35"
},
{
"code": "Tour 11S",
"count": "18"
},
{
"code": "Cataratas del Niagara",
"count": "17"
},
{
"code": "Top Of The Rock",
"count": "14"
},
{
"code": "Museo 11S",
"count": "13"
},
{
"code": "AllStar Basket NY",
"count": "9"
},
{
"code": "Bus Hopin Hopoff",
"count": "8"
},
{
"code": "Estatua de la Libertad",
"count": "4"
},
{
"code": "Visita Washington",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "3"
},
{
"code": "Fantasma de la Opera",
"count": "3"
},
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Chicago Musical",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
]},
{"segment":132,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":133,
"top": [
{
"code": "Chicago Musical",
"count": "1964"
},
{
"code": "Misa Harlem",
"count": "685"
},
{
"code": "Empire State Building",
"count": "459"
},
{
"code": "Bus Hopin Hopoff",
"count": "434"
},
{
"code": "AllStar Basket NY",
"count": "328"
},
{
"code": "Tour Gran Manzana",
"count": "284"
},
{
"code": "Tour Completo de 3 dias",
"count": "167"
},
{
"code": "Cena en el Hardrock",
"count": "166"
},
{
"code": "Helicoptero NY",
"count": "161"
},
{
"code": "Musical Mamma Mia",
"count": "121"
},
{
"code": "Nueva York Nocturno",
"count": "90"
},
{
"code": "Museo de Cera",
"count": "77"
},
{
"code": "Alto y Bajo Manhattan",
"count": "65"
},
{
"code": "Excursion Contrastes NY",
"count": "61"
},
{
"code": "Tour 11S",
"count": "53"
},
{
"code": "Explora Nueva York",
"count": "47"
},
{
"code": "Cataratas del Niagara",
"count": "46"
},
{
"code": "New York City Pass",
"count": "45"
},
{
"code": "Fantasma de la Opera",
"count": "37"
},
{
"code": "Museo 11S",
"count": "33"
},
{
"code": "Top Of The Rock",
"count": "30"
},
{
"code": "Visita Harlem guiada",
"count": "20"
},
{
"code": "Visita Washington",
"count": "12"
},
{
"code": "Estatua de la Libertad",
"count": "10"
},
{
"code": "Rey Leon ",
"count": "7"
},
{
"code": "Ferry en NY",
"count": "3"
},
{
"code": "De tiendas en NY",
"count": "2"
},
]},
{"segment":134,
"top": [
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
]},
{"segment":135,
"top": [
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":136,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":137,
"top": [
{
"code": "Empire State Building",
"count": "40"
},
{
"code": "AllStar Basket NY",
"count": "5"
},
{
"code": "Musical Mamma Mia",
"count": "4"
},
{
"code": "New York City Pass",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "4"
},
{
"code": "Alto y Bajo Manhattan",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
]},
{"segment":138,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
]},
{"segment":139,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "Chicago Musical",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Musical Mamma Mia",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
]},
{"segment":140,
"top": [
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":141,
"top": [
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":142,
"top": [
{
"code": "Empire State Building",
"count": "7"
},
{
"code": "Tour Gran Manzana",
"count": "4"
},
{
"code": "Estatua de la Libertad",
"count": "4"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
]},
{"segment":143,
"top": [
{
"code": "Empire State Building",
"count": "5"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":144,
"top": [
{
"code": "Empire State Building",
"count": "683"
},
{
"code": "Explora Nueva York",
"count": "146"
},
{
"code": "Tour Gran Manzana",
"count": "95"
},
{
"code": "Top Of The Rock",
"count": "69"
},
{
"code": "Tour 11S",
"count": "66"
},
{
"code": "AllStar Basket NY",
"count": "48"
},
{
"code": "Museo 11S",
"count": "33"
},
{
"code": "Cataratas del Niagara",
"count": "27"
},
{
"code": "Visita Washington",
"count": "25"
},
{
"code": "Estatua de la Libertad",
"count": "22"
},
{
"code": "Bus Hopin Hopoff",
"count": "22"
},
{
"code": "Helicoptero NY",
"count": "19"
},
{
"code": "Misa Harlem",
"count": "14"
},
{
"code": "Excursion Contrastes NY",
"count": "9"
},
{
"code": "Tour Completo de 3 dias",
"count": "8"
},
{
"code": "Fantasma de la Opera",
"count": "7"
},
{
"code": "Ferry en NY",
"count": "6"
},
{
"code": "Musical Mamma Mia",
"count": "5"
},
{
"code": "Chicago Musical",
"count": "5"
},
{
"code": "Alto y Bajo Manhattan",
"count": "3"
},
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "De tiendas en NY",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "2"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
]},
{"segment":145,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
]},
{"segment":146,
"top": [
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":147,
"top": [
{
"code": "Empire State Building",
"count": "82"
},
{
"code": "Misa Harlem",
"count": "29"
},
{
"code": "New York City Pass",
"count": "27"
},
{
"code": "Tour Gran Manzana",
"count": "26"
},
{
"code": "Bus Hopin Hopoff",
"count": "21"
},
{
"code": "Fantasma de la Opera",
"count": "16"
},
{
"code": "Cataratas del Niagara",
"count": "14"
},
{
"code": "Explora Nueva York",
"count": "12"
},
{
"code": "Chicago Musical",
"count": "11"
},
{
"code": "Visita Washington",
"count": "10"
},
{
"code": "Ferry en NY",
"count": "9"
},
{
"code": "Helicoptero NY",
"count": "9"
},
{
"code": "Cena en el Hardrock",
"count": "9"
},
{
"code": "AllStar Basket NY",
"count": "9"
},
{
"code": "Estatua de la Libertad",
"count": "9"
},
{
"code": "Tour Completo de 3 dias",
"count": "8"
},
{
"code": "Musical Mamma Mia",
"count": "8"
},
{
"code": "Tour 11S",
"count": "7"
},
{
"code": "Top Of The Rock",
"count": "4"
},
{
"code": "Museo 11S",
"count": "4"
},
{
"code": "Nueva York Nocturno",
"count": "3"
},
{
"code": "Alto y Bajo Manhattan",
"count": "3"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
]},
{"segment":148,
"top": [
{
"code": "Chicago Musical",
"count": "5"
},
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":149,
"top": [
{
"code": "Tour Gran Manzana",
"count": "9"
},
]},
{"segment":150,
"top": [
{
"code": "Empire State Building",
"count": "43"
},
{
"code": "Explora Nueva York",
"count": "36"
},
{
"code": "Estatua de la Libertad",
"count": "24"
},
{
"code": "Top Of The Rock",
"count": "18"
},
{
"code": "Helicoptero NY",
"count": "15"
},
{
"code": "New York City Pass",
"count": "13"
},
{
"code": "Tour 11S",
"count": "12"
},
{
"code": "Tour Gran Manzana",
"count": "11"
},
{
"code": "Museo 11S",
"count": "8"
},
{
"code": "Cataratas del Niagara",
"count": "7"
},
{
"code": "Visita Washington",
"count": "7"
},
{
"code": "Bus Hopin Hopoff",
"count": "6"
},
{
"code": "Fantasma de la Opera",
"count": "4"
},
{
"code": "AllStar Basket NY",
"count": "4"
},
{
"code": "Misa Harlem",
"count": "3"
},
{
"code": "Visita Harlem guiada",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "3"
},
{
"code": "Nueva York Nocturno",
"count": "2"
},
{
"code": "Cena en el Hardrock",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Chicago Musical",
"count": "1"
},
]},
{"segment":151,
"top": [
{
"code": "Tour Gran Manzana",
"count": "40"
},
{
"code": "Tour Completo de 3 dias",
"count": "16"
},
{
"code": "Rey Leon ",
"count": "7"
},
{
"code": "Helicoptero NY",
"count": "7"
},
{
"code": "Empire State Building",
"count": "7"
},
{
"code": "Museo 11S",
"count": "7"
},
{
"code": "Cataratas del Niagara",
"count": "7"
},
{
"code": "De tiendas en NY",
"count": "6"
},
{
"code": "AllStar Basket NY",
"count": "5"
},
{
"code": "Ferry en NY",
"count": "4"
},
{
"code": "Visita Washington",
"count": "4"
},
{
"code": "Visita Harlem guiada",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
]},
{"segment":152,
"top": [
{
"code": "Tour Gran Manzana",
"count": "9"
},
{
"code": "Museo 11S",
"count": "6"
},
{
"code": "Helicoptero NY",
"count": "5"
},
{
"code": "Estatua de la Libertad",
"count": "4"
},
{
"code": "New York City Pass",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "4"
},
{
"code": "Explora Nueva York",
"count": "3"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
]},
{"segment":153,
"top": [
{
"code": "Empire State Building",
"count": "5"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":154,
"top": [
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":155,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
]},
{"segment":156,
"top": [
{
"code": "Empire State Building",
"count": "9"
},
{
"code": "New York City Pass",
"count": "7"
},
{
"code": "Chicago Musical",
"count": "5"
},
{
"code": "Fantasma de la Opera",
"count": "4"
},
{
"code": "Ferry en NY",
"count": "4"
},
{
"code": "Tour Completo de 3 dias",
"count": "4"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Misa Harlem",
"count": "3"
},
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "Bus Hopin Hopoff",
"count": "3"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
]},
{"segment":157,
"top": [
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":158,
"top": [
{
"code": "Empire State Building",
"count": "9"
},
{
"code": "Estatua de la Libertad",
"count": "3"
},
{
"code": "Misa Harlem",
"count": "3"
},
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Bus Hopin Hopoff",
"count": "2"
},
{
"code": "Cataratas del Niagara",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
]},
{"segment":159,
"top": [
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":160,
"top": [
{
"code": "Empire State Building",
"count": "54"
},
{
"code": "New York City Pass",
"count": "23"
},
{
"code": "Misa Harlem",
"count": "16"
},
{
"code": "Cataratas del Niagara",
"count": "8"
},
{
"code": "Bus Hopin Hopoff",
"count": "7"
},
{
"code": "Helicoptero NY",
"count": "6"
},
{
"code": "Tour 11S",
"count": "6"
},
{
"code": "AllStar Basket NY",
"count": "5"
},
{
"code": "Chicago Musical",
"count": "5"
},
{
"code": "Visita Washington",
"count": "4"
},
{
"code": "Visita Harlem guiada",
"count": "4"
},
{
"code": "Explora Nueva York",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":161,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "Chicago Musical",
"count": "3"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":162,
"top": [
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":163,
"top": [
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
]},
{"segment":164,
"top": [
{
"code": "Tour Completo de 3 dias",
"count": "4"
},
{
"code": "Tour Gran Manzana",
"count": "4"
},
{
"code": "De tiendas en NY",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
]},
{"segment":165,
"top": [
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":166,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":167,
"top": [
{
"code": "Empire State Building",
"count": "128"
},
{
"code": "New York City Pass",
"count": "43"
},
{
"code": "Explora Nueva York",
"count": "29"
},
{
"code": "Misa Harlem",
"count": "28"
},
{
"code": "Cataratas del Niagara",
"count": "24"
},
{
"code": "Helicoptero NY",
"count": "18"
},
{
"code": "Bus Hopin Hopoff",
"count": "14"
},
{
"code": "AllStar Basket NY",
"count": "13"
},
{
"code": "Tour 11S",
"count": "13"
},
{
"code": "Visita Washington",
"count": "13"
},
{
"code": "Chicago Musical",
"count": "9"
},
{
"code": "Museo 11S",
"count": "9"
},
{
"code": "Visita Harlem guiada",
"count": "8"
},
{
"code": "Top Of The Rock",
"count": "7"
},
{
"code": "Excursion Contrastes NY",
"count": "7"
},
{
"code": "Nueva York Nocturno",
"count": "6"
},
{
"code": "Tour Gran Manzana",
"count": "5"
},
{
"code": "Tour Completo de 3 dias",
"count": "5"
},
{
"code": "Ferry en NY",
"count": "4"
},
{
"code": "Alto y Bajo Manhattan",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
]},
{"segment":168,
"top": [
{
"code": "Empire State Building",
"count": "166"
},
{
"code": "Musical Mamma Mia",
"count": "39"
},
{
"code": "AllStar Basket NY",
"count": "27"
},
{
"code": "Top Of The Rock",
"count": "19"
},
{
"code": "New York City Pass",
"count": "19"
},
{
"code": "Alto y Bajo Manhattan",
"count": "18"
},
{
"code": "Cataratas del Niagara",
"count": "16"
},
{
"code": "Tour Gran Manzana",
"count": "9"
},
{
"code": "Excursion Contrastes NY",
"count": "9"
},
{
"code": "Misa Harlem",
"count": "8"
},
{
"code": "Tour Completo de 3 dias",
"count": "8"
},
{
"code": "Tour 11S",
"count": "5"
},
{
"code": "Explora Nueva York",
"count": "5"
},
{
"code": "Ferry en NY",
"count": "4"
},
{
"code": "Museo 11S",
"count": "3"
},
{
"code": "Visita Washington",
"count": "3"
},
{
"code": "Rey Leon ",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
]},
{"segment":169,
"top": [
{
"code": "Chicago Musical",
"count": "52"
},
{
"code": "Empire State Building",
"count": "46"
},
{
"code": "AllStar Basket NY",
"count": "19"
},
{
"code": "Misa Harlem",
"count": "18"
},
{
"code": "Bus Hopin Hopoff",
"count": "15"
},
{
"code": "Tour Gran Manzana",
"count": "10"
},
{
"code": "Cena en el Hardrock",
"count": "8"
},
{
"code": "Musical Mamma Mia",
"count": "8"
},
{
"code": "Nueva York Nocturno",
"count": "7"
},
{
"code": "Helicoptero NY",
"count": "6"
},
{
"code": "Tour Completo de 3 dias",
"count": "5"
},
{
"code": "Top Of The Rock",
"count": "4"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Museo de Cera",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
]},
{"segment":170,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
]},
{"segment":171,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":172,
"top": [
{
"code": "Chicago Musical",
"count": "11"
},
{
"code": "Empire State Building",
"count": "7"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Bus Hopin Hopoff",
"count": "3"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Alto y Bajo Manhattan",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "2"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
]},
{"segment":173,
"top": [
{
"code": "Explora Nueva York",
"count": "18"
},
{
"code": "Top Of The Rock",
"count": "17"
},
{
"code": "Empire State Building",
"count": "17"
},
{
"code": "Tour 11S",
"count": "10"
},
{
"code": "Helicoptero NY",
"count": "10"
},
{
"code": "Estatua de la Libertad",
"count": "9"
},
{
"code": "Bus Hopin Hopoff",
"count": "8"
},
{
"code": "Museo 11S",
"count": "6"
},
{
"code": "Tour Gran Manzana",
"count": "6"
},
{
"code": "Cataratas del Niagara",
"count": "5"
},
{
"code": "Misa Harlem",
"count": "4"
},
{
"code": "New York City Pass",
"count": "4"
},
{
"code": "Tour Completo de 3 dias",
"count": "3"
},
{
"code": "Rey Leon ",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "2"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
]},
{"segment":174,
"top": [
{
"code": "Empire State Building",
"count": "32"
},
{
"code": "Tour Completo de 3 dias",
"count": "4"
},
{
"code": "Tour Gran Manzana",
"count": "4"
},
{
"code": "Musical Mamma Mia",
"count": "3"
},
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "Top Of The Rock",
"count": "3"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
]},
{"segment":175,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":176,
"top": [
{
"code": "Chicago Musical",
"count": "10"
},
{
"code": "Empire State Building",
"count": "5"
},
{
"code": "Bus Hopin Hopoff",
"count": "3"
},
{
"code": "Alto y Bajo Manhattan",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
]},
{"segment":177,
"top": [
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "Misa Harlem",
"count": "3"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":178,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "Chicago Musical",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
]},
{"segment":179,
"top": [
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
]},
{"segment":180,
"top": [
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
]},
{"segment":181,
"top": [
{
"code": "Chicago Musical",
"count": "71"
},
{
"code": "Empire State Building",
"count": "46"
},
{
"code": "Misa Harlem",
"count": "25"
},
{
"code": "Tour Gran Manzana",
"count": "18"
},
{
"code": "Bus Hopin Hopoff",
"count": "17"
},
{
"code": "AllStar Basket NY",
"count": "14"
},
{
"code": "Nueva York Nocturno",
"count": "9"
},
{
"code": "Tour 11S",
"count": "9"
},
{
"code": "Cena en el Hardrock",
"count": "8"
},
{
"code": "Tour Completo de 3 dias",
"count": "8"
},
{
"code": "Excursion Contrastes NY",
"count": "6"
},
{
"code": "Musical Mamma Mia",
"count": "6"
},
{
"code": "Cataratas del Niagara",
"count": "6"
},
{
"code": "Helicoptero NY",
"count": "5"
},
{
"code": "Top Of The Rock",
"count": "4"
},
{
"code": "Alto y Bajo Manhattan",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "De tiendas en NY",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "2"
},
{
"code": "Museo de Cera",
"count": "2"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":182,
"top": [
{
"code": "Empire State Building",
"count": "8"
},
{
"code": "Chicago Musical",
"count": "5"
},
{
"code": "AllStar Basket NY",
"count": "4"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
]},
{"segment":183,
"top": [
{
"code": "Tour Gran Manzana",
"count": "18"
},
{
"code": "Tour Completo de 3 dias",
"count": "6"
},
{
"code": "Fantasma de la Opera",
"count": "5"
},
{
"code": "Cataratas del Niagara",
"count": "4"
},
{
"code": "Helicoptero NY",
"count": "4"
},
{
"code": "De tiendas en NY",
"count": "4"
},
{
"code": "Museo 11S",
"count": "3"
},
{
"code": "AllStar Basket NY",
"count": "3"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
]},
{"segment":184,
"top": [
{
"code": "Empire State Building",
"count": "24"
},
{
"code": "Tour Gran Manzana",
"count": "7"
},
{
"code": "Bus Hopin Hopoff",
"count": "7"
},
{
"code": "New York City Pass",
"count": "7"
},
{
"code": "Ferry en NY",
"count": "6"
},
{
"code": "Misa Harlem",
"count": "5"
},
{
"code": "Explora Nueva York",
"count": "5"
},
{
"code": "Tour Completo de 3 dias",
"count": "5"
},
{
"code": "Chicago Musical",
"count": "5"
},
{
"code": "Tour 11S",
"count": "5"
},
{
"code": "Helicoptero NY",
"count": "4"
},
{
"code": "Top Of The Rock",
"count": "3"
},
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "AllStar Basket NY",
"count": "3"
},
{
"code": "Fantasma de la Opera",
"count": "3"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "2"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
]},
{"segment":185,
"top": [
{
"code": "New York City Pass",
"count": "148"
},
{
"code": "Tour Gran Manzana",
"count": "84"
},
{
"code": "Empire State Building",
"count": "48"
},
{
"code": "AllStar Basket NY",
"count": "24"
},
{
"code": "Tour Completo de 3 dias",
"count": "17"
},
{
"code": "Cataratas del Niagara",
"count": "17"
},
{
"code": "De tiendas en NY",
"count": "11"
},
{
"code": "Rey Leon ",
"count": "11"
},
{
"code": "Explora Nueva York",
"count": "10"
},
{
"code": "Musical Mamma Mia",
"count": "10"
},
{
"code": "Visita Harlem guiada",
"count": "9"
},
{
"code": "Excursion Contrastes NY",
"count": "7"
},
{
"code": "Visita Washington",
"count": "7"
},
{
"code": "Tour 11S",
"count": "6"
},
{
"code": "Alto y Bajo Manhattan",
"count": "5"
},
{
"code": "Top Of The Rock",
"count": "5"
},
{
"code": "Ferry en NY",
"count": "5"
},
{
"code": "Museo 11S",
"count": "3"
},
{
"code": "Fantasma de la Opera",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":186,
"top": [
{
"code": "Chicago Musical",
"count": "231"
},
{
"code": "Empire State Building",
"count": "67"
},
{
"code": "Misa Harlem",
"count": "56"
},
{
"code": "Tour Gran Manzana",
"count": "44"
},
{
"code": "Bus Hopin Hopoff",
"count": "44"
},
{
"code": "AllStar Basket NY",
"count": "42"
},
{
"code": "Tour Completo de 3 dias",
"count": "24"
},
{
"code": "Musical Mamma Mia",
"count": "23"
},
{
"code": "Helicoptero NY",
"count": "18"
},
{
"code": "Cena en el Hardrock",
"count": "16"
},
{
"code": "Alto y Bajo Manhattan",
"count": "11"
},
{
"code": "Top Of The Rock",
"count": "9"
},
{
"code": "Museo de Cera",
"count": "8"
},
{
"code": "Museo 11S",
"count": "8"
},
{
"code": "Explora Nueva York",
"count": "7"
},
{
"code": "Excursion Contrastes NY",
"count": "7"
},
{
"code": "New York City Pass",
"count": "6"
},
{
"code": "Cataratas del Niagara",
"count": "6"
},
{
"code": "Nueva York Nocturno",
"count": "5"
},
{
"code": "Tour 11S",
"count": "5"
},
{
"code": "Rey Leon ",
"count": "4"
},
{
"code": "Fantasma de la Opera",
"count": "4"
},
{
"code": "De tiendas en NY",
"count": "3"
},
{
"code": "Visita Harlem guiada",
"count": "2"
},
{
"code": "Visita Washington",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":187,
"top": [
{
"code": "Empire State Building",
"count": "12"
},
{
"code": "Visita Washington",
"count": "3"
},
{
"code": "Helicoptero NY",
"count": "2"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
]},
{"segment":188,
"top": [
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":189,
"top": [
{
"code": "Tour Gran Manzana",
"count": "9"
},
{
"code": "New York City Pass",
"count": "7"
},
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":190,
"top": [
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":191,
"top": [
{
"code": "Chicago Musical",
"count": "9"
},
{
"code": "Bus Hopin Hopoff",
"count": "3"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
]},
{"segment":192,
"top": [
{
"code": "Tour Gran Manzana",
"count": "387"
},
{
"code": "Tour Completo de 3 dias",
"count": "135"
},
{
"code": "AllStar Basket NY",
"count": "119"
},
{
"code": "Cataratas del Niagara",
"count": "84"
},
{
"code": "De tiendas en NY",
"count": "70"
},
{
"code": "New York City Pass",
"count": "57"
},
{
"code": "Museo 11S",
"count": "54"
},
{
"code": "Rey Leon ",
"count": "53"
},
{
"code": "Empire State Building",
"count": "48"
},
{
"code": "Helicoptero NY",
"count": "46"
},
{
"code": "Excursion Contrastes NY",
"count": "34"
},
{
"code": "Fantasma de la Opera",
"count": "33"
},
{
"code": "Visita Washington",
"count": "23"
},
{
"code": "Visita Harlem guiada",
"count": "21"
},
{
"code": "Ferry en NY",
"count": "20"
},
{
"code": "Tour 11S",
"count": "16"
},
{
"code": "Top Of The Rock",
"count": "15"
},
{
"code": "Explora Nueva York",
"count": "13"
},
{
"code": "Estatua de la Libertad",
"count": "12"
},
{
"code": "Museo de Cera",
"count": "11"
},
{
"code": "Nueva York Nocturno",
"count": "4"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
]},
{"segment":193,
"top": [
{
"code": "Empire State Building",
"count": "17"
},
{
"code": "Musical Mamma Mia",
"count": "6"
},
{
"code": "Top Of The Rock",
"count": "4"
},
{
"code": "Cataratas del Niagara",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "AllStar Basket NY",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "2"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
]},
{"segment":194,
"top": [
{
"code": "Empire State Building",
"count": "6"
},
]},
{"segment":195,
"top": [
{
"code": "Chicago Musical",
"count": "35"
},
{
"code": "Empire State Building",
"count": "11"
},
{
"code": "Tour Gran Manzana",
"count": "10"
},
{
"code": "Misa Harlem",
"count": "10"
},
{
"code": "Bus Hopin Hopoff",
"count": "6"
},
{
"code": "AllStar Basket NY",
"count": "6"
},
{
"code": "Cena en el Hardrock",
"count": "3"
},
{
"code": "Musical Mamma Mia",
"count": "3"
},
{
"code": "Helicoptero NY",
"count": "3"
},
{
"code": "Tour Completo de 3 dias",
"count": "3"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":196,
"top": [
{
"code": "Tour Gran Manzana",
"count": "10"
},
]},
{"segment":197,
"top": [
{
"code": "Chicago Musical",
"count": "13"
},
{
"code": "Misa Harlem",
"count": "5"
},
{
"code": "AllStar Basket NY",
"count": "5"
},
{
"code": "Cena en el Hardrock",
"count": "4"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":198,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
]},
{"segment":199,
"top": [
{
"code": "Empire State Building",
"count": "22"
},
{
"code": "AllStar Basket NY",
"count": "16"
},
{
"code": "Tour Gran Manzana",
"count": "10"
},
{
"code": "Tour Completo de 3 dias",
"count": "7"
},
{
"code": "New York City Pass",
"count": "6"
},
{
"code": "Cataratas del Niagara",
"count": "4"
},
{
"code": "Helicoptero NY",
"count": "3"
},
{
"code": "De tiendas en NY",
"count": "3"
},
{
"code": "Estatua de la Libertad",
"count": "3"
},
{
"code": "Excursion Contrastes NY",
"count": "3"
},
{
"code": "Alto y Bajo Manhattan",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "2"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
]},
{"segment":200,
"top": [
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
]},
{"segment":201,
"top": [
{
"code": "Empire State Building",
"count": "52"
},
{
"code": "AllStar Basket NY",
"count": "14"
},
{
"code": "Cataratas del Niagara",
"count": "8"
},
{
"code": "New York City Pass",
"count": "6"
},
{
"code": "Musical Mamma Mia",
"count": "5"
},
{
"code": "Tour 11S",
"count": "4"
},
{
"code": "De tiendas en NY",
"count": "3"
},
{
"code": "Alto y Bajo Manhattan",
"count": "3"
},
{
"code": "Misa Harlem",
"count": "3"
},
{
"code": "Top Of The Rock",
"count": "3"
},
{
"code": "Excursion Contrastes NY",
"count": "3"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Explora Nueva York",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
]},
{"segment":202,
"top": [
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Fantasma de la Opera",
"count": "3"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Museo 11S",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
]},
{"segment":203,
"top": [
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
]},
{"segment":204,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":205,
"top": [
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":206,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
]},
{"segment":207,
"top": [
{
"code": "Empire State Building",
"count": "4"
},
{
"code": "AllStar Basket NY",
"count": "3"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Tour 11S",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
]},
{"segment":208,
"top": [
{
"code": "Tour Gran Manzana",
"count": "1"
},
]},
{"segment":209,
"top": [
{
"code": "Estatua de la Libertad",
"count": "3"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "2"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Bus Hopin Hopoff",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
]},
{"segment":210,
"top": [
{
"code": "Empire State Building",
"count": "9"
},
{
"code": "New York City Pass",
"count": "4"
},
{
"code": "Misa Harlem",
"count": "4"
},
{
"code": "Tour 11S",
"count": "3"
},
{
"code": "Explora Nueva York",
"count": "2"
},
{
"code": "Bus Hopin Hopoff",
"count": "2"
},
{
"code": "Nueva York Nocturno",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Cena en el Hardrock",
"count": "1"
},
{
"code": "Top Of The Rock",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":211,
"top": [
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
{
"code": "Chicago Musical",
"count": "1"
},
{
"code": "Helicoptero NY",
"count": "1"
},
]},
{"segment":212,
"top": [
{
"code": "Empire State Building",
"count": "3"
},
]},
{"segment":213,
"top": [
{
"code": "Empire State Building",
"count": "7"
},
{
"code": "New York City Pass",
"count": "4"
},
{
"code": "Tour Gran Manzana",
"count": "3"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Tour Completo de 3 dias",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
]},
{"segment":214,
"top": [
{
"code": "Helicoptero NY",
"count": "3"
},
{
"code": "Top Of The Rock",
"count": "2"
},
{
"code": "Tour 11S",
"count": "2"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Visita Washington",
"count": "1"
},
]},
{"segment":215,
"top": [
{
"code": "Empire State Building",
"count": "119"
},
{
"code": "AllStar Basket NY",
"count": "29"
},
{
"code": "Musical Mamma Mia",
"count": "24"
},
{
"code": "Tour Gran Manzana",
"count": "15"
},
{
"code": "Cataratas del Niagara",
"count": "14"
},
{
"code": "New York City Pass",
"count": "12"
},
{
"code": "Alto y Bajo Manhattan",
"count": "11"
},
{
"code": "Top Of The Rock",
"count": "10"
},
{
"code": "Tour Completo de 3 dias",
"count": "10"
},
{
"code": "Excursion Contrastes NY",
"count": "8"
},
{
"code": "Visita Washington",
"count": "5"
},
{
"code": "Tour 11S",
"count": "4"
},
{
"code": "Misa Harlem",
"count": "4"
},
{
"code": "Museo 11S",
"count": "3"
},
{
"code": "Fantasma de la Opera",
"count": "3"
},
{
"code": "Museo de Cera",
"count": "2"
},
{
"code": "De tiendas en NY",
"count": "2"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Nueva York Nocturno",
"count": "1"
},
]},
{"segment":216,
"top": [
{
"code": "Tour Gran Manzana",
"count": "6"
},
{
"code": "Estatua de la Libertad",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "New York City Pass",
"count": "1"
},
{
"code": "Museo de Cera",
"count": "1"
},
]},
{"segment":217,
"top": [
{
"code": "New York City Pass",
"count": "24"
},
{
"code": "Tour Gran Manzana",
"count": "12"
},
{
"code": "AllStar Basket NY",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "2"
},
{
"code": "Empire State Building",
"count": "2"
},
{
"code": "Tour 11S",
"count": "2"
},
]},
{"segment":218,
"top": [
{
"code": "New York City Pass",
"count": "22"
},
{
"code": "Tour Gran Manzana",
"count": "11"
},
{
"code": "Empire State Building",
"count": "8"
},
{
"code": "Tour Completo de 3 dias",
"count": "3"
},
{
"code": "AllStar Basket NY",
"count": "3"
},
{
"code": "Rey Leon ",
"count": "2"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Estatua de la Libertad",
"count": "1"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "De tiendas en NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
]},
{"segment":219,
"top": [
{
"code": "New York City Pass",
"count": "2"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Tour Gran Manzana",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
]},
{"segment":220,
"top": [
{
"code": "New York City Pass",
"count": "22"
},
{
"code": "Tour Gran Manzana",
"count": "13"
},
{
"code": "Empire State Building",
"count": "10"
},
{
"code": "Tour Completo de 3 dias",
"count": "7"
},
{
"code": "Cataratas del Niagara",
"count": "4"
},
{
"code": "AllStar Basket NY",
"count": "3"
},
{
"code": "De tiendas en NY",
"count": "3"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
{
"code": "Rey Leon ",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "Visita Harlem guiada",
"count": "1"
},
{
"code": "Fantasma de la Opera",
"count": "1"
},
]},
{"segment":221,
"top": [
{
"code": "Chicago Musical",
"count": "3"
},
{
"code": "Alto y Bajo Manhattan",
"count": "1"
},
{
"code": "Misa Harlem",
"count": "1"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
]},
{"segment":222,
"top": [
{
"code": "Bus Hopin Hopoff",
"count": "2"
},
{
"code": "Musical Mamma Mia",
"count": "1"
},
]},
{"segment":223,
"top": [
{
"code": "Tour Gran Manzana",
"count": "11"
},
{
"code": "New York City Pass",
"count": "3"
},
{
"code": "Museo 11S",
"count": "2"
},
{
"code": "Helicoptero NY",
"count": "1"
},
{
"code": "Ferry en NY",
"count": "1"
},
{
"code": "Cataratas del Niagara",
"count": "1"
},
{
"code": "Empire State Building",
"count": "1"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
]},
{"segment":224,
"top": [
{
"code": "Empire State Building",
"count": "8"
},
{
"code": "Tour Gran Manzana",
"count": "2"
},
{
"code": "Excursion Contrastes NY",
"count": "1"
},
{
"code": "AllStar Basket NY",
"count": "1"
},
]}];
| 91,372
| 44,384
|
module.exports = new Date(2025, 5, 5)
| 38
| 20
|
import * as ItinerariesActionTypes from '../actiontypes/itineraries';
const initialState = []
export default function Itineraries(state=initialState, action){
switch (action.type) {
case ItinerariesActionTypes.UPDATE_ITINERARIES:{
return action.itineraries;
}
default:
return state;
}
}
| 317
| 95
|
/*
Copyright (c) 2009, www.redips.net All rights reserved.
Code licensed under the BSD License: http://www.redips.net/license/
http://www.redips.net/javascript/drag-and-drop-table-content/
version 1.3.3
Jul 15, 2009.
*/
// parameters that can be changed
var hover_color = '#E7AB83'; // define hover color
var bound = 25; // bound width for autoscroll
var speed = 20; // scroll speed in milliseconds
var forbid = 'forbid'; // cell class name where draggable element can not be dropped
var trash = 'trash'; // cell class name where draggable element will be destroyed
var trash_ask = true; // confirm object deletion (ask a question "Are you sure?" before delete)
var single_content = false; // enable dropping to already taken table cells
// other parameters
var obj = false; // draggable object
var obj_margin; // space from clicked point to the object bounds (top, right, bottom, left)
var mouseButton = 0; // if mouseButton == 1 then first mouse button is pressed
var mouseX, mouseY; // mouse coordinates (used in onmousedown, onmousemove and autoscroll)
var window_width= 0, window_height=0; // window width and height (parameters are set in onload and onresize event handler)
var scroll_width, scroll_height; // scroll width and height of the window (it is usually greater then window)
var edgeX=0, edgeY=0; // autoscroll bound values (closer to the page edge, faster scroll) calculated in onmousemove handler
var bgcolor_old; // old cell background color
var tables; // table offsets and row offsets (initialized in onload event)
var autoscrollX_flag=autoscrollY_flag=0;// needed to prevent multiple calls of autoscrollX and autoscrollY from onmousemove event handler
var moved_flag = 0;
// selected, previous and started table, row and cell
var table = table_old = table_source = null;
var row = row_old = row_source = null;
var cell = cell_old = cell_source = null;
//
// event handlers
//
// onLoad event
window.onload = function (){
// collect tables inside div with id=drag
tables = document.getElementById('drag').getElementsByTagName('table');
// set initial window width/height, scroll width/height and define onresize event handler
// onresize event handler calls calculate columns
handler_onresize();
window.onresize = handler_onresize;
// collect div elements inside tables (draggable elements)
var divs = document.getElementById('drag').getElementsByTagName('div');
// attach onmousedown event handler to DIV elements
for (var i=0; i<divs.length; i++) divs[i].onmousedown = handler_onmousedown;
// dissable text selection for IE (but not for the form elements)
document.onselectstart = function(e) {var evt = e || window.event; if (!isFormElement(evt)) return false}
// attach onscroll event (needed for recalculating table cells positions)
window.onscroll = calculate_cells;
}
// onresize window event handler
// this event handler sets window_width and window_height variables used in onmousemove handler
function handler_onresize(){
// Non-IE
if (typeof(window.innerWidth) == 'number'){
window_width = window.innerWidth;
window_height = window.innerHeight;
}
// IE 6+ in 'standards compliant mode'
else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)){
window_width = document.documentElement.clientWidth;
window_height = document.documentElement.clientHeight;
}
// IE 4 compatible
else if (document.body && (document.body.clientWidth || document.body.clientHeight)){
window_width = document.body.clientWidth;
window_height = document.body.clientHeight;
}
// set scroll size (onresize, onload and onmouseup event)
scroll_width = document.documentElement.scrollWidth;
scroll_height = document.documentElement.scrollHeight;
// calculate colums and rows offset (cells dimensions)
calculate_cells();
}
// onmousedown handler
function handler_onmousedown(e){
// define event (cross browser)
var evt = e || window.event;
// enable control for form elements
if (isFormElement(evt)) return true;
// set a reference to the moved object
obj = this;
// set clicked position
mouseX = evt.clientX;
mouseY = evt.clientY;
// set current table, row and cell
set_tcr(evt);
// remember started table, row and cell
table_source = table;
row_source = row;
cell_source = cell;
// define pressed mouse button
if (evt.which) mouseButton = evt.which;
else mouseButton = evt.button;
// activate onmousemove and onmouseup event handlers on document level
// if left mouse button is pressed
if (mouseButton == 1){
moved_flag = 1; // set moved_flag (if need to clone object in handler_onmousemove)
document.onmousemove = handler_onmousemove;
document.onmouseup = handler_onmouseup;
}
// remember background cell color
bgcolor_old = tables[table].rows[row].cells[cell].style.backgroundColor;
// define object offset
var offset = box_offset(obj);
// calculate ofsset from the clicked point inside element to the
// top, right, bottom and left side of the element
obj_margin = [mouseY-offset[0], offset[1]-mouseX, offset[2]-mouseY, mouseX-offset[3]];
// disable text selection
return false;
}
// onmouseup handler
function handler_onmouseup(e){
// define destination table cell
var destination_cell;
// reset mouseButton variable
mouseButton = 0;
// reset left and top styles
obj.style.left = 0;
obj.style.top = 0;
// if object was dropped inside table then define a new location for destination cell
if (table < tables.length)
destination_cell = tables[table].rows[row].cells[cell];
else // or use the last possible location (object was dropped outside table)
destination_cell = tables[table_old].rows[row_old].cells[cell_old];
// return background color for destination color (cell had hover color)
destination_cell.style.backgroundColor = bgcolor_old;
// detach onmousemove and onmouseup events
document.onmousemove = null;
document.onmouseup = null;
// document.body.scroll... only works in compatibility (aka quirks) mode,
// for standard mode, use: document.documentElement.scroll...
scroll_width = document.documentElement.scrollWidth;
scroll_height = document.documentElement.scrollHeight;
// reset autoscroll flags
autoscrollX_flag = autoscrollY_flag = 0;
// reset old positions
table_old = row_old = cell_old = null;
// remove child if destination cell has "trash" in class names
if (destination_cell.className.indexOf(trash) > -1){
// remove child from DOM (node still exists in memory)
obj.parentNode.removeChild(obj);
// if parameter trash_ask is "true", confirm deletion (function trash_delete is at bottom of this script)
if (trash_ask) setTimeout(trash_delete, 10);
}
// else append object to the cell
else destination_cell.appendChild(obj);
// recalculate table cells and scrollers because cell content could change row dimensions
calculate_cells();
}
// onmousemove handler for the document level
// activated after left mouse button is pressed on draggable element
function handler_onmousemove(e){
// define event (FF & IE)
var evt = e || window.event;
// if moved_flag is set and object has clone in class name, then duplicate object
if (moved_flag == 1 && obj.className.indexOf('clone') > -1){
moved_flag = 0;
clone_obj();
}
// set left and top styles for the moved element if element is inside window
// this conditions will stop element on window bounds
if (evt.clientX > obj_margin[3] && evt.clientX < window_width - obj_margin[1]) obj.style.left = (evt.clientX - mouseX) + "px";
if (evt.clientY > obj_margin[0] && evt.clientY < window_height - obj_margin[2]) obj.style.top = (evt.clientY - mouseY) + "px";
// set current table, row and cell
set_tcr(evt);
// if new location is inside table and new location is different then old location
// set background colors for the previous and new table cell
if (table < tables.length && (table != table_old || cell != cell_old || row != row_old)){
// set cell background color to the previous cell
if (table_old != null && row_old != null && cell_old != null)
tables[table_old].rows[row_old].cells[cell_old].style.backgroundColor = bgcolor_old;
// remember background color before setting the new background color
bgcolor_old = tables[table].rows[row].cells[cell].style.backgroundColor;
// set background color to the current table cell
tables[table].rows[row].cells[cell].style.backgroundColor = hover_color;
// remember current position (for table, row and cell)
table_old=table; row_old=row; cell_old=cell;
}
// test if is still first mouse button pressed (in case when user release mouse button out of a window)
if (evt.which) mouseButton = evt.which;
else mouseButton = evt.button;
// if first mouse button is released
if (mouseButton != 1){handler_onmouseup(evt); return;}
// calculate horizontally crossed page bound
edgeX = bound - (window_width/2 > evt.clientX ? evt.clientX-obj_margin[3] : window_width - evt.clientX - obj_margin[1]);
// if element crosses page bound then set scroll direction and call auto scroll
if (edgeX > 0){
// in case when object is only half visible (page is scrolled on that object)
if (edgeX > bound) edgeX = bound;
// set scroll direction: negative - left, positive - right
edgeX *= evt.clientX < window_width/2 ? -1 : 1;
// remove onscroll event handler and call autoscrollY function only once
if (autoscrollX_flag++ == 0) {window.onscroll = null; autoscrollX()}
}
else edgeX = 0;
// calculate vertically crossed page bound
edgeY = bound - (window_height/2 > evt.clientY ? evt.clientY-obj_margin[0] : window_height - evt.clientY - obj_margin[2]);
// if element crosses page bound then set scroll direction and call auto scroll
if (edgeY > 0){
// in case when object is only half visible (page is scrolled on that object)
if (edgeY > bound) edgeY = bound;
// set scroll direction: negative - up, positive - down
edgeY *= evt.clientY < window_height/2 ? -1 : 1;
// remove onscroll event handler and call autoscrollY function only once
if (autoscrollY_flag++ == 0) {window.onscroll = null; autoscrollY()}
}
else edgeY = 0;
}
//
// auto scroll functions
//
// horizontal auto scroll function
function autoscrollX(call){
// define old scroll position and current scroll position
var old = 0;
var scrollPosition = getScrollPosition('X');
// mouse button should be pressed and
// if moved element is over left or right margin
// scroll_width - window_width returns maximum horizontal scroll position
if (mouseButton == 1 && ((edgeX < 0 && scrollPosition > 0) || (edgeX > 0 && scrollPosition < (scroll_width - window_width)))){
// horizontal window scroll
window.scrollBy(edgeX, 0);
// set previous scroll position and new after window is scrolled
old = scrollPosition;
scrollPosition = getScrollPosition('X');
// set style left for the moved element
obj.style.left = (parseInt(obj.style.left) + scrollPosition - old) + "px";
// move X point
mouseX -= scrollPosition - old;
// recursive autoscroll call
setTimeout("autoscrollX('recursive')", speed);
}
// autoscroll stopped by moving element out of the page edge
// or element faced maximum position (left or right)
else{
// recalculate cell positions if call was function itself (spare CPU if moving object across bound)
if (call == 'recursive') calculate_cells();
// return onscroll event handler and reset auto scroll flag
window.onscroll = calculate_cells;
autoscrollX_flag = 0;
}
}
// vertical auto scroll function
function autoscrollY(call){
var top; // top style
var old = 0; // define old scroll position
// define current scroll position
var scrollPosition = getScrollPosition('Y');
// mouse button should be pressed and
// if moved element is over page top or page bottom
// scroll_height - window_height returns maximum vertical scroll position
if (mouseButton == 1 && ((edgeY < 0 && scrollPosition > 0) || (edgeY > 0 && scrollPosition < (scroll_height - window_height)))){
// vertical window scroll
window.scrollBy(0, edgeY);
// set previous scroll position and new after window is scrolled
old = scrollPosition;
scrollPosition = getScrollPosition('Y');
// set top style of the object
top = (isNaN(parseInt(obj.style.top)) ? 0 : parseInt(obj.style.top));
// set style top for the moved element
obj.style.top = (top + scrollPosition - old) + "px";
// move Y point
mouseY -= scrollPosition - old;
// recursive autoscroll call
setTimeout("autoscrollY('recursive')", speed);
}
// autoscroll stopped by moving element out of the page edge
// or element faced maximum position (top or bottom)
else{
// recalculate cell positions if call was function itself (spare CPU if moving object across bound)
if (call == 'recursive') calculate_cells();
// return onscroll event handler and reset auto scroll flag
window.onscroll = calculate_cells;
autoscrollY_flag = 0;
}
}
// function returns scroll position in array (variables scrollX & scrollY) set_scroll_position)
// input parameter is dimension (X or Y)
function getScrollPosition(d){
var scrollX, scrollY; // define scroll position variables
// Netscape compliant
if (typeof(window.pageYOffset) == 'number'){
scrollX = window.pageXOffset;
scrollY = window.pageYOffset;
}
// DOM compliant
else if (document.body && (document.body.scrollLeft || document.body.scrollTop)){
scrollX = document.body.scrollLeft;
scrollY = document.body.scrollTop;
}
// IE6 standards compliant mode
else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)){
scrollX = document.documentElement.scrollLeft;
scrollY = document.documentElement.scrollTop;
}
// needed for IE6 (when vertical scroll bar was on the top)
else scrollX = scrollY = 0;
// return scroll position
if (d == 'X') return scrollX;
else return scrollY
}
//
// other functions
//
// calculate table colums and row offsets (cells dimensions)
function calculate_cells(){
// local variables used in for loops
var i, j;
// open loop for each HTML table inside id=drag (tables variable is initialized in onload event)
for (i=0; i<tables.length; i++){
// define row offsets variable
var row_offset = new Array();
// collect table rows and initialize row offsets array
var tr = tables[i].getElementsByTagName('tr');
// backward loop has better perfomance
for (j=tr.length-1; j>=0; j--) row_offset[j] = box_offset(tr[j]);
// save table informations (table offset and row offsets)
tables[i].offset = box_offset(tables[i]);
tables[i].row_offset = row_offset;
}
}
// function sets current table, row and cell
// please note that variables used in this function (table, cell and row)
// are defined at the beginning of the script (global scope)
function set_tcr(evt){
// define variables for left & right cell offset
var offsetLeft, offsetRight;
// define current cell (needed for some test at the function bottom
var cell_current;
// find table below draggable object
for (table=0; table < tables.length; table++){
// mouse pointer is inside table
if (tables[table].offset[3] < evt.clientX && evt.clientX < tables[table].offset[1] &&
tables[table].offset[0] < evt.clientY && evt.clientY < tables[table].offset[2]){
// row offsets for the selected table (row bounds)
var row_offset = tables[table].row_offset;
// find the current row (loop will stop at the current row; row_offset[row][0] is row top offset)
for (row=0; row<row_offset.length-1 && row_offset[row][0] < evt.clientY; row++)
if (evt.clientY <= row_offset[row][2]) break;
// do loop - needed for rowspaned cells (if there is any)
do{
// set the number of cells in the selected row
var cells = tables[table].rows[row].cells.length - 1;
// find current cell (X mouse position between cell offset left and right)
for (cell = cells; cell >= 0; cell--){
// row left offset + cell left offset
offsetLeft = row_offset[row][3] + tables[table].rows[row].cells[cell].offsetLeft;
// cell right offset is left offset + cell width
offsetRight = offsetLeft + tables[table].rows[row].cells[cell].offsetWidth;
// is mouse pointer is between left and right offset, then cell is found
if (offsetLeft <= evt.clientX && evt.clientX < offsetRight) break;
}
} // mouse pointer is inside table but cell not found (hmm, rowspaned cell - try in upper row)
while (cell == -1 && row-- > 0)
// set current cell
cell_current = tables[table].rows[row].cells[cell];
// if current cell is marked as 'forbid', then return previous location
if (cell_current.className.indexOf(forbid) > -1) {table=table_old; row=row_old; cell=cell_old; break;}
// if single_content == true and current cell has child nodes then test if cell is occupied
if (single_content == true && cell_current.childNodes.length > 0){
// if cell has only one node and that is text node then break - because this is empty cell
if (cell_current.childNodes.length == 1 && cell_current.firstChild.nodeType == 3) break;
// define and set has_content flag to false
var has_content = false;
// open loop for each child node and jump out if 'drag' className found
for (var i=cell_current.childNodes.length-1; i>=0 ; i--){
if (cell_current.childNodes[i].className && cell_current.childNodes[i].className.indexOf('drag') > -1) {has_content = true; break;}
}
// if cell has content and old position exists ...
if (has_content && table_old != null && row_old != null && cell_old != null){
// .. and current position is different then source position then return previous position
if (table_source != table || row_source != row || cell_source != cell) {table=table_old; row=row_old; cell=cell_old; break;}
}
}
// break table loop
break;
}
}
}
// calculate object (box) offset (top, right, bottom, left)
// function returns array of box bounds
// used in calculate_cells and onmousedown event handler
function box_offset(box){
var oLeft = 0 - getScrollPosition('X'); // define offset left (take care of scroll position)
var oTop = 0 - getScrollPosition('Y'); // define offset top (take care od scroll position)
// remember box object
var box_old = box;
// loop to the root element and return box offset (top, right, bottom, left)
do {oLeft += box.offsetLeft; oTop += box.offsetTop} while (box = box.offsetParent);
// return box offset array
// top right, bottom left
return [ oTop, oLeft + box_old.offsetWidth, oTop + box_old.offsetHeight, oLeft ];
}
// clone object
function clone_obj(){
// clone div object and append to the div element (id="obj_new")
var obj_new = obj.cloneNode(true);
document.getElementById('obj_new').appendChild(obj_new);
// offset of the original object
var offset = box_offset(obj);
// offset of the new object (cloned)
var offset_dragged = box_offset(obj_new);
// calculate top and left offset of the new object
obj_new.style.top = (offset[0] - offset_dragged[0]) + "px";
obj_new.style.left = (offset[3] - offset_dragged[3]) + "px";
// set onmouse down event for the new object
obj_new.onmousedown = handler_onmousedown;
// remove clone from the class name of the new object
obj_new.className = obj_new.className.replace('clone', '');
// append 'd' to the innerHTML of the new object 'Clone' -> 'Cloned'
obj_new.innerHTML += 'd';
// set new position because div is appended to div id="obj_new"
mouseX -= parseInt(obj_new.style.left);
mouseY -= parseInt(obj_new.style.top);
// replace reference with new object
obj = obj_new;
}
// delete object
function trash_delete(){
var div_text; // div content (inner text)
var border; // border color (green or blue)
// find the border color of DIV element (t1 - green, t2 - blue, t3 - orange)
if (obj.className.indexOf('t1') > 0) border = 'green';
else if (obj.className.indexOf('t2') > 0) border = 'blue';
else border = 'orange';
// set div text (cross browser)
if (obj.getElementsByTagName('INPUT').length || obj.getElementsByTagName('SELECT').length)
div_text = 'form element';
else
div_text = '"' + (obj.innerText || obj.textContent) + '"';
// ask if user is sure
if (!confirm('Delete '+div_text+' ('+border+') from\n table '+table_source+', row '+row_source+' and column '+cell_source+'?')){
// append removed object to the source table cell
tables[table_source].rows[row_source].cells[cell_source].appendChild(obj);
// and recalculate table cells because undelete can change row dimensions
calculate_cells();
}
}
// function returns true or false if source tag name is form element
function isFormElement(evt){
// declare form element and source tag name
var formElement;
var srcName;
// set source tag name for IE and FF
if (evt.srcElement) srcName = evt.srcElement.tagName;
else srcName = evt.target.tagName;
// set flag (true or false) for form elements
switch(srcName){
case 'INPUT':
case 'SELECT':
case 'OPTION':
formElement = true;
break;
default:
formElement = false;
}
// return formElement flag
return formElement;
}
//
// other, other functions
// if you don't need "show table content" or toggling, than this functions can be left out
//
// function shows how to scan table and display cell content
// (fired on button "Click" click :)
// this function should be customized for your needs
function table_content(id){
// define local variables
var message = ''; // final message
var div_text; // div content (inner text)
var border; // border color (green or blue)
// set reference to the table
var tbl = document.getElementById(id);
// define number of table rows
var tbl_rows = tbl.rows.length;
// iterate through each table row
for (var r=0; r<tbl_rows; r++){
// set the number of cells in the current row
var cells = tbl.rows[r].cells.length
// iterate through each table cell
for (var c=0; c<cells; c++){
// set reference to the table cell
var tbl_cell = tbl.rows[r].cells[c];
// if cells isn't empty and hasn't forbid class
if (tbl_cell.childNodes.length > 0 && tbl_cell.className != forbid){
// cell can contain more then one DIV element
for (var d=0; d<tbl_cell.childNodes.length; d++){
// childNodes should be DIVs, not \n childs
if (tbl_cell.childNodes[d].tagName == 'DIV'){ // and yes, is should be uppercase
// find the border color of DIV element (t1 - green, t2 - blue, t3 - orange)
if (tbl_cell.childNodes[d].className.indexOf('t1') > 0) border = 'green';
else if (tbl_cell.childNodes[d].className.indexOf('t2') > 0) border = 'blue';
else border = 'orange';
// set message line if div contains form elements
if (tbl_cell.childNodes[d].getElementsByTagName('INPUT').length || tbl_cell.childNodes[d].getElementsByTagName('SELECT').length)
div_text = 'form element';
// for other divs that contains only text (cross browser)
else
div_text = '"' + (tbl_cell.childNodes[d].innerText || tbl_cell.childNodes[d].textContent) + '"';
// add line to the message
message += 'row:' + r + ' col:' + c + ' ' + div_text + ' (' + border + ')\n';
}
}
}
}
}
// if table is empty print a nice message
if (message == '') message = 'Table is empty!';
// display message
alert(message);
}
// functions toggles trash_ask defined at the top
function toggle_confirm(chk){
trash_ask = chk.checked;
}
// function toggles single_content defined at the top
function toggle_dropping(chk){
single_content = !chk.checked;
}
| 24,060
| 7,728
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// RUN: %hermes -hermes-parser -dump-ir %s -O0 | %FileCheck %s --match-full-lines
// RUN: %hermes -hermes-parser -dump-ir %s -O
function foo(x, y) {
x = y;
x += y;
x -= y;
x *= y;
x /= y;
x %= y;
//x **= y; Not ES5.
x <<= y;
x >>= y;
x >>>= y;
x &= y;
x ^= y;
x |= y;
x.t = y;
x.t += y;
x.t -= y;
x.t *= y;
x.t /= y;
x.t %= y;
//x.t **= y; Not ES5.
x.t <<= y;
x.t >>= y;
x.t >>>= y;
x.t &= y;
x.t ^= y;
x.t |= y;
return x == y;
return x != y;
return x === y;
// return x !=== y; Not ES5.
return x < y;
return x <= y;
return x > y;
return x >= y;
return x << y;
return x << y;
return x >>> y;
return x + y;
return x - y;
return x * y;
return x / y;
return x % y;
return x | y;
return x ^ y;
return x & y;
return x in y;
return x instanceof y;
}
//CHECK-LABEL:function assignment_test(x, y)
//CHECK-NEXT:frame = [x, y]
//CHECK-NEXT: %BB0:
//CHECK-NEXT: %0 = StoreFrameInst %x, [x]
//CHECK-NEXT: %1 = StoreFrameInst %y, [y]
//CHECK-NEXT: %2 = LoadFrameInst [y]
//CHECK-NEXT: %3 = StoreFrameInst %2, [x]
//CHECK-NEXT: %4 = LoadFrameInst [x]
//CHECK-NEXT: %5 = LoadFrameInst [y]
//CHECK-NEXT: %6 = BinaryOperatorInst '+', %4, %5
//CHECK-NEXT: %7 = StoreFrameInst %6, [x]
//CHECK-NEXT: %8 = ReturnInst undefined : undefined
//CHECK-NEXT:function_end
function assignment_test(x, y) {
x = y;
x += y;
}
//CHECK-LABEL:function member_test(x, y)
//CHECK-NEXT:frame = [x, y]
//CHECK-NEXT: %BB0:
//CHECK-NEXT: %0 = StoreFrameInst %x, [x]
//CHECK-NEXT: %1 = StoreFrameInst %y, [y]
//CHECK-NEXT: %2 = LoadFrameInst [x]
//CHECK-NEXT: %3 = LoadPropertyInst %2, "t" : string
//CHECK-NEXT: %4 = LoadFrameInst [y]
//CHECK-NEXT: %5 = BinaryOperatorInst '+', %3, %4
//CHECK-NEXT: %6 = StorePropertyInst %5, %2, "t" : string
//CHECK-NEXT: %7 = ReturnInst undefined : undefined
//CHECK-NEXT:function_end
function member_test(x, y) {
x.t += y;
}
//CHECK: function binary_ops(x, y)
function binary_ops(x, y) {
//CHECK: %2 = LoadFrameInst [x]
//CHECK: %3 = LoadFrameInst [y]
//CHECK: %4 = BinaryOperatorInst '>>>', %2, %3
//CHECK: %5 = ReturnInst %4
return x >>> y;
}
| 2,530
| 1,106
|
//download.js v3.0, by dandavis; 2008-2014. [CCBY2] see http://danml.com/download.html for tests/usage
// v1 landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
// v2 added named files via a[download], msSaveBlob, IE (10+) support, and window.URL support for larger+faster saves than dataURLs
// v3 added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support
// data can be a string, Blob, File, or dataURL
function download(data, strFileName, strMimeType) {
var self = window, // this script is only for browsers anyway...
u = "application/octet-stream", // this default mime also triggers iframe downloads
m = strMimeType || u,
x = data,
D = document,
a = D.createElement("a"),
z = function(a){return String(a);},
B = self.Blob || self.MozBlob || self.WebKitBlob || z,
BB = self.MSBlobBuilder || self.WebKitBlobBuilder || self.BlobBuilder,
fn = strFileName || "download",
blob,
b,
ua,
fr;
//if(typeof B.bind === 'function' ){ B=B.bind(self); }
if(String(this)==="true"){ //reverse arguments, allowing download.bind(true, "text/xml", "export.xml") to act as a callback
x=[x, m];
m=x[0];
x=x[1];
}
//go ahead and download dataURLs right away
if(String(x).match(/^data\:[\w+\-]+\/[\w+\-]+[,;]/)){
return navigator.msSaveBlob ? // IE10 can't do a[download], only Blobs:
navigator.msSaveBlob(d2b(x), fn) :
saver(x) ; // everyone else can save dataURLs un-processed
}//end if dataURL passed?
try{
blob = x instanceof B ?
x :
new B([x], {type: m}) ;
}catch(y){
if(BB){
b = new BB();
b.append([x]);
blob = b.getBlob(m); // the blob
}
}
function d2b(u) {
var p= u.split(/[:;,]/),
t= p[1],
dec= p[2] == "base64" ? atob : decodeURIComponent,
bin= dec(p.pop()),
mx= bin.length,
i= 0,
uia= new Uint8Array(mx);
for(i;i<mx;++i) uia[i]= bin.charCodeAt(i);
return new B([uia], {type: t});
}
function saver(url, winMode){
if ('download' in a) { //html5 A[download]
a.href = url;
a.setAttribute("download", fn);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
a.click();
D.body.removeChild(a);
if(winMode===true){setTimeout(function(){ self.URL.revokeObjectURL(a.href);}, 250 );}
}, 66);
return true;
}
//do iframe dataURL download (old ch+FF):
var f = D.createElement("iframe");
D.body.appendChild(f);
if(!winMode){ // force a mime that will download:
url="data:"+url.replace(/^data:([\w\/\-\+]+)/, u);
}
f.src = url;
setTimeout(function(){ D.body.removeChild(f); }, 333);
}//end saver
if (navigator.msSaveBlob) { // IE10+ : (has Blob, but not a[download] or URL)
return navigator.msSaveBlob(blob, fn);
}
if(self.URL){ // simple fast and modern way using Blob and URL:
saver(self.URL.createObjectURL(blob), true);
}else{
// handle non-Blob()+non-URL browsers:
if(typeof blob === "string" || blob.constructor===z ){
try{
return saver( "data:" + m + ";base64," + self.btoa(blob) );
}catch(y){
return saver( "data:" + m + "," + encodeURIComponent(blob) );
}
}
// Blob but not URL:
fr=new FileReader();
fr.onload=function(e){
saver(this.result);
};
fr.readAsDataURL(blob);
}
return true;
} /* end download() */
| 4,006
| 1,322
|
import m from 'mithril';
import postgrest from 'mithril-postgrest';
import h from '../h';
import models from '../models';
import landingSignup from '../c/landing-signup';
import projectRow from '../c/project-row';
import landingQA from '../c/landing-qa';
const Flex = {
controller() {
const stats = m.prop([]),
projects = m.prop([]),
l = m.prop(),
sample3 = _.partial(_.sample, _, 3),
builder = {
customAction: 'http://fazum.citizensupported.org/obrigado-landing-catarse-flex'
},
addDisqus = (el, isInitialized) => {
if (!isInitialized) {
h.discuss('https://citizensupported.org/flex', 'flex_page');
}
},
flexVM = postgrest.filtersVM({
mode: 'eq',
state: 'eq',
recommended: 'eq'
}),
statsLoader = postgrest.loaderWithToken(models.statistic.getRowOptions());
flexVM.mode('flex').state('online').recommended(true);
const projectsLoader = postgrest.loader(models.project.getPageOptions(flexVM.parameters()));
statsLoader.load().then(stats);
projectsLoader.load().then(_.compose(projects, sample3));
return {
addDisqus: addDisqus,
builder: builder,
statsLoader: statsLoader,
stats: stats,
projectsLoader: projectsLoader,
projects: {
loader: projectsLoader,
collection: projects
}
};
},
view(ctrl, args) {
let stats = _.first(ctrl.stats());
return [
m('.w-section.hero-full.hero-zelo', [
m('.w-container.u-text-center', [
m('img.logo-flex-home[src=\'/assets/logo-flex.png\'][width=\'359\']'),
m('.w-row', [
m('.w-col.fontsize-large.u-marginbottom-60.w-col-push-2.w-col-8', 'Let`s build a new mode of crowdfunding! Register your email and learn how to register your project on flex!')
]),
m('.w-row', [
m('.w-col.w-col-2'),
m.component(landingSignup, {
builder: ctrl.builder
}),
m('.w-col.w-col-2')
])
])
]), [
m('.section', [
m('.w-container', [
m('.fontsize-largest.u-margintop-40.u-text-center', 'Pra quem será?'), m('.fontsize-base.u-text-center.u-marginbottom-60', 'We will start the testing phase with specific project categories'), m('div', [
m('.w-row.u-marginbottom-60', [
m('.w-col.w-col-6', [
m('.u-text-center.u-marginbottom-20', [
m('img[src=\'https://daks2k3a4ib2z.cloudfront.net/54b440b85608e3f4389db387/560e393a01b66e250aca67cb_icon-zelo-com.png\'][width=\'210\']'), m('.fontsize-largest.lineheight-loose', 'Causes')
]), m('p.fontsize-base', 'Flexibility for causes of impact! We will be open to campaigns of organizations or individuals for the collection of resources for personal causes, assistance projects, health, humanitarian aid, animal protection, socio-environmental entrepreneurship, activism or anything that unites people to do good.')
]), m('.w-col.w-col-6', [
m('.u-text-center.u-marginbottom-20', [
m('img[src=\'https://daks2k3a4ib2z.cloudfront.net/54b440b85608e3f4389db387/560e3929a0daea230a5f12cd_icon-zelo-pessoal.png\'][width=\'210\']'), m('.fontsize-largest.lineheight-loose', 'Kitties')
]), m('p.fontsize-base', 'Simple campaigns that need the flexibility to raise money with people close to you. We will be open to a variety of personal campaigns that can range from covering study costs to helping those in need of medical treatment. To collect the money to make that party buy presents for someone with the help of the galley.')
])
])
])
])
]), m('.w-section.section.bg-greenlime.fontcolor-negative', [
m('.w-container', [
m('.fontsize-largest.u-margintop-40.u-marginbottom-60.u-text-center', 'Como funcionará?'), m('.w-row.u-marginbottom-40', [
m('.w-col.w-col-6', [
m('.u-text-center', [
m('img[src=\'https://daks2k3a4ib2z.cloudfront.net/54b440b85608e3f4389db387/560e39c578b284493e2a428a_zelo-money.png\'][width=\'180\']')
]), m('.fontsize-large.u-marginbottom-10.u-text-center.fontweight-semibold', 'Stay with how much to collect'), m('p.u-text-center.fontsize-base', 'Flex is to drive campaigns where all money is welcome! You get everything you can raise.')
]), m('.w-col.w-col-6', [
m('.u-text-center', [
m('img[src=\'https://daks2k3a4ib2z.cloudfront.net/54b440b85608e3f4389db387/560e39d37c013d4a3ee687d2_icon-reward.png\'][width=\'180\']')
]), m('.fontsize-large.u-marginbottom-10.u-text-center.fontweight-semibold', 'No rewards required'), m('p.u-text-center.fontsize-base', 'No flex offering rewards is optional. You choose whether to offer them makes sense for your project and campaign.')
])
]), m('.w-row.u-marginbottom-40', [
m('.w-col.w-col-6', [
m('.u-text-center', [
m('img[src=\'https://daks2k3a4ib2z.cloudfront.net/54b440b85608e3f4389db387/560e39fb01b66e250aca67e3_icon-curad.png\'][width=\'180\']')
]), m('.fontsize-large.u-marginbottom-10.u-text-center.fontweight-semibold', 'You publish your project yourself'), m('p.u-text-center.fontsize-base', 'All projects enrolled in the flex come on the air. Agility and ease for you to capture resources through the internet.')
]), m('.w-col.w-col-6', [
m('.u-text-center', [
m('img[src=\'https://daks2k3a4ib2z.cloudfront.net/54b440b85608e3f4389db387/560e39e77c013d4a3ee687d4_icon-time.png\'][width=\'180\']')
]), m('.fontsize-large.u-marginbottom-10.u-text-center.fontweight-semibold', 'End the campaign anytime'), m('p.u-text-center.fontsize-base', 'There is no capitation time limit. You choose when to close your campaign and receive the amounts collected.')
])
])
])
]),
m('.w-section.section', [
m('.w-container', [
m('.w-editable.fontsize-larger.u-margintop-40.u-margin-bottom-40.u-text-center', 'Meet some of the first flex projects'),
ctrl.projectsLoader() ? h.loader() : m.component(projectRow, {collection: ctrl.projects, ref: 'ctrse_flex', wrapper: '.w-row.u-margintop-40'})
])
]),
m('.w-section.divider'),
m('.w-section.section', [
m('.w-container', [
m('.fontsize-larger.u-text-center.u-marginbottom-60.u-margintop-40', 'Doubts'), m('.w-row.u-marginbottom-60', [
m('.w-col.w-col-6', [
m.component(landingQA, {
question: 'What are the flexible mode fees? ',
answer: 'Like in Citizen Supported, sending a project costs nothing! The fee charged on the Citizen Supported flex service is 13% on the amount collected.'
}),
m.component(landingQA, {
question: 'Where does the money from my project come from?',
answer: 'Family, friends, fans and members of communities that you are part of are your greatest contributors. It is they who will spread their campaign to the people they know, and so the circle of supporters is increasing and your campaign is gaining strength.'
}),
m.component(landingQA, {
question: 'What is the difference between the flexible and the "all or nothing"?',
answer: 'Currently Citizen Supported uses only the "all or nothing" model, where you only get the money if you beat the collection goal within the term of the campaign. The flexible model is different because it allows the director to keep what he has collected, regardless of whether or not he reaches the project goal within the term of the campaign. There will be no time limit for campaigns. Our flexible system will be something new compared to the models that currently exist in the market.'
}),
]), m('.w-col.w-col-6', [
m.component(landingQA, {
question: 'Can I enter projects for flexible mode already?',
answer: 'Yes. Register your email and learn how to register your project on flex!'
}),
m.component(landingQA, {
question: 'Why do you want to do the Citizen Supported Flex?',
answer: 'We believe that the crowdfunding environment still has room for many actions, tests and experiments to really understand what people need. We dream of making collective financing possible for progressive politics. Citizen Supported Flex is another step in this direction.'
}),
m.component(landingQA, {
question: 'When will you launch Citizen Supported Flex?',
answer: 'We still do not know when we will open flex for the general public, but you can register your email on this page and receive special material on how to submit your project.'
})
])
])
])
]),
m('.w-section.section-large.u-text-center.bg-purple', [
m('.w-container.fontcolor-negative', [
m('.fontsize-largest', 'Enter your project!'), m('.fontsize-base.u-marginbottom-60', 'Register your email and learn how to register your project on flex!'), m('.w-row', [
m('.w-col.w-col-2'),
m.component(landingSignup, {
builder: ctrl.builder
}),
m('.w-col.w-col-2')
])
])
]), m('.w-section.section-one-column.bg-catarse-zelo.section-large[style="min-height: 50vh;"]', [
m('.w-container.u-text-center', [
m('.w-editable.u-marginbottom-40.fontsize-larger.lineheight-tight.fontcolor-negative', 'Flex is an experiment and initiative of Citizen Supported, Nepal`s largest crowdfunding platform.'),
m('.w-row.u-text-center', (ctrl.statsLoader()) ? h.loader() : [
m('.w-col.w-col-4', [
m('.fontsize-jumbo.text-success.lineheight-loose', h.formatNumber(stats.total_contributors, 0, 3)), m('p.start-stats.fontsize-base.fontcolor-negative', 'People have already supported at least 01 project in Citizen Supported')
]),
m('.w-col.w-col-4', [
m('.fontsize-jumbo.text-success.lineheight-loose', h.formatNumber(stats.total_projects_success, 0, 3)), m('p.start-stats.fontsize-base.fontcolor-negative', 'Projects have already been funded in Citizen Supported')
]),
m('.w-col.w-col-4', [
m('.fontsize-jumbo.text-success.lineheight-loose', stats.total_contributed.toString().slice(0, 2) + ' millions'), m('p.start-stats.fontsize-base.fontcolor-negative', 'They were invested in ideas published in Citizen Supported')
])
])
])
]),
m('.w-section.section.bg-blue-one.fontcolor-negative', [
m('.w-container', [
m('.fontsize-large.u-text-center.u-marginbottom-20', 'Recommend the Citizen Supported flex for friends! '),
m('.w-row', [
m('.w-col.w-col-2'),
m('.w-col.w-col-8', [
m('.w-row', [
m('.w-col.w-col-6.w-col-small-6.w-col-tiny-6.w-sub-col-middle', [
m('div', [
m('img.icon-share-mobile[src=\'https://daks2k3a4ib2z.cloudfront.net/54b440b85608e3f4389db387/53a3f66e05eb6144171d8edb_facebook-xxl.png\']'),
m('a.w-button.btn.btn-large.btn-fb[href="http://www.facebook.com/sharer/sharer.php?u=https://www.citizensupported.org/flex?ref=facebook&title=' + encodeURIComponent('Meet the new Citizen Supported Flex!') + '"][target="_blank"]', 'To share')
])
]),
m('.w-col.w-col-6.w-col-small-6.w-col-tiny-6', [
m('div', [
m('img.icon-share-mobile[src=\'https://daks2k3a4ib2z.cloudfront.net/54b440b85608e3f4389db387/53a3f65105eb6144171d8eda_twitter-256.png\']'),
m('a.w-button.btn.btn-large.btn-tweet[href="https://twitter.com/intent/tweet?text=' + encodeURIComponent('Let`s build a new mode of crowdfunding for Citizen Supported! Join us, sign up for your email!') + 'https://www.citizensupported.org/flex?ref=twitter"][target="_blank"]', 'To tweet')
])
])
])
]),
m('.w-col.w-col-2')
])
])
]), m('.w-section.section-large.bg-greenlime', [
m('.w-container', [
m('#participe-do-debate.u-text-center', {config: h.toAnchor()}, [
m('h1.fontsize-largest.fontcolor-negative','Build Flex with us'), m('.fontsize-base.u-marginbottom-60.fontcolor-negative', 'Start a conversation, ask, comment, critique and make suggestions!')
]),
m('#disqus_thread.card.u-radius[style="min-height: 50vh;"]', {
config: ctrl.addDisqus
})
])
])
]
];
}
};
export default Flex;
| 15,748
| 4,510
|
const github = require('@actions/github')
const fs = require('fs/promises')
const isPlainObject = require('lodash/isPlainObject')
const orderBy = require('lodash/orderBy')
const find = require('lodash/find')
const slice = require('lodash/slice')
const round = require('lodash/round')
const { ChartJSNodeCanvas } = require('chartjs-node-canvas')
const chartJSNodeCanvas = new ChartJSNodeCanvas({ type: 'svg', width: 850, height: 300, backgroundColour: '#FFFFFF' })
async function main () {
const token = 'YOUR_TOKEN_HERE'
const gh = github.getOctokit(token)
const owner = 'ietf-tools'
const repo = 'datatracker'
const repoCommon = 'common'
// -> Fetch existing releases
const releases = []
let hasMoreReleases = false
let releasesCurPage = 0
do {
hasMoreReleases = false
releasesCurPage++
const resp = await gh.request('GET /repos/{owner}/{repo}/releases', {
owner,
repo,
page: releasesCurPage,
per_page: 100
})
if (resp?.data?.length > 0) {
console.info(`Fetching existing releases... ${(releasesCurPage - 1) * 100}`)
hasMoreReleases = true
releases.push(...resp.data)
}
} while (hasMoreReleases)
console.info(`Found ${releases.length} existing releases.`)
// -> Load full coverage file
console.info('Loading coverage results file...')
const rawCoverage = await fs.readFile('data/release-coverage.json', 'utf8')
const coverage = JSON.parse(rawCoverage)
// -> Parse and reorder results
const versions = []
for (const [key, value] of Object.entries(coverage)) {
if (isPlainObject(value)) {
versions.push({
tag: key,
time: value?.time,
stats: {
code: value?.code?.coverage || 0,
template: value?.template?.coverage || 0,
url: value?.url?.coverage || 0
}
})
}
}
const oVersions = orderBy(versions, ['time', 'tag'], ['desc', 'desc'])
const roVersions = orderBy(versions, ['time', 'tag'], ['asc', 'asc'])
// -> Fetch list of existing chart files in common repo
console.info('Fetching list of existing chart files from common repo...')
const chartsDirListing = []
const respDir = await gh.request('GET /repos/{owner}/{repo}/contents/{path}', {
owner,
repo: repoCommon,
path: 'assets/graphs/datatracker'
})
if (respDir?.data?.length > 0) {
chartsDirListing.push(...respDir.data)
}
// -> Upload release coverage
for (const [idx, value] of oVersions.entries()) {
const rel = find(releases, ['tag_name', value.tag])
if (!rel) { continue }
// -> Full Coverage File
if (rel?.assets?.some(a => a.name === 'coverage.json')) {
console.info(`Coverage file already exists for ${value.tag}, skipping...`)
} else {
console.info(`Building coverage object for ${value.tag}...`)
const covData = Buffer.from(JSON.stringify({
[value.tag]: coverage[value.tag],
version: value.tag
}), 'utf8')
console.info(`Uploading coverage file for ${value.tag}...`)
await gh.rest.repos.uploadReleaseAsset({
data: covData,
owner,
repo,
release_id: rel.id,
name: 'coverage.json',
headers: {
'Content-Type': 'application/json'
}
})
}
// -> Historical Coverage File
if (rel?.assets?.some(a => a.name === 'historical-coverage.json')) {
console.info(`Historical Coverage file already exists for ${value.tag}, skipping...`)
} else {
console.info(`Building historical coverage object for ${value.tag}...`)
const final = {}
for (const obj of slice(oVersions, idx)) {
final[obj.tag] = obj.stats
}
const covData = Buffer.from(JSON.stringify(final), 'utf8')
console.info(`Uploading historical coverage file for ${value.tag}...`)
await gh.rest.repos.uploadReleaseAsset({
data: covData,
owner,
repo,
release_id: rel.id,
name: 'historical-coverage.json',
headers: {
'Content-Type': 'application/json'
}
})
}
// -> Coverage Chart
if (chartsDirListing.some(c => c.name === `${rel.id}.svg`)) {
console.info(`Chart SVG already exists for ${rel.name}, skipping...`)
} else {
console.info(`Generating chart SVG for ${rel.name}...`)
const labels = []
const datasetCode = []
const datasetTemplate = []
const datasetUrl = []
for (const obj of slice(roVersions, 0, roVersions.length - idx)) {
labels.push(obj.tag)
datasetCode.push(round(obj.stats.code * 100, 2))
datasetTemplate.push(round(obj.stats.template * 100, 2))
datasetUrl.push(round(obj.stats.url * 100, 2))
}
const outputStream = chartJSNodeCanvas.renderToBufferSync({
type: 'line',
options: {
borderColor: '#CCC',
layout: {
padding: 20
},
plugins: {
legend: {
position: 'bottom',
labels: {
font: {
size: 11
}
}
}
},
scales: {
x: {
ticks: {
font: {
size: 10
}
}
},
y: {
ticks: {
callback: (value) => {
return `${value}%`
},
font: {
size: 10
}
}
}
}
},
data: {
labels,
datasets: [
{
label: 'Code',
data: datasetCode,
borderWidth: 2,
borderColor: '#E53935',
backgroundColor: '#C6282833',
fill: false,
cubicInterpolationMode: 'monotone',
tension: 0.4,
pointRadius: 0
},
{
label: 'Templates',
data: datasetTemplate,
borderWidth: 2,
borderColor: '#039BE5',
backgroundColor: '#0277BD33',
fill: false,
cubicInterpolationMode: 'monotone',
tension: 0.4,
pointRadius: 0
},
{
label: 'URLs',
data: datasetUrl,
borderWidth: 2,
borderColor: '#7CB342',
backgroundColor: '#558B2F33',
fill: false,
cubicInterpolationMode: 'monotone',
tension: 0.4,
pointRadius: 0
}
]
}
}, 'image/svg+xml')
const svg = Buffer.from(outputStream).toString('base64')
console.info(`Uploading chart SVG for ${rel.name}...`)
await gh.rest.repos.createOrUpdateFileContents({
owner,
repo: repoCommon,
path: `assets/graphs/datatracker/${rel.id}.svg`,
message: `chore: update datatracker release chart for release ${rel.name}`,
content: svg
})
}
if (rel.body.includes(`${rel.id}.svg`)) {
console.info(`Release ${rel.name} body already contains the chart SVG, skipping...`)
} else {
console.info(`Appending chart SVG to release ${rel.name} body...`)
await gh.request('PATCH /repos/{owner}/{repo}/releases/{release_id}', {
owner,
repo,
release_id: rel.id,
body: `${rel.body}\r\n\r\n`
})
}
}
}
main()
| 7,608
| 2,312
|
const path = require('path')
const { createFilePath } = require('gatsby-source-filesystem')
// Setup Import Alias
exports.onCreateWebpackConfig = ({ getConfig, actions }) => {
const output = getConfig().output || {}
actions.setWebpackConfig({
output,
resolve: {
alias: {
components: path.resolve(__dirname, 'src/components'),
utils: path.resolve(__dirname, 'src/utils'),
hooks: path.resolve(__dirname, 'src/hooks'),
},
},
})
}
// Generate a Slug Each Post Data
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const slug = createFilePath({ node, getNode })
createNodeField({ node, name: 'slug', value: slug })
}
}
// Generate Post Page Through Markdown Data
exports.createPages = async ({ actions, graphql, reporter }) => {
const { createPage } = actions
// Get All Markdown File For Paging
const queryAllMarkdownData = await graphql(
`
{
allMarkdownRemark(
sort: {
order: DESC
fields: [frontmatter___data, frontmatter___title]
}
) {
edges {
node {
fields {
slug
}
}
}
}
}
`,
)
// Handling GraphQL Query Error
if (queryAllMarkdownData.errors) {
reporter.panicOnBuild(`Error while running query`)
return
}
// createPage({
// path: '/using-dsg',
// component: require.resolve('./src/templates/using-dsg.js'),
// context: {},
// defer: true,
// })
}
| 1,632
| 495
|
parse_and_compile_and_run(10, 5, 2,
"function f(x) { \
x + 1; \
} \
f(3); ");
// Line 915: Error: "reached oom"
| 177
| 69
|
(global["webpackJsonp"] = global["webpackJsonp"] || []).push([["pages/component/form/form"],{
/***/ "../../../uniPro/main.js?{\"page\":\"pages%2Fcomponent%2Fform%2Fform\"}":
/*!********************************************************************!*\
!*** D:/uniPro/main.js?{"page":"pages%2Fcomponent%2Fform%2Fform"} ***!
\********************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
__webpack_require__(/*! uni-pages */ "../../../uniPro/pages.json");
var _mpvuePageFactory = _interopRequireDefault(__webpack_require__(/*! mpvue-page-factory */ "./node_modules/@dcloudio/vue-cli-plugin-uni/packages/mpvue-page-factory/index.js"));
var _form = _interopRequireDefault(__webpack_require__(/*! ./pages/component/form/form.vue */ "../../../uniPro/pages/component/form/form.vue"));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
Page((0, _mpvuePageFactory.default)(_form.default));
/***/ }),
/***/ "../../../uniPro/pages/component/form/form.vue":
/*!***********************************************!*\
!*** D:/uniPro/pages/component/form/form.vue ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _form_vue_vue_type_template_id_036ad96e___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./form.vue?vue&type=template&id=036ad96e& */ "../../../uniPro/pages/component/form/form.vue?vue&type=template&id=036ad96e&");
/* harmony import */ var _form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./form.vue?vue&type=script&lang=js& */ "../../../uniPro/pages/component/form/form.vue?vue&type=script&lang=js&");
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _form_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./form.vue?vue&type=style&index=0&lang=css& */ "../../../uniPro/pages/component/form/form.vue?vue&type=style&index=0&lang=css&");
/* harmony import */ var _HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../HBuilderX/plugins/uniapp-cli/node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])(
_form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_form_vue_vue_type_template_id_036ad96e___WEBPACK_IMPORTED_MODULE_0__["render"],
_form_vue_vue_type_template_id_036ad96e___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "uniPro/pages/component/form/form.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "../../../uniPro/pages/component/form/form.vue?vue&type=script&lang=js&":
/*!************************************************************************!*\
!*** D:/uniPro/pages/component/form/form.vue?vue&type=script&lang=js& ***!
\************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_18_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../HBuilderX/plugins/uniapp-cli/node_modules/babel-loader/lib!../../../../HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!../../../../HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--18-0!../../../../HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!../../../../HBuilderX/plugins/uniapp-cli/node_modules/vue-loader/lib??vue-loader-options!./form.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/index.js?!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/index.js?!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/vue-loader/lib/index.js?!../../../uniPro/pages/component/form/form.vue?vue&type=script&lang=js&");
/* harmony import */ var _HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_18_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_18_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_18_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_18_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_18_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/***/ "../../../uniPro/pages/component/form/form.vue?vue&type=style&index=0&lang=css&":
/*!********************************************************************************!*\
!*** D:/uniPro/pages/component/form/form.vue?vue&type=style&index=0&lang=css& ***!
\********************************************************************************/
/*! no static exports found */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_1_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_index_js_ref_6_oneOf_1_2_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_stylePostLoader_js_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../HBuilderX/plugins/uniapp-cli/node_modules/mini-css-extract-plugin/dist/loader.js??ref--6-oneOf-1-0!../../../../HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--6-oneOf-1-1!../../../../HBuilderX/plugins/uniapp-cli/node_modules/css-loader??ref--6-oneOf-1-2!../../../../HBuilderX/plugins/uniapp-cli/node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../HBuilderX/plugins/uniapp-cli/node_modules/postcss-loader/src??ref--6-oneOf-1-3!../../../../HBuilderX/plugins/uniapp-cli/node_modules/vue-loader/lib??vue-loader-options!./form.vue?vue&type=style&index=0&lang=css& */ "./node_modules/mini-css-extract-plugin/dist/loader.js?!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/index.js?!./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!../../../uniPro/pages/component/form/form.vue?vue&type=style&index=0&lang=css&");
/* harmony import */ var _HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_1_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_index_js_ref_6_oneOf_1_2_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_stylePostLoader_js_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_1_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_index_js_ref_6_oneOf_1_2_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_stylePostLoader_js_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_1_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_index_js_ref_6_oneOf_1_2_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_stylePostLoader_js_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_1_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_index_js_ref_6_oneOf_1_2_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_stylePostLoader_js_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony default export */ __webpack_exports__["default"] = (_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_1_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_index_js_ref_6_oneOf_1_2_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_stylePostLoader_js_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default.a);
/***/ }),
/***/ "../../../uniPro/pages/component/form/form.vue?vue&type=template&id=036ad96e&":
/*!******************************************************************************!*\
!*** D:/uniPro/pages/component/form/form.vue?vue&type=template&id=036ad96e& ***!
\******************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_17_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_template_id_036ad96e___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../HBuilderX/plugins/uniapp-cli/node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--17-0!../../../../HBuilderX/plugins/uniapp-cli/node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!../../../../HBuilderX/plugins/uniapp-cli/node_modules/vue-loader/lib??vue-loader-options!./form.vue?vue&type=template&id=036ad96e& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/index.js?!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/vue-loader/lib/index.js?!../../../uniPro/pages/component/form/form.vue?vue&type=template&id=036ad96e&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_17_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_template_id_036ad96e___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_17_0_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_HBuilderX_plugins_uniapp_cli_node_modules_vue_loader_lib_index_js_vue_loader_options_form_vue_vue_type_template_id_036ad96e___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ }),
/***/ "./node_modules/babel-loader/lib/index.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/index.js?!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/index.js?!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/vue-loader/lib/index.js?!../../../uniPro/pages/component/form/form.vue?vue&type=script&lang=js&":
/*!***********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--18-0!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/vue-loader/lib??vue-loader-options!D:/uniPro/pages/component/form/form.vue?vue&type=script&lang=js& ***!
\***********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;var _default =
{
data: function data() {
return {
title: 'form',
pickerHidden: true,
chosen: '' };
},
methods: {
pickerConfirm: function pickerConfirm(e) {
this.pickerHidden = true;
this.chosen = e.target.value;
},
pickerCancel: function pickerCancel(e) {
this.pickerHidden = true;
},
pickerShow: function pickerShow(e) {
this.pickerHidden = false;
},
formSubmit: function formSubmit(e) {
console.log('form发生了submit事件,携带数据为:' + JSON.stringify(e.detail.value));
},
formReset: function formReset(e) {
console.log('清空数据');
this.chosen = '';
} } };exports.default = _default;
/***/ }),
/***/ "./node_modules/mini-css-extract-plugin/dist/loader.js?!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/index.js?!./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!../../../uniPro/pages/component/form/form.vue?vue&type=style&index=0&lang=css&":
/*!********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/mini-css-extract-plugin/dist/loader.js??ref--6-oneOf-1-0!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--6-oneOf-1-1!./node_modules/css-loader??ref--6-oneOf-1-2!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--6-oneOf-1-3!./node_modules/vue-loader/lib??vue-loader-options!D:/uniPro/pages/component/form/form.vue?vue&type=style&index=0&lang=css& ***!
\********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
// extracted by mini-css-extract-plugin
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/index.js?!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/vue-loader/lib/index.js?!../../../uniPro/pages/component/form/form.vue?vue&type=template&id=036ad96e&":
/*!*********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--17-0!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/vue-loader/lib??vue-loader-options!D:/uniPro/pages/component/form/form.vue?vue&type=template&id=036ad96e& ***!
\*********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"view",
[
_c("page-head", { attrs: { title: _vm.title, mpcomid: "39bebf4e-0" } }),
_c(
"view",
{ staticClass: "uni-padding-wrap uni-common-mt" },
[
_c(
"form",
{
attrs: { eventid: "39bebf4e-0" },
on: { submit: _vm.formSubmit, reset: _vm.formReset }
},
[
_c("view", { staticClass: "uni-form-item uni-column" }, [
_c("view", { staticClass: "title" }, [_vm._v("switch")]),
_c("view", [_c("switch", { attrs: { name: "switch" } })])
]),
_c(
"view",
{ staticClass: "uni-form-item uni-column" },
[
_c("view", { staticClass: "title" }, [_vm._v("radio")]),
_c(
"radio-group",
{ attrs: { name: "radio", mpcomid: "39bebf4e-1" } },
[
_c(
"label",
[
_c("radio", { attrs: { value: "radio1" } }),
_vm._v("选项一")
],
1
),
_c(
"label",
[
_c("radio", { attrs: { value: "radio2" } }),
_vm._v("选项二")
],
1
)
],
1
)
],
1
),
_c(
"view",
{ staticClass: "uni-form-item uni-column" },
[
_c("view", { staticClass: "title" }, [_vm._v("checkbox")]),
_c(
"checkbox-group",
{ attrs: { name: "checkbox", mpcomid: "39bebf4e-2" } },
[
_c(
"label",
[
_c("checkbox", { attrs: { value: "checkbox1" } }),
_vm._v("选项一")
],
1
),
_c(
"label",
[
_c("checkbox", { attrs: { value: "checkbox2" } }),
_vm._v("选项二")
],
1
)
],
1
)
],
1
),
_c("view", { staticClass: "uni-form-item uni-column" }, [
_c("view", { staticClass: "title" }, [_vm._v("slider")]),
_c("slider", {
attrs: { value: "50", name: "slider", "show-value": "" }
})
]),
_c("view", { staticClass: "uni-form-item uni-column" }, [
_c("view", { staticClass: "title" }, [_vm._v("input")]),
_c("input", {
staticClass: "uni-input",
attrs: { name: "input", placeholder: "这是一个输入框" }
})
]),
_c(
"view",
{ staticClass: "uni-btn-v" },
[
_c("button", { attrs: { formType: "submit" } }, [
_vm._v("Submit")
]),
_c(
"button",
{ attrs: { type: "default", formType: "reset" } },
[_vm._v("Reset")]
)
],
1
)
]
)
],
1
)
],
1
)
}
var staticRenderFns = []
render._withStripped = true
/***/ })
},[["../../../uniPro/main.js?{\"page\":\"pages%2Fcomponent%2Fform%2Fform\"}","common/runtime","common/vendor"]]]);
//# sourceMappingURL=../../../../.sourcemap/mp-weixin/pages/component/form/form.js.map
| 28,054
| 9,365
|
beforeEach(() => {
jest.resetModules()
})
test('Should start the bot', () => {
const index = require('./index')
const robot = {}
robot.log = jest.fn(() => {})
robot.on = jest.fn(() => {})
index(robot)
expect(robot.log).toBeCalled()
})
test('Should set the utils', () => {
jest.mock('./lib/utils', () => {
return {
foo: jest.fn(() => 'foo'),
bar: jest.fn(() => 'bar')
}
})
const index = require('./index')
const robot = {}
robot.log = jest.fn(() => {})
robot.on = jest.fn(() => {})
index(robot)
expect(robot.utils).toHaveProperty('foo')
expect(robot.utils).toHaveProperty('bar')
})
test('Should Load the webhooks', () => {
jest.mock('./lib/webhooks', () => {
return {
foo: jest.fn(() => 'foo'),
bar: jest.fn(() => 'bar'),
test: jest.fn(() => 'test')
}
})
const index = require('./index')
const robot = {}
robot.log = jest.fn(() => {})
robot.on = jest.fn(() => {})
index(robot)
expect(robot.on).toHaveBeenCalledTimes(3)
expect(robot.on.mock.calls[0][0]).toEqual('foo')
expect(robot.on.mock.calls[1][0]).toEqual('bar')
expect(robot.on.mock.calls[2][0]).toEqual('test')
})
| 1,177
| 456
|
import React from 'react'
import SamplePreview from './sample-preview.js'
import useArticle from '../hooks/useArticle';
export default () => {
const { articles } = useArticle();
return (
<ul className="article-list">
{articles.map((node, i) => {
return (
<li key={i}>
<SamplePreview article={node} />
</li>
)
})}
</ul>
)
}
| 402
| 130
|
const expressModule = require('@luongthanhluu/express-mongoose-api-generator');
class Controller extends expressModule.Controller {
constructor(name, model) {
super(name, model);
}
//overide
getById() {
return async (req, res, next) => {
console.log("run overdie")
if(!req.acceptFields) req.acceptFields = [];
const id = req.params.id;
const acceptFields = {};
req.acceptFields.forEach(field => {
acceptFields[field] = 1;
});
const result = await req.service.findOne({ _id: id }, acceptFields).catch((err) => {
res.status(req.resultConstructor.hardCodeResult || req.resultConstructor.statusCodeError).send({
code: req.resultConstructor.statusCodeError,
message: err
})
});
if(result) {
res.status(req.resultConstructor.hardCodeResult || req.resultConstructor.statusCodeSuccess).send({
code: req.resultConstructor.statusCodeSuccess,
[req.resultConstructor.dataFieldName]: {
a: 1
}
});
}
}
}
}
module.exports = Controller;
| 1,306
| 326
|
/* eslint-env mocha */
'use strict'
const { Buffer } = require('buffer')
const { nanoid } = require('nanoid')
const { getDescribe, getIt, expect } = require('../utils/mocha')
const testTimeout = require('../utils/test-timeout')
const CID = require('cids')
/** @typedef { import("ipfsd-ctl/src/factory") } Factory */
/**
* @param {Factory} common
* @param {Object} options
*/
module.exports = (common, options) => {
const describe = getDescribe(options)
const it = getIt(options)
describe('.object.data', function () {
this.timeout(80 * 1000)
let ipfs
before(async () => {
ipfs = (await common.spawn()).api
})
after(() => common.clean())
it('should respect timeout option when getting the data from an object', () => {
return testTimeout(() => ipfs.object.data(new CID('Qmd7qZS4T7xXtsNFdRoK1trfMs5zU94EpokQ9WFtxdPxsZ'), {
timeout: 1
}))
})
it('should get data by multihash', async () => {
const testObj = {
Data: Buffer.from(nanoid()),
Links: []
}
const nodeCid = await ipfs.object.put(testObj)
const data = await ipfs.object.data(nodeCid)
expect(testObj.Data).to.deep.equal(data)
})
it('should get data by base58 encoded multihash string', async () => {
const testObj = {
Data: Buffer.from(nanoid()),
Links: []
}
const nodeCid = await ipfs.object.put(testObj)
const data = await ipfs.object.data(nodeCid.toV0().toString(), { enc: 'base58' })
expect(testObj.Data).to.eql(data)
})
it('returns error for request without argument', () => {
return expect(ipfs.object.data(null)).to.eventually.be.rejected.and.be.an.instanceOf(Error)
})
it('returns error for request with invalid argument', () => {
return expect(ipfs.object.data('invalid', { enc: 'base58' })).to.eventually.be.rejected.and.be.an.instanceOf(Error)
})
})
}
| 1,933
| 665
|
/** *******************************************************
* *
* *
* LEAVE STATION *
* By Ryker *
* *
* *
******************************************************** */
import * as onlineManager from '../managers/onlineUserManager';
export default async (socket, userId) => {
onlineManager.leaveAllStation(socket, userId);
};
| 642
| 114
|
import React, { useState, useEffect } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../Csscomponents/Findhelp.css';
import db from '../firebase';
import '../Csscomponents/Table.css';
const Findhelp = () => {
// fetch data from firebase start
const [helpOther, setHelpOther] = useState([]);
useEffect(() => {
db.collection('HelpOther').onSnapshot((snapshot) => {
setHelpOther(snapshot.docs.map(doc=>doc.data()))
})
}, [])
// fetch data from firebase end
return (
<>
<div className="container">
<h3>Find Who Can Help You?</h3>
<table class="table table-bordered styled-table">
<thead>
<tr>
<th>District ID</th>
<th>Name</th>
<th>Number</th>
<th>Email</th>
<th>Position</th>
<th>Service Area</th>
<th>How help you other?</th>
</tr>
</thead>
<tbody>
{helpOther.map((helppeople)=>(
<tr>
<td>{helppeople.districtid}</td>
<td>{helppeople.name}</td>
<td>{helppeople.phone}</td>
<td>{helppeople.email}</td>
<td>{helppeople.position}</td>
<td>{helppeople.area}</td>
<td>{helppeople.howhelp}</td>
</tr>
))
}
</tbody>
</table>
</div>
</>
)
}
export default Findhelp;
| 1,842
| 479
|
define([
'jquery',
'angular',
'angular-route',
'bootstrap',
'ng-breadcrumbs',
'angular-growl',
'directives/index.js',
'services/index.js',
'filters/index.js'
],
function() {
'use strict';
var app = require('angular').module('app',
['ngRoute', 'ng-breadcrumbs', 'angular-growl', 'app.directives', 'app.services', 'app.filters', 'ui.bootstrap']);
app.config(['$controllerProvider', '$compileProvider', '$provide', '$filterProvider', 'growlProvider',
function($controllerProvider, $compileProvider, $provide, $filterProvider, growlProvider) {
// Allow dynamic registration
app.filter = $filterProvider.register;
app.factory = $provide.factory;
app.value = $provide.value;
app.controller = $controllerProvider.register;
app.directive = $compileProvider.directive;
// configure growl
growlProvider.globalTimeToLive(10000);
}
]);
return app;
});
| 989
| 307
|
/**
* 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
*/
'use strict';
const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000;
const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000;
const REPORT_USER_STATS_INTERVAL = 10 * 60 * 1000;
const CRASH_REPORT_THROTTLE = 60 * 60 * 1000;
const fs = require('fs');
const path = require('path');
let Rooms = module.exports = getRoom;
Rooms.rooms = new Map();
Rooms.aliases = new Map();
/*********************************************************
* the Room object.
*********************************************************/
class Room {
constructor(roomid, title) {
this.id = roomid;
this.title = (title || roomid);
this.reportJoins = Config.reportjoins;
this.users = Object.create(null);
this.log = [];
this.muteQueue = [];
this.muteTimer = null;
this.type = 'chat';
this.lastUpdate = 0;
this.userCount = 0;
}
send(message, errorArgument) {
if (errorArgument) throw new Error("Use Room#sendUser");
if (this.id !== 'lobby') message = '>' + this.id + '\n' + message;
if (this.userCount) Sockets.channelBroadcast(this.id, message);
}
sendAuth(message) {
for (let i in this.users) {
let user = this.users[i];
if (user.connected && user.can('receiveauthmessages', null, this)) {
user.sendTo(this, message);
}
}
}
sendUser(user, message) {
user.sendTo(this, message);
}
add(message) {
if (typeof message !== 'string') throw new Error("Deprecated message type");
if (message.startsWith('|uhtmlchange|')) return this.uhtmlchange(message);
this.logEntry(message);
if (this.logTimes && message.substr(0, 3) === '|c|') {
message = '|c:|' + (~~(Date.now() / 1000)) + '|' + message.substr(3);
}
this.log.push(message);
return this;
}
uhtmlchange(message) {
let thirdPipe = message.indexOf('|', 13);
let originalStart = '|uhtml|' + message.slice(13, thirdPipe + 1);
for (let i = 0; i < this.log.length; i++) {
if (this.log[i].startsWith(originalStart)) {
this.log[i] = originalStart + message.slice(thirdPipe + 1);
break;
}
}
this.send(message);
return this;
}
logEntry() {}
addRaw(message) {
return this.add('|raw|' + message);
}
addLogMessage(user, text) {
return this.add('|c|' + user.getIdentity(this) + '|/log ' + text).update();
}
getLogSlice(amount) {
let log = this.log.slice(amount);
log.unshift('|:|' + (~~(Date.now() / 1000)));
return log;
}
toString() {
return this.id;
}
//mute handling
runMuteTimer(forceReschedule) {
if (forceReschedule && this.muteTimer) {
clearTimeout(this.muteTimer);
this.muteTimer = null;
}
if (this.muteTimer || this.muteQueue.length === 0) return;
let timeUntilExpire = this.muteQueue[0].time - Date.now();
if (timeUntilExpire <= 1000) { // one second of leeway
this.unmute(this.muteQueue[0].userid, "Your mute in '" + this.title + "' has expired.");
//runMuteTimer() is called again in unmute() so this function instance should be closed
return;
}
this.muteTimer = setTimeout(() => {
this.muteTimer = null;
this.runMuteTimer(true);
}, timeUntilExpire);
}
isMuted(user) {
if (!user) return;
if (this.muteQueue) {
for (let i = 0; i < this.muteQueue.length; i++) {
let entry = this.muteQueue[i];
if (user.userid === entry.userid ||
user.guestNum === entry.guestNum ||
(user.autoconfirmed && user.autoconfirmed === entry.autoconfirmed)) {
return entry.userid;
}
}
}
}
getMuteTime(user) {
let userid = this.isMuted(user);
if (!userid) return;
for (let i = 0; i < this.muteQueue.length; i++) {
if (userid === this.muteQueue[i].userid) {
return this.muteQueue[i].time - Date.now();
}
}
}
getAuth(user) {
if (this.auth) {
if (user.userid in this.auth) {
return this.auth[user.userid];
}
if (this.tour && this.tour.room) {
return this.tour.room.getAuth(user);
}
if (this.isPrivate === true) {
return ' ';
}
}
return user.group;
}
checkModjoin(user) {
if (this.staffRoom && !user.isStaff && (!this.auth || (this.auth[user.userid] || ' ') === ' ')) return false;
if (user.userid in this.users) return true;
if (!this.modjoin) return true;
const userGroup = user.can('makeroom') ? user.group : this.getAuth(user);
let modjoinGroup = this.modjoin !== true ? this.modjoin : this.modchat;
if (!modjoinGroup) return true;
if (modjoinGroup === 'trusted') {
if (user.trusted) return true;
modjoinGroup = Config.groupsranking[1];
}
if (modjoinGroup === 'autoconfirmed') {
if (user.autoconfirmed) return true;
modjoinGroup = Config.groupsranking[1];
}
if (!(userGroup in Config.groups)) return false;
if (!(modjoinGroup in Config.groups)) throw new Error(`Invalid modjoin setting in ${this.id}: ${modjoinGroup}`);
return Config.groups[userGroup].rank >= Config.groups[modjoinGroup].rank;
}
mute(user, setTime) {
let userid = user.userid;
if (!setTime) setTime = 7 * 60000; // default time: 7 minutes
if (setTime > 90 * 60000) setTime = 90 * 60000; // limit 90 minutes
// If the user is already muted, the existing queue position for them should be removed
if (this.isMuted(user)) this.unmute(userid);
// Place the user in a queue for the unmute timer
for (let i = 0; i <= this.muteQueue.length; i++) {
let time = Date.now() + setTime;
if (i === this.muteQueue.length || time < this.muteQueue[i].time) {
let entry = {
userid: userid,
time: time,
guestNum: user.guestNum,
autoconfirmed: user.autoconfirmed,
};
this.muteQueue.splice(i, 0, entry);
// The timer needs to be switched to the new entry if it is to be unmuted
// before the entry the timer is currently running for
if (i === 0 && this.muteTimer) {
clearTimeout(this.muteTimer);
this.muteTimer = null;
}
break;
}
}
this.runMuteTimer();
user.updateIdentity(this.id);
if (!(this.isPrivate === true || this.isPersonal || this.battle)) Punishments.monitorRoomPunishments(user);
return userid;
}
unmute(userid, notifyText) {
let successUserid = false;
let user = Users.get(userid);
if (!user) {
// If the user is not found, construct a dummy user object for them.
user = {
userid: userid,
autoconfirmed: userid,
};
}
for (let i = 0; i < this.muteQueue.length; i++) {
let entry = this.muteQueue[i];
if (entry.userid === user.userid ||
entry.guestNum === user.guestNum ||
(user.autoconfirmed && entry.autoconfirmed === user.autoconfirmed)) {
if (i === 0) {
this.muteQueue.splice(0, 1);
this.runMuteTimer(true);
} else {
this.muteQueue.splice(i, 1);
}
successUserid = entry.userid;
break;
}
}
if (successUserid && user.userid in this.users) {
user.updateIdentity(this.id);
if (notifyText) user.popup(notifyText);
}
return successUserid;
}
modlog(text) {
if (!this.modlogStream) return;
this.modlogStream.write('[' + (new Date().toJSON()) + '] (' + this.id + ') ' + text + '\n');
}
sendModCommand(data) {
for (let i in this.users) {
let user = this.users[i];
// hardcoded for performance reasons (this is an inner loop)
if (user.isStaff || (this.auth && (this.auth[user.userid] || '+') !== '+')) {
user.sendTo(this, data);
}
}
}
}
class GlobalRoom {
constructor(roomid) {
this.id = roomid;
this.type = 'global';
// init battle rooms
this.battleCount = 0;
this.chatRoomData = [];
try {
this.chatRoomData = require('./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 (let 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;
}
let id = toId(this.chatRoomData[i].title);
if (!Config.quietconsole) console.log("NEW CHATROOM: " + id);
let room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]);
if (room.aliases) {
for (let a = 0; a < room.aliases.length; a++) {
Rooms.aliases.set(room.aliases[a], id);
}
}
this.chatRooms.push(room);
if (room.autojoin) this.autojoin.push(id);
if (room.staffAutojoin) this.staffAutojoin.push(id);
}
Rooms.lobby = Rooms.rooms.get('lobby');
// init battle room logging
if (Config.logladderip) {
this.ladderIpLog = fs.createWriteStream('logs/ladderip/ladderip.txt', {encoding: 'utf8', flags: 'a'});
} else {
// Prevent there from being two possible hidden classes an instance
// of GlobalRoom can have.
this.ladderIpLog = new (require('stream')).Writable();
}
let lastBattle;
try {
lastBattle = fs.readFileSync('logs/lastbattle.txt', 'utf8');
} catch (e) {}
this.lastBattle = (!lastBattle || isNaN(lastBattle)) ? 0 : +lastBattle;
this.writeChatRoomData = (() => {
let writing = false;
let writePending = false;
return () => {
if (writing) {
writePending = true;
return;
}
writing = true;
let data = JSON.stringify(this.chatRoomData)
.replace(/\{"title"\:/g, '\n{"title":')
.replace(/\]$/, '\n]');
fs.writeFile('config/chatrooms.json.0', data, () => {
data = null;
fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', () => {
writing = false;
if (writePending) {
writePending = false;
setImmediate(() => this.writeChatRoomData());
}
});
});
};
})();
this.writeNumRooms = (() => {
let writing = false;
let lastBattle = -1; // last lastBattle to be written to file
return () => {
if (writing) return;
// batch writing lastbattle.txt for every 10 battles
if (lastBattle >= this.lastBattle) return;
lastBattle = this.lastBattle + 10;
let filename = 'logs/lastbattle.txt';
writing = true;
fs.writeFile(`${filename}.0`, '' + lastBattle, () => {
fs.rename(`${filename}.0`, filename, () => {
writing = false;
lastBattle = null;
filename = null;
if (lastBattle < this.lastBattle) {
setImmediate(() => this.writeNumRooms());
}
});
});
};
})();
// init users
this.users = Object.create(null);
this.userCount = 0; // cache of `size(this.users)`
this.maxUsers = 0;
this.maxUsersDate = 0;
this.reportUserStatsInterval = setInterval(
() => this.reportUserStats(),
REPORT_USER_STATS_INTERVAL
);
// Create writestream for modlog
this.modlogStream = fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_global.txt'), {flags:'a+'});
}
reportUserStats() {
if (this.maxUsersDate) {
LoginServer.request('updateuserstats', {
date: this.maxUsersDate,
users: this.maxUsers,
}, () => {});
this.maxUsersDate = 0;
}
LoginServer.request('updateuserstats', {
date: Date.now(),
users: this.userCount,
}, () => {});
}
get formatListText() {
if (this.formatList) {
return this.formatList;
}
this.formatList = '|formats' + (Ladders.formatsListPrefix || '');
let section = '', prevSection = '';
let curColumn = 1;
for (let i in Tools.data.Formats) {
let format = Tools.data.Formats[i];
if (format.section) section = format.section;
if (format.column) curColumn = format.column;
if (!format.name) continue;
if (!format.challengeShow && !format.searchShow && !format.tournamentShow) continue;
if (section !== prevSection) {
prevSection = section;
this.formatList += '|,' + curColumn + '|' + section;
}
this.formatList += '|' + format.name;
let displayCode = 0;
if (format.team) displayCode |= 1;
if (format.searchShow) displayCode |= 2;
if (format.challengeShow) displayCode |= 4;
if (format.tournamentShow) displayCode |= 8;
this.formatList += ',' + displayCode.toString(16);
}
return this.formatList;
}
getRoomList(filter) {
let rooms = [];
let skipCount = 0;
let [formatFilter, eloFilter] = filter.split(',');
if (this.battleCount > 150 && !formatFilter && !eloFilter) {
skipCount = this.battleCount - 150;
}
Rooms.rooms.forEach(room => {
if (!room || !room.active || room.isPrivate) return;
if (formatFilter && formatFilter !== room.format) return;
if (eloFilter && (!room.rated || room.rated < eloFilter)) return;
if (skipCount && skipCount--) return;
rooms.push(room);
});
let roomTable = {};
for (let i = rooms.length - 1; i >= rooms.length - 100 && i >= 0; i--) {
let room = rooms[i];
let roomData = {};
if (room.active && room.battle) {
if (room.battle.p1) roomData.p1 = room.battle.p1.name;
if (room.battle.p2) roomData.p2 = room.battle.p2.name;
if (room.tour) roomData.minElo = 'tour';
if (room.rated) roomData.minElo = Math.floor(room.rated);
}
if (!roomData.p1 || !roomData.p2) continue;
roomTable[room.id] = roomData;
}
return roomTable;
}
getRooms(user) {
let roomsData = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount};
for (let i = 0; i < this.chatRooms.length; i++) {
let room = this.chatRooms[i];
if (!room) continue;
if (room.isPrivate && !(room.isPrivate === 'voice' && user.group !== ' ')) continue;
(room.isOfficial ? roomsData.official : roomsData.chat).push({
title: room.title,
desc: room.desc,
userCount: room.userCount,
});
}
return roomsData;
}
checkModjoin() {
return true;
}
update() {}
isMuted() {
return false;
}
send(message, user) {
if (user) {
user.sendTo(this, message);
} else if (this.userCount) {
Sockets.channelBroadcast(this.id, message);
}
}
sendAuth(message) {
for (let i in this.users) {
let user = this.users[i];
if (user.connected && user.can('receiveauthmessages', null, this)) {
user.sendTo(this, message);
}
}
}
add(message) {
if (Rooms.lobby) return Rooms.lobby.add(message);
return this;
}
addRaw(message) {
if (Rooms.lobby) return Rooms.lobby.addRaw(message);
return this;
}
addChatRoom(title) {
let id = toId(title);
if (id === 'battles' || id === 'rooms' || id === 'ladder' || id === 'teambuilder' || id === 'home') return false;
if (Rooms.rooms.has(id)) return false;
let chatRoomData = {
title: title,
};
let room = Rooms.createChatRoom(id, title, chatRoomData);
this.chatRoomData.push(chatRoomData);
this.chatRooms.push(room);
this.writeChatRoomData();
return true;
}
prepBattleRoom(format) {
//console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid);
let roomPrefix = `battle-${toId(format)}-`;
let battleNum = this.lastBattle;
let roomid;
do {
roomid = `${roomPrefix}${++battleNum}`;
} while (Rooms.rooms.has(roomid));
this.lastBattle = battleNum;
this.writeNumRooms();
return roomid;
}
onCreateBattleRoom(p1, p2, room, options) {
if (Config.reportbattles) {
let reportRoom = Rooms(Config.reportbattles === true ? 'lobby' : Config.reportbattles);
if (reportRoom) {
reportRoom
.add(`|b|${room.id}|${p1.getIdentity()}|${p2.getIdentity()}`)
.update();
}
}
if (Config.logladderip && options.rated) {
this.ladderIpLog.write(
`${p1.userid}: ${p1.latestIp}\n` +
`${p2.userid}: ${p2.latestIp}\n`
);
}
}
deregisterChatRoom(id) {
id = toId(id);
let 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 (let 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;
}
delistChatRoom(id) {
id = toId(id);
if (!Rooms.rooms.has(id)) return false; // room doesn't exist
for (let i = this.chatRooms.length - 1; i >= 0; i--) {
if (id === this.chatRooms[i].id) {
this.chatRooms.splice(i, 1);
break;
}
}
}
removeChatRoom(id) {
id = toId(id);
let room = Rooms(id);
if (!room) return false; // room doesn't exist
room.destroy();
return true;
}
autojoinRooms(user, connection) {
// we only autojoin regular rooms if the client requests it with /autojoin
// note that this restriction doesn't apply to staffAutojoin
let includesLobby = false;
for (let i = 0; i < this.autojoin.length; i++) {
user.joinRoom(this.autojoin[i], connection);
if (this.autojoin[i] === 'lobby') includesLobby = true;
}
if (!includesLobby && Config.serverid !== 'showdown') user.send(`>lobby\n|deinit`);
}
checkAutojoin(user, connection) {
if (!user.named) return;
for (let i = 0; i < this.staffAutojoin.length; i++) {
let room = Rooms(this.staffAutojoin[i]);
if (!room) {
this.staffAutojoin.splice(i, 1);
i--;
continue;
}
if (room.staffAutojoin === true && user.isStaff ||
typeof room.staffAutojoin === 'string' && room.staffAutojoin.includes(user.group) ||
room.auth && user.userid in room.auth) {
// if staffAutojoin is true: autojoin if isStaff
// if staffAutojoin is String: autojoin if user.group in staffAutojoin
// if staffAutojoin is anything truthy: autojoin if user has any roomauth
user.joinRoom(room.id, connection);
}
}
for (let i = 0; i < user.connections.length; i++) {
connection = user.connections[i];
if (connection.autojoins) {
let autojoins = connection.autojoins.split(',');
for (let j = 0; j < autojoins.length; j++) {
user.tryJoinRoom(autojoins[j], connection);
}
connection.autojoins = '';
}
}
}
onConnect(user, connection) {
let 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
}
onJoin(user, connection) {
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();
}
return user;
}
onRename(user, oldid, joining) {
delete this.users[oldid];
this.users[user.userid] = user;
return user;
}
onUpdateIdentity() {}
onLeave(user) {
if (!user) return; // ...
delete this.users[user.userid];
--this.userCount;
}
modlog(text) {
this.modlogStream.write('[' + (new Date().toJSON()) + '] ' + text + '\n');
}
startLockdown(err, slow) {
if (this.lockdown && err) return;
let devRoom = Rooms('development');
const stack = (err ? Chat.escapeHTML(err.stack).split(`\n`).slice(0, 2).join(`<br />`) : ``);
Rooms.rooms.forEach((curRoom, id) => {
if (id === 'global') return;
if (err) {
if (id === 'staff' || id === 'development' || (!devRoom && id === 'lobby')) {
curRoom.addRaw(`<div class="broadcast-red"><b>The server needs to restart because of a crash:</b> ${stack}<br />Please restart the server.</div>`);
curRoom.addRaw(`<div class="broadcast-red">You will not be able to start new battles until the server restarts.</div>`);
curRoom.update();
} else {
curRoom.addRaw(`<div class="broadcast-red"><b>The server needs restart because of a crash.</b><br />No new battles can be started until the server is done restarting.</div>`).update();
}
} else {
curRoom.addRaw(`<div class="broadcast-red"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>`).update();
}
const game = curRoom.game;
if (!slow && game && game.timer && !game.ended) {
game.timer.start();
if (curRoom.modchat !== '+') {
curRoom.modchat = '+';
curRoom.addRaw(`<div class="broadcast-red"><b>Moderated chat was set to +!</b><br />Only users of rank + and higher can talk.</div>`).update();
}
}
});
this.lockdown = true;
this.lastReportedCrash = Date.now();
}
reportCrash(err) {
if (this.lockdown) return;
const time = Date.now();
if (time - this.lastReportedCrash < CRASH_REPORT_THROTTLE) {
return;
}
this.lastReportedCrash = time;
const stack = (err ? Chat.escapeHTML(err.stack).split(`\n`).slice(0, 2).join(`<br />`) : ``);
const crashMessage = `|html|<div class="broadcast-red"><b>The server has crashed:</b> ${stack}</div>`;
const devRoom = Rooms('development');
if (devRoom) {
devRoom.add(crashMessage).update();
} else {
if (Rooms.lobby) Rooms.lobby.add(crashMessage).update();
const staffRoom = Rooms('staff');
if (staffRoom) staffRoom.add(crashMessage).update();
}
}
}
class BattleRoom extends Room {
constructor(roomid, format, p1, p2, options) {
super(roomid, "" + p1.name + " vs. " + p2.name);
this.modchat = (Config.battlemodchat || false);
this.modjoin = false;
this.slowchat = false;
this.filterStretching = false;
this.filterCaps = false;
this.reportJoins = Config.reportbattlejoins;
this.type = 'battle';
this.resetUser = '';
this.modchatUser = '';
this.expireTimer = null;
this.active = false;
format = '' + (format || '');
this.format = format;
this.auth = Object.create(null);
//console.log("NEW BATTLE");
let formatid = toId(format);
// Sometimes we might allow BattleRooms to have no options
if (!options) {
options = {};
}
let rated;
if (options.rated && Tools.getFormat(formatid).rated !== false) {
rated = options.rated;
} else {
rated = false;
}
if (options.tour) {
this.tour = options.tour;
} else {
this.tour = false;
}
this.p1 = p1 || null;
this.p2 = p2 || null;
this.rated = rated;
this.battle = new Rooms.RoomBattle(this, format, rated);
this.game = this.battle;
this.sideTicksLeft = [21, 21];
if (!rated && !this.tour) this.sideTicksLeft = [28, 28];
this.sideTurnTicks = [0, 0];
this.disconnectTickDiff = [0, 0];
if (Config.forcetimer) this.battle.timer.start();
this.modlogStream = Rooms.battleModlogStream;
}
push(message) {
if (typeof message === 'string') {
this.log.push(message);
} else {
this.log = this.log.concat(message);
}
}
win(winner) {
// Declare variables here in case we need them for non-rated battles logging.
let p1score = 0.5;
let winnerid = toId(winner);
// Check if the battle was rated to update the ladder, return its response, and log the battle.
if (this.rated) {
this.rated = false;
let p1 = this.battle.p1;
let p2 = this.battle.p2;
if (winnerid === p1.userid) {
p1score = 1;
} else if (winnerid === p2.userid) {
p1score = 0;
}
let p1name = p1.name;
let p2name = 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]');
winner = Users.get(winnerid);
if (winner && !winner.registered) {
this.sendUser(winner, '|askreg|' + winner.userid);
}
// update rankings
Ladders(this.battle.format).updateRating(p1name, p2name, p1score, this);
} else if (Config.logchallenges) {
// Log challenges if the challenge logging config is enabled.
if (winnerid === this.p1.userid) {
p1score = 1;
} else if (winnerid === this.p2.userid) {
p1score = 0;
}
this.update();
this.logBattle(p1score);
} else {
this.battle.logData = null;
}
if (Config.autosavereplays) {
let uploader = Users.get(winnerid);
if (uploader && uploader.connections[0]) {
Chat.parse('/savereplay', this, uploader, uploader.connections[0]);
}
}
if (this.tour) {
this.tour.onBattleWin(this, winnerid);
}
this.update();
}
// logNum = 0 : spectator log (no exact HP)
// logNum = 1, 2 : player log (exact HP for that player)
// logNum = 3 : debug log (exact HP for all players)
getLog(logNum) {
let log = [];
for (let i = 0; i < this.log.length; ++i) {
let line = this.log[i];
if (line === '|split') {
log.push(this.log[i + logNum + 1]);
i += 4;
} else {
log.push(line);
}
}
return log;
}
getLogForUser(user) {
if (!(user in this.game.players)) return this.getLog(0);
return this.getLog(this.game.players[user].slotNum + 1);
}
update(excludeUser) {
if (this.log.length <= this.lastUpdate) return;
if (this.userCount) {
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
let hasUsers = false;
for (let i in this.users) { // eslint-disable-line no-unused-vars
hasUsers = true;
break;
}
if (!hasUsers) {
if (this.expireTimer) clearTimeout(this.expireTimer);
this.expireTimer = setTimeout(() => this.tryExpire(), TIMEOUT_EMPTY_DEALLOCATE);
} else {
if (this.expireTimer) clearTimeout(this.expireTimer);
this.expireTimer = setTimeout(() => this.tryExpire(), TIMEOUT_INACTIVE_DEALLOCATE);
}
}
logBattle(p1score, p1rating, p2rating) {
let logData = this.battle.logData;
if (!logData) return;
this.battle.logData = null; // deallocate to save space
logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage)
// delete some redundant data
if (p1rating) {
delete p1rating.formatid;
delete p1rating.username;
delete p1rating.rpsigma;
delete p1rating.sigma;
}
if (p2rating) {
delete p2rating.formatid;
delete p2rating.username;
delete p2rating.rpsigma;
delete p2rating.sigma;
}
logData.p1rating = p1rating;
logData.p2rating = p2rating;
logData.endType = this.battle.endType;
if (!p1rating) logData.ladderError = true;
const date = new Date();
logData.timestamp = '' + date;
logData.id = this.id;
logData.format = this.format;
const logsubfolder = Chat.toTimestamp(date).split(' ')[0];
const logfolder = logsubfolder.split('-', 2).join('-');
let curpath = 'logs/' + logfolder;
fs.mkdir(curpath, '0755', () => {
let tier = this.format.toLowerCase().replace(/[^a-z0-9]+/g, '');
curpath += '/' + tier;
fs.mkdir(curpath, '0755', () => {
curpath += '/' + logsubfolder;
fs.mkdir(curpath, '0755', () => {
fs.writeFile(curpath + '/' + this.id + '.log.json', JSON.stringify(logData), () => {});
});
});
}); // asychronicity
//console.log(JSON.stringify(logData));
}
tryExpire() {
this.expire();
}
getInactiveSide() {
let p1active = this.battle.p1 && this.battle.p1.active;
let p2active = this.battle.p2 && this.battle.p2.active;
if (p1active && this.battle.requests.p1) {
if (!this.battle.requests.p1[2]) p1active = false;
}
if (p2active && this.battle.requests.p2) {
if (!this.battle.requests.p2[2]) p2active = false;
}
if (p1active && !p2active) return 1;
if (p2active && !p1active) return 0;
return -1;
}
sendPlayer(num, message) {
let player = this.getPlayer(num);
if (!player) return false;
player.sendRoom(message);
}
getPlayer(num) {
return this.battle['p' + (num + 1)];
}
requestModchat(user) {
if (user === null) {
this.modchatUser = '';
return;
} else if (user.can('modchat') || !this.modchatUser || this.modchatUser === user.userid) {
this.modchatUser = user.userid;
return;
} else {
return "Only the user who set modchat and global staff can change modchat levels in battle rooms";
}
}
onConnect(user, connection) {
this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n'));
if (this.game && this.game.onConnect) this.game.onConnect(user, connection);
}
onJoin(user, connection) {
if (!user) return false;
if (this.users[user.userid]) return user;
if (user.named) {
this.add((this.reportJoins && !user.locked ? '|j|' : '|J|') + user.name).update();
}
this.users[user.userid] = user;
this.userCount++;
if (this.game && this.game.onJoin) {
this.game.onJoin(user, connection);
}
return user;
}
onRename(user, oldid, joining) {
if (joining) {
this.add((this.reportJoins && !user.locked ? '|j|' : '|J|') + user.name);
}
delete this.users[oldid];
this.users[user.userid] = user;
this.update();
return user;
}
onUpdateIdentity() {}
onLeave(user) {
if (!user) return; // ...
if (!user.named) {
delete this.users[user.userid];
return;
}
delete this.users[user.userid];
this.userCount--;
this.add((this.reportJoins && !user.locked ? '|l|' : '|L|') + user.name);
if (this.game && this.game.onLeave) {
this.game.onLeave(user);
}
this.update();
}
expire() {
this.send('|expire|');
this.destroy();
}
destroy() {
// deallocate ourself
if (this.tour) {
// resolve state of the tournament;
if (!this.battle.ended) this.tour.onBattleWin(this, '');
this.tour = null;
}
// remove references to ourself
for (let i in this.users) {
this.users[i].leaveRoom(this, null, true);
delete this.users[i];
}
this.users = null;
// deallocate children and get rid of references to them
if (this.game) {
this.game.destroy();
}
this.battle = null;
this.game = null;
this.active = false;
if (this.expireTimer) {
clearTimeout(this.expireTimer);
}
this.expireTimer = null;
if (this.muteTimer) {
clearTimeout(this.muteTimer);
}
this.muteTimer = null;
// get rid of some possibly-circular references
Rooms.rooms.delete(this.id);
}
}
class ChatRoom extends Room {
constructor(roomid, title, options) {
super(roomid, title);
if (options) {
Object.assign(this, options);
if (!this.isPersonal) this.chatRoomData = options;
}
this.logTimes = true;
this.logFile = null;
this.logFilename = '';
this.destroyingLog = false;
if (this.auth) Object.setPrototypeOf(this.auth, null);
if (!this.modchat) this.modchat = (Config.chatmodchat || false);
if (!this.modjoin) this.modjoin = false;
if (!this.filterStretching) this.filterStretching = false;
if (!this.filterCaps) this.filterCaps = false;
this.type = 'chat';
if (Config.logchat) {
this.rollLogFile(true);
this.logEntry = function (entry, date) {
const timestamp = Chat.toTimestamp(new Date()).split(' ')[1] + ' ';
entry = entry.replace(/<img[^>]* src="data:image\/png;base64,[^">]+"[^>]*>/g, '');
this.logFile.write(timestamp + entry + '\n');
};
this.logEntry('NEW CHATROOM: ' + this.id);
if (Config.loguserstats) {
this.logUserStatsInterval = setInterval(() => this.logUserStats(), Config.loguserstats);
}
}
if (Config.reportjoinsperiod) {
this.userList = this.getUserList();
this.reportJoinsQueue = [];
}
if (this.isPersonal) {
this.modlogStream = Rooms.groupchatModlogStream;
} else {
this.modlogStream = fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_' + roomid + '.txt'), {flags:'a+'});
}
}
reportRecentJoins() {
delete this.reportJoinsInterval;
if (!this.reportJoinsQueue || this.reportJoinsQueue.length === 0) {
// nothing to report
return;
}
this.userList = this.getUserList();
this.send(this.reportJoinsQueue.join('\n'));
this.reportJoinsQueue.length = 0;
}
rollLogFile(sync) {
let mkdir = sync ? (path, mode, callback) => {
try {
fs.mkdirSync(path, mode);
} catch (e) {} // directory already exists
callback();
} : fs.mkdir;
let date = new Date();
let basepath = 'logs/chat/' + this.id + '/';
mkdir(basepath, '0755', () => {
const dateString = Chat.toTimestamp(date).split(' ')[0];
let path = dateString.split('-', 2).join('-');
mkdir(basepath + path, '0755', () => {
if (this.destroyingLog) return;
path += '/' + dateString + '.txt';
if (path !== this.logFilename) {
this.logFilename = path;
if (this.logFile) this.logFile.destroySoon();
this.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.
let 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
}
let currentTime = date.getTime();
let nextHour = new Date(date.setMinutes(60)).setSeconds(1);
setTimeout(() => this.rollLogFile(), nextHour - currentTime);
});
});
}
destroyLog(initialCallback, finalCallback) {
this.destroyingLog = true;
initialCallback();
if (this.logFile) {
this.logEntry = function () { };
this.logFile.on('close', finalCallback);
this.logFile.destroySoon();
} else {
finalCallback();
}
}
logUserStats() {
let total = 0;
let guests = 0;
let groups = {};
for (let group of Config.groupsranking) {
groups[group] = 0;
}
for (let i in this.users) {
let user = this.users[i];
++total;
if (!user.named) {
++guests;
}
if (this.auth && this.auth[user.userid] && this.auth[user.userid] in groups) {
++groups[this.auth[user.userid]];
} else {
++groups[user.group];
}
}
let entry = '|userstats|total:' + total + '|guests:' + guests;
for (let i in groups) {
entry += '|' + i + ':' + groups[i];
}
this.logEntry(entry);
}
getUserList() {
let buffer = '';
let counter = 0;
for (let i in this.users) {
if (!this.users[i].named) {
continue;
}
counter++;
buffer += ',' + this.users[i].getIdentity(this.id);
}
let msg = '|users|' + counter + buffer;
return msg;
}
reportJoin(type, entry) {
if (this.reportJoins) {
this.add('|' + type + '|' + entry).update();
return;
}
entry = '|' + type.toUpperCase() + '|' + entry;
if (this.reportJoinsQueue) {
if (!this.reportJoinsInterval) {
this.reportJoinsInterval = setTimeout(
() => this.reportRecentJoins(), Config.reportjoinsperiod
);
}
this.reportJoinsQueue.push(entry);
} else {
this.send(entry);
}
this.logEntry(entry);
}
update() {
if (this.log.length <= this.lastUpdate) return;
let entries = this.log.slice(this.lastUpdate);
if (this.reportJoinsQueue && this.reportJoinsQueue.length) {
clearInterval(this.reportJoinsInterval);
delete this.reportJoinsInterval;
Array.prototype.unshift.apply(entries, this.reportJoinsQueue);
this.reportJoinsQueue.length = 0;
this.userList = this.getUserList();
}
let update = entries.join('\n');
if (this.log.length > 100) {
this.log.splice(0, this.log.length - 100);
}
this.lastUpdate = this.log.length;
// Set up expire timer to clean up inactive personal rooms.
if (this.isPersonal) {
if (this.expireTimer) clearTimeout(this.expireTimer);
this.expireTimer = setTimeout(() => this.tryExpire(), TIMEOUT_INACTIVE_DEALLOCATE);
}
this.send(update);
}
tryExpire() {
this.destroy();
}
getIntroMessage(user) {
let message = '';
if (this.introMessage) message += '\n|raw|<div class="infobox infobox-roomintro"><div' + (!this.isOfficial ? ' class="infobox-limited"' : '') + '>' + this.introMessage.replace(/\n/g, '') + '</div>';
if (this.staffMessage && user.can('mute', null, this)) message += (message ? '<br />' : '\n|raw|<div class="infobox">') + '(Staff intro:)<br /><div>' + this.staffMessage.replace(/\n/g, '') + '</div>';
if (this.modchat) {
message += (message ? '<br />' : '\n|raw|<div class="infobox">') + '<div class="broadcast-red">' +
'Must be rank ' + this.modchat + ' or higher to talk right now.' +
'</div>';
}
if (this.slowchat && user.can('mute', null, this)) {
message += (message ? '<br />' : '\n|raw|<div class="infobox">') + '<div class="broadcast-red">' +
'Messages must have at least ' + this.slowchat + ' seconds between them.' +
'</div>';
}
if (message) message += '</div>';
return message;
}
onConnect(user, connection) {
let 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(user));
if (this.poll) this.poll.onConnect(user, connection);
if (this.game && this.game.onConnect) this.game.onConnect(user, connection);
}
onJoin(user, connection) {
if (!user) return false; // ???
if (this.users[user.userid]) return user;
if (user.named) {
this.reportJoin('j', user.getIdentity(this.id));
}
this.users[user.userid] = user;
this.userCount++;
if (this.game && this.game.onJoin) this.game.onJoin(user, connection);
return user;
}
onRename(user, oldid, joining) {
delete this.users[oldid];
this.users[user.userid] = user;
if (joining) {
this.reportJoin('j', user.getIdentity(this.id));
if (this.staffMessage && user.can('mute', null, this)) this.sendUser(user, '|raw|<div class="infobox">(Staff intro:)<br /><div>' + this.staffMessage.replace(/\n/g, '') + '</div></div>');
} else if (!user.named) {
this.reportJoin('l', oldid);
} else {
this.reportJoin('n', user.getIdentity(this.id) + '|' + oldid);
}
if (this.poll && user.userid in this.poll.voters) this.poll.updateFor(user);
return user;
}
/**
* onRename, but without a userid change
*/
onUpdateIdentity(user) {
if (user && user.connected && user.named) {
if (!this.users[user.userid]) return false;
this.reportJoin('n', user.getIdentity(this.id) + '|' + user.userid);
}
}
onLeave(user) {
if (!user) return; // ...
delete this.users[user.userid];
this.userCount--;
if (user.named) {
this.reportJoin('l', user.getIdentity(this.id));
}
if (this.game && this.game.onLeave) this.game.onLeave(user);
}
destroy() {
// deallocate ourself
// remove references to ourself
for (let i in this.users) {
this.users[i].leaveRoom(this, null, true);
delete this.users[i];
}
this.users = null;
Rooms.global.deregisterChatRoom(this.id);
Rooms.global.delistChatRoom(this.id);
if (this.aliases) {
for (let i = 0; i < this.aliases.length; i++) {
Rooms.aliases.delete(this.aliases[i]);
}
}
if (this.game) {
this.game.destroy();
}
// Clear any active timers for the room
if (this.muteTimer) {
clearTimeout(this.muteTimer);
}
this.muteTimer = null;
if (this.expireTimer) {
clearTimeout(this.expireTimer);
}
this.expireTimer = null;
if (this.reportJoinsInterval) {
clearInterval(this.reportJoinsInterval);
}
this.reportJoinsInterval = null;
if (this.logUserStatsInterval) {
clearInterval(this.logUserStatsInterval);
}
this.logUserStatsInterval = null;
if (!this.isPersonal) {
this.modlogStream.destroySoon();
this.modlogStream.removeAllListeners('finish');
}
this.modlogStream = null;
// get rid of some possibly-circular references
Rooms.rooms.delete(this.id);
}
}
function getRoom(roomid, fallback) {
if (fallback) throw new Error("fallback parameter in getRoom no longer supported");
if (roomid && roomid.id) return roomid;
return Rooms.rooms.get(roomid);
}
Rooms.get = getRoom;
Rooms.search = function (name, fallback) {
if (fallback) throw new Error("fallback parameter in Rooms.search no longer supported");
return getRoom(name) || getRoom(toId(name)) || getRoom(Rooms.aliases.get(toId(name)));
};
Rooms.createBattle = function (roomid, format, p1, p2, options) {
if (roomid && roomid.id) return roomid;
if (!p1 || !p2) return false;
if (!roomid) roomid = 'default';
if (!Rooms.rooms.has(roomid)) {
// console.log("NEW BATTLE ROOM: " + roomid);
Monitor.countBattle(p1.latestIp, p1.name);
Monitor.countBattle(p2.latestIp, p2.name);
Rooms.rooms.set(roomid, new BattleRoom(roomid, format, p1, p2, options));
}
return Rooms(roomid);
};
Rooms.createChatRoom = function (roomid, title, data) {
let room = Rooms.rooms.get(roomid);
if (room) return room;
room = new ChatRoom(roomid, title, data);
Rooms.rooms.set(roomid, room);
return room;
};
Rooms.battleModlogStream = fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_battle.txt'), {flags:'a+'});
Rooms.groupchatModlogStream = fs.createWriteStream(path.resolve(__dirname, 'logs/modlog/modlog_groupchat.txt'), {flags:'a+'});
Rooms.global = null;
Rooms.lobby = null;
Rooms.Room = Room;
Rooms.GlobalRoom = GlobalRoom;
Rooms.BattleRoom = BattleRoom;
Rooms.ChatRoom = ChatRoom;
Rooms.RoomGame = require('./room-game').RoomGame;
Rooms.RoomGamePlayer = require('./room-game').RoomGamePlayer;
Rooms.RoomBattle = require('./room-battle').RoomBattle;
Rooms.RoomBattlePlayer = require('./room-battle').RoomBattlePlayer;
Rooms.SimulatorManager = require('./room-battle').SimulatorManager;
Rooms.SimulatorProcess = require('./room-battle').SimulatorProcess;
// initialize
if (!Config.quietconsole) console.log("NEW GLOBAL: global");
Rooms.global = new GlobalRoom('global');
Rooms.rooms.set('global', Rooms.global);
| 41,786
| 17,490
|
const { app, BrowserWindow } = require('electron');
const path = require('path');
if (require('electron-squirrel-startup')) { app.quit(); }
const createWindow = () => {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 1000,
height: 700,
icon: path.join(__dirname, "/favicon.png"),
webPreferences: {
nodeIntegration: true,
worldSafeExecuteJavaScript: true,
contextIsolation: true
}
});
// and load the index.html of the app.
mainWindow.loadFile(path.join(__dirname, 'index.html'));
// Open the DevTools.
if (require('electron-is-dev')) { mainWindow.webContents.openDevTools(); }
};
app.on('ready', createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') { app.quit(); }
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) { createWindow(); }
});
| 889
| 293
|
const { schemaDir, schemaExtension, schemaTypeDir } = require('../../backend/build/consts');
const fs = require('fs');
const js2ts = require('json-schema-to-typescript');
if (!fs.existsSync(schemaTypeDir)) {
fs.mkdirSync(schemaTypeDir, { recursive: true });
}
fs.readdir(schemaDir, (_err, files) =>
files.forEach(file =>
js2ts.compileFromFile(schemaDir + file, {cwd: schemaDir})
.then(ts => fs.writeFileSync(schemaTypeDir + file.replace(schemaExtension, '') + '.ts', ts))
)
);
| 511
| 165
|
(function ( views ) {
views.AppView = Backbone.View.extend({
el : '#content',
initialize : function () {
var tags = this.collection;
tags.on('add', this.addOne, this);
tags.on('reset', this.addAll, this);
tags.on('all', this.render, this);
tags.pager();
},
addAll : function () {
this.$el.empty();
this.collection.each (this.addOne);
},
addOne : function ( item ) {
var view = new views.ResultView({model:item});
$('#content').append(view.render().el);
},
render: function(){
}
});
})( app.views );
| 590
| 249
|
var { graphqlHTTP } = require("express-graphql");
var { buildSchema, assertInputType } = require("graphql");
var express = require("express");
// Construct a schema, using GraphQL schema language
var restaurants = [
{
id: 1,
name: "WoodsHill ",
description:
"American cuisine, farm to table, with fresh produce every day",
dishes: [
{
name: "Swordfish grill",
price: 27,
},
{
name: "Roasted Broccoli",
price: 11,
},
],
},
{
id: 2,
name: "Fiorellas",
description:
"Italian-American home cooked food with fresh pasta and sauces",
dishes: [
{
name: "Flatbread",
price: 14,
},
{
name: "Carbonara",
price: 18,
},
{
name: "Spaghetti",
price: 19,
},
],
},
{
id: 3,
name: "Karma",
description:
"Malaysian-Chinese-Japanese fusion, with great bar and bartenders",
dishes: [
{
name: "Dragon Roll",
price: 12,
},
{
name: "Pancake roll",
price: 11,
},
{
name: "Cod cakes",
price: 13,
},
],
},
];
var schema = buildSchema(`
type Query{
restaurant(id: Int): Restaurant
restaurants: [Restaurant]
},
type Restaurant {
id: Int
name: String
description: String
dishes:[Dish]
}
type Dish{
name: String
price: Int
}
input RestaurantInput{
id: Int
name: String
description: String
}
type DeleteResponse{
ok: Boolean!
}
type Mutation{
setrestaurant(input: RestaurantInput): Restaurant
deleterestaurant(id: Int!): DeleteResponse
editrestaurant(id: Int!, name: String!): Restaurant
}
`);
// The root provides a resolver function for each API endpoint
var root = {
restaurant: ({id}) => restaurants.find(restaurant => restaurant.id === id),
restaurants: () => restaurants,
setrestaurant: ({ input }) => {
restaurants.push({name: input.name, description: input.description, id:input.id})
return input
},
deleterestaurant: ({ id }) => {
const ok = Boolean(restaurants.find(restaurant => restaurant.id === id))
let delrest = restaurants.find(restaurant => restaurant.id === id);
restaurants = restaurants.filter(restaurant => restaurant.id !== id)
console.log(JSON.stringify(delrest))
return {ok}
},
editrestaurant: ({ id, ...restaurant }) => {
let targetIndex = restaurants.findIndex(restaurant =>restaurant.id === id)
if(!restaurants[targetIndex]){
throw new Error("restaurant doesn't exist")
}
restaurants[targetIndex] = {
...restaurants[targetIndex], ...restaurant
}
return restaurants[targetIndex]
},
};
var app = express();
app.use(
"/graphql",
graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
})
);
var port = 5500;
app.listen(5500, () => console.log("Running Graphql on Port:" + port));
| 2,924
| 989
|
import React from "react";
// import {
// Card,
// CardImg,
// CardText,
// CardBody,
// CardTitle,
// CardSubtitle
// } from "reactstrap";
import {Button} from '@material-ui/core';
// import styled from "styled-components";
import { addFavorite } from "../actions/index";
import { connect } from "react-redux";
import axiosWithAuth from "../utils/axiosWithAuth";
// import axios from "axios";
// const NewCard = styled(Card)`
// width: 30%;
// margin: 1%;
// `;
// const NewDiv = styled.div`
// display: flex;
// flex-wrap: wrap;
// `;
// const NewCardBody = styled(CardBody)`
// display: flex;
// flex-direction: column;
// align-items: center;
// `;
// const BrowseButton = styled.button`
// width: 30%;
// color: white;
// background-color: #2f5973;
// `;
const BrowseCard = props => {
const addSubmit = elem => {
// post favorite here
axiosWithAuth()
.post(`/users/${localStorage.getItem("ID")}/favs`, elem)
.then(response => {
console.log("added fav:", response.data);
})
.catch(error => {
console.log("added fav error:", error);
});
};
return (
<>
<div className="favs-container">
{props.strain.map((elem, i) => (
<div key={i} className="dashboard-favs">
<img alt={elem.name} src={require('../img/botanical-rising-ierZlNiWba0-unsplash.jpg')} />
<p>Strain: {elem.Strain}</p>
<p>Type: {elem.Type}</p>
<p>Flavors: {elem.Flavor}</p>
<p>Effects: {elem.Effects}</p>
<p>Description: {elem.Description}</p>
<br />
<Button
variant="contained"
color="primary"
onClick={() => {
props.addFavorite(elem);
addSubmit(elem);
}}
>
Add Favorite
</Button>
</div>
))}
</div>
{/* string form here */}
</>
);
};
/*
<NewDiv>
{props.strain.map((elem, i) => (
<NewCard key={i}>
<CardImg top width="100%" src={require('../img/botanical-rising-ierZlNiWba0-unsplash.jpg')} alt={elem.name} />
<NewCardBody>
<CardTitle>Strain: {elem.Strain}</CardTitle>
<CardSubtitle>Type: {elem.Type}</CardSubtitle>
<CardText>Flavors: {elem.Flavor}</CardText>
<CardText>Effects: {elem.Effects}</CardText>
<CardText>Description: {elem.Description}</CardText>
</NewCardBody>
<BrowseButton
type="button"
onClick={() => {
props.addFavorite(elem);
addSubmit(elem);
}}
>
Favorite
</BrowseButton>
<BrowseButton type="button">Share</BrowseButton>
</NewCard>
))}
</NewDiv>
*/
const mapStateToProps = state => {
return {
favorites: state.favorites
};
};
export default connect(mapStateToProps, { addFavorite })(BrowseCard);
| 3,063
| 1,001
|
'use strict';
var _utils = require('../utils');
var _lodash = require('lodash');
const arr = v => [].concat(v || []);
module.exports = class UiBundlerEnv {
constructor(workingDir) {
// the location that bundle entry files and all compiles files will
// be written
this.workingDir = workingDir;
// the context that the bundler is running in, this is not officially
// used for anything but it is serialized into the entry file to ensure
// that they are invalidated when the context changes
this.context = {};
// the plugins that are used to build this environment
// are tracked and embedded into the entry file so that when the
// environment changes we can rebuild the bundles
this.pluginInfo = [];
// regular expressions which will prevent webpack from parsing the file
this.noParse = [/node_modules[\/\\](angular|elasticsearch-browser)[\/\\]/, /node_modules[\/\\](mocha|moment)[\/\\]/];
// webpack aliases, like require paths, mapping a prefix to a directory
this.aliases = {
ui: (0, _utils.fromRoot)('src/ui/public'),
test_harness: (0, _utils.fromRoot)('src/test_harness/public'),
querystring: 'querystring-browser'
};
// map of which plugins created which aliases
this.aliasOwners = {};
// loaders that are applied to webpack modules after all other processing
// NOTE: this is intentionally not exposed as a uiExport because it leaks
// too much of the webpack implementation to plugins, but is used by test_bundle
// core plugin to inject the instrumentation loader
this.postLoaders = [];
}
consumePlugin(plugin) {
const tag = `${plugin.id}@${plugin.version}`;
if ((0, _lodash.includes)(this.pluginInfo, tag)) return;
if (plugin.publicDir) {
this.aliases[`plugins/${plugin.id}`] = plugin.publicDir;
}
this.pluginInfo.push(tag);
}
exportConsumer(type) {
switch (type) {
case 'noParse':
return (plugin, spec) => {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = arr(spec)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const re = _step.value;
this.addNoParse(re);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
case '__globalImportAliases__':
return (plugin, spec) => {
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = Object.keys(spec)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
const key = _step2.value;
this.aliases[key] = spec[key];
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
};
}
}
addContext(key, val) {
this.context[key] = val;
}
addPostLoader(loader) {
this.postLoaders.push(loader);
}
addNoParse(regExp) {
this.noParse.push(regExp);
}
};
| 3,941
| 1,101
|
'use strict';
module.exports = function addTransforms(b, transforms) {
if (transforms) b.pipeline.on('package', function(pkg) {
var add = pkg.name && transforms[pkg.name]
if (add) {
var br = pkg.browserify || (pkg.browserify = {})
br.transform = [].concat(br.transform || []).concat(add)
}
})
}
| 330
| 118
|
const Util = require('spike-util')
const glob = require('glob')
const path = require('path')
const fs = require('fs')
const File = require('filewrap')
const Joi = require('joi')
const yaml = require('js-yaml')
const bindAllClass = require('es6bindall')
const bindAll = require('lodash.bindall')
const { map, reduce, filter } = require('objectfn')
const MarkdownIt = require('markdown-it')
const md = new MarkdownIt()
class SpikeCollections {
constructor(opts) {
Object.assign(this, this.validate(opts))
this._pagination = {}
this._locals = {}
this._modifiedOutputs = []
bindAllClass(this, ['apply', 'locals'])
}
validate(opts) {
const schema = Joi.object().keys({
addDataTo: Joi.object().default({}),
collections: Joi.object()
.pattern(
/.*/,
Joi.object().keys({
files: Joi.string(),
transform: Joi.func(),
permalinks: Joi.func(),
markdownLayout: Joi.string(),
paginate: Joi.object().keys({
template: Joi.string().required(),
output: Joi.func().required(),
perPage: Joi.number().default(10)
})
})
)
.default({ posts: { files: 'posts/**' } })
})
const v = Joi.validate(opts, schema)
if (v.error) throw v.error
return v.value
}
apply(compiler) {
this.util = new Util(compiler.options)
// scan to get all the files from posts folders
this.files = map(this.collections, v => {
return glob.sync(v.files, {
cwd: compiler.options.context,
nodir: true,
realpath: true,
ignore: this.util.getSpikeOptions().ignore
})
})
// warn for empty collections
map(this.files, (v, k) => {
if (v.length < 1) {
console.warn(
`Warning: Emtpy collection at path "${this.collections[k].files}"`
)
delete this.files[k]
}
})
// all files as a straight array, no categories
this.allFiles = reduce(
this.files,
(m, v) => {
m.push(...v)
return m
},
[]
)
// If there are no files in collections, we have nothing to do
if (this.allFiles.length < 1) return
// add loader alias so that frontmatter loader can be resolved
const resolveLoader = compiler.options.resolveLoader
if (!resolveLoader.alias) resolveLoader.alias = {}
resolveLoader.alias.frontmatter = path.join(
__dirname,
'frontmatter_loader.js'
)
// add frontmatter loader with pattern converted to regex
compiler.options.module.rules.push({
test: this.util.pathsToRegex(this.allFiles),
use: [
{
loader: 'frontmatter',
options: { _spikeExtension: 'html' } // NOTE: this *could* be configurable
}
]
})
// build utility object used for handling markdownLayout option
const layoutMap = reduce(
this.collections,
(m, v, k) => {
if (v.markdownLayout)
m[path.resolve(compiler.context, v.markdownLayout)] = this.files[k]
return m
},
{}
)
compiler.options._collectionsLayoutMap = layoutMap
// modify matcher to accommodate markdown files
// this will only trigger for simple matcher situations, anything more
// complex and you will have to do it yourself
const spikeOpts = this.util.getSpikeOptions()
const re = /\.(\w+)$/
if (spikeOpts.matchers.html.match(re)) {
spikeOpts.matchers.html = spikeOpts.matchers.html.replace(re, '.($1|md)')
}
// add process the front matter in each file, make available everywhere
compiler.plugin('make', this.processCollectionFiles.bind(this, compiler))
// write the pagination pages if necessary
compiler.plugin(
'before-loader-process',
this.configurePaginationFiles.bind(this, compiler)
)
compiler.plugin('emit', (compilation, cb) => {
// modify output if permalinks dictates
this.util.getSpikeOptions().files.process.map(f => {
const matchedFile = this._modifiedOutputs.find(x => x.path === f.path)
if (matchedFile) {
this.util.modifyOutputPath(f.path, matchedFile.out)
}
})
// that's all!
cb()
})
}
processCollectionFiles(compiler, compilation, done) {
// We need to read the front matter out of each of these files so that it
// can be made available to any other view.
const frontmatterRegex = /^---\s*\n([\s\S]*?)\n?---\s*\n?([\s\S]*)/
const postsWithFrontmatter = map(this.files, (v, k) => {
return v.map(p => {
const relativePath = this.util.getOutputPath(p).relative
// get the front matter
const src = fs.readFileSync(p, 'utf8') // TODO: async this
const fmMatch = frontmatterRegex.exec(src)
let locals
if (!fmMatch) {
locals = {}
} else {
locals = yaml.safeLoad(fmMatch[1])
}
// add _path and _collection special vars
Object.assign(locals, {
_path: relativePath.replace(/(.*)?(\..+?$)/, `$1.html`),
_collection: k
})
// Add _content special vars
const mdExtensions = ['md', 'markdown', 'mdown'];
if (mdExtensions.indexOf(p.split('.').pop()) > -1) {
Object.assign(locals, {
_content: md.render(fmMatch[2]) || null
})
}
// run the transform function to replace frontmatter if it exists
const transformFn = this.collections[k].transform
if (transformFn) {
locals = transformFn(locals)
} // TODO async/promise
// Run permalinks function to get output path (if applicable)
const permalinksFn = this.collections[k].permalinks
if (permalinksFn) {
let outPath
try {
outPath = permalinksFn(p, locals)
} catch (err) {
done(err)
}
if (outPath) {
locals._path = outPath.replace(/(.*)?(\..+?$)/, `$1.html`)
}
this._modifiedOutputs.push({ path: p, out: outPath })
}
// save locals to `this` so they can be accessed by locals fn later
this._locals[relativePath] = locals
return locals
})
})
// Add all posts' data to locals
this.addDataTo._collections = postsWithFrontmatter
// and return
done()
}
configurePaginationFiles(compiler, compilation, options) {
// match template to its config
let conf = filter(this.collections, v => {
if (!v.paginate) return false
const tplPath = path.join(compiler.options.context, v.paginate.template)
return tplPath === options.filename
})
// if it's not a template, return
const key = Object.keys(conf)[0]
if (!key) return options
// get any posts in the current template's collection
conf = conf[key]
const postsInCollection = this.addDataTo._collections[key]
// if it is a template, we split the posts into a pages object, which
// groups them into pages based on options.perPage
let currentPage = 1
const pages = postsInCollection.reduce(
(m, p) => {
let current = m[currentPage - 1]
if (current.posts.length === conf.paginate.perPage) {
currentPage++
current = {
page: currentPage,
path: conf.paginate.output(currentPage),
posts: []
}
m.push(current)
}
current.posts.push(p)
return m
},
[
{
page: currentPage,
path: conf.paginate.output(currentPage),
posts: []
}
]
)
// add the pages to locals
if (!this.addDataTo._pages) this.addDataTo._pages = {}
this.addDataTo._pages[key] = pages
// finally add the custom pagination locals to the template
options.multi = []
pages.map((page, i) => {
options.multi.push({
name: page.path,
locals: Object.assign({}, this.addDataTo, {
_currentPage: page,
next: pages[i + 1],
prev: pages[i - 1]
})
})
})
return options
}
// grabs front matter for the given file and merges it into the locals
locals(ctx, locals = {}) {
if (ctx.options.__frontmatter) {
const f = new File(ctx.options.context, ctx.resourcePath)
const permalinkLocals = this._locals[f.relative]
const frontmatterLocals = ctx.options.__frontmatter[f.relative]
return Object.assign(locals, permalinkLocals, frontmatterLocals)
} else {
return locals
}
}
}
const jekyll = {
regex: /([A-Za-z-_]+)\/(\d+)-(\d+)-(\d+)-([A-Za-z-_]+)\.(\w+)$/,
date: function(p) {
const m = this._checkFormat(p)
return `${m[1]}/${m[2]}/${m[3]}/${m[4]}/${m[5]}.${m[6]}`
},
ordinal: function(p) {
const m = this._checkFormat(p)
const doy = getDOY(new Date(`${m[2]}-${m[3]}-${m[4]}`))
return `${m[1]}/${m[2]}/${doy}/${m[5]}.${m[6]}`
},
none: function(p) {
const m = this._checkFormat(p)
return `${m[1]}/${m[5]}.${m[6]}`
},
_checkFormat: function(p) {
const m = p.match(this.regex)
if (!m || !m[1] || !m[2] || !m[3] || !m[4]) {
throw new Error(`incorrect title formatting for post: ${p}`)
}
return m
}
}
// Date utilities for the ordinal function
function isLeapYear(d) {
const year = d.getFullYear()
if ((year & 3) !== 0) return false
return year % 100 !== 0 || year % 400 === 0
}
function getDOY(d) {
var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
var mn = d.getMonth()
var dn = d.getDate()
var dayOfYear = dayCount[mn] + dn
if (mn > 1 && isLeapYear(d)) dayOfYear++
return dayOfYear
}
module.exports = SpikeCollections
module.exports.jekyll = bindAll(jekyll, ['date', 'ordinal', 'none'])
| 9,861
| 3,187
|
import React, { Component } from 'react';
import CommentList from '../CommentList/CommentList';
import CommentForm from '../CommentForm/CommentForm';
class CommentBox extends Component {
constructor(props) {
super(props);
this.state = {
comments: [
{
id: 1388534400000,
author: 'Pete Hunt',
text: 'Hey there!',
},
{
id: 1420070400000,
author: 'Paul O’Shannessy',
text: 'React is great!',
},
],
};
this.handleCommentSubmit = this.handleCommentSubmit.bind(this);
}
handleCommentSubmit({ author, text }) {
this.setState({
comments : [...this.state.comments, { author, text, id: Date.now() }]
});
}
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList comments={this.state.comments} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
}
export default CommentBox;
| 1,015
| 322
|
/*!
* AdminLTE v3.2.0-rc (https://adminlte.io)
* Copyright 2014-2021 Colorlib <https://colorlib.com>
* Licensed under MIT (https://github.com/ColorlibHQ/AdminLTE/blob/master/LICENSE)
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("jquery")):"function"==typeof define&&define.amd?define(["exports","jquery"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).adminlte={},e.jQuery)}(this,(function(e,t){"use strict";function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=a(t),i="CardRefresh",o="lte.cardrefresh",l=n.default.fn[i],s="card",r='[data-card-widget="card-refresh"]',d={source:"",sourceSelector:"",params:{},trigger:r,content:".card-body",loadInContent:!0,loadOnInit:!0,loadErrorTemplate:!0,responseType:"",overlayTemplate:'<div class="overlay"><i class="fas fa-2x fa-sync-alt fa-spin"></i></div>',errorTemplate:'<span class="text-danger"></span>',onLoadStart:function(){},onLoadDone:function(e){return e},onLoadFail:function(e,t,a){}},f=function(){function e(e,t){if(this._element=e,this._parent=e.parents(".card").first(),this._settings=n.default.extend({},d,t),this._overlay=n.default(this._settings.overlayTemplate),e.hasClass(s)&&(this._parent=e),""===this._settings.source)throw new Error("Source url was not defined. Please specify a url in your CardRefresh source option.")}var t=e.prototype;return t.load=function(){var e=this;this._addOverlay(),this._settings.onLoadStart.call(n.default(this)),n.default.get(this._settings.source,this._settings.params,(function(t){e._settings.loadInContent&&(""!==e._settings.sourceSelector&&(t=n.default(t).find(e._settings.sourceSelector).html()),e._parent.find(e._settings.content).html(t)),e._settings.onLoadDone.call(n.default(e),t),e._removeOverlay()}),""!==this._settings.responseType&&this._settings.responseType).fail((function(t,a,i){if(e._removeOverlay(),e._settings.loadErrorTemplate){var o=n.default(e._settings.errorTemplate).text(i);e._parent.find(e._settings.content).empty().append(o)}e._settings.onLoadFail.call(n.default(e),t,a,i)})),n.default(this._element).trigger(n.default.Event("loaded.lte.cardrefresh"))},t._addOverlay=function(){this._parent.append(this._overlay),n.default(this._element).trigger(n.default.Event("overlay.added.lte.cardrefresh"))},t._removeOverlay=function(){this._parent.find(this._overlay).remove(),n.default(this._element).trigger(n.default.Event("overlay.removed.lte.cardrefresh"))},t._init=function(){var e=this;n.default(this).find(this._settings.trigger).on("click",(function(){e.load()})),this._settings.loadOnInit&&this.load()},e._jQueryInterface=function(t){var a=n.default(this).data(o),i=n.default.extend({},d,n.default(this).data());a||(a=new e(n.default(this),i),n.default(this).data(o,"string"==typeof t?a:t)),"string"==typeof t&&/load/.test(t)?a[t]():a._init(n.default(this))},e}();n.default(document).on("click",r,(function(e){e&&e.preventDefault(),f._jQueryInterface.call(n.default(this),"load")})),n.default((function(){n.default(r).each((function(){f._jQueryInterface.call(n.default(this))}))})),n.default.fn[i]=f._jQueryInterface,n.default.fn[i].Constructor=f,n.default.fn[i].noConflict=function(){return n.default.fn[i]=l,f._jQueryInterface};var u="CardWidget",c="lte.cardwidget",h=n.default.fn[u],g="card",p="collapsed-card",m="collapsing-card",v="expanding-card",_="was-collapsed",b="maximized-card",y='[data-card-widget="remove"]',w='[data-card-widget="collapse"]',C='[data-card-widget="maximize"]',x={animationSpeed:"normal",collapseTrigger:w,removeTrigger:y,maximizeTrigger:C,collapseIcon:"fa-minus",expandIcon:"fa-plus",maximizeIcon:"fa-expand",minimizeIcon:"fa-compress"},I=function(){function e(e,t){this._element=e,this._parent=e.parents(".card").first(),e.hasClass(g)&&(this._parent=e),this._settings=n.default.extend({},x,t)}var t=e.prototype;return t.collapse=function(){var e=this;this._parent.addClass(m).children(".card-body, .card-footer").slideUp(this._settings.animationSpeed,(function(){e._parent.addClass(p).removeClass(m)})),this._parent.find("> .card-header "+this._settings.collapseTrigger+" ."+this._settings.collapseIcon).addClass(this._settings.expandIcon).removeClass(this._settings.collapseIcon),this._element.trigger(n.default.Event("collapsed.lte.cardwidget"),this._parent)},t.expand=function(){var e=this;this._parent.addClass(v).children(".card-body, .card-footer").slideDown(this._settings.animationSpeed,(function(){e._parent.removeClass(p).removeClass(v)})),this._parent.find("> .card-header "+this._settings.collapseTrigger+" ."+this._settings.expandIcon).addClass(this._settings.collapseIcon).removeClass(this._settings.expandIcon),this._element.trigger(n.default.Event("expanded.lte.cardwidget"),this._parent)},t.remove=function(){this._parent.slideUp(),this._element.trigger(n.default.Event("removed.lte.cardwidget"),this._parent)},t.toggle=function(){this._parent.hasClass(p)?this.expand():this.collapse()},t.maximize=function(){this._parent.find(this._settings.maximizeTrigger+" ."+this._settings.maximizeIcon).addClass(this._settings.minimizeIcon).removeClass(this._settings.maximizeIcon),this._parent.css({height:this._parent.height(),width:this._parent.width(),transition:"all .15s"}).delay(150).queue((function(){var e=n.default(this);e.addClass(b),n.default("html").addClass(b),e.hasClass(p)&&e.addClass(_),e.dequeue()})),this._element.trigger(n.default.Event("maximized.lte.cardwidget"),this._parent)},t.minimize=function(){this._parent.find(this._settings.maximizeTrigger+" ."+this._settings.minimizeIcon).addClass(this._settings.maximizeIcon).removeClass(this._settings.minimizeIcon),this._parent.css("cssText","height: "+this._parent[0].style.height+" !important; width: "+this._parent[0].style.width+" !important; transition: all .15s;").delay(10).queue((function(){var e=n.default(this);e.removeClass(b),n.default("html").removeClass(b),e.css({height:"inherit",width:"inherit"}),e.hasClass(_)&&e.removeClass(_),e.dequeue()})),this._element.trigger(n.default.Event("minimized.lte.cardwidget"),this._parent)},t.toggleMaximize=function(){this._parent.hasClass(b)?this.minimize():this.maximize()},t._init=function(e){var t=this;this._parent=e,n.default(this).find(this._settings.collapseTrigger).click((function(){t.toggle()})),n.default(this).find(this._settings.maximizeTrigger).click((function(){t.toggleMaximize()})),n.default(this).find(this._settings.removeTrigger).click((function(){t.remove()}))},e._jQueryInterface=function(t){var a=n.default(this).data(c),i=n.default.extend({},x,n.default(this).data());a||(a=new e(n.default(this),i),n.default(this).data(c,"string"==typeof t?a:t)),"string"==typeof t&&/collapse|expand|remove|toggle|maximize|minimize|toggleMaximize/.test(t)?a[t]():"object"==typeof t&&a._init(n.default(this))},e}();n.default(document).on("click",w,(function(e){e&&e.preventDefault(),I._jQueryInterface.call(n.default(this),"toggle")})),n.default(document).on("click",y,(function(e){e&&e.preventDefault(),I._jQueryInterface.call(n.default(this),"remove")})),n.default(document).on("click",C,(function(e){e&&e.preventDefault(),I._jQueryInterface.call(n.default(this),"toggleMaximize")})),n.default.fn[u]=I._jQueryInterface,n.default.fn[u].Constructor=I,n.default.fn[u].noConflict=function(){return n.default.fn[u]=h,I._jQueryInterface};var T="ControlSidebar",S="lte.controlsidebar",j=n.default.fn[T],k=".control-sidebar",Q=".control-sidebar-content",H='[data-widget="control-sidebar"]',z=".main-header",F=".main-footer",E="control-sidebar-animate",L="control-sidebar-open",D="control-sidebar-slide-open",R="layout-fixed",A={controlsidebarSlide:!0,scrollbarTheme:"os-theme-light",scrollbarAutoHide:"l",target:k,animationSpeed:300},M=function(){function e(e,t){this._element=e,this._config=t}var t=e.prototype;return t.collapse=function(){var e=this,t=n.default("body"),a=n.default("html"),i=this._config.target;this._config.controlsidebarSlide?(a.addClass(E),t.removeClass(D).delay(300).queue((function(){n.default(i).hide(),a.removeClass(E),n.default(this).dequeue()}))):t.removeClass(L),n.default(this._element).trigger(n.default.Event("collapsed.lte.controlsidebar")),setTimeout((function(){n.default(e._element).trigger(n.default.Event("collapsed-done.lte.controlsidebar"))}),this._config.animationSpeed)},t.show=function(){var e=n.default("body"),t=n.default("html");this._config.controlsidebarSlide?(t.addClass(E),n.default(this._config.target).show().delay(10).queue((function(){e.addClass(D).delay(300).queue((function(){t.removeClass(E),n.default(this).dequeue()})),n.default(this).dequeue()}))):e.addClass(L),this._fixHeight(),this._fixScrollHeight(),n.default(this._element).trigger(n.default.Event("expanded.lte.controlsidebar"))},t.toggle=function(){var e=n.default("body");e.hasClass(L)||e.hasClass(D)?this.collapse():this.show()},t._init=function(){var e=this,t=n.default("body");t.hasClass(L)||t.hasClass(D)?(n.default(k).not(this._config.target).hide(),n.default(this._config.target).css("display","block")):n.default(k).hide(),this._fixHeight(),this._fixScrollHeight(),n.default(window).resize((function(){e._fixHeight(),e._fixScrollHeight()})),n.default(window).scroll((function(){var t=n.default("body");(t.hasClass(L)||t.hasClass(D))&&e._fixScrollHeight()}))},t._isNavbarFixed=function(){var e=n.default("body");return e.hasClass("layout-navbar-fixed")||e.hasClass("layout-sm-navbar-fixed")||e.hasClass("layout-md-navbar-fixed")||e.hasClass("layout-lg-navbar-fixed")||e.hasClass("layout-xl-navbar-fixed")},t._isFooterFixed=function(){var e=n.default("body");return e.hasClass("layout-footer-fixed")||e.hasClass("layout-sm-footer-fixed")||e.hasClass("layout-md-footer-fixed")||e.hasClass("layout-lg-footer-fixed")||e.hasClass("layout-xl-footer-fixed")},t._fixScrollHeight=function(){var e=n.default("body"),t=n.default(this._config.target);if(e.hasClass(R)){var a={scroll:n.default(document).height(),window:n.default(window).height(),header:n.default(z).outerHeight(),footer:n.default(F).outerHeight()},i=Math.abs(a.window+n.default(window).scrollTop()-a.scroll),o=n.default(window).scrollTop(),l=this._isNavbarFixed()&&"fixed"===n.default(z).css("position"),s=this._isFooterFixed()&&"fixed"===n.default(F).css("position"),r=n.default(this._config.target+", "+this._config.target+" "+Q);if(0===o&&0===i)t.css({bottom:a.footer,top:a.header}),r.css("height",a.window-(a.header+a.footer));else if(i<=a.footer)if(!1===s){var d=a.header-o;t.css("bottom",a.footer-i).css("top",d>=0?d:0),r.css("height",a.window-(a.footer-i))}else t.css("bottom",a.footer);else o<=a.header?!1===l?(t.css("top",a.header-o),r.css("height",a.window-(a.header-o))):t.css("top",a.header):!1===l?(t.css("top",0),r.css("height",a.window)):t.css("top",a.header);s&&l?(r.css("height","100%"),t.css("height","")):(s||l)&&(r.css("height","100%"),r.css("height",""))}},t._fixHeight=function(){var e=n.default("body"),t=n.default(this._config.target+" "+Q);if(e.hasClass(R)){var a=n.default(window).height(),i=n.default(z).outerHeight(),o=n.default(F).outerHeight(),l=a-i;this._isFooterFixed()&&"fixed"===n.default(F).css("position")&&(l=a-i-o),t.css("height",l),"undefined"!=typeof n.default.fn.overlayScrollbars&&t.overlayScrollbars({className:this._config.scrollbarTheme,sizeAutoCapable:!0,scrollbars:{autoHide:this._config.scrollbarAutoHide,clickScrolling:!0}})}else t.attr("style","")},e._jQueryInterface=function(t){return this.each((function(){var a=n.default(this).data(S),i=n.default.extend({},A,n.default(this).data());if(a||(a=new e(this,i),n.default(this).data(S,a)),"undefined"===a[t])throw new Error(t+" is not a function");a[t]()}))},e}();n.default(document).on("click",H,(function(e){e.preventDefault(),M._jQueryInterface.call(n.default(this),"toggle")})),n.default(document).ready((function(){M._jQueryInterface.call(n.default(H),"_init")})),n.default.fn[T]=M._jQueryInterface,n.default.fn[T].Constructor=M,n.default.fn[T].noConflict=function(){return n.default.fn[T]=j,M._jQueryInterface};var q="DirectChat",O="lte.directchat",N=n.default.fn[q],P=function(){function e(e){this._element=e}return e.prototype.toggle=function(){n.default(this._element).parents(".direct-chat").first().toggleClass("direct-chat-contacts-open"),n.default(this._element).trigger(n.default.Event("toggled.lte.directchat"))},e._jQueryInterface=function(t){return this.each((function(){var a=n.default(this).data(O);a||(a=new e(n.default(this)),n.default(this).data(O,a)),a[t]()}))},e}();n.default(document).on("click",'[data-widget="chat-pane-toggle"]',(function(e){e&&e.preventDefault(),P._jQueryInterface.call(n.default(this),"toggle")})),n.default.fn[q]=P._jQueryInterface,n.default.fn[q].Constructor=P,n.default.fn[q].noConflict=function(){return n.default.fn[q]=N,P._jQueryInterface};var U="Dropdown",B="lte.dropdown",$=n.default.fn[U],J=".dropdown-menu",W={},V=function(){function e(e,t){this._config=t,this._element=e}var t=e.prototype;return t.toggleSubmenu=function(){this._element.siblings().show().toggleClass("show"),this._element.next().hasClass("show")||this._element.parents(J).first().find(".show").removeClass("show").hide(),this._element.parents("li.nav-item.dropdown.show").on("hidden.bs.dropdown",(function(){n.default(".dropdown-submenu .show").removeClass("show").hide()}))},t.fixPosition=function(){var e=n.default(".dropdown-menu.show");if(0!==e.length){e.hasClass("dropdown-menu-right")?e.css({left:"inherit",right:0}):e.css({left:0,right:"inherit"});var t=e.offset(),a=e.width(),i=n.default(window).width()-t.left;t.left<0?e.css({left:"inherit",right:t.left-5}):i<a&&e.css({left:"inherit",right:0})}},e._jQueryInterface=function(t){return this.each((function(){var a=n.default(this).data(B),i=n.default.extend({},W,n.default(this).data());a||(a=new e(n.default(this),i),n.default(this).data(B,a)),"toggleSubmenu"!==t&&"fixPosition"!==t||a[t]()}))},e}();n.default('.dropdown-menu [data-toggle="dropdown"]').on("click",(function(e){e.preventDefault(),e.stopPropagation(),V._jQueryInterface.call(n.default(this),"toggleSubmenu")})),n.default('.navbar [data-toggle="dropdown"]').on("click",(function(e){e.preventDefault(),n.default(e.target).parent().hasClass("dropdown-submenu")||setTimeout((function(){V._jQueryInterface.call(n.default(this),"fixPosition")}),1)})),n.default.fn[U]=V._jQueryInterface,n.default.fn[U].Constructor=V,n.default.fn[U].noConflict=function(){return n.default.fn[U]=$,V._jQueryInterface};var G="ExpandableTable",K="lte.expandableTable",X=n.default.fn[G],Y=".expandable-body",Z='[data-widget="expandable-table"]',ee="aria-expanded",te=function(){function e(e,t){this._options=t,this._element=e}var t=e.prototype;return t.init=function(){n.default(Z).each((function(e,t){var a=n.default(t).attr(ee),i=n.default(t).next(Y).children().first().children();"true"===a?i.show():"false"===a&&(i.hide(),i.parent().parent().addClass("d-none"))}))},t.toggleRow=function(){var e=this._element,t=e.attr(ee),a=e.next(Y).children().first().children();a.stop(),"true"===t?(a.slideUp(500,(function(){e.next(Y).addClass("d-none")})),e.attr(ee,"false"),e.trigger(n.default.Event("collapsed.lte.expandableTable"))):"false"===t&&(e.next(Y).removeClass("d-none"),a.slideDown(500),e.attr(ee,"true"),e.trigger(n.default.Event("expanded.lte.expandableTable")))},e._jQueryInterface=function(t){return this.each((function(){var a=n.default(this).data(K);a||(a=new e(n.default(this)),n.default(this).data(K,a)),"string"==typeof t&&/init|toggleRow/.test(t)&&a[t]()}))},e}();n.default(".expandable-table").ready((function(){te._jQueryInterface.call(n.default(this),"init")})),n.default(document).on("click",Z,(function(){te._jQueryInterface.call(n.default(this),"toggleRow")})),n.default.fn[G]=te._jQueryInterface,n.default.fn[G].Constructor=te,n.default.fn[G].noConflict=function(){return n.default.fn[G]=X,te._jQueryInterface};var ae="Fullscreen",ne="lte.fullscreen",ie=n.default.fn[ae],oe='[data-widget="fullscreen"]',le=oe+" i",se={minimizeIcon:"fa-compress-arrows-alt",maximizeIcon:"fa-expand-arrows-alt"},re=function(){function e(e,t){this.element=e,this.options=n.default.extend({},se,t)}var t=e.prototype;return t.toggle=function(){document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement?this.windowed():this.fullscreen()},t.toggleIcon=function(){document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement||document.msFullscreenElement?n.default(le).removeClass(this.options.maximizeIcon).addClass(this.options.minimizeIcon):n.default(le).removeClass(this.options.minimizeIcon).addClass(this.options.maximizeIcon)},t.fullscreen=function(){document.documentElement.requestFullscreen?document.documentElement.requestFullscreen():document.documentElement.webkitRequestFullscreen?document.documentElement.webkitRequestFullscreen():document.documentElement.msRequestFullscreen&&document.documentElement.msRequestFullscreen()},t.windowed=function(){document.exitFullscreen?document.exitFullscreen():document.webkitExitFullscreen?document.webkitExitFullscreen():document.msExitFullscreen&&document.msExitFullscreen()},e._jQueryInterface=function(t){var a=n.default(this).data(ne);a||(a=n.default(this).data());var i=n.default.extend({},se,"object"==typeof t?t:a),o=new e(n.default(this),i);n.default(this).data(ne,"object"==typeof t?t:a),"string"==typeof t&&/toggle|toggleIcon|fullscreen|windowed/.test(t)?o[t]():o.init()},e}();n.default(document).on("click",oe,(function(){re._jQueryInterface.call(n.default(this),"toggle")})),n.default(document).on("webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange",(function(){re._jQueryInterface.call(n.default(oe),"toggleIcon")})),n.default.fn[ae]=re._jQueryInterface,n.default.fn[ae].Constructor=re,n.default.fn[ae].noConflict=function(){return n.default.fn[ae]=ie,re._jQueryInterface};var de="lte.iframe",fe=n.default.fn.IFrame,ue='[data-widget="iframe"]',ce='[data-widget="iframe-fullscreen"]',he=".content-wrapper",ge=".content-wrapper iframe",pe=".content-wrapper.iframe-mode .nav",me=".content-wrapper.iframe-mode .navbar-nav",ve=me+" .nav-item",_e=me+" .nav-link",be=".content-wrapper.iframe-mode .tab-content",ye=be+" .tab-empty",we=be+" .tab-loading",Ce=be+" .tab-pane",xe=".main-sidebar .nav-item > a.nav-link",Ie=".main-header .nav-item a.nav-link",Te=".main-header a.dropdown-item",Se="iframe-mode",je="iframe-mode-fullscreen",ke={onTabClick:function(e){return e},onTabChanged:function(e){return e},onTabCreated:function(e){return e},autoIframeMode:!0,autoItemActive:!0,autoShowNewTab:!0,autoDarkMode:!1,allowDuplicates:!1,allowReload:!0,loadingScreen:!0,useNavbarItems:!0,scrollOffset:40,scrollBehaviorSwap:!1,iconMaximize:"fa-expand",iconMinimize:"fa-compress"},Qe=function(){function e(e,t){this._config=t,this._element=e,this._init()}var t=e.prototype;return t.onTabClick=function(e){this._config.onTabClick(e)},t.onTabChanged=function(e){this._config.onTabChanged(e)},t.onTabCreated=function(e){this._config.onTabCreated(e)},t.createTab=function(e,t,a,i){var o=this,l="panel-"+a,s="tab-"+a;this._config.allowDuplicates&&(l+="-"+Math.floor(1e3*Math.random()),s+="-"+Math.floor(1e3*Math.random()));var r='<li class="nav-item" role="presentation"><a href="#" class="btn-iframe-close" data-widget="iframe-close" data-type="only-this"><i class="fas fa-times"></i></a><a class="nav-link" data-toggle="row" id="'+s+'" href="#'+l+'" role="tab" aria-controls="'+l+'" aria-selected="false">'+e+"</a></li>";n.default(me).append(unescape(escape(r)));var d='<div class="tab-pane fade" id="'+l+'" role="tabpanel" aria-labelledby="'+s+'"><iframe src="'+t+'"></iframe></div>';if(n.default(be).append(unescape(escape(d))),i)if(this._config.loadingScreen){var f=n.default(we);f.fadeIn(),n.default(l+" iframe").ready((function(){"number"==typeof o._config.loadingScreen?(o.switchTab("#"+s),setTimeout((function(){f.fadeOut()}),o._config.loadingScreen)):(o.switchTab("#"+s),f.fadeOut())}))}else this.switchTab("#"+s);this.onTabCreated(n.default("#"+s))},t.openTabSidebar=function(e,t){void 0===t&&(t=this._config.autoShowNewTab);var a=n.default(e).clone();void 0===a.attr("href")&&(a=n.default(e).parent("a").clone()),a.find(".right, .search-path").remove();var i=a.find("p").text();""===i&&(i=a.text());var o=a.attr("href");if("#"!==o&&""!==o&&void 0!==o){var l=o.replace("./","").replace(/["#&'./:=?[\]]/gi,"-").replace(/(--)/gi,""),s="tab-"+l;if(!this._config.allowDuplicates&&n.default("#"+s).length>0)return this.switchTab("#"+s,this._config.allowReload);(!this._config.allowDuplicates&&0===n.default("#"+s).length||this._config.allowDuplicates)&&this.createTab(i,o,l,t)}},t.switchTab=function(e,t){var a=this;void 0===t&&(t=!1);var i=n.default(e),o=i.attr("href");if(n.default(ye).hide(),t){var l=n.default(we);this._config.loadingScreen?l.show(0,(function(){n.default(o+" iframe").attr("src",n.default(o+" iframe").attr("src")).ready((function(){a._config.loadingScreen&&("number"==typeof a._config.loadingScreen?setTimeout((function(){l.fadeOut()}),a._config.loadingScreen):l.fadeOut())}))})):n.default(o+" iframe").attr("src",n.default(o+" iframe").attr("src"))}n.default(me+" .active").tab("dispose").removeClass("active"),this._fixHeight(),i.tab("show"),i.parents("li").addClass("active"),this.onTabChanged(i),this._config.autoItemActive&&this._setItemActive(n.default(o+" iframe").attr("src"))},t.removeActiveTab=function(e,t){if("all"==e)n.default(ve).remove(),n.default(Ce).remove(),n.default(ye).show();else if("all-other"==e)n.default(ve+":not(.active)").remove(),n.default(Ce+":not(.active)").remove();else if("only-this"==e){var a=n.default(t),i=a.parent(".nav-item"),o=i.parent(),l=i.index(),s=a.siblings(".nav-link").attr("aria-controls");if(i.remove(),n.default("#"+s).remove(),n.default(be).children().length==n.default(ye+", "+we).length)n.default(ye).show();else{var r=l-1;this.switchTab(o.children().eq(r).find("a.nav-link"))}}else{var d=n.default(ve+".active"),f=d.parent(),u=d.index();if(d.remove(),n.default(Ce+".active").remove(),n.default(be).children().length==n.default(ye+", "+we).length)n.default(ye).show();else{var c=u-1;this.switchTab(f.children().eq(c).find("a.nav-link"))}}},t.toggleFullscreen=function(){n.default("body").hasClass(je)?(n.default(ce+" i").removeClass(this._config.iconMinimize).addClass(this._config.iconMaximize),n.default("body").removeClass(je),n.default(ye+", "+we).height("100%"),n.default(he).height("100%"),n.default(ge).height("100%")):(n.default(ce+" i").removeClass(this._config.iconMaximize).addClass(this._config.iconMinimize),n.default("body").addClass(je)),n.default(window).trigger("resize"),this._fixHeight(!0)},t._init=function(){var e=n.default(be).children().length>2;if(this._setupListeners(),this._fixHeight(!0),e){var t=n.default(""+Ce).first();console.log(t);var a="#tab-"+t.attr("id").replace("panel-","");this.switchTab(a,!0)}},t._initFrameElement=function(){if(window.frameElement&&this._config.autoIframeMode){var e=n.default("body");e.addClass(Se),this._config.autoDarkMode&&e.addClass("dark-mode")}},t._navScroll=function(e){var t=n.default(me).scrollLeft();n.default(me).animate({scrollLeft:t+e},250,"linear")},t._setupListeners=function(){var e=this;n.default(window).on("resize",(function(){setTimeout((function(){e._fixHeight()}),1)})),n.default(he).hasClass(Se)&&(n.default(document).on("click",xe+", .sidebar-search-results .list-group-item",(function(t){t.preventDefault(),e.openTabSidebar(t.target)})),this._config.useNavbarItems&&n.default(document).on("click",Ie+", "+Te,(function(t){t.preventDefault(),e.openTabSidebar(t.target)}))),n.default(document).on("click",_e,(function(t){t.preventDefault(),e.onTabClick(t.target),e.switchTab(t.target)})),n.default(document).on("click",_e,(function(t){t.preventDefault(),e.onTabClick(t.target),e.switchTab(t.target)})),n.default(document).on("click",'[data-widget="iframe-close"]',(function(t){t.preventDefault();var a=t.target;"I"==a.nodeName&&(a=t.target.offsetParent),e.removeActiveTab(a.attributes["data-type"]?a.attributes["data-type"].nodeValue:null,a)})),n.default(document).on("click",ce,(function(t){t.preventDefault(),e.toggleFullscreen()}));var t=!1,a=null;n.default(document).on("mousedown",'[data-widget="iframe-scrollleft"]',(function(n){n.preventDefault(),clearInterval(a);var i=e._config.scrollOffset;e._config.scrollBehaviorSwap||(i=-i),t=!0,e._navScroll(i),a=setInterval((function(){e._navScroll(i)}),250)})),n.default(document).on("mousedown",'[data-widget="iframe-scrollright"]',(function(n){n.preventDefault(),clearInterval(a);var i=e._config.scrollOffset;e._config.scrollBehaviorSwap&&(i=-i),t=!0,e._navScroll(i),a=setInterval((function(){e._navScroll(i)}),250)})),n.default(document).on("mouseup",(function(){t&&(t=!1,clearInterval(a),a=null)}))},t._setItemActive=function(e){n.default(xe+", "+Te).removeClass("active"),n.default(Ie).parent().removeClass("active");var t=n.default(Ie+'[href$="'+e+'"]'),a=n.default('.main-header a.dropdown-item[href$="'+e+'"]'),i=n.default(xe+'[href$="'+e+'"]');t.each((function(e,t){n.default(t).parent().addClass("active")})),a.each((function(e,t){n.default(t).addClass("active")})),i.each((function(e,t){n.default(t).addClass("active"),n.default(t).parents(".nav-treeview").prevAll(".nav-link").addClass("active")}))},t._fixHeight=function(e){if(void 0===e&&(e=!1),n.default("body").hasClass(je)){var t=n.default(window).height(),a=n.default(pe).outerHeight();n.default(ye+", "+we+", "+ge).height(t-a),n.default(he).height(t)}else{var i=parseFloat(n.default(he).css("height")),o=n.default(pe).outerHeight();1==e?setTimeout((function(){n.default(ye+", "+we).height(i-o)}),50):n.default(ge).height(i-o)}},e._jQueryInterface=function(t){if(n.default(ue).length>0){var a=n.default(this).data(de);a||(a=n.default(this).data());var i=n.default.extend({},ke,"object"==typeof t?t:a);localStorage.setItem("AdminLTE:IFrame:Options",JSON.stringify(i));var o=new e(n.default(this),i);n.default(this).data(de,"object"==typeof t?t:a),"string"==typeof t&&/createTab|openTabSidebar|switchTab|removeActiveTab/.test(t)&&o[t]()}else new e(n.default(this),JSON.parse(localStorage.getItem("AdminLTE:IFrame:Options")))._initFrameElement()},e}();n.default(window).on("load",(function(){Qe._jQueryInterface.call(n.default(ue))})),n.default.fn.IFrame=Qe._jQueryInterface,n.default.fn.IFrame.Constructor=Qe,n.default.fn.IFrame.noConflict=function(){return n.default.fn.IFrame=fe,Qe._jQueryInterface};var He="lte.layout",ze=n.default.fn.Layout,Fe=".main-header",Ee=".main-sidebar",Le=".main-sidebar .sidebar",De=".main-footer",Re="sidebar-focused",Ae={scrollbarTheme:"os-theme-light",scrollbarAutoHide:"l",panelAutoHeight:!0,panelAutoHeightMode:"min-height",preloadDuration:200,loginRegisterAutoHeight:!0},Me=function(){function e(e,t){this._config=t,this._element=e}var t=e.prototype;return t.fixLayoutHeight=function(e){void 0===e&&(e=null);var t=n.default("body"),a=0;(t.hasClass("control-sidebar-slide-open")||t.hasClass("control-sidebar-open")||"control_sidebar"===e)&&(a=n.default(".control-sidebar-content").outerHeight());var i={window:n.default(window).height(),header:n.default(Fe).length>0&&!n.default("body").hasClass("layout-navbar-fixed")?n.default(Fe).outerHeight():0,footer:n.default(De).length>0?n.default(De).outerHeight():0,sidebar:n.default(Le).length>0?n.default(Le).height():0,controlSidebar:a},o=this._max(i),l=this._config.panelAutoHeight;!0===l&&(l=0);var s=n.default(".content-wrapper");!1!==l&&(o===i.controlSidebar?s.css(this._config.panelAutoHeightMode,o+l):o===i.window?s.css(this._config.panelAutoHeightMode,o+l-i.header-i.footer):s.css(this._config.panelAutoHeightMode,o+l-i.header),this._isFooterFixed()&&s.css(this._config.panelAutoHeightMode,parseFloat(s.css(this._config.panelAutoHeightMode))+i.footer)),t.hasClass("layout-fixed")&&("undefined"!=typeof n.default.fn.overlayScrollbars?n.default(Le).overlayScrollbars({className:this._config.scrollbarTheme,sizeAutoCapable:!0,scrollbars:{autoHide:this._config.scrollbarAutoHide,clickScrolling:!0}}):n.default(Le).css("overflow-y","auto"))},t.fixLoginRegisterHeight=function(){var e=n.default("body"),t=n.default(".login-box, .register-box");if(e.hasClass("iframe-mode"))e.css("height","100%"),n.default(".wrapper").css("height","100%"),n.default("html").css("height","100%");else if(0===t.length)e.css("height","auto"),n.default("html").css("height","auto");else{var a=t.height();e.css(this._config.panelAutoHeightMode)!==a&&e.css(this._config.panelAutoHeightMode,a)}},t._init=function(){var e=this;this.fixLayoutHeight(),!0===this._config.loginRegisterAutoHeight?this.fixLoginRegisterHeight():this._config.loginRegisterAutoHeight===parseInt(this._config.loginRegisterAutoHeight,10)&&setInterval(this.fixLoginRegisterHeight,this._config.loginRegisterAutoHeight),n.default(Le).on("collapsed.lte.treeview expanded.lte.treeview",(function(){e.fixLayoutHeight()})),n.default(Ee).on("mouseenter mouseleave",(function(){n.default("body").hasClass("sidebar-collapse")&&e.fixLayoutHeight()})),n.default('[data-widget="pushmenu"]').on("collapsed.lte.pushmenu shown.lte.pushmenu",(function(){setTimeout((function(){e.fixLayoutHeight()}),300)})),n.default('[data-widget="control-sidebar"]').on("collapsed.lte.controlsidebar",(function(){e.fixLayoutHeight()})).on("expanded.lte.controlsidebar",(function(){e.fixLayoutHeight("control_sidebar")})),n.default(window).resize((function(){e.fixLayoutHeight()})),setTimeout((function(){n.default("body.hold-transition").removeClass("hold-transition")}),50),setTimeout((function(){var e=n.default(".preloader");e&&(e.css("height",0),setTimeout((function(){e.children().hide()}),200))}),this._config.preloadDuration)},t._max=function(e){var t=0;return Object.keys(e).forEach((function(a){e[a]>t&&(t=e[a])})),t},t._isFooterFixed=function(){return"fixed"===n.default(De).css("position")},e._jQueryInterface=function(t){return void 0===t&&(t=""),this.each((function(){var a=n.default(this).data(He),i=n.default.extend({},Ae,n.default(this).data());a||(a=new e(n.default(this),i),n.default(this).data(He,a)),"init"===t||""===t?a._init():"fixLayoutHeight"!==t&&"fixLoginRegisterHeight"!==t||a[t]()}))},e}();n.default(window).on("load",(function(){Me._jQueryInterface.call(n.default("body"))})),n.default(Le+" a").on("focusin",(function(){n.default(Ee).addClass(Re)})).on("focusout",(function(){n.default(Ee).removeClass(Re)})),n.default.fn.Layout=Me._jQueryInterface,n.default.fn.Layout.Constructor=Me,n.default.fn.Layout.noConflict=function(){return n.default.fn.Layout=ze,Me._jQueryInterface};var qe="PushMenu",Oe="lte.pushmenu",Ne="."+Oe,Pe=n.default.fn[qe],Ue='[data-widget="pushmenu"]',Be="body",$e="sidebar-collapse",Je="sidebar-open",We="sidebar-is-opening",Ve="sidebar-closed",Ge={autoCollapseSize:992,enableRemember:!1,noTransitionAfterReload:!0,animationSpeed:300},Ke=function(){function e(e,t){this._element=e,this._options=n.default.extend({},Ge,t),0===n.default("#sidebar-overlay").length&&this._addOverlay(),this._init()}var t=e.prototype;return t.expand=function(){var e=n.default(Be);this._options.autoCollapseSize&&n.default(window).width()<=this._options.autoCollapseSize&&e.addClass(Je),e.addClass(We).removeClass("sidebar-collapse sidebar-closed").delay(50).queue((function(){e.removeClass(We),n.default(this).dequeue()})),this._options.enableRemember&&localStorage.setItem("remember"+Ne,Je),n.default(this._element).trigger(n.default.Event("shown.lte.pushmenu"))},t.collapse=function(){var e=this,t=n.default(Be);this._options.autoCollapseSize&&n.default(window).width()<=this._options.autoCollapseSize&&t.removeClass(Je).addClass(Ve),t.addClass($e),this._options.enableRemember&&localStorage.setItem("remember"+Ne,$e),n.default(this._element).trigger(n.default.Event("collapsed.lte.pushmenu")),setTimeout((function(){n.default(e._element).trigger(n.default.Event("collapsed-done.lte.pushmenu"))}),this._options.animationSpeed)},t.toggle=function(){n.default(Be).hasClass($e)?this.expand():this.collapse()},t.autoCollapse=function(e){if(void 0===e&&(e=!1),this._options.autoCollapseSize){var t=n.default(Be);n.default(window).width()<=this._options.autoCollapseSize?t.hasClass(Je)||this.collapse():!0===e&&(t.hasClass(Je)?t.removeClass(Je):t.hasClass(Ve)&&this.expand())}},t.remember=function(){if(this._options.enableRemember){var e=n.default("body");localStorage.getItem("remember"+Ne)===$e?this._options.noTransitionAfterReload?e.addClass("hold-transition").addClass($e).delay(50).queue((function(){n.default(this).removeClass("hold-transition"),n.default(this).dequeue()})):e.addClass($e):this._options.noTransitionAfterReload?e.addClass("hold-transition").removeClass($e).delay(50).queue((function(){n.default(this).removeClass("hold-transition"),n.default(this).dequeue()})):e.removeClass($e)}},t._init=function(){var e=this;this.remember(),this.autoCollapse(),n.default(window).resize((function(){e.autoCollapse(!0)}))},t._addOverlay=function(){var e=this,t=n.default("<div />",{id:"sidebar-overlay"});t.on("click",(function(){e.collapse()})),n.default(".wrapper").append(t)},e._jQueryInterface=function(t){return this.each((function(){var a=n.default(this).data(Oe),i=n.default.extend({},Ge,n.default(this).data());a||(a=new e(this,i),n.default(this).data(Oe,a)),"string"==typeof t&&/collapse|expand|toggle/.test(t)&&a[t]()}))},e}();n.default(document).on("click",Ue,(function(e){e.preventDefault();var t=e.currentTarget;"pushmenu"!==n.default(t).data("widget")&&(t=n.default(t).closest(Ue)),Ke._jQueryInterface.call(n.default(t),"toggle")})),n.default(window).on("load",(function(){Ke._jQueryInterface.call(n.default(Ue))})),n.default.fn[qe]=Ke._jQueryInterface,n.default.fn[qe].Constructor=Ke,n.default.fn[qe].noConflict=function(){return n.default.fn[qe]=Pe,Ke._jQueryInterface};var Xe="SidebarSearch",Ye="lte.sidebar-search",Ze=n.default.fn[Xe],et="sidebar-search-open",tt="fa-search",at="fa-times",nt="sidebar-search-results",it="list-group",ot='[data-widget="sidebar-search"]',lt=ot+" .form-control",st=ot+" .btn",rt=st+" i",dt=".sidebar-search-results",ft=".sidebar-search-results .list-group",ut={arrowSign:"->",minLength:3,maxResults:7,highlightName:!0,highlightPath:!1,highlightClass:"text-light",notFoundText:"No element found!"},ct=[],ht=function(){function e(e,t){this.element=e,this.options=n.default.extend({},ut,t),this.items=[]}var a=e.prototype;return a.init=function(){var e=this;0!==n.default(ot).length&&(0===n.default(ot).next(dt).length&&n.default(ot).after(n.default("<div />",{class:nt})),0===n.default(dt).children(".list-group").length&&n.default(dt).append(n.default("<div />",{class:it})),this._addNotFound(),n.default(".main-sidebar .nav-sidebar").children().each((function(t,a){e._parseItem(a)})))},a.search=function(){var e=this,t=n.default(lt).val().toLowerCase();if(t.length<this.options.minLength)return n.default(ft).empty(),this._addNotFound(),void this.close();var a=ct.filter((function(e){return e.name.toLowerCase().includes(t)})),i=n.default(a.slice(0,this.options.maxResults));n.default(ft).empty(),0===i.length?this._addNotFound():i.each((function(t,a){n.default(ft).append(e._renderItem(escape(a.name),encodeURI(a.link),a.path))})),this.open()},a.open=function(){n.default(ot).parent().addClass(et),n.default(rt).removeClass(tt).addClass(at)},a.close=function(){n.default(ot).parent().removeClass(et),n.default(rt).removeClass(at).addClass(tt)},a.toggle=function(){n.default(ot).parent().hasClass(et)?this.close():this.open()},a._parseItem=function(e,t){var a=this;if(void 0===t&&(t=[]),!n.default(e).hasClass("nav-header")){var i={},o=n.default(e).clone().find("> .nav-link"),l=n.default(e).clone().find("> .nav-treeview"),s=o.attr("href"),r=o.find("p").children().remove().end().text();if(i.name=this._trimText(r),i.link=s,i.path=t,0===l.length)ct.push(i);else{var d=i.path.concat([i.name]);l.children().each((function(e,t){a._parseItem(t,d)}))}}},a._trimText=function(e){return t.trim(e.replace(/(\r\n|\n|\r)/gm," "))},a._renderItem=function(e,t,a){var i=this;if(a=a.join(" "+this.options.arrowSign+" "),e=unescape(e),t=decodeURI(t),this.options.highlightName||this.options.highlightPath){var o=n.default(lt).val().toLowerCase(),l=new RegExp(o,"gi");this.options.highlightName&&(e=e.replace(l,(function(e){return'<strong class="'+i.options.highlightClass+'">'+e+"</strong>"}))),this.options.highlightPath&&(a=a.replace(l,(function(e){return'<strong class="'+i.options.highlightClass+'">'+e+"</strong>"})))}var s=n.default("<a/>",{href:t,class:"list-group-item"}),r=n.default("<div/>",{class:"search-title"}).html(e),d=n.default("<div/>",{class:"search-path"}).html(a);return s.append(r).append(d),s},a._addNotFound=function(){n.default(ft).append(this._renderItem(this.options.notFoundText,"#",[]))},e._jQueryInterface=function(t){var a=n.default(this).data(Ye);a||(a=n.default(this).data());var i=n.default.extend({},ut,"object"==typeof t?t:a),o=new e(n.default(this),i);n.default(this).data(Ye,"object"==typeof t?t:a),"string"==typeof t&&/init|toggle|close|open|search/.test(t)?o[t]():o.init()},e}();n.default(document).on("click",st,(function(e){e.preventDefault(),ht._jQueryInterface.call(n.default(ot),"toggle")})),n.default(document).on("keyup",lt,(function(e){return 38==e.keyCode?(e.preventDefault(),void n.default(ft).children().last().focus()):40==e.keyCode?(e.preventDefault(),void n.default(ft).children().first().focus()):void setTimeout((function(){ht._jQueryInterface.call(n.default(ot),"search")}),100)})),n.default(document).on("keydown",ft,(function(e){var t=n.default(":focus");38==e.keyCode&&(e.preventDefault(),t.is(":first-child")?t.siblings().last().focus():t.prev().focus()),40==e.keyCode&&(e.preventDefault(),t.is(":last-child")?t.siblings().first().focus():t.next().focus())})),n.default(window).on("load",(function(){ht._jQueryInterface.call(n.default(ot),"init")})),n.default.fn[Xe]=ht._jQueryInterface,n.default.fn[Xe].Constructor=ht,n.default.fn[Xe].noConflict=function(){return n.default.fn[Xe]=Ze,ht._jQueryInterface};var gt="NavbarSearch",pt="lte.navbar-search",mt=n.default.fn[gt],vt='[data-widget="navbar-search"]',_t=".form-control",bt="navbar-search-open",yt={resetOnClose:!0,target:".navbar-search-block"},wt=function(){function e(e,t){this._element=e,this._config=n.default.extend({},yt,t)}var t=e.prototype;return t.open=function(){n.default(this._config.target).css("display","flex").hide().fadeIn().addClass(bt),n.default(this._config.target+" "+_t).focus()},t.close=function(){n.default(this._config.target).fadeOut().removeClass(bt),this._config.resetOnClose&&n.default(this._config.target+" "+_t).val("")},t.toggle=function(){n.default(this._config.target).hasClass(bt)?this.close():this.open()},e._jQueryInterface=function(t){return this.each((function(){var a=n.default(this).data(pt),i=n.default.extend({},yt,n.default(this).data());if(a||(a=new e(this,i),n.default(this).data(pt,a)),!/toggle|close|open/.test(t))throw new Error("Undefined method "+t);a[t]()}))},e}();n.default(document).on("click",vt,(function(e){e.preventDefault();var t=n.default(e.currentTarget);"navbar-search"!==t.data("widget")&&(t=t.closest(vt)),wt._jQueryInterface.call(t,"toggle")})),n.default.fn[gt]=wt._jQueryInterface,n.default.fn[gt].Constructor=wt,n.default.fn[gt].noConflict=function(){return n.default.fn[gt]=mt,wt._jQueryInterface};var Ct=n.default.fn.Toasts,xt="topRight",It="topLeft",Tt="bottomRight",St="bottomLeft",jt={position:xt,fixed:!0,autohide:!1,autoremove:!0,delay:1e3,fade:!0,icon:null,image:null,imageAlt:null,imageHeight:"25px",title:null,subtitle:null,close:!0,body:null,class:null},kt=function(){function e(e,t){this._config=t,this._prepareContainer(),n.default("body").trigger(n.default.Event("init.lte.toasts"))}var t=e.prototype;return t.create=function(){var e=n.default('<div class="toast" role="alert" aria-live="assertive" aria-atomic="true"/>');e.data("autohide",this._config.autohide),e.data("animation",this._config.fade),this._config.class&&e.addClass(this._config.class),this._config.delay&&500!=this._config.delay&&e.data("delay",this._config.delay);var t=n.default('<div class="toast-header">');if(null!=this._config.image){var a=n.default("<img />").addClass("rounded mr-2").attr("src",this._config.image).attr("alt",this._config.imageAlt);null!=this._config.imageHeight&&a.height(this._config.imageHeight).width("auto"),t.append(a)}if(null!=this._config.icon&&t.append(n.default("<i />").addClass("mr-2").addClass(this._config.icon)),null!=this._config.title&&t.append(n.default("<strong />").addClass("mr-auto").html(this._config.title)),null!=this._config.subtitle&&t.append(n.default("<small />").html(this._config.subtitle)),1==this._config.close){var i=n.default('<button data-dismiss="toast" />').attr("type","button").addClass("ml-2 mb-1 close").attr("aria-label","Close").append('<span aria-hidden="true">×</span>');null==this._config.title&&i.toggleClass("ml-2 ml-auto"),t.append(i)}e.append(t),null!=this._config.body&&e.append(n.default('<div class="toast-body" />').html(this._config.body)),n.default(this._getContainerId()).prepend(e);var o=n.default("body");o.trigger(n.default.Event("created.lte.toasts")),e.toast("show"),this._config.autoremove&&e.on("hidden.bs.toast",(function(){n.default(this).delay(200).remove(),o.trigger(n.default.Event("removed.lte.toasts"))}))},t._getContainerId=function(){return this._config.position==xt?"#toastsContainerTopRight":this._config.position==It?"#toastsContainerTopLeft":this._config.position==Tt?"#toastsContainerBottomRight":this._config.position==St?"#toastsContainerBottomLeft":void 0},t._prepareContainer=function(){if(0===n.default(this._getContainerId()).length){var e=n.default("<div />").attr("id",this._getContainerId().replace("#",""));this._config.position==xt?e.addClass("toasts-top-right"):this._config.position==It?e.addClass("toasts-top-left"):this._config.position==Tt?e.addClass("toasts-bottom-right"):this._config.position==St&&e.addClass("toasts-bottom-left"),n.default("body").append(e)}this._config.fixed?n.default(this._getContainerId()).addClass("fixed"):n.default(this._getContainerId()).removeClass("fixed")},e._jQueryInterface=function(t,a){return this.each((function(){var i=n.default.extend({},jt,a),o=new e(n.default(this),i);"create"===t&&o[t]()}))},e}();n.default.fn.Toasts=kt._jQueryInterface,n.default.fn.Toasts.Constructor=kt,n.default.fn.Toasts.noConflict=function(){return n.default.fn.Toasts=Ct,kt._jQueryInterface};var Qt="TodoList",Ht="lte.todolist",zt=n.default.fn[Qt],Ft="done",Et={onCheck:function(e){return e},onUnCheck:function(e){return e}},Lt=function(){function e(e,t){this._config=t,this._element=e,this._init()}var t=e.prototype;return t.toggle=function(e){e.parents("li").toggleClass(Ft),n.default(e).prop("checked")?this.check(e):this.unCheck(n.default(e))},t.check=function(e){this._config.onCheck.call(e)},t.unCheck=function(e){this._config.onUnCheck.call(e)},t._init=function(){var e=this,t=this._element;t.find("input:checkbox:checked").parents("li").toggleClass(Ft),t.on("change","input:checkbox",(function(t){e.toggle(n.default(t.target))}))},e._jQueryInterface=function(t){return this.each((function(){var a=n.default(this).data(Ht);a||(a=n.default(this).data());var i=n.default.extend({},Et,"object"==typeof t?t:a),o=new e(n.default(this),i);n.default(this).data(Ht,"object"==typeof t?t:a),"init"===t&&o[t]()}))},e}();n.default(window).on("load",(function(){Lt._jQueryInterface.call(n.default('[data-widget="todo-list"]'))})),n.default.fn[Qt]=Lt._jQueryInterface,n.default.fn[Qt].Constructor=Lt,n.default.fn[Qt].noConflict=function(){return n.default.fn[Qt]=zt,Lt._jQueryInterface};var Dt="Treeview",Rt="lte.treeview",At=n.default.fn[Dt],Mt=".nav-item",qt=".nav-treeview",Ot=".menu-open",Nt='[data-widget="treeview"]',Pt="menu-open",Ut="menu-is-opening",Bt={trigger:Nt+" .nav-link",animationSpeed:300,accordion:!0,expandSidebar:!1,sidebarButtonSelector:'[data-widget="pushmenu"]'},$t=function(){function e(e,t){this._config=t,this._element=e}var t=e.prototype;return t.init=function(){n.default(".nav-item.menu-open .nav-treeview.menu-open").css("display","block"),this._setupListeners()},t.expand=function(e,t){var a=this,i=n.default.Event("expanded.lte.treeview");if(this._config.accordion){var o=t.siblings(Ot).first(),l=o.find(qt).first();this.collapse(l,o)}t.addClass(Ut),e.stop().slideDown(this._config.animationSpeed,(function(){t.addClass(Pt),n.default(a._element).trigger(i)})),this._config.expandSidebar&&this._expandSidebar()},t.collapse=function(e,t){var a=this,i=n.default.Event("collapsed.lte.treeview");t.removeClass("menu-is-opening menu-open"),e.stop().slideUp(this._config.animationSpeed,(function(){n.default(a._element).trigger(i),e.find(".menu-open > .nav-treeview").slideUp(),e.find(Ot).removeClass("menu-is-opening menu-open")}))},t.toggle=function(e){var t=n.default(e.currentTarget),a=t.parent(),i=a.find("> .nav-treeview");if(i.is(qt)||(a.is(Mt)||(i=a.parent().find("> .nav-treeview")),i.is(qt))){e.preventDefault();var o=t.parents(Mt).first();o.hasClass(Pt)?this.collapse(n.default(i),o):this.expand(n.default(i),o)}},t._setupListeners=function(){var e=this,t=void 0!==this._element.attr("id")?"#"+this._element.attr("id"):"";n.default(document).on("click",""+t+this._config.trigger,(function(t){e.toggle(t)}))},t._expandSidebar=function(){n.default("body").hasClass("sidebar-collapse")&&n.default(this._config.sidebarButtonSelector).PushMenu("expand")},e._jQueryInterface=function(t){return this.each((function(){var a=n.default(this).data(Rt),i=n.default.extend({},Bt,n.default(this).data());a||(a=new e(n.default(this),i),n.default(this).data(Rt,a)),"init"===t&&a[t]()}))},e}();n.default(window).on("load.lte.treeview",(function(){n.default(Nt).each((function(){$t._jQueryInterface.call(n.default(this),"init")}))})),n.default.fn[Dt]=$t._jQueryInterface,n.default.fn[Dt].Constructor=$t,n.default.fn[Dt].noConflict=function(){return n.default.fn[Dt]=At,$t._jQueryInterface},e.CardRefresh=f,e.CardWidget=I,e.ControlSidebar=M,e.DirectChat=P,e.Dropdown=V,e.ExpandableTable=te,e.Fullscreen=re,e.IFrame=Qe,e.Layout=Me,e.NavbarSearch=wt,e.PushMenu=Ke,e.SidebarSearch=ht,e.Toasts=kt,e.TodoList=Lt,e.Treeview=$t,Object.defineProperty(e,"__esModule",{value:!0})}));
| 46,156
| 16,602
|
// @flow
import * as React from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import { createStructuredSelector } from 'reselect';
import Modal from 'react-modal';
import classNames from 'classnames';
import NavBar from '../components/NavBar';
import SearchFilter from '../components/SearchFilter';
import NavBookmark from '../components/NavBookmark';
import SideBar from '../containers/SideBar';
import {
makeSelectAppLayout,
} from '../global/selectors';
import { media, typo } from '../style-utils';
import modalWrapper from './modalWrapper';
import Toast from '../components/Toast';
import DeleteButtonImage from '../images/[email protected]';
Modal.setAppElement('#app');
type Props = {
theme: {
navBarHeight: number,
sideBarMaxWidth: number,
appMaxWidth: number,
},
appLayout: Map<string, any>,
showSideBar: boolean,
theme: any,
};
const SearchFilterModal = styled(modalWrapper)`
&__overlay {
position: fixed;
top: ${(props: Props) => props.theme.navBarHeight}px;
left: 0px;
right: 0px;
bottom: 0px;
background-color: rgba(0, 0, 0, .10);
z-index: ${(props: Props) => props.theme.zIndex.searchFilter};
${media.phone`
top: ${(props: Props) => props.theme.mobileNavBarHeight}px;
`}
}
&__content {
border: none;
right: auto;
bottom: auto;
left: 0;
width: 100%;
margin-right: -50%;
position: relative;
z-index: ${(props: Props) => props.theme.zIndex.searchFilter};
width: 100%;
&:focus {
outline: none;
}
}
`;
const BookmarkModal = styled(modalWrapper)`
&__overlay {
position: fixed;
top: ${(props: Props) => props.theme.navBarHeight}px;
left: calc((100vw - ${(props: Props) => props.theme.appMaxWidth}px)/2.0 + 680px);
width: 320px;
height: 360px;
right: 0px;
bottom: 0px;
background-color: rgba(0, 0, 0, .10);
z-index: ${(props: Props) => props.theme.zIndex.bookmark};
${media.tablet`
left: calc(100vw - 460px);
`}
${media.phone`
top: ${(props: Props) => props.theme.mobileNavBarHeight}px;
left: 0;
width: 100vw;
height: 420px;
`}
}
&__content {
border: none;
position: relative;
z-index: ${(props: Props) => props.theme.zIndex.bookmark};
&:focus {
outline: none;
}
}
`;
const Wrapper = styled.div`
width: 100%;
${media.tablet`
margin: 0 auto;
`}
${media.phone`
margin: 0;
`}
`;
const MainContent = styled.div`
min-height: 100%;
min-height: 100vh;
position: relative;
padding-top: ${(props: Props) => props.theme.navBarHeight}px;
margin-left: ${(props: Props) =>
props.showSideBar ?
`${props.theme.sideBarMaxWidth}px` : '0px'};
${media.tablet`
margin-left: ${(props: Props) =>
props.showSideBar ?
`${props.theme.tabletSideBarMaxWidth}px` : '0px'};
`}
${media.phone`
padding-top: ${(props: Props) => props.theme.mobileNavBarHeight}px;
margin-left: 0;
.focusLecture & {
padding-top: 60px;
}
`}
`;
const DeleteButton = styled.img`
width: 20px;
height: 20px;
margin: auto 0;
`;
const CloseButton = ({ closeToast }: { closeToast: Function }) => (
<DeleteButton src={DeleteButtonImage} title="Close" onClick={closeToast} />
);
const GlobalToast = styled(Toast)`
.Toastify & {
top: ${(props: Props) => props.theme.navBarHeight + 20}px;
${media.phone`
top: ${(props: Props) => props.theme.mobileNavBarHeight + 20}px;
`}
&__toast {
min-height: 60px;
padding: 0 24px 0 20px;
background-color: rgba(255,255,255,0.9);
box-shadow: 0 10px 20px 10px rgba(0, 0, 0, 0.08);
${media.phone`
margin: 0 20px;
`}
}
&__body {
${typo.body1}
color: ${(props: Props) => props.theme.color.primary};
}
}
`;
const mapStateToProps = createStructuredSelector({
appLayout: makeSelectAppLayout(),
});
export default (Component: React.ComponentType<Props>) => connect(mapStateToProps)(
(props: Props) => (
<Wrapper className={classNames({ focusLecture: props.appLayout.get('focusLecture') })}>
<NavBar />
{props.appLayout.get('showSideBar') &&
<SideBar />
}
<SearchFilterModal
isOpen={props.appLayout.get('showSearchFilter')}
>
<SearchFilter />
</SearchFilterModal>
<BookmarkModal
isOpen={props.appLayout.get('showBookmark')}
>
<NavBookmark />
</BookmarkModal>
<MainContent showSideBar={props.appLayout.get('showSideBar')}>
<Component {...props} />
</MainContent>
<GlobalToast
position="top-center"
autoClose={5000}
hideProgressBar
closeOnClick
closeButton={<CloseButton />}
/>
</Wrapper>
)
);
| 4,826
| 1,784
|
/**
* Schema.org/PaymentMethod
* A payment method is a standardized procedure for transferring the monetary amount for a purchase. Payment methods are characterized by the legal and technical structures used, and by the organization or group carrying out the transaction.\n\nCommonly used values:\n\n* http://purl.org/goodrelations/v1#ByBankTransferInAdvance\n* http://purl.org/goodrelations/v1#ByInvoice\n* http://purl.org/goodrelations/v1#Cash\n* http://purl.org/goodrelations/v1#CheckInAdvance\n* http://purl.org/goodrelations/v1#COD\n* http://purl.org/goodrelations/v1#DirectDebit\n* http://purl.org/goodrelations/v1#GoogleCheckout\n* http://purl.org/goodrelations/v1#PayPal\n* http://purl.org/goodrelations/v1#PaySwarm
*
* @author schema.org
* @class PaymentMethod
* @module org.schema
*/
module.exports = class PaymentMethod extends EcRemoteLinkedData {
/**
* Constructor, automatically sets @context and @type.
*
* @constructor
*/
constructor() {
super();
this.setContextAndType("http://schema.org/", "PaymentMethod");
}
};
| 1,054
| 362
|
const replayer = require('watchtower-replayer');
const consumeHandler = replayer.createReplayHandler('handler.js', 'consume')
const produceHandler = replayer.createReplayHandler('handler.js', 'produce')
module.exports = {consumeHandler, produceHandler};
if (require.main === module) {
const execId = process.argv[2];
replayer.replayAsyncHandler(execId, produceHandler, 'wtrnrbucket');
}
| 399
| 120
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var LitisconsortePassivo;
(function (LitisconsortePassivo) {
LitisconsortePassivo["Litispas"] = "Litispas";
LitisconsortePassivo["LitPass"] = "LitPass";
LitisconsortePassivo["LitisconsortePassiv"] = "LitisconsortePassiv";
LitisconsortePassivo["LitisconsortePassivo"] = "LitisconsortePassivo";
})(LitisconsortePassivo = exports.LitisconsortePassivo || (exports.LitisconsortePassivo = {}));
//# sourceMappingURL=litisconsorte-passivo.js.map
| 531
| 184
|
const mongoose = require('mongoose');
const { Schema } = mongoose;
const jobSchema = new Schema(
{
id: String,
companyId: { type: String, ref: 'CompanyModel'},
title: String,
description: String
},
{
collection: 'jobs',
versionKey: false
}
);
const companySchema = new Schema(
{
id: String,
name: String,
description: String
},
{
collection: 'companies',
versionKey: false
}
);
const JobModel = mongoose.model('job', jobSchema);
const CompanyModel = mongoose.model('company', companySchema);
module.exports = {
JobModel,
CompanyModel
};
| 666
| 199
|
function DebitPaymentDAO(db){
this.db = db;
this.getByUuid = function(uuid, callback){
if(!uuid) return false;
var sql = "SELECT * FROM debit_payments WHERE uuid = '" + uuid + "'";
this.db.query(sql, function(err, rows, fields){
if(err) callback(err, null);
else if(rows.length == 1) callback(null, rows[0]);
else if(rows.length == 0) callback(null, null);
});
};
this.insert = function(payment, callback){
if(!payment) return false;
var sql = "INSERT INTO debit_payments (uuid, sale, value, card) VALUES ('" + payment.uuid + "', '" + payment.sale + "', " + payment.value + ", '" + payment.card + "')";
this.db.query(sql, function(err, rows, fields){
if(err) callback(err, null);
else callback(null, payment);
});
};
}
module.exports = DebitPaymentDAO;
| 904
| 287
|
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const { Schema } = mongoose;
const userSchema = new Schema({
email: String,
password: String,
resetToken: String,
firstLogin: Date,
lastLogin: Date,
});
userSchema.virtual('jwt').get(() => {
console.log(this.id);
console.log(this.email);
console.log(this.githubUsername);
const jwtToken = jwt.sign({
id: this.id,
email: this.email,
}, process.env.JWT_SECRET, {
expiresIn: 24 * 60 * 60,
});
console.log(jwtToken);
return jwtToken;
});
userSchema.set('toJSON', { virtuals: true });
const User = mongoose.model('User', userSchema);
module.exports = User;
| 671
| 246
|
import * as utils from './index.js';
describe('Top level exports', () => {
test('should export the modules ', () => {
const expectedExports = [
'guid',
'ObjectPath',
'absoluteUrl',
'addServers',
'sortBy',
'writeScript',
'StackManager',
'studyMetadataManager',
// Updates WADO-RS metaDataManager
'updateMetaDataManager',
'DICOMTagDescriptions',
'DicomLoaderService',
'urlUtil'
].sort();
const exports = Object.keys(utils.default).sort();
expect(exports).toEqual(expectedExports);
});
});
| 588
| 183
|
/**
* @author mrdoob / http://mrdoob.com/
*/
import {
BufferAttribute,
BufferGeometry,
InterleavedBuffer,
InterleavedBufferAttribute,
TriangleFanDrawMode,
TriangleStripDrawMode,
TrianglesDrawMode,
Vector2,
Vector3
} from "../../../build/three.module.js";
var BufferGeometryUtils = {
computeTangents: function ( geometry ) {
var index = geometry.index;
var attributes = geometry.attributes;
// based on http://www.terathon.com/code/tangent.html
// (per vertex tangents)
if ( index === null ||
attributes.position === undefined ||
attributes.normal === undefined ||
attributes.uv === undefined ) {
console.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
return;
}
var indices = index.array;
var positions = attributes.position.array;
var normals = attributes.normal.array;
var uvs = attributes.uv.array;
var nVertices = positions.length / 3;
if ( attributes.tangent === undefined ) {
geometry.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
}
var tangents = attributes.tangent.array;
var tan1 = [], tan2 = [];
for ( var i = 0; i < nVertices; i ++ ) {
tan1[ i ] = new Vector3();
tan2[ i ] = new Vector3();
}
var vA = new Vector3(),
vB = new Vector3(),
vC = new Vector3(),
uvA = new Vector2(),
uvB = new Vector2(),
uvC = new Vector2(),
sdir = new Vector3(),
tdir = new Vector3();
function handleTriangle( a, b, c ) {
vA.fromArray( positions, a * 3 );
vB.fromArray( positions, b * 3 );
vC.fromArray( positions, c * 3 );
uvA.fromArray( uvs, a * 2 );
uvB.fromArray( uvs, b * 2 );
uvC.fromArray( uvs, c * 2 );
vB.sub( vA );
vC.sub( vA );
uvB.sub( uvA );
uvC.sub( uvA );
var r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
// silently ignore degenerate uv triangles having coincident or colinear vertices
if ( ! isFinite( r ) ) return;
sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
tan1[ a ].add( sdir );
tan1[ b ].add( sdir );
tan1[ c ].add( sdir );
tan2[ a ].add( tdir );
tan2[ b ].add( tdir );
tan2[ c ].add( tdir );
}
var groups = geometry.groups;
if ( groups.length === 0 ) {
groups = [ {
start: 0,
count: indices.length
} ];
}
for ( var i = 0, il = groups.length; i < il; ++ i ) {
var group = groups[ i ];
var start = group.start;
var count = group.count;
for ( var j = start, jl = start + count; j < jl; j += 3 ) {
handleTriangle(
indices[ j + 0 ],
indices[ j + 1 ],
indices[ j + 2 ]
);
}
}
var tmp = new Vector3(), tmp2 = new Vector3();
var n = new Vector3(), n2 = new Vector3();
var w, t, test;
function handleVertex( v ) {
n.fromArray( normals, v * 3 );
n2.copy( n );
t = tan1[ v ];
// Gram-Schmidt orthogonalize
tmp.copy( t );
tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
// Calculate handedness
tmp2.crossVectors( n2, t );
test = tmp2.dot( tan2[ v ] );
w = ( test < 0.0 ) ? - 1.0 : 1.0;
tangents[ v * 4 ] = tmp.x;
tangents[ v * 4 + 1 ] = tmp.y;
tangents[ v * 4 + 2 ] = tmp.z;
tangents[ v * 4 + 3 ] = w;
}
for ( var i = 0, il = groups.length; i < il; ++ i ) {
var group = groups[ i ];
var start = group.start;
var count = group.count;
for ( var j = start, jl = start + count; j < jl; j += 3 ) {
handleVertex( indices[ j + 0 ] );
handleVertex( indices[ j + 1 ] );
handleVertex( indices[ j + 2 ] );
}
}
},
/**
* @param {Array<BufferGeometry>} geometries
* @param {Boolean} useGroups
* @return {BufferGeometry}
*/
mergeBufferGeometries: function ( geometries, useGroups ) {
var isIndexed = geometries[ 0 ].index !== null;
var attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) );
var morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) );
var attributes = {};
var morphAttributes = {};
var morphTargetsRelative = geometries[ 0 ].morphTargetsRelative;
var mergedGeometry = new BufferGeometry();
var offset = 0;
for ( var i = 0; i < geometries.length; ++ i ) {
var geometry = geometries[ i ];
// ensure that all geometries are indexed, or none
if ( isIndexed !== ( geometry.index !== null ) ) return null;
// gather attributes, exit early if they're different
for ( var name in geometry.attributes ) {
if ( ! attributesUsed.has( name ) ) return null;
if ( attributes[ name ] === undefined ) attributes[ name ] = [];
attributes[ name ].push( geometry.attributes[ name ] );
}
// gather morph attributes, exit early if they're different
if ( morphTargetsRelative !== geometry.morphTargetsRelative ) return null;
for ( var name in geometry.morphAttributes ) {
if ( ! morphAttributesUsed.has( name ) ) return null;
if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = [];
morphAttributes[ name ].push( geometry.morphAttributes[ name ] );
}
// gather .userData
mergedGeometry.userData.mergedUserData = mergedGeometry.userData.mergedUserData || [];
mergedGeometry.userData.mergedUserData.push( geometry.userData );
if ( useGroups ) {
var count;
if ( isIndexed ) {
count = geometry.index.count;
} else if ( geometry.attributes.position !== undefined ) {
count = geometry.attributes.position.count;
} else {
return null;
}
mergedGeometry.addGroup( offset, count, i );
offset += count;
}
}
// merge indices
if ( isIndexed ) {
var indexOffset = 0;
var mergedIndex = [];
for ( var i = 0; i < geometries.length; ++ i ) {
var index = geometries[ i ].index;
for ( var j = 0; j < index.count; ++ j ) {
mergedIndex.push( index.getX( j ) + indexOffset );
}
indexOffset += geometries[ i ].attributes.position.count;
}
mergedGeometry.setIndex( mergedIndex );
}
// merge attributes
for ( var name in attributes ) {
var mergedAttribute = this.mergeBufferAttributes( attributes[ name ] );
if ( ! mergedAttribute ) return null;
mergedGeometry.setAttribute( name, mergedAttribute );
}
// merge morph attributes
for ( var name in morphAttributes ) {
var numMorphTargets = morphAttributes[ name ][ 0 ].length;
if ( numMorphTargets === 0 ) break;
mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {};
mergedGeometry.morphAttributes[ name ] = [];
for ( var i = 0; i < numMorphTargets; ++ i ) {
var morphAttributesToMerge = [];
for ( var j = 0; j < morphAttributes[ name ].length; ++ j ) {
morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] );
}
var mergedMorphAttribute = this.mergeBufferAttributes( morphAttributesToMerge );
if ( ! mergedMorphAttribute ) return null;
mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute );
}
}
return mergedGeometry;
},
/**
* @param {Array<BufferAttribute>} attributes
* @return {BufferAttribute}
*/
mergeBufferAttributes: function ( attributes ) {
var TypedArray;
var itemSize;
var normalized;
var arrayLength = 0;
for ( var i = 0; i < attributes.length; ++ i ) {
var attribute = attributes[ i ];
if ( attribute.isInterleavedBufferAttribute ) return null;
if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
if ( TypedArray !== attribute.array.constructor ) return null;
if ( itemSize === undefined ) itemSize = attribute.itemSize;
if ( itemSize !== attribute.itemSize ) return null;
if ( normalized === undefined ) normalized = attribute.normalized;
if ( normalized !== attribute.normalized ) return null;
arrayLength += attribute.array.length;
}
var array = new TypedArray( arrayLength );
var offset = 0;
for ( var i = 0; i < attributes.length; ++ i ) {
array.set( attributes[ i ].array, offset );
offset += attributes[ i ].array.length;
}
return new BufferAttribute( array, itemSize, normalized );
},
/**
* @param {Array<BufferAttribute>} attributes
* @return {Array<InterleavedBufferAttribute>}
*/
interleaveAttributes: function ( attributes ) {
// Interleaves the provided attributes into an InterleavedBuffer and returns
// a set of InterleavedBufferAttributes for each attribute
var TypedArray;
var arrayLength = 0;
var stride = 0;
// calculate the the length and type of the interleavedBuffer
for ( var i = 0, l = attributes.length; i < l; ++ i ) {
var attribute = attributes[ i ];
if ( TypedArray === undefined ) TypedArray = attribute.array.constructor;
if ( TypedArray !== attribute.array.constructor ) {
console.warn( 'AttributeBuffers of different types cannot be interleaved' );
return null;
}
arrayLength += attribute.array.length;
stride += attribute.itemSize;
}
// Create the set of buffer attributes
var interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride );
var offset = 0;
var res = [];
var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
var setters = [ 'setX', 'setY', 'setZ', 'setW' ];
for ( var j = 0, l = attributes.length; j < l; j ++ ) {
var attribute = attributes[ j ];
var itemSize = attribute.itemSize;
var count = attribute.count;
var iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized );
res.push( iba );
offset += itemSize;
// Move the data for each attribute into the new interleavedBuffer
// at the appropriate offset
for ( var c = 0; c < count; c ++ ) {
for ( var k = 0; k < itemSize; k ++ ) {
iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) );
}
}
}
return res;
},
/**
* @param {Array<BufferGeometry>} geometry
* @return {number}
*/
estimateBytesUsed: function ( geometry ) {
// Return the estimated memory used by this geometry in bytes
// Calculate using itemSize, count, and BYTES_PER_ELEMENT to account
// for InterleavedBufferAttributes.
var mem = 0;
for ( var name in geometry.attributes ) {
var attr = geometry.getAttribute( name );
mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT;
}
var indices = geometry.getIndex();
mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0;
return mem;
},
/**
* @param {BufferGeometry} geometry
* @param {number} tolerance
* @return {BufferGeometry>}
*/
mergeVertices: function ( geometry, tolerance = 1e-4 ) {
tolerance = Math.max( tolerance, Number.EPSILON );
// Generate an index buffer if the geometry doesn't have one, or optimize it
// if it's already available.
var hashToIndex = {};
var indices = geometry.getIndex();
var positions = geometry.getAttribute( 'position' );
var vertexCount = indices ? indices.count : positions.count;
// next value for triangle indices
var nextIndex = 0;
// attributes and new attribute arrays
var attributeNames = Object.keys( geometry.attributes );
var attrArrays = {};
var morphAttrsArrays = {};
var newIndices = [];
var getters = [ 'getX', 'getY', 'getZ', 'getW' ];
// initialize the arrays
for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
var name = attributeNames[ i ];
attrArrays[ name ] = [];
var morphAttr = geometry.morphAttributes[ name ];
if ( morphAttr ) {
morphAttrsArrays[ name ] = new Array( morphAttr.length ).fill().map( () => [] );
}
}
// convert the error tolerance to an amount of decimal places to truncate to
var decimalShift = Math.log10( 1 / tolerance );
var shiftMultiplier = Math.pow( 10, decimalShift );
for ( var i = 0; i < vertexCount; i ++ ) {
var index = indices ? indices.getX( i ) : i;
// Generate a hash for the vertex attributes at the current index 'i'
var hash = '';
for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
var name = attributeNames[ j ];
var attribute = geometry.getAttribute( name );
var itemSize = attribute.itemSize;
for ( var k = 0; k < itemSize; k ++ ) {
// double tilde truncates the decimal value
hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * shiftMultiplier ) },`;
}
}
// Add another reference to the vertex if it's already
// used by another index
if ( hash in hashToIndex ) {
newIndices.push( hashToIndex[ hash ] );
} else {
// copy data to the new index in the attribute arrays
for ( var j = 0, l = attributeNames.length; j < l; j ++ ) {
var name = attributeNames[ j ];
var attribute = geometry.getAttribute( name );
var morphAttr = geometry.morphAttributes[ name ];
var itemSize = attribute.itemSize;
var newarray = attrArrays[ name ];
var newMorphArrays = morphAttrsArrays[ name ];
for ( var k = 0; k < itemSize; k ++ ) {
var getterFunc = getters[ k ];
newarray.push( attribute[ getterFunc ]( index ) );
if ( morphAttr ) {
for ( var m = 0, ml = morphAttr.length; m < ml; m ++ ) {
newMorphArrays[ m ].push( morphAttr[ m ][ getterFunc ]( index ) );
}
}
}
}
hashToIndex[ hash ] = nextIndex;
newIndices.push( nextIndex );
nextIndex ++;
}
}
// Generate typed arrays from new attribute arrays and update
// the attributeBuffers
const result = geometry.clone();
for ( var i = 0, l = attributeNames.length; i < l; i ++ ) {
var name = attributeNames[ i ];
var oldAttribute = geometry.getAttribute( name );
var buffer = new oldAttribute.array.constructor( attrArrays[ name ] );
var attribute = new BufferAttribute( buffer, oldAttribute.itemSize, oldAttribute.normalized );
result.setAttribute( name, attribute );
// Update the attribute arrays
if ( name in morphAttrsArrays ) {
for ( var j = 0; j < morphAttrsArrays[ name ].length; j ++ ) {
var oldMorphAttribute = geometry.morphAttributes[ name ][ j ];
var buffer = new oldMorphAttribute.array.constructor( morphAttrsArrays[ name ][ j ] );
var morphAttribute = new BufferAttribute( buffer, oldMorphAttribute.itemSize, oldMorphAttribute.normalized );
result.morphAttributes[ name ][ j ] = morphAttribute;
}
}
}
// indices
result.setIndex( newIndices );
return result;
},
/**
* @param {BufferGeometry} geometry
* @param {number} drawMode
* @return {BufferGeometry>}
*/
toTrianglesDrawMode: function ( geometry, drawMode ) {
if ( drawMode === TrianglesDrawMode ) {
console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' );
return geometry;
}
if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) {
var index = geometry.getIndex();
// generate index if not present
if ( index === null ) {
var indices = [];
var position = geometry.getAttribute( 'position' );
if ( position !== undefined ) {
for ( var i = 0; i < position.count; i ++ ) {
indices.push( i );
}
geometry.setIndex( indices );
index = geometry.getIndex();
} else {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' );
return geometry;
}
}
//
var numberOfTriangles = index.count - 2;
var newIndices = [];
if ( drawMode === TriangleFanDrawMode ) {
// gl.TRIANGLE_FAN
for ( var i = 1; i <= numberOfTriangles; i ++ ) {
newIndices.push( index.getX( 0 ) );
newIndices.push( index.getX( i ) );
newIndices.push( index.getX( i + 1 ) );
}
} else {
// gl.TRIANGLE_STRIP
for ( var i = 0; i < numberOfTriangles; i ++ ) {
if ( i % 2 === 0 ) {
newIndices.push( index.getX( i ) );
newIndices.push( index.getX( i + 1 ) );
newIndices.push( index.getX( i + 2 ) );
} else {
newIndices.push( index.getX( i + 2 ) );
newIndices.push( index.getX( i + 1 ) );
newIndices.push( index.getX( i ) );
}
}
}
if ( ( newIndices.length / 3 ) !== numberOfTriangles ) {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' );
}
// build final geometry
var newGeometry = geometry.clone();
newGeometry.setIndex( newIndices );
newGeometry.clearGroups();
return newGeometry;
} else {
console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode );
return geometry;
}
}
};
export { BufferGeometryUtils };
| 16,841
| 6,608
|
import { addClass, div, img, p, section, text } from '../builders';
export default function hero() {
const logo = addClass(img('static/fancybear_white.png'), 'logo');;
const the = addClass(p(text('The')), 'hero-text-light');
const fancyBear = addClass(p(text('Fancy Bear')), 'hero-text-bold');
const eateries = addClass(p(text('Eateries')), 'hero-text-light');
const container = addClass(div(logo, the, fancyBear, eateries), 'container');
const heroContent = addClass(div(container), 'hero-content');
return addClass(section(heroContent), 'hero', 'splash');
}
| 582
| 205
|
var namespaceEnergyPlus_1_1HeatingCoils =
[
[ "HeatingCoilEquipConditions", "structEnergyPlus_1_1HeatingCoils_1_1HeatingCoilEquipConditions.html", "structEnergyPlus_1_1HeatingCoils_1_1HeatingCoilEquipConditions" ],
[ "HeatingCoilNumericFieldData", "structEnergyPlus_1_1HeatingCoils_1_1HeatingCoilNumericFieldData.html", "structEnergyPlus_1_1HeatingCoils_1_1HeatingCoilNumericFieldData" ]
];
| 398
| 160
|
/**
* Copyright 2016 The AMP HTML 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.
*/
import {
calculateEntryPointScriptUrl,
calculateExtensionScriptUrl,
parseExtensionUrl,
} from '../../src/service/extension-location';
import {initLogConstructor, resetLogConstructorForTesting} from '../../src/log';
describes.sandboxed('Extension Location', {}, () => {
describe('get correct script source', () => {
beforeEach(() => {
// These functions must not rely on log for cases in SW.
resetLogConstructorForTesting();
});
afterEach(() => {
initLogConstructor();
});
it('with local mode', () => {
window.__AMP_MODE = {rtvVersion: '123'};
const script = calculateExtensionScriptUrl(
{
pathname: 'examples/ads.amp.html',
host: 'localhost:8000',
protocol: 'http:',
},
'amp-ad',
/*opt_extensionVersion*/ undefined,
true
);
expect(script).to.equal(
'http://localhost:8000/dist/rtv/123/v0/amp-ad-0.1.js'
);
});
it('with remote mode', () => {
window.__AMP_MODE = {rtvVersion: '123'};
const script = calculateExtensionScriptUrl(
{
pathname: 'examples/ads.amp.html',
host: 'localhost:8000',
protocol: 'http:',
},
'amp-ad',
/*opt_extensionVersion*/ undefined,
false
);
expect(script).to.equal(
'https://cdn.ampproject.org/rtv/123/v0/amp-ad-0.1.js'
);
});
it('should allow no versions', () => {
window.__AMP_MODE = {rtvVersion: '123'};
const script = calculateExtensionScriptUrl(
{
pathname: 'examples/ads.amp.html',
host: 'localhost:8000',
protocol: 'http:',
},
'no-version',
/* version is empty but defined */ '',
true
);
expect(script).to.equal(
'http://localhost:8000/dist/rtv/123/v0/no-version.js'
);
});
it('should handles single pass experiment', () => {
window.__AMP_MODE = {rtvVersion: '123', singlePassType: 'sp'};
const script = calculateExtensionScriptUrl(
{
pathname: 'examples/ads.amp.html',
host: 'localhost:8000',
protocol: 'http:',
},
'no-version',
/* version is empty but defined */ '',
true
);
expect(script).to.equal(
'http://localhost:8000/dist/rtv/123/sp/v0/no-version.js'
);
});
});
describe('get correct entry point source', () => {
beforeEach(() => {
// These functions must not rely on log for cases in SW.
resetLogConstructorForTesting();
});
afterEach(() => {
initLogConstructor();
});
it('with local mode', () => {
const script = calculateEntryPointScriptUrl(
{
pathname: 'examples/ads.amp.html',
host: 'localhost:8000',
protocol: 'http:',
},
'sw',
true
);
expect(script).to.equal('http://localhost:8000/dist/sw.js');
});
it('with remote mode', () => {
window.__AMP_MODE = {rtvVersion: '123'};
const script = calculateEntryPointScriptUrl(
{
pathname: 'examples/ads.amp.html',
host: 'localhost:8000',
protocol: 'http:',
},
'sw',
/* isLocalDev */ false
);
expect(script).to.equal('https://cdn.ampproject.org/sw.js');
});
it('with remote mode & rtv', () => {
window.__AMP_MODE = {rtvVersion: '123'};
const script = calculateEntryPointScriptUrl(
{
pathname: 'examples/ads.amp.html',
host: 'localhost:8000',
protocol: 'http:',
},
'ww',
/* isLocalDev */ false,
/* opt_rtv */ true
);
expect(script).to.equal('https://cdn.ampproject.org/rtv/123/ww.js');
});
it('should handle single pass experiment', () => {
window.__AMP_MODE = {rtvVersion: '123', singlePassType: 'sp'};
const script = calculateEntryPointScriptUrl(
{
pathname: 'examples/ads.amp.html',
host: 'localhost:8000',
protocol: 'http:',
},
'ww',
/* isLocalDev */ false,
/* opt_rtv */ true
);
expect(script).to.equal('https://cdn.ampproject.org/rtv/123/sp/ww.js');
});
});
describe('get correct URL parts', () => {
it('unversioned urls', () => {
const urlParts = parseExtensionUrl(
'https://cdn.ampproject.org/v0/amp-ad-1.0.js'
);
expect(urlParts.extensionId).to.equal('amp-ad');
expect(urlParts.extensionVersion).to.equal('1.0');
});
it('versioned urls', () => {
const urlParts = parseExtensionUrl(
'https://cdn.ampproject.org/rtv/123/v0/amp-ad-0.1.js'
);
expect(urlParts.extensionId).to.equal('amp-ad');
expect(urlParts.extensionVersion).to.equal('0.1');
});
});
});
| 5,502
| 1,753
|
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import TipImage from '@assets/img/gold-tip.svg';
export default function TipsWidget({ tips }) {
const [active, setActive] = useState(0);
return (
<div>
<div className='pl-2 md:pl-0 mb-8 md:mb-10'>
<h2 className='text-black-900 text-xl font-semibold font-head'>Tips</h2>
</div>
{/** tips container */}
<div className='bg-gray-500 px-6 py-6 rounded-2xl'>
<div className='flex items-center justify-between mb-5 px-2'>
{tips.map(({ title }, index) => (
<h3
key={index + title}
className={`font-bold text-lg text-black-900 ${
index === active ? 'block' : 'hidden'
}`}>
{title}
</h3>
))}
<img src={TipImage} alt='tips' />
</div>
<div>
{tips.map(({ title, description }, index) => (
<p
key={index + title}
className={`text-sm text-black-900 ${
index === active ? 'block' : 'hidden'
}`}>
{description}
</p>
))}
</div>
</div>
{/** tips pagination */}
<div className='px-6 mt-8 flex items-center'>
{tips.map(({ title }, index) => (
<button
type='button'
onClick={() => setActive(index)}
className={`w-10 h-1 mr-3 rounded-lg ${
index === active ? 'bg-primary-900' : 'bg-gray-600'
}`}
/>
))}
<button
type='button'
onClick={() => {
if (active >= tips.length - 1) {
setActive(0);
} else {
setActive(active + 1);
}
}}
className='text-xs text-black-900 font-semibold font-head ml-4'>
Next
</button>
</div>
</div>
);
}
TipsWidget.propTypes = {
tips: PropTypes.arrayOf(PropTypes.object).isRequired,
};
| 2,039
| 645
|
import React, { PropTypes } from 'react';
class Marker extends React.Component {
static propTypes = {
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
owner: PropTypes.object,
units: PropTypes.number
};
render () {
const { x, y, name, owner, units } = this.props;
let circle = null;
if (owner) {
circle = (
<circle
cx={ x }
cy={ y }
fill={ owner.color }
r={ 10 }
/>
);
}
return (
<g>
{ circle }
<text
x={ x }
y={ y }
fill="black"
strokeWidth={ 0 }
fontSize={ 14 }
>
({ units }) { name }
</text>
</g>
);
}
}
export default Marker;
| 1,033
| 272
|
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup Posts Posts
* @ingroup UnaModules
*
* @{
*/
function BxPostsPolls(oOptions)
{
BxBaseModTextPolls.call(this, oOptions);
this._sObjName = oOptions.sObjName == undefined ? 'oBxPostsPolls' : oOptions.sObjName;
}
BxPostsPolls.prototype = Object.create(BxBaseModTextPolls.prototype);
BxPostsPolls.prototype.constructor = BxPostsPolls;
/** @} */
| 478
| 193
|
var e=(e,t,a)=>new Promise(((o,n)=>{var l=e=>{try{i(a.next(e))}catch(t){n(t)}},s=e=>{try{i(a.throw(e))}catch(t){n(t)}},i=e=>e.done?o(e.value):Promise.resolve(e.value).then(l,s);i((a=a.apply(e,t)).next())}));import{ah as t,az as a,au as o}from"./index.44a64fe8.js";import{r as n,a0 as l,u as s,C as i,t as r}from"./vendor.686fd1d4.js";function u(u){const c=n(null),g=n(!1),d=n(null);let p;function h(){const e=s(c);return e||o("The table instance has not been obtained yet, please make sure the table is presented when performing the table operation!"),e}return[function(e,o){l((()=>{c.value=null,g.value=null})),s(g)&&t()&&e===s(c)||(c.value=e,d.value=o,u&&e.setProps(a(u)),g.value=!0,null==p||p(),p=i((()=>u),(()=>{u&&e.setProps(a(u))}),{immediate:!0,deep:!0}))},{reload:t=>e(this,null,(function*(){h().reload(t)})),setProps:e=>{h().setProps(e)},redoHeight:()=>{h().redoHeight()},setLoading:e=>{h().setLoading(e)},getDataSource:()=>h().getDataSource(),getColumns:({ignoreIndex:e=!1}={})=>{const t=h().getColumns({ignoreIndex:e})||[];return r(t)},setColumns:e=>{h().setColumns(e)},setTableData:e=>h().setTableData(e),setPagination:e=>h().setPagination(e),deleteSelectRowByKey:e=>{h().deleteSelectRowByKey(e)},getSelectRowKeys:()=>r(h().getSelectRowKeys()),getSelectRows:()=>r(h().getSelectRows()),clearSelectedRowKeys:()=>{h().clearSelectedRowKeys()},setSelectedRowKeys:e=>{h().setSelectedRowKeys(e)},getPaginationRef:()=>h().getPaginationRef(),getSize:()=>r(h().getSize()),updateTableData:(e,t,a)=>h().updateTableData(e,t,a),updateTableDataRecord:(e,t)=>h().updateTableDataRecord(e,t),getRowSelection:()=>r(h().getRowSelection()),getCacheColumns:()=>r(h().getCacheColumns()),getForm:()=>s(d),setShowPagination:t=>e(this,null,(function*(){h().setShowPagination(t)})),getShowPagination:()=>r(h().getShowPagination()),expandAll:()=>{h().expandAll()},collapseAll:()=>{h().collapseAll()}}]}export{u};
| 1,897
| 781
|
'use strict';
const shared = require('../shared');
module.exports = (sequelize, DataTypes) => {
const ContactUs = sequelize.define('ContactUs', {
subject: DataTypes.STRING,
body: DataTypes.STRING,
...shared.fields
}, {
...shared.options
}
);
ContactUs.associate = function (models) {
// associations can be defined here
ContactUs.belongsTo(models.Users, { as: 'author' });
};
return ContactUs;
};
| 443
| 140
|
import PropTypes from 'prop-types';
import React from 'react';
import { FlatList, View, StyleSheet, Keyboard, TouchableOpacity, Text, ImageBackground } from 'react-native';
import LoadEarlier from './LoadEarlier';
import Message from './Message';
import Color from './Color';
import { warning } from './utils';
const styles = StyleSheet.create({
container: {
flex: 1,
},
containerAlignTop: {
flexDirection: 'row',
alignItems: 'flex-start',
},
contentContainerStyle: {
justifyContent: 'flex-end',
},
headerWrapper: {
flex: 1,
},
listStyle: {
flex: 1,
},
scrollToBottomStyle: {
opacity: 0.8,
position: 'absolute',
right: 10,
bottom: 30,
zIndex: 999,
height: 40,
width: 40,
borderRadius: 20,
backgroundColor: Color.white,
alignItems: 'center',
justifyContent: 'center',
shadowColor: Color.black,
shadowOpacity: 0.5,
shadowOffset: { width: 0, height: 0 },
shadowRadius: 1,
},
});
export default class MessageContainer extends React.PureComponent {
constructor() {
super(...arguments);
this.state = {
showScrollBottom: false,
};
this.attachKeyboardListeners = () => {
const { invertibleScrollViewProps: invertibleProps } = this.props;
if (invertibleProps) {
this.willShowSub = Keyboard.addListener('keyboardWillShow', invertibleProps.onKeyboardWillShow);
this.didShowSub = Keyboard.addListener('keyboardDidShow', invertibleProps.onKeyboardDidShow);
this.willHideSub = Keyboard.addListener('keyboardWillHide', invertibleProps.onKeyboardWillHide);
this.didHideSub = Keyboard.addListener('keyboardDidHide', invertibleProps.onKeyboardDidHide);
}
};
this.detachKeyboardListeners = () => {
const { invertibleScrollViewProps: invertibleProps } = this.props;
this.willShowSub?.remove();
this.didShowSub?.remove();
this.willHideSub?.remove();
this.didHideSub?.remove();
};
this.renderFooter = () => {
if (this.props.renderFooter) {
const footerProps = {
...this.props,
};
return this.props.renderFooter(footerProps);
}
return null;
};
this.renderLoadEarlier = () => {
if (this.props.loadEarlier === true) {
const loadEarlierProps = {
...this.props,
};
if (this.props.renderLoadEarlier) {
return this.props.renderLoadEarlier(loadEarlierProps);
}
return <LoadEarlier {...loadEarlierProps} />;
}
return null;
};
this.scrollToBottom = (animated = true) => {
const { inverted } = this.props;
if (inverted) {
this.scrollTo({ offset: 0, animated });
}
else {
this.props.forwardRef.current.scrollToEnd({ animated });
}
};
this.handleOnScroll = (event) => {
const { nativeEvent: { contentOffset: { y: contentOffsetY }, contentSize: { height: contentSizeHeight }, layoutMeasurement: { height: layoutMeasurementHeight }, }, } = event;
const { scrollToBottomOffset } = this.props;
if (this.props.inverted) {
if (contentOffsetY > scrollToBottomOffset) {
this.setState({ showScrollBottom: true });
}
else {
this.setState({ showScrollBottom: false });
}
}
else {
if (contentOffsetY < scrollToBottomOffset &&
contentSizeHeight - layoutMeasurementHeight > scrollToBottomOffset) {
this.setState({ showScrollBottom: true });
}
else {
this.setState({ showScrollBottom: false });
}
}
};
this.renderRow = ({ item, index }) => {
if (!item._id && item._id !== 0) {
warning('GiftedChat: `_id` is missing for message', JSON.stringify(item));
}
if (!item.user) {
if (!item.system) {
warning('GiftedChat: `user` is missing for message', JSON.stringify(item));
}
item.user = { _id: 0 };
}
const { messages, user, inverted, ...restProps } = this.props;
if (messages && user) {
const previousMessage = (inverted ? messages[index + 1] : messages[index - 1]) || {};
const nextMessage = (inverted ? messages[index - 1] : messages[index + 1]) || {};
const messageProps = {
...restProps,
user,
key: item._id,
currentMessage: item,
previousMessage,
inverted,
nextMessage,
position: item.user._id === user._id ? 'right' : 'left',
};
if (this.props.renderMessage) {
return this.props.renderMessage(messageProps);
}
return <Message {...messageProps} />;
}
return null;
};
this.renderHeaderWrapper = () => (<View style={styles.headerWrapper}>{this.renderLoadEarlier()}</View>);
this.onLayoutList = () => {
if (!this.props.inverted &&
!!this.props.messages &&
this.props.messages.length) {
setTimeout(() => this.scrollToBottom(false), 15 * this.props.messages.length);
}
};
this.keyExtractor = (item) => `${item._id}`;
}
componentDidMount() {
if (this.props.messages && this.props.messages.length === 0) {
this.attachKeyboardListeners();
}
}
componentWillUnmount() {
this.detachKeyboardListeners();
}
componentDidUpdate(prevProps) {
if (prevProps.messages &&
prevProps.messages.length === 0 &&
this.props.messages &&
this.props.messages.length > 0) {
this.detachKeyboardListeners();
}
else if (prevProps.messages &&
this.props.messages &&
prevProps.messages.length > 0 &&
this.props.messages.length === 0) {
this.attachKeyboardListeners();
}
}
scrollTo(options) {
if (this.props.forwardRef && this.props.forwardRef.current && options) {
this.props.forwardRef.current.scrollToOffset(options);
}
}
renderScrollBottomComponent() {
const { scrollToBottomComponent } = this.props;
if (scrollToBottomComponent) {
return scrollToBottomComponent();
}
return <Text>V</Text>;
}
renderScrollToBottomWrapper() {
const propsStyle = this.props.scrollToBottomStyle || {};
return (<View style={[styles.scrollToBottomStyle, propsStyle]}>
<TouchableOpacity onPress={() => this.scrollToBottom()} hitSlop={{ top: 5, left: 5, right: 5, bottom: 5 }}>
{this.renderScrollBottomComponent()}
</TouchableOpacity>
</View>);
}
render() {
const { inverted } = this.props;
return (<View style={this.props.alignTop ? styles.containerAlignTop : styles.container}>
{this.state.showScrollBottom && this.props.scrollToBottom
? this.renderScrollToBottomWrapper()
: null}
<ImageBackground
source={this.props.is_landscape ? (this.props.is_pad ? require('../assets/iPad_landscape.png') : require('../assets/bg_landscape.png')) : (this.props.is_pad ? require('../assets/iPad_portrait.png') : require('../assets/bg_portrait.png'))}
resizeMode="cover" style={{ flex: 1 }} >
<FlatList ListEmptyComponent={this.props.ListEmptyComponent} ref={this.props.forwardRef} extraData={this.props.extraData} keyExtractor={this.keyExtractor} enableEmptySections automaticallyAdjustContentInsets={false} inverted={inverted} data={this.props.messages} style={styles.listStyle} contentContainerStyle={styles.contentContainerStyle} renderItem={this.renderRow} {...this.props.invertibleScrollViewProps} ListFooterComponent={inverted ? this.renderHeaderWrapper : this.renderFooter} ListHeaderComponent={inverted ? this.renderFooter : this.renderHeaderWrapper} onScroll={this.handleOnScroll} scrollEventThrottle={100} onLayout={this.onLayoutList} {...this.props.listViewProps} />
</ImageBackground>
</View>);
}
}
MessageContainer.defaultProps = {
messages: [],
user: {},
renderFooter: null,
renderMessage: null,
onLoadEarlier: () => { },
onQuickReply: () => { },
inverted: true,
loadEarlier: false,
listViewProps: {},
invertibleScrollViewProps: {},
extraData: null,
scrollToBottom: false,
scrollToBottomOffset: 200,
alignTop: false,
scrollToBottomStyle: {},
};
MessageContainer.propTypes = {
messages: PropTypes.arrayOf(PropTypes.object),
user: PropTypes.object,
renderFooter: PropTypes.func,
renderMessage: PropTypes.func,
renderLoadEarlier: PropTypes.func,
onLoadEarlier: PropTypes.func,
listViewProps: PropTypes.object,
inverted: PropTypes.bool,
loadEarlier: PropTypes.bool,
invertibleScrollViewProps: PropTypes.object,
extraData: PropTypes.object,
scrollToBottom: PropTypes.bool,
scrollToBottomOffset: PropTypes.number,
scrollToBottomComponent: PropTypes.func,
alignTop: PropTypes.bool,
};
//# sourceMappingURL=MessageContainer.js.map
| 9,998
| 2,718
|
// cria a conexão persistente
class Observer
{
source = null;
constructor(url) {
this.source = new EventSource(url)
}
add(event, callback) {
this.source.addEventListener(event, (ev)=> {
callback(JSON.parse(ev.data))
});
}
}
/*
var obs = new Observer('src/Observer.php?id=1036220550');
obs.add("keyObserver", function(data) {
console.log("keyObserver", data)
})
*/
| 430
| 152
|
// @flow
import React from 'react';
import { type StoryDecorator } from '@storybook/react';
import { I18nProvider } from '@lingui/react';
const i18nProviderDecorator: StoryDecorator = (story, context) => (
<I18nProvider language="en">{story(context)}</I18nProvider>
);
export default i18nProviderDecorator;
| 311
| 107
|
console.log("Hello");var cubes,list,math,num,number,opposite,race,square,slice=[].slice;number=42;opposite=true;if(opposite){number=-42}square=function(x){return x*x};list=[1,2,3,4,5];math={root:Math.sqrt,square:square,cube:function(x){return x*square(x)}};race=function(){var runners,winner;winner=arguments[0],runners=2<=arguments.length?slice.call(arguments,1):[];return print(winner,runners)};if(typeof elvis!=="undefined"&&elvis!==null){alert("I knew it!")}cubes=function(){var i,len,results;results=[];for(i=0,len=list.length;i<len;i++){num=list[i];results.push(math.cube(num))}return results}();var dom=React.createElement;ReactDOM.render(dom("h1",null,"Hello,",dom("em",null,"world!")," ",dom("button",{className:"btn btn-primary"},"OK")),document.getElementById("main"));
| 782
| 290
|
import {URL_VIEWS} from "./conf.js";
function addTemplateToElement(element,template) {
element.innerHTML=template;
}
function loadTemplateToElement(path,element) {
getTemplate(path)
.then(res=>{
if(res.ok){
res.text()
.then(template=>{
addTemplateToElement(element,template);
console.log(template);
})
.catch(err=>{
console.log(err);
});
}
})
.catch(err=>{
console.log(err);
});
}
function deleteRequest(url) {
return fetch(url,{
method:"DELETE",
headers: {
'Content-Type': 'application/json'
},
body: null
});
}
function post(url, data,token) {
return fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
'X-CSRF-TOKEN': token
},
body: JSON.stringify(data),
});
}
function postFormData(url,data,token) {
return fetch(url, {
method: "POST",
headers:{
'X-CSRF-TOKEN': token
},
body:data
});
}
function get(url) {
return fetch(url);
}
function getTemplate(path) {
var newPath=URL_VIEWS+path;
return get(newPath);
}
function createCustomElement(element, attributes, children) {
let customElement = document.createElement(element);
if (children !== undefined) {
children.forEach((el) => {
if (el.nodeType) {
if (el.nodeType === 1 || el.nodeType === 11)
customElement.appendChild(el);
} else {
customElement.innerHTML += el;
}
});
}
addAttributes(customElement, attributes);
return customElement;
}
function addAttributes(element, attrObj) {
for (const attr in attrObj) {
if (attrObj.hasOwnProperty(attr)) {
element.setAttribute(attr, attrObj[attr]);
}
}
}
function buildModal(params) {
for (const property in params) {
if (Object.hasOwnProperty.call(params, property)) {
const value = params[property];
if(property){
if(typeof value ==="function"){
//Ejecuta la funcion pasada a la propiedad
value.g;
}
}
}
}
//Crear contenido interno
const modalContentEl = createCustomElement(
"div",
{
id: "modal",
class: "modal",
},
[content]
);
//Crear contenedor principal
const modalContainerEl = createCustomElement(
"div",
{
id: "modal-container",
class: "modal-container",
},
[modalContentEl]
);
//crear contenedor para boton de cancelar y guardar
const saveButton=createCustomElement("button",{
id:"btn-save",
class:"btn"
},[]);
const cancelButton=createCustomElement("button",{
id:"btn-cancel",
class:"btn"
});
const modalButtonsContainer=createCustomElement("div",{
id:"modalButtons-container",
class:"modalButtons-container"
},[cancelButton,saveButton]);
//document.body.appendChild(modalContainerEl);
}
function formatoFecha(fecha, formato) {
const map = {
dd: fecha.getDate(),
mm: fecha.getMonth() + 1,
yy: fecha.getFullYear().toString().slice(-2),
yyyy: fecha.getFullYear(),
};
return formato.replace(/dd|mm|yy|yyy/gi, (matched) => map[matched]);
}
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
export { getTemplate, post,postFormData, get,
createCustomElement,loadTemplateToElement,
buildModal,formatoFecha,dataURLtoFile,
deleteRequest
};
| 3,602
| 1,223
|
var KEY = 'store';
var dottie = require('dottie');
var localStorage = typeof window === 'undefined' ? null : window.localStorage;
if (!localStorage) {
console.log('Mocking localStorage-api');
localStorage = {
getItem: function getItem(key) {},
setItem: function setItem(key, value) {},
removeItem: function removeItem(key) {}
};
}
module.exports = Store;
function Store() {
this.storageKey = KEY;
this.data = {};
this.load();
}
Store.prototype.load = function () {
if (this._loaded) return Promise.resolve(this.data);
var self = this;
return new Promise(function (resolve, reject) {
console.log('store.load');
self.data = JSON.parse(localStorage.getItem(self.storageKey) || '{}') || {};
resolve(self.data);
});
};
Store.prototype.save = function () {
var self = this;
return new Promise(function (resolve, reject) {
console.log('store.save');
localStorage.setItem(self.storageKey, JSON.stringify(self.data));
resolve();
});
};
//
Store.prototype.get = function (key) {
var self = this;
return this.load().then(function (data) {
console.log('store.get', key, data);
return dottie.get(data, key);
});
};
Store.prototype.set = function (key, data) {
var self = this;
return this.load().then(function () {
dottie.set(self.data, key, data, {
force: true // force overwrite defined non-object keys into objects if needed
});
return self.save().then(function () {
console.log('store.set', key, data, self.data);
return data;
});
});
};
Store.prototype.remove = function (key) {
var self = this;
return this.load().then(function () {
console.log('store.remove', key, self.data);
dottie.set(self.data, key, undefined, {
force: true // force overwrite defined non-object keys into objects if needed
});
return self.save();
});
};
Store.prototype.getKeys = function (key) {
var self = this;
return this.load().then(function () {
var data = dottie.get(self.data, key);
data = Object.keys(data || {});
console.log('store.getKeys', key, data, self.data);
return data;
});
};
| 2,138
| 689
|
describe('App', function () {
beforeEach(function () {
browser.get('/');
});
it('should have a title', function () {
expect(browser.getTitle()).toEqual("Angular 2 App | ng2-webpack");
});
it('should have <header>', function () {
expect(element(by.css('my-app header')).isPresent()).toEqual(true);
});
it('should have <main>', function () {
expect(element(by.css('my-app main')).isPresent()).toEqual(true);
});
it('should have a main title', function () {
expect(element(by.css('main h1')).getText()).toEqual('Hello from Angular 2!');
});
it('should have <footer>', function () {
expect(element(by.css('my-app footer')).getText()).toEqual("Reese Admin");
});
});
| 717
| 240
|
const {
MessageEmbed,
Message
} = require("discord.js");
const config = require("../../botconfig/config.json");
const ee = require("../../botconfig/embed.json");
const settings = require("../../botconfig/settings.json");
const {
check_if_dj
} = require("../../handlers/functions")
module.exports = {
name: "jump", //the command name for the Slash Command
category: "Queue",
aliases: ["jump", "skipto"],
usage: "jump <SongPosition>",
description: "Jumps to a specific Song in the Queue", //the command description for Slash Command Overview
cooldown: 10,
requiredroles: [], //Only allow specific Users with a Role to execute a Command [OPTIONAL]
alloweduserids: [], //Only allow specific Users to execute a Command [OPTIONAL]
run: async (client, message, args) => {
try {
//things u can directly access in an interaction!
const {
member,
channelId,
guildId,
applicationId,
commandName,
deferred,
replied,
ephemeral,
options,
id,
createdTimestamp
} = message;
const {
guild
} = member;
const {
channel
} = member.voice;
if (!channel) return message.reply({
embeds: [
new MessageEmbed().setColor(ee.wrongcolor).setTitle(`${client.allEmojis.x} **Please join ${guild.me.voice.channel ? "__my__" : "a"} VoiceChannel First!**`)
],
})
if (channel.guild.me.voice.channel && channel.guild.me.voice.channel.id != channel.id) {
return message.reply({
embeds: [new MessageEmbed()
.setColor(ee.wrongcolor)
.setFooter(ee.footertext, ee.footericon)
.setTitle(`${client.allEmojis.x} Join __my__ Voice Channel!`)
.setDescription(`<#${guild.me.voice.channel.id}>`)
],
});
}
try {
let newQueue = client.distube.getQueue(guildId);
if (!newQueue || !newQueue.songs || newQueue.songs.length == 0) return message.reply({
embeds: [
new MessageEmbed().setColor(ee.wrongcolor).setTitle(`${client.allEmojis.x} **I am nothing Playing right now!**`)
],
})
if (check_if_dj(client, member, newQueue.songs[0])) {
return message.reply({
embeds: [new MessageEmbed()
.setColor(ee.wrongcolor)
.setFooter(ee.footertext, ee.footericon)
.setTitle(`${client.allEmojis.x} **You are not a DJ and not the Song Requester!**`)
.setDescription(`**DJ-ROLES:**\n> ${check_if_dj(client, member, newQueue.songs[0])}`)
],
});
}
if (!args[0]) {
return message.reply({
embeds: [new MessageEmbed()
.setColor(ee.wrongcolor)
.setFooter(ee.footertext, ee.footericon)
.setTitle(`${client.allEmojis.x} **Please add a Position to jump to!**`)
.setDescription(`**Usage:**\n> \`${client.settings.get(message.guild.id, "prefix")}jump <position>\``)
],
});
}
let Position = Number(args[0])
if (Position > newQueue.songs.length - 1 || Position < 0) return message.reply({
embeds: [
new MessageEmbed().setColor(ee.wrongcolor).setTitle(`${client.allEmojis.x} **The Position must be between \`0\` and \`${newQueue.songs.length - 1}\`!**`)
],
})
await newQueue.jump(Position);
message.reply({
embeds: [new MessageEmbed()
.setColor(ee.color)
.setTimestamp()
.setTitle(`👌 **Jumped to the \`${Position}th\` Song in the Queue!**`)
.setFooter(`💢 Action by: ${member.user.tag}`, member.user.displayAvatarURL({dynamic: true}))]
})
} catch (e) {
console.log(e.stack ? e.stack : e)
message.reply({
content: `${client.allEmojis.x} | Error: `,
embeds: [
new MessageEmbed().setColor(ee.wrongcolor)
.setDescription(`\`\`\`${e}\`\`\``)
],
})
}
} catch (e) {
console.log(String(e.stack).bgRed)
}
}
}
// Copyright © Iconical | Discord Music Bot by Iconical
// Github: https://github.com/iconicaal/
// Github Music-Bot Repository: https://github.com/iconicaal/Icosical
| 3,916
| 1,700
|
"use strict";
const path = require('path');
class BundlesServer {
constructor() {
this.bundles = [];
this.bundleBykey = {};
this.backendUrl = `https://${serverConfig.ip}:${serverConfig.port}`;
}
initialize(sessionID) {
for (const i in res.bundles) {
if(!("manifest" in res.bundles[i])) {
continue;
}
let manifestPath = res.bundles[i].manifest;
let manifest = fileIO.readParsed(manifestPath).manifest;
let modName = res.bundles[i].manifest.split("/")[2];
let bundleDir = "";
let manifestPathSplit = manifestPath.split("/");
if(manifestPathSplit[3] === "res" && manifestPathSplit[4] === "bundles" && manifestPathSplit[6] === "manifest.json" ) {
bundleDir = `${modName}/res/bundles/${manifestPathSplit[5]}/`;
}
for (const j in manifest) {
let info = manifest[j];
let dependencyKeys = ("dependencyKeys" in info) ? info.dependencyKeys : [];
let httpPath = this.getHttpPath(bundleDir, info.key);
let filePath = ("path" in info) ? info.path : this.getFilePath(bundleDir, info.key);
let bundle = {
"key": info.key,
"path": httpPath,
"filePath" : filePath,
"dependencyKeys": dependencyKeys
}
this.bundles.push(bundle);
this.bundleBykey[info.key] = bundle;
}
}
}
getBundles(local) {
let bundles = helper_f.clone(this.bundles);
for (const bundle of bundles) {
if(local) {
bundle.path = bundle.filePath;
}
delete bundle.filePath;
}
return bundles;
}
getBundleByKey(key, local) {
let bundle = helper_f.clone(this.bundleBykey[key]);
if(local) {
bundle.path = bundle.filePath;
}
delete bundle.filePath;
return bundle;
}
getFilePath(bundleDir, key) {
return `${internal.path.join(__dirname).split("src")[0]}user/mods/${bundleDir}StreamingAssets/Windows/${key}`.replace(/\\/g, "/");
}
getHttpPath(bundleDir, key) {
return `${this.backendUrl}/files/bundle/${key}`;
}
}
module.exports.handler = new BundlesServer();
| 2,424
| 694
|
import { declare } from "@babel/helper-plugin-utils";
import remapAsyncToGenerator from "@babel/helper-remap-async-to-generator";
import syntaxAsyncGenerators from "@babel/plugin-syntax-async-generators";
import { types as t } from "@babel/core";
import rewriteForAwait from "./for-await";
export default declare(api => {
api.assertVersion(7);
const yieldStarVisitor = {
Function(path) {
path.skip();
},
YieldExpression({ node }, state) {
if (!node.delegate) return;
const callee = state.addHelper("asyncGeneratorDelegate");
node.argument = t.callExpression(callee, [
t.callExpression(state.addHelper("asyncIterator"), [node.argument]),
state.addHelper("awaitAsyncGenerator"),
]);
},
};
const forAwaitVisitor = {
Function(path) {
path.skip();
},
ForOfStatement(path, { file }) {
const { node } = path;
if (!node.await) return;
const build = rewriteForAwait(path, {
getAsyncIterator: file.addHelper("asyncIterator"),
});
const { declar, loop } = build;
const block = loop.body;
// ensure that it's a block so we can take all its statements
path.ensureBlock();
// add the value declaration to the new loop body
if (declar) {
block.body.push(declar);
}
// push the rest of the original loop body onto our new body
block.body = block.body.concat(node.body.body);
t.inherits(loop, node);
t.inherits(loop.body, node.body);
if (build.replaceParent) {
path.parentPath.replaceWithMultiple(build.node);
} else {
path.replaceWithMultiple(build.node);
}
},
};
const visitor = {
Function(path, state) {
if (!path.node.async) return;
path.traverse(forAwaitVisitor, state);
if (!path.node.generator) return;
path.traverse(yieldStarVisitor, state);
// We don't need to pass the noNewArrows assumption, since
// async generators are never arrow functions.
remapAsyncToGenerator(path, {
wrapAsync: state.addHelper("wrapAsyncGenerator"),
wrapAwait: state.addHelper("awaitAsyncGenerator"),
});
},
};
return {
name: "proposal-async-generator-functions",
inherits: syntaxAsyncGenerators.default,
visitor: {
Program(path, state) {
// We need to traverse the ast here (instead of just vising Function
// in the top level visitor) because for-await needs to run before the
// async-to-generator plugin. This is because for-await is transpiled
// using "await" expressions, which are then converted to "yield".
//
// This is bad for performance, but plugin ordering will allow as to
// directly visit Function in the top level visitor.
path.traverse(visitor, state);
},
},
};
});
| 2,879
| 835
|
window.searchData = JSON.parse("{\"kinds\":{\"2\":\"Module\",\"64\":\"Function\",\"128\":\"Class\",\"256\":\"Interface\",\"512\":\"Constructor\",\"1024\":\"Property\",\"2048\":\"Method\",\"65536\":\"Type literal\"},\"rows\":[{\"id\":0,\"kind\":2,\"name\":\"main\",\"url\":\"modules/main.html\",\"classes\":\"tsd-kind-module\"},{\"id\":1,\"kind\":2,\"name\":\"extensions/router\",\"url\":\"modules/extensions_router.html\",\"classes\":\"tsd-kind-module\"},{\"id\":2,\"kind\":256,\"name\":\"RoutingContext\",\"url\":\"interfaces/extensions_router.RoutingContext.html\",\"classes\":\"tsd-kind-interface tsd-parent-kind-module\",\"parent\":\"extensions/router\"},{\"id\":3,\"kind\":1024,\"name\":\"path\",\"url\":\"interfaces/extensions_router.RoutingContext.html#path\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"extensions/router.RoutingContext\"},{\"id\":4,\"kind\":1024,\"name\":\"host\",\"url\":\"interfaces/extensions_router.RoutingContext.html#host\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"extensions/router.RoutingContext\"},{\"id\":5,\"kind\":1024,\"name\":\"route\",\"url\":\"interfaces/extensions_router.RoutingContext.html#route\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"extensions/router.RoutingContext\"},{\"id\":6,\"kind\":1024,\"name\":\"protocol\",\"url\":\"interfaces/extensions_router.RoutingContext.html#protocol\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"extensions/router.RoutingContext\"},{\"id\":7,\"kind\":1024,\"name\":\"query\",\"url\":\"interfaces/extensions_router.RoutingContext.html#query\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"extensions/router.RoutingContext\"},{\"id\":8,\"kind\":1024,\"name\":\"params\",\"url\":\"interfaces/extensions_router.RoutingContext.html#params\",\"classes\":\"tsd-kind-property tsd-parent-kind-interface\",\"parent\":\"extensions/router.RoutingContext\"},{\"id\":9,\"kind\":64,\"name\":\"default\",\"url\":\"modules/extensions_router.html#default\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"extensions/router\"},{\"id\":10,\"kind\":2,\"name\":\"connectors/vue\",\"url\":\"modules/connectors_vue.html\",\"classes\":\"tsd-kind-module\"},{\"id\":11,\"kind\":64,\"name\":\"default\",\"url\":\"modules/connectors_vue.html#default\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"connectors/vue\"},{\"id\":12,\"kind\":2,\"name\":\"connectors/react\",\"url\":\"modules/connectors_react.html\",\"classes\":\"tsd-kind-module\"},{\"id\":13,\"kind\":64,\"name\":\"default\",\"url\":\"modules/connectors_react.html#default\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"connectors/react\"},{\"id\":14,\"kind\":2,\"name\":\"connectors/svelte\",\"url\":\"modules/connectors_svelte.html\",\"classes\":\"tsd-kind-module\"},{\"id\":15,\"kind\":64,\"name\":\"default\",\"url\":\"modules/connectors_svelte.html#default\",\"classes\":\"tsd-kind-function tsd-parent-kind-module\",\"parent\":\"connectors/svelte\"},{\"id\":16,\"kind\":128,\"name\":\"default\",\"url\":\"classes/main.default.html\",\"classes\":\"tsd-kind-class tsd-parent-kind-module\",\"parent\":\"main\"},{\"id\":17,\"kind\":512,\"name\":\"constructor\",\"url\":\"classes/main.default.html#constructor\",\"classes\":\"tsd-kind-constructor tsd-parent-kind-class\",\"parent\":\"main.default\"},{\"id\":18,\"kind\":1024,\"name\":\"middlewares\",\"url\":\"classes/main.default.html#middlewares\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-private\",\"parent\":\"main.default\"},{\"id\":19,\"kind\":1024,\"name\":\"index\",\"url\":\"classes/main.default.html#index\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-private\",\"parent\":\"main.default\"},{\"id\":20,\"kind\":1024,\"name\":\"combiners\",\"url\":\"classes/main.default.html#combiners\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-private\",\"parent\":\"main.default\"},{\"id\":21,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/main.default.html#__type\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"main.default\"},{\"id\":22,\"kind\":1024,\"name\":\"modules\",\"url\":\"classes/main.default.html#modules\",\"classes\":\"tsd-kind-property tsd-parent-kind-class tsd-is-private\",\"parent\":\"main.default\"},{\"id\":23,\"kind\":65536,\"name\":\"__type\",\"url\":\"classes/main.default.html#__type-1\",\"classes\":\"tsd-kind-type-literal tsd-parent-kind-class\",\"parent\":\"main.default\"},{\"id\":24,\"kind\":2048,\"name\":\"generateSubscriptionId\",\"url\":\"classes/main.default.html#generateSubscriptionId\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-is-private\",\"parent\":\"main.default\"},{\"id\":25,\"kind\":2048,\"name\":\"register\",\"url\":\"classes/main.default.html#register\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-has-type-parameter\",\"parent\":\"main.default\"},{\"id\":26,\"kind\":2048,\"name\":\"unregister\",\"url\":\"classes/main.default.html#unregister\",\"classes\":\"tsd-kind-method tsd-parent-kind-class\",\"parent\":\"main.default\"},{\"id\":27,\"kind\":2048,\"name\":\"combine\",\"url\":\"classes/main.default.html#combine\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-has-type-parameter\",\"parent\":\"main.default\"},{\"id\":28,\"kind\":2048,\"name\":\"uncombine\",\"url\":\"classes/main.default.html#uncombine\",\"classes\":\"tsd-kind-method tsd-parent-kind-class\",\"parent\":\"main.default\"},{\"id\":29,\"kind\":2048,\"name\":\"subscribe\",\"url\":\"classes/main.default.html#subscribe\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-has-type-parameter\",\"parent\":\"main.default\"},{\"id\":30,\"kind\":2048,\"name\":\"unsubscribe\",\"url\":\"classes/main.default.html#unsubscribe\",\"classes\":\"tsd-kind-method tsd-parent-kind-class\",\"parent\":\"main.default\"},{\"id\":31,\"kind\":2048,\"name\":\"mutate\",\"url\":\"classes/main.default.html#mutate\",\"classes\":\"tsd-kind-method tsd-parent-kind-class\",\"parent\":\"main.default\"},{\"id\":32,\"kind\":2048,\"name\":\"dispatch\",\"url\":\"classes/main.default.html#dispatch\",\"classes\":\"tsd-kind-method tsd-parent-kind-class\",\"parent\":\"main.default\"},{\"id\":33,\"kind\":2048,\"name\":\"use\",\"url\":\"classes/main.default.html#use\",\"classes\":\"tsd-kind-method tsd-parent-kind-class tsd-has-type-parameter\",\"parent\":\"main.default\"}],\"index\":{\"version\":\"2.3.9\",\"fields\":[\"name\",\"parent\"],\"fieldVectors\":[[\"name/0\",[0,26.391]],[\"parent/0\",[]],[\"name/1\",[1,23.026]],[\"parent/1\",[]],[\"name/2\",[2,31.499]],[\"parent/2\",[1,2.151]],[\"name/3\",[3,31.499]],[\"parent/3\",[4,1.573]],[\"name/4\",[5,31.499]],[\"parent/4\",[4,1.573]],[\"name/5\",[6,31.499]],[\"parent/5\",[4,1.573]],[\"name/6\",[7,31.499]],[\"parent/6\",[4,1.573]],[\"name/7\",[8,31.499]],[\"parent/7\",[4,1.573]],[\"name/8\",[9,31.499]],[\"parent/8\",[4,1.573]],[\"name/9\",[10,18.506]],[\"parent/9\",[1,2.151]],[\"name/10\",[11,26.391]],[\"parent/10\",[]],[\"name/11\",[10,18.506]],[\"parent/11\",[11,2.465]],[\"name/12\",[12,26.391]],[\"parent/12\",[]],[\"name/13\",[10,18.506]],[\"parent/13\",[12,2.465]],[\"name/14\",[13,26.391]],[\"parent/14\",[]],[\"name/15\",[10,18.506]],[\"parent/15\",[13,2.465]],[\"name/16\",[10,18.506]],[\"parent/16\",[0,2.465]],[\"name/17\",[14,31.499]],[\"parent/17\",[15,0.647]],[\"name/18\",[16,31.499]],[\"parent/18\",[15,0.647]],[\"name/19\",[17,31.499]],[\"parent/19\",[15,0.647]],[\"name/20\",[18,31.499]],[\"parent/20\",[15,0.647]],[\"name/21\",[19,26.391]],[\"parent/21\",[15,0.647]],[\"name/22\",[20,31.499]],[\"parent/22\",[15,0.647]],[\"name/23\",[19,26.391]],[\"parent/23\",[15,0.647]],[\"name/24\",[21,31.499]],[\"parent/24\",[15,0.647]],[\"name/25\",[22,31.499]],[\"parent/25\",[15,0.647]],[\"name/26\",[23,31.499]],[\"parent/26\",[15,0.647]],[\"name/27\",[24,31.499]],[\"parent/27\",[15,0.647]],[\"name/28\",[25,31.499]],[\"parent/28\",[15,0.647]],[\"name/29\",[26,31.499]],[\"parent/29\",[15,0.647]],[\"name/30\",[27,31.499]],[\"parent/30\",[15,0.647]],[\"name/31\",[28,31.499]],[\"parent/31\",[15,0.647]],[\"name/32\",[29,31.499]],[\"parent/32\",[15,0.647]],[\"name/33\",[30,31.499]],[\"parent/33\",[15,0.647]]],\"invertedIndex\":[[\"__type\",{\"_index\":19,\"name\":{\"21\":{},\"23\":{}},\"parent\":{}}],[\"combine\",{\"_index\":24,\"name\":{\"27\":{}},\"parent\":{}}],[\"combiners\",{\"_index\":18,\"name\":{\"20\":{}},\"parent\":{}}],[\"connectors/react\",{\"_index\":12,\"name\":{\"12\":{}},\"parent\":{\"13\":{}}}],[\"connectors/svelte\",{\"_index\":13,\"name\":{\"14\":{}},\"parent\":{\"15\":{}}}],[\"connectors/vue\",{\"_index\":11,\"name\":{\"10\":{}},\"parent\":{\"11\":{}}}],[\"constructor\",{\"_index\":14,\"name\":{\"17\":{}},\"parent\":{}}],[\"default\",{\"_index\":10,\"name\":{\"9\":{},\"11\":{},\"13\":{},\"15\":{},\"16\":{}},\"parent\":{}}],[\"dispatch\",{\"_index\":29,\"name\":{\"32\":{}},\"parent\":{}}],[\"extensions/router\",{\"_index\":1,\"name\":{\"1\":{}},\"parent\":{\"2\":{},\"9\":{}}}],[\"extensions/router.routingcontext\",{\"_index\":4,\"name\":{},\"parent\":{\"3\":{},\"4\":{},\"5\":{},\"6\":{},\"7\":{},\"8\":{}}}],[\"generatesubscriptionid\",{\"_index\":21,\"name\":{\"24\":{}},\"parent\":{}}],[\"host\",{\"_index\":5,\"name\":{\"4\":{}},\"parent\":{}}],[\"index\",{\"_index\":17,\"name\":{\"19\":{}},\"parent\":{}}],[\"main\",{\"_index\":0,\"name\":{\"0\":{}},\"parent\":{\"16\":{}}}],[\"main.default\",{\"_index\":15,\"name\":{},\"parent\":{\"17\":{},\"18\":{},\"19\":{},\"20\":{},\"21\":{},\"22\":{},\"23\":{},\"24\":{},\"25\":{},\"26\":{},\"27\":{},\"28\":{},\"29\":{},\"30\":{},\"31\":{},\"32\":{},\"33\":{}}}],[\"middlewares\",{\"_index\":16,\"name\":{\"18\":{}},\"parent\":{}}],[\"modules\",{\"_index\":20,\"name\":{\"22\":{}},\"parent\":{}}],[\"mutate\",{\"_index\":28,\"name\":{\"31\":{}},\"parent\":{}}],[\"params\",{\"_index\":9,\"name\":{\"8\":{}},\"parent\":{}}],[\"path\",{\"_index\":3,\"name\":{\"3\":{}},\"parent\":{}}],[\"protocol\",{\"_index\":7,\"name\":{\"6\":{}},\"parent\":{}}],[\"query\",{\"_index\":8,\"name\":{\"7\":{}},\"parent\":{}}],[\"register\",{\"_index\":22,\"name\":{\"25\":{}},\"parent\":{}}],[\"route\",{\"_index\":6,\"name\":{\"5\":{}},\"parent\":{}}],[\"routingcontext\",{\"_index\":2,\"name\":{\"2\":{}},\"parent\":{}}],[\"subscribe\",{\"_index\":26,\"name\":{\"29\":{}},\"parent\":{}}],[\"uncombine\",{\"_index\":25,\"name\":{\"28\":{}},\"parent\":{}}],[\"unregister\",{\"_index\":23,\"name\":{\"26\":{}},\"parent\":{}}],[\"unsubscribe\",{\"_index\":27,\"name\":{\"30\":{}},\"parent\":{}}],[\"use\",{\"_index\":30,\"name\":{\"33\":{}},\"parent\":{}}]],\"pipeline\":[]}}");
| 10,719
| 4,502
|
import React, { useContext, useEffect } from "react";
import { GlobalContext } from "../context/globalContext";
import Layout from "../components/Layout";
import { Container, Flex } from "../styles/globalStyles";
import {
NavBar,
SwitchButton,
Body,
Heading,
SubPara,
Para,
Content,
} from "../styles/homeStyles";
const Home = () => {
const { theme, themeSwitchHandler } = useContext(GlobalContext);
useEffect(() => {
window.localStorage.setItem("theme", theme);
}, [theme]);
return (
<Layout>
<NavBar>
<Container fluid>
<Flex center>
<SwitchButton>
<input
type='checkbox'
onChange={() =>
themeSwitchHandler(theme === "dark" ? "light" : "dark")
}
/>
<span></span>
</SwitchButton>
</Flex>
</Container>
</NavBar>
<Body>
<Container>
<Heading>Hello</Heading>
<SubPara>
What's up! Toggle the switch above to change the theme
</SubPara>
<Content>
<Container>
<Flex center column>
<Heading>Article</Heading>
<Para>
Lorem, ipsum dolor sit amet consectetur adipisicing elit.
Reprehenderit quis ipsa, sunt, consectetur voluptate dolores
pariatur nisi distinctio iusto vero iure officia. Vero sunt,
ducimus sit eveniet dolor impedit itaque voluptate ipsam!
Omnis totam, beatae dicta fugit praesentium fugiat dolores
laborum, officiis, labore aperiam tempore! Debitis, provident!
Rem, exercitationem enim?
</Para>
</Flex>
</Container>
</Content>
</Container>
</Body>
</Layout>
);
};
export default Home;
| 1,928
| 545
|
const Joi = require('joi')
const fields = {
daysUntilStale: Joi.number()
.description('Number of days of inactivity before an Issue or Pull Request becomes stale'),
daysUntilClose: Joi.alternatives().try(Joi.number(), Joi.boolean().only(false))
.error(() => '"daysUntilClose" must be a number or false')
.description('Number of days of inactivity before a stale Issue or Pull Request is closed. If disabled, issues still need to be closed manually, but will remain marked as stale.'),
exemptLabels: Joi.alternatives().try(Joi.any().valid(null), Joi.array().single())
.description('Issues or Pull Requests with these labels will never be considered stale. Set to `[]` to disable'),
exemptProjects: Joi.boolean()
.description('Set to true to ignore issues in a project (defaults to false)'),
exemptMilestones: Joi.boolean()
.description('Set to true to ignore issues in a milestone (defaults to false)'),
staleLabel: Joi.string()
.description('Label to use when marking as stale'),
markComment: Joi.alternatives().try(Joi.string(), Joi.any().only(false))
.error(() => '"markComment" must be a string or false')
.description('Comment to post when marking as stale. Set to `false` to disable'),
unmarkComment: Joi.alternatives().try(Joi.string(), Joi.boolean().only(false))
.error(() => '"unmarkComment" must be a string or false')
.description('Comment to post when removing the stale label. Set to `false` to disable'),
closeComment: Joi.alternatives().try(Joi.string(), Joi.boolean().only(false))
.error(() => '"closeComment" must be a string or false')
.description('Comment to post when closing a stale Issue or Pull Request. Set to `false` to disable'),
limitPerRun: Joi.number().integer().min(1).max(30)
.error(() => '"limitPerRun" must be an integer between 1 and 30')
.description('Limit the number of actions per hour, from 1-30. Default is 30')
}
const schema = Joi.object().keys({
daysUntilStale: fields.daysUntilStale.default(60),
daysUntilClose: fields.daysUntilClose.default(7),
exemptLabels: fields.exemptLabels.default(['pinned', 'security']),
exemptProjects: fields.exemptProjects.default(false),
exemptMilestones: fields.exemptMilestones.default(false),
staleLabel: fields.staleLabel.default('wontfix'),
markComment: fields.markComment.default(
'This issue has been automatically marked as stale because ' +
'it has not had recent activity. It will be closed if no further ' +
'activity occurs. Thank you for your contributions.'
),
unmarkComment: fields.unmarkComment.default(false),
closeComment: fields.closeComment.default(false),
limitPerRun: fields.limitPerRun.default(30),
perform: Joi.boolean().default(!process.env.DRY_RUN),
only: Joi.any().valid('issues', 'pulls', null).description('Limit to only `issues` or `pulls`'),
pulls: Joi.object().keys(fields),
issues: Joi.object().keys(fields),
_extends: Joi.string().description('Repository to extend settings from')
})
module.exports = schema
| 3,051
| 932
|
(function ($) {
$(document).ready(function(){
if($(window).width() > 767){
$('.home-section').viewportChecker({
classToAdd: 'inView',
offset: '50%'
});
}else{
$('.home-section').viewportChecker({
classToAdd: 'inView',
offset: '30%'
});
}
$('[data-inner-view]').viewportChecker({
classToAdd: 'innerView'
});
$('body').addClass('is-loaded');
$('[data-model-box]').fancybox({
modal: true,
})
});
})(jQuery);
| 616
| 179
|
module.exports = {
list: require('./list'),
details: require('./details'),
dashboard: require('./dashboard')
};
| 118
| 38
|
;
/**
* 原生JavaScript代码实现
* @author SuZhou LichKin Information Technology Co., Ltd.
*/
/**
* 判断是否为JSON对象
* @param json JSON对象
*/
var isJSON = function(json) {
return (typeof json == 'object') && Object.prototype.toString.call(json).toLowerCase() == "[object object]" && !json.length;
};
/**
* 判断是否为空JSON
* @param json JSON对象
*/
var isEmptyJSON = function(json) {
if (isJSON(json)) {
for ( var name in json) {
return false;
}
return true;
}
return false;
};
/**
* 判断是否为字符串
* @param str 字符串
*/
var isString = function(str) {
return typeof str == 'string';
};
/**
* 判断是否为数字
* @param number 数字
*/
var isNumber = function(number) {
return typeof number == 'number';
};
/**
* 判断是否为布尔
* @param boolean 布尔
*/
var isBoolean = function(bool) {
return typeof bool == 'boolean';
};
// BASE64编码正则
var _BASE64_CODE_REGEXP_STR = '([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)';
/**
* 判断是否为BASE64编码
* @param base64 BASE64编码
*/
var isBASE64 = function(base64) {
return new RegExp('^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,' + _BASE64_CODE_REGEXP_STR + '$').test(base64);
};
/**
* 判断是否为BASE64编码
* @param base64 BASE64编码
*/
var isSubBASE64 = function(base64) {
return new RegExp('^' + _BASE64_CODE_REGEXP_STR + '$').test(base64);
};
/**
* 生成随机值
* @param min 最小值
* @param max 最大值
* @return 随机值
*/
var randomInRange = function(min, max) {
return Math.floor(Math.random() * (max + 1 - min) + min);
};
/**
* 显示标准时间格式
* @param time 日期(yyyyMMddHHmmss或yyyyMMddHHmmssSSS)
* @return 标准日期格式(yyyy-MM-dd HH:mm:ss)
*/
var showStandardTime = function(time) {
if (time && (time.length == 14 || time.length == 17)) {
return time.substr(0, 4) + '-' + time.substr(4, 2) + '-' + time.substr(6, 2) + ' ' + time.substr(8, 2) + ':' + time.substr(10, 2) + ':' + time.substr(12, 2);
}
return '';
};
/**
* 时间格式化
* @param fmt 格式化
* @return 格式化后的时间
*/
Date.prototype.format = function(fmt) {
var o = {
"M+" : this.getMonth() + 1,
"d+" : this.getDate(),
"H+" : this.getHours(),
"m+" : this.getMinutes(),
"s+" : this.getSeconds(),
"q+" : Math.floor((this.getMonth() + 3) / 3),
"S" : this.getMilliseconds()
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for ( var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
};
/**
* 重新设置时间
* @param type [string] 格式化单key
* @param cnt [int] 数量
* @return 时间
*/
Date.prototype.reset = function(type, cnt) {
switch (type) {
case 'y':
this.setFullYear(this.getFullYear() + cnt);
break;
case 'M':
this.setMonth(this.getMonth() + cnt);
break;
case 'd':
this.setDate(this.getDate() + cnt);
break;
case 'H':
this.setHours(this.getHours() + cnt);
break;
case 'm':
this.setMinutes(this.getMinutes() + cnt);
break;
case 's':
this.setSeconds(this.getSeconds() + cnt);
break;
case 'S':
this.setMilliseconds(this.getMilliseconds() + cnt);
break;
default:
break;
}
return this;
};
/**
* 当前日期
* @return yyyy-MM-dd
*/
var today = function() {
return new Date().format('yyyy-MM-dd');
};
/**
* 当前日期的上个月日期
* @return yyyy-MM-dd
*/
var lastMonthDay = function() {
return new Date().reset('M', -1).format('yyyy-MM-dd');
};
/**
* 当前日期的下个月日期
* @return yyyy-MM-dd
*/
var nextMonthDay = function() {
return new Date().reset('M', 1).format('yyyy-MM-dd');
};
/**
* 判断字符串开头
*/
String.prototype.startsWith = function(str) {
return new RegExp("^" + str).test(this);
};
/**
* 判断字符串结尾
*/
String.prototype.endsWith = function(str) {
return new RegExp(str + "$").test(this);
};
/**
* 提取整数
*/
String.prototype.extarctInteger = function() {
var arr = this.match(/[\-0-9]/g);
if (Array.isArray(arr)) {
if (arr[0] == '0') {
return '0';
} else if (arr[0] == '-') {
if (arr[1] && arr[1] == '0') {
return '-';
} else {
arr[0] = '';
return '-' + arr.join('').replace(/\-/g, '');
}
} else {
return arr.join('').replace(/\-/g, '');
}
}
return '';
};
/**
* 转换为标准路径,即使用/作为分隔符,并以/开头,不以/结尾。
* @param path 路径
* @return 标准路径
*/
var toStandardPath = function(path) {
if (typeof path == 'undefined' || '' == path || '/' == path) {
return '';
}
path = path.replace(new RegExp("\\\\"), '/');
if (!path.startsWith('/')) {
path = '/' + path;
}
if (path.endsWith('/')) {
path = path.substring(0, path.lastIndexOf('/'));
}
return path;
};
| 4,749
| 2,085
|
"use strict"
const SchemaHelper = require("./SchemaHelper")
/**
*
*/
class schemaValidator {
/**
*
* @param {{[resourceName: string]: import("../types/ResourceConfig").ResourceConfig}} resources
*/
static validate(resources) {
for(const [resourceName, resource] of Object.entries(resources)) {
for(const [attribute, joiSchema] of Object.entries(resource.attributes)) {
if (!SchemaHelper.isRelationship(joiSchema)) return
for(const type of SchemaHelper.relationTypes(joiSchema)) {
if (!resources[type]) {
throw new Error(`'${resourceName}'.'${attribute}' is defined to hold a relation with '${type}', but '${type}' is not a valid resource name!`)
}
}
if (!SchemaHelper.isBelongsToRelationship(joiSchema)) return
const backReference = resources[SchemaHelper.relationTypes(joiSchema)[0]].attributes[SchemaHelper.inverseRelationshipName(joiSchema)]
if (!backReference) {
throw new Error(`'${resourceName}'.'${attribute}' is defined as being a foreign relation to the primary '${types[0]}'.'${foreignRelation}', but that primary relationship does not exist!`)
}
}
}
}
}
module.exports = schemaValidator
| 1,367
| 347
|
export * from './Welcome'
export * from './Logon'
export * from './Confirmation'
export * from './PlantSelect'
export * from './PlantSave'
export * from './UserPlants'
| 167
| 52
|
module.exports = function check(str, bracketsConfig) {
// your solution
const stack = [];
const BRACKETS_PAIR = Object.fromEntries(bracketsConfig);
for (let i = 0; i < str.length; i++) {
let topItem = stack[stack.length - 1];
if (BRACKETS_PAIR[topItem] === str[i]) {
stack.pop();
} else if (BRACKETS_PAIR[str[i]]) {
stack.push(str[i]);
} else {
return false;
}
}
return stack.length === 0;
}
| 444
| 167
|
'use strict';
var TestHelper = require('../../../TestHelper');
var TestContainer = require('mocha-test-container-support');
/* global bootstrapModeler, inject */
var propertiesPanelModule = require('lib'),
domQuery = require('min-dom').query,
domClasses = require('min-dom').classes,
coreModule = require('bpmn-js/lib/core').default,
selectionModule = require('diagram-js/lib/features/selection').default,
modelingModule = require('bpmn-js/lib/features/modeling').default,
propertiesProviderModule = require('lib/provider/bpmn'),
getBusinessObject = require('bpmn-js/lib/util/ModelUtil').getBusinessObject;
describe('process-participant-properties', function() {
var diagramXML = require('./ProcessParticipant.bpmn');
var testModules = [
coreModule, selectionModule, modelingModule,
propertiesPanelModule,
propertiesProviderModule
];
var container;
beforeEach(function() {
container = TestContainer.get(this);
});
beforeEach(bootstrapModeler(diagramXML, {
modules: testModules
}));
beforeEach(inject(function(commandStack, propertiesPanel) {
var undoButton = document.createElement('button');
undoButton.textContent = 'UNDO';
undoButton.addEventListener('click', function() {
commandStack.undo();
});
container.appendChild(undoButton);
propertiesPanel.attachTo(container);
}));
it('should set the isExecutable property of a process', inject(function(propertiesPanel, selection, elementRegistry) {
// given
var shape = elementRegistry.get('Participant_1');
selection.select(shape);
var isExecutable = domQuery('input[name=isExecutable]', propertiesPanel._container),
taskBo = getBusinessObject(shape).get('processRef');
// when
TestHelper.triggerEvent(isExecutable, 'click');
// then
expect(taskBo.get('isExecutable')).to.be.ok;
}));
it('should get the name of a process in a participant', inject(function(propertiesPanel, selection, elementRegistry) {
// given
var shape = elementRegistry.get('_Participant_2');
// when
selection.select(shape);
var name = domQuery('div[data-entry=process-name] div[name=name]', propertiesPanel._container),
shapeBo = getBusinessObject(shape).get('processRef');
// then
expect(shapeBo.get('name')).to.equal(name.textContent);
}));
it('should set the name of a process in a participant', inject(function(propertiesPanel, selection, elementRegistry) {
// given
var shape = elementRegistry.get('_Participant_2');
selection.select(shape);
var name = domQuery('div[data-entry=process-name] div[name=name]', propertiesPanel._container),
shapeBo = getBusinessObject(shape).get('processRef');
// when
TestHelper.triggerValue(name, 'Foo', 'change');
// then
expect(shapeBo.get('name')).to.equal('Foo');
}));
it('should get the id of a process in a participant', inject(function(propertiesPanel, selection, elementRegistry) {
// given
var shape = elementRegistry.get('_Participant_2');
// when
selection.select(shape);
var id = domQuery('input[name=processId]', propertiesPanel._container),
shapeBo = getBusinessObject(shape).get('processRef');
// then
expect(shapeBo.get('id')).to.equal(id.value);
}));
it('should set the id of a process in a participant', inject(function(propertiesPanel, selection, elementRegistry) {
// given
var shape = elementRegistry.get('_Participant_2');
selection.select(shape);
var name = domQuery('input[name=processId]', propertiesPanel._container),
shapeBo = getBusinessObject(shape).get('processRef');
// when
TestHelper.triggerValue(name, 'Foo', 'change');
// then
expect(shapeBo.get('id')).to.equal('Foo');
}));
it('should get the id of the participant', inject(function(propertiesPanel, selection, elementRegistry) {
// given
var shape = elementRegistry.get('_Participant_2');
var participant = getBusinessObject(shape);
// when
selection.select(shape);
// then
var input = domQuery('div[data-entry=id] input[name=id]', propertiesPanel._container);
expect(input.value).to.equal(participant.get('id'));
}));
it('should get the name of the participant', inject(function(propertiesPanel, selection, elementRegistry) {
// given
var shape = elementRegistry.get('_Participant_2');
var participant = getBusinessObject(shape);
// when
selection.select(shape);
// then
var input = domQuery('div[data-entry=name] div[name=name]', propertiesPanel._container);
expect(input.textContent).to.equal(participant.get('name'));
}));
describe('change name of participant', function() {
var participant, textbox;
beforeEach(inject(function(elementRegistry, selection, propertiesPanel) {
// given
var shape = elementRegistry.get('_Participant_2');
selection.select(shape);
participant = getBusinessObject(shape);
textbox = domQuery('div[data-entry=name] div[name=name]');
// when
TestHelper.triggerValue(textbox, 'foo', 'change');
}));
describe('in the DOM', function() {
it('should execute', function() {
// then
expect(textbox.textContent).to.equal('foo');
});
it('should undo', inject(function(commandStack) {
// when
commandStack.undo();
// then
expect(textbox.textContent).to.equal('Pool');
}));
it('should redo', inject(function(commandStack) {
// when
commandStack.undo();
commandStack.redo();
// then
expect(textbox.textContent).to.equal('foo');
}));
});
describe('on the business object', function() {
it('should execute', function() {
// then
expect(participant.get('name')).to.equal('foo');
});
it('should undo', inject(function(commandStack) {
// when
commandStack.undo();
// then
expect(participant.get('name')).to.equal('Pool');
}));
it('should redo', inject(function(commandStack) {
// when
commandStack.undo();
commandStack.redo();
// then
expect(participant.get('name')).to.equal('foo');
}));
});
});
describe('validation errors', function() {
var shape, textField, getTextField;
beforeEach(inject(function(elementRegistry, propertiesPanel, selection) {
shape = elementRegistry.get('_Participant_2');
selection.select(shape);
getTextField = function() {
return domQuery('input[name=processId]', propertiesPanel._container);
};
textField = getTextField();
}));
it('should not be shown if id is valid', function() {
// when
TestHelper.triggerValue(textField, 'Foo', 'change');
// then
expect(domClasses(getTextField()).has('invalid')).to.be.false;
});
it('should be shown if id is invalid', function() {
// when
TestHelper.triggerValue(textField, 'StartEvent_1', 'change');
// then
expect(domClasses(getTextField()).has('invalid')).to.be.true;
});
});
});
| 7,240
| 2,158
|
try {
window.$ = window.jQuery = require('jquery');
} catch (e) {
console.log(e);
}
import Vue from 'vue';
import Cookies from 'js-cookie';
import ElementUI from 'element-ui';
import "./firebase"
import App from './views/App';
import store from './store';
import router from '@/router';
import i18n from './lang'; // Internationalization
import '@/icons'; // icon
import '@/permission'; // permission control
import VCalendar from 'v-calendar';
import * as filters from './filters'; // global filters
import {firestorePlugin} from "vuefire"
Vue.use(firestorePlugin)
Vue.use(ElementUI, {
size: Cookies.get('size') || 'medium', // set element-ui default size
i18n: (key, value) => i18n.t(key, value),
});
// Use v-calendar & v-date-picker components
Vue.use(VCalendar, {
componentPrefix: 'vc', // Use <vc-calendar /> instead of <v-calendar />
});
// register global utility filters.
Object.keys(filters).forEach(key => {
Vue.filter(key, filters[key]);
});
Vue.config.productionTip = false;
new Vue({
el: '#app',
router,
store,
i18n,
render: h => h(App),
});
| 1,087
| 362
|