text
stringlengths 2
1.05M
|
|---|
"use strict";!function(r,i){r(function(){r(".anonymize").each(function(t,n){var n=r(n),a=String(n.attr("data-anonymize")),e=0;n.empty().text(i(function(){var t=a.substr(4*e++,4);return parseInt(t,16)/65536}))})})}(jQuery,sillyName);
|
const fs = require('fs');
const ChromeExtension = require('crx');
/* eslint import/no-unresolved: 0 */
const argv = require('minimist')(process.argv.slice(2));
const name = require('../src/manifest.json').name;
const keyPath = argv.key || 'key.pem';
const existsKey = fs.existsSync(keyPath);
const crx = new ChromeExtension({
appId: argv['app-id'],
codebase: argv.codebase,
privateKey: existsKey ? fs.readFileSync(keyPath) : null
});
crx.load('extension')
.then(() => crx.loadContents())
.then((archiveBuffer) => {
fs.writeFileSync(`${name}.zip`, archiveBuffer);
if (!argv.codebase || !existsKey) return;
crx.pack(archiveBuffer).then((crxBuffer) => {
const updateXML = crx.generateUpdateXML();
fs.writeFileSync('update.xml', updateXML);
fs.writeFileSync(`${name}.crx`, crxBuffer);
});
});
|
var callbackArguments = [];
var argument1 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument3[1] = [843,595,823,0,607,823]
base_0 = 82
argument3[0] = false
return a*b*c/d
};
var argument2 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument4[1] = 7.335461004710814e+307
argument4[0] = {"r":"iT","T":1.3571612592489743e+308,"8.717758929396265e+307":"","":""}
argument4['!j'] = true
return a-b*c+d
};
var argument3 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
base_2[0] = [627,"ZX"]
argument4['w'] = 5e-324
argument5[6] = ""
return a*b+c*d
};
var argument4 = 126;
var argument5 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
base_3[5] = null
base_3[4][3] = null
return a-b*c-d
};
var base_0 = ["zm","c","#","%VWC","<"]
var r_0= undefined
try {
r_0 = base_0.reduceRight(argument1)
}
catch(e) {
r_0= "Error"
}
var base_1 = ["zm","c","#","%VWC","<"]
var r_1= undefined
try {
r_1 = base_1.reduceRight(argument2)
}
catch(e) {
r_1= "Error"
}
var base_2 = ["zm","c","#","%VWC","<"]
var r_2= undefined
try {
r_2 = base_2.reduceRight(argument3,argument4)
}
catch(e) {
r_2= "Error"
}
var base_3 = ["zm","c","#","%VWC","<"]
var r_3= undefined
try {
r_3 = base_3.reduceRight(argument5)
}
catch(e) {
r_3= "Error"
}
function serialize(array){
return array.map(function(a){
if (a === null || a == undefined) return a;
var name = a.constructor.name;
if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String')
return JSON.stringify(a);
return name;
});
}
setTimeout(function(){
require("fs").writeFileSync("./experiments/reduceRight/reduceRightGen/test58.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments}))
},300)
|
import React, {Component} from 'react';
import axios from 'axios';
import {Link} from 'react-router';
class EditItem extends Component {
constructor(props) {
super(props);
this.state = {name: '', price: ''};
// The .bind(this) is to indic that function is about this current component "EditItem"
this.handleChange1 = this.handleChange1.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
axios.get(`http://localhost:8000/api/items/${this.props.params.id}/edit`)
.then(response => {
this.setState({name: response.data.name, price: response.data.price});
})
.catch(function (error) {
console.log(error);
})
}
handleChange1(e) {
this.setState({
name: e.target.value
})
}
handleChange2(e) {
this.setState({
price: e.target.value
})
}
handleSubmit(event) {
event.preventDefault();
const products = {
name: this.state.name,
price: this.state.price
}
let uri = 'http://localhost:8000/api/items/' + this.props.params.id;
axios.patch(uri, products).then((response) => {
this.props.history.push('/display-item');
});
}
render() {
return (
<div>
<h1>Update Item</h1>
<div className="row">
<div className="col-md-10"></div>
<div className="col-md-2">
<Link to="/display-item" className="btn btn-success">Return to Items</Link>
</div>
</div>
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label>Item Name</label>
<input type="text"
className="form-control"
value={this.state.name}
onChange={this.handleChange1}/>
</div>
<div className="form-group">
<label name="product_price">Item Price</label>
<input type="text" className="form-control"
value={this.state.price}
onChange={this.handleChange2}/>
</div>
<div className="form-group">
<button className="btn btn-primary">Update</button>
</div>
</form>
</div>
)
}
}
export default EditItem;
|
import { useState, useEffect } from "react";
import "./styles.css";
//yarn add react-dock, react-dock é a bliblioteca do sidebar, com algumas funções pré defina
import Dock from "react-dock";
import Product from "../product/list";
const Sidebar = () => {
const [opened, setOpened] = useState(false);
//recebendo o chamado para abrir o sidebar
useEffect(() => {
window.addEventListener("openCart", () => {
setOpened(true);
});
}, []);
return (
<Dock
isVisible={opened}
onVisibleChange={(visible) => {
setOpened(visible);
}}
position="right"
>
<div className="container-fluid h-100 pt-4 sidebar">
<h5>Minha Sacola (5)</h5>
<div className="row products">
{[1, 2, 3, 4, 5, 6, 7, 8, 9].map((p) => (
<Product />
))}
</div>
{/* Parte de baixo(botões e informação) do sidebar*/}
<div className="row align-items-end footer ">
<div className="col-12 d-flex justify-content-between align-items-center caixa-total ">
<b className="d-inline-block ">Total</b>
<h3 className="d-inline-block">R$ 90,00</h3>
</div>
<button className="btn btn-block btn-lg btn-secondary rounded-5 h-80 align-items-centers">
Finalizar Compra
</button>
</div>
</div>
</Dock>
);
};
export default Sidebar;
|
"use strict";
if (!require("./is-implemented")()) {
Object.defineProperty(Number, "isNaN", {
value: require("./shim"),
configurable: true,
enumerable: false,
writable: true
});
}
|
/*
Code modified from:
http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
using graphics purchased from vectorstock.com
*/
/* Initialization.
Here, we create and add our "canvas" to the page.
We also load all of our images.
*/
// let canvas;
// let ctx;
var image = new Image();
var imageObstatcle = new Image();
var imageObstatcle2 = new Image();
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// canvas = document.createElement("canvas");
// ctx = canvas.getContext("2d");
// canvas.width = 1600;
// canvas.height = 650;
//document.body.appendChild(canvas);
// function setup() {
// var canvas = createCanvas(100, 100);
// }
//canvas.parent('canvas-holder');
let bgReady, bgReady2, heroReady, monsterReady, imageObstatcleReady;
let bulletReady;
let bulletReady2;
let bulletReady3;
let bullet1Position;
let hero1Position;
let Obstacle3Ready;
let Obstacle3Image;
let imageObstatcle2Ready;
let iObstacle3;
let obtical3 = false;
let bgImage, bgImage2, heroImage, monsterImage;
let bulletImage;
let bulletImage2;
let bulletImage3;
let startTime = Date.now();
const SECONDS_PER_ROUND = 30;
let elapsedTime = 0;
let YouDieStatus;
let GameOverImage;
let bulletOrder = 1;
console.log(bulletOrder);
var AmountBullet = [{ BulletX: 10, BulletY: 10 }, { BulletX: 10, BulletY: 85 }, { BulletX: 10, BulletY: 160 }]
console.log(AmountBullet[0].BulletY);
console.log(AmountBullet[1]);
//console.log(AmountBullet[2].BulletX);
function loadImages() {
image.onload = function() {
let x = 0;
let width = image.width;
let min = 0 - width;
let step = 1;
var loop = function() {
ctx.drawImage(image, x, 0);
ctx.drawImage(image, x + width, 0);
x -= step;
if (x < min) {
x = 0;
}
};
setInterval(loop, 5);
};
image.src = "images/Background.jpg";
heroImage = new Image();
heroImage.onload = function() {
// show the hero image
heroReady = true;
};
heroImage.src = "images/Tank.gif";
monsterImage = new Image();
monsterImage.onload = function() {
// show the monster image
monsterReady = true;
};
monsterImage.src = "images/monster.png";
imageObstatcle = new Image();
imageObstatcle.onload = function() {
// show the monster image
imageObstatcleReady = true;
};
imageObstatcle.src = "images/Monster1.png";
imageObstatcle2 = new Image();
imageObstatcle2.onload = function() {
// show the monster image
imageObstatcle2Ready = true;
};
imageObstatcle2.src = "images/Monster2.png";
Obstacle3Image = new Image();
Obstacle3Image.onload = function() {
// show the monster image
Obstacle3Ready = true;
};
Obstacle3Image.src = "images/Monster3.png";
bulletImage = new Image();
bulletImage.onload = function() {
// show the monster image
bulletReady = true;
};
bulletImage.src = "images/bullet.gif";
bulletImage2 = new Image();
bulletImage2.onload = function() {
// show the monster image
bulletReady2 = true;
};
bulletImage2.src = "images/bullet.gif";
GameOverImage = new Image();
GameOverImage.onload = function() {
// show the monster image
GameOverReady = true;
};
GameOverImage.src = "images/GameOver.png";
}
/**
* Setting up our characters.
*
* Note that heroX represents the X position of our hero.
* heroY represents the Y position.
* We'll need these values to know where to "draw" the hero.
*
* The same applies to the monster.
*/
//let monsterX = 100;
// let monsterY = 100;
let heroX = 50;
let heroY = 460;
let ObstacleX = 1600;
let ObstacleY = 400;
let Obstacle2X = 1300;
let Obstacle2Y = 200;
let Obstacle3X = 1600;
let Obstacle3Y = 430;
let Obstacle3Status = true;
let score = 0;
let bulletFire = false;
let bulletFire2 = false;
let bulletFire3 = false;
let obtical = false;
let GameOverTextReady = false
/**
* Keyboard Listeners
* You can safely ignore this part, for now.
*
* This is just to let JavaScript know when the user has pressed a key.
*/
const keysDown = {};
const keyPress = {}
function setupKeyboardListeners() {
// Check for keys pressed where key represents the keycode captured
// For now, do not worry too much about what's happening here.
addEventListener("keydown", function(key) {
keysDown[key.keyCode] = true;
}, false);
addEventListener("keyup", function(key) {
delete keysDown[key.keyCode];
}, false);
}
/*var down = false;
document.addEventListener('keydown', function() {
if (down) return;
down = true;
// your magic code here
}, false);
document.addEventListener('keyup', function() {
down = false;
}, false); * /
/**
* Update game objects - change player position based on key pressed
* and check to see if the monster has been caught!
*
* If you change the value of 5, the player will move at a different rate.
*/
let time = 0;
function timecounting() {
myTime = setInterval(() => {
time += 1
}, 1000) // every 1 second, it will add 1 into time variable (computer use millisecond so 1000 is 1 second)
}
timecounting();
let GameOver = function() {
ObstacleX = ObstacleX;
ObstacleY = ObstacleY;
Obstacle2X = Obstacle2X;
Obstacle2Y = Obstacle2Y;
heroX = heroX;
heroY = 460;
}
let reset = function() {
heroX = 50;
heroY = 460;
ObstacleX = 1600;
ObstacleY = 400;
Obstacle2X = 1300;
Obstacle2Y = 200;
}
let JumpToward = function() {
heroY += 20;
}
let JumpToward2 = function() {
heroY += 20;
}
let JumpBackward = function() {
heroY += 20;
}
let JumpUp = function() {
heroY += 20;
}
function timeOut() {
clearInterval(myTime);
}
let yourScore = [{
time,
score,
}]
//
localStorage.setItem("yourScore", JSON.stringify(yourScore));
console.log(JSON.parse(localStorage.getItem("yourScore")));
let update = function() {
//check if the hero died
GameOverTextReady = false
GameOverReady = false;
//check bullet position
bullet1Position = AmountBullet[0].BulletX - hero1Position;
/////
if ((heroX + 180 >= ObstacleX &&
heroX + 180 <= ObstacleX + 150 && heroY + 86 >= ObstacleY) || (heroX + 180 >= Obstacle2X &&
heroX + 180 <= Obstacle2X + 150 && heroY <= Obstacle2Y + 142) || (heroX + 180 >= Obstacle3X &&
heroX + 180 <= Obstacle3X + 137 && heroY <= Obstacle3Y + 115))
// && heroX >= ObstacleX &&
// heroX <= ObstacleX + 150 &&
// heroY + 86 >= ObstacleY &&
// heroY + 86 <= ObstacleY + 150 &&
// heroY >= ObstacleY &&
// heroY <= ObstacleY + 150))
{
GameOverReady = true;
GameOverTextReady = true;
GameOver();
console.log("Perform GameOver - Stop game");
timeOut();
yourScore.push(time, score);
if (13 in keysDown) {
time = 0;
timecounting();
reset();
console.log("Perform Reset");
}
} else {
if (13 in keysDown) {
reset();
console.log("Perform Reset");
}
elapsedTime = Math.floor((Date.now() - startTime) / 1000);
if (38 in keysDown && 39 in keysDown) { // Player is holding Up and Right key
heroX += 5;
setTimeout(JumpToward, 200);
console.log("JumpToward");
}
if (38 in keysDown && 37 in keysDown) { // Player is holding Up and Left key
heroX -= 5;
setTimeout(JumpBackward, 200);
console.log("Jump Backward");
}
if (38 in keysDown) { // Player is holding up key
heroY -= 20;
setTimeout(JumpUp, 200);
console.log("Jump Straight");
//setTimeout(delete keysDown[38], 10000);
}
if (heroY < 440) {
hero = 440;
}
// if (40 in keysDown) { // Player is holding down key
// heroY += 5;
// }
if (37 in keysDown) { // Player is holding left key
heroX -= 5;
console.log("Move left");
}
if (39 in keysDown) { // Player is holding right key
heroX += 5;
console.log("Move right");
}
if (heroY > 460) {
heroY = 460;
}
if (heroX < 0) {
heroX = 0;
}
//Obstacle Movement
ObstacleX -= 4;
Obstacle2X -= 3.5;
if (ObstacleX < -150) {
ObstacleX = canvas.width;
console.log("Obstacle 1 Perform Loop");
}
if (Obstacle2X < -150) {
Obstacle2X = canvas.width;
console.log("Obstacle 2 Perform Loop");
}
if (Obstacle3X < -150) {
Obstacle3X = canvas.width;
console.log("Obstacle 3 Perform Loop");
}
//Obstacle2 Movement
if (Obstacle2Y < 50) {
console.log("Obstacle 2 reach highest");
obtical = true;
} else if (Obstacle2Y > 400) {
console.log("Obstacle 2 reach lowest");
obtical = false;
}
if (obtical) {
Obstacle2Y += 3
console.log("Obstacle 2 Start Move Down");
} else
/*if (obtical = false)*/
{
Obstacle2Y -= 3
console.log("Obstacle 2 Start Move Up");
}
//Obstacle 3 movement
if (Obstacle3X < 500) {
console.log("Obstacle 2 reach highest");
obtical3 = true;
} else if (Obstacle3X > 1400) {
console.log("Obstacle 2 reach lowest");
obtical3 = false;
}
if (obtical3) {
Obstacle3X += 5
console.log("Obstacle 2 Start Move Down");
} else
/*if (obtical = false)*/
{
Obstacle3X -= 5;
console.log("Obstacle 2 Start Move Up");
}
//Tank shot bullet function
if (32 in keysDown && AmountBullet[0].BulletX === 10) {
bulletReady = true;
AmountBullet[0].BulletY = heroY;
AmountBullet[0].BulletX = heroX + 180;
bulletFire = true;
console.log("Start Shooting - Bullet Show up");
hero1Position = heroX;
}
////////////////////////////////////////////////////////////////////
if (32 in keysDown && AmountBullet[1].BulletX === 10 && bullet1Position > 500) {
bulletReady2 = true;
AmountBullet[1].BulletY = heroY;
AmountBullet[1].BulletX = heroX + 180;
bulletFire2 = true;
console.log("Start Shooting - Bullet Show up");
setTimeout(bulletOrder += 1, 200);
}
//////////////////////////////////
// else if (32 in keysDown && bulletOrder === 3 && AmountBullet[2].BulletX === 10) {
// bulletReady3 = true;
// AmountBullet[2].BulletY = heroY;
// AmountBullet[2].BulletX = heroX + 180;
// bulletFire3 = true;
// console.log("Start Shooting - Bullet Show up");
// setTimeout(bulletOrder += 1, 200);
// }
if (bulletFire) {
AmountBullet[0].BulletX += 10;
AmountBullet[0].BulletY = AmountBullet[0].BulletY;
console.log("Bullet move");
}
///////////////////////////
if (bulletFire2) {
AmountBullet[1].BulletX += 10;
AmountBullet[1].BulletY = AmountBullet[1].BulletY;
console.log("Bullet move");
}
// Check if player and monster collided. Our images are about 142 148 pixels big.
if (
AmountBullet[0].BulletX > ObstacleX && AmountBullet[0].BulletX < ObstacleX + 147 &&
AmountBullet[0].BulletY > ObstacleY && (AmountBullet[0].BulletY + 50) < (ObstacleY + 148)
) {
// Pick a new location for the monster.
// Note: Change this to place the monster at a new, random location.
ObstacleX = 1800;
ObstacleY = 400;
bulletFire = false;
AmountBullet[0].BulletX = 10;
AmountBullet[0].BulletY = 10;
console.log("Bullet hit Obstacle 1");
score += 1;
};
if (
AmountBullet[0].BulletX > Obstacle2X && AmountBullet[0].BulletY > Obstacle2Y && (AmountBullet[0].BulletY + 50) < (Obstacle2Y + 142)
) {
// Pick a new location for the monster.
// Note: Change this to place the monster at a new, random location.
Obstacle2X = -151;
Obstacle2Y = 200;
AmountBullet[0].BulletX = 10;
AmountBullet[0].BulletY = 10;
bulletFire = false;
score += 1;
};
if (
AmountBullet[0].BulletX > Obstacle3X && AmountBullet[0].BulletX < Obstacle3X + 137 &&
AmountBullet[0].BulletY > Obstacle3Y && (AmountBullet[0].BulletY + 50) < (Obstacle3Y + 115)
) {
// Pick a new location for the monster.
// Note: Change this to place the monster at a new, random location.
Obstacle3X = 1600;
Obstacle3Y = 430;
bulletFire = false;
AmountBullet[0].BulletX = 10;
AmountBullet[0].BulletY = 10;
console.log("Bullet hit Obstacle 3");
score += 1;
};
if (
AmountBullet[1].BulletX > ObstacleX && AmountBullet[1].BulletX < ObstacleX + 147 &&
AmountBullet[1].BulletY > ObstacleY && (AmountBullet[1].BulletY + 50) < (ObstacleY + 148)
) {
// Pick a new location for the monster.
// Note: Change this to place the monster at a new, random location.
ObstacleX = 1800;
ObstacleY = 400;
bulletFire2 = false;
AmountBullet[1].BulletX = 10;
AmountBullet[1].BulletY = 85;
console.log("Bullet hit Obstacle 1");
score += 1;
};
if (
AmountBullet[1].BulletX > Obstacle2X && AmountBullet[1].BulletY > Obstacle2Y && (AmountBullet[1].BulletY + 50) < (Obstacle2Y + 142)
) {
// Pick a new location for the monster.
// Note: Change this to place the monster at a new, random location.
Obstacle2X = -151;
Obstacle2Y = 200;
AmountBullet[1].BulletX = 10;
AmountBullet[1].BulletY = 10;
bulletFire2 = false;
score += 1;
};
if (
AmountBullet[1].BulletX > Obstacle3X && AmountBullet[1].BulletX < Obstacle3X + 137 &&
AmountBullet[1].BulletY > Obstacle3Y && (AmountBullet[1].BulletY + 50) < (Obstacle3Y + 115)
) {
// Pick a new location for the monster.
// Note: Change this to place the monster at a new, random location.
Obstacle3X = 1600;
Obstacle3Y = 430;
bulletFire2 = false;
AmountBullet[1].BulletX = 10;
AmountBullet[1].BulletY = 85;
console.log("Bullet hit Obstacle 3");
score += 1;
};
if (AmountBullet[0].BulletX > canvas.width) {
AmountBullet[0].BulletX = 10;
AmountBullet[0].BulletY = 10;
bulletFire = false;
}
if (AmountBullet[1].BulletX > canvas.width) {
AmountBullet[1].BulletX = 10;
AmountBullet[1].BulletY = 85;
bulletFire2 = false;
}
}
}
/**
* This function, render, runs as often as possible.
*/
let GameOverText = "PRESS ENTER TO PLAY AGAIN!"
ctx.font = "28px Ariel bolder";
var render = function() {
/* if (bgReady) {
ctx.drawImage(bgImage, backgroundX, 0);
}
if (bgReady2) {
ctx.drawImage(bgImage2, background2X, 0);
// }*/
if (imageObstatcleReady) {
ctx.drawImage(imageObstatcle, ObstacleX, ObstacleY);
}
if (imageObstatcle2Ready) {
ctx.drawImage(imageObstatcle2, Obstacle2X, Obstacle2Y);
}
if (Obstacle3Ready) {
ctx.drawImage(Obstacle3Image, Obstacle3X, Obstacle3Y);
}
if (bulletReady) {
ctx.drawImage(bulletImage, AmountBullet[0].BulletX,
AmountBullet[0].BulletY);
}
if (bulletReady2) {
ctx.drawImage(bulletImage2, AmountBullet[1].BulletX,
AmountBullet[1].BulletY);
}
if (heroReady) {
ctx.drawImage(heroImage, heroX, heroY);
}
if (GameOverReady) {
ctx.drawImage(GameOverImage, 544, 140); //544,140
}
if (GameOverTextReady) {
ctx.fillText(GameOverText, 600, 120);
}
//ctx.fillText(`Time Passed: ${SECONDS_PER_ROUND - elapsedTime}`, 20, 100);
ctx.fillText(`TIME PASSED: ${time}`, 100, 50);
ctx.fillText(`SCORED: ${score}`, 100, 125);
// ctx.strokeStyle = "#0000ff";
// ctx.strokeRect(0, 0, 1600, 650);
};
/**
* The main game loop. Most every game will have two distinct parts:
* update (updates the state of the game, in this case our hero and monster)
* render (based on the state of our game, draw the right things)
*/
var main = function() {
update();
render();
// Request to do this again ASAP. This is a special method
// for web browsers.
requestAnimationFrame(main);
};
// Cross-browser support for requestAnimationFrame.
// Safely ignore this line. It's mostly here for people with old web browsers.
var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;
// Let's play this game!
loadImages();
setupKeyboardListeners();
main();
|
/*! jQuery UI - v1.12.1 - 2018-12-06
* http://jqueryui.com
* Includes: keycode.js, widgets/datepicker.js
* Copyright jQuery Foundation and other contributors; Licensed MIT */
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
$.ui = $.ui || {};
var version = $.ui.version = "1.12.1";
/*!
* jQuery UI Keycode 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Keycode
//>>group: Core
//>>description: Provide keycodes as keynames
//>>docs: http://api.jqueryui.com/jQuery.ui.keyCode/
var keycode = $.ui.keyCode = {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
};
// jscs:disable maximumLineLength
/* jscs:disable requireCamelCaseOrUpperCaseIdentifiers */
/*!
* jQuery UI Datepicker 1.12.1
* http://jqueryui.com
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*/
//>>label: Datepicker
//>>group: Widgets
//>>description: Displays a calendar from an input or inline for selecting dates.
//>>docs: http://api.jqueryui.com/datepicker/
//>>demos: http://jqueryui.com/datepicker/
//>>css.structure: ../../themes/base/core.css
//>>css.structure: ../../themes/base/datepicker.css
//>>css.theme: ../../themes/base/theme.css
$.extend( $.ui, { datepicker: { version: "1.12.1" } } );
var datepicker_instActive;
function datepicker_getZindex( elem ) {
var position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
return 0;
}
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[ "" ] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: [ "January","February","March","April","May","June",
"July","August","September","October","November","December" ], // Names of months for drop-down and formatting
monthNamesShort: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], // For formatting
dayNames: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], // For formatting
dayNamesShort: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], // For formatting
dayNamesMin: [ "Su","Mo","Tu","We","Th","Fr","Sa" ], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend( this._defaults, this.regional[ "" ] );
this.regional.en = $.extend( true, {}, this.regional[ "" ] );
this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
this.dpDiv = datepicker_bindHover( $( "<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) );
}
$.extend( Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: "hasDatepicker",
//Keep track of the maximum number of rows displayed (see #7043)
maxRows: 4,
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
* @param settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function( settings ) {
datepicker_extendRemove( this._defaults, settings || {} );
return this;
},
/* Attach the date picker to a jQuery selection.
* @param target element - the target input field or division or span
* @param settings object - the new settings to use for this date picker instance (anonymous)
*/
_attachDatepicker: function( target, settings ) {
var nodeName, inline, inst;
nodeName = target.nodeName.toLowerCase();
inline = ( nodeName === "div" || nodeName === "span" );
if ( !target.id ) {
this.uuid += 1;
target.id = "dp" + this.uuid;
}
inst = this._newInst( $( target ), inline );
inst.settings = $.extend( {}, settings || {} );
if ( nodeName === "input" ) {
this._connectDatepicker( target, inst );
} else if ( inline ) {
this._inlineDatepicker( target, inst );
}
},
/* Create a new instance object. */
_newInst: function( target, inline ) {
var id = target[ 0 ].id.replace( /([^A-Za-z0-9_\-])/g, "\\\\$1" ); // escape jQuery meta chars
return { id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: ( !inline ? this.dpDiv : // presentation div
datepicker_bindHover( $( "<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>" ) ) ) };
},
/* Attach the date picker to an input field. */
_connectDatepicker: function( target, inst ) {
var input = $( target );
inst.append = $( [] );
inst.trigger = $( [] );
if ( input.hasClass( this.markerClassName ) ) {
return;
}
this._attachments( input, inst );
input.addClass( this.markerClassName ).on( "keydown", this._doKeyDown ).
on( "keypress", this._doKeyPress ).on( "keyup", this._doKeyUp );
this._autoSize( inst );
$.data( target, "datepicker", inst );
//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
if ( inst.settings.disabled ) {
this._disableDatepicker( target );
}
},
/* Make attachments based on settings. */
_attachments: function( input, inst ) {
var showOn, buttonText, buttonImage,
appendText = this._get( inst, "appendText" ),
isRTL = this._get( inst, "isRTL" );
if ( inst.append ) {
inst.append.remove();
}
if ( appendText ) {
inst.append = $( "<span class='" + this._appendClass + "'>" + appendText + "</span>" );
input[ isRTL ? "before" : "after" ]( inst.append );
}
input.off( "focus", this._showDatepicker );
if ( inst.trigger ) {
inst.trigger.remove();
}
showOn = this._get( inst, "showOn" );
if ( showOn === "focus" || showOn === "both" ) { // pop-up date picker when in the marked field
input.on( "focus", this._showDatepicker );
}
if ( showOn === "button" || showOn === "both" ) { // pop-up date picker when button clicked
buttonText = this._get( inst, "buttonText" );
buttonImage = this._get( inst, "buttonImage" );
inst.trigger = $( this._get( inst, "buttonImageOnly" ) ?
$( "<img/>" ).addClass( this._triggerClass ).
attr( { src: buttonImage, alt: buttonText, title: buttonText } ) :
$( "<button type='button'></button>" ).addClass( this._triggerClass ).
html( !buttonImage ? buttonText : $( "<img/>" ).attr(
{ src:buttonImage, alt:buttonText, title:buttonText } ) ) );
input[ isRTL ? "before" : "after" ]( inst.trigger );
inst.trigger.on( "click", function() {
if ( $.datepicker._datepickerShowing && $.datepicker._lastInput === input[ 0 ] ) {
$.datepicker._hideDatepicker();
} else if ( $.datepicker._datepickerShowing && $.datepicker._lastInput !== input[ 0 ] ) {
$.datepicker._hideDatepicker();
$.datepicker._showDatepicker( input[ 0 ] );
} else {
$.datepicker._showDatepicker( input[ 0 ] );
}
return false;
} );
}
},
/* Apply the maximum length for the date format. */
_autoSize: function( inst ) {
if ( this._get( inst, "autoSize" ) && !inst.inline ) {
var findMax, max, maxI, i,
date = new Date( 2009, 12 - 1, 20 ), // Ensure double digits
dateFormat = this._get( inst, "dateFormat" );
if ( dateFormat.match( /[DM]/ ) ) {
findMax = function( names ) {
max = 0;
maxI = 0;
for ( i = 0; i < names.length; i++ ) {
if ( names[ i ].length > max ) {
max = names[ i ].length;
maxI = i;
}
}
return maxI;
};
date.setMonth( findMax( this._get( inst, ( dateFormat.match( /MM/ ) ?
"monthNames" : "monthNamesShort" ) ) ) );
date.setDate( findMax( this._get( inst, ( dateFormat.match( /DD/ ) ?
"dayNames" : "dayNamesShort" ) ) ) + 20 - date.getDay() );
}
inst.input.attr( "size", this._formatDate( inst, date ).length );
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function( target, inst ) {
var divSpan = $( target );
if ( divSpan.hasClass( this.markerClassName ) ) {
return;
}
divSpan.addClass( this.markerClassName ).append( inst.dpDiv );
$.data( target, "datepicker", inst );
this._setDate( inst, this._getDefaultDate( inst ), true );
this._updateDatepicker( inst );
this._updateAlternate( inst );
//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
if ( inst.settings.disabled ) {
this._disableDatepicker( target );
}
// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
inst.dpDiv.css( "display", "block" );
},
/* Pop-up the date picker in a "dialog" box.
* @param input element - ignored
* @param date string or Date - the initial date to display
* @param onSelect function - the function to call when a date is selected
* @param settings object - update the dialog date picker instance's settings (anonymous object)
* @param pos int[2] - coordinates for the dialog's position within the screen or
* event - with x/y coordinates or
* leave empty for default (screen centre)
* @return the manager object
*/
_dialogDatepicker: function( input, date, onSelect, settings, pos ) {
var id, browserWidth, browserHeight, scrollX, scrollY,
inst = this._dialogInst; // internal instance
if ( !inst ) {
this.uuid += 1;
id = "dp" + this.uuid;
this._dialogInput = $( "<input type='text' id='" + id +
"' style='position: absolute; top: -100px; width: 0px;'/>" );
this._dialogInput.on( "keydown", this._doKeyDown );
$( "body" ).append( this._dialogInput );
inst = this._dialogInst = this._newInst( this._dialogInput, false );
inst.settings = {};
$.data( this._dialogInput[ 0 ], "datepicker", inst );
}
datepicker_extendRemove( inst.settings, settings || {} );
date = ( date && date.constructor === Date ? this._formatDate( inst, date ) : date );
this._dialogInput.val( date );
this._pos = ( pos ? ( pos.length ? pos : [ pos.pageX, pos.pageY ] ) : null );
if ( !this._pos ) {
browserWidth = document.documentElement.clientWidth;
browserHeight = document.documentElement.clientHeight;
scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[ ( browserWidth / 2 ) - 100 + scrollX, ( browserHeight / 2 ) - 150 + scrollY ];
}
// Move input on screen for focus, but hidden behind dialog
this._dialogInput.css( "left", ( this._pos[ 0 ] + 20 ) + "px" ).css( "top", this._pos[ 1 ] + "px" );
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass( this._dialogClass );
this._showDatepicker( this._dialogInput[ 0 ] );
if ( $.blockUI ) {
$.blockUI( this.dpDiv );
}
$.data( this._dialogInput[ 0 ], "datepicker", inst );
return this;
},
/* Detach a datepicker from its control.
* @param target element - the target input field or division or span
*/
_destroyDatepicker: function( target ) {
var nodeName,
$target = $( target ),
inst = $.data( target, "datepicker" );
if ( !$target.hasClass( this.markerClassName ) ) {
return;
}
nodeName = target.nodeName.toLowerCase();
$.removeData( target, "datepicker" );
if ( nodeName === "input" ) {
inst.append.remove();
inst.trigger.remove();
$target.removeClass( this.markerClassName ).
off( "focus", this._showDatepicker ).
off( "keydown", this._doKeyDown ).
off( "keypress", this._doKeyPress ).
off( "keyup", this._doKeyUp );
} else if ( nodeName === "div" || nodeName === "span" ) {
$target.removeClass( this.markerClassName ).empty();
}
if ( datepicker_instActive === inst ) {
datepicker_instActive = null;
}
},
/* Enable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_enableDatepicker: function( target ) {
var nodeName, inline,
$target = $( target ),
inst = $.data( target, "datepicker" );
if ( !$target.hasClass( this.markerClassName ) ) {
return;
}
nodeName = target.nodeName.toLowerCase();
if ( nodeName === "input" ) {
target.disabled = false;
inst.trigger.filter( "button" ).
each( function() { this.disabled = false; } ).end().
filter( "img" ).css( { opacity: "1.0", cursor: "" } );
} else if ( nodeName === "div" || nodeName === "span" ) {
inline = $target.children( "." + this._inlineClass );
inline.children().removeClass( "ui-state-disabled" );
inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
prop( "disabled", false );
}
this._disabledInputs = $.map( this._disabledInputs,
function( value ) { return ( value === target ? null : value ); } ); // delete entry
},
/* Disable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_disableDatepicker: function( target ) {
var nodeName, inline,
$target = $( target ),
inst = $.data( target, "datepicker" );
if ( !$target.hasClass( this.markerClassName ) ) {
return;
}
nodeName = target.nodeName.toLowerCase();
if ( nodeName === "input" ) {
target.disabled = true;
inst.trigger.filter( "button" ).
each( function() { this.disabled = true; } ).end().
filter( "img" ).css( { opacity: "0.5", cursor: "default" } );
} else if ( nodeName === "div" || nodeName === "span" ) {
inline = $target.children( "." + this._inlineClass );
inline.children().addClass( "ui-state-disabled" );
inline.find( "select.ui-datepicker-month, select.ui-datepicker-year" ).
prop( "disabled", true );
}
this._disabledInputs = $.map( this._disabledInputs,
function( value ) { return ( value === target ? null : value ); } ); // delete entry
this._disabledInputs[ this._disabledInputs.length ] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
* @param target element - the target input field or division or span
* @return boolean - true if disabled, false if enabled
*/
_isDisabledDatepicker: function( target ) {
if ( !target ) {
return false;
}
for ( var i = 0; i < this._disabledInputs.length; i++ ) {
if ( this._disabledInputs[ i ] === target ) {
return true;
}
}
return false;
},
/* Retrieve the instance data for the target control.
* @param target element - the target input field or division or span
* @return object - the associated instance data
* @throws error if a jQuery problem getting data
*/
_getInst: function( target ) {
try {
return $.data( target, "datepicker" );
}
catch ( err ) {
throw "Missing instance data for this datepicker";
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
* @param target element - the target input field or division or span
* @param name object - the new settings to update or
* string - the name of the setting to change or retrieve,
* when retrieving also "all" for all instance settings or
* "defaults" for all global defaults
* @param value any - the new value for the setting
* (omit if above is an object or to retrieve a value)
*/
_optionDatepicker: function( target, name, value ) {
var settings, date, minDate, maxDate,
inst = this._getInst( target );
if ( arguments.length === 2 && typeof name === "string" ) {
return ( name === "defaults" ? $.extend( {}, $.datepicker._defaults ) :
( inst ? ( name === "all" ? $.extend( {}, inst.settings ) :
this._get( inst, name ) ) : null ) );
}
settings = name || {};
if ( typeof name === "string" ) {
settings = {};
settings[ name ] = value;
}
if ( inst ) {
if ( this._curInst === inst ) {
this._hideDatepicker();
}
date = this._getDateDatepicker( target, true );
minDate = this._getMinMaxDate( inst, "min" );
maxDate = this._getMinMaxDate( inst, "max" );
datepicker_extendRemove( inst.settings, settings );
// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
if ( minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined ) {
inst.settings.minDate = this._formatDate( inst, minDate );
}
if ( maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined ) {
inst.settings.maxDate = this._formatDate( inst, maxDate );
}
if ( "disabled" in settings ) {
if ( settings.disabled ) {
this._disableDatepicker( target );
} else {
this._enableDatepicker( target );
}
}
this._attachments( $( target ), inst );
this._autoSize( inst );
this._setDate( inst, date );
this._updateAlternate( inst );
this._updateDatepicker( inst );
}
},
// Change method deprecated
_changeDatepicker: function( target, name, value ) {
this._optionDatepicker( target, name, value );
},
/* Redraw the date picker attached to an input field or division.
* @param target element - the target input field or division or span
*/
_refreshDatepicker: function( target ) {
var inst = this._getInst( target );
if ( inst ) {
this._updateDatepicker( inst );
}
},
/* Set the dates for a jQuery selection.
* @param target element - the target input field or division or span
* @param date Date - the new date
*/
_setDateDatepicker: function( target, date ) {
var inst = this._getInst( target );
if ( inst ) {
this._setDate( inst, date );
this._updateDatepicker( inst );
this._updateAlternate( inst );
}
},
/* Get the date(s) for the first entry in a jQuery selection.
* @param target element - the target input field or division or span
* @param noDefault boolean - true if no default date is to be used
* @return Date - the current date
*/
_getDateDatepicker: function( target, noDefault ) {
var inst = this._getInst( target );
if ( inst && !inst.inline ) {
this._setDateFromField( inst, noDefault );
}
return ( inst ? this._getDate( inst ) : null );
},
/* Handle keystrokes. */
_doKeyDown: function( event ) {
var onSelect, dateStr, sel,
inst = $.datepicker._getInst( event.target ),
handled = true,
isRTL = inst.dpDiv.is( ".ui-datepicker-rtl" );
inst._keyEvent = true;
if ( $.datepicker._datepickerShowing ) {
switch ( event.keyCode ) {
case 9: $.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13: sel = $( "td." + $.datepicker._dayOverClass + ":not(." +
$.datepicker._currentClass + ")", inst.dpDiv );
if ( sel[ 0 ] ) {
$.datepicker._selectDay( event.target, inst.selectedMonth, inst.selectedYear, sel[ 0 ] );
}
onSelect = $.datepicker._get( inst, "onSelect" );
if ( onSelect ) {
dateStr = $.datepicker._formatDate( inst );
// Trigger custom callback
onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] );
} else {
$.datepicker._hideDatepicker();
}
return false; // don't submit the form
case 27: $.datepicker._hideDatepicker();
break; // hide on escape
case 33: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
-$.datepicker._get( inst, "stepBigMonths" ) :
-$.datepicker._get( inst, "stepMonths" ) ), "M" );
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate( event.target, ( event.ctrlKey ?
+$.datepicker._get( inst, "stepBigMonths" ) :
+$.datepicker._get( inst, "stepMonths" ) ), "M" );
break; // next month/year on page down/+ ctrl
case 35: if ( event.ctrlKey || event.metaKey ) {
$.datepicker._clearDate( event.target );
}
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if ( event.ctrlKey || event.metaKey ) {
$.datepicker._gotoToday( event.target );
}
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if ( event.ctrlKey || event.metaKey ) {
$.datepicker._adjustDate( event.target, ( isRTL ? +1 : -1 ), "D" );
}
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if ( event.originalEvent.altKey ) {
$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
-$.datepicker._get( inst, "stepBigMonths" ) :
-$.datepicker._get( inst, "stepMonths" ) ), "M" );
}
// next month/year on alt +left on Mac
break;
case 38: if ( event.ctrlKey || event.metaKey ) {
$.datepicker._adjustDate( event.target, -7, "D" );
}
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if ( event.ctrlKey || event.metaKey ) {
$.datepicker._adjustDate( event.target, ( isRTL ? -1 : +1 ), "D" );
}
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if ( event.originalEvent.altKey ) {
$.datepicker._adjustDate( event.target, ( event.ctrlKey ?
+$.datepicker._get( inst, "stepBigMonths" ) :
+$.datepicker._get( inst, "stepMonths" ) ), "M" );
}
// next month/year on alt +right
break;
case 40: if ( event.ctrlKey || event.metaKey ) {
$.datepicker._adjustDate( event.target, +7, "D" );
}
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
} else if ( event.keyCode === 36 && event.ctrlKey ) { // display the date picker on ctrl+home
$.datepicker._showDatepicker( this );
} else {
handled = false;
}
if ( handled ) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function( event ) {
var chars, chr,
inst = $.datepicker._getInst( event.target );
if ( $.datepicker._get( inst, "constrainInput" ) ) {
chars = $.datepicker._possibleChars( $.datepicker._get( inst, "dateFormat" ) );
chr = String.fromCharCode( event.charCode == null ? event.keyCode : event.charCode );
return event.ctrlKey || event.metaKey || ( chr < " " || !chars || chars.indexOf( chr ) > -1 );
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function( event ) {
var date,
inst = $.datepicker._getInst( event.target );
if ( inst.input.val() !== inst.lastVal ) {
try {
date = $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
( inst.input ? inst.input.val() : null ),
$.datepicker._getFormatConfig( inst ) );
if ( date ) { // only if valid
$.datepicker._setDateFromField( inst );
$.datepicker._updateAlternate( inst );
$.datepicker._updateDatepicker( inst );
}
}
catch ( err ) {
}
}
return true;
},
/* Pop-up the date picker for a given input field.
* If false returned from beforeShow event handler do not show.
* @param input element - the input field attached to the date picker or
* event - if triggered by focus
*/
_showDatepicker: function( input ) {
input = input.target || input;
if ( input.nodeName.toLowerCase() !== "input" ) { // find from button/image trigger
input = $( "input", input.parentNode )[ 0 ];
}
if ( $.datepicker._isDisabledDatepicker( input ) || $.datepicker._lastInput === input ) { // already here
return;
}
var inst, beforeShow, beforeShowSettings, isFixed,
offset, showAnim, duration;
inst = $.datepicker._getInst( input );
if ( $.datepicker._curInst && $.datepicker._curInst !== inst ) {
$.datepicker._curInst.dpDiv.stop( true, true );
if ( inst && $.datepicker._datepickerShowing ) {
$.datepicker._hideDatepicker( $.datepicker._curInst.input[ 0 ] );
}
}
beforeShow = $.datepicker._get( inst, "beforeShow" );
beforeShowSettings = beforeShow ? beforeShow.apply( input, [ input, inst ] ) : {};
if ( beforeShowSettings === false ) {
return;
}
datepicker_extendRemove( inst.settings, beforeShowSettings );
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField( inst );
if ( $.datepicker._inDialog ) { // hide cursor
input.value = "";
}
if ( !$.datepicker._pos ) { // position below input
$.datepicker._pos = $.datepicker._findPos( input );
$.datepicker._pos[ 1 ] += input.offsetHeight; // add the height
}
isFixed = false;
$( input ).parents().each( function() {
isFixed |= $( this ).css( "position" ) === "fixed";
return !isFixed;
} );
offset = { left: $.datepicker._pos[ 0 ], top: $.datepicker._pos[ 1 ] };
$.datepicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css( { position: "absolute", display: "block", top: "-1000px" } );
$.datepicker._updateDatepicker( inst );
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset( inst, offset, isFixed );
inst.dpDiv.css( { position: ( $.datepicker._inDialog && $.blockUI ?
"static" : ( isFixed ? "fixed" : "absolute" ) ), display: "none",
left: offset.left + "px", top: offset.top + "px" } );
if ( !inst.inline ) {
showAnim = $.datepicker._get( inst, "showAnim" );
duration = $.datepicker._get( inst, "duration" );
inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
$.datepicker._datepickerShowing = true;
if ( $.effects && $.effects.effect[ showAnim ] ) {
inst.dpDiv.show( showAnim, $.datepicker._get( inst, "showOptions" ), duration );
} else {
inst.dpDiv[ showAnim || "show" ]( showAnim ? duration : null );
}
if ( $.datepicker._shouldFocusInput( inst ) ) {
inst.input.trigger( "focus" );
}
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function( inst ) {
this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
datepicker_instActive = inst; // for delegate hover events
inst.dpDiv.empty().append( this._generateHTML( inst ) );
this._attachHandlers( inst );
var origyearshtml,
numMonths = this._getNumberOfMonths( inst ),
cols = numMonths[ 1 ],
width = 17,
activeCell = inst.dpDiv.find( "." + this._dayOverClass + " a" );
if ( activeCell.length > 0 ) {
datepicker_handleMouseover.apply( activeCell.get( 0 ) );
}
inst.dpDiv.removeClass( "ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4" ).width( "" );
if ( cols > 1 ) {
inst.dpDiv.addClass( "ui-datepicker-multi-" + cols ).css( "width", ( width * cols ) + "em" );
}
inst.dpDiv[ ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ? "add" : "remove" ) +
"Class" ]( "ui-datepicker-multi" );
inst.dpDiv[ ( this._get( inst, "isRTL" ) ? "add" : "remove" ) +
"Class" ]( "ui-datepicker-rtl" );
if ( inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
inst.input.trigger( "focus" );
}
// Deffered render of the years select (to avoid flashes on Firefox)
if ( inst.yearshtml ) {
origyearshtml = inst.yearshtml;
setTimeout( function() {
//assure that inst.yearshtml didn't change.
if ( origyearshtml === inst.yearshtml && inst.yearshtml ) {
inst.dpDiv.find( "select.ui-datepicker-year:first" ).replaceWith( inst.yearshtml );
}
origyearshtml = inst.yearshtml = null;
}, 0 );
}
},
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
// Support: IE and jQuery <1.9
_shouldFocusInput: function( inst ) {
return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
},
/* Check positioning to remain on screen. */
_checkOffset: function( inst, offset, isFixed ) {
var dpWidth = inst.dpDiv.outerWidth(),
dpHeight = inst.dpDiv.outerHeight(),
inputWidth = inst.input ? inst.input.outerWidth() : 0,
inputHeight = inst.input ? inst.input.outerHeight() : 0,
viewWidth = document.documentElement.clientWidth + ( isFixed ? 0 : $( document ).scrollLeft() ),
viewHeight = document.documentElement.clientHeight + ( isFixed ? 0 : $( document ).scrollTop() );
offset.left -= ( this._get( inst, "isRTL" ) ? ( dpWidth - inputWidth ) : 0 );
offset.left -= ( isFixed && offset.left === inst.input.offset().left ) ? $( document ).scrollLeft() : 0;
offset.top -= ( isFixed && offset.top === ( inst.input.offset().top + inputHeight ) ) ? $( document ).scrollTop() : 0;
// Now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min( offset.left, ( offset.left + dpWidth > viewWidth && viewWidth > dpWidth ) ?
Math.abs( offset.left + dpWidth - viewWidth ) : 0 );
offset.top -= Math.min( offset.top, ( offset.top + dpHeight > viewHeight && viewHeight > dpHeight ) ?
Math.abs( dpHeight + inputHeight ) : 0 );
return offset;
},
/* Find an object's position on the screen. */
_findPos: function( obj ) {
var position,
inst = this._getInst( obj ),
isRTL = this._get( inst, "isRTL" );
while ( obj && ( obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden( obj ) ) ) {
obj = obj[ isRTL ? "previousSibling" : "nextSibling" ];
}
position = $( obj ).offset();
return [ position.left, position.top ];
},
/* Hide the date picker from view.
* @param input element - the input field attached to the date picker
*/
_hideDatepicker: function( input ) {
var showAnim, duration, postProcess, onClose,
inst = this._curInst;
if ( !inst || ( input && inst !== $.data( input, "datepicker" ) ) ) {
return;
}
if ( this._datepickerShowing ) {
showAnim = this._get( inst, "showAnim" );
duration = this._get( inst, "duration" );
postProcess = function() {
$.datepicker._tidyDialog( inst );
};
// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
inst.dpDiv.hide( showAnim, $.datepicker._get( inst, "showOptions" ), duration, postProcess );
} else {
inst.dpDiv[ ( showAnim === "slideDown" ? "slideUp" :
( showAnim === "fadeIn" ? "fadeOut" : "hide" ) ) ]( ( showAnim ? duration : null ), postProcess );
}
if ( !showAnim ) {
postProcess();
}
this._datepickerShowing = false;
onClose = this._get( inst, "onClose" );
if ( onClose ) {
onClose.apply( ( inst.input ? inst.input[ 0 ] : null ), [ ( inst.input ? inst.input.val() : "" ), inst ] );
}
this._lastInput = null;
if ( this._inDialog ) {
this._dialogInput.css( { position: "absolute", left: "0", top: "-100px" } );
if ( $.blockUI ) {
$.unblockUI();
$( "body" ).append( this.dpDiv );
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function( inst ) {
inst.dpDiv.removeClass( this._dialogClass ).off( ".ui-datepicker-calendar" );
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function( event ) {
if ( !$.datepicker._curInst ) {
return;
}
var $target = $( event.target ),
inst = $.datepicker._getInst( $target[ 0 ] );
if ( ( ( $target[ 0 ].id !== $.datepicker._mainDivId &&
$target.parents( "#" + $.datepicker._mainDivId ).length === 0 &&
!$target.hasClass( $.datepicker.markerClassName ) &&
!$target.closest( "." + $.datepicker._triggerClass ).length &&
$.datepicker._datepickerShowing && !( $.datepicker._inDialog && $.blockUI ) ) ) ||
( $target.hasClass( $.datepicker.markerClassName ) && $.datepicker._curInst !== inst ) ) {
$.datepicker._hideDatepicker();
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function( id, offset, period ) {
var target = $( id ),
inst = this._getInst( target[ 0 ] );
if ( this._isDisabledDatepicker( target[ 0 ] ) ) {
return;
}
this._adjustInstDate( inst, offset +
( period === "M" ? this._get( inst, "showCurrentAtPos" ) : 0 ), // undo positioning
period );
this._updateDatepicker( inst );
},
/* Action for current link. */
_gotoToday: function( id ) {
var date,
target = $( id ),
inst = this._getInst( target[ 0 ] );
if ( this._get( inst, "gotoCurrent" ) && inst.currentDay ) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange( inst );
this._adjustDate( target );
},
/* Action for selecting a new month/year. */
_selectMonthYear: function( id, select, period ) {
var target = $( id ),
inst = this._getInst( target[ 0 ] );
inst[ "selected" + ( period === "M" ? "Month" : "Year" ) ] =
inst[ "draw" + ( period === "M" ? "Month" : "Year" ) ] =
parseInt( select.options[ select.selectedIndex ].value, 10 );
this._notifyChange( inst );
this._adjustDate( target );
},
/* Action for selecting a day. */
_selectDay: function( id, month, year, td ) {
var inst,
target = $( id );
if ( $( td ).hasClass( this._unselectableClass ) || this._isDisabledDatepicker( target[ 0 ] ) ) {
return;
}
inst = this._getInst( target[ 0 ] );
inst.selectedDay = inst.currentDay = $( "a", td ).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate( id, this._formatDate( inst,
inst.currentDay, inst.currentMonth, inst.currentYear ) );
},
/* Erase the input field and hide the date picker. */
_clearDate: function( id ) {
var target = $( id );
this._selectDate( target, "" );
},
/* Update the input field with the selected date. */
_selectDate: function( id, dateStr ) {
var onSelect,
target = $( id ),
inst = this._getInst( target[ 0 ] );
dateStr = ( dateStr != null ? dateStr : this._formatDate( inst ) );
if ( inst.input ) {
inst.input.val( dateStr );
}
this._updateAlternate( inst );
onSelect = this._get( inst, "onSelect" );
if ( onSelect ) {
onSelect.apply( ( inst.input ? inst.input[ 0 ] : null ), [ dateStr, inst ] ); // trigger custom callback
} else if ( inst.input ) {
inst.input.trigger( "change" ); // fire the change event
}
if ( inst.inline ) {
this._updateDatepicker( inst );
} else {
this._hideDatepicker();
this._lastInput = inst.input[ 0 ];
if ( typeof( inst.input[ 0 ] ) !== "object" ) {
inst.input.trigger( "focus" ); // restore focus
}
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function( inst ) {
var altFormat, date, dateStr,
altField = this._get( inst, "altField" );
if ( altField ) { // update alternate field too
altFormat = this._get( inst, "altFormat" ) || this._get( inst, "dateFormat" );
date = this._getDate( inst );
dateStr = this.formatDate( altFormat, date, this._getFormatConfig( inst ) );
$( altField ).val( dateStr );
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
* @param date Date - the date to customise
* @return [boolean, string] - is this date selectable?, what is its CSS class?
*/
noWeekends: function( date ) {
var day = date.getDay();
return [ ( day > 0 && day < 6 ), "" ];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* @param date Date - the date to get the week for
* @return number - the number of the week within the year that contains this date
*/
iso8601Week: function( date ) {
var time,
checkDate = new Date( date.getTime() );
// Find Thursday of this week starting on Monday
checkDate.setDate( checkDate.getDate() + 4 - ( checkDate.getDay() || 7 ) );
time = checkDate.getTime();
checkDate.setMonth( 0 ); // Compare with Jan 1
checkDate.setDate( 1 );
return Math.floor( Math.round( ( time - checkDate ) / 86400000 ) / 7 ) + 1;
},
/* Parse a string value into a date object.
* See formatDate below for the possible formats.
*
* @param format string - the expected format of the date
* @param value string - the date in the above format
* @param settings Object - attributes include:
* shortYearCutoff number - the cutoff year for determining the century (optional)
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return Date - the extracted date value or null if value is blank
*/
parseDate: function( format, value, settings ) {
if ( format == null || value == null ) {
throw "Invalid arguments";
}
value = ( typeof value === "object" ? value.toString() : value + "" );
if ( value === "" ) {
return null;
}
var iFormat, dim, extra,
iValue = 0,
shortYearCutoffTemp = ( settings ? settings.shortYearCutoff : null ) || this._defaults.shortYearCutoff,
shortYearCutoff = ( typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
new Date().getFullYear() % 100 + parseInt( shortYearCutoffTemp, 10 ) ),
dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,
year = -1,
month = -1,
day = -1,
doy = -1,
literal = false,
date,
// Check whether a format character is doubled
lookAhead = function( match ) {
var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
if ( matches ) {
iFormat++;
}
return matches;
},
// Extract a number from the string value
getNumber = function( match ) {
var isDoubled = lookAhead( match ),
size = ( match === "@" ? 14 : ( match === "!" ? 20 :
( match === "y" && isDoubled ? 4 : ( match === "o" ? 3 : 2 ) ) ) ),
minSize = ( match === "y" ? size : 1 ),
digits = new RegExp( "^\\d{" + minSize + "," + size + "}" ),
num = value.substring( iValue ).match( digits );
if ( !num ) {
throw "Missing number at position " + iValue;
}
iValue += num[ 0 ].length;
return parseInt( num[ 0 ], 10 );
},
// Extract a name from the string value and convert to an index
getName = function( match, shortNames, longNames ) {
var index = -1,
names = $.map( lookAhead( match ) ? longNames : shortNames, function( v, k ) {
return [ [ k, v ] ];
} ).sort( function( a, b ) {
return -( a[ 1 ].length - b[ 1 ].length );
} );
$.each( names, function( i, pair ) {
var name = pair[ 1 ];
if ( value.substr( iValue, name.length ).toLowerCase() === name.toLowerCase() ) {
index = pair[ 0 ];
iValue += name.length;
return false;
}
} );
if ( index !== -1 ) {
return index + 1;
} else {
throw "Unknown name at position " + iValue;
}
},
// Confirm that a literal character matches the string value
checkLiteral = function() {
if ( value.charAt( iValue ) !== format.charAt( iFormat ) ) {
throw "Unexpected literal at position " + iValue;
}
iValue++;
};
for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
if ( literal ) {
if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
literal = false;
} else {
checkLiteral();
}
} else {
switch ( format.charAt( iFormat ) ) {
case "d":
day = getNumber( "d" );
break;
case "D":
getName( "D", dayNamesShort, dayNames );
break;
case "o":
doy = getNumber( "o" );
break;
case "m":
month = getNumber( "m" );
break;
case "M":
month = getName( "M", monthNamesShort, monthNames );
break;
case "y":
year = getNumber( "y" );
break;
case "@":
date = new Date( getNumber( "@" ) );
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "!":
date = new Date( ( getNumber( "!" ) - this._ticksTo1970 ) / 10000 );
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if ( lookAhead( "'" ) ) {
checkLiteral();
} else {
literal = true;
}
break;
default:
checkLiteral();
}
}
}
if ( iValue < value.length ) {
extra = value.substr( iValue );
if ( !/^\s+/.test( extra ) ) {
throw "Extra/unparsed characters found in date: " + extra;
}
}
if ( year === -1 ) {
year = new Date().getFullYear();
} else if ( year < 100 ) {
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
( year <= shortYearCutoff ? 0 : -100 );
}
if ( doy > -1 ) {
month = 1;
day = doy;
do {
dim = this._getDaysInMonth( year, month - 1 );
if ( day <= dim ) {
break;
}
month++;
day -= dim;
} while ( true );
}
date = this._daylightSavingAdjust( new Date( year, month - 1, day ) );
if ( date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day ) {
throw "Invalid date"; // E.g. 31/02/00
}
return date;
},
/* Standard date formats. */
ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
COOKIE: "D, dd M yy",
ISO_8601: "yy-mm-dd",
RFC_822: "D, d M y",
RFC_850: "DD, dd-M-y",
RFC_1036: "D, d M y",
RFC_1123: "D, d M yy",
RFC_2822: "D, d M yy",
RSS: "D, d M y", // RFC 822
TICKS: "!",
TIMESTAMP: "@",
W3C: "yy-mm-dd", // ISO 8601
_ticksTo1970: ( ( ( 1970 - 1 ) * 365 + Math.floor( 1970 / 4 ) - Math.floor( 1970 / 100 ) +
Math.floor( 1970 / 400 ) ) * 24 * 60 * 60 * 10000000 ),
/* Format a date object into a string value.
* The format can be combinations of the following:
* d - day of month (no leading zero)
* dd - day of month (two digit)
* o - day of year (no leading zeros)
* oo - day of year (three digit)
* D - day name short
* DD - day name long
* m - month of year (no leading zero)
* mm - month of year (two digit)
* M - month name short
* MM - month name long
* y - year (two digit)
* yy - year (four digit)
* @ - Unix timestamp (ms since 01/01/1970)
* ! - Windows ticks (100ns since 01/01/0001)
* "..." - literal text
* '' - single quote
*
* @param format string - the desired format of the date
* @param date Date - the date value to format
* @param settings Object - attributes include:
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return string - the date in the above format
*/
formatDate: function( format, date, settings ) {
if ( !date ) {
return "";
}
var iFormat,
dayNamesShort = ( settings ? settings.dayNamesShort : null ) || this._defaults.dayNamesShort,
dayNames = ( settings ? settings.dayNames : null ) || this._defaults.dayNames,
monthNamesShort = ( settings ? settings.monthNamesShort : null ) || this._defaults.monthNamesShort,
monthNames = ( settings ? settings.monthNames : null ) || this._defaults.monthNames,
// Check whether a format character is doubled
lookAhead = function( match ) {
var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
if ( matches ) {
iFormat++;
}
return matches;
},
// Format a number, with leading zero if necessary
formatNumber = function( match, value, len ) {
var num = "" + value;
if ( lookAhead( match ) ) {
while ( num.length < len ) {
num = "0" + num;
}
}
return num;
},
// Format a name, short or long as requested
formatName = function( match, value, shortNames, longNames ) {
return ( lookAhead( match ) ? longNames[ value ] : shortNames[ value ] );
},
output = "",
literal = false;
if ( date ) {
for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
if ( literal ) {
if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
literal = false;
} else {
output += format.charAt( iFormat );
}
} else {
switch ( format.charAt( iFormat ) ) {
case "d":
output += formatNumber( "d", date.getDate(), 2 );
break;
case "D":
output += formatName( "D", date.getDay(), dayNamesShort, dayNames );
break;
case "o":
output += formatNumber( "o",
Math.round( ( new Date( date.getFullYear(), date.getMonth(), date.getDate() ).getTime() - new Date( date.getFullYear(), 0, 0 ).getTime() ) / 86400000 ), 3 );
break;
case "m":
output += formatNumber( "m", date.getMonth() + 1, 2 );
break;
case "M":
output += formatName( "M", date.getMonth(), monthNamesShort, monthNames );
break;
case "y":
output += ( lookAhead( "y" ) ? date.getFullYear() :
( date.getFullYear() % 100 < 10 ? "0" : "" ) + date.getFullYear() % 100 );
break;
case "@":
output += date.getTime();
break;
case "!":
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if ( lookAhead( "'" ) ) {
output += "'";
} else {
literal = true;
}
break;
default:
output += format.charAt( iFormat );
}
}
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function( format ) {
var iFormat,
chars = "",
literal = false,
// Check whether a format character is doubled
lookAhead = function( match ) {
var matches = ( iFormat + 1 < format.length && format.charAt( iFormat + 1 ) === match );
if ( matches ) {
iFormat++;
}
return matches;
};
for ( iFormat = 0; iFormat < format.length; iFormat++ ) {
if ( literal ) {
if ( format.charAt( iFormat ) === "'" && !lookAhead( "'" ) ) {
literal = false;
} else {
chars += format.charAt( iFormat );
}
} else {
switch ( format.charAt( iFormat ) ) {
case "d": case "m": case "y": case "@":
chars += "0123456789";
break;
case "D": case "M":
return null; // Accept anything
case "'":
if ( lookAhead( "'" ) ) {
chars += "'";
} else {
literal = true;
}
break;
default:
chars += format.charAt( iFormat );
}
}
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function( inst, name ) {
return inst.settings[ name ] !== undefined ?
inst.settings[ name ] : this._defaults[ name ];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function( inst, noDefault ) {
if ( inst.input.val() === inst.lastVal ) {
return;
}
var dateFormat = this._get( inst, "dateFormat" ),
dates = inst.lastVal = inst.input ? inst.input.val() : null,
defaultDate = this._getDefaultDate( inst ),
date = defaultDate,
settings = this._getFormatConfig( inst );
try {
date = this.parseDate( dateFormat, dates, settings ) || defaultDate;
} catch ( event ) {
dates = ( noDefault ? "" : dates );
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = ( dates ? date.getDate() : 0 );
inst.currentMonth = ( dates ? date.getMonth() : 0 );
inst.currentYear = ( dates ? date.getFullYear() : 0 );
this._adjustInstDate( inst );
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function( inst ) {
return this._restrictMinMax( inst,
this._determineDate( inst, this._get( inst, "defaultDate" ), new Date() ) );
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function( inst, date, defaultDate ) {
var offsetNumeric = function( offset ) {
var date = new Date();
date.setDate( date.getDate() + offset );
return date;
},
offsetString = function( offset ) {
try {
return $.datepicker.parseDate( $.datepicker._get( inst, "dateFormat" ),
offset, $.datepicker._getFormatConfig( inst ) );
}
catch ( e ) {
// Ignore
}
var date = ( offset.toLowerCase().match( /^c/ ) ?
$.datepicker._getDate( inst ) : null ) || new Date(),
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec( offset );
while ( matches ) {
switch ( matches[ 2 ] || "d" ) {
case "d" : case "D" :
day += parseInt( matches[ 1 ], 10 ); break;
case "w" : case "W" :
day += parseInt( matches[ 1 ], 10 ) * 7; break;
case "m" : case "M" :
month += parseInt( matches[ 1 ], 10 );
day = Math.min( day, $.datepicker._getDaysInMonth( year, month ) );
break;
case "y": case "Y" :
year += parseInt( matches[ 1 ], 10 );
day = Math.min( day, $.datepicker._getDaysInMonth( year, month ) );
break;
}
matches = pattern.exec( offset );
}
return new Date( year, month, day );
},
newDate = ( date == null || date === "" ? defaultDate : ( typeof date === "string" ? offsetString( date ) :
( typeof date === "number" ? ( isNaN( date ) ? defaultDate : offsetNumeric( date ) ) : new Date( date.getTime() ) ) ) );
newDate = ( newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate );
if ( newDate ) {
newDate.setHours( 0 );
newDate.setMinutes( 0 );
newDate.setSeconds( 0 );
newDate.setMilliseconds( 0 );
}
return this._daylightSavingAdjust( newDate );
},
/* Handle switch to/from daylight saving.
* Hours may be non-zero on daylight saving cut-over:
* > 12 when midnight changeover, but then cannot generate
* midnight datetime, so jump to 1AM, otherwise reset.
* @param date (Date) the date to check
* @return (Date) the corrected date
*/
_daylightSavingAdjust: function( date ) {
if ( !date ) {
return null;
}
date.setHours( date.getHours() > 12 ? date.getHours() + 2 : 0 );
return date;
},
/* Set the date(s) directly. */
_setDate: function( inst, date, noChange ) {
var clear = !date,
origMonth = inst.selectedMonth,
origYear = inst.selectedYear,
newDate = this._restrictMinMax( inst, this._determineDate( inst, date, new Date() ) );
inst.selectedDay = inst.currentDay = newDate.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
if ( ( origMonth !== inst.selectedMonth || origYear !== inst.selectedYear ) && !noChange ) {
this._notifyChange( inst );
}
this._adjustInstDate( inst );
if ( inst.input ) {
inst.input.val( clear ? "" : this._formatDate( inst ) );
}
},
/* Retrieve the date(s) directly. */
_getDate: function( inst ) {
var startDate = ( !inst.currentYear || ( inst.input && inst.input.val() === "" ) ? null :
this._daylightSavingAdjust( new Date(
inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
return startDate;
},
/* Attach the onxxx handlers. These are declared statically so
* they work with static code transformers like Caja.
*/
_attachHandlers: function( inst ) {
var stepMonths = this._get( inst, "stepMonths" ),
id = "#" + inst.id.replace( /\\\\/g, "\\" );
inst.dpDiv.find( "[data-handler]" ).map( function() {
var handler = {
prev: function() {
$.datepicker._adjustDate( id, -stepMonths, "M" );
},
next: function() {
$.datepicker._adjustDate( id, +stepMonths, "M" );
},
hide: function() {
$.datepicker._hideDatepicker();
},
today: function() {
$.datepicker._gotoToday( id );
},
selectDay: function() {
$.datepicker._selectDay( id, +this.getAttribute( "data-month" ), +this.getAttribute( "data-year" ), this );
return false;
},
selectMonth: function() {
$.datepicker._selectMonthYear( id, this, "M" );
return false;
},
selectYear: function() {
$.datepicker._selectMonthYear( id, this, "Y" );
return false;
}
};
$( this ).on( this.getAttribute( "data-event" ), handler[ this.getAttribute( "data-handler" ) ] );
} );
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function( inst ) {
var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
printDate, dRow, tbody, daySettings, otherMonth, unselectable,
tempDate = new Date(),
today = this._daylightSavingAdjust(
new Date( tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate() ) ), // clear time
isRTL = this._get( inst, "isRTL" ),
showButtonPanel = this._get( inst, "showButtonPanel" ),
hideIfNoPrevNext = this._get( inst, "hideIfNoPrevNext" ),
navigationAsDateFormat = this._get( inst, "navigationAsDateFormat" ),
numMonths = this._getNumberOfMonths( inst ),
showCurrentAtPos = this._get( inst, "showCurrentAtPos" ),
stepMonths = this._get( inst, "stepMonths" ),
isMultiMonth = ( numMonths[ 0 ] !== 1 || numMonths[ 1 ] !== 1 ),
currentDate = this._daylightSavingAdjust( ( !inst.currentDay ? new Date( 9999, 9, 9 ) :
new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) ),
minDate = this._getMinMaxDate( inst, "min" ),
maxDate = this._getMinMaxDate( inst, "max" ),
drawMonth = inst.drawMonth - showCurrentAtPos,
drawYear = inst.drawYear;
if ( drawMonth < 0 ) {
drawMonth += 12;
drawYear--;
}
if ( maxDate ) {
maxDraw = this._daylightSavingAdjust( new Date( maxDate.getFullYear(),
maxDate.getMonth() - ( numMonths[ 0 ] * numMonths[ 1 ] ) + 1, maxDate.getDate() ) );
maxDraw = ( minDate && maxDraw < minDate ? minDate : maxDraw );
while ( this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 ) ) > maxDraw ) {
drawMonth--;
if ( drawMonth < 0 ) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
prevText = this._get( inst, "prevText" );
prevText = ( !navigationAsDateFormat ? prevText : this.formatDate( prevText,
this._daylightSavingAdjust( new Date( drawYear, drawMonth - stepMonths, 1 ) ),
this._getFormatConfig( inst ) ) );
prev = ( this._canAdjustMonth( inst, -1, drawYear, drawMonth ) ?
"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w" ) + "'>" + prevText + "</span></a>" :
( hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w" ) + "'>" + prevText + "</span></a>" ) );
nextText = this._get( inst, "nextText" );
nextText = ( !navigationAsDateFormat ? nextText : this.formatDate( nextText,
this._daylightSavingAdjust( new Date( drawYear, drawMonth + stepMonths, 1 ) ),
this._getFormatConfig( inst ) ) );
next = ( this._canAdjustMonth( inst, +1, drawYear, drawMonth ) ?
"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e" ) + "'>" + nextText + "</span></a>" :
( hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e" ) + "'>" + nextText + "</span></a>" ) );
currentText = this._get( inst, "currentText" );
gotoDate = ( this._get( inst, "gotoCurrent" ) && inst.currentDay ? currentDate : today );
currentText = ( !navigationAsDateFormat ? currentText :
this.formatDate( currentText, gotoDate, this._getFormatConfig( inst ) ) );
controls = ( !inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
this._get( inst, "closeText" ) + "</button>" : "" );
buttonPanel = ( showButtonPanel ) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + ( isRTL ? controls : "" ) +
( this._isInRange( inst, gotoDate ) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
">" + currentText + "</button>" : "" ) + ( isRTL ? "" : controls ) + "</div>" : "";
firstDay = parseInt( this._get( inst, "firstDay" ), 10 );
firstDay = ( isNaN( firstDay ) ? 0 : firstDay );
showWeek = this._get( inst, "showWeek" );
dayNames = this._get( inst, "dayNames" );
dayNamesMin = this._get( inst, "dayNamesMin" );
monthNames = this._get( inst, "monthNames" );
monthNamesShort = this._get( inst, "monthNamesShort" );
beforeShowDay = this._get( inst, "beforeShowDay" );
showOtherMonths = this._get( inst, "showOtherMonths" );
selectOtherMonths = this._get( inst, "selectOtherMonths" );
defaultDate = this._getDefaultDate( inst );
html = "";
for ( row = 0; row < numMonths[ 0 ]; row++ ) {
group = "";
this.maxRows = 4;
for ( col = 0; col < numMonths[ 1 ]; col++ ) {
selectedDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, inst.selectedDay ) );
cornerClass = " ui-corner-all";
calender = "";
if ( isMultiMonth ) {
calender += "<div class='ui-datepicker-group";
if ( numMonths[ 1 ] > 1 ) {
switch ( col ) {
case 0: calender += " ui-datepicker-group-first";
cornerClass = " ui-corner-" + ( isRTL ? "right" : "left" ); break;
case numMonths[ 1 ] - 1: calender += " ui-datepicker-group-last";
cornerClass = " ui-corner-" + ( isRTL ? "left" : "right" ); break;
default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
}
}
calender += "'>";
}
calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
( /all|left/.test( cornerClass ) && row === 0 ? ( isRTL ? next : prev ) : "" ) +
( /all|right/.test( cornerClass ) && row === 0 ? ( isRTL ? prev : next ) : "" ) +
this._generateMonthYearHeader( inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort ) + // draw month headers
"</div><table class='ui-datepicker-calendar'><thead>" +
"<tr>";
thead = ( showWeek ? "<th class='ui-datepicker-week-col'>" + this._get( inst, "weekHeader" ) + "</th>" : "" );
for ( dow = 0; dow < 7; dow++ ) { // days of the week
day = ( dow + firstDay ) % 7;
thead += "<th scope='col'" + ( ( dow + firstDay + 6 ) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "" ) + ">" +
"<span title='" + dayNames[ day ] + "'>" + dayNamesMin[ day ] + "</span></th>";
}
calender += thead + "</tr></thead><tbody>";
daysInMonth = this._getDaysInMonth( drawYear, drawMonth );
if ( drawYear === inst.selectedYear && drawMonth === inst.selectedMonth ) {
inst.selectedDay = Math.min( inst.selectedDay, daysInMonth );
}
leadDays = ( this._getFirstDayOfMonth( drawYear, drawMonth ) - firstDay + 7 ) % 7;
curRows = Math.ceil( ( leadDays + daysInMonth ) / 7 ); // calculate the number of rows to generate
numRows = ( isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows ); //If multiple months, use the higher number of rows (see #7043)
this.maxRows = numRows;
printDate = this._daylightSavingAdjust( new Date( drawYear, drawMonth, 1 - leadDays ) );
for ( dRow = 0; dRow < numRows; dRow++ ) { // create date picker rows
calender += "<tr>";
tbody = ( !showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
this._get( inst, "calculateWeek" )( printDate ) + "</td>" );
for ( dow = 0; dow < 7; dow++ ) { // create date picker days
daySettings = ( beforeShowDay ?
beforeShowDay.apply( ( inst.input ? inst.input[ 0 ] : null ), [ printDate ] ) : [ true, "" ] );
otherMonth = ( printDate.getMonth() !== drawMonth );
unselectable = ( otherMonth && !selectOtherMonths ) || !daySettings[ 0 ] ||
( minDate && printDate < minDate ) || ( maxDate && printDate > maxDate );
tbody += "<td class='" +
( ( dow + firstDay + 6 ) % 7 >= 5 ? " ui-datepicker-week-end" : "" ) + // highlight weekends
( otherMonth ? " ui-datepicker-other-month" : "" ) + // highlight days from other months
( ( printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent ) || // user pressed key
( defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime() ) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
" " + this._dayOverClass : "" ) + // highlight selected day
( unselectable ? " " + this._unselectableClass + " ui-state-disabled" : "" ) + // highlight unselectable days
( otherMonth && !showOtherMonths ? "" : " " + daySettings[ 1 ] + // highlight custom dates
( printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "" ) + // highlight selected day
( printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "" ) ) + "'" + // highlight today (if different)
( ( !otherMonth || showOtherMonths ) && daySettings[ 2 ] ? " title='" + daySettings[ 2 ].replace( /'/g, "'" ) + "'" : "" ) + // cell title
( unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'" ) + ">" + // actions
( otherMonth && !showOtherMonths ? " " : // display for other months
( unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
( printDate.getTime() === today.getTime() ? " ui-state-highlight" : "" ) +
( printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "" ) + // highlight selected day
( otherMonth ? " ui-priority-secondary" : "" ) + // distinguish dates from other months
"' href='#'>" + printDate.getDate() + "</a>" ) ) + "</td>"; // display selectable date
printDate.setDate( printDate.getDate() + 1 );
printDate = this._daylightSavingAdjust( printDate );
}
calender += tbody + "</tr>";
}
drawMonth++;
if ( drawMonth > 11 ) {
drawMonth = 0;
drawYear++;
}
calender += "</tbody></table>" + ( isMultiMonth ? "</div>" +
( ( numMonths[ 0 ] > 0 && col === numMonths[ 1 ] - 1 ) ? "<div class='ui-datepicker-row-break'></div>" : "" ) : "" );
group += calender;
}
html += group;
}
html += buttonPanel;
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function( inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort ) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get( inst, "changeMonth" ),
changeYear = this._get( inst, "changeYear" ),
showMonthAfterYear = this._get( inst, "showMonthAfterYear" ),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// Month selection
if ( secondary || !changeMonth ) {
monthHtml += "<span class='ui-datepicker-month'>" + monthNames[ drawMonth ] + "</span>";
} else {
inMinYear = ( minDate && minDate.getFullYear() === drawYear );
inMaxYear = ( maxDate && maxDate.getFullYear() === drawYear );
monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
for ( month = 0; month < 12; month++ ) {
if ( ( !inMinYear || month >= minDate.getMonth() ) && ( !inMaxYear || month <= maxDate.getMonth() ) ) {
monthHtml += "<option value='" + month + "'" +
( month === drawMonth ? " selected='selected'" : "" ) +
">" + monthNamesShort[ month ] + "</option>";
}
}
monthHtml += "</select>";
}
if ( !showMonthAfterYear ) {
html += monthHtml + ( secondary || !( changeMonth && changeYear ) ? " " : "" );
}
// Year selection
if ( !inst.yearshtml ) {
inst.yearshtml = "";
if ( secondary || !changeYear ) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get( inst, "yearRange" ).split( ":" );
thisYear = new Date().getFullYear();
determineYear = function( value ) {
var year = ( value.match( /c[+\-].*/ ) ? drawYear + parseInt( value.substring( 1 ), 10 ) :
( value.match( /[+\-].*/ ) ? thisYear + parseInt( value, 10 ) :
parseInt( value, 10 ) ) );
return ( isNaN( year ) ? thisYear : year );
};
year = determineYear( years[ 0 ] );
endYear = Math.max( year, determineYear( years[ 1 ] || "" ) );
year = ( minDate ? Math.max( year, minDate.getFullYear() ) : year );
endYear = ( maxDate ? Math.min( endYear, maxDate.getFullYear() ) : endYear );
inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
for ( ; year <= endYear; year++ ) {
inst.yearshtml += "<option value='" + year + "'" +
( year === drawYear ? " selected='selected'" : "" ) +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get( inst, "yearSuffix" );
if ( showMonthAfterYear ) {
html += ( secondary || !( changeMonth && changeYear ) ? " " : "" ) + monthHtml;
}
html += "</div>"; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function( inst, offset, period ) {
var year = inst.selectedYear + ( period === "Y" ? offset : 0 ),
month = inst.selectedMonth + ( period === "M" ? offset : 0 ),
day = Math.min( inst.selectedDay, this._getDaysInMonth( year, month ) ) + ( period === "D" ? offset : 0 ),
date = this._restrictMinMax( inst, this._daylightSavingAdjust( new Date( year, month, day ) ) );
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if ( period === "M" || period === "Y" ) {
this._notifyChange( inst );
}
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function( inst, date ) {
var minDate = this._getMinMaxDate( inst, "min" ),
maxDate = this._getMinMaxDate( inst, "max" ),
newDate = ( minDate && date < minDate ? minDate : date );
return ( maxDate && newDate > maxDate ? maxDate : newDate );
},
/* Notify change of month/year. */
_notifyChange: function( inst ) {
var onChange = this._get( inst, "onChangeMonthYear" );
if ( onChange ) {
onChange.apply( ( inst.input ? inst.input[ 0 ] : null ),
[ inst.selectedYear, inst.selectedMonth + 1, inst ] );
}
},
/* Determine the number of months to show. */
_getNumberOfMonths: function( inst ) {
var numMonths = this._get( inst, "numberOfMonths" );
return ( numMonths == null ? [ 1, 1 ] : ( typeof numMonths === "number" ? [ 1, numMonths ] : numMonths ) );
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function( inst, minMax ) {
return this._determineDate( inst, this._get( inst, minMax + "Date" ), null );
},
/* Find the number of days in a given month. */
_getDaysInMonth: function( year, month ) {
return 32 - this._daylightSavingAdjust( new Date( year, month, 32 ) ).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function( year, month ) {
return new Date( year, month, 1 ).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function( inst, offset, curYear, curMonth ) {
var numMonths = this._getNumberOfMonths( inst ),
date = this._daylightSavingAdjust( new Date( curYear,
curMonth + ( offset < 0 ? offset : numMonths[ 0 ] * numMonths[ 1 ] ), 1 ) );
if ( offset < 0 ) {
date.setDate( this._getDaysInMonth( date.getFullYear(), date.getMonth() ) );
}
return this._isInRange( inst, date );
},
/* Is the given date in the accepted range? */
_isInRange: function( inst, date ) {
var yearSplit, currentYear,
minDate = this._getMinMaxDate( inst, "min" ),
maxDate = this._getMinMaxDate( inst, "max" ),
minYear = null,
maxYear = null,
years = this._get( inst, "yearRange" );
if ( years ) {
yearSplit = years.split( ":" );
currentYear = new Date().getFullYear();
minYear = parseInt( yearSplit[ 0 ], 10 );
maxYear = parseInt( yearSplit[ 1 ], 10 );
if ( yearSplit[ 0 ].match( /[+\-].*/ ) ) {
minYear += currentYear;
}
if ( yearSplit[ 1 ].match( /[+\-].*/ ) ) {
maxYear += currentYear;
}
}
return ( ( !minDate || date.getTime() >= minDate.getTime() ) &&
( !maxDate || date.getTime() <= maxDate.getTime() ) &&
( !minYear || date.getFullYear() >= minYear ) &&
( !maxYear || date.getFullYear() <= maxYear ) );
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function( inst ) {
var shortYearCutoff = this._get( inst, "shortYearCutoff" );
shortYearCutoff = ( typeof shortYearCutoff !== "string" ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt( shortYearCutoff, 10 ) );
return { shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get( inst, "dayNamesShort" ), dayNames: this._get( inst, "dayNames" ),
monthNamesShort: this._get( inst, "monthNamesShort" ), monthNames: this._get( inst, "monthNames" ) };
},
/* Format the given date for display. */
_formatDate: function( inst, day, month, year ) {
if ( !day ) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = ( day ? ( typeof day === "object" ? day :
this._daylightSavingAdjust( new Date( year, month, day ) ) ) :
this._daylightSavingAdjust( new Date( inst.currentYear, inst.currentMonth, inst.currentDay ) ) );
return this.formatDate( this._get( inst, "dateFormat" ), date, this._getFormatConfig( inst ) );
}
} );
/*
* Bind hover events for datepicker elements.
* Done via delegate so the binding only occurs once in the lifetime of the parent div.
* Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
*/
function datepicker_bindHover( dpDiv ) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.on( "mouseout", selector, function() {
$( this ).removeClass( "ui-state-hover" );
if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
$( this ).removeClass( "ui-datepicker-prev-hover" );
}
if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
$( this ).removeClass( "ui-datepicker-next-hover" );
}
} )
.on( "mouseover", selector, datepicker_handleMouseover );
}
function datepicker_handleMouseover() {
if ( !$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? datepicker_instActive.dpDiv.parent()[ 0 ] : datepicker_instActive.input[ 0 ] ) ) {
$( this ).parents( ".ui-datepicker-calendar" ).find( "a" ).removeClass( "ui-state-hover" );
$( this ).addClass( "ui-state-hover" );
if ( this.className.indexOf( "ui-datepicker-prev" ) !== -1 ) {
$( this ).addClass( "ui-datepicker-prev-hover" );
}
if ( this.className.indexOf( "ui-datepicker-next" ) !== -1 ) {
$( this ).addClass( "ui-datepicker-next-hover" );
}
}
}
/* jQuery extend now ignores nulls! */
function datepicker_extendRemove( target, props ) {
$.extend( target, props );
for ( var name in props ) {
if ( props[ name ] == null ) {
target[ name ] = props[ name ];
}
}
return target;
}
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function( options ) {
/* Verify an empty collection wasn't passed - Fixes #6976 */
if ( !this.length ) {
return this;
}
/* Initialise the date picker. */
if ( !$.datepicker.initialized ) {
$( document ).on( "mousedown", $.datepicker._checkExternalClick );
$.datepicker.initialized = true;
}
/* Append datepicker main container to body if not exist. */
if ( $( "#" + $.datepicker._mainDivId ).length === 0 ) {
$( "body" ).append( $.datepicker.dpDiv );
}
var otherArgs = Array.prototype.slice.call( arguments, 1 );
if ( typeof options === "string" && ( options === "isDisabled" || options === "getDate" || options === "widget" ) ) {
return $.datepicker[ "_" + options + "Datepicker" ].
apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
}
if ( options === "option" && arguments.length === 2 && typeof arguments[ 1 ] === "string" ) {
return $.datepicker[ "_" + options + "Datepicker" ].
apply( $.datepicker, [ this[ 0 ] ].concat( otherArgs ) );
}
return this.each( function() {
typeof options === "string" ?
$.datepicker[ "_" + options + "Datepicker" ].
apply( $.datepicker, [ this ].concat( otherArgs ) ) :
$.datepicker._attachDatepicker( this, options );
} );
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.12.1";
var widgetsDatepicker = $.datepicker;
}));
|
(function( $ ) {
var productTaggedAs = '.woocommerce-page.single-product div.product .product_meta>span.tagged_as';
// Method for Control's event handlers: sh_pp_sty_tag_typography.
wp.customize('mk_cz[sh_pp_sty_tag_typography]', function (value) {
$(productTaggedAs).css(
mkPreviewTypography(value(), true, ['weight'])
);
$(productTaggedAs).find('a').css(
mkPreviewTypography(value(), false)
);
value.bind(function (to) {
$(productTaggedAs).css(
mkPreviewTypography(to, false, ['weight'])
);
$(productTaggedAs).find('a').css(
mkPreviewTypography(to, false)
);
});
});
// Method for Control's event handlers: sh_pp_sty_tag_box_model.
wp.customize('mk_cz[sh_pp_sty_tag_box_model]', function (value) {
$(productTaggedAs).css(
mkPreviewBoxModel(value())
);
value.bind(function (to) {
$(productTaggedAs).css(
mkPreviewBoxModel(to)
);
});
});
} )( jQuery );
|
// Initialize Firebase
let config = {
apiKey: "AIzaSyBbGawQb-iggUU-OYQ-c0kXeHj9mXLfEgk",
authDomain: "quick-bytes-c7a3c.firebaseapp.com",
databaseURL: "https://quick-bytes-c7a3c.firebaseio.com",
projectId: "quick-bytes-c7a3c",
storageBucket: "quick-bytes-c7a3c.appspot.com",
messagingSenderId: "210399752495"
};
firebase.initializeApp(config);
//firebase realtime database
console.log(firebase); // verify that firebase is loaded by logging the global it created for us
// #1 - get a reference to the databse
let database = firebase.database();
// #2 - refer to a root node named `scores`
let ref = database.ref('searches');
// #3 - create some data
let data = {
search: []
};
// #4 - send data, in this case we are adding it to the `scores` node
ref.set(data);
|
'use strict';
const BoxCommand = require('../../box-command');
const { flags } = require('@oclif/command');
class FilesMoveCommand extends BoxCommand {
async run() {
const { flags, args } = this.parse(FilesMoveCommand);
let updates = {
parent: {
id: args.parentID
}
};
if (flags.etag) {
updates.etag = flags.etag;
}
let movedFile = await this.client.files.update(args.id, updates);
await this.output(movedFile);
}
}
FilesMoveCommand.description = 'Move a file to a different folder';
FilesMoveCommand.flags = {
...BoxCommand.flags,
etag: flags.string({ description: 'Only move if etag value matches' })
};
FilesMoveCommand.args = [
{
name: 'id',
required: true,
hidden: false,
description: 'ID of the file to move',
},
{
name: 'parentID',
required: true,
hidden: false,
description: 'ID of the new parent folder to move the file into',
}
];
module.exports = FilesMoveCommand;
|
const querystring = require('querystring')
const https = require('https')
const { debug } = require('../helpers/debug')
const { generateErrorResponse } = require('../helpers/generate-response')
function validateCaptcha(app, captchaResponse) {
const config = app.config
return new Promise((resolve, reject) => {
const isDebug = app.config.debug
const secret = config.Captcha.secret
const post_data_json = {
secret,
response: captchaResponse,
}
const post_data = querystring.stringify(post_data_json)
debug(isDebug, post_data_json)
debug(isDebug, post_data)
const post_options = {
host: 'www.google.com',
port: '443',
path: '/recaptcha/api/siteverify',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
debug(isDebug, post_options)
const post_req = https.request(post_options, function (res) {
res.setEncoding('utf8')
let output = ''
res.on('data', function (chunk) {
output += chunk
})
res.on('end', function () {
debug(isDebug, '##############')
debug(isDebug, 'Output from validateCaptcha: ')
debug(isDebug, output)
debug(isDebug, '##############')
if (output) {
debug(isDebug, JSON.parse(output))
resolve(JSON.parse(output))
} else {
resolve()
}
})
})
post_req.on('error', function (error) {
debug(isDebug, error)
reject(error)
})
post_req.write(post_data, 'binary', function (error) {
if (error) debug(isDebug, error)
})
post_req.end()
})
}
module.exports = { validateCaptcha }
|
import React from 'react';
import { mount } from 'enzyme';
import { spyElementPrototype } from 'rc-util/lib/test/domHook';
import Popconfirm from '..';
import mountTest from '../../../tests/shared/mountTest';
import { sleep } from '../../../tests/utils';
import rtlTest from '../../../tests/shared/rtlTest';
import Button from '../../button';
describe('Popconfirm', () => {
mountTest(Popconfirm);
rtlTest(Popconfirm);
const eventObject = expect.objectContaining({
target: expect.anything(),
preventDefault: expect.any(Function),
});
beforeAll(() => {
spyElementPrototype(HTMLElement, 'offsetParent', {
get: () => ({}),
});
});
it('should popup Popconfirm dialog', () => {
const onVisibleChange = jest.fn();
const wrapper = mount(
<Popconfirm
title={<span className="popconfirm-test">Are you sure delete this task?</span>}
okText="Yes"
cancelText="No"
mouseEnterDelay={0}
mouseLeaveDelay={0}
onVisibleChange={onVisibleChange}
>
<span>Delete</span>
</Popconfirm>,
);
const triggerNode = wrapper.find('span').at(0);
triggerNode.simulate('click');
expect(onVisibleChange).toHaveBeenLastCalledWith(true, undefined);
expect(wrapper.find('.popconfirm-test').length).toBe(1);
triggerNode.simulate('click');
expect(onVisibleChange).toHaveBeenLastCalledWith(false, undefined);
});
it('should show overlay when trigger is clicked', async () => {
const ref = React.createRef();
const popconfirm = mount(
<Popconfirm ref={ref} title="code">
<span>show me your code</span>
</Popconfirm>,
);
expect(ref.current.getPopupDomNode()).toBe(null);
popconfirm.find('span').simulate('click');
await sleep(100);
const popup = ref.current.getPopupDomNode();
expect(popup).not.toBe(null);
expect(popup.className).toContain('ant-popover-placement-top');
expect(popup.innerHTML).toMatchSnapshot();
expect(popup.innerHTML).toMatchSnapshot();
});
it('shows content for render functions', async () => {
const makeRenderFunction = content => () => content;
const ref = React.createRef();
const popconfirm = mount(
<Popconfirm ref={ref} title={makeRenderFunction('some-title')}>
<span>show me your code</span>
</Popconfirm>,
);
expect(ref.current.getPopupDomNode()).toBe(null);
popconfirm.find('span').simulate('click');
await sleep(100);
const popup = ref.current.getPopupDomNode();
expect(popup).not.toBe(null);
expect(popup.innerHTML).toContain('some-title');
expect(popup.innerHTML).toMatchSnapshot();
});
it('should be controlled by visible', () => {
const ref = React.createRef();
jest.useFakeTimers();
const popconfirm = mount(
<Popconfirm ref={ref} title="code">
<span>show me your code</span>
</Popconfirm>,
);
expect(ref.current.getPopupDomNode()).toBeFalsy();
popconfirm.setProps({ visible: true });
expect(ref.current.getPopupDomNode()).toBeTruthy();
expect(ref.current.getPopupDomNode().className).not.toContain('ant-popover-hidden');
popconfirm.setProps({ visible: false });
popconfirm.update(); // https://github.com/enzymejs/enzyme/issues/2305
jest.runAllTimers();
expect(popconfirm.find('Trigger').props().popupVisible).toBe(false);
jest.useRealTimers();
});
it('should trigger onConfirm and onCancel', () => {
const confirm = jest.fn();
const cancel = jest.fn();
const onVisibleChange = jest.fn();
const popconfirm = mount(
<Popconfirm
title="code"
onConfirm={confirm}
onCancel={cancel}
onVisibleChange={onVisibleChange}
>
<span>show me your code</span>
</Popconfirm>,
);
const triggerNode = popconfirm.find('span').at(0);
triggerNode.simulate('click');
popconfirm.find('.ant-btn-primary').simulate('click');
expect(confirm).toHaveBeenCalled();
expect(onVisibleChange).toHaveBeenLastCalledWith(false, eventObject);
triggerNode.simulate('click');
popconfirm.find('.ant-btn').at(0).simulate('click');
expect(cancel).toHaveBeenCalled();
expect(onVisibleChange).toHaveBeenLastCalledWith(false, eventObject);
});
it('should support onConfirm to return Promise', async () => {
const confirm = () =>
new Promise(res => {
setTimeout(res, 300);
});
const onVisibleChange = jest.fn();
const popconfirm = mount(
<Popconfirm title="code" onConfirm={confirm} onVisibleChange={onVisibleChange}>
<span>show me your code</span>
</Popconfirm>,
);
const triggerNode = popconfirm.find('span').at(0);
triggerNode.simulate('click');
expect(onVisibleChange).toHaveBeenCalledTimes(1);
popconfirm.find('.ant-btn').at(0).simulate('click');
await sleep(400);
expect(onVisibleChange).toHaveBeenCalledWith(false, eventObject);
});
it('should support customize icon', () => {
const wrapper = mount(
<Popconfirm title="code" icon={<span className="customize-icon">custom-icon</span>}>
<span>show me your code</span>
</Popconfirm>,
);
const triggerNode = wrapper.find('span').at(0);
triggerNode.simulate('click');
expect(wrapper.find('.customize-icon').length).toBe(1);
});
it('should prefixCls correctly', () => {
const btnPrefixCls = 'custom-btn';
const wrapper = mount(
<Popconfirm
visible
title="x"
prefixCls="custom-popconfirm"
okButtonProps={{ prefixCls: btnPrefixCls }}
cancelButtonProps={{ prefixCls: btnPrefixCls }}
>
<span>show me your code</span>
</Popconfirm>,
);
expect(wrapper.find('.custom-popconfirm').length).toBeGreaterThan(0);
expect(wrapper.find('.custom-btn').length).toBeGreaterThan(0);
});
it('should support defaultVisible', () => {
const ref = React.createRef();
mount(
<Popconfirm ref={ref} title="code" defaultVisible>
<span>show me your code</span>
</Popconfirm>,
);
expect(ref.current.getPopupDomNode()).toBeTruthy();
});
it('should not open in disabled', () => {
const ref = React.createRef();
const popconfirm = mount(
<Popconfirm ref={ref} title="code" disabled>
<span>click me</span>
</Popconfirm>,
);
const triggerNode = popconfirm.find('span').at(0);
triggerNode.simulate('click');
expect(ref.current.getPopupDomNode()).toBeFalsy();
});
it('should be closed by pressing ESC', () => {
const onVisibleChange = jest.fn();
const wrapper = mount(
<Popconfirm
title="title"
mouseEnterDelay={0}
mouseLeaveDelay={0}
onVisibleChange={onVisibleChange}
>
<span>Delete</span>
</Popconfirm>,
);
const triggerNode = wrapper.find('span').at(0);
triggerNode.simulate('click');
expect(onVisibleChange).toHaveBeenLastCalledWith(true, undefined);
triggerNode.simulate('keydown', { key: 'Escape', keyCode: 27 });
expect(onVisibleChange).toHaveBeenLastCalledWith(false, eventObject);
});
it('should not warn memory leaking if setState in async callback', async () => {
const error = jest.spyOn(console, 'error');
const Test = () => {
const [show, setShow] = React.useState(true);
if (show) {
return (
<Popconfirm
title="will unmount"
onConfirm={() =>
new Promise(resolve => {
setTimeout(() => {
setShow(false);
resolve();
}, 300);
})
}
>
<Button className="clickTarget">Test</Button>
</Popconfirm>
);
}
return <Button>Unmounted</Button>;
};
const wrapper = mount(
<div>
<Test />
</div>,
);
expect(wrapper.text()).toEqual('Test');
const triggerNode = wrapper.find('.clickTarget').at(0);
triggerNode.simulate('click');
wrapper.find('.ant-btn-primary').simulate('click');
await sleep(500);
expect(wrapper.text()).toEqual('Unmounted');
expect(error).not.toHaveBeenCalled();
});
});
|
// source ../src/head.js
(function (root, factory) {
'use strict';
var _global, _exports;
if (typeof exports !== 'undefined' && (root === exports || root == null)){
// raw nodejs module
_global = _exports = global;
}
if (_global == null) {
_global = typeof window === 'undefined' ? global : window;
}
if (_exports == null) {
_exports = root || _global;
}
if (typeof include !== 'undefined' && typeof include.js === 'function') {
// allow only one `include` per application
_exports.include = include;
_exports.includeLib = include.Lib || _global.includeLib;
return;
}
factory(_global, _exports, _global.document);
}(this, function (global, exports, document) {
'use strict';
// end:source ../src/head.js
// source ../src/1.scope-vars.js
/**
* .cfg
* : path := root path. @default current working path, im browser window.location;
* : eval := in node.js this conf. is forced
* : lockedToFolder := makes current url as root path
* Example "/script/main.js" within this window.location "{domain}/apps/1.html"
* will become "{domain}/apps/script/main.js" instead of "{domain}/script/main.js"
*/
var bin = {
js: {},
css: {},
load: {}
},
isWeb = !! (global.location && global.location.protocol && /^https?:/.test(global.location.protocol)),
reg_subFolder = /([^\/]+\/)?\.\.\//,
reg_hasProtocol = /^(file|https?):/i,
cfg = {
path: null,
loader: null,
version: null,
lockedToFolder: null,
sync: null,
eval: document == null
},
handler = {},
hasOwnProp = {}.hasOwnProperty,
emptyResponse = {
load: {}
},
__array_slice = Array.prototype.slice,
XMLHttpRequest = global.XMLHttpRequest;
// end:source ../src/1.scope-vars.js
// source ../src/2.Helper.js
var Helper = { /** TODO: improve url handling*/
reportError: function(e) {
console.error('IncludeJS Error:', e, e.message, e.url);
typeof handler.onerror === 'function' && handler.onerror(e);
}
},
XHR = function(resource, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
xhr.readyState === 4 && callback && callback(resource, xhr.responseText);
};
xhr.open('GET', typeof resource === 'object' ? resource.url : resource, true);
xhr.send();
};
// end:source ../src/2.Helper.js
// source ../src/utils/fn.js
function fn_proxy(fn, ctx) {
return function(){
fn.apply(ctx, arguments);
};
}
function fn_doNothing(fn) {
typeof fn === 'function' && fn();
}
// end:source ../src/utils/fn.js
// source ../src/utils/object.js
var obj_inherit,
obj_getProperty,
obj_setProperty
;
(function(){
obj_inherit = function(target /* source, ..*/ ) {
if (typeof target === 'function') {
target = target.prototype;
}
var i = 1,
imax = arguments.length,
source, key;
for (; i < imax; i++) {
source = typeof arguments[i] === 'function'
? arguments[i].prototype
: arguments[i];
for (key in source) {
target[key] = source[key];
}
}
return target;
};
obj_getProperty = function(obj, property) {
var chain = property.split('.'),
length = chain.length,
i = 0;
for (; i < length; i++) {
if (obj == null)
return null;
obj = obj[chain[i]];
}
return obj;
};
obj_setProperty = function(obj, property, value) {
var chain = property.split('.'),
imax = chain.length - 1,
i = -1,
key;
while ( ++i < imax ) {
key = chain[i];
if (obj[key] == null)
obj[key] = {};
obj = obj[key];
}
obj[chain[i]] = value;
};
}());
// end:source ../src/utils/object.js
// source ../src/utils/array.js
function arr_invoke(arr, args, ctx) {
if (arr == null || arr instanceof Array === false) {
return;
}
for (var i = 0, length = arr.length; i < length; i++) {
if (typeof arr[i] !== 'function') {
continue;
}
if (args == null) {
arr[i].call(ctx);
}else{
arr[i].apply(ctx, args);
}
}
}
function arr_ensure(obj, xpath) {
if (!xpath) {
return obj;
}
var arr = xpath.split('.'),
imax = arr.length - 1,
i = 0,
key;
for (; i < imax; i++) {
key = arr[i];
obj = obj[key] || (obj[key] = {});
}
key = arr[imax];
return obj[key] || (obj[key] = []);
}
// end:source ../src/utils/array.js
// source ../src/utils/path.js
var path_getDir,
path_getFile,
path_getExtension,
path_resolveCurrent,
path_normalize,
path_win32Normalize,
path_resolveUrl,
path_combine,
path_isRelative
;
(function(){
path_getDir = function(path) {
return path.substring(0, path.lastIndexOf('/') + 1);
};
path_getFile = function(path) {
path = path
.replace('file://', '')
.replace(/\\/g, '/')
.replace(/\?[^\n]+$/, '');
if (/^\/\w+:\/[^\/]/i.test(path)){
// win32 drive
return path.substring(1);
}
return path;
};
path_getExtension = function(path) {
var query = path.indexOf('?');
if (query === -1) {
return path.substring(path.lastIndexOf('.') + 1);
}
return path.substring(path.lastIndexOf('.', query) + 1, query);
};
path_resolveCurrent = function() {
if (document == null) {
return typeof module === 'undefined'
? ''
: path_win32Normalize(module.parent.filename);
}
var scripts = document.getElementsByTagName('script'),
last = scripts[scripts.length - 1],
url = last && last.getAttribute('src') || '';
if (url[0] === '/') {
return url;
}
var location = window
.location
.pathname
.replace(/\/[^\/]+\.\w+$/, '');
if (location[location.length - 1] !== '/') {
location += '/';
}
return location + url;
};
path_normalize = function(path) {
return path
.replace(/\\/g, '/')
// remove double slashes, but not near protocol
.replace(/([^:\/])\/{2,}/g, '$1/')
;
};
path_win32Normalize = function(path){
path = path_normalize(path);
if (path.substring(0, 5) === 'file:')
return path;
return 'file:///' + path;
};
path_resolveUrl = function(url, parent) {
if (reg_hasProtocol.test(url))
return path_collapse(url);
if (url.substring(0, 2) === './')
url = url.substring(2);
if (url[0] === '/' && parent != null && parent.base != null) {
url = path_combine(parent.base, url);
if (reg_hasProtocol.test(url))
return path_collapse(url);
}
if (url[0] === '/' && cfg.path) {
url = cfg.path + url.substring(1);
if (reg_hasProtocol.test(url))
return path_collapse(url);
}
if (url[0] === '/') {
if (isWeb === false || cfg.lockedToFolder === true) {
url = url.substring(1);
}
} else if (parent != null && parent.location != null) {
url = parent.location + url;
}
return path_collapse(url);
};
path_isRelative = function(path) {
var c = path.charCodeAt(0);
switch (c) {
case 47:
// /
return false;
case 102:
// f
case 104:
// h
return reg_hasProtocol.test(path) === false;
}
return true;
};
path_combine = function() {
var out = '',
imax = arguments.length,
i = -1,
x
;
while ( ++i < imax ){
x = arguments[i];
if (!x)
continue;
x = path_normalize(x);
if (out === '') {
out = x;
continue;
}
if (out[out.length - 1] !== '/')
out += '/'
if (x[0] === '/')
x = x.substring(1);
out += x;
}
return out;
};
function path_collapse(url) {
while (url.indexOf('../') !== -1) {
url = url.replace(reg_subFolder, '');
}
return url.replace(/\/\.\//g, '/');
}
}());
// end:source ../src/utils/path.js
// source ../src/utils/tree.js
var tree_resolveUsage;
(function(){
tree_resolveUsage = function(resource, usage, next){
var use = [],
imax = usage.length,
i = -1,
obj, path, name, index, parent
;
while( ++i < imax ) {
name = path = usage[i];
index = path.indexOf('.');
if ( index !== -1) {
name = path.substring(0, index);
path = path.substring(index + 1);
}
parent = use_resolveParent(name, resource.parent, resource);
if (parent == null)
return null;
if (parent.state !== 4){
resource.state = 3;
parent.on(4, next, parent, 'push');
return null;
}
obj = parent.exports;
if (name !== path)
obj = obj_getProperty(obj, path);
// if DEBUG
(typeof obj === 'object' && obj == null)
&& console.warn('<include:use> Used resource has no exports', name, resource.url);
// endif
use[i] = obj;
}
return use;
};
function use_resolveParent(name, resource, initiator){
if (resource == null) {
// if DEBUG
console.warn('<include> Usage Not Found:', name);
console.warn('- Ensure to have it included before with the correct alias')
console.warn('- Initiator Stacktrace:');
var arr = [], res = initiator;
while(res != null){
arr.push(res.url);
res = res.parent;
}
console.warn(arr.join('\n'));
// endif
return null;
}
var includes = resource.includes,
i = -1,
imax = includes.length,
include, exports, alias
;
while( ++i < imax ) {
include = includes[i];
alias = include.route.alias || Routes.parseAlias(include.route);
if (alias === name)
return include.resource;
}
return use_resolveParent(name, resource.parent, initiator);
}
}());
// end:source ../src/utils/tree.js
// source ../src/2.Routing.js
var RoutesLib = function() {
var routes = {},
regexpAlias = /([^\\\/]+)\.\w+$/;
return {
/**
* @param route {String} = Example: '.reference/libjs/{0}/{1}.js'
*/
register: function(namespace, route, currentInclude) {
if (typeof route === 'string' && path_isRelative(route)) {
var res = currentInclude || include,
location = res.location || path_getDir(res.url || path_resolveCurrent());
if (path_isRelative(location)) {
location = '/' + location;
}
route = location + route;
}
routes[namespace] = route instanceof Array ? route : route.split(/[\{\}]/g);
},
/**
* @param {String} template = Example: 'scroller/scroller.min?ui=black'
*/
resolve: function(namespace, template) {
var questionMark = template.indexOf('?'),
aliasIndex = template.indexOf('::'),
alias,
path,
params,
route,
i,
x,
length,
arr;
if (aliasIndex !== -1){
alias = template.substring(aliasIndex + 2);
template = template.substring(0, aliasIndex);
}
if (questionMark !== -1) {
arr = template.substring(questionMark + 1).split('&');
params = {};
for (i = 0, length = arr.length; i < length; i++) {
x = arr[i].split('=');
params[x[0]] = x[1];
}
template = template.substring(0, questionMark);
}
template = template.split('/');
route = routes[namespace];
if (route == null){
return {
path: template.join('/'),
params: params,
alias: alias
};
}
path = route[0];
for (i = 1; i < route.length; i++) {
if (i % 2 === 0) {
path += route[i];
} else {
/** if template provides less "breadcrumbs" than needed -
* take always the last one for failed peaces */
var index = route[i] << 0;
if (index > template.length - 1) {
index = template.length - 1;
}
path += template[index];
if (i === route.length - 2){
for(index++; index < template.length; index++){
path += '/' + template[index];
}
}
}
}
return {
path: path,
params: params,
alias: alias
};
},
/**
* @arg includeData :
* 1. string - URL to resource
* 2. array - URLs to resources
* 3. object - {route: x} - route defines the route template to resource,
* it must be set before in include.cfg.
* example:
* include.cfg('net','scripts/net/{name}.js')
* include.js({net: 'downloader'}) // -> will load scipts/net/downloader.js
* @arg namespace - route in case of resource url template, or namespace in case of LazyModule
*
* @arg fn - callback function, which receives namespace|route, url to resource and ?id in case of not relative url
* @arg xpath - xpath string of a lazy object 'object.sub.and.othersub';
*/
each: function(type, includeData, fn, namespace, xpath) {
var key;
if (includeData == null) {
return;
}
if (type === 'lazy' && xpath == null) {
for (key in includeData) {
this.each(type, includeData[key], fn, null, key);
}
return;
}
if (includeData instanceof Array) {
for (var i = 0; i < includeData.length; i++) {
this.each(type, includeData[i], fn, namespace, xpath);
}
return;
}
if (typeof includeData === 'object') {
for (key in includeData) {
if (hasOwnProp.call(includeData, key)) {
this.each(type, includeData[key], fn, key, xpath);
}
}
return;
}
if (typeof includeData === 'string') {
var x = this.resolve(namespace, includeData);
if (namespace){
namespace += '.' + includeData;
}
fn(namespace, x, xpath);
return;
}
console.error('Include Package is invalid', arguments);
},
getRoutes: function(){
return routes;
},
parseAlias: function(route){
var path = route.path,
result = regexpAlias.exec(path);
return result && result[1];
}
};
};
var Routes = RoutesLib();
/*{test}
console.log(JSON.stringify(Routes.resolve(null,'scroller.js::Scroller')));
Routes.register('lib', '.reference/libjs/{0}/lib/{1}.js');
console.log(JSON.stringify(Routes.resolve('lib','scroller::Scroller')));
console.log(JSON.stringify(Routes.resolve('lib','scroller/scroller.mobile?ui=black')));
Routes.register('framework', '.reference/libjs/framework/{0}.js');
console.log(JSON.stringify(Routes.resolve('framework','dom/jquery')));
*/
// end:source ../src/2.Routing.js
// source ../src/3.Events.js
var Events = (function(document) {
if (document == null) {
return {
ready: fn_doNothing,
load: fn_doNothing
};
}
var readycollection = [];
function onReady() {
Events.ready = fn_doNothing;
if (readycollection == null) {
return;
}
arr_invoke(readycollection);
readycollection = null;
}
/** TODO: clean this */
if ('onreadystatechange' in document) {
document.onreadystatechange = function() {
if (/complete|interactive/g.test(document.readyState) === false) {
return;
}
onReady();
};
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', onReady);
}else {
window.onload = onReady;
}
return {
ready: function(callback) {
readycollection.unshift(callback);
}
};
})(document);
// end:source ../src/3.Events.js
// source ../src/6.ScriptStack.js
/** @TODO Refactor loadBy* {combine logic} */
var ScriptStack = (function() {
var head,
currentResource,
stack = [],
_cb_complete = [],
_paused;
function loadScript(url, callback) {
//console.log('load script', url);
var tag = document.createElement('script');
tag.type = 'text/javascript';
tag.src = url;
if ('onreadystatechange' in tag) {
tag.onreadystatechange = function() {
(this.readyState === 'complete' || this.readyState === 'loaded') && callback();
};
} else {
tag.onload = tag.onerror = callback;
}
;(head || (head = document.getElementsByTagName('head')[0])).appendChild(tag);
}
function loadByEmbedding() {
if (_paused) {
return;
}
if (stack.length === 0){
trigger_complete();
return;
}
if (currentResource != null) {
return;
}
var resource = (currentResource = stack[0]);
if (resource.state === 1) {
return;
}
resource.state = 1;
global.include = resource;
global.iparams = resource.route.params;
function resourceLoaded(e) {
if (e && e.type === 'error') {
console.log('Script Loaded Error', resource.url);
}
var i = 0,
length = stack.length;
for (; i < length; i++) {
if (stack[i] === resource) {
stack.splice(i, 1);
break;
}
}
if (i === length) {
console.error('Loaded Resource not found in stack', resource);
return;
}
if (resource.state !== 2.5)
resource.readystatechanged(3);
currentResource = null;
loadByEmbedding();
}
if (resource.source) {
__eval(resource.source, resource);
resourceLoaded();
return;
}
loadScript(resource.url, resourceLoaded);
}
function processByEval() {
if (_paused) {
return;
}
if (stack.length === 0){
trigger_complete();
return;
}
if (currentResource != null) {
return;
}
var resource = stack[0];
if (resource.state < 2) {
return;
}
currentResource = resource;
resource.state = 1;
global.include = resource;
//console.log('evaling', resource.url, stack.length);
__eval(resource.source, resource);
for (var i = 0, x, length = stack.length; i < length; i++) {
x = stack[i];
if (x === resource) {
stack.splice(i, 1);
break;
}
}
if (resource.state !== 2.5)
resource.readystatechanged(3);
currentResource = null;
processByEval();
}
function trigger_complete() {
var i = -1,
imax = _cb_complete.length;
while (++i < imax) {
_cb_complete[i]();
}
_cb_complete.length = 0;
}
return {
load: function(resource, parent, forceEmbed) {
this.add(resource, parent);
if (!cfg.eval || forceEmbed) {
loadByEmbedding();
return;
}
// was already loaded, with custom loader for example
if (resource.source) {
resource.state = 2;
processByEval();
return;
}
XHR(resource, function(resource, response) {
if (!response) {
console.error('Not Loaded:', resource.url);
console.error('- Initiator:', resource.parent && resource.parent.url || '<root resource>');
}
resource.source = response;
resource.state = 2;
processByEval();
});
},
add: function(resource, parent){
if (resource.priority === 1)
return stack.unshift(resource);
if (parent == null)
return stack.push(resource);
var imax = stack.length,
i = -1
;
// move close to parent
while( ++i < imax){
if (stack[i] === parent)
return stack.splice(i, 0, resource);
}
// was still not added
stack.push(resource);
},
/* Move resource in stack close to parent */
moveToParent: function(resource, parent) {
var length = stack.length,
parentIndex = -1,
resourceIndex = -1,
i;
for (i = 0; i < length; i++) {
if (stack[i] === resource) {
resourceIndex = i;
break;
}
}
if (resourceIndex === -1) {
return;
}
for (i= 0; i < length; i++) {
if (stack[i] === parent) {
parentIndex = i;
break;
}
}
if (parentIndex === -1) {
return;
}
if (resourceIndex < parentIndex) {
return;
}
stack.splice(resourceIndex, 1);
stack.splice(parentIndex, 0, resource);
},
pause: function(){
_paused = true;
},
resume: function(){
_paused = false;
if (currentResource != null)
return;
this.touch();
},
touch: function(){
var fn = cfg.eval
? processByEval
: loadByEmbedding
;
fn();
},
complete: function(callback){
if (_paused !== true && stack.length === 0) {
callback();
return;
}
_cb_complete.push(callback);
}
};
})();
// end:source ../src/6.ScriptStack.js
// source ../src/4.IncludeDeferred.js
/**
* STATES:
* 0: Resource Created
* 1: Loading
* 2: Loaded - Evaluating
* 2.5: Paused - Evaluating paused
* 3: Evaluated - Childs Loading
* 4: Childs Loaded - Completed
*/
var IncludeDeferred = function() {
this.callbacks = [];
this.state = -1;
};
IncludeDeferred.prototype = { /** state observer */
on: function(state, callback, sender, mutator) {
if (this === sender && this.state === -1) {
callback(this);
return this;
}
// this === sender in case when script loads additional
// resources and there are already parents listeners
if (mutator == null) {
mutator = (this.state < 3 || this === sender)
? 'unshift'
: 'push'
;
}
state <= this.state ? callback(this) : this.callbacks[mutator]({
state: state,
callback: callback
});
return this;
},
readystatechanged: function(state) {
var i, length, x, currentInclude;
if (state > this.state) {
this.state = state;
}
if (this.state === 3) {
var includes = this.includes;
if (includes != null && includes.length) {
for (i = 0; i < includes.length; i++) {
if (includes[i].resource.state !== 4) {
return;
}
}
}
this.state = 4;
}
i = 0;
length = this.callbacks.length;
if (length === 0){
return;
}
//do not set asset resource to global
if (this.type === 'js' && this.state === 4) {
currentInclude = global.include;
global.include = this;
}
for (; i < length; i++) {
x = this.callbacks[i];
if (x == null || x.state > this.state) {
continue;
}
this.callbacks.splice(i,1);
length--;
i--;
/* if (!DEBUG)
try {
*/
x.callback(this);
/* if (!DEBUG)
} catch(error){
console.error(error.toString(), 'file:', this.url);
}
*/
if (this.state < 4){
break;
}
}
if (currentInclude != null && currentInclude.type === 'js'){
global.include = currentInclude;
}
},
/** assets loaded and DomContentLoaded */
ready: function(callback) {
var that = this;
return this.on(4, function() {
Events.ready(function(){
that.resolve(callback);
});
}, this);
},
/** assets loaded */
done: function(callback) {
var that = this;
return this.on(4, function(){
that.resolve(callback);
}, this);
},
resolve: function(callback) {
var includes = this.includes,
length = includes == null
? 0
: includes.length
;
if (length > 0 && this.response == null){
this.response = {};
var resource,
route;
for(var i = 0, x; i < length; i++){
x = includes[i];
resource = x.resource;
route = x.route;
if (typeof resource.exports === 'undefined')
continue;
var type = resource.type;
switch (type) {
case 'js':
case 'load':
case 'ajax':
var alias = route.alias || Routes.parseAlias(route),
obj = type === 'js'
? (this.response)
: (this.response[type] || (this.response[type] = {}))
;
if (alias != null) {
obj_setProperty(obj, alias, resource.exports);
break;
}
console.warn('<includejs> Alias is undefined', resource);
break;
}
}
}
var response = this.response || emptyResponse;
var that = this;
if (this._use == null && this._usage != null){
this._use = tree_resolveUsage(this, this._usage, function(){
that.state = 4;
that.resolve(callback);
that.readystatechanged(4);
});
if (this.state < 4)
return;
}
if (this._use) {
callback.apply(null, [response].concat(this._use));
return;
}
callback(response);
}
};
// end:source ../src/4.IncludeDeferred.js
// source ../src/5.Include.js
var Include,
IncludeLib = {};
(function(IncludeDeferred) {
Include = function() {
IncludeDeferred.call(this);
};
stub_release(Include.prototype);
obj_inherit(Include, IncludeDeferred, {
// Array: exports
_use: null,
// Array: names
_usage: null,
isBrowser: true,
isNode: false,
setCurrent: function(data) {
var url = data.url,
resource = this.getResourceById(url, 'js');
if (resource == null) {
if (url[0] === '/' && this.base)
url = this.base + url.substring(1);
var resource = new Resource(
'js'
, { path: url }
, data.namespace
, null
, null
, url);
}
if (resource.state < 3) {
console.error("<include> Resource should be loaded", data);
}
/**@TODO - probably state shoulb be changed to 2 at this place */
resource.state = 3;
global.include = resource;
},
cfg: function(arg) {
switch (typeof arg) {
case 'object':
var key, value;
for (key in arg) {
value = arg[key];
switch(key){
case 'loader':
for(var x in value){
CustomLoader.register(x, value[x]);
}
break;
case 'modules':
if (value === true){
enableModules();
}
break;
default:
cfg[key] = value;
break;
}
}
break;
case 'string':
if (arguments.length === 1) {
return cfg[arg];
}
if (arguments.length === 2) {
cfg[arg] = arguments[1];
}
break;
case 'undefined':
return cfg;
}
return this;
},
routes: function(mix) {
if (mix == null) {
return Routes.getRoutes();
}
if (arguments.length === 2) {
Routes.register(mix, arguments[1], this);
return this;
}
for (var key in mix) {
Routes.register(key, mix[key], this);
}
return this;
},
promise: function(namespace) {
var arr = namespace.split('.'),
obj = global;
while (arr.length) {
var key = arr.shift();
obj = obj[key] || (obj[key] = {});
}
return obj;
},
/** @TODO - `id` property seems to be unsed and always equal to `url` */
register: function(_bin) {
var base = this.base,
key,
info,
infos,
imax,
i;
function transform(info){
if (base == null)
return info;
if (info.url[0] === '/')
info.url = base + info.url.substring(1);
if (info.parent[0] === '/')
info.parent = base + info.parent.substring(1);
info.id = info.url;
return info;
}
for (key in _bin) {
infos = _bin[key];
imax = infos.length;
i = -1;
while ( ++i < imax ) {
info = transform(infos[i]);
var id = info.id,
url = info.url,
namespace = info.namespace,
parent = info.parent && incl_getResource(info.parent, 'js'),
resource = new Resource(),
state = info.state
;
if (! (id || url))
continue;
if (url) {
if (url[0] === '/') {
url = url.substring(1);
}
resource.location = path_getDir(url);
}
resource.state = state == null
? (key === 'js' ? 3 : 4)
: state
;
resource.namespace = namespace;
resource.type = key;
resource.url = url || id;
resource.parent = parent;
resource.base = parent && parent.base || base;
switch (key) {
case 'load':
case 'lazy':
var container = document.querySelector('#includejs-' + id.replace(/\W/g, ''));
if (container == null) {
console.error('"%s" Data was not embedded into html', id);
break;
}
resource.exports = container.innerHTML;
if (CustomLoader.exists(resource)){
resource.state = 3;
CustomLoader.load(resource, CustomLoader_onComplete);
}
break;
}
//
(bin[key] || (bin[key] = {}))[id] = resource;
}
}
function CustomLoader_onComplete(resource, response) {
resource.exports = response;
resource.readystatechanged(4);
}
},
/**
* Create new Resource Instance,
* as sometimes it is necessary to call include. on new empty context
*/
instance: function(url, parent) {
var resource;
if (url == null) {
resource = new Include();
resource.state = 4;
return resource;
}
resource = new Resource('package');
resource.state = 4;
resource.location = path_getDir(path_normalize(url));
resource.parent = parent;
return resource;
},
getResource: function(url, type){
if (this.base && url[0] === '/')
url = this.base + url.substring(1);
return incl_getResource(url, type)
},
getResourceById: function(url, type){
var _bin = bin[type],
_res = _bin[url];
if (_res != null)
return _res;
if (this.base && url[0] === '/') {
_res = _bin[path_combine(this.base, url)];
if (_res != null)
return _res;
}
if (this.base && this.location) {
_res = _bin[path_combine(this.base, this.location, url)];
if (_res != null)
return _res;
}
if (this.location) {
_res = _bin[path_combine(this.location, url)];
if (_res != null)
return _res;
}
return null;
},
getResources: function(){
return bin;
},
plugin: function(pckg, callback) {
var urls = [],
length = 0,
j = 0,
i = 0,
onload = function(url, response) {
j++;
embedPlugin(response);
if (j === length - 1 && callback) {
callback();
callback = null;
}
};
Routes.each('', pckg, function(namespace, route) {
urls.push(route.path[0] === '/' ? route.path.substring(1) : route.path);
});
length = urls.length;
for (; i < length; i++) {
XHR(urls[i], onload);
}
return this;
},
client: function(){
if (cfg.server === true)
stub_freeze(this);
return this;
},
server: function(){
if (cfg.server !== true)
stub_freeze(this);
return this;
},
use: function(){
if (this.parent == null) {
console.error('<include.use> Parent resource is undefined');
return this;
}
this._usage = arguments;
return this;
},
pauseStack: fn_proxy(ScriptStack.pause, ScriptStack),
resumeStack: fn_proxy(ScriptStack.resume, ScriptStack),
allDone: function(callback){
ScriptStack.complete(function(){
var pending = include.getPending(),
await = pending.length;
if (await === 0) {
callback();
return;
}
var i = -1,
imax = await;
while( ++i < imax ){
pending[i].on(4, check, null, 'push');
}
function check() {
if (--await < 1)
callback();
}
});
},
getPending: function(type){
var resources = [],
res, key, id;
for(key in bin){
if (type != null && type !== key)
continue;
for (id in bin[key]){
res = bin[key][id];
if (res.state < 4)
resources.push(res);
}
}
return resources;
},
Lib: IncludeLib
});
// >> FUNCTIONS
function incl_getResource(url, type) {
var id = url;
if (path_isRelative(url) === true)
id = '/' + id;
if (type != null){
return bin[type][id];
}
for (var key in bin) {
if (bin[key].hasOwnProperty(id)) {
return bin[key][id];
}
}
return null;
}
function embedPlugin(source) {
eval(source);
}
function enableModules() {
if (typeof Object.defineProperty === 'undefined'){
console.warn('Browser do not support Object.defineProperty');
return;
}
Object.defineProperty(global, 'module', {
get: function() {
return global.include;
}
});
Object.defineProperty(global, 'exports', {
get: function() {
var current = global.include;
return (current.exports || (current.exports = {}));
},
set: function(exports) {
global.include.exports = exports;
}
});
}
function includePackage(resource, type, mix){
var pckg = mix.length === 1 ? mix[0] : __array_slice.call(mix);
if (resource instanceof Resource) {
return resource.include(type, pckg);
}
return new Resource('js').include(type, pckg);
}
function createIncluder(type) {
return function(){
return includePackage(this, type, arguments);
};
}
function doNothing() {
return this;
}
function stub_freeze(include) {
include.js =
include.css =
include.load =
include.ajax =
include.embed =
include.lazy =
include.inject =
doNothing;
}
function stub_release(proto) {
var fns = ['js', 'css', 'load', 'ajax', 'embed', 'lazy'],
i = fns.length;
while (--i !== -1){
proto[fns[i]] = createIncluder(fns[i]);
}
proto['inject'] = proto.js;
}
}(IncludeDeferred));
// end:source ../src/5.Include.js
// source ../src/7.CustomLoader.js
var CustomLoader = (function() {
// source loader/json.js
var JSONParser = {
process: function(source, res){
try {
return JSON.parse(source);
} catch(error) {
console.error(error, source);
return null;
}
}
};
// end:source loader/json.js
cfg.loader = {
json : JSONParser
};
function loader_isInstance(x) {
if (typeof x === 'string')
return false;
return typeof x.ready === 'function' || typeof x.process === 'function';
}
function createLoader(url) {
var extension = path_getExtension(url),
loader = cfg.loader[extension];
if (loader_isInstance(loader)) {
return loader;
}
var path = loader,
namespace;
if (typeof path === 'object') {
// is route {namespace: path}
for (var key in path) {
namespace = key;
path = path[key];
break;
}
}
return (cfg.loader[extension] = new Resource(
'js',
Routes.resolve(namespace, path),
namespace,
null,
null,
null,
1
));
}
function loader_completeDelegate(callback, resource) {
return function(response){
callback(resource, response);
};
}
function loader_process(source, resource, loader, callback) {
if (loader.process == null) {
callback(resource, source);
return;
}
var delegate = loader_completeDelegate(callback, resource),
syncResponse = loader.process(source, resource, delegate);
// match also null
if (typeof syncResponse !== 'undefined') {
callback(resource, syncResponse);
}
}
function tryLoad(resource, loader, callback) {
if (typeof resource.exports === 'string') {
loader_process(resource.exports, resource, loader, callback);
return;
}
function onLoad(resource, response){
loader_process(response, resource, loader, callback);
}
if (loader.load)
return loader.load(resource, onLoad);
XHR(resource, onLoad);
}
return {
load: function(resource, callback) {
var loader = createLoader(resource.url);
if (loader.process) {
tryLoad(resource, loader, callback);
return;
}
loader.on(4, function() {
tryLoad(resource, loader.exports, callback);
}, null, 'push');
},
exists: function(resource) {
if (!resource.url) {
return false;
}
var ext = path_getExtension(resource.url);
return cfg.loader.hasOwnProperty(ext);
},
/**
* IHandler:
* { process: function(content) { return _handler(content); }; }
*
* Url:
* path to IHandler
*/
register: function(extension, handler){
if (typeof handler === 'string'){
var resource = include;
if (resource.location == null) {
resource = {
location: path_getDir(path_resolveCurrent())
};
}
handler = path_resolveUrl(handler, resource);
}
cfg.loader[extension] = handler;
}
};
}());
// end:source ../src/7.CustomLoader.js
// source ../src/8.LazyModule.js
var LazyModule = {
create: function(xpath, code) {
var arr = xpath.split('.'),
obj = global,
module = arr[arr.length - 1];
while (arr.length > 1) {
var prop = arr.shift();
obj = obj[prop] || (obj[prop] = {});
}
arr = null;
Object.defineProperty(obj, module, {
get: function() {
delete obj[module];
try {
var r = __eval(code, global.include);
if (!(r == null || r instanceof Resource)){
obj[module] = r;
}
} catch (error) {
error.xpath = xpath;
Helper.reportError(error);
} finally {
code = null;
xpath = null;
return obj[module];
}
}
});
}
};
// end:source ../src/8.LazyModule.js
// source ../src/9.Resource.js
var Resource;
(function(Include, Routes, ScriptStack, CustomLoader) {
Resource = function(type, route, namespace, xpath, parent, id, priority) {
Include.call(this);
this.childLoaded = fn_proxy(this.childLoaded, this);
var url = route && route.path;
if (url != null)
this.url = url = path_resolveUrl(url, parent);
this.type = type;
this.xpath = xpath;
this.route = route;
this.parent = parent;
this.priority = priority;
this.namespace = namespace;
this.base = parent && parent.base;
if (id == null && url)
id = (path_isRelative(url) ? '/' : '') + url;
var resource = bin[type] && bin[type][id];
if (resource) {
if (resource.state < 4 && type === 'js')
ScriptStack.moveToParent(resource, parent);
return resource;
}
if (url == null) {
this.state = 3;
this.location = path_getDir(path_resolveCurrent());
return this;
}
this.state = 0;
this.location = path_getDir(url);
(bin[type] || (bin[type] = {}))[id] = this;
if (cfg.version)
this.url += (this.url.indexOf('?') === -1 ? '?' : '&') + 'v=' + cfg.version;
return process(this);
};
Resource.prototype = obj_inherit(Resource, Include, {
state: null,
location: null,
includes: null,
response: null,
url: null,
base: null,
type: null,
xpath: null,
route: null,
parent: null,
priority: null,
namespace: null,
setBase: function(baseUrl){
this.base = baseUrl;
return this;
},
childLoaded: function(child) {
var resource = this,
includes = resource.includes;
if (includes && includes.length) {
if (resource.state < 3) {
// resource still loading/include is in process, but one of sub resources are already done
return;
}
for (var i = 0; i < includes.length; i++) {
if (includes[i].resource.state !== 4) {
return;
}
}
}
resource.readystatechanged(4);
},
create: function(type, route, namespace, xpath, id) {
var resource;
this.state = this.state >= 3
? 3
: 2;
this.response = null;
if (this.includes == null)
this.includes = [];
resource = new Resource(type, route, namespace, xpath, this, id);
this.includes.push({
resource: resource,
route: route
});
return resource;
},
include: function(type, pckg) {
var that = this,
children = [],
child;
Routes.each(type, pckg, function(namespace, route, xpath) {
if (that.route != null && that.route.path === route.path) {
// loading itself
return;
}
child = that.create(type, route, namespace, xpath);
children.push(child);
});
var i = -1,
imax = children.length;
while ( ++i < imax ){
children[i].on(4, this.childLoaded);
}
return this;
},
pause: function(){
this.state = 2.5;
var that = this;
return function(exports){
if (arguments.length === 1)
that.exports = exports;
that.readystatechanged(3);
};
},
getNestedOfType: function(type){
return resource_getChildren(this.includes, type);
}
});
// private
function process(resource) {
var type = resource.type,
parent = resource.parent,
url = resource.url;
if (document == null && type === 'css') {
resource.state = 4;
return resource;
}
if (CustomLoader.exists(resource) === false) {
switch (type) {
case 'js':
case 'embed':
ScriptStack.load(resource, parent, type === 'embed');
break;
case 'ajax':
case 'load':
case 'lazy':
XHR(resource, onXHRCompleted);
break;
case 'css':
resource.state = 4;
var tag = document.createElement('link');
tag.href = url;
tag.rel = "stylesheet";
tag.type = "text/css";
document.getElementsByTagName('head')[0].appendChild(tag);
break;
}
} else {
if ('js' === type || 'embed' === type) {
ScriptStack.add(resource, resource.parent);
}
CustomLoader.load(resource, onXHRCompleted);
}
return resource;
}
function onXHRCompleted(resource, response) {
if (!response) {
console.warn('Resource cannt be loaded', resource.url);
//- resource.readystatechanged(4);
//- return;
}
switch (resource.type) {
case 'js':
case 'embed':
resource.source = response;
resource.state = 2;
ScriptStack.touch();
return;
case 'load':
case 'ajax':
resource.exports = response;
break;
case 'lazy':
LazyModule.create(resource.xpath, response);
break;
case 'css':
var tag = document.createElement('style');
tag.type = "text/css";
tag.innerHTML = response;
document.getElementsByTagName('head')[0].appendChild(tag);
break;
}
resource.readystatechanged(4);
}
function resource_getChildren(includes, type, out) {
if (includes == null)
return null;
if (out == null)
out = [];
var imax = includes.length,
i = -1,
x;
while ( ++i < imax ){
x = includes[i].resource;
if (type === x.type)
out.push(x);
if (x.includes != null)
resource_getChildren(x.includes, type, out);
}
return out;
}
}(Include, Routes, ScriptStack, CustomLoader));
// end:source ../src/9.Resource.js
// source ../src/10.export.js
IncludeLib.Routes = RoutesLib;
IncludeLib.Resource = Resource;
IncludeLib.ScriptStack = ScriptStack;
IncludeLib.registerLoader = CustomLoader.register;
exports.include = new Include();
exports.includeLib = IncludeLib;
// end:source ../src/10.export.js
}));
// source ../src/global-vars.js
function __eval(source, include) {
"use strict";
var iparams = include && include.route.params;
/* if !DEBUG
try {
*/
return eval.call(window, source);
/* if !DEBUG
} catch (error) {
error.url = include && include.url;
//Helper.reportError(error);
console.error(error);
}
*/
}
// end:source ../src/global-vars.js
|
"use strict";
const _Common = require("./rolelib.common");
const _Targeting = require("./rolelib.targeting");
const _Military = require("./rolelib.military");
const Logger_1 = require("./tools.Logger");
var State;
(function (State) {
State[State["Waiting"] = 1] = "Waiting";
State[State["MovingToPosition"] = 2] = "MovingToPosition";
State[State["Attacking"] = 3] = "Attacking";
})(State || (State = {}));
function run(creep) {
if (!creep.hasState()) {
creep.setState(State.Waiting);
}
if (creep.ticksToLive === 1498) {
setBoosting(creep);
}
switch (creep.getState()) {
case State.Waiting:
runWaiting(creep);
break;
case State.MovingToPosition:
runMovingToPosition(creep);
break;
case State.Attacking:
runAttacking(creep);
break;
default:
Logger_1.log.error("Creep with unknown state: " + creep.name + " - " + creep.room.name + " - State: " + creep.getState(), creep.room.name);
creep.setState(State.Waiting);
break;
}
}
exports.run = run;
;
function runWaiting(creep) {
let enemies = _Targeting.findHostileCreepsInRoom(creep.room);
for (let c of enemies) {
let rampartCloseToEnemy = findRampartCloseToEnemy(c);
if (rampartCloseToEnemy !== undefined) {
creep.memory.targetEnemy = c.id;
creep.memory.rampart = rampartCloseToEnemy.id;
creep.setState(State.MovingToPosition);
runMovingToPosition(creep);
return;
}
}
if (enemies.length > 0) {
let prioritizedTarget = _Targeting.getPrioritizedTarget(creep);
if (prioritizedTarget !== null) {
_Military.kiteAndAttack(creep, prioritizedTarget);
return;
}
}
_Common.moveOffRoad(creep);
}
function runMovingToPosition(creep) {
let rampartCloseToEnemy = Game.getObjectById(creep.memory.rampart);
let enemy = Game.getObjectById(creep.memory.targetEnemy);
if (rampartCloseToEnemy === null || enemy === null || rampartCloseToEnemy.pos.getRangeTo(enemy) > 3) {
creep.memory.targetEnemy = undefined;
creep.memory.rampart = undefined;
creep.setState(State.Waiting);
return;
}
if (creep.pos.getRangeTo(enemy) < 4) {
creep.rangedAttack(enemy);
}
else {
shootHostileCreeps(creep);
}
if (rampartCloseToEnemy.pos.getRangeTo(creep) === 1) {
let result = getCreepInPosition(rampartCloseToEnemy.pos);
if (result !== undefined) {
creep.memory.rampart = undefined;
}
creep.moveTo(rampartCloseToEnemy);
}
else if (rampartCloseToEnemy.pos.getRangeTo(creep) > 0) {
creep.moveTo(rampartCloseToEnemy);
}
else {
creep.setState(State.Attacking);
runAttacking(creep);
}
}
function runAttacking(creep) {
let rampartNextToEnemy = Game.getObjectById(creep.memory.rampart);
let enemy = Game.getObjectById(creep.memory.targetEnemy);
if (rampartNextToEnemy === null || enemy === null) {
creep.memory.targetEnemy = undefined;
creep.memory.rampart = undefined;
creep.setState(State.Waiting);
return;
}
else if (rampartNextToEnemy.pos.getRangeTo(enemy) > 3) {
enemy = findEnemyNextToPosition(rampartNextToEnemy.pos);
if (enemy === null) {
shootHostileCreeps(creep);
creep.memory.targetEnemy = undefined;
creep.memory.rampart = undefined;
creep.setState(State.Waiting);
return;
}
creep.memory.targetEnemy = enemy.id;
}
creep.rangedAttack(enemy);
}
function setBoosting(creep) {
let threat = creep.room.memory.threat;
if (threat === undefined) {
return;
}
let boostLevelWanted = defendersShouldBoost(threat);
if (boostLevelWanted === 2 && hasMineralsForBoost(creep.room, 30, RESOURCE_CATALYZED_KEANIUM_ALKALIDE)) {
creep.memory.boost = [RESOURCE_CATALYZED_KEANIUM_ALKALIDE];
}
else if (boostLevelWanted > 0 && hasMineralsForBoost(creep.room, 30, RESOURCE_KEANIUM_OXIDE)) {
creep.memory.boost = [RESOURCE_KEANIUM_OXIDE];
}
}
function shootHostileCreeps(creep) {
let closeDangerousCreeps = _Targeting.findHostileCreepsInRangedRange(creep.pos);
let closeDangerousCreepsNotOnRamparts = _.filter(closeDangerousCreeps, function (c) {
let atPos = c.pos.lookFor(LOOK_STRUCTURES);
for (let sAtPos of atPos) {
if (sAtPos.structureType === STRUCTURE_RAMPART) {
return false;
}
}
return true;
});
if (closeDangerousCreepsNotOnRamparts.length > 0) {
creep.rangedAttack(closeDangerousCreepsNotOnRamparts[0]);
}
}
function defendersShouldBoost(threat) {
if (threat.boostedTough < 15) {
return 0;
}
if (threat.boostedHeal < 15) {
return 0;
}
if (threat.boostedAttack < 15 && threat.boostedWork < 15) {
return 0;
}
if (threat.boostedTough < 40) {
return 1;
}
if (threat.boostedHeal < 40) {
return 1;
}
if (threat.boostedAttack < 40 && threat.boostedWork < 40) {
return 1;
}
return 2;
}
function hasMineralsForBoost(room, count, mineral) {
if (room.terminal === undefined || room.terminal.store[mineral] === undefined) {
return false;
}
return room.terminal.store[mineral] > (count * 30);
}
function getCreepInPosition(pos) {
let creep = pos.lookFor(LOOK_CREEPS);
if (creep.length > 0) {
return creep[0];
}
return undefined;
}
function findRampartCloseToEnemy(enemy) {
for (let x of _.range(enemy.pos.x - 3, enemy.pos.x + 4)) {
for (let y of _.range(enemy.pos.y - 3, enemy.pos.y + 4)) {
if (x > 0 && x < 49 && y > 0 && y < 49) {
let pos = new RoomPosition(x, y, enemy.pos.roomName);
if (pos.getRangeTo(enemy) > 1) {
let atPos = pos.lookFor(LOOK_STRUCTURES);
for (let s of atPos) {
if (s.structureType === STRUCTURE_RAMPART) {
let cAtPos = pos.lookFor(LOOK_CREEPS);
if (cAtPos.length === 0) {
return s;
}
}
}
}
}
}
}
}
function findEnemyNextToPosition(pos) {
for (let x of _.range(pos.x - 3, pos.x + 4)) {
for (let y of _.range(pos.y - 3, pos.y + 4)) {
if (x > 0 && x < 49 && y > 0 && y < 49) {
let atPos = (new RoomPosition(x, y, pos.roomName)).lookFor(LOOK_CREEPS);
for (let s of atPos) {
if (!s.my) {
return s;
}
}
}
}
}
return null;
}
|
import '../styles/gameScreen.css';
import PropTypes from 'prop-types';
function playingTitle(player, gameState, allPicked, isCzar) {
return (
<div>
{isCzar(player) ? (
<div className="gameScreenTitle">
You are the Czar, judge the following card combos:
</div>
) : (
<div className="gameScreenTitle">The Czar is making their choice:</div>
)}
</div>
);
}
function judgingTitle(player, gameState, allPicked, isCzar) {
return (
<div>
{isCzar(player) ? (
<div className="gameScreenTitle">
Waiting on other players to make their picks
</div>
) : (
<div className="gameScreenTitle">
You are a player, pick the most suitable card combo:
</div>
)}
</div>
);
}
const GameScreenTitle = ({ player, gameState, allPicked, isCzar }) => (
<div>
{allPicked(gameState)
? playingTitle(player, gameState, allPicked, isCzar)
: judgingTitle(player, gameState, allPicked, isCzar)}
</div>
);
GameScreenTitle.propTypes = {
player: PropTypes.instanceOf(Object).isRequired,
gameState: PropTypes.number.isRequired,
allPicked: PropTypes.instanceOf(Function).isRequired,
isCzar: PropTypes.instanceOf(Function).isRequired,
};
export default GameScreenTitle;
|
/**
* @license Angular v12.2.6
* (c) 2010-2021 Google LLC. https://angular.io/
* License: MIT
*/
import { ɵAnimationGroupPlayer, NoopAnimationPlayer, AUTO_STYLE, ɵPRE_STYLE, sequence, style } from '@angular/animations';
import { Injectable } from '@angular/core';
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function isBrowser() {
return (typeof window !== 'undefined' && typeof window.document !== 'undefined');
}
function isNode() {
// Checking only for `process` isn't enough to identify whether or not we're in a Node
// environment, because Webpack by default will polyfill the `process`. While we can discern
// that Webpack polyfilled it by looking at `process.browser`, it's very Webpack-specific and
// might not be future-proof. Instead we look at the stringified version of `process` which
// is `[object process]` in Node and `[object Object]` when polyfilled.
return typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
}
function optimizeGroupPlayer(players) {
switch (players.length) {
case 0:
return new NoopAnimationPlayer();
case 1:
return players[0];
default:
return new ɵAnimationGroupPlayer(players);
}
}
function normalizeKeyframes(driver, normalizer, element, keyframes, preStyles = {}, postStyles = {}) {
const errors = [];
const normalizedKeyframes = [];
let previousOffset = -1;
let previousKeyframe = null;
keyframes.forEach(kf => {
const offset = kf['offset'];
const isSameOffset = offset == previousOffset;
const normalizedKeyframe = (isSameOffset && previousKeyframe) || {};
Object.keys(kf).forEach(prop => {
let normalizedProp = prop;
let normalizedValue = kf[prop];
if (prop !== 'offset') {
normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);
switch (normalizedValue) {
case ɵPRE_STYLE:
normalizedValue = preStyles[prop];
break;
case AUTO_STYLE:
normalizedValue = postStyles[prop];
break;
default:
normalizedValue =
normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors);
break;
}
}
normalizedKeyframe[normalizedProp] = normalizedValue;
});
if (!isSameOffset) {
normalizedKeyframes.push(normalizedKeyframe);
}
previousKeyframe = normalizedKeyframe;
previousOffset = offset;
});
if (errors.length) {
const LINE_START = '\n - ';
throw new Error(`Unable to animate due to the following errors:${LINE_START}${errors.join(LINE_START)}`);
}
return normalizedKeyframes;
}
function listenOnPlayer(player, eventName, event, callback) {
switch (eventName) {
case 'start':
player.onStart(() => callback(event && copyAnimationEvent(event, 'start', player)));
break;
case 'done':
player.onDone(() => callback(event && copyAnimationEvent(event, 'done', player)));
break;
case 'destroy':
player.onDestroy(() => callback(event && copyAnimationEvent(event, 'destroy', player)));
break;
}
}
function copyAnimationEvent(e, phaseName, player) {
const totalTime = player.totalTime;
const disabled = player.disabled ? true : false;
const event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime, disabled);
const data = e['_data'];
if (data != null) {
event['_data'] = data;
}
return event;
}
function makeAnimationEvent(element, triggerName, fromState, toState, phaseName = '', totalTime = 0, disabled) {
return { element, triggerName, fromState, toState, phaseName, totalTime, disabled: !!disabled };
}
function getOrSetAsInMap(map, key, defaultValue) {
let value;
if (map instanceof Map) {
value = map.get(key);
if (!value) {
map.set(key, value = defaultValue);
}
}
else {
value = map[key];
if (!value) {
value = map[key] = defaultValue;
}
}
return value;
}
function parseTimelineCommand(command) {
const separatorPos = command.indexOf(':');
const id = command.substring(1, separatorPos);
const action = command.substr(separatorPos + 1);
return [id, action];
}
let _contains = (elm1, elm2) => false;
const ɵ0 = _contains;
let _matches = (element, selector) => false;
const ɵ1 = _matches;
let _query = (element, selector, multi) => {
return [];
};
const ɵ2 = _query;
// Define utility methods for browsers and platform-server(domino) where Element
// and utility methods exist.
const _isNode = isNode();
if (_isNode || typeof Element !== 'undefined') {
if (!isBrowser()) {
_contains = (elm1, elm2) => elm1.contains(elm2);
}
else {
_contains = (elm1, elm2) => {
while (elm2 && elm2 !== document.documentElement) {
if (elm2 === elm1) {
return true;
}
elm2 = elm2.parentNode || elm2.host; // consider host to support shadow DOM
}
return false;
};
}
_matches = (() => {
if (_isNode || Element.prototype.matches) {
return (element, selector) => element.matches(selector);
}
else {
const proto = Element.prototype;
const fn = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector ||
proto.oMatchesSelector || proto.webkitMatchesSelector;
if (fn) {
return (element, selector) => fn.apply(element, [selector]);
}
else {
return _matches;
}
}
})();
_query = (element, selector, multi) => {
let results = [];
if (multi) {
// DO NOT REFACTOR TO USE SPREAD SYNTAX.
// For element queries that return sufficiently large NodeList objects,
// using spread syntax to populate the results array causes a RangeError
// due to the call stack limit being reached. `Array.from` can not be used
// as well, since NodeList is not iterable in IE 11, see
// https://developer.mozilla.org/en-US/docs/Web/API/NodeList
// More info is available in #38551.
const elems = element.querySelectorAll(selector);
for (let i = 0; i < elems.length; i++) {
results.push(elems[i]);
}
}
else {
const elm = element.querySelector(selector);
if (elm) {
results.push(elm);
}
}
return results;
};
}
function containsVendorPrefix(prop) {
// Webkit is the only real popular vendor prefix nowadays
// cc: http://shouldiprefix.com/
return prop.substring(1, 6) == 'ebkit'; // webkit or Webkit
}
let _CACHED_BODY = null;
let _IS_WEBKIT = false;
function validateStyleProperty(prop) {
if (!_CACHED_BODY) {
_CACHED_BODY = getBodyNode() || {};
_IS_WEBKIT = _CACHED_BODY.style ? ('WebkitAppearance' in _CACHED_BODY.style) : false;
}
let result = true;
if (_CACHED_BODY.style && !containsVendorPrefix(prop)) {
result = prop in _CACHED_BODY.style;
if (!result && _IS_WEBKIT) {
const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.substr(1);
result = camelProp in _CACHED_BODY.style;
}
}
return result;
}
function getBodyNode() {
if (typeof document != 'undefined') {
return document.body;
}
return null;
}
const matchesElement = _matches;
const containsElement = _contains;
const invokeQuery = _query;
function hypenatePropsObject(object) {
const newObj = {};
Object.keys(object).forEach(prop => {
const newProp = prop.replace(/([a-z])([A-Z])/g, '$1-$2');
newObj[newProp] = object[prop];
});
return newObj;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @publicApi
*/
class NoopAnimationDriver {
validateStyleProperty(prop) {
return validateStyleProperty(prop);
}
matchesElement(element, selector) {
return matchesElement(element, selector);
}
containsElement(elm1, elm2) {
return containsElement(elm1, elm2);
}
query(element, selector, multi) {
return invokeQuery(element, selector, multi);
}
computeStyle(element, prop, defaultValue) {
return defaultValue || '';
}
animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {
return new NoopAnimationPlayer(duration, delay);
}
}
NoopAnimationDriver.decorators = [
{ type: Injectable }
];
/**
* @publicApi
*/
class AnimationDriver {
}
AnimationDriver.NOOP = ( /* @__PURE__ */new NoopAnimationDriver());
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ONE_SECOND = 1000;
const SUBSTITUTION_EXPR_START = '{{';
const SUBSTITUTION_EXPR_END = '}}';
const ENTER_CLASSNAME = 'ng-enter';
const LEAVE_CLASSNAME = 'ng-leave';
const ENTER_SELECTOR = '.ng-enter';
const LEAVE_SELECTOR = '.ng-leave';
const NG_TRIGGER_CLASSNAME = 'ng-trigger';
const NG_TRIGGER_SELECTOR = '.ng-trigger';
const NG_ANIMATING_CLASSNAME = 'ng-animating';
const NG_ANIMATING_SELECTOR = '.ng-animating';
function resolveTimingValue(value) {
if (typeof value == 'number')
return value;
const matches = value.match(/^(-?[\.\d]+)(m?s)/);
if (!matches || matches.length < 2)
return 0;
return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
}
function _convertTimeValueToMS(value, unit) {
switch (unit) {
case 's':
return value * ONE_SECOND;
default: // ms or something else
return value;
}
}
function resolveTiming(timings, errors, allowNegativeValues) {
return timings.hasOwnProperty('duration') ?
timings :
parseTimeExpression(timings, errors, allowNegativeValues);
}
function parseTimeExpression(exp, errors, allowNegativeValues) {
const regex = /^(-?[\.\d]+)(m?s)(?:\s+(-?[\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i;
let duration;
let delay = 0;
let easing = '';
if (typeof exp === 'string') {
const matches = exp.match(regex);
if (matches === null) {
errors.push(`The provided timing value "${exp}" is invalid.`);
return { duration: 0, delay: 0, easing: '' };
}
duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);
const delayMatch = matches[3];
if (delayMatch != null) {
delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);
}
const easingVal = matches[5];
if (easingVal) {
easing = easingVal;
}
}
else {
duration = exp;
}
if (!allowNegativeValues) {
let containsErrors = false;
let startIndex = errors.length;
if (duration < 0) {
errors.push(`Duration values below 0 are not allowed for this animation step.`);
containsErrors = true;
}
if (delay < 0) {
errors.push(`Delay values below 0 are not allowed for this animation step.`);
containsErrors = true;
}
if (containsErrors) {
errors.splice(startIndex, 0, `The provided timing value "${exp}" is invalid.`);
}
}
return { duration, delay, easing };
}
function copyObj(obj, destination = {}) {
Object.keys(obj).forEach(prop => {
destination[prop] = obj[prop];
});
return destination;
}
function normalizeStyles(styles) {
const normalizedStyles = {};
if (Array.isArray(styles)) {
styles.forEach(data => copyStyles(data, false, normalizedStyles));
}
else {
copyStyles(styles, false, normalizedStyles);
}
return normalizedStyles;
}
function copyStyles(styles, readPrototype, destination = {}) {
if (readPrototype) {
// we make use of a for-in loop so that the
// prototypically inherited properties are
// revealed from the backFill map
for (let prop in styles) {
destination[prop] = styles[prop];
}
}
else {
copyObj(styles, destination);
}
return destination;
}
function getStyleAttributeString(element, key, value) {
// Return the key-value pair string to be added to the style attribute for the
// given CSS style key.
if (value) {
return key + ':' + value + ';';
}
else {
return '';
}
}
function writeStyleAttribute(element) {
// Read the style property of the element and manually reflect it to the
// style attribute. This is needed because Domino on platform-server doesn't
// understand the full set of allowed CSS properties and doesn't reflect some
// of them automatically.
let styleAttrValue = '';
for (let i = 0; i < element.style.length; i++) {
const key = element.style.item(i);
styleAttrValue += getStyleAttributeString(element, key, element.style.getPropertyValue(key));
}
for (const key in element.style) {
// Skip internal Domino properties that don't need to be reflected.
if (!element.style.hasOwnProperty(key) || key.startsWith('_')) {
continue;
}
const dashKey = camelCaseToDashCase(key);
styleAttrValue += getStyleAttributeString(element, dashKey, element.style[key]);
}
element.setAttribute('style', styleAttrValue);
}
function setStyles(element, styles, formerStyles) {
if (element['style']) {
Object.keys(styles).forEach(prop => {
const camelProp = dashCaseToCamelCase(prop);
if (formerStyles && !formerStyles.hasOwnProperty(prop)) {
formerStyles[prop] = element.style[camelProp];
}
element.style[camelProp] = styles[prop];
});
// On the server set the 'style' attribute since it's not automatically reflected.
if (isNode()) {
writeStyleAttribute(element);
}
}
}
function eraseStyles(element, styles) {
if (element['style']) {
Object.keys(styles).forEach(prop => {
const camelProp = dashCaseToCamelCase(prop);
element.style[camelProp] = '';
});
// On the server set the 'style' attribute since it's not automatically reflected.
if (isNode()) {
writeStyleAttribute(element);
}
}
}
function normalizeAnimationEntry(steps) {
if (Array.isArray(steps)) {
if (steps.length == 1)
return steps[0];
return sequence(steps);
}
return steps;
}
function validateStyleParams(value, options, errors) {
const params = options.params || {};
const matches = extractStyleParams(value);
if (matches.length) {
matches.forEach(varName => {
if (!params.hasOwnProperty(varName)) {
errors.push(`Unable to resolve the local animation param ${varName} in the given list of values`);
}
});
}
}
const PARAM_REGEX = new RegExp(`${SUBSTITUTION_EXPR_START}\\s*(.+?)\\s*${SUBSTITUTION_EXPR_END}`, 'g');
function extractStyleParams(value) {
let params = [];
if (typeof value === 'string') {
let match;
while (match = PARAM_REGEX.exec(value)) {
params.push(match[1]);
}
PARAM_REGEX.lastIndex = 0;
}
return params;
}
function interpolateParams(value, params, errors) {
const original = value.toString();
const str = original.replace(PARAM_REGEX, (_, varName) => {
let localVal = params[varName];
// this means that the value was never overridden by the data passed in by the user
if (!params.hasOwnProperty(varName)) {
errors.push(`Please provide a value for the animation param ${varName}`);
localVal = '';
}
return localVal.toString();
});
// we do this to assert that numeric values stay as they are
return str == original ? value : str;
}
function iteratorToArray(iterator) {
const arr = [];
let item = iterator.next();
while (!item.done) {
arr.push(item.value);
item = iterator.next();
}
return arr;
}
const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
function dashCaseToCamelCase(input) {
return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());
}
function camelCaseToDashCase(input) {
return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
}
function allowPreviousPlayerStylesMerge(duration, delay) {
return duration === 0 || delay === 0;
}
function balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles) {
const previousStyleProps = Object.keys(previousStyles);
if (previousStyleProps.length && keyframes.length) {
let startingKeyframe = keyframes[0];
let missingStyleProps = [];
previousStyleProps.forEach(prop => {
if (!startingKeyframe.hasOwnProperty(prop)) {
missingStyleProps.push(prop);
}
startingKeyframe[prop] = previousStyles[prop];
});
if (missingStyleProps.length) {
// tslint:disable-next-line
for (var i = 1; i < keyframes.length; i++) {
let kf = keyframes[i];
missingStyleProps.forEach(function (prop) {
kf[prop] = computeStyle(element, prop);
});
}
}
}
return keyframes;
}
function visitDslNode(visitor, node, context) {
switch (node.type) {
case 7 /* Trigger */:
return visitor.visitTrigger(node, context);
case 0 /* State */:
return visitor.visitState(node, context);
case 1 /* Transition */:
return visitor.visitTransition(node, context);
case 2 /* Sequence */:
return visitor.visitSequence(node, context);
case 3 /* Group */:
return visitor.visitGroup(node, context);
case 4 /* Animate */:
return visitor.visitAnimate(node, context);
case 5 /* Keyframes */:
return visitor.visitKeyframes(node, context);
case 6 /* Style */:
return visitor.visitStyle(node, context);
case 8 /* Reference */:
return visitor.visitReference(node, context);
case 9 /* AnimateChild */:
return visitor.visitAnimateChild(node, context);
case 10 /* AnimateRef */:
return visitor.visitAnimateRef(node, context);
case 11 /* Query */:
return visitor.visitQuery(node, context);
case 12 /* Stagger */:
return visitor.visitStagger(node, context);
default:
throw new Error(`Unable to resolve animation metadata node #${node.type}`);
}
}
function computeStyle(element, prop) {
return window.getComputedStyle(element)[prop];
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ANY_STATE = '*';
function parseTransitionExpr(transitionValue, errors) {
const expressions = [];
if (typeof transitionValue == 'string') {
transitionValue.split(/\s*,\s*/).forEach(str => parseInnerTransitionStr(str, expressions, errors));
}
else {
expressions.push(transitionValue);
}
return expressions;
}
function parseInnerTransitionStr(eventStr, expressions, errors) {
if (eventStr[0] == ':') {
const result = parseAnimationAlias(eventStr, errors);
if (typeof result == 'function') {
expressions.push(result);
return;
}
eventStr = result;
}
const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
if (match == null || match.length < 4) {
errors.push(`The provided transition expression "${eventStr}" is not supported`);
return expressions;
}
const fromState = match[1];
const separator = match[2];
const toState = match[3];
expressions.push(makeLambdaFromStates(fromState, toState));
const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
if (separator[0] == '<' && !isFullAnyStateExpr) {
expressions.push(makeLambdaFromStates(toState, fromState));
}
}
function parseAnimationAlias(alias, errors) {
switch (alias) {
case ':enter':
return 'void => *';
case ':leave':
return '* => void';
case ':increment':
return (fromState, toState) => parseFloat(toState) > parseFloat(fromState);
case ':decrement':
return (fromState, toState) => parseFloat(toState) < parseFloat(fromState);
default:
errors.push(`The transition alias value "${alias}" is not supported`);
return '* => *';
}
}
// DO NOT REFACTOR ... keep the follow set instantiations
// with the values intact (closure compiler for some reason
// removes follow-up lines that add the values outside of
// the constructor...
const TRUE_BOOLEAN_VALUES = new Set(['true', '1']);
const FALSE_BOOLEAN_VALUES = new Set(['false', '0']);
function makeLambdaFromStates(lhs, rhs) {
const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);
const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);
return (fromState, toState) => {
let lhsMatch = lhs == ANY_STATE || lhs == fromState;
let rhsMatch = rhs == ANY_STATE || rhs == toState;
if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {
lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);
}
if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {
rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);
}
return lhsMatch && rhsMatch;
};
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const SELF_TOKEN = ':self';
const SELF_TOKEN_REGEX = new RegExp(`\s*${SELF_TOKEN}\s*,?`, 'g');
/*
* [Validation]
* The visitor code below will traverse the animation AST generated by the animation verb functions
* (the output is a tree of objects) and attempt to perform a series of validations on the data. The
* following corner-cases will be validated:
*
* 1. Overlap of animations
* Given that a CSS property cannot be animated in more than one place at the same time, it's
* important that this behavior is detected and validated. The way in which this occurs is that
* each time a style property is examined, a string-map containing the property will be updated with
* the start and end times for when the property is used within an animation step.
*
* If there are two or more parallel animations that are currently running (these are invoked by the
* group()) on the same element then the validator will throw an error. Since the start/end timing
* values are collected for each property then if the current animation step is animating the same
* property and its timing values fall anywhere into the window of time that the property is
* currently being animated within then this is what causes an error.
*
* 2. Timing values
* The validator will validate to see if a timing value of `duration delay easing` or
* `durationNumber` is valid or not.
*
* (note that upon validation the code below will replace the timing data with an object containing
* {duration,delay,easing}.
*
* 3. Offset Validation
* Each of the style() calls are allowed to have an offset value when placed inside of keyframes().
* Offsets within keyframes() are considered valid when:
*
* - No offsets are used at all
* - Each style() entry contains an offset value
* - Each offset is between 0 and 1
* - Each offset is greater to or equal than the previous one
*
* Otherwise an error will be thrown.
*/
function buildAnimationAst(driver, metadata, errors) {
return new AnimationAstBuilderVisitor(driver).build(metadata, errors);
}
const ROOT_SELECTOR = '';
class AnimationAstBuilderVisitor {
constructor(_driver) {
this._driver = _driver;
}
build(metadata, errors) {
const context = new AnimationAstBuilderContext(errors);
this._resetContextStyleTimingState(context);
return visitDslNode(this, normalizeAnimationEntry(metadata), context);
}
_resetContextStyleTimingState(context) {
context.currentQuerySelector = ROOT_SELECTOR;
context.collectedStyles = {};
context.collectedStyles[ROOT_SELECTOR] = {};
context.currentTime = 0;
}
visitTrigger(metadata, context) {
let queryCount = context.queryCount = 0;
let depCount = context.depCount = 0;
const states = [];
const transitions = [];
if (metadata.name.charAt(0) == '@') {
context.errors.push('animation triggers cannot be prefixed with an `@` sign (e.g. trigger(\'@foo\', [...]))');
}
metadata.definitions.forEach(def => {
this._resetContextStyleTimingState(context);
if (def.type == 0 /* State */) {
const stateDef = def;
const name = stateDef.name;
name.toString().split(/\s*,\s*/).forEach(n => {
stateDef.name = n;
states.push(this.visitState(stateDef, context));
});
stateDef.name = name;
}
else if (def.type == 1 /* Transition */) {
const transition = this.visitTransition(def, context);
queryCount += transition.queryCount;
depCount += transition.depCount;
transitions.push(transition);
}
else {
context.errors.push('only state() and transition() definitions can sit inside of a trigger()');
}
});
return {
type: 7 /* Trigger */,
name: metadata.name,
states,
transitions,
queryCount,
depCount,
options: null
};
}
visitState(metadata, context) {
const styleAst = this.visitStyle(metadata.styles, context);
const astParams = (metadata.options && metadata.options.params) || null;
if (styleAst.containsDynamicStyles) {
const missingSubs = new Set();
const params = astParams || {};
styleAst.styles.forEach(value => {
if (isObject(value)) {
const stylesObj = value;
Object.keys(stylesObj).forEach(prop => {
extractStyleParams(stylesObj[prop]).forEach(sub => {
if (!params.hasOwnProperty(sub)) {
missingSubs.add(sub);
}
});
});
}
});
if (missingSubs.size) {
const missingSubsArr = iteratorToArray(missingSubs.values());
context.errors.push(`state("${metadata
.name}", ...) must define default values for all the following style substitutions: ${missingSubsArr.join(', ')}`);
}
}
return {
type: 0 /* State */,
name: metadata.name,
style: styleAst,
options: astParams ? { params: astParams } : null
};
}
visitTransition(metadata, context) {
context.queryCount = 0;
context.depCount = 0;
const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
const matchers = parseTransitionExpr(metadata.expr, context.errors);
return {
type: 1 /* Transition */,
matchers,
animation,
queryCount: context.queryCount,
depCount: context.depCount,
options: normalizeAnimationOptions(metadata.options)
};
}
visitSequence(metadata, context) {
return {
type: 2 /* Sequence */,
steps: metadata.steps.map(s => visitDslNode(this, s, context)),
options: normalizeAnimationOptions(metadata.options)
};
}
visitGroup(metadata, context) {
const currentTime = context.currentTime;
let furthestTime = 0;
const steps = metadata.steps.map(step => {
context.currentTime = currentTime;
const innerAst = visitDslNode(this, step, context);
furthestTime = Math.max(furthestTime, context.currentTime);
return innerAst;
});
context.currentTime = furthestTime;
return {
type: 3 /* Group */,
steps,
options: normalizeAnimationOptions(metadata.options)
};
}
visitAnimate(metadata, context) {
const timingAst = constructTimingAst(metadata.timings, context.errors);
context.currentAnimateTimings = timingAst;
let styleAst;
let styleMetadata = metadata.styles ? metadata.styles : style({});
if (styleMetadata.type == 5 /* Keyframes */) {
styleAst = this.visitKeyframes(styleMetadata, context);
}
else {
let styleMetadata = metadata.styles;
let isEmpty = false;
if (!styleMetadata) {
isEmpty = true;
const newStyleData = {};
if (timingAst.easing) {
newStyleData['easing'] = timingAst.easing;
}
styleMetadata = style(newStyleData);
}
context.currentTime += timingAst.duration + timingAst.delay;
const _styleAst = this.visitStyle(styleMetadata, context);
_styleAst.isEmptyStep = isEmpty;
styleAst = _styleAst;
}
context.currentAnimateTimings = null;
return {
type: 4 /* Animate */,
timings: timingAst,
style: styleAst,
options: null
};
}
visitStyle(metadata, context) {
const ast = this._makeStyleAst(metadata, context);
this._validateStyleAst(ast, context);
return ast;
}
_makeStyleAst(metadata, context) {
const styles = [];
if (Array.isArray(metadata.styles)) {
metadata.styles.forEach(styleTuple => {
if (typeof styleTuple == 'string') {
if (styleTuple == AUTO_STYLE) {
styles.push(styleTuple);
}
else {
context.errors.push(`The provided style string value ${styleTuple} is not allowed.`);
}
}
else {
styles.push(styleTuple);
}
});
}
else {
styles.push(metadata.styles);
}
let containsDynamicStyles = false;
let collectedEasing = null;
styles.forEach(styleData => {
if (isObject(styleData)) {
const styleMap = styleData;
const easing = styleMap['easing'];
if (easing) {
collectedEasing = easing;
delete styleMap['easing'];
}
if (!containsDynamicStyles) {
for (let prop in styleMap) {
const value = styleMap[prop];
if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) {
containsDynamicStyles = true;
break;
}
}
}
}
});
return {
type: 6 /* Style */,
styles,
easing: collectedEasing,
offset: metadata.offset,
containsDynamicStyles,
options: null
};
}
_validateStyleAst(ast, context) {
const timings = context.currentAnimateTimings;
let endTime = context.currentTime;
let startTime = context.currentTime;
if (timings && startTime > 0) {
startTime -= timings.duration + timings.delay;
}
ast.styles.forEach(tuple => {
if (typeof tuple == 'string')
return;
Object.keys(tuple).forEach(prop => {
if (!this._driver.validateStyleProperty(prop)) {
context.errors.push(`The provided animation property "${prop}" is not a supported CSS property for animations`);
return;
}
const collectedStyles = context.collectedStyles[context.currentQuerySelector];
const collectedEntry = collectedStyles[prop];
let updateCollectedStyle = true;
if (collectedEntry) {
if (startTime != endTime && startTime >= collectedEntry.startTime &&
endTime <= collectedEntry.endTime) {
context.errors.push(`The CSS property "${prop}" that exists between the times of "${collectedEntry.startTime}ms" and "${collectedEntry
.endTime}ms" is also being animated in a parallel animation between the times of "${startTime}ms" and "${endTime}ms"`);
updateCollectedStyle = false;
}
// we always choose the smaller start time value since we
// want to have a record of the entire animation window where
// the style property is being animated in between
startTime = collectedEntry.startTime;
}
if (updateCollectedStyle) {
collectedStyles[prop] = { startTime, endTime };
}
if (context.options) {
validateStyleParams(tuple[prop], context.options, context.errors);
}
});
});
}
visitKeyframes(metadata, context) {
const ast = { type: 5 /* Keyframes */, styles: [], options: null };
if (!context.currentAnimateTimings) {
context.errors.push(`keyframes() must be placed inside of a call to animate()`);
return ast;
}
const MAX_KEYFRAME_OFFSET = 1;
let totalKeyframesWithOffsets = 0;
const offsets = [];
let offsetsOutOfOrder = false;
let keyframesOutOfRange = false;
let previousOffset = 0;
const keyframes = metadata.steps.map(styles => {
const style = this._makeStyleAst(styles, context);
let offsetVal = style.offset != null ? style.offset : consumeOffset(style.styles);
let offset = 0;
if (offsetVal != null) {
totalKeyframesWithOffsets++;
offset = style.offset = offsetVal;
}
keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;
offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;
previousOffset = offset;
offsets.push(offset);
return style;
});
if (keyframesOutOfRange) {
context.errors.push(`Please ensure that all keyframe offsets are between 0 and 1`);
}
if (offsetsOutOfOrder) {
context.errors.push(`Please ensure that all keyframe offsets are in order`);
}
const length = metadata.steps.length;
let generatedOffset = 0;
if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {
context.errors.push(`Not all style() steps within the declared keyframes() contain offsets`);
}
else if (totalKeyframesWithOffsets == 0) {
generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1);
}
const limit = length - 1;
const currentTime = context.currentTime;
const currentAnimateTimings = context.currentAnimateTimings;
const animateDuration = currentAnimateTimings.duration;
keyframes.forEach((kf, i) => {
const offset = generatedOffset > 0 ? (i == limit ? 1 : (generatedOffset * i)) : offsets[i];
const durationUpToThisFrame = offset * animateDuration;
context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame;
currentAnimateTimings.duration = durationUpToThisFrame;
this._validateStyleAst(kf, context);
kf.offset = offset;
ast.styles.push(kf);
});
return ast;
}
visitReference(metadata, context) {
return {
type: 8 /* Reference */,
animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
options: normalizeAnimationOptions(metadata.options)
};
}
visitAnimateChild(metadata, context) {
context.depCount++;
return {
type: 9 /* AnimateChild */,
options: normalizeAnimationOptions(metadata.options)
};
}
visitAnimateRef(metadata, context) {
return {
type: 10 /* AnimateRef */,
animation: this.visitReference(metadata.animation, context),
options: normalizeAnimationOptions(metadata.options)
};
}
visitQuery(metadata, context) {
const parentSelector = context.currentQuerySelector;
const options = (metadata.options || {});
context.queryCount++;
context.currentQuery = metadata;
const [selector, includeSelf] = normalizeSelector(metadata.selector);
context.currentQuerySelector =
parentSelector.length ? (parentSelector + ' ' + selector) : selector;
getOrSetAsInMap(context.collectedStyles, context.currentQuerySelector, {});
const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);
context.currentQuery = null;
context.currentQuerySelector = parentSelector;
return {
type: 11 /* Query */,
selector,
limit: options.limit || 0,
optional: !!options.optional,
includeSelf,
animation,
originalSelector: metadata.selector,
options: normalizeAnimationOptions(metadata.options)
};
}
visitStagger(metadata, context) {
if (!context.currentQuery) {
context.errors.push(`stagger() can only be used inside of query()`);
}
const timings = metadata.timings === 'full' ?
{ duration: 0, delay: 0, easing: 'full' } :
resolveTiming(metadata.timings, context.errors, true);
return {
type: 12 /* Stagger */,
animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),
timings,
options: null
};
}
}
function normalizeSelector(selector) {
const hasAmpersand = selector.split(/\s*,\s*/).find(token => token == SELF_TOKEN) ? true : false;
if (hasAmpersand) {
selector = selector.replace(SELF_TOKEN_REGEX, '');
}
// the :enter and :leave selectors are filled in at runtime during timeline building
selector = selector.replace(/@\*/g, NG_TRIGGER_SELECTOR)
.replace(/@\w+/g, match => NG_TRIGGER_SELECTOR + '-' + match.substr(1))
.replace(/:animating/g, NG_ANIMATING_SELECTOR);
return [selector, hasAmpersand];
}
function normalizeParams(obj) {
return obj ? copyObj(obj) : null;
}
class AnimationAstBuilderContext {
constructor(errors) {
this.errors = errors;
this.queryCount = 0;
this.depCount = 0;
this.currentTransition = null;
this.currentQuery = null;
this.currentQuerySelector = null;
this.currentAnimateTimings = null;
this.currentTime = 0;
this.collectedStyles = {};
this.options = null;
}
}
function consumeOffset(styles) {
if (typeof styles == 'string')
return null;
let offset = null;
if (Array.isArray(styles)) {
styles.forEach(styleTuple => {
if (isObject(styleTuple) && styleTuple.hasOwnProperty('offset')) {
const obj = styleTuple;
offset = parseFloat(obj['offset']);
delete obj['offset'];
}
});
}
else if (isObject(styles) && styles.hasOwnProperty('offset')) {
const obj = styles;
offset = parseFloat(obj['offset']);
delete obj['offset'];
}
return offset;
}
function isObject(value) {
return !Array.isArray(value) && typeof value == 'object';
}
function constructTimingAst(value, errors) {
let timings = null;
if (value.hasOwnProperty('duration')) {
timings = value;
}
else if (typeof value == 'number') {
const duration = resolveTiming(value, errors).duration;
return makeTimingAst(duration, 0, '');
}
const strValue = value;
const isDynamic = strValue.split(/\s+/).some(v => v.charAt(0) == '{' && v.charAt(1) == '{');
if (isDynamic) {
const ast = makeTimingAst(0, 0, '');
ast.dynamic = true;
ast.strValue = strValue;
return ast;
}
timings = timings || resolveTiming(strValue, errors);
return makeTimingAst(timings.duration, timings.delay, timings.easing);
}
function normalizeAnimationOptions(options) {
if (options) {
options = copyObj(options);
if (options['params']) {
options['params'] = normalizeParams(options['params']);
}
}
else {
options = {};
}
return options;
}
function makeTimingAst(duration, delay, easing) {
return { duration, delay, easing };
}
function createTimelineInstruction(element, keyframes, preStyleProps, postStyleProps, duration, delay, easing = null, subTimeline = false) {
return {
type: 1 /* TimelineAnimation */,
element,
keyframes,
preStyleProps,
postStyleProps,
duration,
delay,
totalTime: duration + delay,
easing,
subTimeline
};
}
class ElementInstructionMap {
constructor() {
this._map = new Map();
}
consume(element) {
let instructions = this._map.get(element);
if (instructions) {
this._map.delete(element);
}
else {
instructions = [];
}
return instructions;
}
append(element, instructions) {
let existingInstructions = this._map.get(element);
if (!existingInstructions) {
this._map.set(element, existingInstructions = []);
}
existingInstructions.push(...instructions);
}
has(element) {
return this._map.has(element);
}
clear() {
this._map.clear();
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ONE_FRAME_IN_MILLISECONDS = 1;
const ENTER_TOKEN = ':enter';
const ENTER_TOKEN_REGEX = new RegExp(ENTER_TOKEN, 'g');
const LEAVE_TOKEN = ':leave';
const LEAVE_TOKEN_REGEX = new RegExp(LEAVE_TOKEN, 'g');
/*
* The code within this file aims to generate web-animations-compatible keyframes from Angular's
* animation DSL code.
*
* The code below will be converted from:
*
* ```
* sequence([
* style({ opacity: 0 }),
* animate(1000, style({ opacity: 0 }))
* ])
* ```
*
* To:
* ```
* keyframes = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }]
* duration = 1000
* delay = 0
* easing = ''
* ```
*
* For this operation to cover the combination of animation verbs (style, animate, group, etc...) a
* combination of prototypical inheritance, AST traversal and merge-sort-like algorithms are used.
*
* [AST Traversal]
* Each of the animation verbs, when executed, will return an string-map object representing what
* type of action it is (style, animate, group, etc...) and the data associated with it. This means
* that when functional composition mix of these functions is evaluated (like in the example above)
* then it will end up producing a tree of objects representing the animation itself.
*
* When this animation object tree is processed by the visitor code below it will visit each of the
* verb statements within the visitor. And during each visit it will build the context of the
* animation keyframes by interacting with the `TimelineBuilder`.
*
* [TimelineBuilder]
* This class is responsible for tracking the styles and building a series of keyframe objects for a
* timeline between a start and end time. The builder starts off with an initial timeline and each
* time the AST comes across a `group()`, `keyframes()` or a combination of the two wihtin a
* `sequence()` then it will generate a sub timeline for each step as well as a new one after
* they are complete.
*
* As the AST is traversed, the timing state on each of the timelines will be incremented. If a sub
* timeline was created (based on one of the cases above) then the parent timeline will attempt to
* merge the styles used within the sub timelines into itself (only with group() this will happen).
* This happens with a merge operation (much like how the merge works in mergesort) and it will only
* copy the most recently used styles from the sub timelines into the parent timeline. This ensures
* that if the styles are used later on in another phase of the animation then they will be the most
* up-to-date values.
*
* [How Missing Styles Are Updated]
* Each timeline has a `backFill` property which is responsible for filling in new styles into
* already processed keyframes if a new style shows up later within the animation sequence.
*
* ```
* sequence([
* style({ width: 0 }),
* animate(1000, style({ width: 100 })),
* animate(1000, style({ width: 200 })),
* animate(1000, style({ width: 300 }))
* animate(1000, style({ width: 400, height: 400 })) // notice how `height` doesn't exist anywhere
* else
* ])
* ```
*
* What is happening here is that the `height` value is added later in the sequence, but is missing
* from all previous animation steps. Therefore when a keyframe is created it would also be missing
* from all previous keyframes up until where it is first used. For the timeline keyframe generation
* to properly fill in the style it will place the previous value (the value from the parent
* timeline) or a default value of `*` into the backFill object. Given that each of the keyframe
* styles are objects that prototypically inhert from the backFill object, this means that if a
* value is added into the backFill then it will automatically propagate any missing values to all
* keyframes. Therefore the missing `height` value will be properly filled into the already
* processed keyframes.
*
* When a sub-timeline is created it will have its own backFill property. This is done so that
* styles present within the sub-timeline do not accidentally seep into the previous/future timeline
* keyframes
*
* (For prototypically-inherited contents to be detected a `for(i in obj)` loop must be used.)
*
* [Validation]
* The code in this file is not responsible for validation. That functionality happens with within
* the `AnimationValidatorVisitor` code.
*/
function buildAnimationTimelines(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles = {}, finalStyles = {}, options, subInstructions, errors = []) {
return new AnimationTimelineBuilderVisitor().buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors);
}
class AnimationTimelineBuilderVisitor {
buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors = []) {
subInstructions = subInstructions || new ElementInstructionMap();
const context = new AnimationTimelineContext(driver, rootElement, subInstructions, enterClassName, leaveClassName, errors, []);
context.options = options;
context.currentTimeline.setStyles([startingStyles], null, context.errors, options);
visitDslNode(this, ast, context);
// this checks to see if an actual animation happened
const timelines = context.timelines.filter(timeline => timeline.containsAnimation());
if (timelines.length && Object.keys(finalStyles).length) {
const tl = timelines[timelines.length - 1];
if (!tl.allowOnlyTimelineStyles()) {
tl.setStyles([finalStyles], null, context.errors, options);
}
}
return timelines.length ? timelines.map(timeline => timeline.buildKeyframes()) :
[createTimelineInstruction(rootElement, [], [], [], 0, 0, '', false)];
}
visitTrigger(ast, context) {
// these values are not visited in this AST
}
visitState(ast, context) {
// these values are not visited in this AST
}
visitTransition(ast, context) {
// these values are not visited in this AST
}
visitAnimateChild(ast, context) {
const elementInstructions = context.subInstructions.consume(context.element);
if (elementInstructions) {
const innerContext = context.createSubContext(ast.options);
const startTime = context.currentTimeline.currentTime;
const endTime = this._visitSubInstructions(elementInstructions, innerContext, innerContext.options);
if (startTime != endTime) {
// we do this on the upper context because we created a sub context for
// the sub child animations
context.transformIntoNewTimeline(endTime);
}
}
context.previousNode = ast;
}
visitAnimateRef(ast, context) {
const innerContext = context.createSubContext(ast.options);
innerContext.transformIntoNewTimeline();
this.visitReference(ast.animation, innerContext);
context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime);
context.previousNode = ast;
}
_visitSubInstructions(instructions, context, options) {
const startTime = context.currentTimeline.currentTime;
let furthestTime = startTime;
// this is a special-case for when a user wants to skip a sub
// animation from being fired entirely.
const duration = options.duration != null ? resolveTimingValue(options.duration) : null;
const delay = options.delay != null ? resolveTimingValue(options.delay) : null;
if (duration !== 0) {
instructions.forEach(instruction => {
const instructionTimings = context.appendInstructionToTimeline(instruction, duration, delay);
furthestTime =
Math.max(furthestTime, instructionTimings.duration + instructionTimings.delay);
});
}
return furthestTime;
}
visitReference(ast, context) {
context.updateOptions(ast.options, true);
visitDslNode(this, ast.animation, context);
context.previousNode = ast;
}
visitSequence(ast, context) {
const subContextCount = context.subContextCount;
let ctx = context;
const options = ast.options;
if (options && (options.params || options.delay)) {
ctx = context.createSubContext(options);
ctx.transformIntoNewTimeline();
if (options.delay != null) {
if (ctx.previousNode.type == 6 /* Style */) {
ctx.currentTimeline.snapshotCurrentStyles();
ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
}
const delay = resolveTimingValue(options.delay);
ctx.delayNextStep(delay);
}
}
if (ast.steps.length) {
ast.steps.forEach(s => visitDslNode(this, s, ctx));
// this is here just incase the inner steps only contain or end with a style() call
ctx.currentTimeline.applyStylesToKeyframe();
// this means that some animation function within the sequence
// ended up creating a sub timeline (which means the current
// timeline cannot overlap with the contents of the sequence)
if (ctx.subContextCount > subContextCount) {
ctx.transformIntoNewTimeline();
}
}
context.previousNode = ast;
}
visitGroup(ast, context) {
const innerTimelines = [];
let furthestTime = context.currentTimeline.currentTime;
const delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0;
ast.steps.forEach(s => {
const innerContext = context.createSubContext(ast.options);
if (delay) {
innerContext.delayNextStep(delay);
}
visitDslNode(this, s, innerContext);
furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime);
innerTimelines.push(innerContext.currentTimeline);
});
// this operation is run after the AST loop because otherwise
// if the parent timeline's collected styles were updated then
// it would pass in invalid data into the new-to-be forked items
innerTimelines.forEach(timeline => context.currentTimeline.mergeTimelineCollectedStyles(timeline));
context.transformIntoNewTimeline(furthestTime);
context.previousNode = ast;
}
_visitTiming(ast, context) {
if (ast.dynamic) {
const strValue = ast.strValue;
const timingValue = context.params ? interpolateParams(strValue, context.params, context.errors) : strValue;
return resolveTiming(timingValue, context.errors);
}
else {
return { duration: ast.duration, delay: ast.delay, easing: ast.easing };
}
}
visitAnimate(ast, context) {
const timings = context.currentAnimateTimings = this._visitTiming(ast.timings, context);
const timeline = context.currentTimeline;
if (timings.delay) {
context.incrementTime(timings.delay);
timeline.snapshotCurrentStyles();
}
const style = ast.style;
if (style.type == 5 /* Keyframes */) {
this.visitKeyframes(style, context);
}
else {
context.incrementTime(timings.duration);
this.visitStyle(style, context);
timeline.applyStylesToKeyframe();
}
context.currentAnimateTimings = null;
context.previousNode = ast;
}
visitStyle(ast, context) {
const timeline = context.currentTimeline;
const timings = context.currentAnimateTimings;
// this is a special case for when a style() call
// directly follows an animate() call (but not inside of an animate() call)
if (!timings && timeline.getCurrentStyleProperties().length) {
timeline.forwardFrame();
}
const easing = (timings && timings.easing) || ast.easing;
if (ast.isEmptyStep) {
timeline.applyEmptyStep(easing);
}
else {
timeline.setStyles(ast.styles, easing, context.errors, context.options);
}
context.previousNode = ast;
}
visitKeyframes(ast, context) {
const currentAnimateTimings = context.currentAnimateTimings;
const startTime = (context.currentTimeline).duration;
const duration = currentAnimateTimings.duration;
const innerContext = context.createSubContext();
const innerTimeline = innerContext.currentTimeline;
innerTimeline.easing = currentAnimateTimings.easing;
ast.styles.forEach(step => {
const offset = step.offset || 0;
innerTimeline.forwardTime(offset * duration);
innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options);
innerTimeline.applyStylesToKeyframe();
});
// this will ensure that the parent timeline gets all the styles from
// the child even if the new timeline below is not used
context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline);
// we do this because the window between this timeline and the sub timeline
// should ensure that the styles within are exactly the same as they were before
context.transformIntoNewTimeline(startTime + duration);
context.previousNode = ast;
}
visitQuery(ast, context) {
// in the event that the first step before this is a style step we need
// to ensure the styles are applied before the children are animated
const startTime = context.currentTimeline.currentTime;
const options = (ast.options || {});
const delay = options.delay ? resolveTimingValue(options.delay) : 0;
if (delay &&
(context.previousNode.type === 6 /* Style */ ||
(startTime == 0 && context.currentTimeline.getCurrentStyleProperties().length))) {
context.currentTimeline.snapshotCurrentStyles();
context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
}
let furthestTime = startTime;
const elms = context.invokeQuery(ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors);
context.currentQueryTotal = elms.length;
let sameElementTimeline = null;
elms.forEach((element, i) => {
context.currentQueryIndex = i;
const innerContext = context.createSubContext(ast.options, element);
if (delay) {
innerContext.delayNextStep(delay);
}
if (element === context.element) {
sameElementTimeline = innerContext.currentTimeline;
}
visitDslNode(this, ast.animation, innerContext);
// this is here just incase the inner steps only contain or end
// with a style() call (which is here to signal that this is a preparatory
// call to style an element before it is animated again)
innerContext.currentTimeline.applyStylesToKeyframe();
const endTime = innerContext.currentTimeline.currentTime;
furthestTime = Math.max(furthestTime, endTime);
});
context.currentQueryIndex = 0;
context.currentQueryTotal = 0;
context.transformIntoNewTimeline(furthestTime);
if (sameElementTimeline) {
context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline);
context.currentTimeline.snapshotCurrentStyles();
}
context.previousNode = ast;
}
visitStagger(ast, context) {
const parentContext = context.parentContext;
const tl = context.currentTimeline;
const timings = ast.timings;
const duration = Math.abs(timings.duration);
const maxTime = duration * (context.currentQueryTotal - 1);
let delay = duration * context.currentQueryIndex;
let staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing;
switch (staggerTransformer) {
case 'reverse':
delay = maxTime - delay;
break;
case 'full':
delay = parentContext.currentStaggerTime;
break;
}
const timeline = context.currentTimeline;
if (delay) {
timeline.delayNextStep(delay);
}
const startingTime = timeline.currentTime;
visitDslNode(this, ast.animation, context);
context.previousNode = ast;
// time = duration + delay
// the reason why this computation is so complex is because
// the inner timeline may either have a delay value or a stretched
// keyframe depending on if a subtimeline is not used or is used.
parentContext.currentStaggerTime =
(tl.currentTime - startingTime) + (tl.startTime - parentContext.currentTimeline.startTime);
}
}
const DEFAULT_NOOP_PREVIOUS_NODE = {};
class AnimationTimelineContext {
constructor(_driver, element, subInstructions, _enterClassName, _leaveClassName, errors, timelines, initialTimeline) {
this._driver = _driver;
this.element = element;
this.subInstructions = subInstructions;
this._enterClassName = _enterClassName;
this._leaveClassName = _leaveClassName;
this.errors = errors;
this.timelines = timelines;
this.parentContext = null;
this.currentAnimateTimings = null;
this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
this.subContextCount = 0;
this.options = {};
this.currentQueryIndex = 0;
this.currentQueryTotal = 0;
this.currentStaggerTime = 0;
this.currentTimeline = initialTimeline || new TimelineBuilder(this._driver, element, 0);
timelines.push(this.currentTimeline);
}
get params() {
return this.options.params;
}
updateOptions(options, skipIfExists) {
if (!options)
return;
const newOptions = options;
let optionsToUpdate = this.options;
// NOTE: this will get patched up when other animation methods support duration overrides
if (newOptions.duration != null) {
optionsToUpdate.duration = resolveTimingValue(newOptions.duration);
}
if (newOptions.delay != null) {
optionsToUpdate.delay = resolveTimingValue(newOptions.delay);
}
const newParams = newOptions.params;
if (newParams) {
let paramsToUpdate = optionsToUpdate.params;
if (!paramsToUpdate) {
paramsToUpdate = this.options.params = {};
}
Object.keys(newParams).forEach(name => {
if (!skipIfExists || !paramsToUpdate.hasOwnProperty(name)) {
paramsToUpdate[name] = interpolateParams(newParams[name], paramsToUpdate, this.errors);
}
});
}
}
_copyOptions() {
const options = {};
if (this.options) {
const oldParams = this.options.params;
if (oldParams) {
const params = options['params'] = {};
Object.keys(oldParams).forEach(name => {
params[name] = oldParams[name];
});
}
}
return options;
}
createSubContext(options = null, element, newTime) {
const target = element || this.element;
const context = new AnimationTimelineContext(this._driver, target, this.subInstructions, this._enterClassName, this._leaveClassName, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0));
context.previousNode = this.previousNode;
context.currentAnimateTimings = this.currentAnimateTimings;
context.options = this._copyOptions();
context.updateOptions(options);
context.currentQueryIndex = this.currentQueryIndex;
context.currentQueryTotal = this.currentQueryTotal;
context.parentContext = this;
this.subContextCount++;
return context;
}
transformIntoNewTimeline(newTime) {
this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;
this.currentTimeline = this.currentTimeline.fork(this.element, newTime);
this.timelines.push(this.currentTimeline);
return this.currentTimeline;
}
appendInstructionToTimeline(instruction, duration, delay) {
const updatedTimings = {
duration: duration != null ? duration : instruction.duration,
delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay,
easing: ''
};
const builder = new SubTimelineBuilder(this._driver, instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe);
this.timelines.push(builder);
return updatedTimings;
}
incrementTime(time) {
this.currentTimeline.forwardTime(this.currentTimeline.duration + time);
}
delayNextStep(delay) {
// negative delays are not yet supported
if (delay > 0) {
this.currentTimeline.delayNextStep(delay);
}
}
invokeQuery(selector, originalSelector, limit, includeSelf, optional, errors) {
let results = [];
if (includeSelf) {
results.push(this.element);
}
if (selector.length > 0) { // if :self is only used then the selector is empty
selector = selector.replace(ENTER_TOKEN_REGEX, '.' + this._enterClassName);
selector = selector.replace(LEAVE_TOKEN_REGEX, '.' + this._leaveClassName);
const multi = limit != 1;
let elements = this._driver.query(this.element, selector, multi);
if (limit !== 0) {
elements = limit < 0 ? elements.slice(elements.length + limit, elements.length) :
elements.slice(0, limit);
}
results.push(...elements);
}
if (!optional && results.length == 0) {
errors.push(`\`query("${originalSelector}")\` returned zero elements. (Use \`query("${originalSelector}", { optional: true })\` if you wish to allow this.)`);
}
return results;
}
}
class TimelineBuilder {
constructor(_driver, element, startTime, _elementTimelineStylesLookup) {
this._driver = _driver;
this.element = element;
this.startTime = startTime;
this._elementTimelineStylesLookup = _elementTimelineStylesLookup;
this.duration = 0;
this._previousKeyframe = {};
this._currentKeyframe = {};
this._keyframes = new Map();
this._styleSummary = {};
this._pendingStyles = {};
this._backFill = {};
this._currentEmptyStepKeyframe = null;
if (!this._elementTimelineStylesLookup) {
this._elementTimelineStylesLookup = new Map();
}
this._localTimelineStyles = Object.create(this._backFill, {});
this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element);
if (!this._globalTimelineStyles) {
this._globalTimelineStyles = this._localTimelineStyles;
this._elementTimelineStylesLookup.set(element, this._localTimelineStyles);
}
this._loadKeyframe();
}
containsAnimation() {
switch (this._keyframes.size) {
case 0:
return false;
case 1:
return this.getCurrentStyleProperties().length > 0;
default:
return true;
}
}
getCurrentStyleProperties() {
return Object.keys(this._currentKeyframe);
}
get currentTime() {
return this.startTime + this.duration;
}
delayNextStep(delay) {
// in the event that a style() step is placed right before a stagger()
// and that style() step is the very first style() value in the animation
// then we need to make a copy of the keyframe [0, copy, 1] so that the delay
// properly applies the style() values to work with the stagger...
const hasPreStyleStep = this._keyframes.size == 1 && Object.keys(this._pendingStyles).length;
if (this.duration || hasPreStyleStep) {
this.forwardTime(this.currentTime + delay);
if (hasPreStyleStep) {
this.snapshotCurrentStyles();
}
}
else {
this.startTime += delay;
}
}
fork(element, currentTime) {
this.applyStylesToKeyframe();
return new TimelineBuilder(this._driver, element, currentTime || this.currentTime, this._elementTimelineStylesLookup);
}
_loadKeyframe() {
if (this._currentKeyframe) {
this._previousKeyframe = this._currentKeyframe;
}
this._currentKeyframe = this._keyframes.get(this.duration);
if (!this._currentKeyframe) {
this._currentKeyframe = Object.create(this._backFill, {});
this._keyframes.set(this.duration, this._currentKeyframe);
}
}
forwardFrame() {
this.duration += ONE_FRAME_IN_MILLISECONDS;
this._loadKeyframe();
}
forwardTime(time) {
this.applyStylesToKeyframe();
this.duration = time;
this._loadKeyframe();
}
_updateStyle(prop, value) {
this._localTimelineStyles[prop] = value;
this._globalTimelineStyles[prop] = value;
this._styleSummary[prop] = { time: this.currentTime, value };
}
allowOnlyTimelineStyles() {
return this._currentEmptyStepKeyframe !== this._currentKeyframe;
}
applyEmptyStep(easing) {
if (easing) {
this._previousKeyframe['easing'] = easing;
}
// special case for animate(duration):
// all missing styles are filled with a `*` value then
// if any destination styles are filled in later on the same
// keyframe then they will override the overridden styles
// We use `_globalTimelineStyles` here because there may be
// styles in previous keyframes that are not present in this timeline
Object.keys(this._globalTimelineStyles).forEach(prop => {
this._backFill[prop] = this._globalTimelineStyles[prop] || AUTO_STYLE;
this._currentKeyframe[prop] = AUTO_STYLE;
});
this._currentEmptyStepKeyframe = this._currentKeyframe;
}
setStyles(input, easing, errors, options) {
if (easing) {
this._previousKeyframe['easing'] = easing;
}
const params = (options && options.params) || {};
const styles = flattenStyles(input, this._globalTimelineStyles);
Object.keys(styles).forEach(prop => {
const val = interpolateParams(styles[prop], params, errors);
this._pendingStyles[prop] = val;
if (!this._localTimelineStyles.hasOwnProperty(prop)) {
this._backFill[prop] = this._globalTimelineStyles.hasOwnProperty(prop) ?
this._globalTimelineStyles[prop] :
AUTO_STYLE;
}
this._updateStyle(prop, val);
});
}
applyStylesToKeyframe() {
const styles = this._pendingStyles;
const props = Object.keys(styles);
if (props.length == 0)
return;
this._pendingStyles = {};
props.forEach(prop => {
const val = styles[prop];
this._currentKeyframe[prop] = val;
});
Object.keys(this._localTimelineStyles).forEach(prop => {
if (!this._currentKeyframe.hasOwnProperty(prop)) {
this._currentKeyframe[prop] = this._localTimelineStyles[prop];
}
});
}
snapshotCurrentStyles() {
Object.keys(this._localTimelineStyles).forEach(prop => {
const val = this._localTimelineStyles[prop];
this._pendingStyles[prop] = val;
this._updateStyle(prop, val);
});
}
getFinalKeyframe() {
return this._keyframes.get(this.duration);
}
get properties() {
const properties = [];
for (let prop in this._currentKeyframe) {
properties.push(prop);
}
return properties;
}
mergeTimelineCollectedStyles(timeline) {
Object.keys(timeline._styleSummary).forEach(prop => {
const details0 = this._styleSummary[prop];
const details1 = timeline._styleSummary[prop];
if (!details0 || details1.time > details0.time) {
this._updateStyle(prop, details1.value);
}
});
}
buildKeyframes() {
this.applyStylesToKeyframe();
const preStyleProps = new Set();
const postStyleProps = new Set();
const isEmpty = this._keyframes.size === 1 && this.duration === 0;
let finalKeyframes = [];
this._keyframes.forEach((keyframe, time) => {
const finalKeyframe = copyStyles(keyframe, true);
Object.keys(finalKeyframe).forEach(prop => {
const value = finalKeyframe[prop];
if (value == ɵPRE_STYLE) {
preStyleProps.add(prop);
}
else if (value == AUTO_STYLE) {
postStyleProps.add(prop);
}
});
if (!isEmpty) {
finalKeyframe['offset'] = time / this.duration;
}
finalKeyframes.push(finalKeyframe);
});
const preProps = preStyleProps.size ? iteratorToArray(preStyleProps.values()) : [];
const postProps = postStyleProps.size ? iteratorToArray(postStyleProps.values()) : [];
// special case for a 0-second animation (which is designed just to place styles onscreen)
if (isEmpty) {
const kf0 = finalKeyframes[0];
const kf1 = copyObj(kf0);
kf0['offset'] = 0;
kf1['offset'] = 1;
finalKeyframes = [kf0, kf1];
}
return createTimelineInstruction(this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false);
}
}
class SubTimelineBuilder extends TimelineBuilder {
constructor(driver, element, keyframes, preStyleProps, postStyleProps, timings, _stretchStartingKeyframe = false) {
super(driver, element, timings.delay);
this.keyframes = keyframes;
this.preStyleProps = preStyleProps;
this.postStyleProps = postStyleProps;
this._stretchStartingKeyframe = _stretchStartingKeyframe;
this.timings = { duration: timings.duration, delay: timings.delay, easing: timings.easing };
}
containsAnimation() {
return this.keyframes.length > 1;
}
buildKeyframes() {
let keyframes = this.keyframes;
let { delay, duration, easing } = this.timings;
if (this._stretchStartingKeyframe && delay) {
const newKeyframes = [];
const totalTime = duration + delay;
const startingGap = delay / totalTime;
// the original starting keyframe now starts once the delay is done
const newFirstKeyframe = copyStyles(keyframes[0], false);
newFirstKeyframe['offset'] = 0;
newKeyframes.push(newFirstKeyframe);
const oldFirstKeyframe = copyStyles(keyframes[0], false);
oldFirstKeyframe['offset'] = roundOffset(startingGap);
newKeyframes.push(oldFirstKeyframe);
/*
When the keyframe is stretched then it means that the delay before the animation
starts is gone. Instead the first keyframe is placed at the start of the animation
and it is then copied to where it starts when the original delay is over. This basically
means nothing animates during that delay, but the styles are still renderered. For this
to work the original offset values that exist in the original keyframes must be "warped"
so that they can take the new keyframe + delay into account.
delay=1000, duration=1000, keyframes = 0 .5 1
turns into
delay=0, duration=2000, keyframes = 0 .33 .66 1
*/
// offsets between 1 ... n -1 are all warped by the keyframe stretch
const limit = keyframes.length - 1;
for (let i = 1; i <= limit; i++) {
let kf = copyStyles(keyframes[i], false);
const oldOffset = kf['offset'];
const timeAtKeyframe = delay + oldOffset * duration;
kf['offset'] = roundOffset(timeAtKeyframe / totalTime);
newKeyframes.push(kf);
}
// the new starting keyframe should be added at the start
duration = totalTime;
delay = 0;
easing = '';
keyframes = newKeyframes;
}
return createTimelineInstruction(this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true);
}
}
function roundOffset(offset, decimalPoints = 3) {
const mult = Math.pow(10, decimalPoints - 1);
return Math.round(offset * mult) / mult;
}
function flattenStyles(input, allStyles) {
const styles = {};
let allProperties;
input.forEach(token => {
if (token === '*') {
allProperties = allProperties || Object.keys(allStyles);
allProperties.forEach(prop => {
styles[prop] = AUTO_STYLE;
});
}
else {
copyStyles(token, false, styles);
}
});
return styles;
}
class Animation {
constructor(_driver, input) {
this._driver = _driver;
const errors = [];
const ast = buildAnimationAst(_driver, input, errors);
if (errors.length) {
const errorMessage = `animation validation failed:\n${errors.join('\n')}`;
throw new Error(errorMessage);
}
this._animationAst = ast;
}
buildTimelines(element, startingStyles, destinationStyles, options, subInstructions) {
const start = Array.isArray(startingStyles) ? normalizeStyles(startingStyles) :
startingStyles;
const dest = Array.isArray(destinationStyles) ? normalizeStyles(destinationStyles) :
destinationStyles;
const errors = [];
subInstructions = subInstructions || new ElementInstructionMap();
const result = buildAnimationTimelines(this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors);
if (errors.length) {
const errorMessage = `animation building failed:\n${errors.join('\n')}`;
throw new Error(errorMessage);
}
return result;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @publicApi
*/
class AnimationStyleNormalizer {
}
/**
* @publicApi
*/
class NoopAnimationStyleNormalizer {
normalizePropertyName(propertyName, errors) {
return propertyName;
}
normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {
return value;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class WebAnimationsStyleNormalizer extends AnimationStyleNormalizer {
normalizePropertyName(propertyName, errors) {
return dashCaseToCamelCase(propertyName);
}
normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {
let unit = '';
const strVal = value.toString().trim();
if (DIMENSIONAL_PROP_MAP[normalizedProperty] && value !== 0 && value !== '0') {
if (typeof value === 'number') {
unit = 'px';
}
else {
const valAndSuffixMatch = value.match(/^[+-]?[\d\.]+([a-z]*)$/);
if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
errors.push(`Please provide a CSS unit value for ${userProvidedProperty}:${value}`);
}
}
}
return strVal + unit;
}
}
const ɵ0$1 = () => makeBooleanMap('width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective'
.split(','));
const DIMENSIONAL_PROP_MAP = (ɵ0$1)();
function makeBooleanMap(keys) {
const map = {};
keys.forEach(key => map[key] = true);
return map;
}
function createTransitionInstruction(element, triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, totalTime, errors) {
return {
type: 0 /* TransitionAnimation */,
element,
triggerName,
isRemovalTransition,
fromState,
fromStyles,
toState,
toStyles,
timelines,
queriedElements,
preStyleProps,
postStyleProps,
totalTime,
errors
};
}
const EMPTY_OBJECT = {};
class AnimationTransitionFactory {
constructor(_triggerName, ast, _stateStyles) {
this._triggerName = _triggerName;
this.ast = ast;
this._stateStyles = _stateStyles;
}
match(currentState, nextState, element, params) {
return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState, element, params);
}
buildStyles(stateName, params, errors) {
const backupStateStyler = this._stateStyles['*'];
const stateStyler = this._stateStyles[stateName];
const backupStyles = backupStateStyler ? backupStateStyler.buildStyles(params, errors) : {};
return stateStyler ? stateStyler.buildStyles(params, errors) : backupStyles;
}
build(driver, element, currentState, nextState, enterClassName, leaveClassName, currentOptions, nextOptions, subInstructions, skipAstBuild) {
const errors = [];
const transitionAnimationParams = this.ast.options && this.ast.options.params || EMPTY_OBJECT;
const currentAnimationParams = currentOptions && currentOptions.params || EMPTY_OBJECT;
const currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors);
const nextAnimationParams = nextOptions && nextOptions.params || EMPTY_OBJECT;
const nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors);
const queriedElements = new Set();
const preStyleMap = new Map();
const postStyleMap = new Map();
const isRemoval = nextState === 'void';
const animationOptions = { params: Object.assign(Object.assign({}, transitionAnimationParams), nextAnimationParams) };
const timelines = skipAstBuild ?
[] :
buildAnimationTimelines(driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors);
let totalTime = 0;
timelines.forEach(tl => {
totalTime = Math.max(tl.duration + tl.delay, totalTime);
});
if (errors.length) {
return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, totalTime, errors);
}
timelines.forEach(tl => {
const elm = tl.element;
const preProps = getOrSetAsInMap(preStyleMap, elm, {});
tl.preStyleProps.forEach(prop => preProps[prop] = true);
const postProps = getOrSetAsInMap(postStyleMap, elm, {});
tl.postStyleProps.forEach(prop => postProps[prop] = true);
if (elm !== element) {
queriedElements.add(elm);
}
});
const queriedElementsList = iteratorToArray(queriedElements.values());
return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, queriedElementsList, preStyleMap, postStyleMap, totalTime);
}
}
function oneOrMoreTransitionsMatch(matchFns, currentState, nextState, element, params) {
return matchFns.some(fn => fn(currentState, nextState, element, params));
}
class AnimationStateStyles {
constructor(styles, defaultParams, normalizer) {
this.styles = styles;
this.defaultParams = defaultParams;
this.normalizer = normalizer;
}
buildStyles(params, errors) {
const finalStyles = {};
const combinedParams = copyObj(this.defaultParams);
Object.keys(params).forEach(key => {
const value = params[key];
if (value != null) {
combinedParams[key] = value;
}
});
this.styles.styles.forEach(value => {
if (typeof value !== 'string') {
const styleObj = value;
Object.keys(styleObj).forEach(prop => {
let val = styleObj[prop];
if (val.length > 1) {
val = interpolateParams(val, combinedParams, errors);
}
const normalizedProp = this.normalizer.normalizePropertyName(prop, errors);
val = this.normalizer.normalizeStyleValue(prop, normalizedProp, val, errors);
finalStyles[normalizedProp] = val;
});
}
});
return finalStyles;
}
}
function buildTrigger(name, ast, normalizer) {
return new AnimationTrigger(name, ast, normalizer);
}
class AnimationTrigger {
constructor(name, ast, _normalizer) {
this.name = name;
this.ast = ast;
this._normalizer = _normalizer;
this.transitionFactories = [];
this.states = {};
ast.states.forEach(ast => {
const defaultParams = (ast.options && ast.options.params) || {};
this.states[ast.name] = new AnimationStateStyles(ast.style, defaultParams, _normalizer);
});
balanceProperties(this.states, 'true', '1');
balanceProperties(this.states, 'false', '0');
ast.transitions.forEach(ast => {
this.transitionFactories.push(new AnimationTransitionFactory(name, ast, this.states));
});
this.fallbackTransition = createFallbackTransition(name, this.states, this._normalizer);
}
get containsQueries() {
return this.ast.queryCount > 0;
}
matchTransition(currentState, nextState, element, params) {
const entry = this.transitionFactories.find(f => f.match(currentState, nextState, element, params));
return entry || null;
}
matchStyles(currentState, params, errors) {
return this.fallbackTransition.buildStyles(currentState, params, errors);
}
}
function createFallbackTransition(triggerName, states, normalizer) {
const matchers = [(fromState, toState) => true];
const animation = { type: 2 /* Sequence */, steps: [], options: null };
const transition = {
type: 1 /* Transition */,
animation,
matchers,
options: null,
queryCount: 0,
depCount: 0
};
return new AnimationTransitionFactory(triggerName, transition, states);
}
function balanceProperties(obj, key1, key2) {
if (obj.hasOwnProperty(key1)) {
if (!obj.hasOwnProperty(key2)) {
obj[key2] = obj[key1];
}
}
else if (obj.hasOwnProperty(key2)) {
obj[key1] = obj[key2];
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const EMPTY_INSTRUCTION_MAP = new ElementInstructionMap();
class TimelineAnimationEngine {
constructor(bodyNode, _driver, _normalizer) {
this.bodyNode = bodyNode;
this._driver = _driver;
this._normalizer = _normalizer;
this._animations = {};
this._playersById = {};
this.players = [];
}
register(id, metadata) {
const errors = [];
const ast = buildAnimationAst(this._driver, metadata, errors);
if (errors.length) {
throw new Error(`Unable to build the animation due to the following errors: ${errors.join('\n')}`);
}
else {
this._animations[id] = ast;
}
}
_buildPlayer(i, preStyles, postStyles) {
const element = i.element;
const keyframes = normalizeKeyframes(this._driver, this._normalizer, element, i.keyframes, preStyles, postStyles);
return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, [], true);
}
create(id, element, options = {}) {
const errors = [];
const ast = this._animations[id];
let instructions;
const autoStylesMap = new Map();
if (ast) {
instructions = buildAnimationTimelines(this._driver, element, ast, ENTER_CLASSNAME, LEAVE_CLASSNAME, {}, {}, options, EMPTY_INSTRUCTION_MAP, errors);
instructions.forEach(inst => {
const styles = getOrSetAsInMap(autoStylesMap, inst.element, {});
inst.postStyleProps.forEach(prop => styles[prop] = null);
});
}
else {
errors.push('The requested animation doesn\'t exist or has already been destroyed');
instructions = [];
}
if (errors.length) {
throw new Error(`Unable to create the animation due to the following errors: ${errors.join('\n')}`);
}
autoStylesMap.forEach((styles, element) => {
Object.keys(styles).forEach(prop => {
styles[prop] = this._driver.computeStyle(element, prop, AUTO_STYLE);
});
});
const players = instructions.map(i => {
const styles = autoStylesMap.get(i.element);
return this._buildPlayer(i, {}, styles);
});
const player = optimizeGroupPlayer(players);
this._playersById[id] = player;
player.onDestroy(() => this.destroy(id));
this.players.push(player);
return player;
}
destroy(id) {
const player = this._getPlayer(id);
player.destroy();
delete this._playersById[id];
const index = this.players.indexOf(player);
if (index >= 0) {
this.players.splice(index, 1);
}
}
_getPlayer(id) {
const player = this._playersById[id];
if (!player) {
throw new Error(`Unable to find the timeline player referenced by ${id}`);
}
return player;
}
listen(id, element, eventName, callback) {
// triggerName, fromState, toState are all ignored for timeline animations
const baseEvent = makeAnimationEvent(element, '', '', '');
listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback);
return () => { };
}
command(id, element, command, args) {
if (command == 'register') {
this.register(id, args[0]);
return;
}
if (command == 'create') {
const options = (args[0] || {});
this.create(id, element, options);
return;
}
const player = this._getPlayer(id);
switch (command) {
case 'play':
player.play();
break;
case 'pause':
player.pause();
break;
case 'reset':
player.reset();
break;
case 'restart':
player.restart();
break;
case 'finish':
player.finish();
break;
case 'init':
player.init();
break;
case 'setPosition':
player.setPosition(parseFloat(args[0]));
break;
case 'destroy':
this.destroy(id);
break;
}
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const QUEUED_CLASSNAME = 'ng-animate-queued';
const QUEUED_SELECTOR = '.ng-animate-queued';
const DISABLED_CLASSNAME = 'ng-animate-disabled';
const DISABLED_SELECTOR = '.ng-animate-disabled';
const STAR_CLASSNAME = 'ng-star-inserted';
const STAR_SELECTOR = '.ng-star-inserted';
const EMPTY_PLAYER_ARRAY = [];
const NULL_REMOVAL_STATE = {
namespaceId: '',
setForRemoval: false,
setForMove: false,
hasAnimation: false,
removedBeforeQueried: false
};
const NULL_REMOVED_QUERIED_STATE = {
namespaceId: '',
setForMove: false,
setForRemoval: false,
hasAnimation: false,
removedBeforeQueried: true
};
const REMOVAL_FLAG = '__ng_removed';
class StateValue {
constructor(input, namespaceId = '') {
this.namespaceId = namespaceId;
const isObj = input && input.hasOwnProperty('value');
const value = isObj ? input['value'] : input;
this.value = normalizeTriggerValue(value);
if (isObj) {
const options = copyObj(input);
delete options['value'];
this.options = options;
}
else {
this.options = {};
}
if (!this.options.params) {
this.options.params = {};
}
}
get params() {
return this.options.params;
}
absorbOptions(options) {
const newParams = options.params;
if (newParams) {
const oldParams = this.options.params;
Object.keys(newParams).forEach(prop => {
if (oldParams[prop] == null) {
oldParams[prop] = newParams[prop];
}
});
}
}
}
const VOID_VALUE = 'void';
const DEFAULT_STATE_VALUE = new StateValue(VOID_VALUE);
class AnimationTransitionNamespace {
constructor(id, hostElement, _engine) {
this.id = id;
this.hostElement = hostElement;
this._engine = _engine;
this.players = [];
this._triggers = {};
this._queue = [];
this._elementListeners = new Map();
this._hostClassName = 'ng-tns-' + id;
addClass(hostElement, this._hostClassName);
}
listen(element, name, phase, callback) {
if (!this._triggers.hasOwnProperty(name)) {
throw new Error(`Unable to listen on the animation trigger event "${phase}" because the animation trigger "${name}" doesn\'t exist!`);
}
if (phase == null || phase.length == 0) {
throw new Error(`Unable to listen on the animation trigger "${name}" because the provided event is undefined!`);
}
if (!isTriggerEventValid(phase)) {
throw new Error(`The provided animation trigger event "${phase}" for the animation trigger "${name}" is not supported!`);
}
const listeners = getOrSetAsInMap(this._elementListeners, element, []);
const data = { name, phase, callback };
listeners.push(data);
const triggersWithStates = getOrSetAsInMap(this._engine.statesByElement, element, {});
if (!triggersWithStates.hasOwnProperty(name)) {
addClass(element, NG_TRIGGER_CLASSNAME);
addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);
triggersWithStates[name] = DEFAULT_STATE_VALUE;
}
return () => {
// the event listener is removed AFTER the flush has occurred such
// that leave animations callbacks can fire (otherwise if the node
// is removed in between then the listeners would be deregistered)
this._engine.afterFlush(() => {
const index = listeners.indexOf(data);
if (index >= 0) {
listeners.splice(index, 1);
}
if (!this._triggers[name]) {
delete triggersWithStates[name];
}
});
};
}
register(name, ast) {
if (this._triggers[name]) {
// throw
return false;
}
else {
this._triggers[name] = ast;
return true;
}
}
_getTrigger(name) {
const trigger = this._triggers[name];
if (!trigger) {
throw new Error(`The provided animation trigger "${name}" has not been registered!`);
}
return trigger;
}
trigger(element, triggerName, value, defaultToFallback = true) {
const trigger = this._getTrigger(triggerName);
const player = new TransitionAnimationPlayer(this.id, triggerName, element);
let triggersWithStates = this._engine.statesByElement.get(element);
if (!triggersWithStates) {
addClass(element, NG_TRIGGER_CLASSNAME);
addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);
this._engine.statesByElement.set(element, triggersWithStates = {});
}
let fromState = triggersWithStates[triggerName];
const toState = new StateValue(value, this.id);
const isObj = value && value.hasOwnProperty('value');
if (!isObj && fromState) {
toState.absorbOptions(fromState.options);
}
triggersWithStates[triggerName] = toState;
if (!fromState) {
fromState = DEFAULT_STATE_VALUE;
}
const isRemoval = toState.value === VOID_VALUE;
// normally this isn't reached by here, however, if an object expression
// is passed in then it may be a new object each time. Comparing the value
// is important since that will stay the same despite there being a new object.
// The removal arc here is special cased because the same element is triggered
// twice in the event that it contains animations on the outer/inner portions
// of the host container
if (!isRemoval && fromState.value === toState.value) {
// this means that despite the value not changing, some inner params
// have changed which means that the animation final styles need to be applied
if (!objEquals(fromState.params, toState.params)) {
const errors = [];
const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);
const toStyles = trigger.matchStyles(toState.value, toState.params, errors);
if (errors.length) {
this._engine.reportError(errors);
}
else {
this._engine.afterFlush(() => {
eraseStyles(element, fromStyles);
setStyles(element, toStyles);
});
}
}
return;
}
const playersOnElement = getOrSetAsInMap(this._engine.playersByElement, element, []);
playersOnElement.forEach(player => {
// only remove the player if it is queued on the EXACT same trigger/namespace
// we only also deal with queued players here because if the animation has
// started then we want to keep the player alive until the flush happens
// (which is where the previousPlayers are passed into the new palyer)
if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {
player.destroy();
}
});
let transition = trigger.matchTransition(fromState.value, toState.value, element, toState.params);
let isFallbackTransition = false;
if (!transition) {
if (!defaultToFallback)
return;
transition = trigger.fallbackTransition;
isFallbackTransition = true;
}
this._engine.totalQueuedPlayers++;
this._queue.push({ element, triggerName, transition, fromState, toState, player, isFallbackTransition });
if (!isFallbackTransition) {
addClass(element, QUEUED_CLASSNAME);
player.onStart(() => {
removeClass(element, QUEUED_CLASSNAME);
});
}
player.onDone(() => {
let index = this.players.indexOf(player);
if (index >= 0) {
this.players.splice(index, 1);
}
const players = this._engine.playersByElement.get(element);
if (players) {
let index = players.indexOf(player);
if (index >= 0) {
players.splice(index, 1);
}
}
});
this.players.push(player);
playersOnElement.push(player);
return player;
}
deregister(name) {
delete this._triggers[name];
this._engine.statesByElement.forEach((stateMap, element) => {
delete stateMap[name];
});
this._elementListeners.forEach((listeners, element) => {
this._elementListeners.set(element, listeners.filter(entry => {
return entry.name != name;
}));
});
}
clearElementCache(element) {
this._engine.statesByElement.delete(element);
this._elementListeners.delete(element);
const elementPlayers = this._engine.playersByElement.get(element);
if (elementPlayers) {
elementPlayers.forEach(player => player.destroy());
this._engine.playersByElement.delete(element);
}
}
_signalRemovalForInnerTriggers(rootElement, context) {
const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);
// emulate a leave animation for all inner nodes within this node.
// If there are no animations found for any of the nodes then clear the cache
// for the element.
elements.forEach(elm => {
// this means that an inner remove() operation has already kicked off
// the animation on this element...
if (elm[REMOVAL_FLAG])
return;
const namespaces = this._engine.fetchNamespacesByElement(elm);
if (namespaces.size) {
namespaces.forEach(ns => ns.triggerLeaveAnimation(elm, context, false, true));
}
else {
this.clearElementCache(elm);
}
});
// If the child elements were removed along with the parent, their animations might not
// have completed. Clear all the elements from the cache so we don't end up with a memory leak.
this._engine.afterFlushAnimationsDone(() => elements.forEach(elm => this.clearElementCache(elm)));
}
triggerLeaveAnimation(element, context, destroyAfterComplete, defaultToFallback) {
const triggerStates = this._engine.statesByElement.get(element);
if (triggerStates) {
const players = [];
Object.keys(triggerStates).forEach(triggerName => {
// this check is here in the event that an element is removed
// twice (both on the host level and the component level)
if (this._triggers[triggerName]) {
const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);
if (player) {
players.push(player);
}
}
});
if (players.length) {
this._engine.markElementAsRemoved(this.id, element, true, context);
if (destroyAfterComplete) {
optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));
}
return true;
}
}
return false;
}
prepareLeaveAnimationListeners(element) {
const listeners = this._elementListeners.get(element);
const elementStates = this._engine.statesByElement.get(element);
// if this statement fails then it means that the element was picked up
// by an earlier flush (or there are no listeners at all to track the leave).
if (listeners && elementStates) {
const visitedTriggers = new Set();
listeners.forEach(listener => {
const triggerName = listener.name;
if (visitedTriggers.has(triggerName))
return;
visitedTriggers.add(triggerName);
const trigger = this._triggers[triggerName];
const transition = trigger.fallbackTransition;
const fromState = elementStates[triggerName] || DEFAULT_STATE_VALUE;
const toState = new StateValue(VOID_VALUE);
const player = new TransitionAnimationPlayer(this.id, triggerName, element);
this._engine.totalQueuedPlayers++;
this._queue.push({
element,
triggerName,
transition,
fromState,
toState,
player,
isFallbackTransition: true
});
});
}
}
removeNode(element, context) {
const engine = this._engine;
if (element.childElementCount) {
this._signalRemovalForInnerTriggers(element, context);
}
// this means that a * => VOID animation was detected and kicked off
if (this.triggerLeaveAnimation(element, context, true))
return;
// find the player that is animating and make sure that the
// removal is delayed until that player has completed
let containsPotentialParentTransition = false;
if (engine.totalAnimations) {
const currentPlayers = engine.players.length ? engine.playersByQueriedElement.get(element) : [];
// when this `if statement` does not continue forward it means that
// a previous animation query has selected the current element and
// is animating it. In this situation want to continue forwards and
// allow the element to be queued up for animation later.
if (currentPlayers && currentPlayers.length) {
containsPotentialParentTransition = true;
}
else {
let parent = element;
while (parent = parent.parentNode) {
const triggers = engine.statesByElement.get(parent);
if (triggers) {
containsPotentialParentTransition = true;
break;
}
}
}
}
// at this stage we know that the element will either get removed
// during flush or will be picked up by a parent query. Either way
// we need to fire the listeners for this element when it DOES get
// removed (once the query parent animation is done or after flush)
this.prepareLeaveAnimationListeners(element);
// whether or not a parent has an animation we need to delay the deferral of the leave
// operation until we have more information (which we do after flush() has been called)
if (containsPotentialParentTransition) {
engine.markElementAsRemoved(this.id, element, false, context);
}
else {
const removalFlag = element[REMOVAL_FLAG];
if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {
// we do this after the flush has occurred such
// that the callbacks can be fired
engine.afterFlush(() => this.clearElementCache(element));
engine.destroyInnerAnimations(element);
engine._onRemovalComplete(element, context);
}
}
}
insertNode(element, parent) {
addClass(element, this._hostClassName);
}
drainQueuedTransitions(microtaskId) {
const instructions = [];
this._queue.forEach(entry => {
const player = entry.player;
if (player.destroyed)
return;
const element = entry.element;
const listeners = this._elementListeners.get(element);
if (listeners) {
listeners.forEach((listener) => {
if (listener.name == entry.triggerName) {
const baseEvent = makeAnimationEvent(element, entry.triggerName, entry.fromState.value, entry.toState.value);
baseEvent['_data'] = microtaskId;
listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);
}
});
}
if (player.markedForDestroy) {
this._engine.afterFlush(() => {
// now we can destroy the element properly since the event listeners have
// been bound to the player
player.destroy();
});
}
else {
instructions.push(entry);
}
});
this._queue = [];
return instructions.sort((a, b) => {
// if depCount == 0 them move to front
// otherwise if a contains b then move back
const d0 = a.transition.ast.depCount;
const d1 = b.transition.ast.depCount;
if (d0 == 0 || d1 == 0) {
return d0 - d1;
}
return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;
});
}
destroy(context) {
this.players.forEach(p => p.destroy());
this._signalRemovalForInnerTriggers(this.hostElement, context);
}
elementContainsData(element) {
let containsData = false;
if (this._elementListeners.has(element))
containsData = true;
containsData =
(this._queue.find(entry => entry.element === element) ? true : false) || containsData;
return containsData;
}
}
class TransitionAnimationEngine {
constructor(bodyNode, driver, _normalizer) {
this.bodyNode = bodyNode;
this.driver = driver;
this._normalizer = _normalizer;
this.players = [];
this.newHostElements = new Map();
this.playersByElement = new Map();
this.playersByQueriedElement = new Map();
this.statesByElement = new Map();
this.disabledNodes = new Set();
this.totalAnimations = 0;
this.totalQueuedPlayers = 0;
this._namespaceLookup = {};
this._namespaceList = [];
this._flushFns = [];
this._whenQuietFns = [];
this.namespacesByHostElement = new Map();
this.collectedEnterElements = [];
this.collectedLeaveElements = [];
// this method is designed to be overridden by the code that uses this engine
this.onRemovalComplete = (element, context) => { };
}
/** @internal */
_onRemovalComplete(element, context) {
this.onRemovalComplete(element, context);
}
get queuedPlayers() {
const players = [];
this._namespaceList.forEach(ns => {
ns.players.forEach(player => {
if (player.queued) {
players.push(player);
}
});
});
return players;
}
createNamespace(namespaceId, hostElement) {
const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);
if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {
this._balanceNamespaceList(ns, hostElement);
}
else {
// defer this later until flush during when the host element has
// been inserted so that we know exactly where to place it in
// the namespace list
this.newHostElements.set(hostElement, ns);
// given that this host element is apart of the animation code, it
// may or may not be inserted by a parent node that is of an
// animation renderer type. If this happens then we can still have
// access to this item when we query for :enter nodes. If the parent
// is a renderer then the set data-structure will normalize the entry
this.collectEnterElement(hostElement);
}
return this._namespaceLookup[namespaceId] = ns;
}
_balanceNamespaceList(ns, hostElement) {
const limit = this._namespaceList.length - 1;
if (limit >= 0) {
let found = false;
for (let i = limit; i >= 0; i--) {
const nextNamespace = this._namespaceList[i];
if (this.driver.containsElement(nextNamespace.hostElement, hostElement)) {
this._namespaceList.splice(i + 1, 0, ns);
found = true;
break;
}
}
if (!found) {
this._namespaceList.splice(0, 0, ns);
}
}
else {
this._namespaceList.push(ns);
}
this.namespacesByHostElement.set(hostElement, ns);
return ns;
}
register(namespaceId, hostElement) {
let ns = this._namespaceLookup[namespaceId];
if (!ns) {
ns = this.createNamespace(namespaceId, hostElement);
}
return ns;
}
registerTrigger(namespaceId, name, trigger) {
let ns = this._namespaceLookup[namespaceId];
if (ns && ns.register(name, trigger)) {
this.totalAnimations++;
}
}
destroy(namespaceId, context) {
if (!namespaceId)
return;
const ns = this._fetchNamespace(namespaceId);
this.afterFlush(() => {
this.namespacesByHostElement.delete(ns.hostElement);
delete this._namespaceLookup[namespaceId];
const index = this._namespaceList.indexOf(ns);
if (index >= 0) {
this._namespaceList.splice(index, 1);
}
});
this.afterFlushAnimationsDone(() => ns.destroy(context));
}
_fetchNamespace(id) {
return this._namespaceLookup[id];
}
fetchNamespacesByElement(element) {
// normally there should only be one namespace per element, however
// if @triggers are placed on both the component element and then
// its host element (within the component code) then there will be
// two namespaces returned. We use a set here to simply the dedupe
// of namespaces incase there are multiple triggers both the elm and host
const namespaces = new Set();
const elementStates = this.statesByElement.get(element);
if (elementStates) {
const keys = Object.keys(elementStates);
for (let i = 0; i < keys.length; i++) {
const nsId = elementStates[keys[i]].namespaceId;
if (nsId) {
const ns = this._fetchNamespace(nsId);
if (ns) {
namespaces.add(ns);
}
}
}
}
return namespaces;
}
trigger(namespaceId, element, name, value) {
if (isElementNode(element)) {
const ns = this._fetchNamespace(namespaceId);
if (ns) {
ns.trigger(element, name, value);
return true;
}
}
return false;
}
insertNode(namespaceId, element, parent, insertBefore) {
if (!isElementNode(element))
return;
// special case for when an element is removed and reinserted (move operation)
// when this occurs we do not want to use the element for deletion later
const details = element[REMOVAL_FLAG];
if (details && details.setForRemoval) {
details.setForRemoval = false;
details.setForMove = true;
const index = this.collectedLeaveElements.indexOf(element);
if (index >= 0) {
this.collectedLeaveElements.splice(index, 1);
}
}
// in the event that the namespaceId is blank then the caller
// code does not contain any animation code in it, but it is
// just being called so that the node is marked as being inserted
if (namespaceId) {
const ns = this._fetchNamespace(namespaceId);
// This if-statement is a workaround for router issue #21947.
// The router sometimes hits a race condition where while a route
// is being instantiated a new navigation arrives, triggering leave
// animation of DOM that has not been fully initialized, until this
// is resolved, we need to handle the scenario when DOM is not in a
// consistent state during the animation.
if (ns) {
ns.insertNode(element, parent);
}
}
// only *directives and host elements are inserted before
if (insertBefore) {
this.collectEnterElement(element);
}
}
collectEnterElement(element) {
this.collectedEnterElements.push(element);
}
markElementAsDisabled(element, value) {
if (value) {
if (!this.disabledNodes.has(element)) {
this.disabledNodes.add(element);
addClass(element, DISABLED_CLASSNAME);
}
}
else if (this.disabledNodes.has(element)) {
this.disabledNodes.delete(element);
removeClass(element, DISABLED_CLASSNAME);
}
}
removeNode(namespaceId, element, isHostElement, context) {
if (isElementNode(element)) {
const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;
if (ns) {
ns.removeNode(element, context);
}
else {
this.markElementAsRemoved(namespaceId, element, false, context);
}
if (isHostElement) {
const hostNS = this.namespacesByHostElement.get(element);
if (hostNS && hostNS.id !== namespaceId) {
hostNS.removeNode(element, context);
}
}
}
else {
this._onRemovalComplete(element, context);
}
}
markElementAsRemoved(namespaceId, element, hasAnimation, context) {
this.collectedLeaveElements.push(element);
element[REMOVAL_FLAG] =
{ namespaceId, setForRemoval: context, hasAnimation, removedBeforeQueried: false };
}
listen(namespaceId, element, name, phase, callback) {
if (isElementNode(element)) {
return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);
}
return () => { };
}
_buildInstruction(entry, subTimelines, enterClassName, leaveClassName, skipBuildAst) {
return entry.transition.build(this.driver, entry.element, entry.fromState.value, entry.toState.value, enterClassName, leaveClassName, entry.fromState.options, entry.toState.options, subTimelines, skipBuildAst);
}
destroyInnerAnimations(containerElement) {
let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);
elements.forEach(element => this.destroyActiveAnimationsForElement(element));
if (this.playersByQueriedElement.size == 0)
return;
elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);
elements.forEach(element => this.finishActiveQueriedAnimationOnElement(element));
}
destroyActiveAnimationsForElement(element) {
const players = this.playersByElement.get(element);
if (players) {
players.forEach(player => {
// special case for when an element is set for destruction, but hasn't started.
// in this situation we want to delay the destruction until the flush occurs
// so that any event listeners attached to the player are triggered.
if (player.queued) {
player.markedForDestroy = true;
}
else {
player.destroy();
}
});
}
}
finishActiveQueriedAnimationOnElement(element) {
const players = this.playersByQueriedElement.get(element);
if (players) {
players.forEach(player => player.finish());
}
}
whenRenderingDone() {
return new Promise(resolve => {
if (this.players.length) {
return optimizeGroupPlayer(this.players).onDone(() => resolve());
}
else {
resolve();
}
});
}
processLeaveNode(element) {
const details = element[REMOVAL_FLAG];
if (details && details.setForRemoval) {
// this will prevent it from removing it twice
element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;
if (details.namespaceId) {
this.destroyInnerAnimations(element);
const ns = this._fetchNamespace(details.namespaceId);
if (ns) {
ns.clearElementCache(element);
}
}
this._onRemovalComplete(element, details.setForRemoval);
}
if (this.driver.matchesElement(element, DISABLED_SELECTOR)) {
this.markElementAsDisabled(element, false);
}
this.driver.query(element, DISABLED_SELECTOR, true).forEach(node => {
this.markElementAsDisabled(node, false);
});
}
flush(microtaskId = -1) {
let players = [];
if (this.newHostElements.size) {
this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));
this.newHostElements.clear();
}
if (this.totalAnimations && this.collectedEnterElements.length) {
for (let i = 0; i < this.collectedEnterElements.length; i++) {
const elm = this.collectedEnterElements[i];
addClass(elm, STAR_CLASSNAME);
}
}
if (this._namespaceList.length &&
(this.totalQueuedPlayers || this.collectedLeaveElements.length)) {
const cleanupFns = [];
try {
players = this._flushAnimations(cleanupFns, microtaskId);
}
finally {
for (let i = 0; i < cleanupFns.length; i++) {
cleanupFns[i]();
}
}
}
else {
for (let i = 0; i < this.collectedLeaveElements.length; i++) {
const element = this.collectedLeaveElements[i];
this.processLeaveNode(element);
}
}
this.totalQueuedPlayers = 0;
this.collectedEnterElements.length = 0;
this.collectedLeaveElements.length = 0;
this._flushFns.forEach(fn => fn());
this._flushFns = [];
if (this._whenQuietFns.length) {
// we move these over to a variable so that
// if any new callbacks are registered in another
// flush they do not populate the existing set
const quietFns = this._whenQuietFns;
this._whenQuietFns = [];
if (players.length) {
optimizeGroupPlayer(players).onDone(() => {
quietFns.forEach(fn => fn());
});
}
else {
quietFns.forEach(fn => fn());
}
}
}
reportError(errors) {
throw new Error(`Unable to process animations due to the following failed trigger transitions\n ${errors.join('\n')}`);
}
_flushAnimations(cleanupFns, microtaskId) {
const subTimelines = new ElementInstructionMap();
const skippedPlayers = [];
const skippedPlayersMap = new Map();
const queuedInstructions = [];
const queriedElements = new Map();
const allPreStyleElements = new Map();
const allPostStyleElements = new Map();
const disabledElementsSet = new Set();
this.disabledNodes.forEach(node => {
disabledElementsSet.add(node);
const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);
for (let i = 0; i < nodesThatAreDisabled.length; i++) {
disabledElementsSet.add(nodesThatAreDisabled[i]);
}
});
const bodyNode = this.bodyNode;
const allTriggerElements = Array.from(this.statesByElement.keys());
const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);
// this must occur before the instructions are built below such that
// the :enter queries match the elements (since the timeline queries
// are fired during instruction building).
const enterNodeMapIds = new Map();
let i = 0;
enterNodeMap.forEach((nodes, root) => {
const className = ENTER_CLASSNAME + i++;
enterNodeMapIds.set(root, className);
nodes.forEach(node => addClass(node, className));
});
const allLeaveNodes = [];
const mergedLeaveNodes = new Set();
const leaveNodesWithoutAnimations = new Set();
for (let i = 0; i < this.collectedLeaveElements.length; i++) {
const element = this.collectedLeaveElements[i];
const details = element[REMOVAL_FLAG];
if (details && details.setForRemoval) {
allLeaveNodes.push(element);
mergedLeaveNodes.add(element);
if (details.hasAnimation) {
this.driver.query(element, STAR_SELECTOR, true).forEach(elm => mergedLeaveNodes.add(elm));
}
else {
leaveNodesWithoutAnimations.add(element);
}
}
}
const leaveNodeMapIds = new Map();
const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));
leaveNodeMap.forEach((nodes, root) => {
const className = LEAVE_CLASSNAME + i++;
leaveNodeMapIds.set(root, className);
nodes.forEach(node => addClass(node, className));
});
cleanupFns.push(() => {
enterNodeMap.forEach((nodes, root) => {
const className = enterNodeMapIds.get(root);
nodes.forEach(node => removeClass(node, className));
});
leaveNodeMap.forEach((nodes, root) => {
const className = leaveNodeMapIds.get(root);
nodes.forEach(node => removeClass(node, className));
});
allLeaveNodes.forEach(element => {
this.processLeaveNode(element);
});
});
const allPlayers = [];
const erroneousTransitions = [];
for (let i = this._namespaceList.length - 1; i >= 0; i--) {
const ns = this._namespaceList[i];
ns.drainQueuedTransitions(microtaskId).forEach(entry => {
const player = entry.player;
const element = entry.element;
allPlayers.push(player);
if (this.collectedEnterElements.length) {
const details = element[REMOVAL_FLAG];
// move animations are currently not supported...
if (details && details.setForMove) {
player.destroy();
return;
}
}
const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element);
const leaveClassName = leaveNodeMapIds.get(element);
const enterClassName = enterNodeMapIds.get(element);
const instruction = this._buildInstruction(entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned);
if (instruction.errors && instruction.errors.length) {
erroneousTransitions.push(instruction);
return;
}
// even though the element may not be apart of the DOM, it may
// still be added at a later point (due to the mechanics of content
// projection and/or dynamic component insertion) therefore it's
// important we still style the element.
if (nodeIsOrphaned) {
player.onStart(() => eraseStyles(element, instruction.fromStyles));
player.onDestroy(() => setStyles(element, instruction.toStyles));
skippedPlayers.push(player);
return;
}
// if a unmatched transition is queued to go then it SHOULD NOT render
// an animation and cancel the previously running animations.
if (entry.isFallbackTransition) {
player.onStart(() => eraseStyles(element, instruction.fromStyles));
player.onDestroy(() => setStyles(element, instruction.toStyles));
skippedPlayers.push(player);
return;
}
// this means that if a parent animation uses this animation as a sub trigger
// then it will instruct the timeline builder to not add a player delay, but
// instead stretch the first keyframe gap up until the animation starts. The
// reason this is important is to prevent extra initialization styles from being
// required by the user in the animation.
instruction.timelines.forEach(tl => tl.stretchStartingKeyframe = true);
subTimelines.append(element, instruction.timelines);
const tuple = { instruction, player, element };
queuedInstructions.push(tuple);
instruction.queriedElements.forEach(element => getOrSetAsInMap(queriedElements, element, []).push(player));
instruction.preStyleProps.forEach((stringMap, element) => {
const props = Object.keys(stringMap);
if (props.length) {
let setVal = allPreStyleElements.get(element);
if (!setVal) {
allPreStyleElements.set(element, setVal = new Set());
}
props.forEach(prop => setVal.add(prop));
}
});
instruction.postStyleProps.forEach((stringMap, element) => {
const props = Object.keys(stringMap);
let setVal = allPostStyleElements.get(element);
if (!setVal) {
allPostStyleElements.set(element, setVal = new Set());
}
props.forEach(prop => setVal.add(prop));
});
});
}
if (erroneousTransitions.length) {
const errors = [];
erroneousTransitions.forEach(instruction => {
errors.push(`@${instruction.triggerName} has failed due to:\n`);
instruction.errors.forEach(error => errors.push(`- ${error}\n`));
});
allPlayers.forEach(player => player.destroy());
this.reportError(errors);
}
const allPreviousPlayersMap = new Map();
// this map works to tell which element in the DOM tree is contained by
// which animation. Further down below this map will get populated once
// the players are built and in doing so it can efficiently figure out
// if a sub player is skipped due to a parent player having priority.
const animationElementMap = new Map();
queuedInstructions.forEach(entry => {
const element = entry.element;
if (subTimelines.has(element)) {
animationElementMap.set(element, element);
this._beforeAnimationBuild(entry.player.namespaceId, entry.instruction, allPreviousPlayersMap);
}
});
skippedPlayers.forEach(player => {
const element = player.element;
const previousPlayers = this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null);
previousPlayers.forEach(prevPlayer => {
getOrSetAsInMap(allPreviousPlayersMap, element, []).push(prevPlayer);
prevPlayer.destroy();
});
});
// this is a special case for nodes that will be removed (either by)
// having their own leave animations or by being queried in a container
// that will be removed once a parent animation is complete. The idea
// here is that * styles must be identical to ! styles because of
// backwards compatibility (* is also filled in by default in many places).
// Otherwise * styles will return an empty value or auto since the element
// that is being getComputedStyle'd will not be visible (since * = destination)
const replaceNodes = allLeaveNodes.filter(node => {
return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements);
});
// POST STAGE: fill the * styles
const postStylesMap = new Map();
const allLeaveQueriedNodes = cloakAndComputeStyles(postStylesMap, this.driver, leaveNodesWithoutAnimations, allPostStyleElements, AUTO_STYLE);
allLeaveQueriedNodes.forEach(node => {
if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) {
replaceNodes.push(node);
}
});
// PRE STAGE: fill the ! styles
const preStylesMap = new Map();
enterNodeMap.forEach((nodes, root) => {
cloakAndComputeStyles(preStylesMap, this.driver, new Set(nodes), allPreStyleElements, ɵPRE_STYLE);
});
replaceNodes.forEach(node => {
const post = postStylesMap.get(node);
const pre = preStylesMap.get(node);
postStylesMap.set(node, Object.assign(Object.assign({}, post), pre));
});
const rootPlayers = [];
const subPlayers = [];
const NO_PARENT_ANIMATION_ELEMENT_DETECTED = {};
queuedInstructions.forEach(entry => {
const { element, player, instruction } = entry;
// this means that it was never consumed by a parent animation which
// means that it is independent and therefore should be set for animation
if (subTimelines.has(element)) {
if (disabledElementsSet.has(element)) {
player.onDestroy(() => setStyles(element, instruction.toStyles));
player.disabled = true;
player.overrideTotalTime(instruction.totalTime);
skippedPlayers.push(player);
return;
}
// this will flow up the DOM and query the map to figure out
// if a parent animation has priority over it. In the situation
// that a parent is detected then it will cancel the loop. If
// nothing is detected, or it takes a few hops to find a parent,
// then it will fill in the missing nodes and signal them as having
// a detected parent (or a NO_PARENT value via a special constant).
let parentWithAnimation = NO_PARENT_ANIMATION_ELEMENT_DETECTED;
if (animationElementMap.size > 1) {
let elm = element;
const parentsToAdd = [];
while (elm = elm.parentNode) {
const detectedParent = animationElementMap.get(elm);
if (detectedParent) {
parentWithAnimation = detectedParent;
break;
}
parentsToAdd.push(elm);
}
parentsToAdd.forEach(parent => animationElementMap.set(parent, parentWithAnimation));
}
const innerPlayer = this._buildAnimation(player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap);
player.setRealPlayer(innerPlayer);
if (parentWithAnimation === NO_PARENT_ANIMATION_ELEMENT_DETECTED) {
rootPlayers.push(player);
}
else {
const parentPlayers = this.playersByElement.get(parentWithAnimation);
if (parentPlayers && parentPlayers.length) {
player.parentPlayer = optimizeGroupPlayer(parentPlayers);
}
skippedPlayers.push(player);
}
}
else {
eraseStyles(element, instruction.fromStyles);
player.onDestroy(() => setStyles(element, instruction.toStyles));
// there still might be a ancestor player animating this
// element therefore we will still add it as a sub player
// even if its animation may be disabled
subPlayers.push(player);
if (disabledElementsSet.has(element)) {
skippedPlayers.push(player);
}
}
});
// find all of the sub players' corresponding inner animation player
subPlayers.forEach(player => {
// even if any players are not found for a sub animation then it
// will still complete itself after the next tick since it's Noop
const playersForElement = skippedPlayersMap.get(player.element);
if (playersForElement && playersForElement.length) {
const innerPlayer = optimizeGroupPlayer(playersForElement);
player.setRealPlayer(innerPlayer);
}
});
// the reason why we don't actually play the animation is
// because all that a skipped player is designed to do is to
// fire the start/done transition callback events
skippedPlayers.forEach(player => {
if (player.parentPlayer) {
player.syncPlayerEvents(player.parentPlayer);
}
else {
player.destroy();
}
});
// run through all of the queued removals and see if they
// were picked up by a query. If not then perform the removal
// operation right away unless a parent animation is ongoing.
for (let i = 0; i < allLeaveNodes.length; i++) {
const element = allLeaveNodes[i];
const details = element[REMOVAL_FLAG];
removeClass(element, LEAVE_CLASSNAME);
// this means the element has a removal animation that is being
// taken care of and therefore the inner elements will hang around
// until that animation is over (or the parent queried animation)
if (details && details.hasAnimation)
continue;
let players = [];
// if this element is queried or if it contains queried children
// then we want for the element not to be removed from the page
// until the queried animations have finished
if (queriedElements.size) {
let queriedPlayerResults = queriedElements.get(element);
if (queriedPlayerResults && queriedPlayerResults.length) {
players.push(...queriedPlayerResults);
}
let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true);
for (let j = 0; j < queriedInnerElements.length; j++) {
let queriedPlayers = queriedElements.get(queriedInnerElements[j]);
if (queriedPlayers && queriedPlayers.length) {
players.push(...queriedPlayers);
}
}
}
const activePlayers = players.filter(p => !p.destroyed);
if (activePlayers.length) {
removeNodesAfterAnimationDone(this, element, activePlayers);
}
else {
this.processLeaveNode(element);
}
}
// this is required so the cleanup method doesn't remove them
allLeaveNodes.length = 0;
rootPlayers.forEach(player => {
this.players.push(player);
player.onDone(() => {
player.destroy();
const index = this.players.indexOf(player);
this.players.splice(index, 1);
});
player.play();
});
return rootPlayers;
}
elementContainsData(namespaceId, element) {
let containsData = false;
const details = element[REMOVAL_FLAG];
if (details && details.setForRemoval)
containsData = true;
if (this.playersByElement.has(element))
containsData = true;
if (this.playersByQueriedElement.has(element))
containsData = true;
if (this.statesByElement.has(element))
containsData = true;
return this._fetchNamespace(namespaceId).elementContainsData(element) || containsData;
}
afterFlush(callback) {
this._flushFns.push(callback);
}
afterFlushAnimationsDone(callback) {
this._whenQuietFns.push(callback);
}
_getPreviousPlayers(element, isQueriedElement, namespaceId, triggerName, toStateValue) {
let players = [];
if (isQueriedElement) {
const queriedElementPlayers = this.playersByQueriedElement.get(element);
if (queriedElementPlayers) {
players = queriedElementPlayers;
}
}
else {
const elementPlayers = this.playersByElement.get(element);
if (elementPlayers) {
const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE;
elementPlayers.forEach(player => {
if (player.queued)
return;
if (!isRemovalAnimation && player.triggerName != triggerName)
return;
players.push(player);
});
}
}
if (namespaceId || triggerName) {
players = players.filter(player => {
if (namespaceId && namespaceId != player.namespaceId)
return false;
if (triggerName && triggerName != player.triggerName)
return false;
return true;
});
}
return players;
}
_beforeAnimationBuild(namespaceId, instruction, allPreviousPlayersMap) {
const triggerName = instruction.triggerName;
const rootElement = instruction.element;
// when a removal animation occurs, ALL previous players are collected
// and destroyed (even if they are outside of the current namespace)
const targetNameSpaceId = instruction.isRemovalTransition ? undefined : namespaceId;
const targetTriggerName = instruction.isRemovalTransition ? undefined : triggerName;
for (const timelineInstruction of instruction.timelines) {
const element = timelineInstruction.element;
const isQueriedElement = element !== rootElement;
const players = getOrSetAsInMap(allPreviousPlayersMap, element, []);
const previousPlayers = this._getPreviousPlayers(element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState);
previousPlayers.forEach(player => {
const realPlayer = player.getRealPlayer();
if (realPlayer.beforeDestroy) {
realPlayer.beforeDestroy();
}
player.destroy();
players.push(player);
});
}
// this needs to be done so that the PRE/POST styles can be
// computed properly without interfering with the previous animation
eraseStyles(rootElement, instruction.fromStyles);
}
_buildAnimation(namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap) {
const triggerName = instruction.triggerName;
const rootElement = instruction.element;
// we first run this so that the previous animation player
// data can be passed into the successive animation players
const allQueriedPlayers = [];
const allConsumedElements = new Set();
const allSubElements = new Set();
const allNewPlayers = instruction.timelines.map(timelineInstruction => {
const element = timelineInstruction.element;
allConsumedElements.add(element);
// FIXME (matsko): make sure to-be-removed animations are removed properly
const details = element[REMOVAL_FLAG];
if (details && details.removedBeforeQueried)
return new NoopAnimationPlayer(timelineInstruction.duration, timelineInstruction.delay);
const isQueriedElement = element !== rootElement;
const previousPlayers = flattenGroupPlayers((allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY)
.map(p => p.getRealPlayer()))
.filter(p => {
// the `element` is not apart of the AnimationPlayer definition, but
// Mock/WebAnimations
// use the element within their implementation. This will be added in Angular5 to
// AnimationPlayer
const pp = p;
return pp.element ? pp.element === element : false;
});
const preStyles = preStylesMap.get(element);
const postStyles = postStylesMap.get(element);
const keyframes = normalizeKeyframes(this.driver, this._normalizer, element, timelineInstruction.keyframes, preStyles, postStyles);
const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers);
// this means that this particular player belongs to a sub trigger. It is
// important that we match this player up with the corresponding (@trigger.listener)
if (timelineInstruction.subTimeline && skippedPlayersMap) {
allSubElements.add(element);
}
if (isQueriedElement) {
const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element);
wrappedPlayer.setRealPlayer(player);
allQueriedPlayers.push(wrappedPlayer);
}
return player;
});
allQueriedPlayers.forEach(player => {
getOrSetAsInMap(this.playersByQueriedElement, player.element, []).push(player);
player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player));
});
allConsumedElements.forEach(element => addClass(element, NG_ANIMATING_CLASSNAME));
const player = optimizeGroupPlayer(allNewPlayers);
player.onDestroy(() => {
allConsumedElements.forEach(element => removeClass(element, NG_ANIMATING_CLASSNAME));
setStyles(rootElement, instruction.toStyles);
});
// this basically makes all of the callbacks for sub element animations
// be dependent on the upper players for when they finish
allSubElements.forEach(element => {
getOrSetAsInMap(skippedPlayersMap, element, []).push(player);
});
return player;
}
_buildPlayer(instruction, keyframes, previousPlayers) {
if (keyframes.length > 0) {
return this.driver.animate(instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers);
}
// special case for when an empty transition|definition is provided
// ... there is no point in rendering an empty animation
return new NoopAnimationPlayer(instruction.duration, instruction.delay);
}
}
class TransitionAnimationPlayer {
constructor(namespaceId, triggerName, element) {
this.namespaceId = namespaceId;
this.triggerName = triggerName;
this.element = element;
this._player = new NoopAnimationPlayer();
this._containsRealPlayer = false;
this._queuedCallbacks = {};
this.destroyed = false;
this.markedForDestroy = false;
this.disabled = false;
this.queued = true;
this.totalTime = 0;
}
setRealPlayer(player) {
if (this._containsRealPlayer)
return;
this._player = player;
Object.keys(this._queuedCallbacks).forEach(phase => {
this._queuedCallbacks[phase].forEach(callback => listenOnPlayer(player, phase, undefined, callback));
});
this._queuedCallbacks = {};
this._containsRealPlayer = true;
this.overrideTotalTime(player.totalTime);
this.queued = false;
}
getRealPlayer() {
return this._player;
}
overrideTotalTime(totalTime) {
this.totalTime = totalTime;
}
syncPlayerEvents(player) {
const p = this._player;
if (p.triggerCallback) {
player.onStart(() => p.triggerCallback('start'));
}
player.onDone(() => this.finish());
player.onDestroy(() => this.destroy());
}
_queueEvent(name, callback) {
getOrSetAsInMap(this._queuedCallbacks, name, []).push(callback);
}
onDone(fn) {
if (this.queued) {
this._queueEvent('done', fn);
}
this._player.onDone(fn);
}
onStart(fn) {
if (this.queued) {
this._queueEvent('start', fn);
}
this._player.onStart(fn);
}
onDestroy(fn) {
if (this.queued) {
this._queueEvent('destroy', fn);
}
this._player.onDestroy(fn);
}
init() {
this._player.init();
}
hasStarted() {
return this.queued ? false : this._player.hasStarted();
}
play() {
!this.queued && this._player.play();
}
pause() {
!this.queued && this._player.pause();
}
restart() {
!this.queued && this._player.restart();
}
finish() {
this._player.finish();
}
destroy() {
this.destroyed = true;
this._player.destroy();
}
reset() {
!this.queued && this._player.reset();
}
setPosition(p) {
if (!this.queued) {
this._player.setPosition(p);
}
}
getPosition() {
return this.queued ? 0 : this._player.getPosition();
}
/** @internal */
triggerCallback(phaseName) {
const p = this._player;
if (p.triggerCallback) {
p.triggerCallback(phaseName);
}
}
}
function deleteOrUnsetInMap(map, key, value) {
let currentValues;
if (map instanceof Map) {
currentValues = map.get(key);
if (currentValues) {
if (currentValues.length) {
const index = currentValues.indexOf(value);
currentValues.splice(index, 1);
}
if (currentValues.length == 0) {
map.delete(key);
}
}
}
else {
currentValues = map[key];
if (currentValues) {
if (currentValues.length) {
const index = currentValues.indexOf(value);
currentValues.splice(index, 1);
}
if (currentValues.length == 0) {
delete map[key];
}
}
}
return currentValues;
}
function normalizeTriggerValue(value) {
// we use `!= null` here because it's the most simple
// way to test against a "falsy" value without mixing
// in empty strings or a zero value. DO NOT OPTIMIZE.
return value != null ? value : null;
}
function isElementNode(node) {
return node && node['nodeType'] === 1;
}
function isTriggerEventValid(eventName) {
return eventName == 'start' || eventName == 'done';
}
function cloakElement(element, value) {
const oldValue = element.style.display;
element.style.display = value != null ? value : 'none';
return oldValue;
}
function cloakAndComputeStyles(valuesMap, driver, elements, elementPropsMap, defaultStyle) {
const cloakVals = [];
elements.forEach(element => cloakVals.push(cloakElement(element)));
const failedElements = [];
elementPropsMap.forEach((props, element) => {
const styles = {};
props.forEach(prop => {
const value = styles[prop] = driver.computeStyle(element, prop, defaultStyle);
// there is no easy way to detect this because a sub element could be removed
// by a parent animation element being detached.
if (!value || value.length == 0) {
element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE;
failedElements.push(element);
}
});
valuesMap.set(element, styles);
});
// we use a index variable here since Set.forEach(a, i) does not return
// an index value for the closure (but instead just the value)
let i = 0;
elements.forEach(element => cloakElement(element, cloakVals[i++]));
return failedElements;
}
/*
Since the Angular renderer code will return a collection of inserted
nodes in all areas of a DOM tree, it's up to this algorithm to figure
out which nodes are roots for each animation @trigger.
By placing each inserted node into a Set and traversing upwards, it
is possible to find the @trigger elements and well any direct *star
insertion nodes, if a @trigger root is found then the enter element
is placed into the Map[@trigger] spot.
*/
function buildRootMap(roots, nodes) {
const rootMap = new Map();
roots.forEach(root => rootMap.set(root, []));
if (nodes.length == 0)
return rootMap;
const NULL_NODE = 1;
const nodeSet = new Set(nodes);
const localRootMap = new Map();
function getRoot(node) {
if (!node)
return NULL_NODE;
let root = localRootMap.get(node);
if (root)
return root;
const parent = node.parentNode;
if (rootMap.has(parent)) { // ngIf inside @trigger
root = parent;
}
else if (nodeSet.has(parent)) { // ngIf inside ngIf
root = NULL_NODE;
}
else { // recurse upwards
root = getRoot(parent);
}
localRootMap.set(node, root);
return root;
}
nodes.forEach(node => {
const root = getRoot(node);
if (root !== NULL_NODE) {
rootMap.get(root).push(node);
}
});
return rootMap;
}
const CLASSES_CACHE_KEY = '$$classes';
function containsClass(element, className) {
if (element.classList) {
return element.classList.contains(className);
}
else {
const classes = element[CLASSES_CACHE_KEY];
return classes && classes[className];
}
}
function addClass(element, className) {
if (element.classList) {
element.classList.add(className);
}
else {
let classes = element[CLASSES_CACHE_KEY];
if (!classes) {
classes = element[CLASSES_CACHE_KEY] = {};
}
classes[className] = true;
}
}
function removeClass(element, className) {
if (element.classList) {
element.classList.remove(className);
}
else {
let classes = element[CLASSES_CACHE_KEY];
if (classes) {
delete classes[className];
}
}
}
function removeNodesAfterAnimationDone(engine, element, players) {
optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));
}
function flattenGroupPlayers(players) {
const finalPlayers = [];
_flattenGroupPlayersRecur(players, finalPlayers);
return finalPlayers;
}
function _flattenGroupPlayersRecur(players, finalPlayers) {
for (let i = 0; i < players.length; i++) {
const player = players[i];
if (player instanceof ɵAnimationGroupPlayer) {
_flattenGroupPlayersRecur(player.players, finalPlayers);
}
else {
finalPlayers.push(player);
}
}
}
function objEquals(a, b) {
const k1 = Object.keys(a);
const k2 = Object.keys(b);
if (k1.length != k2.length)
return false;
for (let i = 0; i < k1.length; i++) {
const prop = k1[i];
if (!b.hasOwnProperty(prop) || a[prop] !== b[prop])
return false;
}
return true;
}
function replacePostStylesAsPre(element, allPreStyleElements, allPostStyleElements) {
const postEntry = allPostStyleElements.get(element);
if (!postEntry)
return false;
let preEntry = allPreStyleElements.get(element);
if (preEntry) {
postEntry.forEach(data => preEntry.add(data));
}
else {
allPreStyleElements.set(element, postEntry);
}
allPostStyleElements.delete(element);
return true;
}
class AnimationEngine {
constructor(bodyNode, _driver, _normalizer) {
this.bodyNode = bodyNode;
this._driver = _driver;
this._normalizer = _normalizer;
this._triggerCache = {};
// this method is designed to be overridden by the code that uses this engine
this.onRemovalComplete = (element, context) => { };
this._transitionEngine = new TransitionAnimationEngine(bodyNode, _driver, _normalizer);
this._timelineEngine = new TimelineAnimationEngine(bodyNode, _driver, _normalizer);
this._transitionEngine.onRemovalComplete = (element, context) => this.onRemovalComplete(element, context);
}
registerTrigger(componentId, namespaceId, hostElement, name, metadata) {
const cacheKey = componentId + '-' + name;
let trigger = this._triggerCache[cacheKey];
if (!trigger) {
const errors = [];
const ast = buildAnimationAst(this._driver, metadata, errors);
if (errors.length) {
throw new Error(`The animation trigger "${name}" has failed to build due to the following errors:\n - ${errors.join('\n - ')}`);
}
trigger = buildTrigger(name, ast, this._normalizer);
this._triggerCache[cacheKey] = trigger;
}
this._transitionEngine.registerTrigger(namespaceId, name, trigger);
}
register(namespaceId, hostElement) {
this._transitionEngine.register(namespaceId, hostElement);
}
destroy(namespaceId, context) {
this._transitionEngine.destroy(namespaceId, context);
}
onInsert(namespaceId, element, parent, insertBefore) {
this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);
}
onRemove(namespaceId, element, context, isHostElement) {
this._transitionEngine.removeNode(namespaceId, element, isHostElement || false, context);
}
disableAnimations(element, disable) {
this._transitionEngine.markElementAsDisabled(element, disable);
}
process(namespaceId, element, property, value) {
if (property.charAt(0) == '@') {
const [id, action] = parseTimelineCommand(property);
const args = value;
this._timelineEngine.command(id, element, action, args);
}
else {
this._transitionEngine.trigger(namespaceId, element, property, value);
}
}
listen(namespaceId, element, eventName, eventPhase, callback) {
// @@listen
if (eventName.charAt(0) == '@') {
const [id, action] = parseTimelineCommand(eventName);
return this._timelineEngine.listen(id, element, action, callback);
}
return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);
}
flush(microtaskId = -1) {
this._transitionEngine.flush(microtaskId);
}
get players() {
return this._transitionEngine.players
.concat(this._timelineEngine.players);
}
whenRenderingDone() {
return this._transitionEngine.whenRenderingDone();
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Returns an instance of `SpecialCasedStyles` if and when any special (non animateable) styles are
* detected.
*
* In CSS there exist properties that cannot be animated within a keyframe animation
* (whether it be via CSS keyframes or web-animations) and the animation implementation
* will ignore them. This function is designed to detect those special cased styles and
* return a container that will be executed at the start and end of the animation.
*
* @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null`
*/
function packageNonAnimatableStyles(element, styles) {
let startStyles = null;
let endStyles = null;
if (Array.isArray(styles) && styles.length) {
startStyles = filterNonAnimatableStyles(styles[0]);
if (styles.length > 1) {
endStyles = filterNonAnimatableStyles(styles[styles.length - 1]);
}
}
else if (styles) {
startStyles = filterNonAnimatableStyles(styles);
}
return (startStyles || endStyles) ? new SpecialCasedStyles(element, startStyles, endStyles) :
null;
}
/**
* Designed to be executed during a keyframe-based animation to apply any special-cased styles.
*
* When started (when the `start()` method is run) then the provided `startStyles`
* will be applied. When finished (when the `finish()` method is called) the
* `endStyles` will be applied as well any any starting styles. Finally when
* `destroy()` is called then all styles will be removed.
*/
class SpecialCasedStyles {
constructor(_element, _startStyles, _endStyles) {
this._element = _element;
this._startStyles = _startStyles;
this._endStyles = _endStyles;
this._state = 0 /* Pending */;
let initialStyles = SpecialCasedStyles.initialStylesByElement.get(_element);
if (!initialStyles) {
SpecialCasedStyles.initialStylesByElement.set(_element, initialStyles = {});
}
this._initialStyles = initialStyles;
}
start() {
if (this._state < 1 /* Started */) {
if (this._startStyles) {
setStyles(this._element, this._startStyles, this._initialStyles);
}
this._state = 1 /* Started */;
}
}
finish() {
this.start();
if (this._state < 2 /* Finished */) {
setStyles(this._element, this._initialStyles);
if (this._endStyles) {
setStyles(this._element, this._endStyles);
this._endStyles = null;
}
this._state = 1 /* Started */;
}
}
destroy() {
this.finish();
if (this._state < 3 /* Destroyed */) {
SpecialCasedStyles.initialStylesByElement.delete(this._element);
if (this._startStyles) {
eraseStyles(this._element, this._startStyles);
this._endStyles = null;
}
if (this._endStyles) {
eraseStyles(this._element, this._endStyles);
this._endStyles = null;
}
setStyles(this._element, this._initialStyles);
this._state = 3 /* Destroyed */;
}
}
}
SpecialCasedStyles.initialStylesByElement = ( /* @__PURE__ */new WeakMap());
function filterNonAnimatableStyles(styles) {
let result = null;
const props = Object.keys(styles);
for (let i = 0; i < props.length; i++) {
const prop = props[i];
if (isNonAnimatableStyle(prop)) {
result = result || {};
result[prop] = styles[prop];
}
}
return result;
}
function isNonAnimatableStyle(prop) {
return prop === 'display' || prop === 'position';
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
const ANIMATION_PROP = 'animation';
const ANIMATIONEND_EVENT = 'animationend';
const ONE_SECOND$1 = 1000;
class ElementAnimationStyleHandler {
constructor(_element, _name, _duration, _delay, _easing, _fillMode, _onDoneFn) {
this._element = _element;
this._name = _name;
this._duration = _duration;
this._delay = _delay;
this._easing = _easing;
this._fillMode = _fillMode;
this._onDoneFn = _onDoneFn;
this._finished = false;
this._destroyed = false;
this._startTime = 0;
this._position = 0;
this._eventFn = (e) => this._handleCallback(e);
}
apply() {
applyKeyframeAnimation(this._element, `${this._duration}ms ${this._easing} ${this._delay}ms 1 normal ${this._fillMode} ${this._name}`);
addRemoveAnimationEvent(this._element, this._eventFn, false);
this._startTime = Date.now();
}
pause() {
playPauseAnimation(this._element, this._name, 'paused');
}
resume() {
playPauseAnimation(this._element, this._name, 'running');
}
setPosition(position) {
const index = findIndexForAnimation(this._element, this._name);
this._position = position * this._duration;
setAnimationStyle(this._element, 'Delay', `-${this._position}ms`, index);
}
getPosition() {
return this._position;
}
_handleCallback(event) {
const timestamp = event._ngTestManualTimestamp || Date.now();
const elapsedTime = parseFloat(event.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES)) * ONE_SECOND$1;
if (event.animationName == this._name &&
Math.max(timestamp - this._startTime, 0) >= this._delay && elapsedTime >= this._duration) {
this.finish();
}
}
finish() {
if (this._finished)
return;
this._finished = true;
this._onDoneFn();
addRemoveAnimationEvent(this._element, this._eventFn, true);
}
destroy() {
if (this._destroyed)
return;
this._destroyed = true;
this.finish();
removeKeyframeAnimation(this._element, this._name);
}
}
function playPauseAnimation(element, name, status) {
const index = findIndexForAnimation(element, name);
setAnimationStyle(element, 'PlayState', status, index);
}
function applyKeyframeAnimation(element, value) {
const anim = getAnimationStyle(element, '').trim();
let index = 0;
if (anim.length) {
index = countChars(anim, ',') + 1;
value = `${anim}, ${value}`;
}
setAnimationStyle(element, '', value);
return index;
}
function removeKeyframeAnimation(element, name) {
const anim = getAnimationStyle(element, '');
const tokens = anim.split(',');
const index = findMatchingTokenIndex(tokens, name);
if (index >= 0) {
tokens.splice(index, 1);
const newValue = tokens.join(',');
setAnimationStyle(element, '', newValue);
}
}
function findIndexForAnimation(element, value) {
const anim = getAnimationStyle(element, '');
if (anim.indexOf(',') > 0) {
const tokens = anim.split(',');
return findMatchingTokenIndex(tokens, value);
}
return findMatchingTokenIndex([anim], value);
}
function findMatchingTokenIndex(tokens, searchToken) {
for (let i = 0; i < tokens.length; i++) {
if (tokens[i].indexOf(searchToken) >= 0) {
return i;
}
}
return -1;
}
function addRemoveAnimationEvent(element, fn, doRemove) {
doRemove ? element.removeEventListener(ANIMATIONEND_EVENT, fn) :
element.addEventListener(ANIMATIONEND_EVENT, fn);
}
function setAnimationStyle(element, name, value, index) {
const prop = ANIMATION_PROP + name;
if (index != null) {
const oldValue = element.style[prop];
if (oldValue.length) {
const tokens = oldValue.split(',');
tokens[index] = value;
value = tokens.join(',');
}
}
element.style[prop] = value;
}
function getAnimationStyle(element, name) {
return element.style[ANIMATION_PROP + name] || '';
}
function countChars(value, char) {
let count = 0;
for (let i = 0; i < value.length; i++) {
const c = value.charAt(i);
if (c === char)
count++;
}
return count;
}
const DEFAULT_FILL_MODE = 'forwards';
const DEFAULT_EASING = 'linear';
class CssKeyframesPlayer {
constructor(element, keyframes, animationName, _duration, _delay, easing, _finalStyles, _specialStyles) {
this.element = element;
this.keyframes = keyframes;
this.animationName = animationName;
this._duration = _duration;
this._delay = _delay;
this._finalStyles = _finalStyles;
this._specialStyles = _specialStyles;
this._onDoneFns = [];
this._onStartFns = [];
this._onDestroyFns = [];
this.currentSnapshot = {};
this._state = 0;
this.easing = easing || DEFAULT_EASING;
this.totalTime = _duration + _delay;
this._buildStyler();
}
onStart(fn) {
this._onStartFns.push(fn);
}
onDone(fn) {
this._onDoneFns.push(fn);
}
onDestroy(fn) {
this._onDestroyFns.push(fn);
}
destroy() {
this.init();
if (this._state >= 4 /* DESTROYED */)
return;
this._state = 4 /* DESTROYED */;
this._styler.destroy();
this._flushStartFns();
this._flushDoneFns();
if (this._specialStyles) {
this._specialStyles.destroy();
}
this._onDestroyFns.forEach(fn => fn());
this._onDestroyFns = [];
}
_flushDoneFns() {
this._onDoneFns.forEach(fn => fn());
this._onDoneFns = [];
}
_flushStartFns() {
this._onStartFns.forEach(fn => fn());
this._onStartFns = [];
}
finish() {
this.init();
if (this._state >= 3 /* FINISHED */)
return;
this._state = 3 /* FINISHED */;
this._styler.finish();
this._flushStartFns();
if (this._specialStyles) {
this._specialStyles.finish();
}
this._flushDoneFns();
}
setPosition(value) {
this._styler.setPosition(value);
}
getPosition() {
return this._styler.getPosition();
}
hasStarted() {
return this._state >= 2 /* STARTED */;
}
init() {
if (this._state >= 1 /* INITIALIZED */)
return;
this._state = 1 /* INITIALIZED */;
const elm = this.element;
this._styler.apply();
if (this._delay) {
this._styler.pause();
}
}
play() {
this.init();
if (!this.hasStarted()) {
this._flushStartFns();
this._state = 2 /* STARTED */;
if (this._specialStyles) {
this._specialStyles.start();
}
}
this._styler.resume();
}
pause() {
this.init();
this._styler.pause();
}
restart() {
this.reset();
this.play();
}
reset() {
this._state = 0 /* RESET */;
this._styler.destroy();
this._buildStyler();
this._styler.apply();
}
_buildStyler() {
this._styler = new ElementAnimationStyleHandler(this.element, this.animationName, this._duration, this._delay, this.easing, DEFAULT_FILL_MODE, () => this.finish());
}
/** @internal */
triggerCallback(phaseName) {
const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns;
methods.forEach(fn => fn());
methods.length = 0;
}
beforeDestroy() {
this.init();
const styles = {};
if (this.hasStarted()) {
const finished = this._state >= 3 /* FINISHED */;
Object.keys(this._finalStyles).forEach(prop => {
if (prop != 'offset') {
styles[prop] = finished ? this._finalStyles[prop] : computeStyle(this.element, prop);
}
});
}
this.currentSnapshot = styles;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class DirectStylePlayer extends NoopAnimationPlayer {
constructor(element, styles) {
super();
this.element = element;
this._startingStyles = {};
this.__initialized = false;
this._styles = hypenatePropsObject(styles);
}
init() {
if (this.__initialized || !this._startingStyles)
return;
this.__initialized = true;
Object.keys(this._styles).forEach(prop => {
this._startingStyles[prop] = this.element.style[prop];
});
super.init();
}
play() {
if (!this._startingStyles)
return;
this.init();
Object.keys(this._styles)
.forEach(prop => this.element.style.setProperty(prop, this._styles[prop]));
super.play();
}
destroy() {
if (!this._startingStyles)
return;
Object.keys(this._startingStyles).forEach(prop => {
const value = this._startingStyles[prop];
if (value) {
this.element.style.setProperty(prop, value);
}
else {
this.element.style.removeProperty(prop);
}
});
this._startingStyles = null;
super.destroy();
}
}
const KEYFRAMES_NAME_PREFIX = 'gen_css_kf_';
const TAB_SPACE = ' ';
class CssKeyframesDriver {
constructor() {
this._count = 0;
}
validateStyleProperty(prop) {
return validateStyleProperty(prop);
}
matchesElement(element, selector) {
return matchesElement(element, selector);
}
containsElement(elm1, elm2) {
return containsElement(elm1, elm2);
}
query(element, selector, multi) {
return invokeQuery(element, selector, multi);
}
computeStyle(element, prop, defaultValue) {
return window.getComputedStyle(element)[prop];
}
buildKeyframeElement(element, name, keyframes) {
keyframes = keyframes.map(kf => hypenatePropsObject(kf));
let keyframeStr = `@keyframes ${name} {\n`;
let tab = '';
keyframes.forEach(kf => {
tab = TAB_SPACE;
const offset = parseFloat(kf['offset']);
keyframeStr += `${tab}${offset * 100}% {\n`;
tab += TAB_SPACE;
Object.keys(kf).forEach(prop => {
const value = kf[prop];
switch (prop) {
case 'offset':
return;
case 'easing':
if (value) {
keyframeStr += `${tab}animation-timing-function: ${value};\n`;
}
return;
default:
keyframeStr += `${tab}${prop}: ${value};\n`;
return;
}
});
keyframeStr += `${tab}}\n`;
});
keyframeStr += `}\n`;
const kfElm = document.createElement('style');
kfElm.textContent = keyframeStr;
return kfElm;
}
animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && scrubberAccessRequested) {
notifyFaultyScrubber();
}
const previousCssKeyframePlayers = previousPlayers.filter(player => player instanceof CssKeyframesPlayer);
const previousStyles = {};
if (allowPreviousPlayerStylesMerge(duration, delay)) {
previousCssKeyframePlayers.forEach(player => {
let styles = player.currentSnapshot;
Object.keys(styles).forEach(prop => previousStyles[prop] = styles[prop]);
});
}
keyframes = balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles);
const finalStyles = flattenKeyframesIntoStyles(keyframes);
// if there is no animation then there is no point in applying
// styles and waiting for an event to get fired. This causes lag.
// It's better to just directly apply the styles to the element
// via the direct styling animation player.
if (duration == 0) {
return new DirectStylePlayer(element, finalStyles);
}
const animationName = `${KEYFRAMES_NAME_PREFIX}${this._count++}`;
const kfElm = this.buildKeyframeElement(element, animationName, keyframes);
const nodeToAppendKfElm = findNodeToAppendKeyframeElement(element);
nodeToAppendKfElm.appendChild(kfElm);
const specialStyles = packageNonAnimatableStyles(element, keyframes);
const player = new CssKeyframesPlayer(element, keyframes, animationName, duration, delay, easing, finalStyles, specialStyles);
player.onDestroy(() => removeElement(kfElm));
return player;
}
}
function findNodeToAppendKeyframeElement(element) {
var _a;
const rootNode = (_a = element.getRootNode) === null || _a === void 0 ? void 0 : _a.call(element);
if (typeof ShadowRoot !== 'undefined' && rootNode instanceof ShadowRoot) {
return rootNode;
}
return document.head;
}
function flattenKeyframesIntoStyles(keyframes) {
let flatKeyframes = {};
if (keyframes) {
const kfs = Array.isArray(keyframes) ? keyframes : [keyframes];
kfs.forEach(kf => {
Object.keys(kf).forEach(prop => {
if (prop == 'offset' || prop == 'easing')
return;
flatKeyframes[prop] = kf[prop];
});
});
}
return flatKeyframes;
}
function removeElement(node) {
node.parentNode.removeChild(node);
}
let warningIssued = false;
function notifyFaultyScrubber() {
if (warningIssued)
return;
console.warn('@angular/animations: please load the web-animations.js polyfill to allow programmatic access...\n', ' visit https://bit.ly/IWukam to learn more about using the web-animation-js polyfill.');
warningIssued = true;
}
class WebAnimationsPlayer {
constructor(element, keyframes, options, _specialStyles) {
this.element = element;
this.keyframes = keyframes;
this.options = options;
this._specialStyles = _specialStyles;
this._onDoneFns = [];
this._onStartFns = [];
this._onDestroyFns = [];
this._initialized = false;
this._finished = false;
this._started = false;
this._destroyed = false;
this.time = 0;
this.parentPlayer = null;
this.currentSnapshot = {};
this._duration = options['duration'];
this._delay = options['delay'] || 0;
this.time = this._duration + this._delay;
}
_onFinish() {
if (!this._finished) {
this._finished = true;
this._onDoneFns.forEach(fn => fn());
this._onDoneFns = [];
}
}
init() {
this._buildPlayer();
this._preparePlayerBeforeStart();
}
_buildPlayer() {
if (this._initialized)
return;
this._initialized = true;
const keyframes = this.keyframes;
this.domPlayer =
this._triggerWebAnimation(this.element, keyframes, this.options);
this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : {};
this.domPlayer.addEventListener('finish', () => this._onFinish());
}
_preparePlayerBeforeStart() {
// this is required so that the player doesn't start to animate right away
if (this._delay) {
this._resetDomPlayerState();
}
else {
this.domPlayer.pause();
}
}
/** @internal */
_triggerWebAnimation(element, keyframes, options) {
// jscompiler doesn't seem to know animate is a native property because it's not fully
// supported yet across common browsers (we polyfill it for Edge/Safari) [CL #143630929]
return element['animate'](keyframes, options);
}
onStart(fn) {
this._onStartFns.push(fn);
}
onDone(fn) {
this._onDoneFns.push(fn);
}
onDestroy(fn) {
this._onDestroyFns.push(fn);
}
play() {
this._buildPlayer();
if (!this.hasStarted()) {
this._onStartFns.forEach(fn => fn());
this._onStartFns = [];
this._started = true;
if (this._specialStyles) {
this._specialStyles.start();
}
}
this.domPlayer.play();
}
pause() {
this.init();
this.domPlayer.pause();
}
finish() {
this.init();
if (this._specialStyles) {
this._specialStyles.finish();
}
this._onFinish();
this.domPlayer.finish();
}
reset() {
this._resetDomPlayerState();
this._destroyed = false;
this._finished = false;
this._started = false;
}
_resetDomPlayerState() {
if (this.domPlayer) {
this.domPlayer.cancel();
}
}
restart() {
this.reset();
this.play();
}
hasStarted() {
return this._started;
}
destroy() {
if (!this._destroyed) {
this._destroyed = true;
this._resetDomPlayerState();
this._onFinish();
if (this._specialStyles) {
this._specialStyles.destroy();
}
this._onDestroyFns.forEach(fn => fn());
this._onDestroyFns = [];
}
}
setPosition(p) {
if (this.domPlayer === undefined) {
this.init();
}
this.domPlayer.currentTime = p * this.time;
}
getPosition() {
return this.domPlayer.currentTime / this.time;
}
get totalTime() {
return this._delay + this._duration;
}
beforeDestroy() {
const styles = {};
if (this.hasStarted()) {
Object.keys(this._finalKeyframe).forEach(prop => {
if (prop != 'offset') {
styles[prop] =
this._finished ? this._finalKeyframe[prop] : computeStyle(this.element, prop);
}
});
}
this.currentSnapshot = styles;
}
/** @internal */
triggerCallback(phaseName) {
const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns;
methods.forEach(fn => fn());
methods.length = 0;
}
}
class WebAnimationsDriver {
constructor() {
this._isNativeImpl = /\{\s*\[native\s+code\]\s*\}/.test(getElementAnimateFn().toString());
this._cssKeyframesDriver = new CssKeyframesDriver();
}
validateStyleProperty(prop) {
return validateStyleProperty(prop);
}
matchesElement(element, selector) {
return matchesElement(element, selector);
}
containsElement(elm1, elm2) {
return containsElement(elm1, elm2);
}
query(element, selector, multi) {
return invokeQuery(element, selector, multi);
}
computeStyle(element, prop, defaultValue) {
return window.getComputedStyle(element)[prop];
}
overrideWebAnimationsSupport(supported) {
this._isNativeImpl = supported;
}
animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {
const useKeyframes = !scrubberAccessRequested && !this._isNativeImpl;
if (useKeyframes) {
return this._cssKeyframesDriver.animate(element, keyframes, duration, delay, easing, previousPlayers);
}
const fill = delay == 0 ? 'both' : 'forwards';
const playerOptions = { duration, delay, fill };
// we check for this to avoid having a null|undefined value be present
// for the easing (which results in an error for certain browsers #9752)
if (easing) {
playerOptions['easing'] = easing;
}
const previousStyles = {};
const previousWebAnimationPlayers = previousPlayers.filter(player => player instanceof WebAnimationsPlayer);
if (allowPreviousPlayerStylesMerge(duration, delay)) {
previousWebAnimationPlayers.forEach(player => {
let styles = player.currentSnapshot;
Object.keys(styles).forEach(prop => previousStyles[prop] = styles[prop]);
});
}
keyframes = keyframes.map(styles => copyStyles(styles, false));
keyframes = balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles);
const specialStyles = packageNonAnimatableStyles(element, keyframes);
return new WebAnimationsPlayer(element, keyframes, playerOptions, specialStyles);
}
}
function supportsWebAnimations() {
return typeof getElementAnimateFn() === 'function';
}
function getElementAnimateFn() {
return (isBrowser() && Element.prototype['animate']) || {};
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Generated bundle index. Do not edit.
*/
export { AnimationDriver, Animation as ɵAnimation, AnimationEngine as ɵAnimationEngine, AnimationStyleNormalizer as ɵAnimationStyleNormalizer, CssKeyframesDriver as ɵCssKeyframesDriver, CssKeyframesPlayer as ɵCssKeyframesPlayer, NoopAnimationDriver as ɵNoopAnimationDriver, NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer, WebAnimationsDriver as ɵWebAnimationsDriver, WebAnimationsPlayer as ɵWebAnimationsPlayer, WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer, allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge, SpecialCasedStyles as ɵangular_packages_animations_browser_browser_a, containsElement as ɵcontainsElement, invokeQuery as ɵinvokeQuery, matchesElement as ɵmatchesElement, supportsWebAnimations as ɵsupportsWebAnimations, validateStyleProperty as ɵvalidateStyleProperty };
//# sourceMappingURL=browser.js.map
|
/* ------------------------------------------------------------------------- *
* Copyright 2002-2021, OpenNebula Project, OpenNebula Systems *
* *
* 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 VmTemplatesTable, { STEP_ID as TEMPLATE_ID } from 'client/components/Forms/VmTemplate/InstantiateForm/Steps/VmTemplatesTable'
import BasicConfiguration, { STEP_ID as BASIC_ID } from 'client/components/Forms/VmTemplate/InstantiateForm/Steps/BasicConfiguration'
import ExtraConfiguration, { STEP_ID as EXTRA_ID } from 'client/components/Forms/VmTemplate/InstantiateForm/Steps/ExtraConfiguration'
import { jsonToXml } from 'client/models/Helper'
import { createSteps } from 'client/utils'
const Steps = createSteps(
vmTemplate => [
!vmTemplate?.ID && VmTemplatesTable,
BasicConfiguration,
ExtraConfiguration
].filter(Boolean),
{
transformInitialValue: (vmTemplate, schema) => ({
...schema.cast({
[TEMPLATE_ID]: [vmTemplate],
[BASIC_ID]: vmTemplate?.TEMPLATE,
[EXTRA_ID]: vmTemplate?.TEMPLATE
}, { stripUnknown: true })
}),
transformBeforeSubmit: formData => {
const {
[TEMPLATE_ID]: [templateSelected] = [],
[BASIC_ID]: { name, instances, hold, persistent, ...restOfConfig } = {},
[EXTRA_ID]: extraTemplate = {}
} = formData ?? {}
// merge with template disks to get TYPE attribute
const templateXML = jsonToXml({ ...extraTemplate, ...restOfConfig })
const data = { instances, hold, persistent, template: templateXML }
const templates = [...new Array(instances)]
.map((_, idx) => ({ name: name?.replace(/%idx/gi, idx), ...data }))
return [templateSelected, templates]
}
}
)
export default Steps
|
const React = require('react')
const ampHtmlValidator = require('amphtml-validator')
const Application = require('./Application')
const ampReactRenderer = require('../../../dist/AmpHtmlRenderer.js')
test('render a valid AMP page with amp-soundcloud component', async () => {
// arrangement
const AppComponent = <Application />
const title = 'case - amp-soundcloud'
const canonical = 'https://amp-soundcloud.test.com.tw'
const headComponents = [<meta key='test' name='format-detection' content='telephone=no' />]
// action
const htmlString = ampReactRenderer({
entryName: 'amp-soundcloud',
AppComponent,
title,
canonical,
headComponents
})
// assertion
expect.assertions(2)
expect(htmlString).toMatchSnapshot()
const validator = await ampHtmlValidator.getInstance()
const result = validator.validateString(htmlString)
console.log('amp validation result: ', result)
expect(result.status).toEqual('PASS')
})
|
export default {
props: {
myClass: 'one two',
attributes: {
role: 'button'
}
},
html: '<div class="one two three" role="button"></div>',
test({ assert, component, target, window }) {
component.myClass = 'one';
component.attributes = {
'aria-label': 'Test'
};
assert.htmlEqual(target.innerHTML, `
<div class="one three" aria-label="Test"></div>
`);
}
};
|
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var api_error_1 = require('./api_error');
var file_flag_1 = require('./file_flag');
var path = require('path');
/**
* Basic filesystem class. Most filesystems should extend this class, as it
* provides default implementations for a handful of methods.
*/
var BaseFileSystem = (function () {
function BaseFileSystem() {
}
BaseFileSystem.prototype.supportsLinks = function () {
return false;
};
BaseFileSystem.prototype.diskSpace = function (p, cb) {
cb(0, 0);
};
/**
* Opens the file at path p with the given flag. The file must exist.
* @param p The path to open.
* @param flag The flag to use when opening the file.
*/
BaseFileSystem.prototype.openFile = function (p, flag, cb) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
/**
* Create the file at path p with the given mode. Then, open it with the given
* flag.
*/
BaseFileSystem.prototype.createFile = function (p, flag, mode, cb) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.open = function (p, flag, mode, cb) {
var _this = this;
var mustBeFile = function (e, stats) {
if (e) {
// File does not exist.
switch (flag.pathNotExistsAction()) {
case file_flag_1.ActionType.CREATE_FILE:
// Ensure parent exists.
return _this.stat(path.dirname(p), false, function (e, parentStats) {
if (e) {
cb(e);
}
else if (!parentStats.isDirectory()) {
cb(api_error_1.ApiError.ENOTDIR(path.dirname(p)));
}
else {
_this.createFile(p, flag, mode, cb);
}
});
case file_flag_1.ActionType.THROW_EXCEPTION:
return cb(api_error_1.ApiError.ENOENT(p));
default:
return cb(new api_error_1.ApiError(api_error_1.ErrorCode.EINVAL, 'Invalid FileFlag object.'));
}
}
else {
// File exists.
if (stats.isDirectory()) {
return cb(api_error_1.ApiError.EISDIR(p));
}
switch (flag.pathExistsAction()) {
case file_flag_1.ActionType.THROW_EXCEPTION:
return cb(api_error_1.ApiError.EEXIST(p));
case file_flag_1.ActionType.TRUNCATE_FILE:
// NOTE: In a previous implementation, we deleted the file and
// re-created it. However, this created a race condition if another
// asynchronous request was trying to read the file, as the file
// would not exist for a small period of time.
return _this.openFile(p, flag, function (e, fd) {
if (e) {
cb(e);
}
else {
fd.truncate(0, function () {
fd.sync(function () {
cb(null, fd);
});
});
}
});
case file_flag_1.ActionType.NOP:
return _this.openFile(p, flag, cb);
default:
return cb(new api_error_1.ApiError(api_error_1.ErrorCode.EINVAL, 'Invalid FileFlag object.'));
}
}
};
this.stat(p, false, mustBeFile);
};
BaseFileSystem.prototype.rename = function (oldPath, newPath, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.renameSync = function (oldPath, newPath) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.stat = function (p, isLstat, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.statSync = function (p, isLstat) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
/**
* Opens the file at path p with the given flag. The file must exist.
* @param p The path to open.
* @param flag The flag to use when opening the file.
* @return A File object corresponding to the opened file.
*/
BaseFileSystem.prototype.openFileSync = function (p, flag, mode) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
/**
* Create the file at path p with the given mode. Then, open it with the given
* flag.
*/
BaseFileSystem.prototype.createFileSync = function (p, flag, mode) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.openSync = function (p, flag, mode) {
// Check if the path exists, and is a file.
var stats;
try {
stats = this.statSync(p, false);
}
catch (e) {
// File does not exist.
switch (flag.pathNotExistsAction()) {
case file_flag_1.ActionType.CREATE_FILE:
// Ensure parent exists.
var parentStats = this.statSync(path.dirname(p), false);
if (!parentStats.isDirectory()) {
throw api_error_1.ApiError.ENOTDIR(path.dirname(p));
}
return this.createFileSync(p, flag, mode);
case file_flag_1.ActionType.THROW_EXCEPTION:
throw api_error_1.ApiError.ENOENT(p);
default:
throw new api_error_1.ApiError(api_error_1.ErrorCode.EINVAL, 'Invalid FileFlag object.');
}
}
// File exists.
if (stats.isDirectory()) {
throw api_error_1.ApiError.EISDIR(p);
}
switch (flag.pathExistsAction()) {
case file_flag_1.ActionType.THROW_EXCEPTION:
throw api_error_1.ApiError.EEXIST(p);
case file_flag_1.ActionType.TRUNCATE_FILE:
// Delete file.
this.unlinkSync(p);
// Create file. Use the same mode as the old file.
// Node itself modifies the ctime when this occurs, so this action
// will preserve that behavior if the underlying file system
// supports those properties.
return this.createFileSync(p, flag, stats.mode);
case file_flag_1.ActionType.NOP:
return this.openFileSync(p, flag, mode);
default:
throw new api_error_1.ApiError(api_error_1.ErrorCode.EINVAL, 'Invalid FileFlag object.');
}
};
BaseFileSystem.prototype.unlink = function (p, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.unlinkSync = function (p) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.rmdir = function (p, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.rmdirSync = function (p) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.mkdir = function (p, mode, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.mkdirSync = function (p, mode) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.readdir = function (p, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.readdirSync = function (p) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.exists = function (p, cb) {
this.stat(p, null, function (err) {
cb(!err);
});
};
BaseFileSystem.prototype.existsSync = function (p) {
try {
this.statSync(p, true);
return true;
}
catch (e) {
return false;
}
};
BaseFileSystem.prototype.realpath = function (p, cache, cb) {
if (this.supportsLinks()) {
// The path could contain symlinks. Split up the path,
// resolve any symlinks, return the resolved string.
var splitPath = p.split(path.sep);
// TODO: Simpler to just pass through file, find sep and such.
for (var i = 0; i < splitPath.length; i++) {
var addPaths = splitPath.slice(0, i + 1);
splitPath[i] = path.join.apply(null, addPaths);
}
}
else {
// No symlinks. We just need to verify that it exists.
this.exists(p, function (doesExist) {
if (doesExist) {
cb(null, p);
}
else {
cb(api_error_1.ApiError.ENOENT(p));
}
});
}
};
BaseFileSystem.prototype.realpathSync = function (p, cache) {
if (this.supportsLinks()) {
// The path could contain symlinks. Split up the path,
// resolve any symlinks, return the resolved string.
var splitPath = p.split(path.sep);
// TODO: Simpler to just pass through file, find sep and such.
for (var i = 0; i < splitPath.length; i++) {
var addPaths = splitPath.slice(0, i + 1);
splitPath[i] = path.join.apply(path, addPaths);
}
return splitPath.join(path.sep);
}
else {
// No symlinks. We just need to verify that it exists.
if (this.existsSync(p)) {
return p;
}
else {
throw api_error_1.ApiError.ENOENT(p);
}
}
};
BaseFileSystem.prototype.truncate = function (p, len, cb) {
this.open(p, file_flag_1.FileFlag.getFileFlag('r+'), 0x1a4, (function (er, fd) {
if (er) {
return cb(er);
}
fd.truncate(len, (function (er) {
fd.close((function (er2) {
cb(er || er2);
}));
}));
}));
};
BaseFileSystem.prototype.truncateSync = function (p, len) {
var fd = this.openSync(p, file_flag_1.FileFlag.getFileFlag('r+'), 0x1a4);
// Need to safely close FD, regardless of whether or not truncate succeeds.
try {
fd.truncateSync(len);
}
catch (e) {
throw e;
}
finally {
fd.closeSync();
}
};
BaseFileSystem.prototype.readFile = function (fname, encoding, flag, cb) {
// Wrap cb in file closing code.
var oldCb = cb;
// Get file.
this.open(fname, flag, 0x1a4, function (err, fd) {
if (err) {
return cb(err);
}
cb = function (err, arg) {
fd.close(function (err2) {
if (!err) {
err = err2;
}
return oldCb(err, arg);
});
};
fd.stat(function (err, stat) {
if (err) {
return cb(err);
}
// Allocate buffer.
var buf = new Buffer(stat.size);
fd.read(buf, 0, stat.size, 0, function (err) {
if (err) {
return cb(err);
}
else if (encoding === null) {
return cb(err, buf);
}
try {
cb(null, buf.toString(encoding));
}
catch (e) {
cb(e);
}
});
});
});
};
BaseFileSystem.prototype.readFileSync = function (fname, encoding, flag) {
// Get file.
var fd = this.openSync(fname, flag, 0x1a4);
try {
var stat = fd.statSync();
// Allocate buffer.
var buf = new Buffer(stat.size);
fd.readSync(buf, 0, stat.size, 0);
fd.closeSync();
if (encoding === null) {
return buf;
}
return buf.toString(encoding);
}
finally {
fd.closeSync();
}
};
BaseFileSystem.prototype.writeFile = function (fname, data, encoding, flag, mode, cb) {
// Wrap cb in file closing code.
var oldCb = cb;
// Get file.
this.open(fname, flag, 0x1a4, function (err, fd) {
if (err) {
return cb(err);
}
cb = function (err) {
fd.close(function (err2) {
oldCb(err ? err : err2);
});
};
try {
if (typeof data === 'string') {
data = new Buffer(data, encoding);
}
}
catch (e) {
return cb(e);
}
// Write into file.
fd.write(data, 0, data.length, 0, cb);
});
};
BaseFileSystem.prototype.writeFileSync = function (fname, data, encoding, flag, mode) {
// Get file.
var fd = this.openSync(fname, flag, mode);
try {
if (typeof data === 'string') {
data = new Buffer(data, encoding);
}
// Write into file.
fd.writeSync(data, 0, data.length, 0);
}
finally {
fd.closeSync();
}
};
BaseFileSystem.prototype.appendFile = function (fname, data, encoding, flag, mode, cb) {
// Wrap cb in file closing code.
var oldCb = cb;
this.open(fname, flag, mode, function (err, fd) {
if (err) {
return cb(err);
}
cb = function (err) {
fd.close(function (err2) {
oldCb(err ? err : err2);
});
};
if (typeof data === 'string') {
data = new Buffer(data, encoding);
}
fd.write(data, 0, data.length, null, cb);
});
};
BaseFileSystem.prototype.appendFileSync = function (fname, data, encoding, flag, mode) {
var fd = this.openSync(fname, flag, mode);
try {
if (typeof data === 'string') {
data = new Buffer(data, encoding);
}
fd.writeSync(data, 0, data.length, null);
}
finally {
fd.closeSync();
}
};
BaseFileSystem.prototype.chmod = function (p, isLchmod, mode, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.chmodSync = function (p, isLchmod, mode) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.chown = function (p, isLchown, uid, gid, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.chownSync = function (p, isLchown, uid, gid) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.utimes = function (p, atime, mtime, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.utimesSync = function (p, atime, mtime) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.link = function (srcpath, dstpath, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.linkSync = function (srcpath, dstpath) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.symlink = function (srcpath, dstpath, type, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.symlinkSync = function (srcpath, dstpath, type) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
BaseFileSystem.prototype.readlink = function (p, cb) {
cb(new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP));
};
BaseFileSystem.prototype.readlinkSync = function (p) {
throw new api_error_1.ApiError(api_error_1.ErrorCode.ENOTSUP);
};
return BaseFileSystem;
}());
exports.BaseFileSystem = BaseFileSystem;
/**
* Implements the asynchronous API in terms of the synchronous API.
* @class SynchronousFileSystem
*/
var SynchronousFileSystem = (function (_super) {
__extends(SynchronousFileSystem, _super);
function SynchronousFileSystem() {
_super.apply(this, arguments);
}
SynchronousFileSystem.prototype.supportsSynch = function () {
return true;
};
SynchronousFileSystem.prototype.rename = function (oldPath, newPath, cb) {
try {
this.renameSync(oldPath, newPath);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.stat = function (p, isLstat, cb) {
try {
cb(null, this.statSync(p, isLstat));
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.open = function (p, flags, mode, cb) {
try {
cb(null, this.openSync(p, flags, mode));
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.unlink = function (p, cb) {
try {
this.unlinkSync(p);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.rmdir = function (p, cb) {
try {
this.rmdirSync(p);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.mkdir = function (p, mode, cb) {
try {
this.mkdirSync(p, mode);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.readdir = function (p, cb) {
try {
cb(null, this.readdirSync(p));
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.chmod = function (p, isLchmod, mode, cb) {
try {
this.chmodSync(p, isLchmod, mode);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.chown = function (p, isLchown, uid, gid, cb) {
try {
this.chownSync(p, isLchown, uid, gid);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.utimes = function (p, atime, mtime, cb) {
try {
this.utimesSync(p, atime, mtime);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.link = function (srcpath, dstpath, cb) {
try {
this.linkSync(srcpath, dstpath);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.symlink = function (srcpath, dstpath, type, cb) {
try {
this.symlinkSync(srcpath, dstpath, type);
cb();
}
catch (e) {
cb(e);
}
};
SynchronousFileSystem.prototype.readlink = function (p, cb) {
try {
cb(null, this.readlinkSync(p));
}
catch (e) {
cb(e);
}
};
return SynchronousFileSystem;
}(BaseFileSystem));
exports.SynchronousFileSystem = SynchronousFileSystem;
//# sourceMappingURL=file_system.js.map
|
var group__Generic =
[
[ "acc_service_configuration_t", "group__Generic.html#ga3659144b760468217ed4cb1fc3447330", null ],
[ "acc_service_handle_t", "group__Generic.html#gac31f87097f46e587c8d54fb0406f62d4", null ],
[ "acc_service_status_t", "group__Generic.html#ga0fe34d6e342de54ae87279d7e10b5066", null ],
[ "acc_service_status_enum_t", "group__Generic.html#gaf872bd7ad1e331ca9e41ea47eb5dfc75", [
[ "ACC_SERVICE_STATUS_OK", "group__Generic.html#ggaf872bd7ad1e331ca9e41ea47eb5dfc75af11d3960899895c1eaa94ed573da65b1", null ],
[ "ACC_SERVICE_STATUS_FAILURE_UNSPECIFIED", "group__Generic.html#ggaf872bd7ad1e331ca9e41ea47eb5dfc75a7dc54772144765d998d565a4cafa6d17", null ]
] ],
[ "acc_service_activate", "group__Generic.html#ga83f29fef7b79d216d4c6d1959b7eda03", null ],
[ "acc_service_create", "group__Generic.html#ga165f40004fae21f84757a839f7253db0", null ],
[ "acc_service_deactivate", "group__Generic.html#ga17fbd89e106d36a25a18a038cc625bb9", null ],
[ "acc_service_destroy", "group__Generic.html#gad7cc3154b0227e63d18b11aa672de3af", null ],
[ "acc_service_get_sweep_configuration", "group__Generic.html#ga0f281d408a20366b6f7504f52dcad964", null ],
[ "acc_service_is_service_active", "group__Generic.html#ga5a2d777e945aa9ff278278283d95f369", null ],
[ "acc_service_status_name_get", "group__Generic.html#ga90c67ad99fbc5b8038f29279900082a3", null ]
];
|
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["js/admin/DepartmentEdit"],{
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/setting/department/Edit.vue?vue&type=script&lang=js&":
/*!***********************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/admin/pages/setting/department/Edit.vue?vue&type=script&lang=js& ***!
\***********************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var vform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vform */ "./node_modules/vform/dist/vform.common.js");
/* harmony import */ var vform__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(vform__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _admin_components_buttons_FormButtons_vue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/admin/components/buttons/FormButtons.vue */ "./resources/js/admin/components/buttons/FormButtons.vue");
/* harmony import */ var _admin_components_layout_FormLayout_vue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/admin/components/layout/FormLayout.vue */ "./resources/js/admin/components/layout/FormLayout.vue");
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
name: "EditFlight",
components: {
Form: vform__WEBPACK_IMPORTED_MODULE_0__["Form"],
"has-error": vform__WEBPACK_IMPORTED_MODULE_0__["HasError"],
"form-buttons": _admin_components_buttons_FormButtons_vue__WEBPACK_IMPORTED_MODULE_1__["default"],
"form-layout": _admin_components_layout_FormLayout_vue__WEBPACK_IMPORTED_MODULE_2__["default"]
},
data: function data() {
return {
// Create a new form instance
form: new vform__WEBPACK_IMPORTED_MODULE_0__["Form"]({
name: "",
description: ""
})
};
},
created: function created() {
this.getData();
},
methods: {
getData: function getData() {
var _this = this;
axios.get("/api/departments/".concat(this.$route.params.id, "/edit")).then(function (response) {
_this.form.fill(response.data);
});
},
UpdateDepartment: function UpdateDepartment() {
var _this2 = this;
// Submit the form via a itinerary request
this.form.put("/api/departments/".concat(this.$route.params.id)).then(function (response) {
_this2.$router.go(-1);
_this2.$toast.fire({
icon: "success",
title: "Successfully Updated"
});
})["catch"](function () {});
}
}
});
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/setting/department/Edit.vue?vue&type=template&id=9ce69d22&":
/*!***************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/admin/pages/setting/department/Edit.vue?vue&type=template&id=9ce69d22& ***!
\***************************************************************************************************************************************************************************************************************************/
/*! 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("form-layout", {
scopedSlots: _vm._u([
{
key: "formdata",
fn: function() {
return [
_c(
"form",
{
attrs: { role: "form", enctype: "multipart/form-data" },
on: {
submit: function($event) {
$event.preventDefault()
return _vm.UpdateDepartment()
}
}
},
[
_c("div", { staticClass: "row" }, [
_c("div", { staticClass: "col-sm-6" }, [
_c(
"div",
{ staticClass: "form-group" },
[
_c("label", { attrs: { for: "name" } }, [
_vm._v("Department Name")
]),
_vm._v(" "),
_c("input", {
directives: [
{
name: "model",
rawName: "v-model",
value: _vm.form.name,
expression: "form.name"
}
],
staticClass: "form-control",
class: { "is-invalid": _vm.form.errors.has("name") },
attrs: { type: "text", placeholder: "Enter name" },
domProps: { value: _vm.form.name },
on: {
input: function($event) {
if ($event.target.composing) {
return
}
_vm.$set(_vm.form, "name", $event.target.value)
}
}
}),
_vm._v(" "),
_c("has-error", {
attrs: { form: _vm.form, field: "name" }
})
],
1
)
])
]),
_vm._v(" "),
_c("div", { staticClass: "row" }, [
_c("div", { staticClass: "col-sm-12" }, [
_c(
"div",
{ staticClass: "form-group" },
[
_c("label", { attrs: { for: "name" } }, [
_vm._v("Department Description")
]),
_vm._v(" "),
_c("textarea", {
directives: [
{
name: "model",
rawName: "v-model",
value: _vm.form.description,
expression: "form.description"
}
],
staticClass: "form-control",
class: {
"is-invalid": _vm.form.errors.has("description")
},
attrs: {
rows: "4",
placeholder: "Enter Description"
},
domProps: { value: _vm.form.description },
on: {
input: function($event) {
if ($event.target.composing) {
return
}
_vm.$set(
_vm.form,
"description",
$event.target.value
)
}
}
}),
_vm._v(" "),
_c("has-error", {
attrs: { form: _vm.form, field: "description" }
})
],
1
)
])
]),
_vm._v(" "),
_c("form-buttons")
],
1
)
]
},
proxy: true
}
])
})
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./resources/js/admin/pages/setting/department/Edit.vue":
/*!**************************************************************!*\
!*** ./resources/js/admin/pages/setting/department/Edit.vue ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Edit_vue_vue_type_template_id_9ce69d22___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Edit.vue?vue&type=template&id=9ce69d22& */ "./resources/js/admin/pages/setting/department/Edit.vue?vue&type=template&id=9ce69d22&");
/* harmony import */ var _Edit_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Edit.vue?vue&type=script&lang=js& */ "./resources/js/admin/pages/setting/department/Edit.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])(
_Edit_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_Edit_vue_vue_type_template_id_9ce69d22___WEBPACK_IMPORTED_MODULE_0__["render"],
_Edit_vue_vue_type_template_id_9ce69d22___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/js/admin/pages/setting/department/Edit.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/js/admin/pages/setting/department/Edit.vue?vue&type=script&lang=js&":
/*!***************************************************************************************!*\
!*** ./resources/js/admin/pages/setting/department/Edit.vue?vue&type=script&lang=js& ***!
\***************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Edit_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../../node_modules/babel-loader/lib??ref--4-0!../../../../../../node_modules/vue-loader/lib??vue-loader-options!./Edit.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/setting/department/Edit.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Edit_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/js/admin/pages/setting/department/Edit.vue?vue&type=template&id=9ce69d22&":
/*!*********************************************************************************************!*\
!*** ./resources/js/admin/pages/setting/department/Edit.vue?vue&type=template&id=9ce69d22& ***!
\*********************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Edit_vue_vue_type_template_id_9ce69d22___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../../node_modules/vue-loader/lib??vue-loader-options!./Edit.vue?vue&type=template&id=9ce69d22& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/admin/pages/setting/department/Edit.vue?vue&type=template&id=9ce69d22&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Edit_vue_vue_type_template_id_9ce69d22___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Edit_vue_vue_type_template_id_9ce69d22___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ })
}]);
|
/**
* Seanica
*
* User: sean
* Date: 13/04/13
* Time: 10:57 PM
*
*/
define(['sf1','modules/post/post.models','modules/post/post.views','text!modules/post/post.templates.html','uirte'],
function(sf1, Model, View, template, RTE){
var anchorSelector = '#TemplateContainer';
_.templateSettings.variable = 'S';
var baseMarkup = $(template);
// attach the module template markup to the DOM
$(anchorSelector).append(baseMarkup);
var editorMode = 'new';
var userId;
/*
*
* Index View
*
* */
var indexView = function(slug){
var targetLayoutView = new View.IndexLayout();
var indexView = new View.IndexView();
// targetLayoutView.container.show(targetView);
var indexContainerRegion = new Backbone.Marionette.Region({
el: ".view-index"
});
targetLayoutView.on('show',function(layout){
indexContainerRegion.show(indexView);
var editorRegion = new Marionette.Region({
el:'[data-region="editorRegion"]'
});
var composerRegion = new Marionette.Region({
el:'[data-region="composerRegion"]'
});
composerRegion.show(new View.PostEditorLayout());
editorRegion.show(new RTE.RTE());
// check if slug passed in
if (slug){
sf1.EventBus.trigger('post.loadEditPostBySlug',slug);
}
if (sf1.isUserAuth()){
$('.form-controls-container').show();
userId = sf1.currUserId();
sf1.EventBus.trigger('post.loadUserPosts',userId);
}
});
//targetLayoutView.container.show(targetView);
//
return targetLayoutView;
};
/*
*
* Functions
*
*
* */
function createNewPost(postObj){
postObj.status = 'draft';
// save new post
sf1.io.ajax({
type:'POST',
url:'/posts',
data:postObj,
success:function(response){
sf1.log('success saving post: ' + response);
sf1.EventBus.trigger('post.createNewPostSuccess');
},
error:function(response){
sf1.log('error saving post: ' + response);
sf1.EventBus.trigger('post.createNewPostFailed');
}
});
}
function getPostBySlug(slug){
if (slug){
var postObj = {
slug:slug
};
// get post
sf1.io.ajax({
type:'POST',
url:'/postbyslug/' + slug,
data:postObj,
success:function(response){
sf1.log('success getting post: ' + response);
sf1.EventBus.trigger('post.getPostBySlugSuccess',response);
},
error:function(response){
sf1.log('error getting post: ' + response);
sf1.EventBus.trigger('post.getPostBySlugFailed');
}
});
}
}
function publishPostDialog(options){
return new View.PublishPostDialog({
model:new Model.PostModel(options.data)
});
}
/*
*
* EVENT BINDING
*
*
* */
/*
*
* Load Edit Post by Slug
*
* */
sf1.EventBus.bind('post.loadEditPostBySlug',function(slug){
if (slug){
sf1.io.ajax({
type:'GET',
url:'/postbyslug/' + slug,
success:function(response){
sf1.log('success retrieve post: ' + response);
sf1.EventBus.trigger('post.initializeEditForm',response);
},
error:function(response){
sf1.log('error getting post: ' + response);
}
});
}
});
/*
*
* Load User Post List
*
* */
sf1.EventBus.bind('post.loadUserPosts',function(userId){
if (userId){
var postCollection = new Model.PostCollection();
var postsUrl = '/userposts/' + userId;
postCollection.fetch({
url:postsUrl,
success:function(response){
sf1.log('success get posts: ' + response);
var postListRegion = new Marionette.Region({
el:'[data-region="postListRegion"]'
});
// postListRegion.show(new View.PostListView());
postListRegion.show(new View.PostListView({
model:new Backbone.Model({'collectionTitle':'Your Posts'}),
collection:postCollection
}));
},
error:function(response){
sf1.log('error get posts: ' + response);
}
});
}
});
/*
*
* Initialize Edit Post Form
*
* */
sf1.EventBus.bind('post.initializeEditForm',function(post){
editorMode = 'update';
$('#PostId').val(post._id);
$('#PostTitle').val(post.title);
$('#PostSlug').text(post.slug);
CKEDITOR.instances.sf1RTEEditor.setData(post.body);
$('#PostStatus').val(post.status);
});
/*
*
* Load Post to Edit
*
*
* */
sf1.EventBus.bind('post.loadEditPost',function(postId){
if (postId){
sf1.io.ajax({
type:'GET',
url:'/posts/' + postId,
success:function(response){
sf1.log('success retrieve post: ' + response);
sf1.EventBus.trigger('post.initializeEditForm',response);
},
error:function(response){
sf1.log('error getting post: ' + response);
}
});
}
});
/*
*
* Save Button
*
* */
sf1.EventBus.bind('post.savePostButtonClicked',function(event){
sf1.log('save post button click event');
sf1.log('Post Contents: ' + CKEDITOR.instances.sf1RTEEditor.getData());
if (userId){
var postObj = {};
postObj.userId = userId;
postObj.title = $('#PostTitle').val();
postObj.body = CKEDITOR.instances.sf1RTEEditor.getData();
if ('new' === editorMode){
postObj.status = 'draft';
// save new post
sf1.io.ajax({
type:'POST',
url:'/posts',
data:postObj,
success:function(response){
sf1.log('success saving post: ' + response);
},
error:function(response){
sf1.log('error saving post: ' + response);
}
});
}
if ('update' === editorMode){
var postId = $('#PostId').val();
if (postId){
postObj.id = postId;
postObj.status = $('#PostStatus').val();
// update post
sf1.io.ajax({
type:'PUT',
url:'/posts/' + postObj.id,
data:postObj,
success:function(response){
sf1.log('success saving post: ' + response);
},
error:function(response){
sf1.log('error saving post: ' + response);
}
});
}
}
}
else{
sf1.log('warn - no user id');
}
});
/*
*
* Preview Button
*
* */
sf1.EventBus.bind('post.previewPostButtonClicked',function(event){
sf1.log('Preview post button click event');
sf1.log('Post Contents: ' + CKEDITOR.instances.sf1RTEEditor.getData());
var postData = CKEDITOR.instances.sf1RTEEditor.getData();
if (postData){
$('.btn-close-preview').show();
$('.post-preview').html(postData);
}
});
/*
*
* Reset Button
*
* */
sf1.EventBus.bind('post.resetPostButtonClicked',function(event){
sf1.log('Reset post button click event');
sf1.log('Post Contents: ' + CKEDITOR.instances.sf1RTEEditor.getData());
});
/*
*
* Close Preview Button
*
* */
sf1.EventBus.bind('post.closePostPreviewButtonClicked',function(event){
sf1.log('close preview post button click event');
sf1.log('Post Contents: ' + CKEDITOR.instances.sf1RTEEditor.getData());
$('.btn-close-preview').hide();
$('.post-preview').empty();
});
/*
* Change Post Status
*
* */
sf1.EventBus.bind('post.changePostStatusClicked',function(event){
// replace link with select control
// set the value of the control
var postId = $(event.target).data('id');
var postStatus = $(event.target).data('status');
if (postId){
sf1.log('in post.changePostStatusClicked: ' + postId);
var postItemStatusRegion = new Marionette.Region({
el:'td.col-post-status[data-id="' + postId + '"]'
});
// hide the link
// show the select
postItemStatusRegion.show(new View.PostStatusSelectView({
model:new Backbone.Model({'_id':postId,'status':postStatus})
}));
// set the value of the select
// set the event listener on select change
}
else{
sf1.log('attempt to edit status chang but no post id');
}
});
/*
*
* Change Post Status Select Element Change Event
*
* */
sf1.EventBus.bind('post.postStatusSelectChanged',function(data){
var postId = data.id;
var postStatus = data.status;
var postData = {};
postData.id = postId;
postData.status = postStatus;
postData.title = $('a[data-id="' + postId + '"]').prop('title');
if (postId){
switch(postStatus){
/*
*
*
* Publish
*
*
* */
case 'published':
sf1.EventBus.trigger('post.publishPostDialogRequest',postData);
break;
case 'draft':
sf1.log('TO BE IMPLEMENTED change to draft THIS POST: ' + postId);
break;
case 'deleted':
if (confirm('delete this post?')){
sf1.log('DELETE THIS POST: ' + postId);
}
break;
default:
sf1.log('warn - attempt to change post status with no status');
}
}
else{
sf1.log('warn - attempt to change status with no post id');
}
});
/*
*
* Edit Post
*
* */
sf1.EventBus.bind('post.editPostRequest',function(event){
var postId = $(event.target).data('id');
if (postId){
sf1.EventBus.trigger('post.loadEditPost',postId);
}
});
/*
*
* Publish Post Request
*
* */
sf1.EventBus.bind('post.publishPostDialogRequest',function(post){
// set the author
var author = sf1.currUserName();
if (sf1.hasStorage){
if (localStorage.getItem('sf1UserPrefs')){
var userPrefsObj = JSON.parse(localStorage.getItem('sf1UserPrefs'));
if (userPrefsObj){
if (userPrefsObj.publishSettings){
if (userPrefsObj.publishSettings.authorName){
author = userPrefsObj.publishSettings.authorName;
}
}
}
}
}
post.author = author;
sf1.EventBus.trigger('ia.loadRegionContentRequest',{
region:'modalRegion',
module:'post',
view:'PublishPostDialog',
data:{data:post},
callback:function(){
sf1.EventBus.bind('post.publishPostSuccess',function(){
$.modal.close();
userId = sf1.currUserId();
sf1.EventBus.trigger('post.loadUserPosts',userId);
});
}
});
});
sf1.EventBus.bind('post.publishPostBtnClicked',function(event){
// get the post data
var postId = $(event.target).data('id');
var postAuthor = $('#InputPublishPostAuthor').val();
if (sf1.hasStorage){
if (!localStorage.getItem('sf1UserPrefs')){
localStorage.setItem('sf1UserPrefs','');
}
var userPrefs = localStorage.getItem('sf1UserPrefs');
if (!userPrefs){
userPrefs = '{}';
}
var userPrefsObj = JSON.parse(userPrefs);
if (userPrefsObj){
if (!userPrefsObj.publishSettings){
userPrefsObj.publishSettings = {};
}
userPrefsObj.publishSettings.authorName = postAuthor;
localStorage.setItem('sf1UserPrefs',JSON.stringify(userPrefsObj));
}
}
var postData = {};
postData.id = postId;
postData.author = postAuthor;
sf1.EventBus.trigger('post.publishPostRequest',postData);
});
/*
*
* AJAX
*
* Publish Post
*
*
* */
sf1.EventBus.bind('post.publishPostRequest',function(postObj){
sf1.io.ajax({
type:'PUT',
url:'/publishpost/' + postObj.id,
data:postObj,
error:function(response){
sf1.log('error publishing: ' + response);
},
success:function(response){
sf1.log('SUCCESS PUBLISH');
//close modal window
sf1.EventBus.trigger('post.publishPostSuccess');
}
});
});
return{
IndexView:indexView,
PostEditor:function(){
return new View.PostEditorLayout();
},
createNewPost:createNewPost,
getPostBySlug:getPostBySlug,
PostListView:View.PostListView,
PostCollection:Model.PostCollection,
RecentPostListView:View.RecentPostListView,
PublishPostDialog:publishPostDialog
};
}
);
|
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Serializer | stripe bank account token', function(hooks) {
setupTest(hooks);
// Replace this with your real tests.
test('it exists', function(assert) {
let store = this.owner.lookup('service:store');
let serializer = store.serializerFor('stripe-bank-account-token');
assert.ok(serializer);
});
test('it serializes records', function(assert) {
let store = this.owner.lookup('service:store');
let record = store.createRecord('stripe-bank-account-token', {});
let serializedRecord = record.serialize();
assert.ok(serializedRecord);
});
});
|
import React from 'react';
import {
compose,
withStateHandlers,
withHandlers,
lifecycle,
} from 'recompose';
import { withRouter, Link } from 'react-router-dom';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import { MdArrowBack } from 'react-icons/lib/md';
import TextField from 'material-ui/TextField';
import FontIcon from 'material-ui/FontIcon/FontIcon';
import IconButton from 'material-ui/IconButton';
import { withApollo, graphql } from 'react-apollo';
import Helmet from 'react-helmet';
import { InsertCarQuery, CarQuery } from '../graph';
const addCarOptions = {
props: ({ mutate }) => ({
submit: (car) => mutate({
variables: { car },
}),
}),
};
export default compose(
withRouter,
withApollo,
graphql(InsertCarQuery, addCarOptions),
withStateHandlers(
() => ({
car: {
brand: '',
model: '',
carryingCapacity: 0,
fuelConsumption: 0,
stateNumber: '',
cargoType: 'any',
},
}),
{
onInfoFilled: ({ car }) => ({ target: { name, value } }) => ({
car: {
...car,
[name]: value,
},
}),
onSetCar: () => (editedCar) => ({
car: editedCar,
}),
},
),
withHandlers({
onAddHandler: ({ submit, car, history }) => async () => {
await submit(car);
history.push('/cars');
},
onEditHandler: () => () => {
},
onCancelHandler: ({ history }) => () => {
history.push('/cars');
},
validateClient: ({ car }) => () => {
for (const i in car) {
if (!car[i]) {
return false;
}
}
return true;
},
}),
lifecycle({
async componentDidMount() {
const { match: { params: { id } }, onSetCar, client } = this.props;
if (id) {
try {
const { data } = await client.query({
query: CarQuery,
variables: {
id,
},
});
onSetCar(data.car);
} catch (e) {
console.log(e);
}
}
},
}),
)(({ car, onInfoFilled, onAddHandler, onCancelHandler }) => (
<section className="container-fluid with-maxwidth chapter">
<Helmet>
<title>{(!car._id) ? 'Додати автомобіль' : 'Редагувати автомобіль'}</title>
</Helmet>
<article className="article">
<div className="row">
<IconButton style={{ alignSelf: 'flex-end', display: 'flex' }}>
<Link to="/cars">
<FontIcon color="#000" className="material-icons"><MdArrowBack /></FontIcon>
</Link>
</IconButton>
{
(!car._id) ?
<h2 className="article-title col-xl-10">
Додати автомобіль
</h2> :
<h2 className="article-title col-xl-10">
Редагувати автомобіль
</h2>
}
</div>
<div className="box box-default col-xl-6">
<div className="box-body">
<form>
<TextField
floatingLabelText="Марка"
name="brand"
onChange={onInfoFilled}
value={car.brand}
fullWidth
/>
<br />
<TextField
floatingLabelText="Модель"
name="model"
onChange={onInfoFilled}
value={car.model}
fullWidth
/>
<br />
<TextField
floatingLabelText="Державний номер"
name="stateNumber"
onChange={onInfoFilled}
value={car.stateNumber}
fullWidth
/>
<br />
<div className="row">
<div className="col-md-6">
<TextField
floatingLabelText="Вантажопідйомність"
name="carryingCapacity"
style={{ width: '60%' }}
onChange={onInfoFilled}
value={car.carryingCapacity}
/>
<span>т.</span>
</div>
<div className="col-md-6">
<TextField
floatingLabelText="Витрати палива"
name="fuelConsumption"
style={{ width: '60%' }}
onChange={onInfoFilled}
value={car.fuelConsumption}
/>
<span>л/км</span>
</div>
</div>
<div className="row" style={{ marginTop: 20 }}>
<div className="col-xs-3">
{
(!car._id) ?
<RaisedButton
label="Зберегти"
onClick={onAddHandler}
primary
className="btn-w-md"
/> :
<RaisedButton
label="Редагувати"
primary
className="btn-w-md"
/>
}
</div>
<div className="col-xs-3">
<FlatButton
label="Відміна"
onClick={onCancelHandler}
className="btn-w-md"
/>
</div>
</div>
<div className="divider" />
</form>
</div>
</div>
</article>
</section>
));
|
var moment = require("../../index");
exports["America/La_Paz"] = {
"1931" : function (t) {
t.equal(moment("1931-10-15T04:32:35+00:00").tz("America/La_Paz").format("HH:mm:ss"), "23:59:59", "1931-10-15T04:32:35+00:00 should be 23:59:59 CMT");
t.equal(moment("1931-10-15T04:32:36+00:00").tz("America/La_Paz").format("HH:mm:ss"), "01:00:00", "1931-10-15T04:32:36+00:00 should be 01:00:00 BOST");
t.equal(moment("1931-10-15T04:32:35+00:00").tz("America/La_Paz").zone(), 16356 / 60, "1931-10-15T04:32:35+00:00 should be 16356 / 60 minutes offset in CMT");
t.equal(moment("1931-10-15T04:32:36+00:00").tz("America/La_Paz").zone(), 12756 / 60, "1931-10-15T04:32:36+00:00 should be 12756 / 60 minutes offset in BOST");
t.done();
},
"1932" : function (t) {
t.equal(moment("1932-03-21T03:32:35+00:00").tz("America/La_Paz").format("HH:mm:ss"), "23:59:59", "1932-03-21T03:32:35+00:00 should be 23:59:59 BOST");
t.equal(moment("1932-03-21T03:32:36+00:00").tz("America/La_Paz").format("HH:mm:ss"), "23:32:36", "1932-03-21T03:32:36+00:00 should be 23:32:36 BOT");
t.equal(moment("1932-03-21T03:32:35+00:00").tz("America/La_Paz").zone(), 12756 / 60, "1932-03-21T03:32:35+00:00 should be 12756 / 60 minutes offset in BOST");
t.equal(moment("1932-03-21T03:32:36+00:00").tz("America/La_Paz").zone(), 240, "1932-03-21T03:32:36+00:00 should be 240 minutes offset in BOT");
t.done();
}
};
|
import {initComponent, destroy} from '../Utils'
import Header from '../../src/components/Header.vue'
//There are issues of importing vuetify components https://github.com/vuejs/vue-cli/issues/1584
import _ from 'lodash'
let wrapper
describe('Header.vue', () => {
afterEach(() => {
destroy(wrapper)
});
test('component name', () => {
wrapper = initComponent(Header)
expect(wrapper.name()).toBe('Header')
})
test('component props', () => {
wrapper = initComponent(Header)
expect(_.keys(wrapper.props())).toHaveLength(5)
})
test('generator brand', () => {
const testGen = 'Yeoman Generators'
wrapper = initComponent(Header, { headerTitle: testGen})
expect(wrapper.find('v-toolbar-title-stub').text()).toBe(testGen)
expect(wrapper.find('v-icon-stub').text()).toBe("mdi-console")
})
test('click triggers collapseOutput method', async () => {
const rpcInvokeMockFunction = jest.fn()
wrapper = initComponent(Header, {
rpc: {
invoke: rpcInvokeMockFunction
},
isGeneric: false
}, true)
wrapper.findAll("button").wrappers[0].trigger('click')
expect(rpcInvokeMockFunction).toHaveBeenCalledWith("toggleOutput", [{}])
})
test('openExploreGenerators', async () => {
const rpcInvokeMockFunction = jest.fn()
wrapper = initComponent(Header, {
rpc: {
invoke: rpcInvokeMockFunction
},
isGeneric: true
}, true)
wrapper.findAll("button").wrappers[0].trigger('click')
expect(rpcInvokeMockFunction).toHaveBeenCalledWith("exploreGenerators", [{}])
})
})
|
const jwt = require('jsonwebtoken');
const generateJWT = (username = '', id = 0) => {
if(id <= 0) {
return;
}
return new Promise ((resolve, reject) => {
const payload = { username, id };
jwt.sign( payload, process.env.SECRET_JWT_KEY, {
expiresIn: process.env.SECRET_JWT_KEY_EXPIRATION
}, (err, token) => {
if(err) {
console.log(`Error signing token: ${err}`);
reject('No se pudo generar el token');
}
else {
resolve(token);
}
});
});
};
module.exports = {
generateJWT
};
|
const function720 = function (t, e, i) {
"use strict";
var n = this && this.__extends || function () {
var t = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (t, e) {
t.__proto__ = e
} || function (t, e) {
for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i])
};
return function (e, i) {
function n() {
this.constructor = e
}
t(e, i), e.prototype = null === i ? Object.create(i) : (n.prototype = i.prototype, new n)
}
}();
Object.defineProperty(e, "__esModule", { value: !0 });
var o = i(11), r = function (t) {
function e(e) {
var i = t.call(this) || this;
return i.organizeSceneMain = e, i
}
return n(e, t), e.prototype._start = function () {
this.organizeSceneMain.prefinalize(), this._completedEnd()
}, e
}(o.TaskBase);
e.PreFinalizeTask = r
}
|
import { FilledAddToHomeScreen as OutlineAddToHomeScreen } from './FilledAddToHomeScreen';
export { OutlineAddToHomeScreen };
|
var gulp = require('gulp')
var $ = require('gulp-load-plugins')()
function errHandler( e ) {
$.util.beep()
$.util.log($.util.colors.red('↓看这里看这里,报错了:'))
$.util.log(e)
return this
}
module.exports = errHandler
|
module.exports = {
parser: '@typescript-eslint/parser', // Specifies the ESLint parser
extends: [
'plugin:react/recommended', // Uses the recommended rules from @eslint-plugin-react
'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
'plugin:prettier/recommended', // Enables eslint-plugin-prettier and
],
parserOptions: {
ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features
sourceType: 'module', // Allows for the use of imports
ecmaFeatures: {
jsx: true, // Allows for the parsing of JSX
},
},
rules: {
// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
'prettier/prettier': 'error',
// e.g. "@typescript-eslint/explicit-function-return-type": "off",
},
settings: {
react: {
version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use
},
},
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import App from './App';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css'; // Main css for the project
import './custom.css'; // Custom Theme for Bootstrap
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
|
(function($){
var Slideshow = function (element, options) {
this.$element = $(element);
this.options = options;
this.paused = false;
this.activeIndex = 0;
this.init = function() {
this.$items = this.$element.find('.item');
}
this.attachEvents();
this.init();
}
Slideshow.prototype = {
slide: function(item) {
var $item = $(item),
$frame = $item.find('.frame'),
marginTop = 0;
this.$items.hide();
$item.show();
marginTop = Math.round($item.height() - $frame.height())/2;
this.activeIndex = this.$items.index(item);
if (this.options.autoPlay && !this.paused) this.play();
return this;
},
play: function() {
this.paused = false;
if (this.interval) clearInterval(this.interval);
this.interval = setInterval($.proxy(this.next, this), this.options.interval);
},
pause: function() {
this.paused = true;
this.interval = clearInterval(this.interval);
return this;
},
startAt: function(pos) {
this.to(pos);
},
next: function() {
return this.to('next');
},
to: function(pos) {
if (pos === 'next') pos = this.activeIndex + 1;
if (pos === 'prev') pos = this.activeIndex - 1;
return this.slide(this.$items[this.getValidIndex(pos)]);
},
getValidIndex: function(index) {
if (typeof index === 'undefined' || index > (this.$items.length - 1)) index = 0;
if (index < 0) index = this.$items.length - 1;
return index;
},
attachEvents: function() {
var $img = this.$element.find('.frame img'),
_this = this;
// pause slideshow on image mouseenter event
$img.on('mouseenter', function() { _this.pause(); });
// play slideshow on image mouseleave event
$img.on('mouseleave', function() {
if (_this.options.autoPlay) _this.play();
});
$(document).on('click', '[data-slide], [data-slide-to]', function(e) {
e.preventDefault();
pos = parseInt($(this).attr('data-slide-to'), 10) || $(this).attr('data-slide');
if (pos === 'next' || pos === 'prev') _this.pause();
_this.to(pos);
});
// pause slideshow on modal close
$('#slideshow-modal').on('hidden.bs.modal', function() {
_this.pause();
});
}
}
Slideshow.DEFAULTS = {
autoPlay: true,
interval: 5000 // in milliseconds
}
$.fn.slideshow = function(option) {
return this.each(function() {
var $this = $(this);
var data = $this.data('slideshow');
var options = $.extend({}, Slideshow.DEFAULTS, $this.data(), typeof option == 'object' && option);
if (!data) $this.data('slideshow', (data = new Slideshow(this, options)));
})
}
})(jQuery);
Blacklight.onLoad(function() {
$('#slideshow').slideshow();
});
|
export const Header = () => (
<div class="container col-md-12 mr-3">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Movies.com</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Detalhes</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Preços</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#">Sobre</a>
</li>
</ul>
</div>
</nav>
</div>
)
|
var util = require('util');
var Moniker = require('moniker');
var maxEmits=4; //Maximum number of flood emits allowed
var emitInterval=2; //emitCount will be increased if two messages arrive in X seconds.
var ipList = {};
var maxKicks=3; //user will be banned after kicked X times.
var banTime=1800; //Ban for X seconds
var namer = Moniker.generator([Moniker.adjective, Moniker.noun], {
glue: ' '
});
module.exports = function(options) {
return function(socket, next) {
socket.user = namer.choose().replace(/\b\w/g, l => l.toUpperCase());
socket.floodTimer=0;
socket.emitCount=0;
if (socket.request.connection.remoteAddress in ipList) {
if (ipList[socket.request.connection.remoteAddress].banned) {
if ((timeInSeconds()-ipList[socket.request.connection.remoteAddress].time)>banTime) {
console.log("Unbanned "+socket.request.connection.remoteAddress);
delete ipList[socket.request.connection.remoteAddress];
} else {
socket.disconnect();
}
}
}
function timeInSeconds() {
var date = new Date();
return (date.getTime()/1000);
}
socket
.on('join', function(room) {
//console.log("%s joined %s", socket.user, room);
if (room) {
socket.join(socket.room = room);
socket.nsp.in(socket.room).emit('join', {u: "Info", m: socket.user+" joined."});
socket.emit('welcome',{u: socket.user})
}
})
.on('message', function(message) {
if (socket.room) {
//console.log("%s: %s %s", socket.user, message, socket.room);
var curTime=timeInSeconds();
if ((curTime-socket.floodTimer)<emitInterval) {
//console.log(socket.user+" is flooding.");
socket.emitCount+=1;
if (socket.emitCount==maxEmits) {
socket.disconnect();
socket.nsp.in(socket.room).emit('message', {u: "Info", m: socket.user+" has been disconnected due to sending too many messages."});
if (socket.request.connection.remoteAddress in ipList) {
ipList[socket.request.connection.remoteAddress].kickCount+=1;
ipList[socket.request.connection.remoteAddress].time=curTime;
console.log("KickCount increased for "+socket.request.connection.remoteAddress);
if (ipList[socket.request.connection.remoteAddress].kickCount==maxKicks) {
console.log("Banned "+socket.request.connection.remoteAddress);
ipList[socket.request.connection.remoteAddress].banned=true;
}
} else {
ipList[socket.request.connection.remoteAddress]={kickCount:1, banned:false, time:curTime};
console.log("KickCount is 1 for "+socket.request.connection.remoteAddress);
}
//}
return;
}
} else {
if (socket.emitCount)
socket.emitCount-=1;
}
socket.floodTimer=curTime;
var mIndex=message.indexOf(" ");
if (mIndex==-1) {
if (!/^\/.*/.test(message)) {
if (/^https?\:\/\//.test(message)) {
socket.nsp.in(socket.room).emit('message', {
u: socket.user,
m: message.replace(/<>"/,''),
link: true
});
return;
}
} else { return; }
socket.nsp.in(socket.room).emit('message', {
u: socket.user,
m: message
});
return;
}
switch (message.slice(0,mIndex)) {
case '/me':
message="*"+socket.user+" "+message.slice(mIndex)+"*";
break;
}
if (!/^\/.*/.test(message))
socket.nsp.in(socket.room).emit('message', {
u: socket.user,
m: message
});
}
})
.on('disconnect', function() {
//console.log("%s left %s", socket.user, socket.room);
if (socket.room) {
socket.nsp.in(socket.room).emit('leave', {u: "Info", m: socket.user+" left."});
}
});
next();
};
};
|
// Dependencies
const Logger = require('../logger')
// Constants
const DEBUG = process.env.DEBUG
// Helpers
class FakeConsole {
constructor () {
this.printed = ''
}
log (x) {
this.printed = x
if (DEBUG) { console.log(x) }
}
}
// Tests
describe('logging', () => {
beforeAll(() => {
this.log = Logger('petshop',
{},
() => '2016-02-15T12:34:56.789Z',
new FakeConsole())
})
it('should throw an error without a message', () => {
expect(() => {
this.log.info()
}).toThrow()
})
it('should log mandatory attributes', () => {
this.log.error({ message: 'Out of pets exception' })
const contents = JSON.parse(this.log.output.printed)
expect(contents['@timestamp']).toBe('2016-02-15T12:34:56.789Z')
expect(contents.service.name).toBe('petshop')
expect(contents.log.level).toBe('error')
expect(contents.ecs.version).toBe(this.log.ECS_VERSION)
expect(contents.message).toBe('Out of pets exception')
})
it('should log the provided message', () => {
this.log.error({ event: { action: 'exception' }, message: 'Emergency! Emergency!' })
const contents = JSON.parse(this.log.output.printed)
expect(contents.event.action).toBe('exception')
expect(contents.message).toBe('Emergency! Emergency!')
})
it('should log a stack trace if provided', () => {
try {
console.thing()
} catch (err) {
this.log.error({ message: 'An error!' }, err)
}
const contents = JSON.parse(this.log.output.printed)
expect(contents.message).toBe('An error!')
expect(contents.error.message).toBe('console.thing is not a function')
expect(contents.error.type).toBe('TypeError')
expect(contents.error.stack_trace[1]).toContain('logger-spec')
})
it('should log scoped properties defined at creation', () => {
const extraProperties = {
trace: {
id: '1c8a5fb2-fecd-44d8-92a4-449eb2ce4dcb'
},
message: 'GET /cats',
request: { method: 'get' },
response: { status_code: 200 }
}
const myLogger = Logger('petshop',
extraProperties,
() => '2016-02-15T12:34:56.789Z',
new FakeConsole())
myLogger.error(extraProperties)
const contents = JSON.parse(myLogger.output.printed)
expect(contents.trace.id).toBe('1c8a5fb2-fecd-44d8-92a4-449eb2ce4dcb')
expect(contents.request.method).toBe('get')
expect(contents.response.status_code).toBe(200)
expect(contents.message).toBe('GET /cats')
})
it("should be able to add properties with '.with'", () => {
// Let's add some context to this customer journey
const purchaseLog = this.log.with({
trace: { id: '1c8a5fb2-fecd-44d8-92a4-449eb2ce4dcb' },
customer: { full_name: 'Freda Bloggs' },
event: { action: 'pet purchase' }
})
// do stuff
purchaseLog.info({
message: 'customer bought a dog',
pet: { name: 'Barker', species: 'dog', breed: 'Bitsa' }
})
const contents = JSON.parse(purchaseLog.output.printed)
expect(contents.trace.id).toBe('1c8a5fb2-fecd-44d8-92a4-449eb2ce4dcb')
expect(contents.customer.full_name).toBe('Freda Bloggs')
expect(contents.event.action).toBe('pet purchase')
expect(contents.message).toBe('customer bought a dog')
expect(contents.pet.name).toBe('Barker')
})
})
describe('logging dotted keys', () => {
it('should be able to convert dotted keys to nested objects', () => {
this.log.debug({
'trace.id': '1c8a5fb2-fecd-44d8-92a4-449eb2ce4dcb',
'customer.full_name': 'Freda Bloggs',
'event.action': 'pet purchase',
message: 'customer bought a dog',
'pet.name': 'Barker',
'pet.species': 'dog',
'pet.breed': 'Bitsa'
})
const contents = JSON.parse(this.log.output.printed)
expect(contents.trace.id).toBe('1c8a5fb2-fecd-44d8-92a4-449eb2ce4dcb')
expect(contents.customer.full_name).toBe('Freda Bloggs')
expect(contents.event.action).toBe('pet purchase')
expect(contents.message).toBe('customer bought a dog')
expect(contents.pet.name).toBe('Barker')
expect(contents.pet.species).toBe('dog')
expect(contents.pet.breed).toBe('Bitsa')
})
it('should be able to mix dotted keys and nested objects', () => {
this.log.debug({
'trace.id': '1c8a5fb2-fecd-44d8-92a4-449eb2ce4dcb',
'customer.full_name': 'Freda Bloggs',
'event.action': 'pet purchase',
message: 'customer bought a dog',
pet: { name: 'Barker', breed: 'Bitsa' },
'pet.species': 'dog'
})
const contents = JSON.parse(this.log.output.printed)
expect(contents.trace.id).toBe('1c8a5fb2-fecd-44d8-92a4-449eb2ce4dcb')
expect(contents.customer.full_name).toBe('Freda Bloggs')
expect(contents.event.action).toBe('pet purchase')
expect(contents.message).toBe('customer bought a dog')
expect(contents.pet.name).toBe('Barker')
expect(contents.pet.species).toBe('dog')
expect(contents.pet.breed).toBe('Bitsa')
})
})
describe('enforcing non-empty message', () => {
it('should throw an error on an empty message', () => {
expect(() => {
this.log.info('')
}).toThrow()
})
it('should throw an error on a message of blank spaces', () => {
expect(() => {
this.log.info(' ')
}).toThrow()
})
it('should throw an error on a null message', () => {
expect(() => {
this.log.info(null)
}).toThrow()
})
it('should throw an error on an undefined message', () => {
expect(() => {
this.log.info(undefined)
}).toThrow()
})
it('should throw an error if message property is missing', () => {
expect(() => {
this.log.debug({ event: { action: 'pet purchase' }})
}).toThrow()
})
it('should throw an error on an undefined message as a property', () => {
expect(() => {
this.log.debug({ event: { action: 'pet purchase' }, message: undefined })
}).toThrow()
})
it('should throw an error on an null message as a property', () => {
expect(() => {
this.log.debug({ event: { action: 'pet purchase' }, message: null })
}).toThrow()
})
it('should throw an error on an empty message as a property', () => {
expect(() => {
this.log.debug({ event: { action: 'pet purchase' }, message: '' })
}).toThrow()
})
it('should throw an error on an message of blank spaces as a property', () => {
expect(() => {
this.log.debug({ event: { action: 'pet purchase' }, message: ' ' })
}).toThrow()
})
})
|
import React from 'react';
import { expect } from 'chai';
import { mount, configure } from 'enzyme';
import {
Stage,
Layer,
Rect,
Group,
Image,
useStrictMode,
Text,
__matchRectVersion
} from '../src/ReactKonva';
import useImage from 'use-image';
import './mocking';
import Konva from 'konva';
import sinon from 'sinon/pkg/sinon';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
describe('Test version matching', function() {
it('should match react version', function() {
expect(__matchRectVersion).to.equal(true);
});
});
describe('Test references', function() {
let instance;
class App extends React.Component {
render() {
return (
<Stage width={300} height={300} ref={node => (this.stage = node)}>
<Layer ref={node => (this.layer = node)} />
</Stage>
);
}
}
beforeEach(() => {
const wrapper = mount(<App />);
instance = wrapper.instance();
});
it('can get stage instance', function() {
const stageRef = instance.stage;
expect(stageRef.getStage() instanceof Konva.Stage).to.equal(true);
});
it('check initial props set', function() {
const stage = instance.stage.getStage();
expect(stage.width()).to.equal(300);
expect(stage.height()).to.equal(300);
});
it('can get layer instance', function() {
expect(instance.layer instanceof Konva.Layer).to.equal(true);
});
// how can we make this work?
it('stage ref should go to the stage', function() {
const stageRef = instance.stage;
expect(stageRef instanceof Konva.Stage).to.equal(true);
});
it('works ok with no ref', function() {
class App extends React.Component {
render() {
return (
<Stage width={300} height={300}>
<Layer ref={node => (this.layer = node)} />
</Stage>
);
}
}
const wrapper = mount(<App />);
instance = wrapper.instance();
});
it('works ok with react ref', function() {
class App extends React.Component {
stage = React.createRef();
render() {
return (
<Stage width={300} height={300} ref={this.stage}>
<Layer ref={node => (this.layer = node)} />
</Stage>
);
}
}
const wrapper = mount(<App />);
instance = wrapper.instance();
const stage = instance.stage.current;
expect(stage instanceof Konva.Stage).to.equal(true);
});
it('forward ref', function() {
const MyRect = React.forwardRef((props, ref) => <Rect ref={ref} />);
class App extends React.Component {
stage = React.createRef();
render() {
return (
<Stage width={300} height={300} ref={this.stage}>
<Layer ref={node => (this.layer = node)}>
<MyRect ref={node => (this.rect = node)} />
</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
instance = wrapper.instance();
const rect = instance.rect;
expect(rect instanceof Konva.Rect).to.equal(true);
});
});
describe('Test stage component', function() {
it('can attach stage events', function() {
let eventCount = 0;
const handleEvent = () => {
eventCount += 1;
};
class App extends React.Component {
render() {
return (
<Stage
ref={node => (this.stage = node)}
width={300}
height={300}
onMouseDown={handleEvent}
>
<Layer ref={node => (this.layer = node)}>
<Rect ref={node => (this.rect = node)} width={100} height={100} />
</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
const instance = wrapper.instance();
const stage = instance.stage.getStage();
stage.simulateMouseDown({ x: 50, y: 50 });
expect(eventCount).to.equal(1);
});
it('can attach stage content events', function() {
let eventCount = 0;
const handleEvent = () => {
eventCount += 1;
};
class App extends React.Component {
render() {
return (
<Stage
ref={node => (this.stage = node)}
width={300}
height={300}
onContentMouseDown={handleEvent}
>
<Layer ref={node => (this.layer = node)}>
<Rect ref={node => (this.rect = node)} width={100} height={100} />
</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
const instance = wrapper.instance();
const stage = instance.stage.getStage();
stage.simulateMouseDown({ x: 50, y: 50 });
expect(eventCount).to.equal(1);
});
it('unmount stage should destroy it from Konva', () => {
class App extends React.Component {
render() {
if (this.props.skipStage) {
return <div />;
}
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)} />
</Stage>
);
}
}
const wrapper = mount(<App />);
const instance = wrapper.instance();
const stagesNumber = Konva.stages.length;
wrapper.setProps({ skipStage: true });
expect(Konva.stages.length).to.equal(stagesNumber - 1);
});
it('test null event', function() {
class App extends React.Component {
render() {
return (
<Stage
ref={node => (this.stage = node)}
width={300}
height={300}
onMouseDown={null}
>
<Layer ref={node => (this.layer = node)}>
<Rect ref={node => (this.rect = node)} width={100} height={100} />
</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
const instance = wrapper.instance();
const stage = instance.stage.getStage();
stage.simulateMouseDown({ x: 50, y: 50 });
});
});
describe('Test props setting', function() {
let instance, wrapper;
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>
<Rect ref={node => (this.rect = node)} {...this.props.rectProps} />
</Layer>
</Stage>
);
}
}
beforeEach(() => {
wrapper = mount(<App />);
instance = wrapper.instance();
});
it('can update component props', () => {
const rect = instance.rect;
// set new props
const props1 = {
width: 100,
height: 100
};
wrapper.setProps({ rectProps: props1 });
expect(rect.width()).to.equal(100);
const props2 = {
width: 200,
height: 100
};
wrapper.setProps({ rectProps: props2 });
expect(rect.width()).to.equal(200);
});
it('can update component events', () => {
const rect = instance.rect;
// set new props
const props1 = {
onClick: () => {}
};
wrapper.setProps({ rectProps: props1 });
expect(rect.eventListeners.click.length).to.equal(1);
expect(rect.eventListeners.click[0].handler).to.equal(props1.onClick);
const props2 = {
onClick: () => {}
};
wrapper.setProps({ rectProps: props2 });
expect(rect.eventListeners.click.length).to.equal(1);
expect(rect.eventListeners.click[0].handler).to.equal(props2.onClick);
});
it('updating props should call layer redraw', () => {
const layer = instance.layer;
sinon.spy(layer, 'batchDraw');
wrapper.setProps({
rectProps: {
fill: 'green'
}
});
wrapper.setProps({
rectProps: {
fill: 'red'
}
});
expect(layer.batchDraw.callCount).to.equal(2);
});
it('unset props', () => {
const rect = instance.rect;
wrapper.setProps({
rectProps: {
fill: 'red',
x: 10
}
});
expect(rect.fill()).to.equal('red');
wrapper.setProps({ rectProps: {} });
expect(!!rect.fill()).to.equal(false);
expect(rect.x()).to.equal(0);
});
it('do not overwrite properties if that changed manually', () => {
const rect = instance.rect;
wrapper.setProps({
rectProps: {
fill: 'red',
x: 10
}
});
expect(rect.x()).to.equal(10);
// change position manually
rect.x(20);
wrapper.setProps({
rectProps: {
fill: 'red',
x: 10
}
});
expect(rect.x()).to.equal(20);
});
it('overwrite properties if that changed manually in strict-mode', () => {
useStrictMode(true);
const rect = instance.rect;
wrapper.setProps({
rectProps: {
fill: 'red',
x: 10
}
});
expect(rect.x()).to.equal(10);
// change position manually
rect.x(20);
wrapper.setProps({
rectProps: {
fill: 'red',
x: 10
}
});
expect(rect.x()).to.equal(10);
useStrictMode(false);
});
it('overwrite properties if that passed _useStrictMode', () => {
const rect = instance.rect;
wrapper.setProps({
rectProps: {
fill: 'red',
x: 10
}
});
expect(rect.x()).to.equal(10);
// change position manually
rect.x(20);
wrapper.setProps({
rectProps: {
fill: 'red',
x: 10,
_useStrictMode: true
}
});
expect(rect.x()).to.equal(10);
});
it('call draw immediately after props change to get 60 fps', async () => {
const layer = instance.layer;
sinon.spy(layer, 'batchDraw');
sinon.spy(layer, 'draw');
wrapper.setProps({
rectProps: {
fill: 'green'
}
});
expect(layer.batchDraw.calledOnce).to.equal(true);
expect(layer.draw.notCalled).to.equal(true);
const startTime = Date.now();
await 1;
expect(layer.draw.calledOnce).to.equal(true);
// Normally it's 1 or 2 ms.
// We just need to make sure it's less than min frame length 16ms.
expect(Date.now() - startTime < 15).to.equal(true);
});
it('call draw once if batchDraw is called multiple times inside one event loop', async () => {
const layer = instance.layer;
sinon.spy(layer, 'batchDraw');
sinon.spy(layer, 'draw');
wrapper.setProps({
rectProps: {
fill: 'green'
}
});
wrapper.setProps({
rectProps: {
fill: 'red'
}
});
expect(layer.batchDraw.callCount).to.equal(2);
expect(layer.draw.callCount).to.equal(0);
await 1;
expect(layer.draw.callCount).to.equal(1);
});
});
describe('test lifecycle methods', () => {
let instance, wrapper;
class SubComponent extends React.Component {
// comment, as it will be removed
// componentWillMount() {
// this.props.componentWillMount();
// }
componentDidMount() {
this.props.componentDidMount();
}
// componentWillReceiveProps(newProps) {
// this.props.componentWillReceiveProps(newProps);
// }
shouldComponentUpdate() {
this.props.shouldComponentUpdate(...arguments);
return true;
}
// componentWillUpdate() {
// this.props.componentWillUpdate();
// }
componentDidUpdate() {
this.props.componentDidUpdate();
}
componentWillUnmount() {
this.props.componentWillUnmount();
}
render() {
return <Rect />;
}
}
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>
{this.props.dontDrawChildren ? null : (
<SubComponent {...this.props} />
)}
</Layer>
</Stage>
);
}
}
it('test mount', () => {
const props = {
// componentWillMount: sinon.spy(),
componentDidMount: sinon.spy()
};
wrapper = mount(<App {...props} />);
// expect(props.componentWillMount.called).to.equal(true);
expect(props.componentDidMount.called).to.equal(true);
});
it('test update', () => {
const props = {
// componentWillMount: sinon.spy(),
componentDidMount: sinon.spy(),
// componentWillReceiveProps: sinon.spy(),
shouldComponentUpdate: sinon.spy(),
// componentWillUpdate: sinon.spy(),
componentDidUpdate: sinon.spy(),
componentWillUnmount: sinon.spy()
};
wrapper = mount(<App {...props} />);
wrapper.setProps(props);
// expect(props.componentWillMount.called).to.equal(true);
expect(props.shouldComponentUpdate.called).to.equal(true);
// expect(props.componentWillUpdate.called).to.equal(true);
expect(props.componentDidUpdate.called).to.equal(true);
});
it('test remove', () => {
const props = {
// componentWillMount: sinon.spy(),
componentDidMount: sinon.spy(),
// componentWillReceiveProps: sinon.spy(),
shouldComponentUpdate: sinon.spy(),
// componentWillUpdate: sinon.spy(),
componentDidUpdate: sinon.spy(),
componentWillUnmount: sinon.spy()
};
wrapper = mount(<App {...props} />);
const stage = wrapper.instance().stage.getStage();
expect(stage.findOne('Rect')).to.not.equal(undefined);
props.dontDrawChildren = props;
wrapper.setProps(props);
expect(stage.findOne('Rect')).to.equal(undefined);
// This line don't work... why????
expect(props.componentWillUnmount.called).to.equal(true);
});
});
describe('Test Events', function() {
let instance;
class App extends React.Component {
render() {
return (
<Stage width={300} height={300} ref={node => (this.stage = node)}>
{this.props.shouldDrawLayer && (
<Layer
ref={node => (this.layer = node)}
onClick={this.props.onClick}
/>
)}
</Stage>
);
}
}
it('should remove events on unmount', function() {
const onClickRect = sinon.spy();
const onClickExternal = sinon.spy();
const wrapper = mount(<App onClick={onClickRect} shouldDrawLayer />);
instance = wrapper.instance();
const stageRef = instance.stage;
const layer = stageRef.getStage().findOne('Layer');
layer.on('click', onClickExternal);
expect(onClickRect.callCount).to.equal(0);
expect(onClickExternal.callCount).to.equal(0);
layer._fire('click', {});
expect(onClickRect.callCount).to.equal(1);
expect(onClickExternal.callCount).to.equal(1);
// remove layer
wrapper.setProps({ shouldDrawLayer: false });
expect(layer.getParent()).to.equal(null);
layer._fire('click', {});
expect(onClickRect.callCount).to.equal(1);
expect(onClickExternal.callCount).to.equal(2);
});
});
// will fail
describe.skip('Bad structure', () => {
it('No dom inside Konva', function() {
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer>
<div />
</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
const instance = wrapper.instance();
const stage = instance.stage.getStage();
});
});
// TODO: how to fix it?
// react is creating new nodes before removing old one
// that creates mess in id references
// see: https://github.com/konvajs/react-konva/issues/119
describe('Check id saving', () => {
it('Konva can loose ids?', function() {
class App extends React.Component {
render() {
const kids = [
<Rect key="1" id="rect1" fill="red" />,
<Rect key="2" id="rect2" fill="green" />
];
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer>
{this.props.drawAsGroup ? <Group>{kids}</Group> : kids}
</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
const instance = wrapper.instance();
const stage = instance.stage.getStage();
expect(stage.findOne('#rect1').fill()).to.equal('red');
expect(stage.findOne('#rect2').fill()).to.equal('green');
wrapper.setProps({ drawAsGroup: true });
expect(stage.findOne('#rect1').fill()).to.equal('red');
expect(stage.findOne('#rect2').fill()).to.equal('green');
});
});
describe('Test drawing calls', () => {
it('Draw layer on mount', function() {
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer>
<Rect fill="red" />
</Layer>
</Stage>
);
}
}
expect(Konva.Layer.prototype.batchDraw.callCount).to.equal(undefined);
sinon.spy(Konva.Layer.prototype, 'batchDraw');
const wrapper = mount(<App />);
expect(Konva.Layer.prototype.batchDraw.called).to.equal(true);
Konva.Layer.prototype.batchDraw.restore();
});
it('Draw layer on node add', function() {
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer>{this.props.showRect && <Rect fill="red" />}</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
sinon.spy(Konva.Layer.prototype, 'batchDraw');
wrapper.setProps({ showRect: true });
expect(Konva.Layer.prototype.batchDraw.callCount).to.equal(1);
Konva.Layer.prototype.batchDraw.restore();
});
it('Draw layer on node remove', function() {
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer>{!this.props.hideRect && <Rect fill="red" />}</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
sinon.spy(Konva.Layer.prototype, 'batchDraw');
expect(Konva.Layer.prototype.batchDraw.callCount).to.equal(0);
wrapper.setProps({ hideRect: true });
expect(Konva.Layer.prototype.batchDraw.callCount).to.equal(1);
Konva.Layer.prototype.batchDraw.restore();
});
});
describe('test reconciler', () => {
it('add before', function() {
class App extends React.Component {
render() {
const kids = this.props.drawMany
? [<Rect key="1" name="rect1" />, <Rect key="2" name="rect2" />]
: [<Rect key="2" name="rect2" />];
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>{kids}</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
sinon.spy(Konva.Layer.prototype, 'batchDraw');
wrapper.setProps({ drawMany: true });
const layer = wrapper.instance().layer;
expect(layer.children[0].name()).to.equal('rect1');
expect(layer.children[1].name()).to.equal('rect2');
expect(Konva.Layer.prototype.batchDraw.callCount).to.equal(1);
Konva.Layer.prototype.batchDraw.restore();
});
it('add before (mane)', function() {
class App extends React.Component {
render() {
const kids = this.props.drawMany
? [
<Rect key="1" name="rect1" />,
<Rect key="2" name="rect2" />,
<Rect key="3" name="rect3" />
]
: [<Rect key="1" name="rect1" />, <Rect key="3" name="rect3" />];
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>{kids}</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
wrapper.setProps({ drawMany: true });
const layer = wrapper.instance().layer;
expect(layer.children[0].name()).to.equal('rect1');
expect(layer.children[1].name()).to.equal('rect2');
expect(layer.children[2].name()).to.equal('rect3');
});
it('add after', function() {
class App extends React.Component {
render() {
const kids = this.props.drawMany
? [<Rect key="1" name="rect1" />, <Rect key="2" name="rect2" />]
: [<Rect key="1" name="rect1" />];
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>{kids}</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
sinon.spy(Konva.Layer.prototype, 'batchDraw');
wrapper.setProps({ drawMany: true });
const layer = wrapper.instance().layer;
expect(layer.children[0].name()).to.equal('rect1');
expect(layer.children[1].name()).to.equal('rect2');
expect(Konva.Layer.prototype.batchDraw.callCount).to.equal(1);
Konva.Layer.prototype.batchDraw.restore();
});
it('change order', function() {
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>{this.props.kids}</Layer>
</Stage>
);
}
}
let kids = [
<Rect key="1" name="rect1" />,
<Rect key="2" name="rect2" />,
<Rect key="3" name="rect3" />
];
const wrapper = mount(<App kids={kids} />);
const layer = wrapper.instance().layer;
expect(layer.children[0].name()).to.equal('rect1');
expect(layer.children[1].name()).to.equal('rect2');
expect(layer.children[2].name()).to.equal('rect3');
// last to first
kids = [
<Rect key="3" name="rect3" />,
<Rect key="1" name="rect1" />,
<Rect key="2" name="rect2" />
];
wrapper.setProps({ kids });
expect(layer.children[0].name()).to.equal('rect3');
expect(layer.children[1].name()).to.equal('rect1');
expect(layer.children[2].name()).to.equal('rect2');
// second to first
kids = [
<Rect key="1" name="rect1" />,
<Rect key="3" name="rect3" />,
<Rect key="2" name="rect2" />
];
wrapper.setProps({ kids });
expect(layer.children[0].name()).to.equal('rect1');
expect(layer.children[1].name()).to.equal('rect3');
expect(layer.children[2].name()).to.equal('rect2');
kids = [
<Rect key="2" name="rect2" />,
<Rect key="1" name="rect1" />,
<Rect key="3" name="rect3" />
];
wrapper.setProps({ kids });
expect(layer.children[0].name()).to.equal('rect2');
expect(layer.children[1].name()).to.equal('rect1');
expect(layer.children[2].name()).to.equal('rect3');
kids = [
<Rect key="4" name="rect4" />,
<Rect key="2" name="rect2" />,
<Rect key="1" name="rect1" />,
<Rect key="3" name="rect3" />
];
wrapper.setProps({ kids });
expect(layer.children[0].name()).to.equal('rect4');
expect(layer.children[1].name()).to.equal('rect2');
expect(layer.children[2].name()).to.equal('rect1');
expect(layer.children[3].name()).to.equal('rect3');
});
it('changing order should not stop dragging', function() {
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>{this.props.kids}</Layer>
</Stage>
);
}
}
let kids = [
<Rect key="1" name="rect1" />,
<Rect key="2" name="rect2" />,
<Rect key="3" name="rect3" />
];
const wrapper = mount(<App kids={kids} />);
const layer = wrapper.instance().layer;
const rect1 = layer.findOne('.rect1');
layer.getStage().simulateMouseDown({ x: 5, y: 5 });
rect1.startDrag();
// move mouse
layer.getStage().simulateMouseMove({ x: 10, y: 10 });
expect(rect1.isDragging()).to.equal(true);
kids = [
<Rect key="3" name="rect3" />,
<Rect key="1" name="rect1" />,
<Rect key="2" name="rect2" />
];
wrapper.setProps({ kids });
expect(rect1.isDragging()).to.equal(true);
rect1.stopDrag();
});
});
describe('Test context API', function() {
let instance;
const { Consumer, Provider } = React.createContext({
width: 100,
height: 100
});
class App extends React.Component {
render() {
return (
<Provider value={{ width: 200, height: 100 }}>
<Consumer>
{({ width, height }) => (
<Stage
width={width}
height={height}
ref={node => (this.stage = node)}
>
<Layer ref={node => (this.layer = node)} />
</Stage>
)}
</Consumer>
</Provider>
);
}
}
beforeEach(() => {
const wrapper = mount(<App />);
instance = wrapper.instance();
});
it('test correct set', function() {
const stageRef = instance.stage;
const stage = stageRef.getStage();
expect(stage.width()).to.equal(200);
expect(stage.height()).to.equal(100);
});
});
// wait for react team response
describe('Test nested context API', function() {
const Context = React.createContext({
color: 'red'
});
class Tools extends React.Component {
static contextType = Context;
render() {
return (
<Layer>
<Rect width={50} height={50} fill={this.context.color} />
</Layer>
);
}
}
class Canvas extends React.Component {
static contextType = Context;
render() {
return (
<Stage width={300} height={200} ref={node => (this.stage = node)}>
<Tools />
</Stage>
);
}
}
class App extends React.Component {
render() {
return (
<Context.Provider value={{ color: 'black' }}>
<Canvas />
</Context.Provider>
);
}
}
beforeEach(() => {
mount(<App />);
});
it.skip('test correct set', function() {
const stage = Konva.stages[Konva.stages.length - 1];
expect(stage.findOne('Rect').fill()).to.equal('black');
});
});
// wait for react team response
describe('try lazy and suspense', function() {
const LazyRect = React.lazy(() => {
return new Promise(resolve => {
setTimeout(() => {
resolve({
default: () => <Rect />
});
}, 5);
});
});
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>
<React.Suspense fallback={<Text text="fallback" />}>
<LazyRect />
</React.Suspense>
</Layer>
</Stage>
);
}
}
let instance;
beforeEach(() => {
const wrapper = mount(<App />);
instance = wrapper.instance();
});
it('can use lazy and suspense', function(done) {
const stageRef = instance.stage;
const stage = stageRef.getStage();
expect(stage.find('Text').length).to.equal(1);
expect(stage.find('Shape').length).to.equal(1);
setTimeout(() => {
expect(stage.find('Text').length).to.equal(0);
expect(stage.find('Rect').length).to.equal(1);
expect(stage.find('Shape').length).to.equal(1);
done();
}, 50);
});
});
describe('Fragments', function() {
const Fragmented = () => (
<React.Fragment>
<Rect />
<Rect />
</React.Fragment>
);
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>
<Fragmented />
</Layer>
</Stage>
);
}
}
let instance;
beforeEach(() => {
const wrapper = mount(<App />);
instance = wrapper.instance();
});
it('can use lazy and suspense', function() {
const stage = instance.stage;
expect(stage.find('Rect').length).to.equal(2);
});
});
describe('warnings', function() {
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer ref={node => (this.layer = node)}>
<Rect draggable x={0} y={0} />
</Layer>
</Stage>
);
}
}
it('check draggable warning', function() {
const wrapper = mount(<App />);
// sinon.spy(console, 'warning');
// expect(console.warning.callCount).to.equal(1);
});
});
describe('Hooks', function() {
it('check setState hook', function() {
const App = () => {
const [fill, setColor] = React.useState('black');
return (
<Stage width={300} height={300}>
<Layer>
<Rect
fill={fill}
width={100}
height={100}
onMouseDown={() => {
setColor('red');
}}
/>
</Layer>
</Stage>
);
};
const wrapper = mount(<App />);
const instance = wrapper.instance();
const stage = Konva.stages[Konva.stages.length - 1];
expect(stage.findOne('Rect').fill()).to.equal('black');
stage.simulateMouseDown({ x: 50, y: 50 });
expect(stage.findOne('Rect').fill()).to.equal('red');
});
it('check useEffect hook', function(done) {
let callCount = 0;
const App = () => {
React.useEffect(() => {
callCount += 1;
});
return (
<Stage width={300} height={300}>
<Layer />
</Stage>
);
};
const wrapper = mount(<App />);
// not sure why timeouts are required
// are hooks async?
setTimeout(() => {
expect(callCount).to.equal(1);
wrapper.setProps({ randomProp: 1 });
setTimeout(() => {
expect(callCount).to.equal(2);
done();
}, 50);
}, 50);
});
it('check useEffect hook 2', function(done) {
let callCount = 0;
const MyRect = ({ name }) => {
React.useEffect(() => {
callCount += 1;
});
return <Rect name={name} />;
};
const App = () => {
const [name, setName] = React.useState('');
React.useEffect(() => {
setName('rect name');
}, []);
return (
<Stage width={300} height={300}>
<Layer>
<MyRect name={name} />
</Layer>
</Stage>
);
};
const wrapper = mount(<App />);
// not sure why timeouts are required
// are hooks async?
setTimeout(() => {
const stage = Konva.stages[Konva.stages.length - 1];
const rect = stage.findOne('Rect');
expect(rect.name()).to.equal('rect name');
expect(callCount).to.equal(2);
done();
}, 50);
});
it('check useImage hook', function(done) {
const url = 'https://konvajs.org/favicon-32x32.png';
const App = () => {
const [image, status] = useImage(url);
return (
<Stage width={300} height={300}>
<Layer>
<Image image={image} />
<Text text={status} />
</Layer>
</Stage>
);
};
const wrapper = mount(<App />);
const stage = Konva.stages[Konva.stages.length - 1];
// not image while loading
expect(stage.findOne('Image').image()).to.equal(undefined);
expect(stage.findOne('Text').text()).to.equal('loading');
const img = new window.Image();
img.onload = () => {
// here should hook trigger
setTimeout(() => {
expect(stage.findOne('Image').image()).not.to.equal(undefined);
expect(stage.findOne('Text').text()).to.equal('loaded');
done();
}, 50);
};
img.src = url;
});
it('unsubscribe on unmount', function(done) {
const url = 'https://konvajs.org/favicon-32x32.png';
const App = () => {
const [image, status] = useImage(url);
return (
<Stage width={300} height={300}>
<Layer>
<Image image={image} />
<Text text={status} />
</Layer>
</Stage>
);
};
const wrapper = mount(<App />);
const stage = Konva.stages[Konva.stages.length - 1];
// not image while loading
expect(stage.findOne('Image').image()).to.equal(undefined);
expect(stage.findOne('Text').text()).to.equal('loading');
wrapper.unmount();
const img = new window.Image();
img.onload = () => {
setTimeout(() => {
// image is loaded here
// if hook is unsubcribed we should have no errors
// so just
done();
}, 50);
};
img.src = url;
});
});
describe('external', () => {
it('make sure node has _applyProps for react-spring integration', function() {
class App extends React.Component {
render() {
return (
<Stage ref={node => (this.stage = node)} width={300} height={300}>
<Layer>
<Rect fill="red" />
</Layer>
</Stage>
);
}
}
const wrapper = mount(<App />);
const instance = wrapper.instance();
const stage = instance.stage;
expect(typeof stage.findOne('Rect')._applyProps).to.equal('function');
});
});
|
import React from 'react';
import Profile_picture from '../profile_picture/Profile_picture';
import './profile_data.css';
function Profile_data({user}) {
return (
<div className = 'profile_data'>
{/* Datos : Foto Perfil + Nombre + Seguidores + Seguidos */}
{/* Imagen de perfil */}
<Profile_picture/>
{/* TODO: Conteo y guardar seguidores y seguidos */}
<h3>Seguidores: 0</h3>
<h3>Seguidos: 0</h3>
</div>
)
}
export default Profile_data
|
import Route from '@ember/routing/route';
import { get, set } from '@ember/object';
import { inject as service } from '@ember/service';
export default Route.extend({
intl: service(),
model() {
return this.modelFor('groups.group.group-page');
},
afterModel(model) {
const tags = this.setHeadTags(model);
set(this, 'headTags', tags);
},
setupController(controller) {
this._super(...arguments);
set(controller, '_addedTickets', []);
},
titleToken() {
const model = this.modelFor('groups.group.group-page');
const group = get(model, 'group.name');
return get(this, 'intl').t('titles.groups.group.group-page.leaders', { group });
},
setHeadTags(model) {
const description = `Group leaders for ${get(model, 'group.name')}.
${get(model, 'group.tagline')}`;
return [{
type: 'meta',
tagId: 'meta-description',
attrs: {
property: 'description',
content: description
}
}, {
type: 'meta',
tagId: 'meta-og-description',
attrs: {
property: 'og:description',
content: description
}
}];
}
});
|
/*global document, jQuery, window, sw, Offline */
(function ($) {
"use strict";
try {
var isUndefinedOrNull, declare_namespace;
isUndefinedOrNull = function (o) {
if (!(o === undefined || o === null)) {
return false;
}
return true;
};
declare_namespace = function (namespace) {
var obj = window;
$.each(namespace.split('.'), function (i, name) {
if (isUndefinedOrNull(obj[name])) {
obj[name] = {};
}
obj = obj[name];
});
};
Offline.options = {
checkOnLoad: true,
interceptRequests: true,
reconnect: {
initialDelay: 3,
delay: 1.5
},
requests: false,
checks: {xhr: {url: '/api/login'}},
game: false
};
declare_namespace('sw.allotmentclub');
declare_namespace('sw.flashmessage');
sw.allotmentclub.isUndefinedOrNull = isUndefinedOrNull;
sw.allotmentclub.declare_namespace = declare_namespace;
sw.allotmentclub.online = function () {
var status = Offline.state, color, message;
if (status === 'up') {
message = 'ONLINE\nKlicken, um OFFLINE zu gehen.';
color = '#8ac38b';
} else {
message = 'OFFLINE\nKlicken, um ONLINE zu gehen.';
color = '#953b39';
}
$('#online_status a').attr('style', 'color: ' + color);
$('#online_status a').attr('title', message);
if (status === 'up') {
return true;
}
return false;
};
Offline.on('up', sw.allotmentclub.online);
Offline.on('down', sw.allotmentclub.online);
sw.flashmessage.notify = function (message) {
if (!message) {
return;
}
var items = message.split(/\.(.+)?/);
$.smallBox({
title: items[0],
content: items[1],
color: "#739E73",
iconSmall: "fa fa-check",
timeout: 5000
});
};
sw.flashmessage.error = function (error) {
$.smallBox({
title: "Es ist ein Fehler aufgetreten!",
content: error,
color: "#C46A69",
icon: "fa fa-warning",
timeout: 5000
});
};
sw.flashmessage.warning = function (message) {
if (!message) {
return;
}
$.smallBox({
title: "Hinweis",
content: message,
color: "#dfb56c",
icon: "fa fa-bell",
timeout: 5000
});
};
$(document).ajaxStart(function () {
$.blockUI(
{
message: '',
onBlock: function () {
$('.pace').removeClass('pace-inactive');
},
onUnblock: function () {
$('.pace').addClass('pace-inactive');
}
}
);
}).ajaxStop($.unblockUI);
$(document).delegate('textarea.md-input', 'keydown', function (e) {
var keyCode = e.keyCode || e.which, start, end;
if (keyCode === 9) {
e.preventDefault();
start = $(this).get(0).selectionStart;
end = $(this).get(0).selectionEnd;
// set textarea value to: text before caret + 4 spaces + text after caret
$(this).val($(this).val().substring(0, start) + " " + $(this).val().substring(end));
// put caret at right position again
$(this).get(0).selectionStart = $(this).get(0).selectionEnd = start + 1;
}
});
if (typeof String.prototype.startsWith !== 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) === str;
};
}
$(document).ready(function () {
$('#online_status').click(function () {
var state = Offline.state;
if (state === 'up') {
Offline.state = 'down';
sw.allotmentclub.online();
} else {
Offline.check();
}
});
});
} catch (e) {
console.error(e);
}
}(jQuery));
|
/*+**********************************************************************************
* The contents of this file are subject to the vtiger CRM Public License Version 1.0
* ("License"); You may not use this file except in compliance with the License
* The Original Code is: vtiger CRM Open Source
* The Initial Developer of the Original Code is vtiger.
* Portions created by vtiger are Copyright (C) vtiger.
* All Rights Reserved.
************************************************************************************/
if (typeof(ImportJs) == 'undefined') {
/*
* Namespaced javascript class for Import
*/
ImportJs = {
toogleMergeConfiguration: function() {
var mergeChecked = jQuery('#auto_merge').is(':checked');
var duplicateMergeConfiguration = jQuery('#duplicates_merge_configuration');
if(mergeChecked) {
duplicateMergeConfiguration.show();
} else {
duplicateMergeConfiguration.hide();
}
},
checkFileType: function() {
var filePath = jQuery('#import_file').val();
if(filePath != '') {
var fileExtension = filePath.split('.').pop();
jQuery('#type').val(fileExtension);
ImportJs.handleFileTypeChange();
}
},
handleFileTypeChange: function() {
var fileType = jQuery('#type').val();
var delimiterContainer = jQuery('#delimiter_container');
var hasHeaderContainer = jQuery('#has_header_container');
if(fileType != 'csv') {
delimiterContainer.hide();
hasHeaderContainer.hide();
} else {
delimiterContainer.show();
hasHeaderContainer.show();
}
},
uploadAndParse: function() {
if(!ImportJs.validateFilePath()) return false;
if(!ImportJs.validateMergeCriteria()) return false;
return true;
},
registerImportClickEvent : function(){
jQuery('#importButton').on('click',function(e){
var result = ImportJs.sanitizeAndSubmit()
return result;
});
},
validateFilePath: function() {
var importFile = jQuery('#import_file');
var filePath = importFile.val();
if(jQuery.trim(filePath) == '') {
var errorMessage = app.vtranslate('JS_IMPORT_FILE_CAN_NOT_BE_EMPTY');
var params = {
text: errorMessage,
type: 'error'
};
Vtiger_Helper_Js.showMessage(params);
importFile.focus();
return false;
}
if(!ImportJs.uploadFilter("import_file", "csv|vcf")) {
return false;
}
if(!ImportJs.uploadFileSize("import_file")) {
return false;
}
return true;
},
uploadFilter: function(elementId, allowedExtensions) {
var obj = jQuery('#'+elementId);
if(obj) {
var filePath = obj.val();
var fileParts = filePath.toLowerCase().split('.');
var fileType = fileParts[fileParts.length-1];
var validExtensions = allowedExtensions.toLowerCase().split('|');
if(validExtensions.indexOf(fileType) < 0) {
var errorMessage = app.vtranslate('JS_SELECT_FILE_EXTENSION')+'\n' +validExtensions;
var params = {
text: errorMessage,
type: 'error'
};
Vtiger_Helper_Js.showMessage(params);
obj.focus();
return false;
}
}
return true;
},
uploadFileSize : function(elementId) {
var element = jQuery('#'+elementId);
var importMaxUploadSize = element.closest('td').data('importUploadSize');
var importMaxUploadSizeInMb = element.closest('td').data('importUploadSizeMb');
var uploadedFileSize = element.get(0).files[0].size;
if(uploadedFileSize > importMaxUploadSize){
var errorMessage = app.vtranslate('JS_UPLOADED_FILE_SIZE_EXCEEDS')+" "+importMaxUploadSizeInMb+ " MB." + app.vtranslate('JS_PLEASE_SPLIT_FILE_AND_IMPORT_AGAIN');
var params = {
text: errorMessage,
type: 'error'
};
Vtiger_Helper_Js.showMessage(params);
return false;
}
return true;
},
validateMergeCriteria: function() {
$mergeChecked = jQuery('#auto_merge').is(':checked');
if($mergeChecked) {
var selectedOptions = jQuery('#selected_merge_fields option');
if(selectedOptions.length == 0) {
var errorMessage = app.vtranslate('JS_PLEASE_SELECT_ONE_FIELD_FOR_MERGE');
var params = {
text: errorMessage,
'type': 'error'
};
Vtiger_Helper_Js.showMessage(params);
return false;
}
}
ImportJs.convertOptionsToJSONArray('#selected_merge_fields', '#merge_fields');
return true;
},
//TODO move to a common file
convertOptionsToJSONArray : function(objName, targetObjName) {
var obj = jQuery(objName);
var arr = [];
if(typeof(obj) != 'undefined' && obj[0] != '') {
for (i=0; i<obj[0].length; ++i) {
arr.push(obj[0].options[i].value);
}
}
if(targetObjName != 'undefined') {
var targetObj = $(targetObjName);
if(typeof(targetObj) != 'undefined') targetObj.val(JSON.stringify(arr));
}
return arr;
},
//TODO: move to a common file
copySelectedOptions : function(source, destination) {
var srcObj = jQuery(source);
var destObj = jQuery(destination);
if(typeof(srcObj) == 'undefined' || typeof(destObj) == 'undefined') return;
for (i=0;i<srcObj[0].length;i++) {
if (srcObj[0].options[i].selected == true) {
var rowFound = false;
var existingObj = null;
for (j=0;j<destObj[0].length;j++) {
if (destObj[0].options[j].value == srcObj[0].options[i].value) {
rowFound = true;
existingObj = destObj[0].options[j];
break;
}
}
if (rowFound != true) {
var opt = $('<option selected>');
opt.attr('value', srcObj[0].options[i].value);
opt.text(srcObj[0].options[i].text);
jQuery(destObj[0]).append(opt);
srcObj[0].options[i].selected = false;
rowFound = false;
} else {
if(existingObj != null) existingObj.selected = true;
}
}
}
},
//TODO move to a common file
removeSelectedOptions : function (objName) {
var obj = jQuery(objName);
if(obj == null || typeof(obj) == 'undefined') return;
for (i=obj[0].options.length-1;i>=0;i--) {
if (obj[0].options[i].selected == true) {
obj[0].options[i] = null;
}
}
},
sanitizeAndSubmit: function() {
if(!ImportJs.sanitizeFieldMapping()) return false;
if(!ImportJs.validateCustomMap()) return false;
return true;
},
sanitizeFieldMapping: function() {
var fieldsList = jQuery('.fieldIdentifier');
var mappedFields = {};
var errorMessage;
var params = {};
var mappedDefaultValues = {};
for(var i=0; i<fieldsList.length; ++i) {
var fieldElement = jQuery(fieldsList.get(i));
var rowId = jQuery('[name=row_counter]', fieldElement).get(0).value;
var selectedFieldElement = jQuery('select option:selected', fieldElement);
var selectedFieldName = selectedFieldElement.val();
var selectedFieldDefaultValueElement = jQuery('#'+selectedFieldName+'_defaultvalue', fieldElement);
var defaultValue = '';
if(selectedFieldDefaultValueElement.attr('type') == 'checkbox') {
defaultValue = selectedFieldDefaultValueElement.is(':checked');
} else {
defaultValue = selectedFieldDefaultValueElement.val();
}
if(selectedFieldName != '') {
if(selectedFieldName in mappedFields) {
errorMessage = app.vtranslate('JS_FIELD_MAPPED_MORE_THAN_ONCE')+" " + selectedFieldElement.data('label');
params = {
text: errorMessage,
'type': 'error'
};
Vtiger_Helper_Js.showMessage(params);
return false;
}
mappedFields[selectedFieldName] = rowId-1;
if(defaultValue != '') {
mappedDefaultValues[selectedFieldName] = defaultValue;
}
}
}
var mandatoryFields = JSON.parse(jQuery('#mandatory_fields').val());
var moduleName = app.getModuleName();
if(moduleName == 'PurchaseOrder' || moduleName == 'Invoice' || moduleName == 'Quotes' || moduleName == 'SalesOrder') {
mandatoryFields.hdnTaxType = app.vtranslate('Tax Type');
}
var missingMandatoryFields = [];
for(var mandatoryFieldName in mandatoryFields) {
if(mandatoryFieldName in mappedFields) {
continue;
} else {
missingMandatoryFields.push('"'+mandatoryFields[mandatoryFieldName]+'"');
}
}
if(missingMandatoryFields.length > 0) {
errorMessage = app.vtranslate('JS_MAP_MANDATORY_FIELDS')+ missingMandatoryFields.join(',');
params = {
text: errorMessage,
'type': 'error'
};
Vtiger_Helper_Js.showMessage(params);
return false;
}
jQuery('#field_mapping').val(JSON.stringify(mappedFields));
jQuery('#default_values').val(JSON.stringify(mappedDefaultValues));
return true;
},
validateCustomMap: function() {
var errorMessage;
var params = {};
var saveMap = jQuery('#save_map').is(':checked');
if(saveMap) {
var mapName = jQuery('#save_map_as').val();
if(jQuery.trim(mapName) == '') {
errorMessage = app.vtranslate('JS_MAP_NAME_CAN_NOT_BE_EMPTY');
params = {
text: errorMessage,
'type': 'error'
};
Vtiger_Helper_Js.showMessage(params);
return false;
}
var mapOptions = jQuery('#saved_maps option');
for(var i=0; i<mapOptions.length; ++i) {
var mapOption = jQuery(mapOptions.get(i));
if(mapOption.html() == mapName) {
errorMessage = app.vtranslate('JS_MAP_NAME_ALREADY_EXISTS');
params = {
text: errorMessage,
'type': 'error'
};
Vtiger_Helper_Js.showMessage(params);
return false;
}
}
}
return true;
},
loadSavedMap: function() {
var selectedMapElement = jQuery('#saved_maps option:selected');
var mapId = selectedMapElement.attr('id');
var fieldsList = jQuery('.fieldIdentifier');
var deleteMapContainer = jQuery('#delete_map_container');
fieldsList.each(function(i, element) {
var fieldElement = jQuery(element);
jQuery('[name=mapped_fields]', fieldElement).val('');
});
if(mapId == -1) {
deleteMapContainer.hide();
return;
}
deleteMapContainer.show();
var mappingString = selectedMapElement.val()
if(mappingString == '') return;
var mappingPairs = mappingString.split('&');
var mapping = {};
for(var i=0; i<mappingPairs.length; ++i) {
var mappingPair = mappingPairs[i].split('=');
var header = mappingPair[0];
header = header.replace(/\/eq\//g, '=');
header = header.replace(/\/amp\//g, '&');
mapping["'"+header+"'"] = mappingPair[1];
}
fieldsList.each(function(i, element) {
var fieldElement = jQuery(element);
var mappedFields = jQuery('[name=mapped_fields]', fieldElement);
var rowId = jQuery('[name=row_counter]', fieldElement).get(0).value;
var headerNameElement = jQuery('[name=header_name]', fieldElement).get(0);
var headerName = jQuery(headerNameElement).html();
if("'"+headerName+"'" in mapping) {
mappedFields.val(mapping["'"+headerName+"'"]);
} else if(rowId in mapping) {
mappedFields.val($rowId);
}
mappedFields.trigger('liszt:updated');
ImportJs.loadDefaultValueWidget(fieldElement.attr('id'));
});
},
deleteMap : function(module) {
if(confirm(app.vtranslate('LBL_DELETE_CONFIRMATION'))) {
var selectedMapElement = jQuery('#saved_maps option:selected');
var mapId = selectedMapElement.attr('id');
var status = jQuery('#status');
status.show();
var postData = {
"module": module,
"view": 'Import',
"mode": 'deleteMap',
"mapid": mapId
}
AppConnector.request(postData).then(
function(data){
jQuery('#savedMapsContainer').html(data);
status.hide();
var parent = jQuery("#saved_maps");
app.changeSelectElementView(parent);
},
function(error,err){
}
);
}
},
loadDefaultValueWidget: function(rowIdentifierId) {
var affectedRow = jQuery('#'+rowIdentifierId);
if(typeof affectedRow == 'undefined' || affectedRow == null) return;
var selectedFieldElement = jQuery('[name=mapped_fields]', affectedRow).get(0);
var selectedFieldName = jQuery(selectedFieldElement).val();
var defaultValueContainer = jQuery(jQuery('[name=default_value_container]', affectedRow).get(0));
var allDefaultValuesContainer = jQuery('#defaultValuesElementsContainer');
if(defaultValueContainer.children.length > 0) {
var copyOfDefaultValueWidget = jQuery(':first', defaultValueContainer).detach();
copyOfDefaultValueWidget.appendTo(allDefaultValuesContainer);
}
var selectedFieldDefValueContainer = jQuery('#'+selectedFieldName+'_defaultvalue_container', allDefaultValuesContainer);
var defaultValueWidget = selectedFieldDefValueContainer.detach();
defaultValueWidget.appendTo(defaultValueContainer);
},
loadDefaultValueWidgetForMappedFields: function() {
var fieldsList = jQuery('.fieldIdentifier');
fieldsList.each(function(i, element) {
var fieldElement = jQuery(element);
var mappedFieldName = jQuery('[name=mapped_fields]', fieldElement).val();
if(mappedFieldName != '') {
ImportJs.loadDefaultValueWidget(fieldElement.attr('id'));
}
});
}
}
jQuery(document).ready(function() {
ImportJs.toogleMergeConfiguration();
ImportJs.loadDefaultValueWidgetForMappedFields();
ImportJs.registerImportClickEvent();
});
}
|
'use strict';
/**
* @ngdoc function
* @name chofraNetflixApp.controller:DisclaimerctrlCtrl
* @description
* # DisclaimerctrlCtrl
* Controller of the chofraNetflixApp
*/
angular.module('chofraNetflixApp')
.controller('DisclaimerCtrl', ['myModals', '$rootScope', '$scope', '$location', '$timeout', '$routeParams', 'anchorSmoothScroll', function (myModals, $rootScope, $scope, $location, $timeout, $routeParams, anchorSmoothScroll) {
$scope.lang = $rootScope.lang;
$scope.close = function(){
myModals.showScreen = null;
}
$rootScope.$watch('lang', function(){
$scope.lang = $rootScope.lang;
})
}]);
|
import React from "react";
import renderer from "react-test-renderer";
import ExtraLargeTitle from "../extra-large-title";
import LargeTitle from "../large-title";
import MediumTitle from "../MediumTitle";
describe("title", () => {
it("renders extra large title correctly", () => {
const tree = renderer
.create(<ExtraLargeTitle/>)
.toJSON();
expect(tree).toMatchSnapshot();
});
it("Returns the correct extra large title 'text' prop passed in", () => {
const tree = renderer
.create(<ExtraLargeTitle text={"a title"}/>);
const testInstance = tree.root;
expect(testInstance.props.text).toBe("a title");
});
it("renders large title correctly", () => {
const tree = renderer
.create(<LargeTitle/>)
.toJSON();
expect(tree).toMatchSnapshot();
});
it("Returns the correct large title 'text' prop passed in", () => {
const tree = renderer
.create(<LargeTitle text={"a title"}/>);
const testInstance = tree.root;
expect(testInstance.props.text).toBe("a title");
});
it("renders medium title correctly", () => {
const tree = renderer
.create(<MediumTitle/>)
.toJSON();
expect(tree).toMatchSnapshot();
});
it("Returns the correct medium title 'text' prop passed in", () => {
const tree = renderer
.create(<MediumTitle text={"a title"}/>);
const testInstance = tree.root;
expect(testInstance.props.text).toBe("a title");
});
});
|
var class_y_t_music_uploader_1_1_providers_1_1_request_models_1_1_search_result_context_1_1_musicres092063fc46031c768065e3a0a4887fe5 =
[
[ "displayPriority", "d0/d41/class_y_t_music_uploader_1_1_providers_1_1_request_models_1_1_search_result_context_1_1_musicres092063fc46031c768065e3a0a4887fe5.html#a2c3d6218f8248d8c22ca74df5b6d15c9", null ],
[ "text", "d0/d41/class_y_t_music_uploader_1_1_providers_1_1_request_models_1_1_search_result_context_1_1_musicres092063fc46031c768065e3a0a4887fe5.html#af2e600efe26f751da6cbec95db72cca2", null ]
];
|
import React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@storybook/theming';
import { Link, styles } from '@storybook/design-system';
import { rgba } from 'polished';
import GatsbyLink from './GatsbyLink';
const boxLinkStyles = `
&& {
display: block;
background: ${styles.color.lightest};
border: 1px solid ${styles.color.border};
border-radius: ${styles.spacing.borderRadius.small}px;
transition: background 150ms ease-out, border 150ms ease-out, transform 150ms ease-out;
&:hover {
border-color: ${rgba(styles.color.secondary, 0.5)};
transform: translate3d(0, -3px, 0);
box-shadow: rgba(0, 0, 0, 0.08) 0 3px 10px 0;
}
&:active {
border-color: ${rgba(styles.color.secondary, 1)};
transform: translate3d(0, 0, 0);
}
}
`;
const InternalBoxLink = styled(GatsbyLink)`
${boxLinkStyles}
`;
const ExternalBoxLink = styled((props) => <Link target="_blank" rel="noopener" {...props} />)`
${boxLinkStyles}
`;
const BoxLink = ({ isInternal, to, ...rest }) =>
isInternal ? <InternalBoxLink to={to} {...rest} /> : <ExternalBoxLink href={to} {...rest} />;
BoxLink.propTypes = {
isInternal: PropTypes.bool,
to: PropTypes.string.isRequired,
};
BoxLink.defaultProps = {
isInternal: false,
};
export default BoxLink;
|
export default class Manager {
/**
* @param {Function} rollbackFn will execute when call undo or redo method. pass the stepDetail and isLastRollback for the function(require return a stepDetail to push on undo/redo stack)
* @param {Number} maxStep max stored undoList and redoList
*/
constructor(rollbackFn, maxStep = 500) {
// if (typeof undoFn !== 'function') throw new Error('not define undoFn or undoFn is not a function')
// if (typeof redoFn !== 'function') throw new Error('not define redoFn or redoFn is not a function')
if (typeof rollbackFn !== 'function') throw new Error('not define rollbackFn or rollbackFn is not a function')
// this._undoFn = undoFn
// this._redoFn = redoFn
this._rollbackFn = rollbackFn
this._maxStep = maxStep
this._undoStack = []
this._redoStack = []
}
/**
* pushes a stepDetail on the undo stack, and clears the redo stack
* @param {*} stepDetail the stepDetail to push on last of the undo stack
*/
push(stepDetail) {
if (!stepDetail) throw new Error('no stepDetail')
this._redoStack = []
this._undoStack.push(stepDetail)
if (this._undoStack.length > this._maxStep) this._undoStack.splice(0, 1)
return this
}
/**
* call once or more rollbackFn function, and push rollbackFn returns to redo stack
* @param {Number} stepNum number of undo times
*/
undo(stepNum = 1) {
if (!this.canUndo) return this
if (stepNum > this._undoStack.length) stepNum = this._undoStack.length
let stepDetail = this._rollbackFn(this._undoStack[this._undoStack.length - 1], stepNum === 1)
this._undoStack.pop()
if (!stepDetail) throw new Error('the rollbackFn not return a stepDetail, manager can not be work well')
this._redoStack.push(stepDetail)
if (stepNum > 1) this.undo(stepNum - 1)
return this
}
/**
* call once or more rollbackFn function, and push rollbackFn returns to undo stack
* @param {Number} stepNum number of redo times
*/
redo(stepNum = 1) {
if (!this.canRedo) return this
if (stepNum > this._redoStack.length) stepNum = this._redoStack.length
this._undoStack.push(this._rollbackFn(this._redoStack[this._redoStack.length - 1], stepNum === 1))
this._redoStack.pop()
if (stepNum > 1) this.redo(stepNum - 1)
return this
}
/**
* clear undo stack and redo stack
*/
clear() {
this._undoStack = []
this._redoStack = []
}
get canUndo() {
return !!this._undoStack.length
}
get canRedo() {
return !!this._redoStack.length
}
get undoStack() {
return this._undoStack
}
get redoStack() {
return this._redoStack
}
}
|
import * as core from '@pluralsight/ps-design-system-core'
import * as vars from '../vars/index.js'
export default {
'.psds-banner': {
display: 'flex',
alignItems: 'flex-start',
width: '100%',
overflow: 'hidden',
fontSize: core.type.fontSizeSmall,
lineHeight: core.type.lineHeightStandard,
fontWeight: core.type.fontWeightMedium,
padding: `${core.layout.spacingXSmall} ${core.layout.spacingSmall}`
},
[`.psds-banner--color-${vars.colors.blue}`]: {
color: core.colors.white,
backgroundColor: core.colors.blue
},
[`.psds-banner--color-${vars.colors.green}`]: {
color: core.colors.white,
backgroundColor: core.colors.green
},
[`.psds-banner--color-${vars.colors.yellow}`]: {
color: core.colors.black,
backgroundColor: core.colors.yellow
},
[`.psds-banner--color-${vars.colors.red}`]: {
color: core.colors.white,
backgroundColor: core.colors.red
},
'.psds-banner__button': {
'&:hover, &:active, &:focus': {
transition: `all ${core.motion.speedNormal}`,
opacity: '0.65'
}
},
'.psds-banner__text': {
flex: '1',
textAlign: 'center',
'& a': {
color: 'inherit',
cursor: 'pointer',
textDecoration: 'underline',
'&:hover, &:active, &:focus': {
color: 'inherit',
transition: `all ${core.motion.speedNormal}`,
opacity: '0.65'
}
}
},
'.psds-banner__dismiss': {
position: 'relative',
display: 'flex',
alignItems: 'flex-start',
background: 'none',
border: 'none',
marginLeft: core.layout.spacingSmall,
padding: '0',
color: 'currentColor',
cursor: 'pointer',
'&:hover, &:focus, &:active': {
outline: 'none',
borderRadius: '2px',
boxShadow: '0 0 2px currentColor, inset 0 0 2px currentColor'
}
}
}
|
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/schedule-tracing.profiling.min.js');
} else {
module.exports = require('./cjs/schedule-tracing.development.js');
}
|
/* @flow */
/*eslint-disable no-undef, no-unused-vars, no-console*/
import _, {
compose,
pipe,
curry,
filter,
find,
reduce,
repeat,
subtract,
zipWith
} from "ramda";
const ns: Array<number> = [1, 2, 3, 4, 5];
const ss: Array<string> = ["one", "two", "three", "four"];
const obj: { [k: string]: number } = { a: 1, c: 2 };
const objMixed: { [k: string]: mixed } = { a: 1, c: "d" };
const os: Array<{ [k: string]: number | string }> = [
{ a: 1, c: "d" },
{ b: 2 }
];
const str: string = "hello world";
// List
{
const xs: Array<number> = _.adjust(x => x + 1, 2, ns);
const xs1: Array<number> = _.adjust(x => x + 1, 2)(ns);
//$ExpectError
const xs3: Array<string> = _.adjust(x => x + 1)(2)(ns);
const as: boolean = _.all(x => x > 1, ns);
const asf: (s: Array<string>) => boolean = _.any(x => x.length > 1);
const as1: boolean = asf(ss);
const aps: Array<Array<number>> = _.aperture(2, ns);
const aps2: Array<Array<string>> = _.aperture(2)(ss);
const newXs: Array<string> = _.append("one", ss);
const newXs1: Array<number> = _.prepend(1)(ns);
const concatxs1: Array<number> = _.concat([4, 5, 6], [1, 2, 3]);
const concatxs2: string = _.concat("ABC", "DEF");
const cont1: boolean = _.contains("s", ss);
const dropxs: Array<string> = _.drop(4, ss);
const dropxs1: string = _.drop(3)(str);
const dropxs2: Array<string> = _.dropLast(4, ss);
const dropxs3: string = _.dropLast(3)(str);
const dropxs4: Array<number> = _.dropLastWhile(x => x <= 3, ns);
const dropxs5: Array<string> = _.dropRepeats(ss);
const dropxs6: Array<number> = _.dropRepeatsWith(_.eqBy(Math.abs), ns);
const dropxs7: Array<number> = _.dropWhile(x => x === 1, ns);
const findxs: ?{ [k: string]: number | string } = _.find(
_.propEq("a", 2),
os
);
const findxs1: ?{ [k: string]: number | string } = _.find(_.propEq("a", 4))(
os
);
// Ramda doesn't strictly break if you pass it an object, but it always
// returns undefined.
// $ExpectError
const findObj = find(o => o == "bar", { foo: "bar" });
const findxs2: ?{ [k: string]: number | string } = _.findLast(
_.propEq("a", 2),
os
);
const findxs3: ?{ [k: string]: number | string } = _.findLast(
_.propEq("a", 4)
)(os);
const findxs4: number = _.findIndex(_.propEq("a", 2), os);
const findxs5: number = _.findIndex(_.propEq("a", 4))(os);
const findxs6: number = _.findLastIndex(_.propEq("a", 2), os);
const findxs7: number = _.findLastIndex(_.propEq("a", 4))(os);
const s: Array<number> = filter(x => x > 1, [1, 2]);
const s1: Array<string> = _.filter(x => x === "2", ["2", "3"]);
const s3: { [key: string]: string } = _.filter(x => x === "2", {
a: "2",
b: "3"
});
const s4 = _.find(x => x === "2", ["1", "2"]);
//$ExpectError
const s5: ?{ [key: string]: string } = _.find(x => x === "2", { a: 1, b: 2 });
const s6: number = _.findIndex(x => x === "2", ["1", "2"]);
const s7: number = _.findIndex(x => x === "2", { a: "1", b: "2" });
const forEachxs = _.forEach(x => console.log(x), ns);
const forEachObj = _.forEachObjIndexed((value, key) => {}, { x: 1, y: 2 });
const groupedBy: { [k: string]: Array<number> } = _.groupBy(
x => (x > 1 ? "more" : "less"),
ns
);
//$ExpectError
const groupedBy1: { [k: string]: Array<string> } = _.groupBy(
x => (x > 1 ? "more" : "less")
)(ns);
const groupedWith: Array<Array<number>> = _.groupWith(x => x > 1, ns);
const groupedWith1: Array<Array<string>> = _.groupWith(x => x === "one")(ss);
const xOfXs: ?number = _.head(ns);
const xOfXs2: ?number = _.head(ns);
const xOfStr: string = _.head(str);
const transducer = _.compose(_.map(_.add(1)), _.take(2));
const txs: Array<number> = _.into([], transducer, ns);
//$ExpectError
const txs1: string = _.into([], transducer, ns);
//$ExpectError
const txs2: string = _.into([], transducer, ss);
const ind: number = _.indexOf(1, ns);
const ind1: number = _.indexOf(str)(ss);
const ind2: { [key: string]: { [k: string]: number | string } } = _.indexBy(
x => "s",
os
);
const ind3: { [key: string]: { [k: string]: number | string } } = _.indexBy(
x => "s"
)(os);
const ind4: number = _.indexOf(null)(ss);
const insxs: Array<number> = _.insert(1, 2, ns);
const insxs2: Array<string> = _.insert(1, "2", ss);
const insxs3: Array<number> = _.insertAll(1, [2, 3], ns);
// this is disgusting — don't do this :)
// Technically it's a tuple with arbitrary size
const insxs4: Array<number | boolean | string> = _.insertAll(
1,
["2", false],
ns
);
const insxs5: Array<string | number> = _.insertAll(1, [2], ss);
const joinxs: string = _.join("|", ns);
const lastxs: ?number = _.last(ns);
const laststr: string = _.last(str);
const lasti: number = _.lastIndexOf(3, [-1, 3, 3, 0, 1, 2, 3, 4]);
const mapxs: Array<number> = _.map(x => x + 1, ns);
const functor = {
x: 1,
map(f) {
return f(this.x);
}
};
// Doesn't typecheck (yet) but at least doesn't break
const mapFxs = _.map(_.toString, functor);
const double = x => x * 2;
const dxs: Array<number> = _.map(double, [1, 2, 3]);
const dos: $Shape<typeof obj> = _.map(double, obj);
const appender = (a, b) => [a + b, a + b];
const mapacc: [number, Array<number>] = _.mapAccum(appender, 0, ns);
const mapacc1: [number, Array<number>] = _.mapAccumRight(appender, 0, ns);
const nxs: boolean = _.none(x => x > 1, ns);
const nthxs: ?string = _.nth(2, ["curry"]);
const nthxs1: ?string = _.nth(2)(["curry"]);
//$ExpectError
const nthxs2: string = _.nth(2, [1, 2, 3]);
const xxs: Array<number> = _.append(1, [1, 2, 3]);
const xxxs: Array<number> = _.intersperse(1, [1, 2, 3]);
const pairxs: [number, string] = _.pair(2, "str");
const partxs: [Array<string>, Array<string>] = _.partition(_.contains("s"), [
"sss",
"ttt",
"foo",
"bars"
]);
const partxs1: [
{ [k: string]: string },
{ [k: string]: string }
] = _.partition(_.contains("s"), { a: "sss", b: "ttt", foo: "bars" });
const pl: Array<number | string> = _.pluck("a")([{ a: "1" }, { a: 2 }]);
const pl1: Array<number> = _.pluck(0)([[1, 2], [3, 4]]);
const rxs: Array<number> = _.range(1, 10);
const remxs: Array<string> = _.remove(0, 2, ss);
const remxs1: Array<string> = _.remove(0, 2)(ss);
const remxs2: Array<string> = _.remove(0)(2)(ss);
const remxs3: Array<string> = _.remove(0)(2, ss);
const ys4: Array<string> = _.repeat("1", 10);
const ys5: Array<number> = _.repeat(1, 10);
// reduce
const redxs: number = reduce(_.add, 10, ns);
const redxs1: string = reduce(_.concat, "", ss);
const redxs2: Array<string> = reduce(_.concat, [])(_.map(x => [x], ss));
// Example used in docs: http://ramdajs.com/docs/#reduce
const redxs4: number = reduce(subtract, 0, [1, 2, 3, 4]);
// Using accumulator type that differs from the element type (A and B).
const redxs5: number = reduce((acc, s) => acc + parseInt(s), 0, [
"1",
"2",
"3"
]);
// Ramda works with $ReadOnlyArray as it is immutable.
const readOnlyArray: $ReadOnlyArray<number> = [1, 2, 3, 4];
// $ReadOnlyArray with curried permutations:
const redxsReadOnly3: number = reduce(subtract, 0, readOnlyArray);
const redxsReadOnly2_1: number = reduce(subtract, 0)(readOnlyArray);
const redxsReadOnly1_2: number = reduce(subtract)(0, readOnlyArray);
const redxsReadOnly1_1_1: number = reduce(subtract)(0)(readOnlyArray);
// $ExpectError reduce will not work with an object.
reduce(subtract, 0, { foo: 1, bar: 2 });
// reduceRight
const redrxs1: number = _.reduceRight(_.add, 10, ns);
const redrxs2: string = _.reduceRight(_.concat, "", ss);
const redrxs3: Array<string> = _.reduceRight(_.concat, [])(
_.map(x => [x], ss)
);
//$ExpectError
const redrxs3a: string = _.reduceRight(
(acc: string, value: number): string => acc,
"",
ns
);
const redrxs3b: string = _.reduceRight(
(value: number, acc: string): string => acc,
"",
ns
);
const scanxs6: Array<number> = _.scan(_.add)(10)(ns);
const scanxs7: Array<number> = _.scan(_.add, 10)(ns);
const scanxs8: Array<number> = _.scan(_.add)(10, ns);
const scanxs9: Array<number> = _.scan(_.add, 10, ns);
const scanxs10: Array<string> = _.scan(_.concat)("")(ss);
const scanxs11: Array<string> = _.scan(_.concat, "")(ss);
const scanxs12: Array<string> = _.scan(_.concat)("", ss);
const scanxs13: Array<string> = _.scan(_.concat, "", ss);
const reduceToNamesBy = _.reduceBy(
(acc, student) => acc.concat(student.name),
[]
);
const namesByGrade = reduceToNamesBy(student => {
const score = student.score;
return score < 65
? "F"
: score < 70 ? "D" : score < 80 ? "C" : score < 90 ? "B" : "A";
});
const students = [
{ name: "Lucy", score: 92 },
{ name: "Drew", score: 85 },
{ name: "Bart", score: 62 }
];
const names1: { [k: string]: Array<string> } = namesByGrade(students);
const spl: Array<string> = _.split(/\./, "a.b.c.xyz.d");
const spl1: [Array<number>, Array<number>] = _.splitAt(1, [1, 2, 3]);
const spl2: [string, string] = _.splitAt(5, "hello world");
const spl3: [string, string] = _.splitAt(-1, "foobar");
const spl4: Array<Array<number>> = _.splitEvery(3, [1, 2, 3, 4, 5, 6, 7]);
const spl5: Array<string> = _.splitEvery(3, "foobarbaz");
const spl6: [Array<number>, Array<number>] = _.splitWhen(_.equals(2))([
1,
2,
3,
1,
2,
3
]);
const slixs: Array<string> = _.slice(0, 2, ss);
const slixs1: Array<string> = _.slice(0, 2)(ss);
const slixs2: Array<string> = _.slice(0)(2)(ss);
const slixs3: Array<string> = _.slice(0)(2, ss);
const diff = function(a, b) {
return a - b;
};
const sortxs: Array<number> = _.sort(diff, [4, 2, 7, 5]);
const timesxs: Array<number> = _.times(_.identity, 5);
const unf: (x: string) => Array<string> = _.unfold(
(x: string) => x.length > 10 || [x, x + "0"]
);
const unf1: Array<number> = _.unfold(x => x > 10 || [x, x + 1], 0);
const f = n => (n > 50 ? false : [-n, n + 10]);
const unf11: Array<number> = _.unfold(f, 10);
//$ExpectError
const unf2 = _.unfold(x => x.length > 10 || [x, x + "0"], 2);
const unby: Array<number> = _.uniqBy(Math.abs)([-1, -5, 2, 10, 1, 2]);
const strEq = _.eqBy(String);
const strEq2 = _.eqBy(String, 1, 2);
const unw = _.uniqWith(strEq)([1, "1", 2, 1]);
const unw1 = _.uniqWith(strEq)([{}, {}]);
const unw2 = _.uniqWith(strEq)([1, "1", 1]);
const unw3 = _.uniqWith(strEq)(["1", 1, 1]);
//$ExpectError
const ys6: { [key: string]: string } = _.fromPairs([["h", 2]]);
const withoutxs: Array<number> = _.without([1, 2], ns);
const withoutxs1: Array<string> = _.without(["a"], ss);
const xprodxs: Array<[number, string]> = _.xprod([1, 2], ["a", "b", "c"]);
const xprodxs1: Array<[boolean, string]> = _.xprod([true, false])(["a", "b"]);
const zipxs: Array<[number, string]> = _.zip([1, 2, 3], ["a", "b", "c"]);
//$ExpectError
const zipxs1: Array<[number, string]> = _.zip([true, false])(["a", "b"]);
const zipos: { [k: string]: number } = _.zipObj(["a", "b", "c"], [1, 2, 3]);
const ys9: { [k: string]: number } = _.zipObj(["me", "you"], [1, 2]);
const zipped: Array<{ s: number, y: string }> = zipWith(
(a, b) => ({ s: a, y: b }),
[1, 2, 3],
["1", "2", "3"]
);
const zipped2: Array<{ s: number, y: string }> = _.zipWith(
(a, b) => ({ s: a, y: b }),
[1, 2, 3]
)(["1", "2", "3"]);
const zipped3: Array<{ s: number, y: string }> = _.zipWith((a, b) => ({
s: a,
y: b
}))([1, 2, 3])(["1", "2", "3"]);
}
|
import './row.sass'
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Checkbox from 'controls/checkbox/Checkbox';
import request from 'actions/request';
const columns = [
{ attribute: 'start', style: 'col-sm-1' },
{ attribute: 'end', style: 'col-sm-1' },
{ attribute: 'duration', style: 'col-sm-1' },
{ attribute: 'code', style: 'col-sm-1' },
{ attribute: 'comment', style: 'col-sm-2' },
{ attribute: 'algText', style: 'col-sm-1' },
{ attribute: 'excAditionalInfo', style: 'col-sm-2' },
{ attribute: 'reliability', style: 'col-sm-1' },
{ attribute: 'userComment', style: 'col-sm-2' },
];
const columnsShort = [
{ attribute: 'sample', style: 'col-sm-2' },
{ attribute: 'duration', style: 'col-sm-2' },
{ attribute: 'code', style: 'col-sm-2' },
{ attribute: 'comment', style: 'col-sm-3' },
{ attribute: 'excAditionalInfo', style: 'col-sm-3' },
];
const coloredStatuses = ['c', 'd', 'e'];
class Row extends Component {
constructor(props) {
super(props);
this.state = {
isChecked: props.item.reliability ? 'checked' : ''
}
this.isShort = props.isShort || false
}
handleClick(eventId, eventType) {
let boolValue = (this.state.isChecked === '');
this.setState({
isChecked: boolValue ? 'checked' : ''
});
this.props.request(
['flightEvents', 'changeReliability'],
'post',
'CHANGE_EVENT_RELIABILITY',
{
flightId: this.props.flightId,
eventId: eventId,
eventType: eventType,
reliability: boolValue
}
);
}
buildCheckbox(item) {
let eventId = item.id;
let eventType = item.eventType;
return <Checkbox
checkstate={ this.state.isChecked }
changeCheckState={ this.handleClick.bind(this, eventId, eventType) }
/>
}
buildCellContent(item, attribute) {
if (attribute === 'reliability') {
return this.buildCheckbox(item);
}
if (attribute === 'sample') {
return <div>
<div>{ item.start } </div>
<div>{ item.end } </div>
</div>
}
return <span>{ item[attribute] }</span>
}
buildCells(item) {
let columnsToBuild = this.isShort ? columnsShort : columns;
return columnsToBuild.map((col, colIndex) => {
return (
<div key={ colIndex } className={ 'flight-events-row__cell ' + col.style }>
{ this.buildCellContent(item, col.attribute) }
</div>
);
})
}
getStatusClass(status) {
status = status.toLowerCase();
if (coloredStatuses.indexOf(status) >= 0) {
return 'flight-events-row-' + status;
}
return '';
}
render() {
return (
<div
className={
'flight-events-row row '
+ this.getStatusClass(this.props.item.status)
}
>
{ this.buildCells(this.props.item) }
</div>
);
}
}
Row.propTypes = {
flightId: PropTypes.number.isRequired,
item: PropTypes.object.isRequired,
columns: PropTypes.array,
isShort: PropTypes.bool
};
function mapStateToProps() {
return {};
}
function mapDispatchToProps(dispatch) {
return {
request: bindActionCreators(request, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Row);
|
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoid2Vla2RheS5pbnRlcmZhY2UuanMiLCJzb3VyY2VSb290Ijoibmc6Ly9uZy11aWtpdC1wcm8tc3RhbmRhcmQvIiwic291cmNlcyI6WyJsaWIvcHJvL2RhdGUtcGlja2VyL2ludGVyZmFjZXMvd2Vla2RheS5pbnRlcmZhY2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBpbnRlcmZhY2UgSU15V2Vla2RheSB7XHJcbiAgbnVtYmVyOiBudW1iZXI7XHJcbiAgd2Vla2RheTogc3RyaW5nO1xyXG59XHJcbiJdfQ==
|
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["pages-Order-Orderpages-PaySuccessful"],{"187c":function(n,a,t){"use strict";var r;t.r(a);var e,s=function(){var n=this,a=n.$createElement,r=n._self._c||a;return r("v-uni-view",{staticClass:"PaySunc"},[r("v-uni-view",{staticClass:"PaySunc_img"},[r("v-uni-image",{staticClass:"PaySunc_img",attrs:{src:t("e900")}}),r("v-uni-text",{staticClass:"PaySunc_text"},[n._v("支付成功")])],1),r("v-uni-view",{staticClass:"flish_btn"},[n._v("完成")])],1)},i=[],c=(t("c703"),t("f0c5")),u={},o=Object(c["a"])(u,s,i,!1,null,"51ae2085",null,!1,r,e);a["default"]=o.exports},"8fa1":function(n,a,t){var r=t("b6ce");"string"===typeof r&&(r=[[n.i,r,""]]),r.locals&&(n.exports=r.locals);var e=t("4f06").default;e("7cc90daa",r,!0,{sourceMap:!1,shadowMode:!1})},b6ce:function(n,a,t){var r=t("24fb");a=r(!1),a.push([n.i,'@charset "UTF-8";\r\n/**\r\n * 这里是uni-app内置的常用样式变量\r\n *\r\n * uni-app 官方扩展插件及插件市场(https://ext.dcloud.net.cn)上很多三方插件均使用了这些样式变量\r\n * 如果你是插件开发者,建议你使用scss预处理,并在插件代码中直接使用这些变量(无需 import 这个文件),方便用户通过搭积木的方式开发整体风格一致的App\r\n *\r\n */\r\n/**\r\n * 如果你是App开发者(插件使用者),你可以通过修改这些变量来定制自己的插件主题,实现自定义主题功能\r\n *\r\n * 如果你的项目同样使用了scss预处理,你也可以直接在你的 scss 代码中使用如下变量,同时无需 import 这个文件\r\n */\r\n/* 颜色变量 */\r\n/* 行为相关颜色 */\r\n/* 文字基本颜色 */\r\n/* 背景颜色 */\r\n/* 边框颜色 */\r\n/* 尺寸变量 */\r\n/* 文字尺寸 */\r\n/* 图片尺寸 */\r\n/* Border Radius */\r\n/* 水平间距 */\r\n/* 垂直间距 */\r\n/* 透明度 */\r\n/* 文章场景相关 */.PaySunc[data-v-51ae2085]{text-align:center;color:#666}.PaySunc .PaySunc_img[data-v-51ae2085]{width:%?500?%;height:%?500?%;margin:auto}.PaySunc .PaySunc_text[data-v-51ae2085]{position:relative;top:%?-60?%}.PaySunc .flish_btn[data-v-51ae2085]{width:%?180?%;height:%?56?%;line-height:%?56?%;-webkit-border-radius:%?12?%;border-radius:%?12?%;border:1px solid #333;margin:%?160?% auto 0}',""]),n.exports=a},c703:function(n,a,t){"use strict";var r=t("8fa1"),e=t.n(r);e.a},e900:function(n,a,t){n.exports=t.p+"static/img/zhifu_zhifuchenggong.0cb97b97.png"}}]);
|
/*
jQWidgets v3.5.0 (2014-Sep-15)
Copyright (c) 2011-2014 jQWidgets.
License: http://jqwidgets.com/license/
*/
(function(a){a.jqx.jqxWidget("jqxValidator","",{});a.extend(a.jqx._jqxValidator.prototype,{defineInstance:function(){var b={rules:null,scroll:true,focus:true,scrollDuration:300,scrollCallback:null,position:"right",arrow:true,animation:"fade",animationDuration:150,closeOnClick:true,onError:null,onSuccess:null,ownerElement:null,_events:["validationError","validationSuccess"],hintPositionOffset:5,_inputHint:[],rtl:false,hintType:"tooltip"};a.extend(true,this,b)},createInstance:function(){if(this.hintType=="label"&&this.animationDuration==150){this.animationDuration=0}this._configureInputs();this._removeEventListeners();this._addEventListeners()},destroy:function(){this._removeEventListeners();this.hide()},validate:function(p){var b=true,o,e=Infinity,h,g,c,j=[],n;this.updatePosition();var k=this;var d=0;for(var f=0;f<this.rules.length;f+=1){if(typeof this.rules[f].rule==="function"){d++}}this.positions=new Array();for(var f=0;f<this.rules.length;f+=1){var m=a(this.rules[f].input);if(typeof this.rules[f].rule==="function"){var l=function(r,q){o=r;if(false==o){b=false;var i=a(q.input);c=a(q.input);j.push(c);h=c.offset().top;if(e>h){e=h;g=c}}d--;if(d==0){if(typeof p==="function"){k._handleValidation(b,e,g,j);if(p){p(b)}}}};this._validateRule(this.rules[f],l)}else{o=this._validateRule(this.rules[f])}if(false==o){b=false;c=a(this.rules[f].input);j.push(c);h=c.offset().top;if(e>h){e=h;g=c}}}if(d==0){this._handleValidation(b,e,g,j);return b}else{return undefined}},validateInput:function(b){var e=this._getRulesForInput(b),d=true;for(var c=0;c<e.length;c+=1){if(!this._validateRule(e[c])){d=false}}return d},hideHint:function(b){var d=this._getRulesForInput(b);for(var c=0;c<d.length;c+=1){this._hideHintByRule(d[c])}},hide:function(){var c;for(var b=0;b<this.rules.length;b+=1){c=this.rules[b];this._hideHintByRule(this.rules[b])}},updatePosition:function(){var c;this.positions=new Array();for(var b=0;b<this.rules.length;b+=1){c=this.rules[b];if(c.hint){this._hintLayout(c.hint,a(c.input),c.position,c)}}},_getRulesForInput:function(b){var d=[];for(var c=0;c<this.rules.length;c+=1){if(this.rules[c].input===b){d.push(this.rules[c])}}return d},_validateRule:function(f,i){var b=a(f.input),h,e=true;var d=this;var g=function(k){if(!k){var j=d.animation;d.animation=null;if(f.hint){d._hideHintByRule(f)}h=f.hintRender.apply(d,[f.message,b]);d._hintLayout(h,b,f.position,f);d._showHint(h);f.hint=h;d._removeLowPriorityHints(f);if(i){i(false,f)}d.animation=j}else{d._hideHintByRule(f);if(i){i(true,f)}}};var c=false;if(typeof f.rule==="function"){c=f.rule.call(this,b,g);if(c==true&&i){i(true,f)}}if(typeof f.rule==="function"&&c==false){if(typeof f.hintRender==="function"&&!f.hint&&!this._higherPriorityActive(f)&&b.is(":visible")){h=f.hintRender.apply(this,[f.message,b]);this._removeLowPriorityHints(f);this._hintLayout(h,b,f.position,f);this._showHint(h);f.hint=h}e=false;if(i){i(false,f)}}else{this._hideHintByRule(f)}return e},_hideHintByRule:function(e){var c=a(e.input);var b=this,f;var d=function(){if(b.hintType!="label"){return}var g=b;if(g.position=="top"||g.position=="left"){if(c.prev().hasClass(".jqx-validator-error-label")){return}}else{if(c.next().hasClass(".jqx-validator-error-label")){return}}if(c[0].nodeName.toLowerCase()!="input"){if(c.find("input").length>0){if(c.find(".jqx-input").length>0){c.find(".jqx-input").removeClass(g.toThemeProperty("jqx-validator-error-element"))}else{if(c.is(".jqx-checkbox")){c.find(".jqx-checkbox-default").removeClass(g.toThemeProperty("jqx-validator-error-element"))}}if(c.is(".jqx-radiobutton")){c.find(".jqx-radiobutton-default").removeClass(g.toThemeProperty("jqx-validator-error-element"))}else{c.removeClass(g.toThemeProperty("jqx-validator-error-element"))}}}else{c.removeClass(g.toThemeProperty("jqx-validator-error-element"))}};if(e){f=e.hint;if(f){if(this.positions){if(this.positions[Math.round(f.offset().top)+"_"+Math.round(f.offset().left)]){this.positions[Math.round(f.offset().top)+"_"+Math.round(f.offset().left)]=null}}if(this.animation==="fade"){f.fadeOut(this.animationDuration,function(){f.remove();d()})}else{f.remove();d()}}e.hint=null}},_handleValidation:function(b,e,d,c){if(!b){this._scrollHandler(e);if(this.focus){d.focus()}this._raiseEvent(0,{invalidInputs:c});if(typeof this.onError==="function"){this.onError(c)}}else{this._raiseEvent(1);if(typeof this.onSuccess==="function"){this.onSuccess()}}},_scrollHandler:function(c){if(this.scroll){var b=this;a("html,body").animate({scrollTop:c},this.scrollDuration,function(){if(typeof b.scrollCallback==="function"){b.scrollCallback.call(b)}})}},_higherPriorityActive:function(d){var e=false,c;for(var b=this.rules.length-1;b>=0;b-=1){c=this.rules[b];if(e&&c.input===d.input&&c.hint){return true}if(c===d){e=true}}return false},_removeLowPriorityHints:function(d){var e=false,c;for(var b=0;b<this.rules.length;b+=1){c=this.rules[b];if(e&&c.input===d.input){this._hideHintByRule(c)}if(c===d){e=true}}},_getHintRuleByInput:function(b){var d;for(var c=0;c<this.rules.length;c+=1){d=this.rules[c];if(a(d.input)[0]===b[0]&&d.hint){return d}}return null},_removeEventListeners:function(){var f,b,e;for(var d=0;d<this.rules.length;d+=1){f=this.rules[d];e=f.action.split(",");b=a(f.input);for(var c=0;c<e.length;c+=1){this.removeHandler(b,a.trim(e[c])+".jqx-validator")}}},_addEventListeners:function(){var f,c;if(this.host.parents(".jqx-window").length>0){var b=this;var g=function(){b.updatePosition()};var e=this.host.parents(".jqx-window");this.addHandler(e,"closed",function(){b.hide()});this.addHandler(e,"moved",g);this.addHandler(e,"moving",g);this.addHandler(e,"resized",g);this.addHandler(e,"resizing",g);this.addHandler(a(document.parentWindow),"scroll",function(){if(b.scroll){g()}})}for(var d=0;d<this.rules.length;d+=1){f=this.rules[d];c=a(f.input);this._addListenerTo(c,f)}},_addListenerTo:function(c,h){var b=this,f=h.action.split(",");var e=false;if(this._isjQWidget(c)){e=true}for(var d=0;d<f.length;d+=1){var g=a.trim(f[d]);if(e&&(g=="blur"||g=="focus")){if(c&&c[0].nodeName.toLowerCase()!="input"){c=c.find("input")}}this.addHandler(c,g+".jqx-validator",function(i){b._validateRule(h)})}},_configureInputs:function(){var b,d;this.rules=this.rules||[];for(var c=0;c<this.rules.length;c+=1){this._handleInput(c)}},_handleInput:function(b){var c=this.rules[b];if(!c.position){c.position=this.position}if(!c.message){c.message="Validation Failed!"}if(!c.action){c.action="blur"}if(!c.hintRender){c.hintRender=this._hintRender}if(!c.rule){c.rule=null}else{this._handleRule(c)}},_handleRule:function(f){var c=f.rule,e,d,b=false;if(typeof c==="string"){if(c.indexOf("=")>=0){c=c.split("=");d=c[1].split(",");c=c[0]}e=this["_"+c];if(e){f.rule=function(g,h){return e.apply(this,[g].concat(d))}}else{b=true}}else{if(typeof c!=="function"){b=true}else{f.rule=c}}if(b){throw new Error("Wrong parameter!")}},_required:function(b){switch(this._getType(b)){case"textarea":case"password":case"jqx-input":case"text":var d=a.data(b[0]);if(d.jqxMaskedInput){var e=b.jqxMaskedInput("promptChar"),c=b.jqxMaskedInput("value");return c&&c.indexOf(e)<0}else{if(d.jqxNumberInput){return b.jqxNumberInput("inputValue")!==""}else{if(d.jqxDateTimeInput){return true}else{return a.trim(b.val())!==""}}}case"checkbox":return b.is(":checked");case"radio":return b.is(":checked");case"div":if(b.is(".jqx-checkbox")){return b.jqxCheckBox("checked")}if(b.is(".jqx-radiobutton")){return b.jqxRadioButton("checked")}return false}return false},_notNumber:function(b){return this._validateText(b,function(d){if(d==""){return true}var c=/\d/;return !c.test(d)})},_startWithLetter:function(b){return this._validateText(b,function(d){if(d==""){return true}var c=/\d/;return !c.test(d.substring(0,1))})},_number:function(b){return this._validateText(b,function(d){if(d==""){return true}var c=new Number(d);return !isNaN(c)&&isFinite(c)})},_phone:function(b){return this._validateText(b,function(d){if(d==""){return true}var c=/^\(\d{3}\)(\d){3}-(\d){4}$/;return c.test(d)})},_length:function(c,d,b){return this._minLength(c,d)&&this._maxLength(c,b)},_maxLength:function(c,b){b=parseInt(b,10);return this._validateText(c,function(d){return d.length<=b})},_minLength:function(c,b){b=parseInt(b,10);return this._validateText(c,function(d){return d.length>=b})},_email:function(b){return this._validateText(b,function(d){if(d==""){return true}var c=/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;return c.test(d)})},_zipCode:function(b){return this._validateText(b,function(d){if(d==""){return true}var c=/^(^\d{5}$)|(^\d{5}-\d{4}$)|(\d{3}-\d{2}-\d{4})$/;return c.test(d)})},_ssn:function(b){return this._validateText(b,function(d){if(d==""){return true}var c=/\d{3}-\d{2}-\d{4}/;return c.test(d)})},_validateText:function(b,d){var c;if(this._isTextInput(b)){if(this._isjQWidget(b)){if(b.find("input").length>0){c=b.find("input").val()}else{c=b.val()}}else{c=b.val()}return d(c)}return false},_isjQWidget:function(b){var c=a.data(b[0]);if(c.jqxMaskedInput||c.jqxNumberInput||c.jqxDateTimeInput){return true}return false},_isTextInput:function(b){var c=this._getType(b);return c==="text"||c==="textarea"||c==="password"||b.is(".jqx-input")},_getType:function(c){var b=c[0].tagName.toLowerCase(),d;if(b==="textarea"){return"textarea"}else{if(c.is(".jqx-input")){return"jqx-input"}else{if(b==="input"){d=a(c).attr("type")?a(c).attr("type").toLowerCase():"text";return d}}}return b},_hintRender:function(e,c){if(this.hintType=="label"){var f=a('<label class="'+this.toThemeProperty("jqx-validator-error-label")+'"></label>');f.html(e);var d=this;if(this.closeOnClick){f.click(function(){d.hideHint(c.selector)})}if(this.position=="left"||this.position=="top"){f.insertBefore(a(c))}else{f.insertAfter(a(c))}return f}var f=a('<div class="'+this.toThemeProperty("jqx-validator-hint")+' jqx-rc-all"></div>'),b=this;f.html(e);if(this.closeOnClick){f.click(function(){b.hideHint(c.selector)})}if(this.ownerElement==null){f.appendTo(document.body)}else{if(this.ownerElement.innerHTML){f.appendTo(a(this.ownerElement))}else{f.appendTo(this.ownerElement)}}return f},_hintLayout:function(h,c,b,f){if(this._hintRender===f.hintRender){var i;i=this._getPosition(c,b,h,f);if(this.hintType=="label"){var e="2px";if(this.position=="left"||this.position=="top"){e="-2px"}if(c[0].nodeName.toLowerCase()!="input"){if(c.find("input").length>0){if(c.find(".jqx-input").length>0){c.find(".jqx-input").addClass(this.toThemeProperty("jqx-validator-error-element"))}else{if(c.is(".jqx-checkbox")){c.find(".jqx-checkbox-default").addClass(this.toThemeProperty("jqx-validator-error-element"))}}if(c.is(".jqx-radiobutton")){c.find(".jqx-radiobutton-default").addClass(this.toThemeProperty("jqx-validator-error-element"))}else{c.addClass(this.toThemeProperty("jqx-validator-error-element"))}}}else{c.addClass(this.toThemeProperty("jqx-validator-error-element"))}var d=a("<span></span>");d.addClass(this.toThemeProperty("jqx-validator-hint"));d.html(h.text());d.appendTo(a(document.body));var g=d.outerWidth();d.remove();h.css({position:"relative",left:a(c).css("margin-left"),width:a(c).width(),top:e});if(b=="center"){h.css("width",g);h.css("left","0px");h.css("margin-left","auto");h.css("margin-right","auto")}return}h.css({position:"absolute",left:i.left,top:i.top});if(this.arrow){this._addArrow(c,h,b,i)}}},_showHint:function(b){if(b){if(this.animation==="fade"){b.fadeOut(0);b.fadeIn(this.animationDuration)}}},_getPosition:function(i,f,d,g){var e=i.offset(),h,c;var b=i.outerWidth();var j=i.outerHeight();if(this.rtl&&f.indexOf("left")>=0){f="right"}if(this.rtl&&f.indexOf("right")>=0){f="left"}if(this.ownerElement!=null){e={left:0,top:0};e.top=parseInt(e.top)+i.position().top;e.left=parseInt(e.left)+i.position().left}if(g&&g.hintPositionRelativeElement){var k=a(g.hintPositionRelativeElement);e=k.offset();b=k.width();j=k.height()}if(f.indexOf("top")>=0){h=e.top-j}else{if(f.indexOf("bottom")>=0){h=e.top+d.outerHeight()+this.hintPositionOffset+5}else{h=e.top}}if(f.indexOf("center")>=0){c=e.left+this.hintPositionOffset+(b-d.outerWidth())/2}else{if(f.indexOf("left")>=0){c=e.left-d.outerWidth()-this.hintPositionOffset}else{if(f.indexOf("right")>=0){c=e.left+b+this.hintPositionOffset}else{c=e.left+this.hintPositionOffset}}}if(f.indexOf(":")>=0){f=f.split(":")[1].split(",");c+=parseInt(f[0],10);h+=parseInt(f[1],10)}if(!this.positions){this.positions=new Array()}if(this.positions[Math.round(h)+"_"+Math.round(c)]){if(this.positions[Math.round(h)+"_"+Math.round(c)].top==h){h+=i.outerHeight()}}this.positions[Math.round(h)+"_"+Math.round(c)]={left:c,top:h};return{left:c,top:h}},_addArrow:function(j,e,g,k){var l=a('<div class="'+this.toThemeProperty("jqx-validator-hint-arrow")+'"></div>'),d,i;if(this.rtl&&g.indexOf("left")>=0){g="right"}if(this.rtl&&g.indexOf("right")>=0){g="left"}e.children(".jqx-validator-hint-arrow").remove();e.append(l);var c=l.outerHeight(),f=l.outerWidth(),h=e.outerHeight(),b=e.outerWidth();this._addImage(l);if(g.indexOf("top")>=0){i=h-c}else{if(g.indexOf("bottom")>=0){i=-c}else{i=(h-c)/2-c/2}}if(g.indexOf("center")>=0){d=(b-f)/2}else{if(g.indexOf("left")>=0){d=b-f/2-1}else{if(g.indexOf("right")>=0){d=-f/2}}}if(g.indexOf("topright")>=0||g.indexOf("bottomright")>=0){d=0}if(g.indexOf("topleft")>=0||g.indexOf("bottomleft")>=0){d=b-f}l.css({position:"absolute",left:d,top:i})},_addImage:function(b){var c=b.css("background-image");c=c.replace('url("',"");c=c.replace('")',"");c=c.replace("url(","");c=c.replace(")","");b.css("background-image","none");b.append('<img src="'+c+'" alt="Arrow" style="position: relative; top: 0px; left: 0px; width: '+b.width()+"px; height: "+b.height()+'px;" />')},_raiseEvent:function(b,d){var c=a.Event(this._events[b]);c.args=d;return this.host.trigger(c)},propertyChangedHandler:function(b,c,e,d){if(c==="rules"){this._configureInputs();this._removeEventListeners();this._addEventListeners()}}})})(jqxBaseFramework);
|
import React from 'react'
import './Spinner.css'
const Spinner = () => {
return <div className='lds-dual-ring'></div>
}
export default Spinner
|
import React from 'react'
import Container from '../container'
import Prose from '../prose'
import ProductShowcase from './product-showcase'
import { uppercase, border } from '../typography.module.css'
import { cn } from '../../lib/helpers'
import Cart from '../snipcart/cart'
import styles from './product.module.css'
import ProductDetailPicker from './product-detail-picker'
import ProductPreview from './product-preview'
const Product = ({ product, similarProducts }) => {
const { title, images, descriptionHtml } = product
return (
<article className={styles.root}>
<Container>
<div className={cn(border, styles.productWrapper)}>
<h1 className={cn(styles.title, uppercase)}>{title}</h1>
<Cart />
</div>
<div className={styles.grid}>
<div className={styles.mainContent}>
{images && (
<ProductShowcase
image={images[0] && images[0].localFile && images[0].localFile.childImageSharp.fluid}
alt={title}
images={images}
/>
)}
</div>
<aside className={styles.metaContent}>
<ProductDetailPicker product={product} />
{descriptionHtml && (
<div className={styles.description}>
<Prose html={descriptionHtml} />
</div>
)}
</aside>
</div>
<div className={cn(border, styles.productWrapper)}>
<h1 className={cn(styles.title, uppercase)}>SIMILAR PRODUCTS</h1>
</div>
<div className={styles.similarProducts}>
{similarProducts.map((prod, i) => (
<ProductPreview {...prod.node} handle={prod.node.handle} key={`similarProd-${i}`} />
))}
</div>
</Container>
</article>
)
}
export default Product
|
var mongoose = require('mongoose');
const movieSchema = mongoose.Schema({
name:{
type: String,
required: true,
},
indate:{
type: String,
required: true,
},
outdate:{
type: String,
required: true,
},
genre:{
type: String,
required: true,
},
duration:{
type: String,
required: true,
},
imdb:{
type: String,
required: true,
},
director:{
type: String,
required: true,
},
poster:{
type: String,
required: true,
},
trailer:{
type: String,
required: true,
}
});
module.exports = mongoose.model('Movie',movieSchema,'movies');
|
const router = require('express').Router();
const UserService = require('../service/UserService');
const User = require('../model/User');
const SchemaValidation = require('../validation/SchemaValidation');
const GPError = require('../error/GPError');
const { isAdmin, isModerator } = require('../middleware/authorization');
const userService = new UserService(User, SchemaValidation, GPError);
router.post('/register/admin', isAdmin, async (req, res) => {
const user = await userService.register(req.body);
res.json(user);
});
router.post('/register/moderator', isAdmin, async (req, res) => {
const user = await userService.register(req.body);
res.json(user);
});
router.post('/register/doctor', isModerator, async (req, res) => {
const user = await userService.register(req.body);
res.json(user);
});
router.post('/login', async (req, res) => {
const user = await userService.login(req.body);
res.json({ _id: user.id, name: user.name, token: user.generateAuthToken() });
});
module.exports = router;
|
import ScrollReveal from 'scrollreveal'
// Export your custom function for declarative use
export { scrollRevelation }
// Code your custom function
function scrollRevelation( classString ) {
window.sr = new ScrollReveal();
sr.reveal('.card', 100);
}
|
const runExecutable = require('./run-executable');
const {getFlagArrayFromObject} = require('./utils');
const themekit = {
/**
* Runs a ThemeKit command with the runExecutable utility.
* Forces the --no-update-notifier flag to prevent update messages from
* appearing when `theme update` can't be run via CLI for this package.
* @param {string} cmd Theme Kit command to run
* @param {Object} flagObj flags for the Theme Kit command
* @param {Object} options additional options (cwd and logLevel)
*/
command(cmd, flagObj = {}, options = {cwd: process.cwd()}) {
const updatedFlagObj = Object.assign({}, flagObj, {
noUpdateNotifier: true
});
const flagArr = getFlagArrayFromObject(updatedFlagObj);
return runExecutable(
[cmd, ...flagArr],
options.cwd,
options.logLevel || null
);
}
};
module.exports = themekit;
|
function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
|
;
(function () {
'use strict';
//=require globalVars.js
//=require gtm-modules.js
//=require expose.js
})();
|
/*
*插件作者:周祥
*发布时间:2014年12月12日
*插件介绍:图片上传本地预览插件 兼容浏览器(IE 谷歌 火狐) 不支持safari 当然如果是使用这些内核的浏览器基本都兼容
*插件网站:http://jquery.decadework.com
*作 者QQ:200592114
*使用方法:
*界面构造(IMG标签外必须拥有DIV 而且必须给予DIV控件ID)
* <div id="imgdiv"><img id="imgShow" width="120" height="120" /></div>
* <input type="file" id="up_img" />
*调用代码:
* new uploadPreview({ UpBtn: "up_img", DivShow: "imgdiv", ImgShow: "imgShow" });
*参数说明:
*UpBtn:选择文件控件ID;
*DivShow:DIV控件ID;
*ImgShow:图片控件ID;
*Width:预览宽度;
*Height:预览高度;
*ImgType:支持文件类型 格式:["jpg","png"];
*callback:选择文件后回调方法;
*版本:v1.4
更新内容如下:
1.修复回调.
*版本:v1.3
更新内容如下:
1.修复多层级框架获取路径BUG.
2.去除对jquery插件的依赖.
*/
/*
*author:周祥
*date:2014年12月12日
*work:图片预览插件
*/
var uploadPreview = function(setting) {
/*
*author:周祥
*date:2014年12月11日
*work:this(当前对象)
*/
var _self = this;
/*
*author:周祥
*date:2014年12月11日
*work:判断为null或者空值
*/
_self.IsNull = function(value) {
if (typeof (value) == "function") { return false; }
if (value == undefined || value == null || value == "" || value.length == 0) {
return true;
}
return false;
}
/*
*author:周祥
*date:2014年12月11日
*work:默认配置
*/
_self.DefautlSetting = {
UpBtn: "",
DivShow: "",
ImgShow: "",
Width: 100,
Height: 100,
ImgType: ["gif", "jpeg", "jpg", "bmp", "png",""],
ErrMsg: "选择文件错误,图片类型必须是(gif,jpeg,jpg,bmp,png)中的一种",
callback: function() { }
};
/*
*author:周祥
*date:2014年12月11日
*work:读取配置
*/
_self.Setting = {
UpBtn: _self.IsNull(setting.UpBtn) ? _self.DefautlSetting.UpBtn : setting.UpBtn,
DivShow: _self.IsNull(setting.DivShow) ? _self.DefautlSetting.DivShow : setting.DivShow,
ImgShow: _self.IsNull(setting.ImgShow) ? _self.DefautlSetting.ImgShow : setting.ImgShow,
Width: _self.IsNull(setting.Width) ? _self.DefautlSetting.Width : setting.Width,
Height: _self.IsNull(setting.Height) ? _self.DefautlSetting.Height : setting.Height,
ImgType: _self.IsNull(setting.ImgType) ? _self.DefautlSetting.ImgType : setting.ImgType,
ErrMsg: _self.IsNull(setting.ErrMsg) ? _self.DefautlSetting.ErrMsg : setting.ErrMsg,
callback: _self.IsNull(setting.callback) ? _self.DefautlSetting.callback : setting.callback
};
/*
*author:周祥
*date:2014年12月11日
*work:获取文本控件URL
*/
_self.getObjectURL = function(file) {
var url = null;
if (window.createObjectURL != undefined) {
url = window.createObjectURL(file);
} else if (window.URL != undefined) {
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) {
url = window.webkitURL.createObjectURL(file);
}
return url;
}
/*
*author:周祥
*date:2014年12月11日
*work:绑定事件
*/
_self.Bind = function() {
document.getElementById(_self.Setting.UpBtn).onchange = function() {
if (this.value) {
if (!RegExp("\.(" + _self.Setting.ImgType.join("|") + ")$", "i").test(this.value.toLowerCase())) {
alert(_self.Setting.ErrMsg);
this.value = "";
return false;
}
if (navigator.userAgent.indexOf("MSIE") > -1) {
try {
document.getElementById(_self.Setting.ImgShow).src = _self.getObjectURL(this.files[0]);
} catch (e) {
var div = document.getElementById(_self.Setting.DivShow);
this.select();
top.parent.document.body.focus();
var src = document.selection.createRange().text;
document.selection.empty();
document.getElementById(_self.Setting.ImgShow).style.display = "none";
div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
div.style.width = _self.Setting.Width + "px";
div.style.height = _self.Setting.Height + "px";
div.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = src;
}
} else {
document.getElementById(_self.Setting.ImgShow).src = _self.getObjectURL(this.files[0]);
}
_self.Setting.callback();
}
}
}
/*
*author:周祥
*date:2014年12月11日
*work:执行绑定事件
*/
_self.Bind();
}
|
/*! UIkit 2.27.5 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(t){var e;window.UIkit2&&(e=t(UIkit2)),"function"==typeof define&&define.amd&&define("uikit-htmleditor",["uikit"],function(){return e||t(UIkit2)})}(function(t){"use strict";var e=[];return t.component("htmleditor",{defaults:{iframe:!1,mode:"split",markdown:!1,autocomplete:!0,enablescripts:!1,height:500,maxsplitsize:1e3,codemirror:{mode:"htmlmixed",lineWrapping:!0,dragDrop:!1,autoCloseTags:!0,matchTags:!0,autoCloseBrackets:!0,matchBrackets:!0,indentUnit:4,indentWithTabs:!1,tabSize:4,hintOptions:{completionSingle:!1}},toolbar:["bold","italic","strike","link","image","blockquote","listUl","listOl"],lblPreview:"Preview",lblCodeview:"HTML",lblMarkedview:"Markdown"},boot:function(){t.ready(function(e){t.$("textarea[data-uk-htmleditor]",e).each(function(){var e=t.$(this);e.data("htmleditor")||t.htmleditor(e,t.Utils.options(e.attr("data-uk-htmleditor")))})})},init:function(){var i=this,o=t.components.htmleditor.template;this.CodeMirror=this.options.CodeMirror||CodeMirror,this.buttons={},o=o.replace(/\{:lblPreview}/g,this.options.lblPreview),o=o.replace(/\{:lblCodeview}/g,this.options.lblCodeview),this.htmleditor=t.$(o),this.content=this.htmleditor.find(".uk-htmleditor-content"),this.toolbar=this.htmleditor.find(".uk-htmleditor-toolbar"),this.preview=this.htmleditor.find(".uk-htmleditor-preview").children().eq(0),this.code=this.htmleditor.find(".uk-htmleditor-code"),this.element.before(this.htmleditor).appendTo(this.code),this.editor=this.CodeMirror.fromTextArea(this.element[0],this.options.codemirror),this.editor.htmleditor=this,this.editor.on("change",t.Utils.debounce(function(){i.render()},150)),this.editor.on("change",function(){i.editor.save(),i.element.trigger("input")}),this.code.find(".CodeMirror").css("height",this.options.height),this.options.iframe?(this.iframe=t.$('<iframe class="uk-htmleditor-iframe" frameborder="0" scrolling="auto" height="100" width="100%"></iframe>'),this.preview.append(this.iframe),this.iframe[0].contentWindow.document.open(),this.iframe[0].contentWindow.document.close(),this.preview.container=t.$(this.iframe[0].contentWindow.document).find("body"),"string"==typeof this.options.iframe&&this.preview.container.parent().append('<link rel="stylesheet" href="'+this.options.iframe+'">')):this.preview.container=this.preview,t.$win.on("resize load",t.Utils.debounce(function(){i.fit()},200));var n=this.iframe?this.preview.container:i.preview.parent(),r=this.code.find(".CodeMirror-sizer"),l=this.code.find(".CodeMirror-scroll").on("scroll",t.Utils.debounce(function(){if("tab"!=i.htmleditor.attr("data-mode")){var t=r.height()-l.height(),e=n[0].scrollHeight-(i.iframe?i.iframe.height():n.height()),o=e/t,s=l.scrollTop()*o;n.scrollTop(s)}},10));this.htmleditor.on("click",".uk-htmleditor-button-code, .uk-htmleditor-button-preview",function(e){e.preventDefault(),"tab"==i.htmleditor.attr("data-mode")&&(i.htmleditor.find(".uk-htmleditor-button-code, .uk-htmleditor-button-preview").removeClass("uk-active").filter(this).addClass("uk-active"),i.activetab=t.$(this).hasClass("uk-htmleditor-button-code")?"code":"preview",i.htmleditor.attr("data-active-tab",i.activetab),i.editor.refresh())}),this.htmleditor.on("click","a[data-htmleditor-button]",function(){i.code.is(":visible")&&i.trigger("action."+t.$(this).data("htmleditor-button"),[i.editor])}),this.preview.parent().css("height",this.code.height()),this.options.autocomplete&&this.CodeMirror.showHint&&this.CodeMirror.hint&&this.CodeMirror.hint.html&&this.editor.on("inputRead",t.Utils.debounce(function(){var t=i.editor.getDoc(),e=t.getCursor(),o=i.CodeMirror.innerMode(i.editor.getMode(),i.editor.getTokenAt(e).state).mode.name;if("xml"==o){var n=i.editor.getCursor(),r=i.editor.getTokenAt(n);("<"==r.string.charAt(0)||"attribute"==r.type)&&i.CodeMirror.showHint(i.editor,i.CodeMirror.hint.html,{completeSingle:!1})}},100)),this.debouncedRedraw=t.Utils.debounce(function(){i.redraw()},5),this.on("init.uk.component",function(){i.debouncedRedraw()}),this.element.attr("data-uk-check-display",1).on("display.uk.check",function(){this.htmleditor.is(":visible")&&this.fit()}.bind(this)),e.push(this)},addButton:function(t,e){this.buttons[t]=e},addButtons:function(e){t.$.extend(this.buttons,e)},replaceInPreview:function(t,e){function i(t){var e=o.getValue().substring(0,t).split("\n");return{line:e.length-1,ch:e[e.length-1].length}}var o=this.editor,n=[],r=o.getValue(),l=-1,s=0;return this.currentvalue=this.currentvalue.replace(t,function(){l=r.indexOf(arguments[0],++l);var t={matches:arguments,from:i(l),to:i(l+arguments[0].length),replace:function(e){o.replaceRange(e,t.from,t.to)},inRange:function(e){return e.line===t.from.line&&e.line===t.to.line?e.ch>=t.from.ch&&e.ch<t.to.ch:e.line===t.from.line&&e.ch>=t.from.ch||e.line>t.from.line&&e.line<t.to.line||e.line===t.to.line&&e.ch<t.to.ch}},a="string"==typeof e?e:e(t,s);return a||""===a?(s++,n.push(t),a):arguments[0]}),n},_buildtoolbar:function(){if(this.options.toolbar&&this.options.toolbar.length){var t=this,e=[];this.toolbar.empty(),this.options.toolbar.forEach(function(i){if(t.buttons[i]){var o=t.buttons[i].title?t.buttons[i].title:i;e.push('<li><a data-htmleditor-button="'+i+'" title="'+o+'" data-uk-tooltip>'+t.buttons[i].label+"</a></li>")}}),this.toolbar.html(e.join("\n"))}},fit:function(){var t=this.options.mode;"split"==t&&this.htmleditor.width()<this.options.maxsplitsize&&(t="tab"),"tab"==t&&(this.activetab||(this.activetab="code",this.htmleditor.attr("data-active-tab",this.activetab)),this.htmleditor.find(".uk-htmleditor-button-code, .uk-htmleditor-button-preview").removeClass("uk-active").filter("code"==this.activetab?".uk-htmleditor-button-code":".uk-htmleditor-button-preview").addClass("uk-active")),this.editor.refresh(),this.preview.parent().css("height",this.code.height()),this.htmleditor.attr("data-mode",t)},redraw:function(){this._buildtoolbar(),this.render(),this.fit()},getMode:function(){return this.editor.getOption("mode")},getCursorMode:function(){var t={mode:"html"};return this.trigger("cursorMode",[t]),t.mode},render:function(){return this.currentvalue=this.editor.getValue(),this.options.enablescripts||(this.currentvalue=this.currentvalue.replace(/<(script|style)\b[^<]*(?:(?!<\/(script|style)>)<[^<]*)*<\/(script|style)>/gim,"")),this.currentvalue?(this.trigger("render",[this]),this.trigger("renderLate",[this]),this.preview.container.html(this.currentvalue),void 0):(this.element.val(""),this.preview.container.html(""),void 0)},addShortcut:function(e,i){var o={};return t.$.isArray(e)||(e=[e]),e.forEach(function(t){o[t]=i}),this.editor.addKeyMap(o),o},addShortcutAction:function(t,e){var i=this;this.addShortcut(e,function(){i.element.trigger("action."+t,[i.editor])})},replaceSelection:function(t){var e=this.editor.getSelection();if(!e.length){for(var i=this.editor.getCursor(),o=this.editor.getLine(i.line),n=i.ch,r=n;r<o.length&&/[\w$]+/.test(o.charAt(r));)++r;for(;n&&/[\w$]+/.test(o.charAt(n-1));)--n;var l=n!=r&&o.slice(n,r);l&&(this.editor.setSelection({line:i.line,ch:n},{line:i.line,ch:r}),e=l)}var s=t.replace("$1",e);this.editor.replaceSelection(s,"end"),this.editor.focus()},replaceLine:function(t){var e=this.editor.getDoc().getCursor(),i=this.editor.getLine(e.line),o=t.replace("$1",i);this.editor.replaceRange(o,{line:e.line,ch:0},{line:e.line,ch:i.length}),this.editor.setCursor({line:e.line,ch:o.length}),this.editor.focus()},save:function(){this.editor.save()}}),t.components.htmleditor.template=['<div class="uk-htmleditor uk-clearfix" data-mode="split">','<div class="uk-htmleditor-navbar">','<ul class="uk-htmleditor-navbar-nav uk-htmleditor-toolbar"></ul>','<div class="uk-htmleditor-navbar-flip">','<ul class="uk-htmleditor-navbar-nav">','<li class="uk-htmleditor-button-code"><a>{:lblCodeview}</a></li>','<li class="uk-htmleditor-button-preview"><a>{:lblPreview}</a></li>','<li><a data-htmleditor-button="fullscreen"><i class="uk-icon-expand"></i></a></li>',"</ul>","</div>","</div>",'<div class="uk-htmleditor-content">','<div class="uk-htmleditor-code"></div>','<div class="uk-htmleditor-preview"><div></div></div>',"</div>","</div>"].join(""),t.plugin("htmleditor","base",{init:function(e){function i(t,i,o){e.on("action."+t,function(){"html"==e.getCursorMode()&&e["replaceLine"==o?"replaceLine":"replaceSelection"](i)})}e.addButtons({fullscreen:{title:"Fullscreen",label:'<i class="uk-icon-expand"></i>'},bold:{title:"Bold",label:'<i class="uk-icon-bold"></i>'},italic:{title:"Italic",label:'<i class="uk-icon-italic"></i>'},strike:{title:"Strikethrough",label:'<i class="uk-icon-strikethrough"></i>'},blockquote:{title:"Blockquote",label:'<i class="uk-icon-quote-right"></i>'},link:{title:"Link",label:'<i class="uk-icon-link"></i>'},image:{title:"Image",label:'<i class="uk-icon-picture-o"></i>'},listUl:{title:"Unordered List",label:'<i class="uk-icon-list-ul"></i>'},listOl:{title:"Ordered List",label:'<i class="uk-icon-list-ol"></i>'}}),i("bold","<strong>$1</strong>"),i("italic","<em>$1</em>"),i("strike","<del>$1</del>"),i("blockquote","<blockquote><p>$1</p></blockquote>","replaceLine"),i("link",'<a href="http://">$1</a>'),i("image",'<img src="http://" alt="$1">');var o=function(t){if("html"==e.getCursorMode()){t=t||"ul";for(var i=e.editor,o=i.getDoc(),n=o.getCursor(!0),r=o.getCursor(!1),l=CodeMirror.innerMode(i.getMode(),i.getTokenAt(i.getCursor()).state),s=l&&l.state&&l.state.context&&-1!=["ul","ol"].indexOf(l.state.context.tagName),a=n.line;a<r.line+1;a++)i.replaceRange("<li>"+i.getLine(a)+"</li>",{line:a,ch:0},{line:a,ch:i.getLine(a).length});s?i.setCursor({line:r.line,ch:i.getLine(r.line).length}):(i.replaceRange("<"+t+">\n"+i.getLine(n.line),{line:n.line,ch:0},{line:n.line,ch:i.getLine(n.line).length}),i.replaceRange(i.getLine(r.line+1)+"\n</"+t+">",{line:r.line+1,ch:0},{line:r.line+1,ch:i.getLine(r.line+1).length}),i.setCursor({line:r.line+1,ch:i.getLine(r.line+1).length})),i.focus()}};e.on("action.listUl",function(){o("ul")}),e.on("action.listOl",function(){o("ol")}),e.htmleditor.on("click",'a[data-htmleditor-button="fullscreen"]',function(){e.htmleditor.toggleClass("uk-htmleditor-fullscreen");var i=e.editor.getWrapperElement();if(e.htmleditor.hasClass("uk-htmleditor-fullscreen")){var o=!1,n=e.htmleditor.parents().each(function(){"fixed"!=t.$(this).css("position")||t.$(this).is("html")||(o=t.$(this))});if(e.htmleditor.data("fixedParents",!1),o){var r=[];o=o.parent().find(n).each(function(){"none"!=t.$(this).css("transform")&&r.push(t.$(this).data("transform-reset",{transform:this.style.transform,"-webkit-transform":this.style.webkitTransform,"-webkit-transition":this.style.webkitTransition,transition:this.style.transition}).css({transform:"none","-webkit-transform":"none","-webkit-transition":"none",transition:"none"}))}),e.htmleditor.data("fixedParents",r)}e.editor.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:i.style.width,height:i.style.height},i.style.width="",i.style.height=e.content.height()+"px",document.documentElement.style.overflow="hidden"}else{document.documentElement.style.overflow="";var l=e.editor.state.fullScreenRestore;i.style.width=l.width,i.style.height=l.height,window.scrollTo(l.scrollLeft,l.scrollTop),e.htmleditor.data("fixedParents")&&e.htmleditor.data("fixedParents").forEach(function(t){t.css(t.data("transform-reset"))})}setTimeout(function(){e.fit(),t.$win.trigger("resize")},50)}),e.addShortcut(["Ctrl-S","Cmd-S"],function(){e.element.trigger("htmleditor-save",[e])}),e.addShortcutAction("bold",["Ctrl-B","Cmd-B"])}}),t.plugin("htmleditor","markdown",{init:function(e){function i(){e.editor.setOption("mode","gfm"),e.htmleditor.find(".uk-htmleditor-button-code a").html(e.options.lblMarkedview)}function o(t,i,o){e.on("action."+t,function(){"markdown"==e.getCursorMode()&&e["replaceLine"==o?"replaceLine":"replaceSelection"](i)})}var n=e.options.mdparser||window.marked||null;n&&(e.options.markdown&&i(),o("bold","**$1**"),o("italic","*$1*"),o("strike","~~$1~~"),o("blockquote","> $1","replaceLine"),o("link","[$1](http://)"),o("image",""),e.on("action.listUl",function(){if("markdown"==e.getCursorMode()){for(var t=e.editor,i=t.getDoc().getCursor(!0),o=t.getDoc().getCursor(!1),n=i.line;n<o.line+1;n++)t.replaceRange("* "+t.getLine(n),{line:n,ch:0},{line:n,ch:t.getLine(n).length});t.setCursor({line:o.line,ch:t.getLine(o.line).length}),t.focus()}}),e.on("action.listOl",function(){if("markdown"==e.getCursorMode()){var t=e.editor,i=t.getDoc().getCursor(!0),o=t.getDoc().getCursor(!1),n=1;if(i.line>0){var r,l=t.getLine(i.line-1);(r=l.match(/^(\d+)\./))&&(n=Number(r[1])+1)}for(var s=i.line;s<o.line+1;s++)t.replaceRange(n+". "+t.getLine(s),{line:s,ch:0},{line:s,ch:t.getLine(s).length}),n++;t.setCursor({line:o.line,ch:t.getLine(o.line).length}),t.focus()}}),e.on("renderLate",function(){"gfm"==e.editor.options.mode&&(e.currentvalue=n(e.currentvalue))}),e.on("cursorMode",function(t,i){if("gfm"==e.editor.options.mode){var o=e.editor.getDoc().getCursor();e.editor.getTokenAt(o).state.base.htmlState||(i.mode="markdown")}}),t.$.extend(e,{enableMarkdown:function(){i(),this.render()},disableMarkdown:function(){this.editor.setOption("mode","htmlmixed"),this.htmleditor.find(".uk-htmleditor-button-code a").html(this.options.lblCodeview),this.render()}}),e.on({enableMarkdown:function(){e.enableMarkdown()},disableMarkdown:function(){e.disableMarkdown()}}))}}),t.htmleditor});
|
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(693);
module.exports = __webpack_require__(693);
/***/ }),
/***/ 693:
/***/ (function(module, exports) {
(function( window, undefined ) {
kendo.cultures["saq-KE"] = {
name: "saq-KE",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
name: "Kenyan Shilling",
abbr: "KES",
pattern: ["-$n","$n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "Ksh"
}
},
calendars: {
standard: {
days: {
names: ["Mderot ee are","Mderot ee kuni","Mderot ee ong’wan","Mderot ee inet","Mderot ee ile","Mderot ee sapa","Mderot ee kwe"],
namesAbbr: ["Are","Kun","Ong","Ine","Ile","Sap","Kwe"],
namesShort: ["Are","Kun","Ong","Ine","Ile","Sap","Kwe"]
},
months: {
names: ["Lapa le obo","Lapa le waare","Lapa le okuni","Lapa le ong’wan","Lapa le imet","Lapa le ile","Lapa le sapa","Lapa le isiet","Lapa le saal","Lapa le tomon","Lapa le tomon obo","Lapa le tomon waare"],
namesAbbr: ["Obo","Waa","Oku","Ong","Ime","Ile","Sap","Isi","Saa","Tom","Tob","Tow"]
},
AM: ["Tesiran","tesiran","TESIRAN"],
PM: ["Teipa","teipa","TEIPA"],
patterns: {
d: "dd/MM/yyyy",
D: "dddd, d MMMM yyyy",
F: "dddd, d MMMM yyyy HH:mm:ss",
g: "dd/MM/yyyy HH:mm",
G: "dd/MM/yyyy HH:mm:ss",
m: "MMMM d",
M: "MMMM d",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
/***/ })
/******/ });
|
// code to define and exporting the Employee class
class Employee {
constructor(name,id,email) {
this.name = name
this.id = id
this.email = email
}
getName() {
return this.name
}
getId() {
return this.id
}
getEmail() {
return this.email
}
getRole() {
return "Employee"
}
}
module.exports = Employee
|
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* This file was added automatically by CKEditor builder.
* You may re-use it at any time to build CKEditor again.
*
* If you would like to build CKEditor online again
* (for example to upgrade), visit one the following links:
*
* (1) http://ckeditor.com/builder
* Visit online builder to build CKEditor from scratch.
*
* (2) http://ckeditor.com/builder/b9263a8915532211fa6b73d1a3f73953
* Visit online builder to build CKEditor, starting with the same setup as before.
*
* (3) http://ckeditor.com/builder/download/b9263a8915532211fa6b73d1a3f73953
* Straight download link to the latest version of CKEditor (Optimized) with the same setup as before.
*
* NOTE:
* This file is not used by CKEditor, you may remove it.
* Changing this file will not change your CKEditor configuration.
*/
var CKBUILDER_CONFIG = {
skin: 'office2013',
preset: 'standard',
ignore: [
'.bender',
'bender.js',
'bender-err.log',
'bender-out.log',
'dev',
'.DS_Store',
'.editorconfig',
'.gitattributes',
'.gitignore',
'gruntfile.js',
'.idea',
'.jscsrc',
'.jshintignore',
'.jshintrc',
'less',
'.mailmap',
'node_modules',
'package.json',
'README.md',
'tests'
],
plugins : {
'basicstyles' : 1,
'blockquote' : 1,
'clipboard' : 1,
'colordialog' : 1,
'contextmenu' : 1,
'elementspath' : 1,
'enterkey' : 1,
'entities' : 1,
'filebrowser' : 1,
'floatingspace' : 1,
'font' : 1,
'format' : 1,
'horizontalrule' : 1,
'htmlwriter' : 1,
'image' : 1,
'indentlist' : 1,
'link' : 1,
'list' : 1,
'magicline' : 1,
'maximize' : 1,
'pastefromword' : 1,
'pastetext' : 1,
'removeformat' : 1,
'resize' : 1,
'showborders' : 1,
'sourcearea' : 1,
'specialchar' : 1,
'stylescombo' : 1,
'tab' : 1,
'table' : 1,
'tabletools' : 1,
'toolbar' : 1,
'undo' : 1,
'wysiwygarea' : 1
},
languages : {
'en' : 1,
'ru' : 1
}
};
|
(window.webpackJsonpFileIcons=window.webpackJsonpFileIcons||[]).push([[424],{226:function(q){q.exports={viewBox:"0 0 1024 1024",font:"file-icons",code:"263f",ref:"hg",path:"M209 473q0-60-52.5-90.5T52 382Q0 412 0 472.5T52 563q52 30 104.5 0t52.5-90m-115 4q2-26 32-40t45 10q12 19-5 39.5T131 512q-20 5-29-2t-8-33m18 73q3-3 16.5-4t27.5-9q14-7 28-23.5t18-40.5q1-14 2-12.5t2 9.5q-3 39-31 60.5T126 555q-5 1-12 0t-2-5M513 19q-138 17-208 89-71 71-76 156t54 165q59 80 181 115 105 29 127 75t7.5 98Q584 769 555 822t-27 97q3 45 44 71t103.5 16Q738 996 814 941q75-55 145-171 69-115 65-253-4-139-66.5-256T780 72Q666 0 513 19m60 538q-10-6-35.5-19T464 509q-40-13-62-24t-32-20q31 14 58.5 21t58.5 15q66 20 87 31.5t23 36.5q-1 14-7.5 4.5T573 557m163 178q30 4 60-22 31-26 56.5-66t44.5-87q19-47 26-85 14-75 19-25.5T933 550q-8 30-25 68-18 37-39 73.5T825 761q-22 32-41 54-30 34-63 50t-73 21q-41 8-44-16t16.5-55q19.5-31 51.5-57 33-27 64-23m137 121q-38 45-91.5 80.5T665 976q-16 3-27 0t-10-13q1-15 16.5-12t39.5-3q87-21 135.5-67.5T920 752q41-64 60-124t20-73q2 8-4 38t-21 72.5Q960 708 935 758q-26 50-62 98M207 672q-40 23-60 60-20 38-20 78t20 78q20 37 60 60 39 23 82 21 42-1 77-21t58-56q22-36 22-82t-22-82q-23-36-58-56t-77-22q-43-1-82 22m100 165q36-12 55.5-60.5T386 763q9 70-24 95t-48 29q-53 14-57-9t50-41m124-8q-7 48-45.5 80.5T308 944q-8 0-15-2.5t3-4.5q12-2 62.5-24t66.5-78q5-18 6.5-17t-.5 11z"}}}]);
|
/*
Copyright (c) Uber Technologies, Inc.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/
// @flow
export {default as PhoneInput} from './phone-input.js';
export {default as PhoneInputLite} from './phone-input-lite.js';
export {default as PhoneInputNext} from './phone-input-next.js';
export {default as StatefulPhoneInput} from './stateful-phone-input.js';
export {
default as StatefulPhoneInputNext,
} from './stateful-phone-input-next.js';
export {
default as StatefulPhoneInputContainer,
} from './stateful-phone-input-container.js';
export {default as CountryPicker} from './country-picker.js';
export {default as CountrySelect} from './country-select.js';
export {default as CountrySelectDropdown} from './country-select-dropdown.js';
export {default as Flag, StyledFlag} from './flag.js';
export * from './constants.js';
export type * from './types.js';
export * from './styled-components.js';
|
/**
*
* Root handler for "/" route
* restify each path to its handler
*
**/
var $ = require('../lib/dollar').$,
BaseHandler = require('./BaseHandler'),
DefaultHandler = require('./DefaultHandler'),
UserHandler = require('./UserHandler'),
MeHandler = require('./MeHandler');
function RootHandler(ctx) {
$('util').inherits(this, BaseHandler);
BaseHandler.call(this, ctx);
this.dispatch = function() {
// get the current step and change ctx for the next handler
var step = ctx.shift();
var method = ctx.getMethod();
switch (step) {
case '':
this[method](ctx.getContext());
break;
case 'user':
new UserHandler(ctx).dispatch();
break;
case 'me':
new MeHandler(ctx).dispatch();
break;
default:
new DefaultHandler(ctx).dispatch();
}
};
}
module.exports = RootHandler;
|
import { connect } from 'react-redux'
import Controls from '../components/Controls'
import {
changeAmpLevel,
changeAttack,
changeCents,
changeDecay,
changeLFORate,
changeLFOSend,
changeLFOWaveform,
changeNoiseAmount,
changeOscGain,
changeOscWaveform,
changeRelease,
changeSemitones,
changeSustain,
updateFilterCutoff,
updateFilterQ,
} from '../actions'
import { OSC_A, OSC_B, LFO_A, LFO_B } from '../constants'
const mapStateToProps = state => ({ ...state })
const mapDispatchToProps = dispatch => ({
changeAttack: level => dispatch(changeAttack(level)),
changeDecay: level => dispatch(changeDecay(level)),
changeSustain: level => dispatch(changeSustain(level)),
changeRelease: level => dispatch(changeRelease(level)),
changeAmpLevel: level => dispatch(changeAmpLevel(level)),
changeLFOARate: rate => dispatch(changeLFORate({
id: LFO_A,
rate,
})),
changeLFOBRate: rate => dispatch(changeLFORate({
id: LFO_B,
rate,
})),
changeLFOAWaveform: waveform => dispatch(changeLFOWaveform({
id: LFO_A,
waveform,
})),
changeLFOBWaveform: waveform => dispatch(changeLFOWaveform({
id: LFO_B,
waveform,
})),
changeLFOASend: (value, destination) => dispatch(changeLFOSend({
id: LFO_A,
sends: {
[destination]: value,
},
})),
changeLFOBSend: (value, destination) => dispatch(changeLFOSend({
id: LFO_B,
sends: {
[destination]: value,
},
})),
changeNoiseAmount: amount => dispatch(changeNoiseAmount(amount)),
changeOscACents: cents => dispatch(changeCents({
id: OSC_A,
cents,
})),
changeOscASemitones: semitones => dispatch(changeSemitones({
id: OSC_A,
semitones,
})),
changeOscAGain: gain => dispatch(changeOscGain({
id: OSC_A,
gain,
})),
changeOscBCents: cents => dispatch(changeCents({
id: OSC_B,
cents,
})),
changeOscBSemitones: semitones => dispatch(changeSemitones({
id: OSC_B,
semitones,
})),
changeOscBGain: gain => dispatch(changeOscGain({
id: OSC_B,
gain,
})),
changeOscAWaveform: waveform => dispatch(changeOscWaveform({
id: OSC_A,
waveform,
})),
changeOscBWaveform: waveform => dispatch(changeOscWaveform({
id: OSC_B,
waveform,
})),
changeCutoff: level => updateFilterCutoff(level),
changeQ: level => updateFilterQ(level),
})
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Controls)
|
import {registerBidder} from '../src/adapters/bidderFactory.js';
import { BANNER, NATIVE, VIDEO } from '../src/mediaTypes.js';
import * as utils from '../src/utils.js';
const BIDDER_CODE = 'krushmedia';
const AD_URL = 'https://ads4.krushmedia.com/?c=rtb&m=hb';
function isBidResponseValid(bid) {
if (!bid.requestId || !bid.cpm || !bid.creativeId ||
!bid.ttl || !bid.currency) {
return false;
}
switch (bid.mediaType) {
case BANNER:
return Boolean(bid.width && bid.height && bid.ad);
case VIDEO:
return Boolean(bid.vastUrl);
case NATIVE:
return Boolean(bid.native && bid.native.impressionTrackers);
default:
return false;
}
}
export const spec = {
code: BIDDER_CODE,
supportedMediaTypes: [BANNER, VIDEO, NATIVE],
isBidRequestValid: (bid) => {
return Boolean(bid.bidId && bid.params && !isNaN(parseInt(bid.params.key)));
},
buildRequests: (validBidRequests = [], bidderRequest) => {
let winTop = window;
let location;
try {
location = new URL(bidderRequest.refererInfo.referer)
winTop = window.top;
} catch (e) {
location = winTop.location;
utils.logMessage(e);
};
const placements = [];
const request = {
'deviceWidth': winTop.screen.width,
'deviceHeight': winTop.screen.height,
'language': (navigator && navigator.language) ? navigator.language.split('-')[0] : '',
'secure': 1,
'host': location.host,
'page': location.pathname,
'placements': placements
};
if (bidderRequest) {
if (bidderRequest.uspConsent) {
request.ccpa = bidderRequest.uspConsent;
}
if (bidderRequest.gdprConsent) {
request.gdpr = bidderRequest.gdprConsent
}
}
const len = validBidRequests.length;
for (let i = 0; i < len; i++) {
const bid = validBidRequests[i];
const placement = {
key: bid.params.key,
bidId: bid.bidId,
traffic: bid.params.traffic || BANNER,
schain: bid.schain || {},
};
if (bid.mediaTypes && bid.mediaTypes[BANNER] && bid.mediaTypes[BANNER].sizes) {
placement.sizes = bid.mediaTypes[BANNER].sizes;
} else if (bid.mediaTypes && bid.mediaTypes[VIDEO] && bid.mediaTypes[VIDEO].playerSize) {
placement.wPlayer = bid.mediaTypes[VIDEO].playerSize[0];
placement.hPlayer = bid.mediaTypes[VIDEO].playerSize[1];
} else if (bid.mediaTypes && bid.mediaTypes[NATIVE]) {
placement.native = bid.mediaTypes[NATIVE];
}
placements.push(placement);
}
return {
method: 'POST',
url: AD_URL,
data: request
};
},
interpretResponse: (serverResponse) => {
let response = [];
for (let i = 0; i < serverResponse.body.length; i++) {
let resItem = serverResponse.body[i];
if (isBidResponseValid(resItem)) {
response.push(resItem);
}
}
return response;
},
};
registerBidder(spec);
|
"use strict";(function(p,g,c){function q(d,h,k){return function(e){var m=this.getAttribute(d);h.call(this,e);this.getAttribute(d)===m&&this.setAttribute(d,k.call(this))}}for(var n=g.getOwnPropertyNames(c),l=0,r=n.length|0,a;l<r;l=l+1|0)a=n[l],/^HTML[A-Z]\w*Element$/.test(a)&&c.hasOwnProperty(a)&&!c.propertyIsEnumerable(a)&&"function"===typeof c[a]&&function(){for(var d=g.getOwnPropertyDescriptors(c[a].prototype),h=g.keys(d),k={},e=0,m=h.length|0,b,f;e<m;e=e+1|0)b=h[e],f=d[b],"nonce"===b||b.startsWith("on")&&null===
p[b]||"function"!==typeof f.set||-1===f.set.toString().indexOf("[native code]")||(k[b]={configurable:!0,enumerable:!0,get:f.get,set:q(b,f.set,f.get)});g.defineProperties(c[a].prototype,k)}()})(document.firstElementChild,Object,window);//AnonyCo
|
import React from 'react'
import Svg from './Svg'
export const SvgPlusSquare = ({ size, ...props }) => (
<Svg
width={size}
height={size}
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
className="plus-square_svg__feather plus-square_svg__feather-plus-square"
viewBox="0 0 24 24"
fill="none"
{...props}
>
<rect x={3} y={3} width={18} height={18} rx={2} ry={2} />
<path d="M12 8v8M8 12h8" />
</Svg>
)
SvgPlusSquare.isIcon = true
SvgPlusSquare.defaultProps = {
size: 24
}
export default SvgPlusSquare
|
var callbackArguments = [];
var argument1 = null;
var argument2 = null;
var argument3 = null;
var base_0 = [":,<2","nk","^","]","q","$","`"]
var r_0= undefined
try {
r_0 = base_0.some(argument1,argument2,argument3)
}
catch(e) {
r_0= "Error"
}
function serialize(array){
return array.map(function(a){
if (a === null || a == undefined) return a;
var name = a.constructor.name;
if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String')
return JSON.stringify(a);
return name;
});
}
setTimeout(function(){
require("fs").writeFileSync("./experiments/some/someRandom/test28.json",JSON.stringify({"baseObjects":serialize([base_0]),"returnObjects":serialize([r_0]),"callbackArgs":callbackArguments}))
},300)
|
const GuardConfig = {
registerMethods: ['email'],
loginMethods: ['password'],
mode: 'modal',
logo: 'https://static.nicegoodthings.com/project/ext/wb.logo.png',
title: 'Webrowse',
socialConnections: ['github', 'google'],
appHost: "https://portal-lite-china.authing.cn",
lang: 'en-US'
};
const appId = '6034a70af621af721e5320b9'
export { appId, GuardConfig }
export default GuardConfig
|
var metadata = require('./_metadata')
, anObject = require('./_an-object')
, getPrototypeOf = require('./_object-gpo')
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
|
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 23.2.3.2
description: >
Set.prototype.clear ( )
1. Let S be the this value.
2. If Type(S) is not Object, throw a TypeError exception.
---*/
assert.throws(TypeError, function() {
Set.prototype.clear.call("");
});
assert.throws(TypeError, function() {
var s = new Set();
s.clear.call("");
});
|
import { GraphQLFloat, GraphQLObjectType } from 'graphql';
export const ItemPriceType = new GraphQLObjectType({
name: 'ItemPriceType',
description: 'Item Price',
fields: () => ({
amount: {
type: GraphQLFloat
}
})
});
|
import { GET_ACTIVE_HOUSE_SUCCESS, GET_ACTIVE_HOUSE_START } from '../constants/actionTypes';
import { loadReview, getReviewIsFinished, resetReviews, getReviewStart } from './reviewsActions';
import { loadUser } from './userActions';
import housesApi from '../api/housesApi';
export function loadActiveHouseStart() {
return {type: GET_ACTIVE_HOUSE_START};
}
export function loadActiveHouseSuccess(house) {
return {type: GET_ACTIVE_HOUSE_SUCCESS, payload: house};
}
export function loadHouse(id) {
return function(dispatch) {
dispatch(getReviewStart());
dispatch(loadActiveHouseStart());
dispatch(resetReviews());
return housesApi.getHouse(id).then(house => {
let promises = [];
promises.push(dispatch(loadUser(house.ownerId)))
house.reviews.forEach(reviewId => {
promises.push(dispatch(loadReview(reviewId, house.id)))
})
return Promise.all(promises).then(() => {
dispatch(loadActiveHouseSuccess(house));
dispatch(getReviewIsFinished());
});
}).catch(error => {
throw(error);
});
};
}
|
/**
* Copyright IBM Corp. 2016, 2021
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*
* Code generated by @carbon/icon-build-helpers. DO NOT EDIT.
*/
'use strict';
var iconPropTypes = require('./iconPropTypes-379308c1.js');
var React = require('react');
require('@carbon/icon-helpers');
require('prop-types');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var _path;
var PenFountain = /*#__PURE__*/React__default['default'].forwardRef(function PenFountain(_ref, ref) {
var children = _ref.children,
_ref$size = _ref.size,
size = _ref$size === void 0 ? 16 : _ref$size,
rest = iconPropTypes._objectWithoutProperties(_ref, ["children", "size"]);
return /*#__PURE__*/React__default['default'].createElement(iconPropTypes.Icon, iconPropTypes._objectSpread2({
width: size,
height: size,
ref: ref,
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 32 32",
fill: "currentColor"
}, rest), _path || (_path = /*#__PURE__*/React__default['default'].createElement("path", {
d: "M29.707,5.293l-3-3a.9994.9994,0,0,0-1.414,0L19.5859,8H17.0947A11.0118,11.0118,0,0,0,6.7124,15.3662L2.0562,28.67a1,1,0,0,0,1.2744,1.2739l13.3037-4.6562A11.012,11.012,0,0,0,24,14.9053V12.4141L29.707,6.707A.9994.9994,0,0,0,29.707,5.293Zm-7.414,6A1,1,0,0,0,22,12v2.9053A9.01,9.01,0,0,1,15.9731,23.4l-9.1677,3.209L16,17.4141,14.5859,16,5.3914,25.1948,8.6,16.0269A9.01,9.01,0,0,1,17.0947,10H20a1,1,0,0,0,.707-.293L26,4.4141,27.5859,6Z"
})), children);
});
PenFountain.propTypes = iconPropTypes.iconPropTypes;
module.exports = PenFountain;
|
export { default as raised } from './raised.svelte';
export { default as depressed } from './depressed.svelte';
export { default as block } from './block.svelte';
export { default as fab } from './fab.svelte';
export { default as icon } from './icon.svelte';
export { default as outlined } from './outlined.svelte';
export { default as rounded } from './rounded.svelte';
export { default as text } from './text.svelte';
export { default as tile } from './tile.svelte';
export { default as sizing } from './sizing.svelte';
|
import React, { Component } from "react";
import { GlobalStyle1 } from "./statics/global/style";
import { GlobalStyle2 } from "./statics/global/iconfont/iconfont";
import { Provider } from "react-redux";
import store from "./store";
import { BrowserRouter, Route } from "react-router-dom";
import Header from "./pages/header";
import Home from "./pages/home";
import Detail from "./pages/detail";
import Login from './pages/login/loadable.js'
import Write from './pages/write'
class App extends Component {
render() {
return (
<div>
<GlobalStyle1 />
<GlobalStyle2 />
<Provider store={store}>
<BrowserRouter>
<div>
<Header />
<Route path="/" exact component={Home} />
<Route path="/detail/:id" exact component={Detail} />
<Route path="/login" exact component={Login} />
<Route path="/write" exact component={Write} />
</div>
</BrowserRouter>
</Provider>
</div>
);
}
}
export default App;
|
define(function(require, exports, module) {
"use strict";
exports.snippetText = require("../requirejs/text!./ruby.snippets");
exports.scope = "ruby";
});
|
// Changes XML to JSON
function parseXmlToJson(string){
}
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
exports.xmlToJson = xmlToJson;
|
/*!
=========================================================
* Argon Dashboard - v1.0.0
=========================================================
* Product Page: https://www.creative-tim.com/product/argon-dashboard
* Copyright 2018 Creative Tim (https://www.creative-tim.com)
* Licensed under MIT (https://github.com/creativetimofficial/argon-dashboard/blob/master/LICENSE.md)
* Coded by www.creative-tim.com
=========================================================
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
//
// Bootstrap Datepicker
//
'use strict';
var Datepicker = (function() {
// Variables
var $datepicker = $('.datepicker');
// Methods
function init($this) {
var options = {
disableTouchKeyboard: true,
autoclose: false
};
$this.datepicker(options);
}
// Events
if ($datepicker.length) {
$datepicker.each(function() {
init($(this));
});
}
})();
//
// Icon code copy/paste
//
'use strict';
var CopyIcon = (function() {
// Variables
var $element = '.btn-icon-clipboard',
$btn = $($element);
// Methods
function init($this) {
$this.tooltip().on('mouseleave', function() {
// Explicitly hide tooltip, since after clicking it remains
// focused (as it's a button), so tooltip would otherwise
// remain visible until focus is moved away
$this.tooltip('hide');
});
var clipboard = new ClipboardJS($element);
clipboard.on('success', function(e) {
$(e.trigger)
.attr('title', 'Copied!')
.tooltip('_fixTitle')
.tooltip('show')
.attr('title', 'Copy to clipboard')
.tooltip('_fixTitle')
e.clearSelection()
});
}
// Events
if ($btn.length) {
init($btn);
}
})();
//
// Form control
//
'use strict';
var FormControl = (function() {
// Variables
var $input = $('.form-control');
// Methods
function init($this) {
$this.on('focus blur', function(e) {
$(this).parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
}).trigger('blur');
}
// Events
if ($input.length) {
init($input);
}
})();
//
// Google maps
//
var $map = $('#map-canvas'),
map,
lat,
lng,
color = "#5e72e4";
function initMap() {
map = document.getElementById('map-canvas');
lat = map.getAttribute('data-lat');
lng = map.getAttribute('data-lng');
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 12,
scrollwheel: false,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"landscape","elementType":"all","stylers":[{"color":"#f2f2f2"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":color},{"visibility":"on"}]}]
}
map = new google.maps.Map(map, mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP,
title: 'Hello World!'
});
var contentString = '<div class="info-window-content"><h2>Argon Dashboard</h2>' +
'<p>A beautiful Dashboard for Bootstrap 4. It is Free and Open Source.</p></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
if($map.length) {
google.maps.event.addDomListener(window, 'load', initMap);
}
// //
// // Headroom - show/hide navbar on scroll
// //
//
// 'use strict';
//
// var Headroom = (function() {
//
// // Variables
//
// var $headroom = $('#navbar-main');
//
//
// // Methods
//
// function init($this) {
//
// var headroom = new Headroom(document.querySelector("#navbar-main"), {
// offset: 300,
// tolerance: {
// up: 30,
// down: 30
// },
// });
//
//
//
// // Events
//
// if ($headroom.length) {
// headroom.init();
// }
//
// })();
//
// Navbar
//
'use strict';
var Navbar = (function() {
// Variables
var $nav = $('.navbar-nav, .navbar-nav .nav');
var $collapse = $('.navbar .collapse');
var $dropdown = $('.navbar .dropdown');
// Methods
function accordion($this) {
$this.closest($nav).find($collapse).not($this).collapse('hide');
}
function closeDropdown($this) {
var $dropdownMenu = $this.find('.dropdown-menu');
$dropdownMenu.addClass('close');
setTimeout(function() {
$dropdownMenu.removeClass('close');
}, 200);
}
// Events
$collapse.on({
'show.bs.collapse': function() {
accordion($(this));
}
})
$dropdown.on({
'hide.bs.dropdown': function() {
closeDropdown($(this));
}
})
})();
//
// Navbar collapse
//
var NavbarCollapse = (function() {
// Variables
var $nav = $('.navbar-nav'),
$collapse = $('.navbar .collapse');
// Methods
function hideNavbarCollapse($this) {
$this.addClass('collapsing-out');
}
function hiddenNavbarCollapse($this) {
$this.removeClass('collapsing-out');
}
// Events
if ($collapse.length) {
$collapse.on({
'hide.bs.collapse': function() {
hideNavbarCollapse($collapse);
}
})
$collapse.on({
'hidden.bs.collapse': function() {
hiddenNavbarCollapse($collapse);
}
})
}
})();
//
// Form control
//
'use strict';
var noUiSlider = (function() {
// Variables
// var $sliderContainer = $('.input-slider-container'),
// $slider = $('.input-slider'),
// $sliderId = $slider.attr('id'),
// $sliderMinValue = $slider.data('range-value-min');
// $sliderMaxValue = $slider.data('range-value-max');;
// // Methods
//
// function init($this) {
// $this.on('focus blur', function(e) {
// $this.parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
// }).trigger('blur');
// }
//
//
// // Events
//
// if ($input.length) {
// init($input);
// }
if ($(".input-slider-container")[0]) {
$('.input-slider-container').each(function() {
var slider = $(this).find('.input-slider');
var sliderId = slider.attr('id');
var minValue = slider.data('range-value-min');
var maxValue = slider.data('range-value-max');
var sliderValue = $(this).find('.range-slider-value');
var sliderValueId = sliderValue.attr('id');
var startValue = sliderValue.data('range-value-low');
var c = document.getElementById(sliderId),
d = document.getElementById(sliderValueId);
noUiSlider.create(c, {
start: [parseInt(startValue)],
connect: [true, false],
//step: 1000,
range: {
'min': [parseInt(minValue)],
'max': [parseInt(maxValue)]
}
});
c.noUiSlider.on('update', function(a, b) {
d.textContent = a[b];
});
})
}
if ($("#input-slider-range")[0]) {
var c = document.getElementById("input-slider-range"),
d = document.getElementById("input-slider-range-value-low"),
e = document.getElementById("input-slider-range-value-high"),
f = [d, e];
noUiSlider.create(c, {
start: [parseInt(d.getAttribute('data-range-value-low')), parseInt(e.getAttribute('data-range-value-high'))],
connect: !0,
range: {
min: parseInt(c.getAttribute('data-range-value-min')),
max: parseInt(c.getAttribute('data-range-value-max'))
}
}), c.noUiSlider.on("update", function(a, b) {
f[b].textContent = a[b]
})
}
})();
//
// Popover
//
'use strict';
var Popover = (function() {
// Variables
var $popover = $('[data-toggle="popover"]'),
$popoverClass = '';
// Methods
function init($this) {
if ($this.data('color')) {
$popoverClass = 'popover-' + $this.data('color');
}
var options = {
trigger: 'focus',
template: '<div class="popover ' + $popoverClass + '" role="tooltip"><div class="arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>'
};
$this.popover(options);
}
// Events
if ($popover.length) {
$popover.each(function() {
init($(this));
});
}
})();
//
// Scroll to (anchor links)
//
'use strict';
var ScrollTo = (function() {
//
// Variables
//
var $scrollTo = $('.scroll-me, [data-scroll-to], .toc-entry a');
//
// Methods
//
function scrollTo($this) {
var $el = $this.attr('href');
var offset = $this.data('scroll-to-offset') ? $this.data('scroll-to-offset') : 0;
var options = {
scrollTop: $($el).offset().top - offset
};
// Animate scroll to the selected section
$('html, body').stop(true, true).animate(options, 600);
event.preventDefault();
}
//
// Events
//
if ($scrollTo.length) {
$scrollTo.on('click', function(event) {
scrollTo($(this));
});
}
})();
//
// Tooltip
//
'use strict';
var Tooltip = (function() {
// Variables
var $tooltip = $('[data-toggle="tooltip"]');
// Methods
function init() {
$tooltip.tooltip();
}
// Events
if ($tooltip.length) {
init();
}
})();
//
// Charts
//
'use strict';
var Charts = (function() {
// Variable
var $toggle = $('[data-toggle="chart"]');
var mode = 'light';//(themeMode) ? themeMode : 'light';
var fonts = {
base: 'Open Sans'
}
// Colors
var colors = {
gray: {
100: '#f6f9fc',
200: '#e9ecef',
300: '#dee2e6',
400: '#ced4da',
500: '#adb5bd',
600: '#8898aa',
700: '#525f7f',
800: '#32325d',
900: '#212529'
},
theme: {
'default': '#172b4d',
'primary': '#5e72e4',
'secondary': '#f4f5f7',
'info': '#11cdef',
'success': '#2dce89',
'danger': '#f5365c',
'warning': '#fb6340'
},
black: '#12263F',
white: '#FFFFFF',
transparent: 'transparent',
};
// Methods
// Chart.js global options
function chartOptions() {
// Options
var options = {
defaults: {
global: {
responsive: true,
maintainAspectRatio: false,
defaultColor: (mode == 'dark') ? colors.gray[700] : colors.gray[600],
defaultFontColor: (mode == 'dark') ? colors.gray[700] : colors.gray[600],
defaultFontFamily: fonts.base,
defaultFontSize: 13,
layout: {
padding: 0
},
legend: {
display: false,
position: 'bottom',
labels: {
usePointStyle: true,
padding: 16
}
},
elements: {
point: {
radius: 0,
backgroundColor: colors.theme['primary']
},
line: {
tension: .4,
borderWidth: 4,
borderColor: colors.theme['primary'],
backgroundColor: colors.transparent,
borderCapStyle: 'rounded'
},
rectangle: {
backgroundColor: colors.theme['warning']
},
arc: {
backgroundColor: colors.theme['primary'],
borderColor: (mode == 'dark') ? colors.gray[800] : colors.white,
borderWidth: 4
}
},
tooltips: {
enabled: false,
mode: 'index',
intersect: false,
custom: function(model) {
// Get tooltip
var $tooltip = $('#chart-tooltip');
// Create tooltip on first render
if (!$tooltip.length) {
$tooltip = $('<div id="chart-tooltip" class="popover bs-popover-top" role="tooltip"></div>');
// Append to body
$('body').append($tooltip);
}
// Hide if no tooltip
if (model.opacity === 0) {
$tooltip.css('display', 'none');
return;
}
function getBody(bodyItem) {
return bodyItem.lines;
}
// Fill with content
if (model.body) {
var titleLines = model.title || [];
var bodyLines = model.body.map(getBody);
var html = '';
// Add arrow
html += '<div class="arrow"></div>';
// Add header
titleLines.forEach(function(title) {
html += '<h3 class="popover-header text-center">' + title + '</h3>';
});
// Add body
bodyLines.forEach(function(body, i) {
var colors = model.labelColors[i];
var styles = 'background-color: ' + colors.backgroundColor;
var indicator = '<span class="badge badge-dot"><i class="bg-primary"></i></span>';
var align = (bodyLines.length > 1) ? 'justify-content-left' : 'justify-content-center';
html += '<div class="popover-body d-flex align-items-center ' + align + '">' + indicator + body + '</div>';
});
$tooltip.html(html);
}
// Get tooltip position
var $canvas = $(this._chart.canvas);
var canvasWidth = $canvas.outerWidth();
var canvasHeight = $canvas.outerHeight();
var canvasTop = $canvas.offset().top;
var canvasLeft = $canvas.offset().left;
var tooltipWidth = $tooltip.outerWidth();
var tooltipHeight = $tooltip.outerHeight();
var top = canvasTop + model.caretY - tooltipHeight - 16;
var left = canvasLeft + model.caretX - tooltipWidth / 2;
// Display tooltip
$tooltip.css({
'top': top + 'px',
'left': left + 'px',
'display': 'block',
'z-index': '100'
});
},
callbacks: {
label: function(item, data) {
var label = data.datasets[item.datasetIndex].label || '';
var yLabel = item.yLabel;
var content = '';
if (data.datasets.length > 1) {
content += '<span class="badge badge-primary mr-auto">' + label + '</span>';
}
content += '<span class="popover-body-value">' + yLabel + '</span>' ;
return content;
}
}
}
},
doughnut: {
cutoutPercentage: 83,
tooltips: {
callbacks: {
title: function(item, data) {
var title = data.labels[item[0].index];
return title;
},
label: function(item, data) {
var value = data.datasets[0].data[item.index];
var content = '';
content += '<span class="popover-body-value">' + value + '</span>';
return content;
}
}
},
legendCallback: function(chart) {
var data = chart.data;
var content = '';
data.labels.forEach(function(label, index) {
var bgColor = data.datasets[0].backgroundColor[index];
content += '<span class="chart-legend-item">';
content += '<i class="chart-legend-indicator" style="background-color: ' + bgColor + '"></i>';
content += label;
content += '</span>';
});
return content;
}
}
}
}
// yAxes
Chart.scaleService.updateScaleDefaults('linear', {
gridLines: {
borderDash: [2],
borderDashOffset: [2],
color: (mode == 'dark') ? colors.gray[900] : colors.gray[300],
drawBorder: false,
drawTicks: false,
lineWidth: 0,
zeroLineWidth: 0,
zeroLineColor: (mode == 'dark') ? colors.gray[900] : colors.gray[300],
zeroLineBorderDash: [2],
zeroLineBorderDashOffset: [2]
},
ticks: {
beginAtZero: true,
padding: 10,
callback: function(value) {
if (!(value % 10)) {
return value
}
}
}
});
// xAxes
Chart.scaleService.updateScaleDefaults('category', {
gridLines: {
drawBorder: false,
drawOnChartArea: false,
drawTicks: false
},
ticks: {
padding: 20
},
maxBarThickness: 10
});
return options;
}
// Parse global options
function parseOptions(parent, options) {
for (var item in options) {
if (typeof options[item] !== 'object') {
parent[item] = options[item];
} else {
parseOptions(parent[item], options[item]);
}
}
}
// Push options
function pushOptions(parent, options) {
for (var item in options) {
if (Array.isArray(options[item])) {
options[item].forEach(function(data) {
parent[item].push(data);
});
} else {
pushOptions(parent[item], options[item]);
}
}
}
// Pop options
function popOptions(parent, options) {
for (var item in options) {
if (Array.isArray(options[item])) {
options[item].forEach(function(data) {
parent[item].pop();
});
} else {
popOptions(parent[item], options[item]);
}
}
}
// Toggle options
function toggleOptions(elem) {
var options = elem.data('add');
var $target = $(elem.data('target'));
var $chart = $target.data('chart');
if (elem.is(':checked')) {
// Add options
pushOptions($chart, options);
// Update chart
$chart.update();
} else {
// Remove options
popOptions($chart, options);
// Update chart
$chart.update();
}
}
// Update options
function updateOptions(elem) {
var options = elem.data('update');
var $target = $(elem.data('target'));
var $chart = $target.data('chart');
// Parse options
parseOptions($chart, options);
// Toggle ticks
toggleTicks(elem, $chart);
// Update chart
$chart.update();
}
// Toggle ticks
function toggleTicks(elem, $chart) {
if (elem.data('prefix') !== undefined || elem.data('prefix') !== undefined) {
var prefix = elem.data('prefix') ? elem.data('prefix') : '';
var suffix = elem.data('suffix') ? elem.data('suffix') : '';
// Update ticks
$chart.options.scales.yAxes[0].ticks.callback = function(value) {
if (!(value % 10)) {
return prefix + value + suffix;
}
}
// Update tooltips
$chart.options.tooltips.callbacks.label = function(item, data) {
var label = data.datasets[item.datasetIndex].label || '';
var yLabel = item.yLabel;
var content = '';
if (data.datasets.length > 1) {
content += '<span class="popover-body-label mr-auto">' + label + '</span>';
}
content += '<span class="popover-body-value">' + prefix + yLabel + suffix + '</span>';
return content;
}
}
}
// Events
// Parse global options
if (window.Chart) {
parseOptions(Chart, chartOptions());
}
// Toggle options
$toggle.on({
'change': function() {
var $this = $(this);
if ($this.is('[data-add]')) {
toggleOptions($this);
}
},
'click': function() {
var $this = $(this);
if ($this.is('[data-update]')) {
updateOptions($this);
}
}
});
// Return
return {
colors: colors,
fonts: fonts,
mode: mode
};
})();
//
// Orders chart
//
var OrdersChart = (function() {
//
// Variables
//
var $chart = $('#chart-orders');
var $ordersSelect = $('[name="ordersSelect"]');
//
// Methods
//
// Init chart
function initChart($chart) {
// Create chart
var ordersChart = new Chart($chart, {
type: 'bar',
options: {
scales: {
yAxes: [{
ticks: {
callback: function(value) {
if (!(value % 10)) {
//return '$' + value + 'k'
return value
}
}
}
}]
},
tooltips: {
callbacks: {
label: function(item, data) {
var label = data.datasets[item.datasetIndex].label || '';
var yLabel = item.yLabel;
var content = '';
if (data.datasets.length > 1) {
content += '<span class="popover-body-label mr-auto">' + label + '</span>';
}
content += '<span class="popover-body-value">' + yLabel + '</span>';
return content;
}
}
}
},
data: {
labels: ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Sales',
data: [25, 20, 30, 22, 17, 29]
}]
}
});
// Save to jQuery object
$chart.data('chart', ordersChart);
}
// Init chart
if ($chart.length) {
initChart($chart);
}
})();
//
// Charts
//
'use strict';
//
// Sales chart
//
var SalesChart = (function() {
// Variables
var $chart = $('#chart-sales');
// Methods
function init($chart) {
var salesChart = new Chart($chart, {
type: 'line',
options: {
scales: {
yAxes: [{
gridLines: {
color: Charts.colors.gray[900],
zeroLineColor: Charts.colors.gray[900]
},
ticks: {
callback: function(value) {
if (!(value % 10)) {
return '$' + value + 'k';
}
}
}
}]
},
tooltips: {
callbacks: {
label: function(item, data) {
var label = data.datasets[item.datasetIndex].label || '';
var yLabel = item.yLabel;
var content = '';
if (data.datasets.length > 1) {
content += '<span class="popover-body-label mr-auto">' + label + '</span>';
}
content += '<span class="popover-body-value">$' + yLabel + 'k</span>';
return content;
}
}
}
},
data: {
labels: ['May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Performance',
data: [0, 20, 10, 30, 15, 40, 20, 60, 60]
}]
}
});
// Save to jQuery object
$chart.data('chart', salesChart);
}
// Events
if ($chart.length) {
init($chart);
}
})();
|
export function registerElement(component, element) {
component.element = element;
}
export function deregisterElement(component) {
component.element = null;
}
|
import { SAVE_COMMENT } from '../actions/types';
export default function(state = [], action) {
console.log(action.type);
switch (action.type) {
case SAVE_COMMENT:
return [ ...state, action.payload ];
}
return state;
}
|
exports.run = (client, message) => {
const Discord = require('discord.js');
let user = message.mentions.users.first();
if (!user) {
return message.reply('You must mention someone!');
}
const mentioneduser = message.mentions.users.first();
const joineddiscord = (mentioneduser.createdAt.getDate() + 1) + '-' + (mentioneduser.createdAt.getMonth() + 1) + '-' + mentioneduser.createdAt.getFullYear() + ' | ' + mentioneduser.createdAt.getHours() + ':' + mentioneduser.createdAt.getMinutes() + ':' + mentioneduser.createdAt.getSeconds();
message.delete();
let game;
if (user.presence.game === null) {
game = 'Not currently Playing.';
} else {
game = user.presence.game.name;
}
let messag;
if (user.lastMessage === null) {
messag = 'He/She didnt sent a message.';
} else {
messag = user.lastMessage;
}
let status;
if (user.presence.status === 'online') {
status = ':green_heart:';
} else if (user.presence.status === 'dnd') {
status = ':heart:';
} else if (user.presence.status === 'idle') {
status = ':yellow_heart:';
} else if (user.presence.status === 'offline') {
status = ':black_heart:';
}
let stat;
if (user.presence.status === 'offline') {
stat = 0x000000;
} else if (user.presence.status === 'online') {
stat = 0x00AA4C;
} else if (user.presence.status === 'dnd') {
stat = 0x9C0000;
} else if (user.presence.status === 'idle') {
stat = 0xF7C035;
}
const embed = new Discord.RichEmbed()
.addField('**UserInfo:**', `**name:** ${user.username}#${user.discriminator}\n**JoinedDiscord:** ${joineddiscord}\n**LastMessage:** ${messag}\n**Playing:** ${game}\n**Status:** ${status}\n**Bot?** ${user.bot}`, true)
.setThumbnail(user.displayAvatarURL)
.addField(`Roles:`, '``' + message.mentions.members.first().roles.map(r => r.name).join(', ') + '``')
.addField('DiscordInfo:', `**Discriminator:** ${user.discriminator}\n**ID:** ${user.id}\n**Username:** ${user.username}`)
.setAuthor(`Info for ${user.username} Below`, user.displayAvatarURL)
.setColor(stat);
message.channel.send({embed})
.catch(e => logger.error(e));
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: [],
permLevel: "User"
};
exports.help = {
name: "userinfo",
category: "Info Commands",
description: "Userinfo about you or another user",
usage: "userinfo @user"
};
|
/**
* Copyright (c) Microsoft. 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.
*/
'use strict';
var util = require('util');
var adUtils = require('./adUtils');
var profile = require('../../../util/profile');
var utils = require('../../../util/utils');
var $ = utils.getLocaleString;
exports.init = function (cli) {
var log = cli.output;
var withProgress = cli.interaction.withProgress.bind(cli.interaction);
var ad = cli.category('ad')
.description($('Commands to display Active Directory objects'));
var adGroup = ad.category('group')
.description($('Commands to display Active Directory groups'));
adGroup.command('list')
.description($('Get Active Directory groups in current subscription\'s tenant. When --json flag is used, it will get the information from all the pages and then provide the final json array.'))
.option('| more', $('Provides paging support. Press \'Enter\' for more information.'))
.execute(function (objectId, options, _) {
var subscription = profile.current.getSubscription(options.subscription);
var client = adUtils.getADGraphClient(subscription);
var progress = cli.interaction.progress($('Listing Active Directory groups'));
try {
adUtils.listGraphObjects(client, 'group', cli.interaction, log, options.json, _);
} finally {
progress.end();
}
});
adGroup.command('show')
.description($('Get Active Directory groups'))
.option('-o --objectId <objectId>', $('the object Id of the group to return'))
.option('-c --search <search>', $('Search by display name which starts with the provided value'))
.execute(function (options, _) {
var objectId = options.objectId,
search = options.search;
adUtils.validateParameters({
objectId: objectId,
search: search
});
var subscription = profile.current.getSubscription(options.subscription);
var client = adUtils.getADGraphClient(subscription);
var progress = cli.interaction.progress($('Getting group list'));
var groups;
try {
groups = getSpecificGroups(client, objectId, search, _);
} finally {
progress.end();
}
if (groups.length > 0) {
adUtils.displayGroups(groups, cli.interaction, log);
} else {
log.data($('No matching group was found'));
}
});
adGroup.command('create [display-name] [mail-nickname]')
.description($('Creates an Active Directory group in the tenant.'))
.usage('[options] <display-name> <mail-nickname>')
.option('-d --display-name <display-name>', $('The name to display in the address book for the group.'))
.option('-m --mail-nickname <mail-nickname>', $('The mail alias for the group.'))
.execute(function (displayName, mailNickname, options, _) {
if (!displayName) {
return cli.missingArgument('display-name');
}
if (!mailNickname) {
return cli.missingArgument('mail-nickname');
}
// We are hardcoding mailEnabled to false and securityEnabled to true. This is because,
// the doc https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations#CreateGroup
// says so. It makes no sense to expose them to the users if they always need to have those values.
var parameters = {
displayName: displayName,
mailNickname: mailNickname
};
var subscription = profile.current.getSubscription(options.subscription);
var client = adUtils.getADGraphClient(subscription);
var group = withProgress(util.format($('Creating Active Directory group: \'%s\'.'), displayName),
function (log, _) {
return client.groups.create(parameters, _);
}, _);
cli.interaction.formatOutput(group, function (data) {
if (data) {
adUtils.displayAGroup(data, log, true);
}
});
});
adGroup.command('delete [objectId]')
.description($('Deletes an Active Directory group.'))
.usage('[options] <objectId>')
.option('-o --objectId <objectId>', $('the object Id of the group to delete'))
.option('-q, --quiet', $('quiet mode (do not ask for delete confirmation)'))
.execute(function (objectId, options, _) {
adUtils.validateParameters({
objectId: objectId
});
if (!options.quiet && !cli.interaction.confirm(util.format($('Delete group \'%s\' ? [y/n] '), objectId), _)) {
return;
}
var subscription = profile.current.getSubscription(options.subscription);
var client = adUtils.getADGraphClient(subscription);
var progress = cli.interaction.progress($('Deleting group with objectId: ' + objectId));
try {
client.groups.deleteMethod(objectId, _);
} finally {
progress.end();
}
});
var adGroupMember = adGroup.category('member')
.description($('Commands to provide an Active Directory sub group or member info'));
adGroupMember.command('list [objectId]')
.description($('Provides an Active Directory sub group or member info. When --json flag is used, it will get the information from all the pages and then provide the final json array.'))
.usage('[options] <objectId>')
.option('-o --objectId <objectId>', $('Object id of group whose members to return.'))
.option('| more', $('Provides paging support. Press \'Enter\' for more information.'))
.execute(function (objectId, options, _) {
if (!objectId) {
return cli.missingArgument('objectId');
}
var subscription = profile.current.getSubscription(options.subscription);
var client = adUtils.getADGraphClient(subscription);
var progress = cli.interaction.progress($('Getting group members'));
try {
adUtils.listGroupMembers(client, objectId, cli.interaction, log, options.json, _);
} finally {
progress.end();
}
});
adGroupMember.command('add [objectId] [member-objectId]')
.description($('Adds a member to an Active Directory group.'))
.usage('[options] <objectId> <member-objectId>')
.option('-o --objectId <objectId>', $('Object id of group to which the member needs to be added.'))
.option('-m --member-objectId <member-objectId>', $('Object id of the member (application, user, servicePrincipal, ' +
'another-group) to be added to this group.'))
.option('-e --graph-endpoint <graph-endpoint>', $('The graph endpoint which will be the part of the member url created by the command. Default value: \'https://graph.windows.net\'.'))
.option('-t --tenant <tenant>', $('TenantId (in a GUID format) to which the member belongs. Default value is the current tenant of the logged in user/sp.'))
.execute(function (objectId, memberObjectId, options, _) {
if (!options) options = {};
if (!objectId) {
return cli.missingArgument('objectId');
}
if (!memberObjectId) {
return cli.missingArgument('member-objectId');
}
var subscription = profile.current.getSubscription(options.subscription);
var tenant = options.tenant;
if (!tenant) tenant = subscription.tenantId;
var endpoint = options.graphEndpoint;
if (!endpoint) endpoint = 'https://graph.windows.net';
var memberUrl = util.format('%s/%s/directoryObjects/%s', endpoint, tenant, memberObjectId);
var progress = cli.interaction.progress(util.format($('Adding member \'%s\' to the Group \'%s\'.'), memberUrl, objectId));
var client = adUtils.getADGraphClient(subscription);
try {
client.groups.addMember(objectId, memberUrl, _);
} finally {
progress.end();
}
});
adGroupMember.command('delete [objectId] [member-objectId]')
.description($('Deletes a member from an Active Directory group.'))
.usage('[options] <objectId> <member-objectId>')
.option('-o --objectId <objectId>', $('Object id of group from which the member needs to be deleted.'))
.option('-m --member-objectId <member-objectId>', $('Object id of the member (application, user, servicePrincipal, ' +
'another-group) to be deleted from this group.'))
.option('-q, --quiet', $('quiet mode (do not ask for delete confirmation)'))
.execute(function (objectId, memberObjectId, options, _) {
if (!objectId) {
return cli.missingArgument('objectId');
}
if (!memberObjectId) {
return cli.missingArgument('member-objectId');
}
if (!options.quiet && !cli.interaction.confirm(util.format($('Delete member from the group \'%s\' ? [y/n] '), objectId), _)) {
return;
}
var subscription = profile.current.getSubscription(options.subscription);
var client = adUtils.getADGraphClient(subscription);
var progress = cli.interaction.progress(util.format($('Deleting member \'%s\' from Group \'%s\'.'), memberObjectId, objectId));
try {
client.groups.removeMember(objectId, memberObjectId, _);
} finally {
progress.end();
}
});
adGroupMember.command('check [objectId] [member-objectId]')
.description($('Checks whether the specified user, group, contact, or service principal is a direct or a transitive member of the specified Active Directory group.'))
.usage('[options] <objectId> <member-objectId>')
.option('-o --objectId <objectId>', $('Object id of group against which the membership needs to be checked.'))
.option('-m --member-objectId <member-objectId>', $('Object id of the member (application, user, servicePrincipal, ' +
'another-group) for which membership needs to be checked in the specified group.'))
.execute(function (objectId, memberObjectId, options, _) {
if (!options) options = {};
if (!objectId) {
return cli.missingArgument('objectId');
}
if (!memberObjectId) {
return cli.missingArgument('member-objectId');
}
var progress = cli.interaction.progress(util.format($('Checking membership of member \'%s\' in the Group \'%s\'.'), memberObjectId, objectId));
var subscription = profile.current.getSubscription(options.subscription);
var client = adUtils.getADGraphClient(subscription);
var result;
try {
var parameters = { groupId: objectId, memberId: memberObjectId };
result = client.groups.isMemberOf(parameters, _);
} finally {
progress.end();
}
if (options.json) {
log.json(result);
} else {
log.data($('IsMember: '), result.value ? 'true' : 'false' );
}
});
};
function getSpecificGroups(client, objectId, search, _) {
if (search) {
var parameters = { filter: 'startswith(displayName,\'' + search + '\')' };
return client.groups.list(parameters, _);
} else {
var group = client.groups.get(objectId, _);
return group ? [group] : [];
}
}
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import './editor.all';
import './standalone/browser/accessibilityHelp/accessibilityHelp';
import './standalone/browser/inspectTokens/inspectTokens';
import './standalone/browser/iPadShowKeyboard/iPadShowKeyboard';
import './standalone/browser/quickOpen/quickOutline';
import './standalone/browser/quickOpen/gotoLine';
import './standalone/browser/quickOpen/quickCommand';
import './standalone/browser/toggleHighContrast/toggleHighContrast';
import './standalone/browser/referenceSearch/standaloneReferenceSearch';
export * from './editor.api';
|
$(document).ready(function() {
AttachTaskListeners();
AttachProjectIndexListeners();
AttachSearchListener();
});
function AttachTaskListeners () {
var tasks = $('.todo li');
for (var i=0; i<tasks.length; i++) {
var task = $(tasks[i]);
$(task).on("click", function (e) {
if (!$(e.target).hasClass("fui-document")) {
$(e.target.closest("li")).toggleClass("todo-done");
}
});
}
}
function AttachProjectIndexListeners () {
var projects = $('.project-index li');
for (var i=0; i<projects.length; i++) {
var project = $(projects[i]);
$(project).on("click", function (e) {
SwitchProject($(e.target));
})
}
}
function SwitchProject (project) {
var name = project.html();
console.log(name);
var headers = $('.project-header');
for (var i=0; i<headers.length; i++) {
var header = $(headers[i]);
if (header.html() != name && name != "All") {
header.closest('.project').slideUp();
}
else header.closest('.project').slideDown();
}
}
function AttachSearchListener () {
$('.todo-search-field').on("keyup", function(e) {
var input = e.target.value;
FilterTasks(input);
});
}
function FilterTasks (filter) {
var tasks = $('.task');
for (var i=0; i<tasks.length; i++) {
var task = $(tasks[i]);
var name = $(task.find('.todo-name')).html();
if (ContainsString(name, filter)) task.show();
else task.hide();
}
}
function ContainsString (string, substring) {
return string.toLowerCase().indexOf(substring.toLowerCase()) >= 0;
}
|
import PropTypes from 'prop-types';
import clsx from 'clsx';
function foo(props) {
const { position: p } = props;
const x = clsx(p === 'top' && classes.x, p === 'bottom' && classes.y);
}
foo.propTypes = {
position: PropTypes.oneOf(['top', 'bottom']).isRequired,
};
|
import React from 'react';
import PropTypes from 'prop-types';
import { autoScrollUpDown } from '../../../hocs/autoScrollUpDown';
import { noop } from '../../../utils/misc';
import { BlockContentBoxAreaStyled } from './styles/BlockContentBoxAreaStyled';
const propTypes = {
isBordered: PropTypes.bool,
flex: PropTypes.bool,
spread: PropTypes.bool,
notScrollable: PropTypes.bool,
hidden: PropTypes.bool,
elementRef: PropTypes.func,
colorScheme: PropTypes.oneOf(['default', 'alt']),
};
const defaultProps = {
isBordered: false,
flex: false,
spread: false,
notScrollable: false,
hidden: false,
elementRef: noop,
colorScheme: 'default',
};
const BlockContentBoxComponent = props => {
const style = {};
if (props.hidden) style.display = 'none';
return (
<BlockContentBoxAreaStyled
bordered={props.isBordered}
scrollable={!props.notScrollable}
colorScheme={props.colorScheme}
flex={props.flex}
spread={props.spread}
style={style}
innerRef={props.elementRef}
>
{props.children}
</BlockContentBoxAreaStyled>
);
};
BlockContentBoxComponent.propTypes = propTypes;
BlockContentBoxComponent.defaultProps = defaultProps;
BlockContentBoxComponent.displayName = 'BlockContentBox';
export const BlockContentBox = autoScrollUpDown(BlockContentBoxComponent);
export * from './BlockContentBoxItem/BlockContentBoxItem';
export * from './BlockContentBoxHeading/BlockContentBoxHeading';
export * from './BlockContentBoxGroup/BlockContentBoxGroup';
|
// Copyright © 2021 The Things Network Foundation, The Things Industries B.V.
//
// 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 { defineMessages } from 'react-intl'
import GLOSSARY_IDS from '@ttn-lw/lib/constants/glossary-ids'
const m = defineMessages({
freqPlanDescription:
'A Frequency Plan defines data rates and channels which comply with the LoRaWAN Regional Parameters for a band or geographical area.',
freqPlanLocation:
'You need to choose a Frequency Plan which adheres to the local regulations of where your end device is located. It is also important that the gateways in reach of this end device use the same Frequency Plan.',
devEuiDescription: 'A 64 bit extended unique identifier for your end device.',
devEuiLocation:
'It should be provided to you by the manufacturer, or printed on the end device packaging.',
devEuiAbsence: 'Contact the manufacturer or your reseller.',
joinEuiDescription:
'The JoinEUI (formerly called AppEUI) is a 64 bit extended unique identifier used to identify the Join Server during activation.',
joinEuiLocation:
'It should be provided by the end device manufacturer for pre-provisioned end devices, or by the owner of the Join Server you will use.',
joinEuiAbsence:
'Contact the manufacturer or your reseller. If they can not provide a JoinEUI, and your end device is programmable, it is okay to use all-zeros, but ensure that you use the same JoinEUI in your device as you enter in The Things Stack.',
appKeyDescription:
'An end device specific encryption key used during OTAA to derive the AppSKey (in LoRaWAN 1.1x) or both the NwkSKey and AppSKey in LoRaWAN 1.0x.',
appKeyLocation:
'It is usually pre-provisioned by the end device manufacturer, but can also be created by the user.',
appKeyAbsence:
'Contact the manufacturer or your reseller. If they cannot provide an AppKey, and your end device is programmable, it is okay to generate one.',
nwkKeyDescription:
'A device specific encryption key used to derive the FNwkSIntKey, SNwkSIntKey, NwkSEncKey in LoRaWAN 1.1. When a LoRaWAN 1.1 capable device connects to a LoRaWAN 1.0x Network Server which does not support dual root keys (NwkKey and AppKey), the NwkKey value is used as the AppKey value.',
nwkKeyLocation:
'It is usually pre-provisioned by the end device manufacturer, but some end devices also allow using a user-defined value.',
nwkKeyAbsence:
'Contact the manufacturer or your reseller. If they cannot provide an AppKey, and your end device is programmable, it is okay to generate one.',
devIdDescription: 'A unique, human-readable identifier for your end device.',
devIdLocation:
'You can make it up, so be creative. End device IDs can not be reused by multiple end devices within the same application.',
joinServerDescription:
"The Join Server's role is to store root keys, generate session keys, and to send those securely to the Network Server and Application Server of choice. The device contains the same root keys, which can be provisioned as part of assembly, distribution or upon installation.",
joinServerLocation:
'Contact your manufacturer or reseller to find out if your end device is pre-provisioned on an external Join Server. If not, you may use the local Join Server, or provision the end device on our Global Join Server so that you can transfer it without lock-in.',
joinServerAbsence:
'If the end device is pre-provisioned, you will need the keys from the manufacturer to activate it.',
devAddrDescription:
'A 32 bit non-unique identifier, assigned by the Network Server during end device activation.',
devAddrLocation:
'For Activation-By-Personalization (ABP), you must generate a device address and manually program it into the end device. You can use the generate button next to the input field to generate a device address.',
appSKeyDescription:
'After activation, this encryption key is used to secure messages which carry a payload.',
appSKeyLocation:
'For Activation-By-Personalization (ABP), you must generate a key and manually program it into your end device. You can use the generate button next to the input field to generate a key.',
nwkSKeyDescription:
'After activation, this encryption key is used to secure messages which do not carry a payload.',
nwkSKeyLocation:
'For OTAA, it is created by the Network Server. If using ABP, you must create one and manually enter it in the end device and The Things Stack.',
lwVersionDescription:
'The LoRa Alliance LoRaWAN specification your end device conforms to, which defines which Media Access Control (MAC) features it supports.',
lwVersionLocation:
'The LoRaWAN version for your end device should be provided by the manufacturer in a datasheet as LoRaWAN version or LoRaWAN specification',
lwVersionAbsence:
'Contact your manufacturer or reseller, since specifying the wrong version can lead to complex issues when the Network Server provides the end device with unsupported configuration (MAC) commands.',
regParameterDescription:
'The Regional Parameters specify frequency, dwell time, and other communication settings for different geographical areas. The Regional Parameters version is the version of the LoRa Alliance specification which your device supports.',
regParameterLocation:
'The Regional Parameters version should be provided by the end device manufacturer in a datasheet.',
regParameterAbsence:
'Contact your manufacturer or reseller to obtain the correct specification. Specifying a wrong version can lead to complex issues when the Network Server provides the end device with unsupported configuration (MAC) commands.',
classDescription:
'The LoRaWAN specification defines three end device types. All LoRaWAN end devices must implement Class A, whereas Class B and Class C are extensions to the specification of Class A devices that specify different downlink reception behavior.',
classLocation:
'The class capabilities of your end device should be provided by the manufaturer in a datasheet.',
classAbsence:
'If your end device will not receive downlink messages, you can safely use Class A, which all LoRaWAN certified devices must implement. Otherwise contact your manufacturer or reseller.',
rx1DataRateOffsetDescription:
'The Data Rate Offset sets the offset between the uplink data rate and the downlink data rate used to communicate with the End Device during the first reception slot (RX1).',
dataRateIndexDescription:
'The Data Rate Index specifies which data rate downlink communications will use, as given in the Regional Parameters.',
})
const descriptions = Object.freeze({
[GLOSSARY_IDS.FREQUENCY_PLAN]: {
description: m.freqPlanDescription,
location: m.freqPlanLocation,
},
[GLOSSARY_IDS.DEV_EUI]: {
description: m.devEuiDescription,
location: m.devEuiLocation,
absence: m.devEuiAbsence,
},
[GLOSSARY_IDS.JOIN_EUI]: {
description: m.joinEuiDescription,
location: m.joinEuiLocation,
absence: m.joinEuiAbsence,
},
[GLOSSARY_IDS.APP_KEY]: {
description: m.appKeyDescription,
location: m.appKeyLocation,
absence: m.appKeyAbsence,
},
[GLOSSARY_IDS.NETWORK_KEY]: {
description: m.nwkKeyDescription,
location: m.nwkKeyLocation,
absence: m.nwkKeyAbsence,
},
[GLOSSARY_IDS.DEVICE_ID]: {
description: m.devIdDescription,
location: m.devIdLocation,
},
[GLOSSARY_IDS.JOIN_SERVER]: {
description: m.joinServerDescription,
location: m.joinServerLocation,
absence: m.joinServerAbsence,
},
[GLOSSARY_IDS.DEVICE_ADDRESS]: {
description: m.devAddrDescription,
location: m.devAddrLocation,
},
[GLOSSARY_IDS.APP_SESSION_KEY]: {
description: m.appSKeyDescription,
location: m.appSKeyLocation,
},
[GLOSSARY_IDS.NETWORK_SESSION_KEY]: {
description: m.nwkSKeyDescription,
location: m.nwkSKeyLocation,
},
[GLOSSARY_IDS.LORAWAN_VERSION]: {
description: m.lwVersionDescription,
location: m.lwVersionLocation,
absence: m.lwVersionAbsence,
},
[GLOSSARY_IDS.REGIONAL_PARAMETERS]: {
description: m.regParameterDescription,
location: m.regParameterLocation,
absence: m.regParameterAbsence,
},
[GLOSSARY_IDS.CLASSES]: {
description: m.classDescription,
location: m.classLocation,
absence: m.classAbsence,
},
[GLOSSARY_IDS.DATA_RATE_OFFSET]: {
description: m.rx1DataRateOffsetDescription,
},
[GLOSSARY_IDS.DATA_RATE_INDEX]: {
description: m.dataRateIndexDescription,
},
})
const links = Object.freeze({
[GLOSSARY_IDS.FREQUENCY_PLAN]: {
documentationPath: '/reference/frequency-plans',
},
})
export { descriptions, links }
|
export function configure(config) {
config.globalResources('./template-factory');
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es5id: 15.2.3.10-3-5
description: >
Object.preventExtensions - indexed properties cannot be added into
a String object
---*/
var strObj = new String();
var preCheck = Object.isExtensible(strObj);
Object.preventExtensions(strObj);
assert.throws(TypeError, function() {
Object.defineProperty(strObj, "0", {
value: "c"
});
});
assert(preCheck, 'preCheck !== true');
assert.sameValue(strObj.hasOwnProperty("0"), false, 'strObj.hasOwnProperty("0")');
assert.sameValue(typeof strObj[0], "undefined", 'typeof strObj[0]');
|
/*
* Copyright 2014 Amadeus s.a.s.
* 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.
*/
var Aria = require("ariatemplates/Aria");
module.exports = Aria.classDefinition({
$classpath : "test.aria.widgets.dropdown.touchDevices.SelectBoxPopupTouchRobotTestCase",
$extends : require("./RobotBase")
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObservableShim = exports.setObservable = exports.getObservable = void 0;
let _observable;
function getObservable() {
if (_observable) {
return _observable;
}
if (typeof window !== 'undefined' && window.Observable) {
_observable = window.Observable;
return _observable;
}
try {
const { Observable } = require('rxjs'); //'rxjs/internal/observable'
if (!Observable) {
throw new Error('not loaded');
}
_observable = Observable;
return Observable;
}
catch (err) {
throw new Error(`RxJS Observable could not be loaded. If you are using a browser build, add it to AceBase using db.setObservable. For node.js builds, add it to your project with: npm i rxjs`);
}
}
exports.getObservable = getObservable;
function setObservable(Observable) {
if (Observable === 'shim') {
console.warn(`Using AceBase's simple Observable shim. Only use this if you know what you're doing.`);
Observable = ObservableShim;
}
_observable = Observable;
}
exports.setObservable = setObservable;
/**
* rxjs is an optional dependency that only needs installing when any of AceBase's observe methods are used.
* If for some reason rxjs is not available (eg in test suite), we can provide a shim. This class is used when
* `db.setObservable("shim")` is called
*/
class ObservableShim {
constructor(create) {
this._active = false;
this._subscribers = [];
this._create = create;
}
subscribe(subscriber) {
if (!this._active) {
const next = (value) => {
// emit value to all subscribers
this._subscribers.forEach(s => {
try {
s(value);
}
catch (err) {
console.error(`Error in subscriber callback:`, err);
}
});
};
const observer = { next };
this._cleanup = this._create(observer);
this._active = true;
}
this._subscribers.push(subscriber);
const unsubscribe = () => {
this._subscribers.splice(this._subscribers.indexOf(subscriber), 1);
if (this._subscribers.length === 0) {
this._active = false;
this._cleanup();
}
};
const subscription = {
unsubscribe
};
return subscription;
}
}
exports.ObservableShim = ObservableShim;
//# sourceMappingURL=optional-observable.js.map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.