code
stringlengths 2
1.05M
|
---|
import * as colors from '../../constants/colors.js';
import store from '../../store/index.js';
import { AR } from '../../constants/languages.js';
import mapbox from '../../constants/mapbox.js';
import layers from '../../constants/layers.js';
import sources from '../../constants/sources.js';
import keys from '../../constants/keys/camp-facilities.js';
function addLayer({ map }) {
map.addLayer(getLayerOptions());
}
function getLayerOptions() {
const language = store.getState().lang === AR ? keys.NAME_AR : keys.NAME_EN;
return {
id: layers.CAMP_FACILITIES_TEXT,
layout: {
'text-field': `{${keys[language]}}`,
'text-font': ['open-sans-regular'],
},
minzoom: mapbox.LABEL_ZOOM_BREAK,
paint: {
'text-halo-color': colors.WHITE,
'text-halo-width': 1.5,
},
source: sources.CAMP_FACILITIES_POINT,
type: 'symbol',
};
}
export default addLayer;
|
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash');
exports.render = function(req, res) {
res.render('index', {
user: JSON.stringify(req.user)
});
};
|
/**
* Token route
*/
'use strict';
var locator = require('node-service-locator');
var express = require('express');
var validator = require('validator');
var moment = require('moment-timezone');
var Table = require('dynamic-table').table();
var PgAdapter = require('dynamic-table').pgAdapter();
var ValidatorService = locator.get('validator-service');
var TokenModel = locator.get('token-model');
module.exports = function () {
var router = express.Router();
var app = locator.get('app');
/**
* GET routes
*/
// Token list table route
router.get('/table', function (req, res) {
var userId = parseInt(req.query.user_id, 10);
if (isNaN(userId))
return app.abort(res, 400, "Invalid user ID");
if (!req.user)
return app.abort(res, 401, "Not logged in");
var acl = locator.get('acl');
acl.isAllowed(req.user, 'token', 'read')
.then(function (isAllowed) {
if (!isAllowed)
return app.abort(res, 403, "ACL denied");
var table = new Table();
table.setColumns({
id: {
title: res.locals.glMessage('TOKEN_ID_COLUMN'),
sql_id: 'id',
type: Table.TYPE_INTEGER,
filters: [ Table.FILTER_EQUAL ],
sortable: true,
visible: true,
},
ip_address: {
title: res.locals.glMessage('TOKEN_IP_ADDRESS_COLUMN'),
sql_id: 'ip_address',
type: Table.TYPE_STRING,
filters: [ Table.FILTER_LIKE, Table.FILTER_NULL ],
sortable: true,
visible: true,
},
created_at: {
title: res.locals.glMessage('TOKEN_CREATED_AT_COLUMN'),
sql_id: 'created_at',
type: Table.TYPE_DATETIME,
filters: [ Table.FILTER_BETWEEN ],
sortable: true,
visible: true,
},
updated_at: {
title: res.locals.glMessage('TOKEN_UPDATED_AT_COLUMN'),
sql_id: 'updated_at',
type: Table.TYPE_DATETIME,
filters: [ Table.FILTER_BETWEEN ],
sortable: true,
visible: true,
},
});
table.setMapper(function (row) {
row['ip_address'] = ValidatorService.escape(row['ip_address']);
if (row['created_at'])
row['created_at'] = row['created_at'].unix();
if (row['updated_at'])
row['updated_at'] = row['updated_at'].unix();
return row;
});
var tokenRepo = locator.get('token-repository');
var adapter = new PgAdapter();
adapter.setClient(tokenRepo.getPostgres());
adapter.setSelect("*");
adapter.setFrom("tokens");
adapter.setWhere("user_id = $1");
adapter.setParams([ userId ]);
adapter.setDbTimezone('UTC');
table.setAdapter(adapter);
switch (req.query.query) {
case 'describe':
table.describe(function (err, result) {
if (err)
return app.abort(res, 500, 'GET /v1/tokens/table failed', err);
result['success'] = true;
res.json(result);
});
break;
case 'data':
table.setPageParams(req.query)
.fetch(function (err, result) {
if (err)
return app.abort(res, 500, 'GET /v1/tokens/table failed', err);
result['success'] = true;
res.json(result);
});
break;
default:
res.json({ success: false });
}
})
.catch(function (err) {
app.abort(res, 500, 'GET /v1/tokens/table failed', err);
});
});
// Get particular token route
router.get('/:tokenId', function (req, res) {
var tokenId = parseInt(req.params.tokenId, 10);
if (isNaN(tokenId))
return app.abort(res, 400, "Invalid token ID");
if (!req.user)
return app.abort(res, 401, "Not logged in");
var acl = locator.get('acl');
acl.isAllowed(req.user, 'token', 'read')
.then(function (isAllowed) {
if (!isAllowed)
return app.abort(res, 403, "ACL denied");
var tokenRepo = locator.get('token-repository');
return tokenRepo.find(tokenId)
.then(function (tokens) {
var token = tokens.length && tokens[0];
if (!token)
return app.abort(res, 404, "Token " + tokenId + " not found");
res.json({
id: token.getId(),
user_id: token.getUserId(),
ip_address: token.getIpAddress(),
created_at: token.getCreatedAt().unix(),
updated_at: token.getUpdatedAt().unix(),
payload: token.getPayload(),
});
});
})
.catch(function (err) {
app.abort(res, 500, 'GET /v1/tokens/' + tokenId + ' failed', err);
});
});
// Get all tokens route
router.get('/', function (req, res) {
if (!req.user)
return app.abort(res, 401, "Not logged in");
var acl = locator.get('acl');
acl.isAllowed(req.user, 'token', 'read')
.then(function (isAllowed) {
if (!isAllowed)
return app.abort(res, 403, "ACL denied");
var tokenRepo = locator.get('token-repository');
return tokenRepo.findAll()
.then(function (tokens) {
var result = [];
tokens.forEach(function (token) {
result.push({
id: token.getId(),
user_id: token.getUserId(),
ip_address: token.getIpAddress(),
created_at: token.getCreatedAt().unix(),
updated_at: token.getUpdatedAt().unix(),
payload: token.getPayload(),
});
});
res.json(result);
});
})
.catch(function (err) {
app.abort(res, 500, 'GET /v1/tokens failed', err);
});
});
/**
* DELETE routes
*/
// Delete particular token route
router.delete('/:tokenId', function (req, res) {
var tokenId = parseInt(req.params.tokenId, 10);
if (isNaN(tokenId))
return app.abort(res, 400, "Invalid token ID");
if (!req.user)
return app.abort(res, 401, "Not logged in");
var acl = locator.get('acl');
acl.isAllowed(req.user, 'token', 'delete')
.then(function (isAllowed) {
if (!isAllowed)
return app.abort(res, 403, "ACL denied");
var tokenRepo = locator.get('token-repository');
return tokenRepo.find(tokenId)
.then(function (tokens) {
var token = tokens.length && tokens[0];
if (!token)
return app.abort(res, 404, "Token " + tokenId + " not found");
return tokenRepo.delete(token);
})
.then(function (count) {
if (count === 0)
return res.json({ success: false, messages: [ res.locals.glMessage('ERROR_OPERATION_FAILED') ] });
res.json({ success: true });
});
})
.catch(function (err) {
app.abort(res, 500, 'DELETE /v1/tokens/' + tokenId + ' failed', err);
});
});
// Delete all tokens route
router.delete('/', function (req, res) {
if (!req.user)
return app.abort(res, 401, "Not logged in");
var acl = locator.get('acl');
acl.isAllowed(req.user, 'token', 'delete')
.then(function (isAllowed) {
if (!isAllowed)
return app.abort(res, 403, "ACL denied");
var tokenRepo = locator.get('token-repository');
return tokenRepo.deleteAll()
.then(function (count) {
if (count === 0)
return res.json({ success: false, messages: [ res.locals.glMessage('ERROR_OPERATION_FAILED') ] });
res.json({ success: true });
});
})
.catch(function (err) {
app.abort(res, 500, 'DELETE /v1/tokens failed', err);
});
});
app.use('/v1/tokens', router);
};
|
'use strict';
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const password = process.env.JWT_PASSWORD || 'asoetuh!{}l+oestnuhouoe13AOUeothaus';
exports.createToken = function (user) {
return jwt.sign({ id: user._id, email: user.email, scope: user.scope }, password, {
algorithm: 'HS256',
expiresIn: '1h',
});
};
exports.decodeToken = function (token) {
var userInfo = {};
try {
var decoded = jwt.verify(token, password);
userInfo.userId = decoded.id;
userInfo.email = decoded.email;
userInfo.scope = decoded.scope;
} catch (e) {
}
return userInfo;
};
exports.validate = function (decoded, request, callback) {
User.findOne({ _id: decoded.id }).then(user => {
if (user != null) {
callback(null, true);
} else {
callback(null, false);
}
}).catch(err => {
callback(null, false);
});
};
exports.password = password;
|
!function(a){a(document).ready(function(){b.navigation(),b.scrollToAnchor()});var b={navigation:function(){var b=a("#site-wrapper"),c="show-nav",d=function(){b.toggleClass(c)};a(".toggle-nav").click(function(){d()}),a(document).keyup(function(a){27==a.keyCode&&d()})},scrollToAnchor:function(){a("#scroll-down").click(function(b){b.preventDefault(),a("html,body").animate({scrollTop:a("#services").offset().top},"slow")})}}}(jQuery);
|
<!DOCTYPE html>
<head>
<title>PyntCloud</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {{
color: #050505;
font-family: Monospace;
font-size: 13px;
text-align: center;
background-color: #ffffff;
margin: 0px;
overflow: hidden;
align: 'center';
}}
#logo_container {{
position: absolute;
top: 0px;
width: 100 %;
}}
.logo {{
max-width: 20%;
}}
</style>
</head>
<body>
<h1> {title} </h1>
<div id="container">
</div>
<script src="http://threejs.org/build/three.js"></script>
<script src="http://threejs.org/examples/js/WebGL.js"></script>
<script src="http://threejs.org/examples/js/controls/OrbitControls.js"></script>
<script src="http://threejs.org/examples/js/libs/stats.min.js"></script>
<script>
var container, stats;
var camera, scene, renderer;
var points;
init();
animate();
function init() {{
var camera_x = {camera_x};
var camera_y = {camera_y};
var camera_z = {camera_z};
var look_x = {look_x};
var look_y = {look_y};
var look_z = {look_z};
var positions = new Float32Array({positions});
var colors = new Float32Array({colors});
var points_size = {points_size};
var axis_size = {axis_size};
container = document.getElementById('container');
scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff)
camera = new THREE.PerspectiveCamera(90, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.x = camera_x;
camera.position.y = camera_y;
camera.position.z = camera_z;
camera.up = new THREE.Vector3(0, 0, 1);
if(axis_size > 0) {{
var axisHelper = new THREE.AxisHelper(axis_size);
scene.add(axisHelper);
}}
var geometry = new THREE.BufferGeometry();
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
geometry.computeBoundingSphere();
var material = new THREE.PointsMaterial({{ size: points_size, vertexColors: THREE.VertexColors }} );
points = new THREE.Points( geometry, material );
scene.add( points );
renderer = new THREE.WebGLRenderer( {{ antialias: false, alpha: true }} );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
controls = new THREE.OrbitControls( camera, renderer.domElement );
controls.target.copy( new THREE.Vector3(look_x, look_y, look_z) );
camera.lookAt( new THREE.Vector3(look_x, look_y, look_z));
container.appendChild( renderer.domElement );
window.addEventListener( 'resize', onWindowResize, false );
}}
function onWindowResize() {{
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}}
function animate() {{
requestAnimationFrame(animate);
render();
}}
function render() {{
renderer.render(scene, camera);
}}
</script>
</body>
</html>
|
var checkout_url = base_url + 'checkout/';
function hide_card_details()
{
var pay_type = $("input[name=pay_type]:checked").val();
if(pay_type=="paypal")
{
$(".err_cc_name").text('');
$(".err_cc_number").text('');
$(".err_cc_ccd").text('');
$(".err_exp_date").text('');
$("input[name='cc_name']").prop("readonly",true);
$("input[name='cc_number']").prop("readonly",true);
$("input[name='cc_ccd']").prop("readonly",true);
$("#exp_month").prop("disabled","disabled");
$("#exp_year").prop("disabled","disabled");
$("input[name='cc_name']").val('');
$("input[name='cc_number']").val('');
$("input[name='cc_ccd']").val('');
$('#card_type').prop('selectedIndex',0);
$('#exp_month').prop('selectedIndex',0);
$('#exp_year').prop('selectedIndex',0);
}
else
{
$("input[name='cc_name']").removeAttr("readonly");
$("input[name='cc_number']").removeAttr("readonly");
$("input[name='cc_ccd']").removeAttr("readonly");
$("#exp_month").removeAttr("disabled");
$("#exp_year").removeAttr("disabled");
}
}
$(document).on("click",".edit_billing_addr",function(){
$("input[name='ship_to_addr']").prop("checked",false);
var url = base_url+'checkout/set_billing_address';
$.ajax({
url : url,
type: "GET",
dataType: "JSON",
success: function(data)
{
if(data.status=="success")
{
$("#billing_form").show();
$("#billing_form").html(data.content);
$("#billing_list").hide();
$("#billing_address").html('');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error in Edit Billing Address');
}
});
});
$(document).on("click",".edit_shipping_addr",function(){
var url = base_url+'checkout/set_shipping_address';
$.ajax({
url : url,
type: "GET",
dataType: "JSON",
success: function(data)
{
if(data.status=="success")
{
$("#shipping_form").show();
$("#shipping_form").html(data.content);
$("#shipping_list").hide();
$("#shipping_address").html('');
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error in Edit Shipping Address');
}
});
});
$(document).on("change","input[name='ship_to_addr']",function(){
var val = $(this).val();
if(val==0)
{
var name = $("input[name='name']").val(),
company_name = $("input[name='company_name']").val(),
email = $("input[name='email']").val(),
phone = $("input[name='phone']").val(),
address = $("input[name='address']").val(),
city = $("input[name='city']").val(),
state = $("input[name='state']").val(),
country = $(".country option:selected").val(),
zip_code = $("input[name='zip_code']").val();
if(name!=undefined)
{
if(name!='' && company_name!='' && email!='' && phone!='' && address!='' && city!='' && state!='' && country!='' && zip_code!='')
{
$("input[name='sa_name']").val(name);
$("input[name='sa_company_name']").val(company_name);
$("input[name='sa_email']").val(email);
$("input[name='sa_phone']").val(phone);
$("input[name='sa_address']").val(address);
$("input[name='sa_city']").val(city);
$("input[name='sa_state']").val(state);
$(".sa_country").val(country);
$("input[name='sa_zip_code']").val(zip_code);
}
else
{
alert("Please fill all the fields in billing form");
$("input[name='ship_to_addr']").prop("checked",false);
return false;
}
}
else
{
name = $("#billing_list").find("span.name").text();
company_name = $("#billing_list").find("span.company").text();
email = $("#billing_list").find("span.email").text();
phone = $("#billing_list").find("span.phone").text();
address = $("#billing_list").find("span.address").text();
city = $("#billing_list").find("span.city").text();
country = $("#billing_list").find("span.country").text();
state = $("#billing_list").find("span.state").text();
zip_code = $("#billing_list").find("span.zip_code").text();
$("input[name='sa_name']").val(name);
$("input[name='sa_company_name']").val(company_name);
$("input[name='sa_email']").val(email);
$("input[name='sa_phone']").val(phone);
$("input[name='sa_address']").val(address);
$("input[name='sa_city']").val(city);
$("input[name='sa_state']").val(state);
$(".sa_country").val(country);
$("input[name='sa_zip_code']").val(zip_code);
}
}
else
{
$("input[name='sa_name']").val('');
$("input[name='sa_company_name']").val('');
$("input[name='sa_email']").val('');
$("input[name='sa_phone']").val('');
$("input[name='sa_address']").val('');
$("input[name='sa_city']").val('');
$("input[name='sa_state']").val('');
$(".sa_country").val('');
$("input[name='sa_zip_code']").val('');
}
});
function billing_address_validation()
{
var name = $("input[name='name']").val(),
company_name = $("input[name='company_name']").val(),
email = $("input[name='email']").val(),
phone = $("input[name='phone']").val(),
address = $("input[name='address']").val(),
city = $("input[name='city']").val(),
state = $("input[name='state']").val(),
country = $(".country option:selected").val(),
zip_code = $("input[name='zip_code']").val(),
valid_email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
url = base_url +'checkout/save_billing_address';
if(name!=undefined)
{
if(name.length)
{
$(".err_name").text('');
}
else
{
$(".err_name").text("Please Enter Your Name");
}
if(email=='' || !valid_email.test(email))
{
$(".err_email").text('Please Enter Valid Email Address');
}
else
{
$(".err_email").text('');
}
if(phone.length && phone.length >=10 && !isNaN(phone))
{
$(".err_phone").text('');
}
else
{
$(".err_phone").text('Please Enter Valid Phone No');
}
if(address.length)
{
$(".err_add").text('');
}
else
{
$(".err_add").text('Please Enter Your Address');
}
if(city.length)
{
$(".err_city").text('');
}
else
{
$(".err_city").text('Please Enter Your City');
}
if(state.length)
{
$(".err_state").text('');
}
else
{
$(".err_state").text('Please Enter Your State');
}
if(country.length)
{
$(".err_country").text('');
}
else
{
$(".err_country").text('Please Enter Your Country');
}
if(zip_code.length)
{
$(".err_zip").text('');
}
else
{
$(".err_zip").text("Please Enter Valid Zip Code")
}
if(name=='' || email=='' || !valid_email.test(email) || phone=='' || phone.length <10 || isNaN(phone) || address=='' || city=='' || state=='' || country=='' || zip_code=='')
{
$('html, body').animate({ scrollTop: $('#billing_information').offset().top }, 'slow');
return false;
}
else if(name!='' && email!='' && phone!='' && address!='' && city!='' && state!='' && country!='' && zip_code!='')
{
var data = 'name='+ name +'&company_name='+ company_name +'&email=' + email +'&phone=' + phone+'&address=' + address+'&city=' + city+'&state=' + state+'&country=' + country+'&zip_code=' + zip_code;
$.ajax({
url : url,
type: "POST",
data: data,
dataType: "JSON",
success: function(data)
{
if(data.status=="success")
{
$("#billing_address").hide();
$("#billing_form").html('');
$("#billing_list").show();
$("#billing_list").html(data.content);
$("input[name='success1']").val("billing_success");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
}
}
function shipping_address_validation()
{
var name = $("input[name='sa_name']").val(),
company_name = $("input[name='sa_company_name']").val(),
email = $("input[name='sa_email']").val(),
phone = $("input[name='sa_phone']").val(),
address = $("input[name='sa_address']").val(),
city = $("input[name='sa_city']").val(),
state = $("input[name='sa_state']").val(),
country = $(".sa_country option:selected").val(),
zip_code = $("input[name='sa_zip_code']").val(),
valid_email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
url = base_url +'checkout/save_shipping_address';
if(name!=undefined)
{
if(name.length)
{
$(".err_sa_name").text('');
}
else
{
$(".err_sa_name").text("Please Enter Your Name");
}
if(email=='' || !valid_email.test(email))
{
$(".err_sa_email").text('Please Enter Valid Email Address');
}
else
{
$(".err_sa_email").text('');
}
if(phone.length && phone.length >=10 && !isNaN(phone))
{
$(".err_sa_phone").text('');
}
else
{
$(".err_sa_phone").text('Please Enter Valid Phone No');
}
if(address.length)
{
$(".err_sa_add").text('');
}
else
{
$(".err_sa_add").text('Please Enter Your Address');
}
if(city.length)
{
$(".err_sa_city").text('');
}
else
{
$(".err_sa_city").text('Please Enter Your City');
}
if(state.length)
{
$(".err_sa_state").text('');
}
else
{
$(".err_sa_state").text('Please Enter Your State');
}
if(country.length)
{
$(".err_sa_country").text('');
}
else
{
$(".err_sa_country").text('Please Enter Your Country');
}
if(zip_code.length)
{
$(".err_sa_zip").text('');
}
else
{
$(".err_sa_zip").text('Please Enter Valid Zip Code');
}
if(name=='' || email=='' || !valid_email.test(email) || phone=='' || phone.length <10 || isNaN(phone) || address=='' || city=='' || state=='' || country=='' || zip_code=='' )
{
$('html, body').animate({ scrollTop: $('#shipping_information').offset().top }, 'slow');
return false;
}
else if(name!='' && email!='' && phone!='' && address!='' && city!='' && state!='' && country!='' && zip_code!='')
{
var data = 'name='+ name +'&company_name='+ company_name +'&email=' + email +'&phone=' + phone+'&address=' + address+'&city=' + city+'&state=' + state+'&country=' + country+'&zip_code=' + zip_code;
$.ajax({
url : url,
type: "POST",
data: data,
dataType: "JSON",
success: function(data)
{
if(data.status=="success")
{
$("#shipping_information").hide();
$("#shipping_form").html('');
$("#shipping_list").show();
$("#shipping_list").html(data.content);
$("input[name='success']").val("shipping_success");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}
}
}
function card_validation()
{
var pay_type = $("input[name=pay_type]:checked").val(),
cc_name = $("input[name='cc_name']").val(),
cc_number = $("input[name='cc_number']").val(),
cc_ccd = $("input[name='cc_ccd']").val(),
exp_month = $(".exp_month option:selected").val(),
exp_year = $(".exp_year option:selected").val(),
currentYear = new Date().getFullYear(),
currentMonth = new Date().getMonth() + 1,
month = parseInt(exp_month, 10),
year = parseInt(exp_year, 10);
if(pay_type!="paypal")
{
if(cc_name.length)
{
$(".err_cc_name").text('');
}
else
{
$(".err_cc_name").text('Please Enter Your Name on Card');
}
if(cc_number.length)
{
$('#cc_number').validateCreditCard(function(result) {
if(!result.valid)
{
$('.err_cc_number').text("Please Enter Valid Credit Card Number");
}
else
{
$('.err_cc_number').text("");
}
});
}
else
{
$(".err_cc_number").text('Please Enter Your Credit Card Number');
}
if(exp_month.length && exp_year.length)
{
if ((year > currentYear) || ((year === currentYear) && (month >= currentMonth)))
{
$(".err_exp_date").text("");
}
else
{
$(".err_exp_date").text("Date is Expired");
}
}
else
{
$(".err_exp_date").text('Please Select Expiry Date');
}
if(cc_ccd.length && cc_ccd.length <=4 && !isNaN(cc_ccd))
{
$(".err_cc_ccd").text('');
}
else
{
$(".err_cc_ccd").text('Please Enter Valid CCV Number');
}
}
if(pay_type=="authorize" && cc_name!='' && cc_number!='' && exp_month!='' && exp_year!='' && (year > currentYear) || ((year === currentYear) && (month >= currentMonth)) && cc_ccd!='' && cc_ccd.length <=4 && !isNaN(cc_ccd))
{
$('#cc_number').validateCreditCard(function(result) {
if(!result.valid)
{
$('.err_cc_number').text("Please Enter Valid Credit Card Number");
}
else
{
$('.err_cc_number').text("");
$("input[name='card_success']").val("card_success");
}
});
}
}
$("#check_before_order").on("click",function(event){
event.preventDefault();
$("input[name='ship_to_addr']").prop("checked",false);
billing_address_validation();
shipping_address_validation();
card_validation();
var pay_type = $("input[name=pay_type]:checked").val(),
billing_succ = $("input[name='success1']").val(),
shipping_succ = $("input[name='success']").val(),
card_succ = $("input[name='card_success']").val();
if(pay_type =="paypal" && billing_succ=="billing_success" && shipping_succ=="shipping_success")
{
location.href = base_url + 'paypal_exp';
}
else if(pay_type=="authorize" && billing_succ=="billing_success" && shipping_succ=="shipping_success" && card_succ=="card_success")
{
submit_order();
}
});
function submit_order()
{
var url = checkout_url+'submit_order';
var rurl1 = checkout_url+'success';
var rurl2 = base_url + 'paypal/process';
var data = $("#paymethod").serialize();
$.ajax({
url : url,
type: "POST",
data: data,
dataType: "JSON",
beforeSend: function() {
$("#preloader").css("display",'block');
},
success: function(data)
{
//$("#preloader").css("display",'none');
if(data.status=="success" && data.message == 'success')
{
location.href = rurl1;
}
},
error: function (jqXHR, textStatus, errorThrown)
{
$("#preloader").css("display",'none');
alert('Error adding / update data');
}
});
}
$(window).load(function(){
if ($(".checkout-area").length)
{
var name = sessionStorage.getItem('name');
var company_name = sessionStorage.getItem('company_name');
var email = sessionStorage.getItem('email');
var phone = sessionStorage.getItem('phone');
var address = sessionStorage.getItem('address');
var city = sessionStorage.getItem('city');
var state = sessionStorage.getItem('state');
var country = sessionStorage.getItem('country');
var zip_code = sessionStorage.getItem('zip_code');
var sa_name = sessionStorage.getItem('sa_name');
var sa_company_name = sessionStorage.getItem('sa_company_name');
var sa_email = sessionStorage.getItem('sa_email');
var sa_phone = sessionStorage.getItem('sa_phone');
var sa_address = sessionStorage.getItem('sa_address');
var sa_city = sessionStorage.getItem('sa_city');
var sa_state = sessionStorage.getItem('sa_state');
var sa_country = sessionStorage.getItem('sa_country');
var sa_zip_code = sessionStorage.getItem('sa_zip_code');
if (name!="undefined") $('input[name="name"]').val(name);
if (company_name!="undefined") $('input[name="company_name"]').val(company_name);
if (email!="undefined") $('input[name="email"]').val(email);
if (phone!="undefined") $('input[name="phone"]').val(phone);
if (address!="undefined") $('input[name="address"]').val(address);
if (city!="undefined") $('input[name="city"]').val(city);
if (state!="undefined") $('input[name="state"]').val(state);
if (country!="undefined") $("#country option[value='"+country+"']").prop('selected', true);;
if (zip_code!="undefined") $('input[name="zip_code"]').val(zip_code);
if (sa_name!="undefined") $('input[name="sa_name"]').val(sa_name);
if (sa_company_name!="undefined") $('input[name="sa_company_name"]').val(sa_company_name);
if (sa_email!="undefined") $('input[name="sa_email"]').val(sa_email);
if (sa_phone!="undefined") $('input[name="sa_phone"]').val(sa_phone);
if (sa_address!="undefined") $('input[name="sa_address"]').val(sa_address);
if (sa_city!="undefined") $('input[name="sa_city"]').val(sa_city);
if (sa_state!="undefined") $('input[name="sa_state"]').val(sa_state);
if (sa_country!="undefined") $(".sa_country option[value='"+sa_country+"']").prop('selected', true);;
if (sa_zip_code!="undefined") $('input[name="sa_zip_code"]').val(sa_zip_code);
}
});
$(window).unload(function(){
if ($(".checkout-area").length)
{
var name = $("input[name='name']").val(),
company_name = $("input[name='company_name']").val(),
email = $("input[name='email']").val(),
phone = $("input[name='phone']").val(),
address = $("input[name='address']").val(),
city = $("input[name='city']").val(),
state = $("input[name='state']").val(),
country = $(".country option:selected").val(),
zip_code = $("input[name='zip_code']").val(),
sa_name = $("input[name='sa_name']").val(),
sa_company_name = $("input[name='sa_company_name']").val(),
sa_email = $("input[name='sa_email']").val(),
sa_phone = $("input[name='sa_phone']").val(),
sa_address = $("input[name='sa_address']").val(),
sa_city = $("input[name='sa_city']").val(),
sa_state = $("input[name='sa_state']").val(),
sa_country = $(".sa_country option:selected").val(),
sa_zip_code = $("input[name='sa_zip_code']").val();
sessionStorage.setItem("name", name);
sessionStorage.setItem("company_name", company_name);
sessionStorage.setItem("email", email);
sessionStorage.setItem("phone", phone);
sessionStorage.setItem("address", address);
sessionStorage.setItem("city", city);
sessionStorage.setItem("state", state);
sessionStorage.setItem("country", country);
sessionStorage.setItem("zip_code", zip_code);
sessionStorage.setItem("sa_name", sa_name);
sessionStorage.setItem("sa_company_name", sa_company_name);
sessionStorage.setItem("sa_email", sa_email);
sessionStorage.setItem("sa_phone", sa_phone);
sessionStorage.setItem("sa_address", sa_address);
sessionStorage.setItem("sa_city", sa_city);
sessionStorage.setItem("sa_state", sa_state);
sessionStorage.setItem("sa_country", sa_country);
sessionStorage.setItem("sa_zip_code", sa_zip_code);
}
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M12 4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zM8.88 7.82L11 9.94 9.94 11 8.88 9.94 7.82 11 6.76 9.94l2.12-2.12zM12 17.5c-2.33 0-4.31-1.46-5.11-3.5h10.22c-.8 2.04-2.78 3.5-5.11 3.5zm4.18-6.5l-1.06-1.06L14.06 11 13 9.94l2.12-2.12 2.12 2.12L16.18 11z" opacity=".3" /><path d="M8.88 9.94L9.94 11 11 9.94 8.88 7.82 6.76 9.94 7.82 11zm4.12 0L14.06 11l1.06-1.06L16.18 11l1.06-1.06-2.12-2.12zM11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-2.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z" /></React.Fragment>
, 'SentimentVerySatisfiedTwoTone');
|
define(["application-configuration"],function(app) {
function chatController($rootScope, $scope,$compile, $routeParams, $location, $localStorage,api){
$scope.user = api.current_user();
$scope.userActions = [1,2,3,4,5,6,7,8,9,10];
$scope.onlineUsers = [1,2,3,4,5,6,7,8,9,10];
$scope.activeChats = [];
$scope.openChat = function(userId){
if(!($scope.activeChats.indexOf(userId)>-1 && userId)){
$scope.activeChats.push(userId);
$scope.register_popup('user'+userId,'name'+userId)
}
};
//this function can remove a array element.
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
//this variable represents the total number of popups can be displayed according to the viewport width
var total_popups = 0;
//arrays of popups ids
var popups = [];
//this is used to close a popup
$scope.close_popup = function(id)
{
for(var iii = 0; iii < popups.length; iii++)
{
if(id == popups[iii])
{
Array.remove(popups, iii);
document.getElementById(id).style.display = "none";
calculate_popups();
return;
}
}
}
//displays the popups. Displays based on the maximum number of popups that can be displayed on the current viewport width
function display_popups()
{
var right = 320;
var iii = 0;
for(iii; iii < total_popups; iii++)
{
if(popups[iii] != undefined)
{
var element = angular.element('#'+popups[iii]);
element.css("right", right + "px");
right = right + 320;
element.css("display","block");
}
}
for(var jjj = iii; jjj < popups.length; jjj++)
{
var element = angular.element('#'+popups[jjj]);
element.css('display',"none");
}
}
//creates markup for a new popup. Adds the id to popups array.
$scope.register_popup = function(id, name)
{
for(var iii = 0; iii < popups.length; iii++)
{
//already registered. Bring it to front.
if(id == popups[iii])
{
Array.remove(popups, iii);
popups.unshift(id);
calculate_popups();
return;
}
}
var element = '';
angular.element('body').append($compile(element)($scope));
popups.unshift(id);
calculate_popups();
};
//calculate the total number of popups suitable and then populate the toatal_popups variable.
function calculate_popups()
{
var width = window.innerWidth;
if(width < 540)
{
total_popups = 0;
}
else
{
width = width - 320;
//320 is width of a single popup box
total_popups = parseInt(width/320);
}
display_popups();
}
console.log($scope);
$scope.classname = 'slide-right';
}
app.register.controller("chatController", ['$rootScope', '$scope','$compile','$routeParams', '$location', '$localStorage','api',chatController]);
app.register.directive('chatresize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return {
'h': w.height(),
'w': w.width()
};
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
scope.lastfeedStyle = function () {
return {
'height': (newValue.h/3.5) + 'px',
'overflow-y' : 'scroll'
};
};
scope.chatStyle = function(){
return {
'height': (newValue.h/1.6) + 'px',
'overflow-y' : 'scroll'
};
};
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
});
|
System.register(["TinyDecorations"], function (exports_1, context_1) {
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var TinyDecorations_1, View2Controller;
var __moduleName = context_1 && context_1.id;
return {
setters: [
function (TinyDecorations_1_1) {
TinyDecorations_1 = TinyDecorations_1_1;
}
],
execute: function () {
View2Controller = /** @class */ (function () {
function View2Controller($timeout) {
this.$timeout = $timeout;
$timeout(function () {
console.debug("hello world");
}, 1000);
}
View2Controller = __decorate([
TinyDecorations_1.Controller({
name: "View2Ctrl",
template: "\n<p>This is the partial for view 2.</p>\n<p>\n Showing of 'interpolate' filter:\n {{ 'Current version is v%VERSION%.' | interpolate }}\n</p>\n"
}),
__metadata("design:paramtypes", [Object])
], View2Controller);
return View2Controller;
}());
exports_1("View2Controller", View2Controller);
}
};
});
//# sourceMappingURL=View2Controller.js.map
|
'use strict';
// Setting up route
angular.module('cars').config(['$stateProvider',
function ($stateProvider) {
// Articles state routing
$stateProvider
.state('cars', {
abstract: true,
url: '/cars',
template: '<ui-view/>'
})
.state('cars.list', {
url: '',
templateUrl: 'modules/cars/client/views/list-cars.client.view.html'
})
.state('cars.create', {
url: '/create',
templateUrl: 'modules/cars/client/views/create-car.client.view.html',
data: {
roles: ['user', 'admin']
}
})
.state('cars.view', {
url: '/:carId',
templateUrl: 'modules/cars/client/views/view-car.client.view.html'
})
.state('cars.search', {
url: '/search',
templateUrl: 'modules/cars/client/views/search-car.client.view.html'
})
.state('cars.edit', {
url: '/:carId/edit',
templateUrl: 'modules/cars/client/views/edit-car.client.view.html',
data: {
roles: ['user', 'admin']
}
});
}
]);
|
window.addEventListener("load", Ready);
function Ready(){
if(window.File && window.FileReader){ //These are the relevant HTML5 objects that we are going to use
document.getElementById('uploadButton').addEventListener('click', StartUpload);
document.getElementById('fileInput').addEventListener('change', FileChosen);
}
else
{
document.getElementById('attachment_upload').innerHTML = "Your Browser Doesn't Support The File API Please Update Your Browser";
}
}
var SelectedFile;
function FileChosen(evnt) {
SelectedFile = evnt.target.files[0];
document.getElementById('fileName').value = SelectedFile.name;
}
var FReader;
var Name;
function StartUpload(){
if(document.getElementById('fileInput').value != "")
{
FReader = new FileReader();
Name = document.getElementById('fileName').value;
document.getElementById('attachment_upload').style.display = 'none';
document.getElementById('progress').style.display = 'inline';
FReader.onload = function(evnt){
socket.emit('Upload', { 'Name' : Name, Data : evnt.target.result });
}
socket.emit('Start', { 'Name' : Name, 'Size' : SelectedFile.size });
}
else
{
alert("Please Select A File");
}
}
socket.on('MoreData', function (data){
UpdateBar(data['Percent']);
var Place = data['Place'] * 524288; //The Next Blocks Starting Position
var NewFile; //The Variable that will hold the new Block of Data
if(SelectedFile.slice)
NewFile = SelectedFile.slice(Place, Place + Math.min(524288, (SelectedFile.size-Place)));
else
NewFile = SelectedFile.mozSlice(Place, Place + Math.min(524288, (SelectedFile.size-Place)));
FReader.readAsBinaryString(NewFile);
});
function UpdateBar(percent){
document.getElementById('progressbar').style.width = percent + '%';
}
var Path = "http://localhost/";
socket.on('Done', function (data){
var Content = "Successfully Uploaded !!"
document.getElementById('progress').style.display = 'none';
document.getElementById('attachment_upload').style.display = 'inline';
});
function Refresh(){
location.reload(true);
}
|
var auth = require('auth');
var Command = require('streamhub-sdk/ui/command');
var hasFooterButtons = require('streamhub-sdk/content/views/mixins/footer-buttons-mixin');
var HubButton = require('streamhub-sdk/ui/hub-button');
var HubLikeButton = require('streamhub-sdk/ui/hub-like-button');
var i18n = require('streamhub-sdk/i18n');
var LivefyreContent = require('streamhub-sdk/content/types/livefyre-content');
// TODO: move share to a separate mixin
var ShareButton = require('streamhub-sdk/ui/share-button');
var ExpandButton = require('streamhub-sdk/ui/expand-button');
'use strict';
/**
* A mixin that decorates an instance of ContentView
* to be a LivefyreContentView
* LivefyreContentViews have streamhub-powered like, reply, and share buttons
*/
function asLivefyreContentView(contentView, opts) {
opts = opts || {};
hasFooterButtons(contentView);
/**
* Set the a command for a buton
* This should only be called once.
* @private
*/
contentView._setCommand = function (cmds) {
for (var name in cmds) {
if (cmds.hasOwnProperty(name)) {
if (! cmds[name]) {
continue;
}
contentView._commands[name] = cmds[name];
// If canExecute changes, re-render buttons because now maybe the button should appear
cmds[name].on('change:canExecute', contentView._footerView._renderButtons.bind(contentView));
}
}
};
contentView._addInitialButtons = function () {
// Expand
if (opts.showExpandButton) {
contentView._expandButton = contentView._createExpandButton();
if (contentView._expandButton) {
contentView.addButton(contentView._expandButton);
}
}
// Like
contentView._likeButton = contentView._createLikeButton();
if (contentView._likeButton) {
contentView.addButton(contentView._likeButton);
}
// Reply
contentView._replyButton = contentView._createReplyButton();
if (contentView._replyButton) {
contentView.addButton(contentView._replyButton);
}
// Share
contentView._shareButton = contentView._createShareButton();
if (contentView._shareButton) {
contentView.addButton(contentView._shareButton);
}
};
/**
* Create a Button to be used for showing modal
* @protected
*/
contentView._createExpandButton = function () {
var expandCommand = contentView._commands.expand;
if ( ! (expandCommand && expandCommand.canExecute())) {
return;
}
return new ExpandButton(expandCommand, {
contentView: contentView
});
};
/**
* Create a Button to be used for Liking functionality
* @protected
*/
contentView._createLikeButton = function () {
// Don't render a button when no auth delegate
if ( ! auth.hasDelegate('login')) {
return;
}
// Don't render a button if contentView isn't actually LivefyreContent
if (! contentView.content.id) {
return;
}
return new HubLikeButton(contentView._commands.like, {
content: contentView.content
});
};
/**
* Create a Button to be used for replying
*/
contentView._createReplyButton = function () {
if ( ! contentView._replying) {
return;
}
// Don't render reply button when no auth delegate
if ( ! auth.hasDelegate('login')) {
return;
}
var replyCommand = contentView._commands.reply;
if ( ! (replyCommand && replyCommand.canExecute())) {
return;
}
return new HubButton(replyCommand, {
className: 'btn-link content-reply',
label: 'Reply'
});
};
/**
* Create a Share Button
* @protected
*/
contentView._createShareButton = function () {
var label = i18n.get('shareButtonText', 'Share');
var shareCommand = contentView._commands.share;
if (!shareCommand) {
return new ShareButton({
className: 'btn-link content-share',
content: this.content,
label: label
});
}
if (! shareCommand.canExecute()) {
return;
}
return new HubButton(shareCommand, {
className: 'btn-link content-share',
label: label
});
};
/**
* Render the content inside of the LivefyreContentView's element.
* @returns {LivefyreContentView}
*/
var oldRender = contentView.render;
contentView.render = function () {
oldRender.apply(contentView, arguments);
contentView.$el.addClass(contentView._themeClass);
};
contentView._updateLikeCount = function () {
contentView._likeButton.updateLabel(contentView.content.getLikeCount().toString());
};
// init
contentView._commands = {};
contentView._setCommand({
expand: opts.expandCommand,
like: opts.likeCommand,
reply: opts.replyCommand,
share: opts.shareCommand
});
contentView._addInitialButtons();
};
module.exports = asLivefyreContentView;
|
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/sw.js').then(function (registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}, function (err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
});
}
$(document).ready(function () {
$('#fullpage').fullpage({
navigation: false,
continuousVertical: false,
keyboardScrolling: true,
controlArrows: false,
anchors: ['Homepage', 'About me', 'Online CV'],
menu: '#myMenu',
slidesNavigation: false,
slidesNavPosition: 'bottom',
verticalCentered: true,
lazyLoading: true,
bigSectionsDestination: top,
fitToSection: true,
scrollOverflow: true
});
});
|
V.registerTrigger("", function(handle, index, parentHandle) {
var textHandle = handle.childNodes[0],
textHandleId = textHandle.id,
key = textHandle.node.data,
trigger;
// console.log("getData:",key)
if (parentHandle.type !== "handle") { //as textHandle
if ($.isString(key)) { // single String
trigger = { //const
key: ".", //const trigger
bubble: true,
event: function(NodeList_of_ViewInstance, dataManager) {
NodeList_of_ViewInstance[textHandleId].currentNode.data = key.substring(1, key.length - 1);
// trigger.event = $.noop;
}
};
} else { //String for databese by key
trigger = {
key: key,
event: function(NodeList_of_ViewInstance, dataManager, triggerBy, isAttr, vi) { //call by ViewInstance's Node
// console.log("getData:",key,":",dataManager)
var data;
if (isAttr) {
if (isAttr.key.indexOf("on") === 0) {
data = String(dataManager.get(key)).replace(/"/g, '\\"').replace(/'/g, "\\'");
// }else if(isAttr.key.indexOf("event-")===0&&_isIE){
// data = String(dataManager.get(key)).replace(/\n/g, _ieEnterPlaceholder);
} else {
data = dataManager.get(key);
}
} else {
data = dataManager.get(key)
};
NodeList_of_ViewInstance[textHandleId].currentNode.data = data;
}
}
}
} else { //as stringHandle
if ($.isString(key)) { // single String
trigger = { //const
key: ".", //const trigger
bubble: true,
event: function(NodeList_of_ViewInstance, dataManager) {
NodeList_of_ViewInstance[this.handleId]._data = key.substring(1, key.length - 1);
}
};
} else { //String for databese by key
trigger = {
key: key,
bubble: true,
event: function(NodeList_of_ViewInstance, dataManager) {
NodeList_of_ViewInstance[this.handleId]._data = dataManager.get(key);
}
};
}
}
return trigger;
});
|
var AnsiFSM,
__hasProp = {}.hasOwnProperty;
(typeof exports !== "undefined" && exports !== null ? exports : window).AnsiFSM = AnsiFSM = (function() {
AnsiFSM.prototype.states = {
plain: {
"\u001b": ["esc_seen"],
"\r": ["plain", "cr"],
"\n": ["plain", "nl"],
"\u0008": ["plain", "bs"],
"\t": ["plain", "ht"],
"default": ["plain", "echo_char"]
},
esc_seen: {
"A": ["skip_emacs_term_mode_sequence"],
"[": ["csi_seen", null, "reset_args"],
"default": ["plain"]
},
skip_emacs_term_mode_sequence: {
"\n": ["plain"],
"default": ["skip_emacs_term_mode_sequence"]
},
csi_seen: {
"?": ["private_seen"],
">": ["private_seen"],
"0": ["csi_seen", null, "collect_args"],
"1": ["csi_seen", null, "collect_args"],
"2": ["csi_seen", null, "collect_args"],
"3": ["csi_seen", null, "collect_args"],
"4": ["csi_seen", null, "collect_args"],
"5": ["csi_seen", null, "collect_args"],
"6": ["csi_seen", null, "collect_args"],
"7": ["csi_seen", null, "collect_args"],
"8": ["csi_seen", null, "collect_args"],
"9": ["csi_seen", null, "collect_args"],
";": ["csi_seen", null, "collect_args"],
"@": ["plain", "ich"],
"A": ["plain", "cuu"],
"B": ["plain", "cud"],
"C": ["plain", "cuf"],
"D": ["plain", "cub"],
"E": ["plain", "cnl"],
"F": ["plain", "cpl"],
"G": ["plain", "cha"],
"H": ["plain", "cup"],
"J": ["plain", "ed"],
"K": ["plain", "el"],
"L": ["plain", "il"],
"S": ["plain", "su"],
"T": ["plain", "sd"],
"d": ["plain", "vpa"],
"f": ["plain", "cup"],
"m": ["plain", "sgr"],
"n": ["plain", "dsr"],
"r": ["plain", "decstbm"],
"s": ["plain", "scp"],
"u": ["plain", "rsp"],
"default": ["plain", null, "unhandled"]
},
private_seen: {
"0": ["private_seen", null, "collect_args"],
"1": ["private_seen", null, "collect_args"],
"2": ["private_seen", null, "collect_args"],
"3": ["private_seen", null, "collect_args"],
"4": ["private_seen", null, "collect_args"],
"5": ["private_seen", null, "collect_args"],
"6": ["private_seen", null, "collect_args"],
"7": ["private_seen", null, "collect_args"],
"8": ["private_seen", null, "collect_args"],
"9": ["private_seen", null, "collect_args"],
";": ["private_seen", null, "collect_args"],
"c": ["plain"],
"h": ["plain", "sm"],
"l": ["plain", "rm"],
"default": ["plain", null, "punhandled"]
}
};
function AnsiFSM(terminal) {
this.terminal = terminal;
this.state = this.states.plain;
}
AnsiFSM.prototype.accept_string = function(string) {
var char, _i, _len;
for (_i = 0, _len = string.length; _i < _len; _i++) {
char = string[_i];
this.accept_char(char);
}
return this.terminal.update();
};
AnsiFSM.prototype.accept_char = function(char) {
var local_action, next_state, terminal_action, _ref;
_ref = this.transition(char), next_state = _ref[0], terminal_action = _ref[1], local_action = _ref[2];
this.state = this.states[next_state];
if (local_action) {
this[local_action](char);
}
if (terminal_action) {
return this.terminal[terminal_action](char, this.args);
}
};
AnsiFSM.prototype.transition = function(char) {
return this.state[char] || this.state["default"];
};
AnsiFSM.prototype.reset_args = function(char) {
return this.args = [0];
};
AnsiFSM.prototype.collect_args = function(char) {
if (char === ";") {
return this.args = this.args.concat(0);
} else {
return this.args.push(this.args.pop() * 10 + (char - "0"));
}
};
AnsiFSM.prototype.unhandled = function(char) {
return console.log("Unhandled CSI " + (this.args.join(';')) + " " + char);
};
AnsiFSM.prototype.punhandled = function(char) {
return console.log("Unhandled PRIVATE CSI " + (this.args.join(';')) + " " + char);
};
AnsiFSM.prototype.save = function() {
var arg, current_state, state, value;
current_state = (function() {
var _ref, _results;
_ref = this.states;
_results = [];
for (state in _ref) {
if (!__hasProp.call(_ref, state)) continue;
value = _ref[state];
if (value === this.state) {
_results.push(state);
}
}
return _results;
}).call(this);
return {
state: current_state[0],
args: (function() {
var _i, _len, _ref, _results;
if ($.isArray(this.args)) {
_ref = this.args;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
_results.push(arg);
}
return _results;
} else {
return this.args;
}
}).call(this)
};
};
AnsiFSM.prototype.load_from = function(state) {
this.state = this.states[state.state];
return this.args = state.args;
};
return AnsiFSM;
})();
|
import { readOnly } from '@ember/object/computed';
import Mixin from '@ember/object/mixin';
import moment from 'moment';
/**
* Simple mixin to share a bunch of the properties between the `input-date` & `input-iso8601` components.
*/
export default Mixin.create({
/**
* Assign an action that will be triggered after failing to parse the date. You will passed this
* component as an argument.
*/
afterParseFail(/*inputDateComponent*/) {
// override accordingly
},
/**
* Assign an action that will be triggered after successfully parsing a date. You will passed this
* component as an argument.
*/
afterParseSuccess(/*inputDateComponent*/) {
// override accordingly
},
/**
* Assign an action that will be triggered before attempting to parse the date. You will passed this
* component as an argument.
*/
beforeParse(/*inputDateComponent*/) {
// override accordingly
},
/**
* CTRL+ENTER will submit the closest form.
*/
'ctrlEnterSubmitsForm?': true,
/**
* The format mask to apply to the date once it's been parsed. The formatted date will
* appear in the textbox while the actual date's ISO8601 string value will be in the
* `iso8601` property.
*/
displayFormat: 'LL',
/**
* When `true`, the parsed date will have its time component set to the last moment of the day.
* Defaults to `false`.
*/
'endOfDay?': false,
/**
* Pressing ENTER will never submit the closest form.
*/
'enterWillSubmitForm?': readOnly('_enterWillNeverSubmitForm'),
/**
* If `true`, ambiguous dates like `Sunday` will be parsed as `next Sunday`. Note that
* non-ambiguous dates are not guaranteed to be in the future. Default is `false`.
*
* @see https://sugarjs.com/docs/#/Date/create
*/
'future?': false,
/**
* If `true`, ambiguous dates like `Sunday` will be parsed as `last Sunday`. Note that non-ambiguous
* dates are not guaranteed to be in the past. Default is `false`.
*
* @see https://sugarjs.com/docs/#/Date/create
*/
'past?': false,
/**
* When `true`, the parsed date will have its time component set to the first moment of the day. The `startOfDay?`
* option takes precedence over the `endOfDay?` option; if both are set to `true` the start of day logic will
* take precedence.
* Defaults to `false`.
*/
'startOfDay?': false,
_enterWillNeverSubmitForm: false,
_processTimezoneAndTimeOfDay(parsedDate) {
// date successfully parsed; now put it into the timezone assigned to this input
const parsedMoment = moment.tz(moment(parsedDate).toArray(), this.get('timezone'));
if (this.get('endOfDay?')) {
parsedMoment.endOf('day');
}
if (this.get('startOfDay?')) {
parsedMoment.startOf('day');
}
return parsedMoment.toDate();
},
/**
* Trigger the appropriate post-parse action.
* @param isFailedParse
* @private
*/
_triggerPostParseEvents(isFailedParse) {
// determine which after-action to triggered based on the parsedDate value
if (isFailedParse) {
this.get('afterParseFail')(this);
} else {
this.get('afterParseSuccess')(this);
}
}
});
|
'use strict'
const path = require('path')
const webpack = require('webpack')
const providePlugin = new webpack.ProvidePlugin({
'jQuery': 'jquery',
'$': 'jquery',
'window.jQuery': 'jquery'
})
module.exports = {
'context': path.join(__dirname, '.'),
'resolve': {
'root': [
path.join(__dirname, '.')
],
'alias': {
'jquery': 'lib/jquery/jquery',
'moment': 'lib/moment',
'underscore': 'lib/wrapper/underscore',
'backbone': 'lib/wrapper/backbone'
}
},
'entry': {
'module-one': './module-one',
'module-two': './module-two'
},
'output': {
'path': path.join(__dirname, '../build/js'),
'filename': '[name].js'
},
'plugins': [
providePlugin
],
'modules': {
'loaders': [
{
'test': /underscore/,
'loader': 'exports?_'
},
{
'test': /backbone/,
'loader': 'exports?Backbone!imports?jquery,underscore'
}
]
}
}
|
var JSLINT = require("./lib/jslint").JSLINT,
print = require("sys").print,
src = require("fs").readFileSync("download/matrix.js", "utf8");
JSLINT(src, { evil: true, forin: true, maxerr: 100 });
// All of the following are known issues that we think are 'ok'
// (in contradiction with JSLint) more information here:
// http://docs.jquery.com/JQuery_Core_Style_Guidelines
var ok = {
"Expected an identifier and instead saw 'undefined' (a reserved word).": true,
"Use '===' to compare with 'null'.": true,
"Use '!==' to compare with 'null'.": true,
"Expected an assignment or function call and instead saw an expression.": true,
"Expected a 'break' statement before 'case'.": true,
"'e' is already defined.": true
};
var e = JSLINT.errors, found = 0, w;
for ( var i = 0; i < e.length; i++ ) {
w = e[i];
if ( !ok[ w.reason ] ) {
found++;
print( "\n" + w.evidence + "\n" );
print( " Problem at line " + w.line + " character " + w.character + ": " + w.reason );
}
}
if ( found > 0 ) {
print( "\n" + found + " Error(s) found.\n" );
} else {
print( "JSLint check passed.\n" );
}
|
function onlyNumber(){
/*
* 05/19/2014
* Kevin Anaya
* www.anaya@gmail.com
*/
// Variable para almacenar array de inputs
inputs = [];
/* Teclas permitidas
*
* En el rango funcKey hasta nine tiene las teclas que usaremos en el if:
* backspace, tab, enter, shift, ctrl, alt, pause/break,
* capslock, escape, pageup, pagedown, end, home,
* leftarrow, uparrow, rightarrow, downarrow, insert, delete,
* 0,1,2,3,4,5,6,7,8,9
*
* En el rango de zero2 y nine2 tiene las teclas que usaremos en el if:
* numpad se refiere a el teclado alfanumerico
* numpad 0, numpad 1, numpad 2, numpad 3, numpad 4,
* numpad 5, numpad 6, numpad 7, numpad 8, numpad 9
*
* variable dot y dot2 contienen el punto para los decimales
*/
var funcKey, zero, nine, zero2, nine2;
funcKey = 8;
//zero = 48;
nine = 57;
zero2 = 96;
nine2 = 105;
dot = 190;
dot2 = 110;
// Se llena el array con los inputs enviados
for (var i = 0; i < arguments.length; i++) {
inputs[i] = arguments[i];
// Al precionarse una tecla en los inputs
$(inputs[i]).keydown(function(evt){
/* Para debug, se puede remover */
//console.log(evt.keyCode);
// Primer rango de teclas
if (!(evt.keyCode >= funcKey) || !(evt.keyCode <= nine)) {
// Segundo rango de teclas
if (!(evt.keyCode >= zero2) || !(evt.keyCode <= nine2)) {
// Verificando dot
if (!(evt.keyCode == dot)) {
if (!(evt.keyCode == dot2)) {
evt.preventDefault();
};
};
};
};
});
};
};
|
'use strict';
module.exports = {
app: {
title: '蜗牛冒险',
description: '蜗牛冒险岛官网',
keywords: '冒险岛,蜗牛,怀旧冒险,游戏,80后',
googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID'
},
db: {
promise: global.Promise
},
port: process.env.PORT || 3300,
host: process.env.HOST || '0.0.0.0',
// DOMAIN config should be set to the fully qualified application accessible
// URL. For example: https://www.myapp.com (including port if required).
domain: process.env.DOMAIN,
// Session Cookie settings
sessionCookie: {
// session expiration is set by default to 24 hours
maxAge: 24 * (60 * 60 * 1000),
// httpOnly flag makes sure the cookie is only accessed
// through the HTTP protocol and not JS/browser
httpOnly: true,
// secure cookie should be turned to true to provide additional
// layer of security so that the cookie is set only when working
// in HTTPS mode.
secure: false
},
// sessionSecret should be changed for security measures and concerns
sessionSecret: process.env.SESSION_SECRET || 'MEAN',
// sessionKey is the cookie session name
sessionKey: 'sessionId',
sessionCollection: 'sessions',
// Lusca config
csrf: {
csrf: false,
csp: false,
xframe: 'SAMEORIGIN',
p3p: 'ABCDEF',
xssProtection: true
},
logo: 'modules/core/client/img/brand/logo.png',
favicon: 'modules/core/client/img/brand/favicon.ico',
illegalUsernames: ['meanjs', 'administrator', 'password', 'admin', 'user',
'unknown', 'anonymous', 'null', 'undefined', 'api'
],
uploads: {
profile: {
image: {
dest: './modules/users/client/img/profile/uploads/',
limits: {
fileSize: 1 * 1024 * 1024 // Max file size in bytes (1 MB)
}
}
}
},
shared: {
owasp: {
allowPassphrases: true,
maxLength: 128,
minLength: 10,
minPhraseLength: 20,
minOptionalTestsToPass: 4
}
}
};
|
import { module, test } from "qunit";
import { setupRenderingTest } from "ember-qunit";
import { buildResolver } from "test-utils";
import { triggerKeyDownEvent } from "event-utils";
import { render, click, focus } from "@ember/test-helpers";
import hbs from "htmlbars-inline-precompile";
import RadioButtonsComponent from "ui/components/form/radio-buttons/component";
import RadioButtonsItemComponent from "ui/components/form/radio-buttons-item/component";
import { helper as IsEqualHelper } from "ui/components/helper/is-equal";
module( "ui/components/form/radio-buttons", function( hooks ) {
setupRenderingTest( hooks, {
resolver: buildResolver({
RadioButtonsComponent,
RadioButtonsItemComponent,
IsEqualHelper
})
});
hooks.beforeEach(function() {
this.getItems = () => Array.from(
this.element.querySelectorAll( ".radio-buttons-item-component" )
);
this.getItem = n => this.getItems()[ n ];
this.getLabels = () => this.getItems()
.map( item => item.innerText.trim() );
this.getChecked = () => this.getItems()
.map( item => item.classList.contains( "checked" ) );
this.getDisabled = () => this.getItems()
.map( item => item.classList.contains( "disabled" ) );
});
test( "DOM nodes, selection and labels", async function( assert ) {
const content = [{
label: "foo",
anotherLabel: "FOO"
}, {
label: "bar",
anotherLabel: "BAR"
}, {
label: "baz",
anotherLabel: "BAZ"
}];
this.setProperties({
content,
selection: content[1],
optionLabelPath: "label"
});
await render( hbs`
{{radio-buttons
content=content
selection=selection
optionLabelPath=optionLabelPath
}}
` );
const elem = this.element.querySelector( ".radio-buttons-component" );
assert.ok( elem instanceof HTMLElement, "Component renders" );
assert.propEqual(
this.getLabels(),
[ "foo", "bar", "baz" ],
"Sets initial item labels"
);
assert.propEqual(
this.getChecked(),
[ false, true, false ],
"Sets initial item selection"
);
assert.propEqual(
this.getDisabled(),
[ false, false, false ],
"Sets initial disabled states"
);
// unset selection (unknown selection)
this.set( "selection", null );
assert.propEqual( this.getChecked(), [ false, false, false ], "No item is selected" );
// set a matching selection
this.set( "selection", content[2] );
assert.propEqual( this.getChecked(), [ false, false, true ], "Updates item selection" );
// click the first list item
await click( this.getItem( 0 ) );
assert.strictEqual( this.get( "selection" ), content[0], "Updates selection on change" );
assert.propEqual( this.getChecked(), [ true, false, false ], "Updates item selections" );
// disable the third item
this.set( "content.2.disabled", true );
assert.propEqual( this.getDisabled(), [ false, false, true ], "Disables third item" );
// try to click the disabled item
await click( this.getItem( 2 ) );
assert.strictEqual( this.get( "selection" ), content[0], "Can't click disabled items" );
assert.propEqual( this.getChecked(), [ true, false, false ], "Selection stays the same" );
// change the optionLabelPath
this.set( "optionLabelPath", "anotherLabel" );
assert.propEqual(
this.getLabels(),
[ "FOO", "BAR", "BAZ" ],
"optionLabelPath changes labels"
);
});
test( "Custom component and child-component blocks", async function( assert ) {
const content = [{
id: 1,
label: "foo",
disabled: true
}, {
id: 2,
label: "bar"
}];
this.setProperties({
content,
selection: content[1]
});
await render( hbs`
{{#radio-buttons content=content selection=selection as |rb|}}
{{#rb.button}}
{{rb.label}}: {{rb.value}} ({{if rb.checked 'y' 'n'}} - {{if rb.disabled 'y' 'n'}})
{{/rb.button}}
{{/radio-buttons}}
` );
assert.propEqual(
this.getLabels(),
[ "foo: 1 (n - y)", "bar: 2 (y - n)" ],
"Custom labels"
);
assert.propEqual(
this.getChecked(),
[ false, true ],
"Items have correct checked states"
);
assert.propEqual(
this.getDisabled(),
[ true, false ],
"items have correct disabled states"
);
});
test( "Hotkeys", async function( assert ) {
let e;
const content = [{
id: 1,
label: "foo"
}, {
id: 2,
label: "bar"
}];
this.setProperties({
content,
selection: content[0]
});
await render( hbs`{{radio-buttons content=content selection=selection}}` );
const elems = this.getItems();
const elemTwo = elems[ 1 ];
assert.propEqual(
elems.map( elem => elem.getAttribute( "tabindex" ) ),
[ "0", "0" ],
"All items have a tabindex attribute with value 0"
);
e = await triggerKeyDownEvent( elemTwo, "Space" );
assert.strictEqual( this.get( "selection" ), content[0], "Ignores Space if not focused" );
assert.notOk( e.isDefaultPrevented(), "Doesn't prevent event's default action" );
assert.notOk( e.isPropagationStopped(), "Doesn't stop event's propagation" );
await focus( elemTwo );
assert.strictEqual(
this.element.ownerDocument.activeElement,
elemTwo,
"Second item is now focused"
);
e = await triggerKeyDownEvent( elemTwo, "Space" );
assert.strictEqual( this.get( "selection" ), content[1], "Changes selection if focused" );
assert.ok( e.isDefaultPrevented(), "Prevents event's default action" );
assert.ok( e.isPropagationStopped(), "Stops event's propagation" );
e = await triggerKeyDownEvent( elemTwo, "Space" );
assert.strictEqual( this.get( "selection" ), content[1], "Keeps selection" );
assert.ok( e.isDefaultPrevented(), "Prevents event's default action" );
assert.ok( e.isPropagationStopped(), "Stops event's propagation" );
await triggerKeyDownEvent( elemTwo, "Escape" );
assert.notStrictEqual(
document.activeElement,
elemTwo,
"Removes focus on Escape"
);
});
});
|
import React from 'react';
import PropTypes from 'prop-types';
import { POSITION_TOP, POSITION_RIGHT, POSITION_BOTTOM, POSITION_LEFT } from '../constants';
import RandomUID from "../utils/RandomUID";
var prefixID = 'react-svg-pan-zoom_border_gradient';
function BorderGradient(_ref) {
var direction = _ref.direction,
width = _ref.width,
height = _ref.height,
_uid = _ref._uid;
var transform = void 0;
switch (direction) {
case POSITION_TOP:
transform = 'translate(' + width + ', 0) rotate(90)';
break;
case POSITION_RIGHT:
transform = 'translate(' + width + ', ' + height + ') rotate(180)';
break;
case POSITION_BOTTOM:
transform = 'translate(0, ' + height + ') rotate(270)';
break;
case POSITION_LEFT:
transform = " ";
break;
}
var gradientID = prefixID + '_gradient_' + _uid;
var maskID = prefixID + '_mask_' + _uid;
return React.createElement(
'g',
null,
React.createElement(
'defs',
null,
React.createElement(
'linearGradient',
{ id: gradientID, x1: '0%', y1: '0%', x2: '100%', y2: '0%', spreadMethod: 'pad' },
React.createElement('stop', { offset: '0%', stopColor: '#fff', stopOpacity: '0.8' }),
React.createElement('stop', { offset: '100%', stopColor: '#000', stopOpacity: '0.5' })
),
React.createElement(
'mask',
{ id: maskID, x: '0', y: '0', width: '20', height: Math.max(width, height) },
React.createElement('rect', { x: '0', y: '0', width: '20', height: Math.max(width, height),
style: { stroke: "none", fill: 'url(#' + gradientID + ')' } })
)
),
React.createElement('rect', { x: '0', y: '0', width: '20', height: Math.max(width, height),
style: { stroke: "none", fill: "#000", mask: 'url(#' + maskID + ')' }, transform: transform })
);
}
BorderGradient.propTypes = {
direction: PropTypes.oneOf([POSITION_TOP, POSITION_RIGHT, POSITION_BOTTOM, POSITION_LEFT]).isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired
};
export default RandomUID(BorderGradient);
|
/**
* requestAnimationFrame
*/
window.requestAnimationFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
/**
* Vector
*/
function Vector(x, y) {
this.x = x || 0;
this.y = y || 0;
}
Vector.add = function(a, b) {
return new Vector(a.x + b.x, a.y + b.y);
};
Vector.sub = function(a, b) {
return new Vector(a.x - b.x, a.y - b.y);
};
Vector.scale = function(v, s) {
return v.clone().scale(s);
};
Vector.random = function() {
return new Vector(
Math.random() * 2 - 1,
Math.random() * 2 - 1
);
};
Vector.prototype = {
set: function(x, y) {
if (typeof x === 'object') {
y = x.y;
x = x.x;
}
this.x = x || 0;
this.y = y || 0;
return this;
},
add: function(v) {
this.x += v.x;
this.y += v.y;
return this;
},
sub: function(v) {
this.x -= v.x;
this.y -= v.y;
return this;
},
scale: function(s) {
this.x *= s;
this.y *= s;
return this;
},
length: function() {
return Math.sqrt(this.x * this.x + this.y * this.y);
},
lengthSq: function() {
return this.x * this.x + this.y * this.y;
},
normalize: function() {
var m = Math.sqrt(this.x * this.x + this.y * this.y);
if (m) {
this.x /= m;
this.y /= m;
}
return this;
},
angle: function() {
return Math.atan2(this.y, this.x);
},
angleTo: function(v) {
var dx = v.x - this.x,
dy = v.y - this.y;
return Math.atan2(dy, dx);
},
distanceTo: function(v) {
var dx = v.x - this.x,
dy = v.y - this.y;
return Math.sqrt(dx * dx + dy * dy);
},
distanceToSq: function(v) {
var dx = v.x - this.x,
dy = v.y - this.y;
return dx * dx + dy * dy;
},
lerp: function(v, t) {
this.x += (v.x - this.x) * t;
this.y += (v.y - this.y) * t;
return this;
},
clone: function() {
return new Vector(this.x, this.y);
},
toString: function() {
return '(x:' + this.x + ', y:' + this.y + ')';
}
};
/**
* GravityPoint
*/
function GravityPoint(x, y, radius, targets) {
Vector.call(this, x, y);
this.radius = radius;
this.currentRadius = radius * 0.5;
this._targets = {
particles: targets.particles || [],
gravities: targets.gravities || []
};
this._speed = new Vector();
}
GravityPoint.RADIUS_LIMIT = 65;
GravityPoint.interferenceToPoint = true;
GravityPoint.prototype = (function(o) {
var s = new Vector(0, 0), p;
for (p in o) s[p] = o[p];
return s;
})({
gravity: 0.05,
isMouseOver: false,
dragging: false,
destroyed: false,
_easeRadius: 0,
_dragDistance: null,
_collapsing: false,
hitTest: function(p) {
return this.distanceTo(p) < this.radius;
},
startDrag: function(dragStartPoint) {
this._dragDistance = Vector.sub(dragStartPoint, this);
this.dragging = true;
},
drag: function(dragToPoint) {
this.x = dragToPoint.x - this._dragDistance.x;
this.y = dragToPoint.y - this._dragDistance.y;
},
endDrag: function() {
this._dragDistance = null;
this.dragging = false;
},
addSpeed: function(d) {
this._speed = this._speed.add(d);
},
collapse: function(e) {
this.currentRadius *= 1.75;
this._collapsing = true;
},
render: function(ctx) {
if (this.destroyed) return;
var particles = this._targets.particles,
i, len;
for (i = 0, len = particles.length; i < len; i++) {
particles[i].addSpeed(Vector.sub(this, particles[i]).normalize().scale(this.gravity));
}
this._easeRadius = (this._easeRadius + (this.radius - this.currentRadius) * 0.07) * 0.95;
this.currentRadius += this._easeRadius;
if (this.currentRadius < 0) this.currentRadius = 0;
if (this._collapsing) {
this.radius *= 0.75;
if (this.currentRadius < 1) this.destroyed = true;
this._draw(ctx);
return;
}
var gravities = this._targets.gravities,
g, absorp,
area = this.radius * this.radius * Math.PI, garea;
for (i = 0, len = gravities.length; i < len; i++) {
g = gravities[i];
if (g === this || g.destroyed) continue;
if (
(this.currentRadius >= g.radius || this.dragging) &&
this.distanceTo(g) < (this.currentRadius + g.radius) * 0.85
) {
g.destroyed = true;
this.gravity += g.gravity;
absorp = Vector.sub(g, this).scale(g.radius / this.radius * 0.5);
this.addSpeed(absorp);
garea = g.radius * g.radius * Math.PI;
this.currentRadius = Math.sqrt((area + garea * 3) / Math.PI);
this.radius = Math.sqrt((area + garea) / Math.PI);
}
g.addSpeed(Vector.sub(this, g).normalize().scale(this.gravity));
}
if (GravityPoint.interferenceToPoint && !this.dragging)
this.add(this._speed);
this._speed = new Vector();
if (this.currentRadius > GravityPoint.RADIUS_LIMIT) this.collapse();
this._draw(ctx);
},
_draw: function(ctx) {
var grd, r;
ctx.save();
grd = ctx.createRadialGradient(this.x, this.y, this.radius, this.x, this.y, this.radius * 5);
grd.addColorStop(0, 'rgba(0, 0, 0, 0.1)');
grd.addColorStop(1, 'rgba(0, 0, 0, 0)');
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius * 5, 0, Math.PI * 2, false);
ctx.fillStyle = grd;
ctx.fill();
r = Math.random() * this.currentRadius * 0.7 + this.currentRadius * 0.3;
grd = ctx.createRadialGradient(this.x, this.y, r, this.x, this.y, this.currentRadius);
grd.addColorStop(0, 'rgba(0, 0, 0, 1)');
grd.addColorStop(1, Math.random() < 0.2 ? 'rgba(255, 196, 0, 0.15)' : 'rgba(103, 181, 191, 0.75)');
ctx.beginPath();
ctx.arc(this.x, this.y, this.currentRadius, 0, Math.PI * 2, false);
ctx.fillStyle = grd;
ctx.fill();
ctx.restore();
}
});
/**
* Particle
*/
function Particle(x, y, radius) {
Vector.call(this, x, y);
this.radius = radius;
this._latest = new Vector();
this._speed = new Vector();
}
Particle.prototype = (function(o) {
var s = new Vector(0, 0), p;
for (p in o) s[p] = o[p];
return s;
})({
addSpeed: function(d) {
this._speed.add(d);
},
update: function() {
if (this._speed.length() > 12) this._speed.normalize().scale(12);
this._latest.set(this);
this.add(this._speed);
}
// render: function(ctx) {
// if (this._speed.length() > 12) this._speed.normalize().scale(12);
// this._latest.set(this);
// this.add(this._speed);
// ctx.save();
// ctx.fillStyle = ctx.strokeStyle = '#fff';
// ctx.lineCap = ctx.lineJoin = 'round';
// ctx.lineWidth = this.radius * 2;
// ctx.beginPath();
// ctx.moveTo(this.x, this.y);
// ctx.lineTo(this._latest.x, this._latest.y);
// ctx.stroke();
// ctx.beginPath();
// ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
// ctx.fill();
// ctx.restore();
// }
});
// Initialize
(function() {
// Configs
var BACKGROUND_COLOR = 'rgba(11, 51, 56, 1)',
PARTICLE_RADIUS = 1,
G_POINT_RADIUS = 10,
G_POINT_RADIUS_LIMITS = 65;
// Vars
var canvas, context,
bufferCvs, bufferCtx,
screenWidth, screenHeight,
mouse = new Vector(),
gravities = [],
particles = [],
grad,
gui, control;
// Event Listeners
function resize(e) {
screenWidth = canvas.width = window.innerWidth;
screenHeight = canvas.height = window.innerHeight;
bufferCvs.width = screenWidth;
bufferCvs.height = screenHeight;
context = canvas.getContext('2d');
bufferCtx = bufferCvs.getContext('2d');
var cx = canvas.width * 0.5,
cy = canvas.height * 0.5;
grad = context.createRadialGradient(cx, cy, 0, cx, cy, Math.sqrt(cx * cx + cy * cy));
grad.addColorStop(0, 'rgba(0, 0, 0, 0)');
grad.addColorStop(1, 'rgba(0, 0, 0, 0.35)');
}
function mouseMove(e) {
mouse.set(e.clientX, e.clientY);
var i, g, hit = false;
for (i = gravities.length - 1; i >= 0; i--) {
g = gravities[i];
if ((!hit && g.hitTest(mouse)) || g.dragging)
g.isMouseOver = hit = true;
else
g.isMouseOver = false;
}
canvas.style.cursor = hit ? 'pointer' : 'default';
}
function mouseDown(e) {
for (var i = gravities.length - 1; i >= 0; i--) {
if (gravities[i].isMouseOver) {
gravities[i].startDrag(mouse);
return;
}
}
gravities.push(new GravityPoint(e.clientX, e.clientY, G_POINT_RADIUS, {
particles: particles,
gravities: gravities
}));
}
function mouseUp(e) {
for (var i = 0, len = gravities.length; i < len; i++) {
if (gravities[i].dragging) {
gravities[i].endDrag();
break;
}
}
}
function doubleClick(e) {
for (var i = gravities.length - 1; i >= 0; i--) {
if (gravities[i].isMouseOver) {
gravities[i].collapse();
break;
}
}
}
// Functions
function addParticle(num) {
var i, p;
for (i = 0; i < num; i++) {
p = new Particle(
Math.floor(Math.random() * screenWidth - PARTICLE_RADIUS * 2) + 1 + PARTICLE_RADIUS,
Math.floor(Math.random() * screenHeight - PARTICLE_RADIUS * 2) + 1 + PARTICLE_RADIUS,
PARTICLE_RADIUS
);
p.addSpeed(Vector.random());
particles.push(p);
}
}
function removeParticle(num) {
if (particles.length < num) num = particles.length;
for (var i = 0; i < num; i++) {
particles.pop();
}
}
// GUI Control
control = {
particleNum: 100
};
// Init
canvas = document.getElementById('c');
bufferCvs = document.createElement('canvas');
window.addEventListener('resize', resize, false);
resize(null);
addParticle(control.particleNum);
canvas.addEventListener('mousemove', mouseMove, false);
canvas.addEventListener('mousedown', mouseDown, false);
canvas.addEventListener('mouseup', mouseUp, false);
canvas.addEventListener('dblclick', doubleClick, false);
// GUI
gui = new dat.GUI();
gui.add(control, 'particleNum', 0, 500).step(1).name('动力因子数').onChange(function() {
var n = (control.particleNum | 0) - particles.length;
if (n > 0)
addParticle(n);
else if (n < 0)
removeParticle(-n);
});
gui.add(GravityPoint, 'interferenceToPoint').name('重力点相互吸引');
gui.close();
// Start Update
var loop = function() {
var i, len, g, p;
context.save();
context.fillStyle = BACKGROUND_COLOR;
context.fillRect(0, 0, screenWidth, screenHeight);
context.fillStyle = grad;
context.fillRect(0, 0, screenWidth, screenHeight);
context.restore();
for (i = 0, len = gravities.length; i < len; i++) {
g = gravities[i];
if (g.dragging) g.drag(mouse);
g.render(context);
if (g.destroyed) {
gravities.splice(i, 1);
len--;
i--;
}
}
bufferCtx.save();
bufferCtx.globalCompositeOperation = 'destination-out';
bufferCtx.globalAlpha = 0.35;
bufferCtx.fillRect(0, 0, screenWidth, screenHeight);
bufferCtx.restore();
// パーティクルをバッファに描画
// for (i = 0, len = particles.length; i < len; i++) {
// particles[i].render(bufferCtx);
// }
len = particles.length;
bufferCtx.save();
bufferCtx.fillStyle = bufferCtx.strokeStyle = '#fff';
bufferCtx.lineCap = bufferCtx.lineJoin = 'round';
bufferCtx.lineWidth = PARTICLE_RADIUS * 2;
bufferCtx.beginPath();
for (i = 0; i < len; i++) {
p = particles[i];
p.update();
bufferCtx.moveTo(p.x, p.y);
bufferCtx.lineTo(p._latest.x, p._latest.y);
}
bufferCtx.stroke();
bufferCtx.beginPath();
for (i = 0; i < len; i++) {
p = particles[i];
bufferCtx.moveTo(p.x, p.y);
bufferCtx.arc(p.x, p.y, p.radius, 0, Math.PI * 2, false);
}
bufferCtx.fill();
bufferCtx.restore();
// バッファをキャンバスに描画
context.drawImage(bufferCvs, 0, 0);
requestAnimationFrame(loop);
};
loop();
})();
|
module.exports = {
purge: [
'./**/*.html.tera',
'../content/**/*.md'
],
theme: {
extend: {},
},
variants: {},
plugins: [],
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:6f9bc384ce6942215d73b95984a9406979d8f679c1152ecfe36a3f0536341d98
size 167
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from '../styles/itemDetailTabs.scss';
const activeStyle = { filter: 'none', opacity: 1 };
const inactiveStyle = { filter: 'grayscale(100%)', opacity: 0.4 };
const ItemDetailTabs = ({ isCancelOrderPlus, onToggleOrderTab, activeOrderTab, onToggleCancelOrder }) =>
<div id={styles.item_details_tabs}>
<div className={styles.details_tabs}
style={
isCancelOrderPlus ? inactiveStyle : activeStyle
}>
<div style={{background: activeOrderTab === 'item_details' ? '#25C7C7' : '#23A0A0'}} id={styles.item_details_tab} tabIndex={1} onFocus={() => isCancelOrderPlus || onToggleOrderTab('item_details')}></div>
<div style={{background: activeOrderTab === 'fulfilment_details' ? '#25C7C7' : '#23A0A0'}} id={styles.fulfilment_details_tab} tabIndex={2} onFocus={() => isCancelOrderPlus || onToggleOrderTab('fulfilment_details')}></div>
</div>
<button style={
isCancelOrderPlus ? inactiveStyle : activeStyle
} id={styles.priority}>
<span>Medium</span>
</button>
<button style={
isCancelOrderPlus ? inactiveStyle : activeStyle
} id={styles.unlock}></button>
<button id={styles.delete} onClick={() => isCancelOrderPlus || onToggleCancelOrder()} style={
{backgroundColor: isCancelOrderPlus ? '#E86D6D' : '#23A0A0'}
}></button>
</div>;
ItemDetailTabs.propTypes = {
isCancelOrderPlus: PropTypes.bool,
onToggleOrderTab: PropTypes.func,
onToggleCancelOrder: PropTypes.func,
activeOrderTab: PropTypes.string
};
export default ItemDetailTabs;
|
var logger = require('../util/logger')(__filename),
request = require('request'),
async = require('async'),
geo = require('../util/geo'),
util = require('../util/util');
var BASE_URL_CALENDAR = 'https://www.googleapis.com/calendar/v3/';
function calendars(user, done) {
util.doCall('GET', BASE_URL_CALENDAR, 'users/me/calendarList', user.accessToken, function(err, calendars) {
if (err) {
return done(err, null);
}
var results = [];
if (calendars && calendars.items) {
calendars.items.forEach(function(calendar) {
//logger.info('Calendar kind ', calendar.kind);
if (calendar.kind === "calendar#calendarListEntry") {
var item = {};
item.id = calendar.id;
item.summary = calendar.summary;
if (calendar.location) {
item.location = calendar.location;
}
results.push(item);
}
});
}
logger.info('User "' + user.name + '" has ' + results.length + ' calendars');
done(null, results);
});
}
function checkAttendee(user, event) {
if (event.creator && event.creator.email === user.email || event.organizer && event.organizer.email === user.email) {
return true;
}
if (event.attendees) {
return rdo = event.attendees.some(function(attendee) {
return attendee.email === user.email && attendee.responseStatus === "accepted";
});
}
}
function upcomingEventsFromCalendar(user, calendarId, done) {
var time = new Date();
var timeMin = time.toISOString();
time.setHours(time.getHours() + 24);
var timeMax = time.toISOString();
var url = 'calendars/' + encodeURIComponent(calendarId) + "/events?singleEvents=true&timeMin=" + timeMin + "&timeMax=" + timeMax;
util.doCall('GET', BASE_URL_CALENDAR, url, user.accessToken, function(err, events) {
if (err) {
return done(err, null);
}
var results = [];
if (events && events.items) {
events.items.forEach(function(event) {
if (event.kind === "calendar#event" && checkAttendee(user, event)) {
var item = {};
item.id = event.id;
item.summary = event.summary;
item.start = event.start;
item.end = event.end;
logger.info('Event "' + event.summary + '" location = ' + event.location);
if (event.location) {
item.location = event.location;
}
results.push(item);
}
});
}
logger.info('calendar ' + calendarId + ' has ' + results.length + ' events.');
done(null, results);
});
}
function allUpcomingEvents(user, done) {
calendars(user, function(err, calendars) {
if (err) {
return done(err, null);
}
async.each(calendars, function(calendar, callback) {
upcomingEventsFromCalendar(user, calendar.id, function(err, events) {
if (err) {
callback(err);
} else {
calendar.events = events;
callback();
}
});
}, function(err) {
if (err) {
return done(err, null);
}
var results = [];
var q = async.queue(function(event, callback) {
logger.info('Searching for event address = ' + event.address, event);
if (!event.address) {
return callback();
}
geo.geoLoc(event, callback);
});
q.drain = function() {
done(null, results);
};
//Creates a fake task to ensure q.drain method is called
q.push({});
if (calendars) {
calendars.forEach(function(calendar) {
logger.info('Calendar "' + calendar.summary + '" has ' + calendar.events.length + ' events');
if (calendar && calendar.events) {
calendar.events.forEach(function(event) {
var location = event.location || calendar.location;
logger.info('Location "' + location + '"', event);
if (location) {
event.address = location;
event.idCalendar = calendar.id;
results.push(event);
q.push(event, function(err) {
if (err) {
logger.error("Error: " + err);
}
});
}
});
}
});
}
});
});
}
module.exports = {
upcomingEvents: allUpcomingEvents,
calendars: calendars
};
|
export const db = process.env.MONGOHQ_URL || process.env.MONGODB_URI || 'mongodb://localhost/EDocs';
export default {
db
};
|
import '../../../images/profile.jpg';
import * as actions from '../../../actions/HeaderActions';
import { APP_NAME, LABEL_BOOKS, LABEL_LIBRARY, LABEL_SETTINGS } from '../../../labels/';
import FontAwesome from 'react-fontawesome';
import { HeaderControls } from './HeaderControls';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Navbar from 'react-bootstrap/lib/Navbar';
import PropTypes from 'prop-types';
import React from 'react';
import { bindActionCreators } from 'redux';
import { browserHistory } from 'react-router';
import { connect } from 'react-redux';
export class Header extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.goToSettingsFromHeader = this.goToSettings.bind(this);
this.thisGoToLibrary = this.goToLibrary.bind(this);
this.thisGoToBooks = this.goToBooks.bind(this);
}
goToSettings() {
browserHistory.push('/settings');
}
goToBooks() {
browserHistory.push('/books');
}
goToLibrary() {
browserHistory.push('/library');
}
render() {
return (<Navbar collapseOnSelect fixedTop={true} fluid={true}>
<Navbar.Header>
<Navbar.Brand>
<a href="">{APP_NAME}</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<HeaderControls router={this.props.router} headers={this.props.headers} />
<Nav pullRight>
<NavItem onClick={this.thisGoToBooks}><FontAwesome size="lg" name="book"
fixedWidth={true} /> {LABEL_BOOKS}</NavItem>
<NavItem onClick={this.thisGoToLibrary}><FontAwesome size="lg" name="bookmark"
fixedWidth={true} /> {LABEL_LIBRARY}</NavItem>
<NavItem onClick={this.goToSettingsFromHeader}><FontAwesome size="lg" name="gear"
fixedWidth={true} /> {LABEL_SETTINGS}
</NavItem>
<NavItem><img className="header-thumbnail" height="24" width="24"
src="/profile.jpg" /> {this.props.security.fullname}</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>);
}
}
Header.propTypes = {
security: PropTypes.object.isRequired,
headers: PropTypes.object.isRequired,
router: PropTypes.object.isRequired
};
function mapStateToProps(state) {
return {
headers: state.headers
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export const ConnectedHeader = connect(mapStateToProps, mapDispatchToProps)(Header);
|
const Task = require('data.task');
const fs = require('fs');
// readFile : String -> Task e String
exports.readFile = fileName =>
new Task((reject, resolve) =>
fs.readFile(fileName, 'utf-8', (err, contents) =>
err ? reject(err) : resolve(contents))
);
// writeFile : String -> String -> Task e ()
exports.writeFile = fileName => contents =>
new Task((reject, resolve) =>
fs.writeFile(fileName, contents, err =>
err ? reject(err) : resolve()));
// stat : String -> Task e Stats
exports.stat = path =>
new Task((reject, resolve) =>
fs.stat(path, (err, stats) =>
err ? reject(err) : resolve(stats)));
// mkdir : String -> Task e ()
exports.mkdir = path =>
new Task((reject, resolve) =>
fs.mkdir(path, err =>
err ? reject(err) : resolve()));
|
(function (factory) {
if (typeof module === 'object' && typeof module.exports === 'object') {
var v = factory(require, exports);
if (v !== undefined) {
module.exports = v;
}
} else if (typeof define === 'function' && define.amd) {
define(['require', 'exports'], factory);
}
})(function (require, exports) {
'use strict';
var _hasOwnProperty = Object.prototype.hasOwnProperty;
var _hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator !== 'undefined';
var ObjectPathError = (function () {
function ObjectPathError (message) {
this.message = message;
this.name = 'ObjectPathError';
ReferenceError.call(this, message);
/* istanbul ignore next: no need to test */
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
/* istanbul ignore next: no need to test */
if (!this.stack) {
this.stack = (new Error).stack;
}
}
return ObjectPathError;
})();
ObjectPathError.prototype = Object.create(ReferenceError.prototype, {
constructor: {
value: ObjectPathError
}
});
function isNumber (value) {
return typeof value === 'number' && value.constructor === Number;
}
function isString (obj) {
return typeof obj === 'string' && obj.constructor === String;
}
function isObject (obj) {
return typeof obj === 'object' && obj !== null && obj.constructor !== Array;
}
function isSymbol (obj) {
return _hasSymbols && typeof obj === 'symbol' && obj.constructor === Symbol;
}
function isArray (obj) {
return typeof obj === 'object' && obj !== null && obj.constructor === Array;
}
function isBoolean (obj) {
return typeof obj === 'boolean' && obj.constructor === Boolean;
}
function merge (base) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (!isObject(base)) {
base = {};
}
for (var _a = 0; _a < args.length; _a++) {
var arg = args[_a];
if (isObject(arg)) {
for (var option in arg) {
base[option] = arg[option];
}
}
}
return base;
}
function isEmpty (value, ownPropertiesOnly) {
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
// String, boolean, number that is either '', false respectivelly or null and undefined
// 0 is a valid "path", as it can refer to either the key of an object, or an array index
if (!value) {
if (value === 0) {
return false;
}
return true;
} else if (isNumber(value)) {
return false;
}
// Preemptively return as soon as we get something for performance reasons
if (isArray(value) && value.length === 0) {
return true;
} else if (isSymbol(value)) {
return false;
} else if (!isString(value)) {
for (var i in value) {
if (ownPropertiesOnly === true) {
// Must have own property to be considered non-empty
if (_hasOwnProperty.call(value, i)) {
return false;
}
} else {
// Since it has at least one member, assume non-empty, return immediately
return false;
}
}
// symbols can't be walked with for in
/* istanbul ignore else */
if (_hasSymbols) {
if (Object.getOwnPropertySymbols(value).length) {
return false;
}
}
return true;
}
return false;
}
function getKey (key) {
if (isSymbol(key)) {
return key;
}
// Perf: http://jsperf.com/tostring-vs-typecast-vs
if (('' + ~~key) === key) {
// Return the integer if it's a real number
return ~~key;
}
return key;
}
function ensureExists (obj, path, value, noThrow, ownPropertiesOnly) {
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
return set(obj, path, value, true, noThrow, ownPropertiesOnly);
}
function set (obj, path, value, doNotReplace, noThrow, ownPropertiesOnly) {
if (doNotReplace === void 0) {
doNotReplace = false;
}
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
if (typeof obj !== 'object' && isEmpty(obj, ownPropertiesOnly)) {
if (noThrow === true) {
return obj;
}
throw new ObjectPathError('provided object is empty');
}
if (isNumber(path) || isSymbol(path)) {
path = [path];
}
if (isEmpty(path, ownPropertiesOnly)) {
if (noThrow === true) {
return obj;
}
throw new ObjectPathError('provided path is empty');
}
if (isString(path)) {
path = path.split('.');
return set(obj, path.map(getKey), value, doNotReplace, noThrow, ownPropertiesOnly);
}
var currentPath = path[0];
if (path.length === 1) {
var oldVal = obj[currentPath];
if (oldVal === void 0 || !doNotReplace) {
obj[currentPath] = value;
}
return oldVal;
}
if (obj[currentPath] === void 0) {
if (isNumber(path[1])) {
obj[currentPath] = [];
} else {
obj[currentPath] = {};
}
}
return set(obj[currentPath], path.slice(1), value, doNotReplace, true, ownPropertiesOnly);
}
function del (obj, path, noThrow, ownPropertiesOnly) {
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
if (isEmpty(obj, ownPropertiesOnly)) {
if (noThrow === true) {
return obj;
}
throw new ObjectPathError('provided object is empty');
}
if (isNumber(path) || isSymbol(path)) {
path = [path];
}
if (isEmpty(path, ownPropertiesOnly)) {
if (noThrow === true) {
return obj;
}
throw new ObjectPathError('provided path is empty');
}
if (isString(path)) {
return del(obj, path.split('.'), noThrow, ownPropertiesOnly);
}
var currentPath = getKey(path[0]);
var oldVal = obj[currentPath];
if (path.length === 1) {
if (oldVal !== void 0) {
if (isNumber(currentPath) && isArray(obj)) {
obj.splice(currentPath, 1);
} else {
delete obj[currentPath];
}
}
} else if (obj[currentPath] !== void 0) {
return del(obj[currentPath], path.slice(1), true, ownPropertiesOnly);
}
return obj;
}
function has (obj, path, noThrow, ownPropertiesOnly) {
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
if (isEmpty(obj, ownPropertiesOnly)) {
if (noThrow === true) {
return false;
}
throw new ObjectPathError('provided object is empty');
}
if (isNumber(path) || isSymbol(path)) {
path = [path];
}
if (isEmpty(path, ownPropertiesOnly)) {
if (noThrow === true) {
return false;
}
throw new ObjectPathError('provided path is empty');
}
if (isString(path)) {
path = path.split('.');
}
for (var i = 0; i < path.length; i++) {
var j = path[i];
if (isObject(obj) || isArray(obj)) {
if (ownPropertiesOnly) {
if (_hasOwnProperty.call(obj, j)) {
obj = obj[j];
} else {
return false;
}
} else {
if (j in obj) {
obj = obj[j];
} else {
return false;
}
}
} else {
return false;
}
}
return true;
}
function insert (obj, path, value, at, noThrow, ownPropertiesOnly) {
if (at === void 0) {
at = 0;
}
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
var arr = get(obj, path, void 0, noThrow, ownPropertiesOnly);
at = ~~at;
if (!isArray(arr)) {
arr = [];
set(obj, path, arr, false, noThrow, ownPropertiesOnly);
}
arr.splice(at, 0, value);
}
function empty (obj, path, noThrow, ownPropertiesOnly) {
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
var value = get(obj, path, Number.NaN, noThrow, ownPropertiesOnly);
if (value !== value) {
return void 0;
}
if (isString(value)) {
return set(obj, path, '', false, noThrow, ownPropertiesOnly);
} else if (isBoolean(value)) {
return set(obj, path, false, false, noThrow, ownPropertiesOnly);
} else if (isNumber(value)) {
return set(obj, path, 0, false, noThrow, ownPropertiesOnly);
} else if (isArray(value)) {
value.length = 0;
} else if (isObject(value)) {
for (var i in value) {
if (ownPropertiesOnly === true) {
if (_hasOwnProperty.call(value, i)) {
delete value[i];
}
} else {
delete value[i];
}
}
/* istanbul ignore else */
if (_hasSymbols) {
var symbols = Object.getOwnPropertySymbols(value);
if (symbols.length) {
for (var x = 0; x < symbols.length; x++) {
delete value[symbols[x]];
}
}
}
} else {
return set(obj, path, null, false, noThrow, ownPropertiesOnly);
}
}
function push (obj, path, args, noThrow, ownPropertiesOnly) {
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
if (!isArray(args)) {
// breaking change needs to be forcefully noticed
throw new ObjectPathError('3rd parameter "args" must be an array');
}
var arr = get(obj, path, void 0, noThrow, ownPropertiesOnly);
if (!isArray(arr)) {
arr = [];
set(obj, path, arr, false, noThrow, ownPropertiesOnly);
}
Array.prototype.push.apply(arr, args);
}
function coalesce (obj, paths, defaultValue, noThrow, ownPropertiesOnly) {
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
var value;
for (var i = 0, len = paths.length; i < len; i++) {
value = get(obj, paths[i], Number.NaN, noThrow, ownPropertiesOnly);
// looks silly but NaN is never equal to itself, it's a good unique value
if (value === value) {
return value;
}
}
return defaultValue;
}
function get (obj, path, defaultValue, noThrow, ownPropertiesOnly) {
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
if (isEmpty(obj, ownPropertiesOnly)) {
if (noThrow === true) {
return defaultValue;
}
throw new ObjectPathError('provided object is empty');
}
if (isNumber(path) || isSymbol(path)) {
path = [path];
}
if (isEmpty(path, ownPropertiesOnly)) {
if (noThrow === true) {
return defaultValue;
}
throw new ObjectPathError('provided path is empty');
}
if (isString(path)) {
return get(obj, path.split('.'), defaultValue, noThrow, ownPropertiesOnly);
}
var currentPath = getKey(path[0]);
if (path.length === 1) {
if (obj[currentPath] === void 0) {
return defaultValue;
}
return obj[currentPath];
}
return get(obj[currentPath], path.slice(1), defaultValue, true, ownPropertiesOnly);
}
var skipProps = {bind: true,ObjectPathError: true};
var objectPath = {
ObjectPathError: ObjectPathError,
get: get,
set: set,
coalesce: coalesce,
push: push,
ensureExists: ensureExists,
empty: empty,
del: del,
insert: insert,
has: has,
bind: bind,
extend: extend
};
function bind (obj, noThrow, ownPropertiesOnly) {
if (noThrow === void 0) {
noThrow = false;
}
if (ownPropertiesOnly === void 0) {
ownPropertiesOnly = true;
}
if (noThrow === false && isEmpty(obj, ownPropertiesOnly)) {
throw new ObjectPathError('provided object is empty');
}
var funcNames = [];
var self = this;
for (var x in self) {
if (!(x in skipProps) && typeof self[x] === 'function') {
funcNames.push(x);
}
}
return funcNames.reduce(function (proxy, prop) {
/* Function.prototype.bind is easier, but much slower in V8 (aka node/chrome) */
proxy[prop] = function () {
var args = [obj];
Array.prototype.push.apply(args, arguments);
return self[prop].apply(self, args);
};
return proxy;
}, {});
}
function extend (ctor, noConflict) {
if (noConflict === void 0) {
noConflict = false;
}
var base = {
set: set,
merge: merge,
coalesce: coalesce,
del: del,
empty: empty,
ensureExists: ensureExists,
isSymbol: isSymbol,
get: get,
getKey: getKey,
has: has,
insert: insert,
isArray: isArray,
isBoolean: isBoolean,
isEmpty: isEmpty,
isNumber: isNumber,
isObject: isObject,
isString: isString,
push: push,
extend: extend,
bind: bind,
ObjectPathError: ObjectPathError
};
var self = this;
if (noConflict === true) {
return merge({}, self, ctor(base));
} else {
return merge(self, ctor(base));
}
}
return objectPath;
});
|
var geometry = require("../src/index");
var expect = require("chai").expect;
describe("Polygon", function(){
describe("new Polygon", function(){
it("creates point object", function(){
var poly = new geometry.Polygon([]);
expect(poly instanceof geometry.IShape).to.equal(true);
});
});
describe("toString()", function () {
it("checks class name", function () {
var poly = new geometry.Polygon([]);
expect(poly.toString()).to.equal("[object Polygon]");
});
});
describe("constructor", function () {
it("checks constructor property", function () {
var poly = new geometry.Polygon([]);
expect(poly.constructor).to.equal(geometry.Polygon);
});
});
describe("contains()", function(){
it("checks point inside the polygon (point is between two vertices (horizontally))", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 5),
new geometry.Point(1, 3),
new geometry.Point(4, 0),
new geometry.Point(5, 3),
new geometry.Point(4, 5),
new geometry.Point(3, 4)
]);
expect(poly.contains(new geometry.Point(3, 3))).to.equal(true);
});
it("checks point inside the polygon (point is between three vertices (horizontally))", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 5),
new geometry.Point(1, 3),
new geometry.Point(3, 3),
new geometry.Point(4, 0),
new geometry.Point(5, 3),
new geometry.Point(4, 5),
new geometry.Point(3, 4)
]);
expect(poly.contains(new geometry.Point(4, 3))).to.equal(true);
});
it("checks point outside complex polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 8),
new geometry.Point(3, 1),
new geometry.Point(9, 1),
new geometry.Point(9, 9),
new geometry.Point(5, 9),
new geometry.Point(3, 3),
new geometry.Point(8, 4),
new geometry.Point(8, 2),
new geometry.Point(4, 2),
new geometry.Point(6, 7)
]);
expect(poly.contains(new geometry.Point(4, 4))).to.equal(false);
expect(poly.contains(new geometry.Point(4, 5))).to.equal(false);
expect(poly.contains(new geometry.Point(5, 5))).to.equal(false);
expect(poly.contains(new geometry.Point(5, 6))).to.equal(false);
expect(poly.contains(new geometry.Point(5, 3))).to.equal(false);
expect(poly.contains(new geometry.Point(6, 3))).to.equal(false);
expect(poly.contains(new geometry.Point(7, 3))).to.equal(false);
});
it("checks all points inside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 0),
new geometry.Point(2, 2),
new geometry.Point(4, 2),
new geometry.Point(5, 1)
]);
expect(poly.contains(new geometry.Point(1, 0))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 2))).to.equal(true);
});
it("checks all points of the arbitrary polygon to be inside it", function(){
var poly = new geometry.Polygon([
new geometry.Point(7, 1),
new geometry.Point(1, 2),
new geometry.Point(5, 4),
new geometry.Point(2, 7),
new geometry.Point(8, 7),
new geometry.Point(9, 2)
]);
expect(poly.contains(new geometry.Point(7, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(6, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(7, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(8, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(9, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(6, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(7, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(8, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 4))).to.equal(true);
expect(poly.contains(new geometry.Point(6, 4))).to.equal(true);
expect(poly.contains(new geometry.Point(7, 4))).to.equal(true);
expect(poly.contains(new geometry.Point(8, 4))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(6, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(7, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(8, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(6, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(7, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(8, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 7))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 7))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 7))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 7))).to.equal(true);
expect(poly.contains(new geometry.Point(6, 7))).to.equal(true);
expect(poly.contains(new geometry.Point(7, 7))).to.equal(true);
expect(poly.contains(new geometry.Point(8, 7))).to.equal(true);
});
it("checks all points of the complex arbitrary polygon to be inside it", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(6, 1),
new geometry.Point(1, 6),
new geometry.Point(6, 6)
]);
expect(poly.contains(new geometry.Point(1, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(6, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 4))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 4))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 5))).to.equal(true);
expect(poly.contains(new geometry.Point(1, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(4, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(5, 6))).to.equal(true);
expect(poly.contains(new geometry.Point(6, 6))).to.equal(true);
});
it("checks point to be outside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 0),
new geometry.Point(2, 2),
new geometry.Point(4, 2),
new geometry.Point(5, 1)
]);
expect(poly.contains(new geometry.Point(1, 2))).to.equal(false);
expect(poly.contains(new geometry.Point(4, 0))).to.equal(false);
expect(poly.contains(new geometry.Point(3, 0))).to.equal(false);
});
it("checks point that stands exact on polygon's edges", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(3, 3),
new geometry.Point(0, 3)
]);
expect(poly.contains(new geometry.Point(0, 0))).to.equal(true);
expect(poly.contains(new geometry.Point(1, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 2))).to.equal(true);
expect(poly.contains(new geometry.Point(3, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(0, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(1, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(2, 3))).to.equal(true);
expect(poly.contains(new geometry.Point(0, 1))).to.equal(true);
expect(poly.contains(new geometry.Point(0, 2))).to.equal(true);
});
it("checks line to be inside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var line = new geometry.Line(
new geometry.Point(3, 3),
new geometry.Point(2, 3));
expect(poly.contains(line)).to.equal(true);
});
it("checks line to be inside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var line = new geometry.Line(
new geometry.Point(1, 1),
new geometry.Point(1, 4));
expect(poly.contains(line)).to.equal(true);
});
it("checks line to be inside the arbitrary polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(1, 7),
new geometry.Point(7, 7),
new geometry.Point(7, 1),
new geometry.Point(4, 5)
]);
var line = new geometry.Line(
new geometry.Point(2, 6),
new geometry.Point(6, 6));
expect(poly.contains(line)).to.equal(true);
});
it("checks line to be inside the arbitrary polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(1, 7),
new geometry.Point(7, 7),
new geometry.Point(7, 1),
new geometry.Point(4, 5)
]);
var line = new geometry.Line(
new geometry.Point(2, 4),
new geometry.Point(6, 4));
expect(poly.contains(line)).to.equal(false);
});
it("checks line to be inside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 0),
new geometry.Point(2, 2),
new geometry.Point(4, 2),
new geometry.Point(5, 1)
]);
var line = new geometry.Line(
new geometry.Point(1, 0),
new geometry.Point(4, 1));
expect(poly.contains(line)).to.equal(true);
});
it("checks line to be outside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 0),
new geometry.Point(2, 2),
new geometry.Point(4, 2),
new geometry.Point(5, 1)
]);
var line = new geometry.Line(
new geometry.Point(2, 1),
new geometry.Point(3, 3));
expect(poly.contains(line)).to.equal(false);
});
it("checks polygon to be inside the polygon", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(3, 3),
new geometry.Point(1, 3)
]);
expect(poly1.contains(poly2)).to.equal(true);
});
it("checks polygon not to be inside the convex polygon", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(1, 7),
new geometry.Point(7, 7),
new geometry.Point(7, 1),
new geometry.Point(4, 5)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(2, 6),
new geometry.Point(6, 6),
new geometry.Point(6, 4)
]);
expect(poly1.contains(poly2)).to.equal(false);
});
it("checks polygon to be outside the polygon", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(4, 1),
new geometry.Point(1, 3)
]);
expect(poly1.contains(poly2)).to.equal(false);
});
it("checks rectangle to be inside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(4, 0),
new geometry.Point(8, 5),
new geometry.Point(0, 4)
]);
var rect = new geometry.Rectangle(3, 2, 2, 1);
expect(poly.contains(rect)).to.equal(true);
});
it("checks rectangle not to be inside convex polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(1, 7),
new geometry.Point(7, 7),
new geometry.Point(7, 1),
new geometry.Point(4, 5)
]);
var rect = new geometry.Rectangle(2, 4, 5, 2);
expect(poly.contains(rect)).to.equal(false);
});
it("checks rectangle to be not inside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(1, 5),
new geometry.Point(5, 5),
new geometry.Point(5, 1)
]);
var rect = new geometry.Rectangle(1, 1, 4, 4);
expect(poly.contains(rect)).to.equal(true);
});
it("checks rectangle to be outside the polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(4, 0),
new geometry.Point(8, 5),
new geometry.Point(0, 4)
]);
var rect = new geometry.Rectangle(0, 3, 4, 1);
expect(poly.contains(rect)).to.equal(false);
});
});
describe("equals()", function(){
it("checks two same polygons", function(){
var poly1 = new geometry.Polygon([]);
var poly2 = new geometry.Polygon([]);
expect(poly1.equals(poly2)).to.equal(true);
});
it("checks two same polygons", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(2, 2),
new geometry.Point(3, 3)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(2, 2),
new geometry.Point(3, 3)
]);
expect(poly1.equals(poly2)).to.equal(true);
});
it("checks two different polygons", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(0, 1),
new geometry.Point(2, 2),
new geometry.Point(3, 3)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(2, 2),
new geometry.Point(3, 3)
]);
expect(poly1.equals(poly2)).to.equal(false);
});
it("checks two almost same polygons (order of vertices is different)", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(0, 1),
new geometry.Point(2, 2),
new geometry.Point(3, 3)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(2, 2),
new geometry.Point(0, 1),
new geometry.Point(3, 3)
]);
expect(poly1.equals(poly2)).to.equal(false);
});
it("checks two polygons with different amount of vertices", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(2, 2),
new geometry.Point(3, 3)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(2, 2)
]);
expect(poly1.equals(poly2)).to.equal(false);
});
});
describe("intersects()", function(){
it("check point intersection with polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
expect(poly.intersects(new geometry.Point(0, 2))).to.equal(true);
expect(poly.intersects(new geometry.Point(3, 3))).to.equal(true);
});
it("check point to not intersects with polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
expect(poly.intersects(new geometry.Point(-1, 2))).to.equal(false);
});
it("check line to intersects with polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var line = new geometry.Line(
new geometry.Point(1, 2),
new geometry.Point(3, 0));
expect(poly.intersects(line)).to.equal(true);
});
it("check line to intersects with polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var line = new geometry.Line(
new geometry.Point(2, 5),
new geometry.Point(3, 0));
expect(poly.intersects(line)).to.equal(true);
});
it("check line to intersects with complex polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(6, 1),
new geometry.Point(1, 6),
new geometry.Point(6, 6)
]);
var line = new geometry.Line(
new geometry.Point(6, 0),
new geometry.Point(6, 7));
expect(poly.intersects(line)).to.equal(true);
});
it("check line to intersects with complex polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(6, 1),
new geometry.Point(1, 6),
new geometry.Point(6, 6)
]);
var line = new geometry.Line(
new geometry.Point(1, 0),
new geometry.Point(1, 7));
expect(poly.intersects(line)).to.equal(true);
});
it("check line to intersects with complex polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(6, 1),
new geometry.Point(1, 6),
new geometry.Point(6, 6)
]);
var line = new geometry.Line(
new geometry.Point(7, 0),
new geometry.Point(0, 7));
expect(poly.intersects(line)).to.equal(true);
});
it("check line to intersects with complex polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(6, 1),
new geometry.Point(1, 6),
new geometry.Point(6, 6)
]);
var line = new geometry.Line(
new geometry.Point(0, 0),
new geometry.Point(7, 7));
expect(poly.intersects(line)).to.equal(true);
});
it("check line to intersects with complex polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(6, 1),
new geometry.Point(1, 6),
new geometry.Point(6, 6)
]);
var line = new geometry.Line(
new geometry.Point(0, 1),
new geometry.Point(7, 1));
expect(poly.intersects(line)).to.equal(true);
});
it("check line to intersects with complex polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(6, 1),
new geometry.Point(1, 6),
new geometry.Point(6, 6)
]);
var line = new geometry.Line(
new geometry.Point(0, 6),
new geometry.Point(7, 6));
expect(poly.intersects(line)).to.equal(true);
});
it("check line to not intersects with polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var line = new geometry.Line(
new geometry.Point(3, 1),
new geometry.Point(3, 0));
expect(poly.intersects(line)).to.equal(false);
});
it("check polygon to intersects with polygon", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(3, 3),
new geometry.Point(5, 0),
new geometry.Point(6, 1)
]);
expect(poly1.intersects(poly2)).to.equal(true);
});
it("check polygon to intersects with polygon", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(-2, 2),
new geometry.Point(5, 0),
new geometry.Point(6, 1)
]);
expect(poly1.intersects(poly2)).to.equal(true);
});
it("check polygon to contain another polygon", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(7, 7),
new geometry.Point(0, 7)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(5, 5),
new geometry.Point(0, 5)
]);
expect(poly1.intersects(poly2)).to.equal(true);
});
it("check polygon to not intersects with polygon", function(){
var poly1 = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var poly2 = new geometry.Polygon([
new geometry.Point(3, 0),
new geometry.Point(5, 0),
new geometry.Point(6, 1)
]);
expect(poly1.intersects(poly2)).to.equal(false);
});
it("check rectangle to intersects with polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var rect = new geometry.Rectangle(0, 3, 4, 1);
expect(poly.intersects(rect)).to.equal(true);
});
it("check rectangle to not intersects with polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(6, 4),
new geometry.Point(0, 4)
]);
var rect = new geometry.Rectangle(3, -1, 2, 2);
expect(poly.intersects(rect)).to.equal(false);
});
it("check rectangle to not intersects with empty polygon", function(){
var poly = new geometry.Polygon([]);
var rect = new geometry.Rectangle(0, 0, 2, 2);
expect(poly.intersects(rect)).to.equal(false);
});
});
describe("getBoundingRectangle()", function(){
it("bounding rectangle of empty polygon", function(){
var poly = new geometry.Polygon([]);
var rect = poly.getBoundingRectangle();
expect(rect).to.equal(null);
});
it("bounding rectangle of polygon with only one point", function(){
var poly = new geometry.Polygon([new geometry.Point(4, 5)]);
var rect = poly.getBoundingRectangle();
expect(rect.x).to.equal(4);
expect(rect.y).to.equal(5);
expect(rect.width).to.equal(1);
expect(rect.height).to.equal(1);
expect(rect.contains(poly)).to.equal(true);
});
it("bounding rectangle of rectangle-like polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(0, 0),
new geometry.Point(10, 0),
new geometry.Point(10, 10),
new geometry.Point(0, 10)
]);
var rect = poly.getBoundingRectangle();
expect(rect.x).to.equal(0);
expect(rect.y).to.equal(0);
expect(rect.width).to.equal(10);
expect(rect.height).to.equal(10);
expect(rect.contains(poly)).to.equal(true);
expect(poly.contains(rect)).to.equal(true);
});
it("bounding rectangle of polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(1, 1),
new geometry.Point(8, 0),
new geometry.Point(7, 4),
new geometry.Point(4, 5),
new geometry.Point(2, 3)
]);
var rect = poly.getBoundingRectangle();
expect(rect.x).to.equal(1);
expect(rect.y).to.equal(0);
expect(rect.width).to.equal(7);
expect(rect.height).to.equal(5);
expect(rect.contains(poly)).to.equal(true);
});
});
describe("clip()", function(){
it("clips line inside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(2, 4),
new geometry.Point(6, 7)]);
var line = new geometry.Line(new geometry.Point(4, 1), new geometry.Point(4, 7));
var result = poly.clip(line);
expect(result.length).to.equal(2);
expect(result[0].x).to.equal(4);
expect(result[0].y).to.equal(2);
expect(result[1].x).to.equal(4);
expect(result[1].y).to.equal(6);
});
it("clips line inside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(2, 4),
new geometry.Point(6, 7)]);
var line = new geometry.Line(new geometry.Point(1, 5), new geometry.Point(8, 5));
var result = poly.clip(line);
expect(result.length).to.equal(2);
expect(result[0].x).to.equal(6);
expect(result[0].y).to.equal(5);
expect(result[1].x).to.equal(3);
expect(result[1].y).to.equal(5);
});
it("clips line inside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(2, 1),
new geometry.Point(2, 7),
new geometry.Point(7, 9),
new geometry.Point(9, 1),
new geometry.Point(5, 5)]);
var line = new geometry.Line(new geometry.Point(1, 3), new geometry.Point(10, 3));
var result = poly.clip(line);
expect(result.length).to.equal(4);
expect(result[0].x).to.equal(2);
expect(result[0].y).to.equal(3);
expect(result[1].x).to.equal(4);
expect(result[1].y).to.equal(3);
expect(result[2].x).to.equal(7);
expect(result[2].y).to.equal(3);
expect(result[3].x).to.equal(9);
expect(result[3].y).to.equal(3);
});
it("clips line inside polygon (one point is inside of polygon)", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(2, 4),
new geometry.Point(6, 7)]);
var line = new geometry.Line(new geometry.Point(1, 5), new geometry.Point(5, 5));
var result = poly.clip(line);
expect(result.length).to.equal(2);
expect(result[0].x).to.equal(5);
expect(result[0].y).to.equal(5);
expect(result[1].x).to.equal(3);
expect(result[1].y).to.equal(5);
});
it("clips line fully inside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(2, 4),
new geometry.Point(6, 7)]);
var line = new geometry.Line(new geometry.Point(4, 3), new geometry.Point(5, 5));
var result = poly.clip(line);
expect(result.length).to.equal(2);
expect(result[0].x).to.equal(4);
expect(result[0].y).to.equal(3);
expect(result[1].x).to.equal(5);
expect(result[1].y).to.equal(5);
});
it("tries to clip line outside of polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(2, 4),
new geometry.Point(6, 7)]);
var line = new geometry.Line(new geometry.Point(1, 1), new geometry.Point(1, 5));
var result = poly.clip(line);
expect(result.length).to.equal(0);
});
it("tries to clip line outside of polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(2, 4),
new geometry.Point(6, 7)]);
var line = new geometry.Line(new geometry.Point(1, -1), new geometry.Point(7, 0));
var result = poly.clip(line);
expect(result.length).to.equal(0);
});
/*it("clips one polygon against another polygon", function(){
// TODO
});*/
it("clips rectangle inside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(3, 1),
new geometry.Point(1, 5),
new geometry.Point(6, 6)]);
var rect = new geometry.Rectangle(1, 3, 5, 2);
var result = poly.clip(rect);
expect(result.length).to.equal(4);
expect(result[0].x).to.equal(4);
expect(result[0].y).to.equal(3);
expect(result[1].x).to.equal(2);
expect(result[1].y).to.equal(3);
expect(result[2].x).to.equal(1);
expect(result[2].y).to.equal(5);
expect(result[3].x).to.equal(5);
expect(result[3].y).to.equal(5);
});
it("clips rectangle inside polygon (only one rect vertex inside polygon)", function(){
var poly = new geometry.Polygon([
new geometry.Point(3, 1),
new geometry.Point(1, 5),
new geometry.Point(6, 6)]);
var rect = new geometry.Rectangle(4, 4, 5, 4);
var result = poly.clip(rect);
expect(result.length).to.equal(3);
expect(result[0].x).to.equal(4);
expect(result[0].y).to.equal(4);
expect(result[1].x).to.equal(4);
expect(result[1].y).to.equal(5);
expect(result[2].x).to.equal(6);
expect(result[2].y).to.equal(6);
});
it("clips rectangle inside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(3, 2),
new geometry.Point(6, 5),
new geometry.Point(2, 7),
new geometry.Point(7, 7),
new geometry.Point(8, 2)]);
var rect = new geometry.Rectangle(4, 1, 3, 6);
var result = poly.clip(rect);
expect(result.length).to.equal(7);
expect(result[0].x).to.equal(7);
expect(result[0].y).to.equal(7);
expect(result[1].x).to.equal(7);
expect(result[1].y).to.equal(2);
expect(result[2].x).to.equal(4);
expect(result[2].y).to.equal(2);
expect(result[3].x).to.equal(4);
expect(result[3].y).to.equal(3);
expect(result[4].x).to.equal(6);
expect(result[4].y).to.equal(5);
expect(result[5].x).to.equal(4);
expect(result[5].y).to.equal(6);
expect(result[6].x).to.equal(4);
expect(result[6].y).to.equal(7);
});
it("clips rectangle fully inside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(1, 6),
new geometry.Point(7, 6)]);
var rect = new geometry.Rectangle(3, 4, 3, 1);
var result = poly.clip(rect);
expect(result.length).to.equal(4);
expect(result[0].x).to.equal(6);
expect(result[0].y).to.equal(4);
expect(result[1].x).to.equal(3);
expect(result[1].y).to.equal(4);
expect(result[2].x).to.equal(3);
expect(result[2].y).to.equal(5);
expect(result[3].x).to.equal(6);
expect(result[3].y).to.equal(5);
});
it("tries to clip rectangle outside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(1, 6),
new geometry.Point(7, 6)]);
var rect = new geometry.Rectangle(-1, 1, 2, 1);
var result = poly.clip(rect);
expect(result.length).to.equal(0);
});
it("tries to clip rectangle outside polygon", function(){
var poly = new geometry.Polygon([
new geometry.Point(5, 1),
new geometry.Point(1, 6),
new geometry.Point(7, 6)]);
var rect = new geometry.Rectangle(7, 1, 3, 2);
var result = poly.clip(rect);
expect(result.length).to.equal(0);
});
});
});
|
// -------------------------------------------------------------------------- //
// ------------------------------ Allow/deny -------------------------------- //
// -------------------------------------------------------------------------- //
/**
* Wether or not the broadcast is allowed
* @param {Object} data Data of the message
* @param {Socket} from From socket
*/
Streamy.BroadCasts.allow = function(data, from) {
return true;
};
// -------------------------------------------------------------------------- //
// -------------------------------- Handlers -------------------------------- //
// -------------------------------------------------------------------------- //
/**
* Attach the broadcast message handler
* @param {Object} data Data object
* @param {Socket} from Socket emitter
*/
Streamy.on('__broadcast__', function(data, from) {
// Check for sanity
if(!data.__msg || !data.__data)
return;
// Check if the server allows this direct message
if(!Streamy.BroadCasts.allow(data, from))
return;
// Attach the sender ID to the inner data
data.__data.__from = Streamy.id(from);
data.__data.__fromUserId = from._meteorSession.userId;
// And then emit the message
Streamy.broadcast(data.__msg, data.__data, data.__except);
});
// -------------------------------------------------------------------------- //
// ------------------------------- Overrides -------------------------------- //
// -------------------------------------------------------------------------- //
Streamy.broadcast = function(message, data, except) {
if(!_.isArray(except))
except = [except];
_.each(Streamy.sockets(), function(sock) {
if(except.indexOf(Streamy.id(sock)) !== -1)
return;
Streamy.emit(message, data, sock);
});
};
|
search_result['1577']=["topic_00000000000003CA_events--.html","tlece_PostVacancyStageQuestion Events",""];
|
import { INITIAL_STATE } from './index';
import { INCREASE_GENERATION } from '../actions/index';
import { CLEAR_GENERATION } from '../actions/index';
export default function(state = INITIAL_STATE.generation, action) {
switch(action.type) {
case INCREASE_GENERATION:
return state + 1;
case CLEAR_GENERATION:
return 0;
}
return state;
}
|
function setFaq(lang) {
var faqText = $(".faq-text-"+lang.toLowerCase());
var faqDisplay = $(".faq-text.lang-"+lang.toLowerCase());
faqText.children().find("b").each(function() {
var question = $(this).text()
var answer = $(this).parent().next().text();
if (answer.length > 5) {
html = "<div class='faq-div'><p class='faq-question'>" + question + "</p><p class='faq-answer'>" + answer + "</p></div>"
faqDisplay.append(html)
}
});
}
$(function() {
setFaq("TW");
setFaq("EN");
});
|
var Backbone = require('backbone');
var CommentModel = require('../model/comment');
module.exports = Backbone.Collection.extend({
model: CommentModel,
url: function(){
return "http://blogmv-api.appspot.com/api/articles/"+this.article.id+"/comments/"
},
initialize: function(models, options){
this.article = options.article
},
postNewComment: function(model){
this.create(model);
}
});
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from './reducers'
import 'bootstrap/dist/css/bootstrap.min.css'
import App from './components/App.jsx'
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('miew-react-app')
)
|
'use strict';
// Articles controller
angular.module('core').controller('MinController', ['$scope', 'Authentication','$location',
function ($scope, Authentication,$location) {
$scope.authentication = Authentication;
// $location.hash('top');
//Dummy data...
$scope.ministries = [
{
name: 'Mens Minstry',
pic: 'eric.jpg',
details: 'daslkdja ljdaslkd aksdha lsdalksdjaoisuoiusdifu lsidfklsd fds flksdhjfjsdhfksu dfsdjfjsdf ks dhfoewus ndfsdfliejfl wefli uslkdfh jshdfskdhf uwhfskjdhf skjdfweuhfsdhfks',
vision:'BWhahahahahahahahah'
}
];
/**
* Function that takes a specific ministry and updates the popup modal information
* @param min (ministry details)
*/
$scope.selectMin = function(min){
$scope.selectedMin = min;
}
/**
* Functions to control search filters
*/
$scope.affix = false;
$scope.filterSections = [''];
$scope.filterSearch = function (search) {
$scope.$parent.searchText = search;
};
}
]);
|
module.exports = {
extends: 'airbnb',
rules: {
'import/no-extraneous-dependencies': 'off',
},
};
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by CodeZu.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
var Client = require('../../../../../client'), constants = Client.constants;
module.exports = Client.sub({
getLocationInventories: Client.method({
method: constants.verbs.GET,
url: '{+tenantPod}api/commerce/catalog/admin/products/{ProductCode}/LocationInventory/?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&responseFields={responseFields}'
}),
getLocationInventory: Client.method({
method: constants.verbs.GET,
url: '{+tenantPod}api/commerce/catalog/admin/products/{ProductCode}/LocationInventory/{LocationCode}?responseFields={responseFields}'
}),
addLocationInventory: Client.method({
method: constants.verbs.POST,
url: '{+tenantPod}api/commerce/catalog/admin/products/{ProductCode}/LocationInventory?performUpserts={performUpserts}'
}),
updateLocationInventory: Client.method({
method: constants.verbs.PUT,
url: '{+tenantPod}api/commerce/catalog/admin/products/{ProductCode}/LocationInventory'
}),
deleteLocationInventory: Client.method({
method: constants.verbs.DELETE,
url: '{+tenantPod}api/commerce/catalog/admin/products/{ProductCode}/LocationInventory/{LocationCode}'
})
});
|
var path = require('path');
var express = require('express');
var app = express();
var PORT = process.env.PORT || 4541
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var webpack = require('webpack');
var config = require('./webpack.config-dev');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}))
app.use(webpackHotMiddleware(compiler, {
stats: {
colors: true
}
}))
let publicPath = path.join(__dirname, 'build')
app.use(express.static(publicPath))
app.get('/', function (request, response) {
response.sendFile('index-dev.html', {
root: publicPath
})
})
app.listen(PORT, function (error) {
if (error) {
console.error(error);
} else {
console.info("==> Listening on port %s. Visit http://localhost:%s/ in your browser.", PORT, PORT);
}
});
|
if (sessionStorage.FontsLoaded) {
document.documentElement.className += ' fonts-loaded';
}
|
var Flags = {
stateChange: 'statechange',
systemReady: 'systemready',
loadSystem: 'loadsystem',
updateComponentInfo: 'updatecomponentinfo'
}
|
const util = require('util');
var EventEmitter = require('events').EventEmitter;
var debug = require('debug')('state');
var StateManager = function(initial) {
EventEmitter.call(this);
var _state = null;
this.set = (new_state) => {
debug("state_change", _state, new_state);
this.emit("state_change", _state, new_state);
_state = new_state;
}
this.get = () => {
return _state;
}
this.is = (other_state) => {
return _state == other_state;
}
this.set(initial);
}
util.inherits(StateManager, EventEmitter);
module.exports = StateManager;
|
var mongoose = require('mongoose');
var thing;
var thingSchema = mongoose.Schema({
thing_id: String,
owner: String,
name: String,
created: { type: Date, default: Date.now },
config: mongoose.Schema.Types.Mixed,
status: mongoose.Schema.Types.Mixed
});
thing = module.exports = mongoose.model('thing', thingSchema);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _ramda = require('ramda');
var getDomain = (0, _ramda.pipe)((0, _ramda.split)('@'), _ramda.last);
exports.default = getDomain;
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsaXR5L2dldC1kb21haW4uanMiXSwibmFtZXMiOlsiZ2V0RG9tYWluIl0sIm1hcHBpbmdzIjoiOzs7Ozs7QUFBQTs7QUFFQSxJQUFNQSxZQUFZLGlCQUNkLGtCQUFNLEdBQU4sQ0FEYyxjQUFsQjs7a0JBS2VBLFMiLCJmaWxlIjoiZ2V0LWRvbWFpbi5qcyIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IHBpcGUsIHNwbGl0LCBsYXN0IH0gZnJvbSAncmFtZGEnO1xuXG5jb25zdCBnZXREb21haW4gPSBwaXBlKFxuICAgIHNwbGl0KCdAJyksXG4gICAgbGFzdFxuKTtcblxuZXhwb3J0IGRlZmF1bHQgZ2V0RG9tYWluO1xuIl19
|
import gravity from "lib/loaders/gravity"
import Artwork from "./artwork"
import { GraphQLList, GraphQLString } from "graphql"
const Artworks = {
type: new GraphQLList(Artwork.type),
description: "A list of Artworks",
args: {
ids: {
type: new GraphQLList(GraphQLString),
},
},
resolve: (root, options) => gravity("artworks", options),
}
export default Artworks
|
'use strict';
exports.keys = 'test key';
exports.cookies = {
sameSite: 'lax',
};
|
/*
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertDataProperty
} = Assert;
// 15.11.1.1: "message" property no longer non-enumerable
// https://bugs.ecmascript.org/show_bug.cgi?id=1404
const constructors = [
Error, EvalError, RangeError, ReferenceError, SyntaxError, TypeError, URIError
];
for (let ctor of constructors) {
let message = "should-be-non-enumerable";
assertDataProperty(new ctor(message), "message", {value: message, writable: true, enumerable: false, configurable: true});
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
angular.module('eappApp').component('otiprixStep', {
templateUrl: 'templates/components/otiprixStep.html',
controller : function($scope)
{
var ctrl = this;
ctrl.$onInit = function()
{
$scope.displayBorder = ctrl.displayBorder;
$scope.caption = ctrl.caption;
};
},
bindings:
{
index: '@',
image : '@',
caption: '<',
displayBorder: '<'
}
});
|
/*global define*/
define(
['marionette','vent','tpl!templates/wizard.tmpl','models/Wizard'],
function (Marionette, vent, tmpl, Wizard) {
'use strict';
return Marionette.ItemView.extend({
template: tmpl,
className: 'tr-container container',
events: {
'click .mongo-toggle' : 'toggleMongo',
'click .login-toggle' : 'toggleLogin',
'change [name]' : 'updateModel',
'submit #setup-form' : 'verify'
},
initialize: function() {
this.model = new Wizard();
Backbone.Validation.bind(this);
},
onShow: function() {
$('body').addClass('wizard');
},
onClose: function() {
$('body').removeClass('wizard');
},
toggleMongo: function(ev) {
this.model.set('mongo', $(ev.currentTarget).text());
$(this.el).find('[name="mongo"]').val($(ev.currentTarget).text());
this.render();
},
toggleLogin: function(ev) {
this.model.set('loginmechanism', $(ev.currentTarget).text());
$(this.el).find('[name="loginmechanism"]').val($(ev.currentTarget).text());
this.render();
},
updateModel: function(ev) {
this.model.set($(ev.currentTarget).attr('name'), $(ev.currentTarget).val());
this.model.checkPasswords();
this.doValidate();
},
doValidate: function() {
this.model.set('valid', this.model.validate());
this.render();
},
verify: function() {
// Verify the form is filled out correctly.
if (!this.model.isValid()) {
this.doValidate();
console.log('Failed validation');
console.log(this.model.get('valid'));
return false;
}
vent.trigger('route:remove', 'setup');
console.log('good!');
$(this.el).find('#setup-form').submit();
}
});
}
);
|
/* The MIT License
Copyright (c) 2008 Genome Research Ltd (GRL).
2010 Broad Institute
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Author: Heng Li <lh3@sanger.ac.uk>
// Modified/adapted by: Neal Conrad <nconrad@mcs.anl.gov>
/*
A phylogenetic tree is parsed into the following Java-like structure:
class Node {
Node parent; // pointer to the parent node; null if root
Node[] child; // array of pointers to child nodes
String name; // name of the current node
double d; // distance to the parent node
bool hl; // if the node needs to be highlighted
bool hidden; // if the node and all its desendants are collapsed
};
class Tree {
Node[] node; // list of nodes in the finishing order (the leftmost leaf is the first and the root the last)
int error; // errors in parsing: 0x1=missing left parenthesis; 0x2=missing right; 0x4=unpaired brackets
int n_tips; // number of tips/leaves in the tree
};
The minimal code for plotting/editing a tree in the Newick format is:
<head><!--[if IE]><script src="excanvas.js"></script><![endif]-->
<script language="JavaScript" src="knhx.js"></script></head>
<body onLoad="knhx_init('canvas', 'nhx');">
<textarea id="nhx" rows="20" cols="120" style="font:11px monospace"></textarea>
<canvas id="canvas" width="800" height="100" style="border:1px solid"></canvas>
</body>
*/
/********************************************
****** The New Hampshire format parser *****
********************************************/
/*global
define, console
*/
/*jslint
browser: true,
white: true,
bitwise: true
*/
define(['canvastext', 'popit'], function (CanvasTextFunctions, popmenu) {
'use strict';
function kn_new_node() { // private method
return {parent: null, child: [], name: "", meta: "", d: -1.0, hl: false, hidden: false};
}
function kn_add_node(str, l, tree, x) // private method
{
var r,
beg,
end = 0,
z,
i;
z = kn_new_node();
for (i = l, beg = l; i < str.length && str.charAt(i) !== ',' && str.charAt(i) !== ')'; ++i) {
var c = str.charAt(i);
if (c === '[') {
var meta_beg = i;
if (end === 0) {
end = i;
}
do {
++i;
} while (i < str.length && str.charAt(i) !== ']');
if (i === str.length) {
tree.error |= 4;
break;
}
z.meta = str.substr(meta_beg, i - meta_beg + 1);
} else if (c === ':') {
if (end === 0) {
end = i;
}
var j;
for (j = ++i; i < str.length; ++i) {
var cc = str.charAt(i);
if ((cc < '0' || cc > '9') && cc !== 'e' && cc !== 'E' && cc !== '+' && cc !== '-' && cc !== '.') {
break;
}
}
z.d = parseFloat(str.substr(j, i - j));
--i;
} else if (c < '!' && c > '~' && end === 0) {
end = i;
}
}
if (end === 0) {
end = i;
}
if (end > beg) {
z.name = str.substr(beg, end - beg);
}
tree.node.push(z);
return i;
}
/* Parse a string in the New Hampshire format and return a pointer to the tree. */
function kn_parse(str)
{
var stack = new Array();
var tree = {};
tree.error = tree.n_tips = 0;
tree.node = [];
var l;
for (l = 0; l < str.length; l += 0) {
while (l < str.length && (str.charAt(l) < '!' || str.charAt(l) > '~')) {
++l;
}
if (l === str.length) {
break;
}
var c = str.charAt(l);
if (c === ',') {
++l;
} else if (c === '(') {
stack.push(-1);
++l;
} else if (c === ')') {
var x, m, i;
x = tree.node.length;
for (i = stack.length - 1; i >= 0; --i) {
if (stack[i] < 0) {
break;
}
}
if (i < 0) {
tree.error |= 1;
break;
}
m = stack.length - 1 - i;
l = kn_add_node(str, l + 1, tree, m);
for (i = stack.length - 1, m = m - 1; m >= 0; --m, --i) {
tree.node[x].child[m] = tree.node[stack[i]];
tree.node[stack[i]].parent = tree.node[x];
}
stack.length = i;
stack.push(x);
} else {
++tree.n_tips;
stack.push(tree.node.length);
l = kn_add_node(str, l, tree, 0);
}
}
if (stack.length > 1) {
tree.error |= 2;
}
tree.root = tree.node[tree.node.length - 1];
return tree;
}
/*
***** Output a tree in text *****
*/
/* convert a tree to the New Hampshire string */
function kn_write_nh(tree)
{
// calculate the depth of each node
tree.node[tree.node.length - 1].depth = 0;
var i, j;
for (i = tree.node.length - 2; i >= 0; --i) {
var p = tree.node[i];
p.depth = p.parent.depth + 1;
}
// generate the string
var str = '';
var cur_depth = 0, is_first = 1;
for (i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
var n_bra = p.depth - cur_depth;
if (n_bra > 0) {
if (is_first) {
is_first = 0;
} else {
str += ",\n";
}
for (j = 0; j < n_bra; ++j) {
str += "(";
}
} else if (n_bra < 0) {
str += "\n)";
} else {
str += ",\n";
}
if (p.name) {
str += String(p.name);
}
if (p.d >= 0.0) {
str += ":" + p.d;
}
if (p.meta) {
str += p.meta;
}
cur_depth = p.depth;
}
str += "\n";
return str;
}
/* print the tree topology (for debugging only) */
function kn_check_tree(tree)
{
document.write("<table border=1><tr><th>name<th>id<th>dist<th>x<th>y</tr>");
var i;
for (i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
document.write("<tr>" + "<td>" + p.name + "<td>" + i + "<td>" + p.d
+ "<td>" + p.x + "<td>" + p.y + "</tr>");
}
document.write("</table>");
}
/*
****** Functions for manipulating a tree *****
*/
/* Expand the tree into an array in the finishing order */
function kn_expand_node(root)
{
var node, stack;
node = [];
stack = [];
stack.push({p: root, i: 0});
for (; ; ) {
while (stack[stack.length - 1].i !== stack[stack.length - 1].p.child.length && !stack[stack.length - 1].p.hidden) {
var q = stack[stack.length - 1];
stack.push({p: q.p.child[q.i], i: 0});
}
node.push(stack.pop().p);
if (stack.length > 0) {
++stack[stack.length - 1].i;
} else {
break;
}
}
return node;
}
/* Count the number of leaves */
function kn_count_tips(tree)
{
tree.n_tips = 0;
var i;
for (i = 0; i < tree.node.length; ++i) {
if (tree.node[i].child.length === 0 || tree.node[i].hidden) {
++tree.n_tips;
}
}
return tree.n_tips;
}
/* Highlight: set node.hl for leaves matching "pattern" */
function kn_search_leaf(tree, pattern)
{
var i, p;
for (i = 0; i < tree.node.length; ++i) {
p = tree.node[i];
if (p.child.length === 0) {
p.hl = (pattern && pattern !== "" && p.name.match(pattern)) ? true : false;
}
}
}
/* Remove: delete a node and all its descendants */
function kn_remove_node(tree, node)
{
var root = tree.node[tree.node.length - 1];
if (node === root)
return;
var z = kn_new_node();
z.child.push(root);
root.parent = z;
var p = node.parent, i;
if (p.child.length === 2) { // then p will be removed
var q, r = p.parent;
i = (p.child[0] === node) ? 0 : 1;
q = p.child[1 - i]; // the other child
q.d += p.d;
q.parent = r;
for (i = 0; i < r.child.length; ++i)
if (r.child[i] === p)
break;
r.child[i] = q;
p.parent = null;
} else {
var j, k;
for (i = 0; i < p.child.length; ++i)
if (p.child[i] === node)
break;
for (j = k = 0; j < p.child.length; ++j) {
p.node[k] = p.node[j];
if (j !== i)
++k;
}
--p.child.length;
}
root = z.child[0];
root.parent = null;
return root;
}
/* Move: prune the subtree descending from p and regragh it to the edge between q and its parent */
function kn_move_node(tree, p, q)
{
var root = tree.node[tree.node.length - 1];
if (p === root)
return null; // p cannot be root
for (var r = q; r.parent; r = r.parent)
if (r === p)
return null; // p is an ancestor of q. We cannot move in this case.
root = kn_remove_node(tree, p);
var z = kn_new_node(); // a fake root
z.child.push(root);
root.parent = z;
var i, r = q.parent;
for (i = 0; i < r.child.length; ++i)
if (r.child[i] === q)
break;
var s = kn_new_node(); // a new node
s.parent = r;
r.child[i] = s;
if (q.d >= 0.0) {
s.d = q.d / 2.0;
q.d /= 2.0;
}
s.child.push(p);
p.parent = s;
s.child.push(q);
q.parent = s;
root = z.child[0];
root.parent = null;
return root;
}
/* Reroot: put the root in the middle of node and its parent */
function kn_reroot(root, node, dist)
{
var i, d, tmp;
var p, q, r, s, new_root;
if (node === root)
return root;
if (dist < 0.0 || dist > node.d)
dist = node.d / 2.0;
tmp = node.d;
/* p: the central multi-parent node
* q: the new parent, previous a child of p
* r: old parent
* i: previous position of q in p
* d: previous distance p->d
*/
q = new_root = kn_new_node();
q.child[0] = node;
q.child[0].d = dist;
p = node.parent;
q.child[0].parent = q;
for (i = 0; i < p.child.length; ++i)
if (p.child[i] === node)
break;
q.child[1] = p;
d = p.d;
p.d = tmp - dist;
r = p.parent;
p.parent = q;
while (r !== null) {
s = r.parent; /* store r's parent */
p.child[i] = r; /* change r to p's child */
for (i = 0; i < r.child.length; ++i) /* update i */
if (r.child[i] === p)
break;
r.parent = p; /* update r's parent */
tmp = r.d;
r.d = d;
d = tmp; /* swap r->d and d, i.e. update r->d */
q = p;
p = r;
r = s; /* update p, q and r */
}
/* now p is the root node */
if (p.child.length === 2) { /* remove p and link the other child of p to q */
r = p.child[1 - i]; /* get the other child */
for (i = 0; i < q.child.length; ++i) /* the position of p in q */
if (q.child[i] === p)
break;
r.d += p.d;
r.parent = q;
q.child[i] = r; /* link r to q */
} else { /* remove one child in p */
for (j = k = 0; j < p.child.length; ++j) {
p.child[k] = p.child[j];
if (j !== i)
++k;
}
--p.child.length;
}
return new_root;
}
function kn_multifurcate(p)
{
var i, par, idx, tmp, old_length;
if (p.child.length === 0 || !p.parent)
return;
par = p.parent;
for (i = 0; i < par.child.length; ++i)
if (par.child[i] === p)
break;
idx = i;
tmp = par.child.length - idx - 1;
old_length = par.child.length;
par.child.length += p.child.length - 1;
for (i = 0; i < tmp; ++i)
par.child[par.child.length - 1 - i] = par.child[old_length - 1 - i];
for (i = 0; i < p.child.length; ++i) {
p.child[i].parent = par;
if (p.child[i].d >= 0 && p.d >= 0)
p.child[i].d += p.d;
par.child[i + idx] = p.child[i];
}
}
function kn_reorder(root)
{
sort_leaf = function (a, b) {
if (a.depth < b.depth)
return 1;
if (a.depth > b.depth)
return -1;
return String(a.name) < String(b.name) ? -1 : String(a.name) > String(b.name) ? 1 : 0;
};
sort_weight = function (a, b) {
return a.weight / a.n_tips - b.weight / b.n_tips;
};
var x = new Array();
var i, node = kn_expand_node(root);
// get depth
node[node.length - 1].depth = 0;
for (i = node.length - 2; i >= 0; --i) {
var q = node[i];
q.depth = q.parent.depth + 1;
if (q.child.length === 0)
x.push(q);
}
// set weight for leaves
x.sort(sort_leaf);
for (i = 0; i < x.length; ++i)
x[i].weight = i, x[i].n_tips = 1;
// set weight for internal nodes
for (i = 0; i < node.length; ++i) {
var q = node[i];
if (q.child.length) { // internal
var j, n = 0, w = 0;
for (j = 0; j < q.child.length; ++j) {
n += q.child[j].n_tips;
w += q.child[j].weight;
}
q.n_tips = n;
q.weight = w;
}
}
// swap children
for (i = 0; i < node.length; ++i)
if (node[i].child.length >= 2)
node[i].child.sort(sort_weight);
}
/*
***** Functions for plotting a tree *****
*/
/* Calculate the coordinate of each node */
function kn_calxy(tree, is_real)
{
var i, j, scale;
// calculate y
scale = tree.n_tips - 1;
for (i = j = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
p.y = (p.child.length && !p.hidden) ? (p.child[0].y + p.child[p.child.length - 1].y) / 2.0 : (j++) / scale;
if (p.child.length === 0)
p.miny = p.maxy = p.y;
else
p.miny = p.child[0].miny, p.maxy = p.child[p.child.length - 1].maxy;
}
// calculate x
if (is_real) { // use branch length
var root = tree.node[tree.node.length - 1];
scale = root.x = (root.d >= 0.0) ? root.d : 0.0;
for (i = tree.node.length - 2; i >= 0; --i) {
var p = tree.node[i];
p.x = p.parent.x + (p.d >= 0.0 ? p.d : 0.0);
if (p.x > scale)
scale = p.x;
}
if (scale == 0.0) {
is_real = false;
}
}
if (!is_real) { // no branch length
scale = tree.node[tree.node.length - 1].x = 1.0;
for (i = tree.node.length - 2; i >= 0; --i) {
var p = tree.node[i];
p.x = p.parent.x + 1.0;
if (p.x > scale)
scale = p.x;
}
for (i = 0; i < tree.node.length - 1; ++i)
if (tree.node[i].child.length === 0)
tree.node[i].x = scale;
}
// rescale x
for (i = 0; i < tree.node.length; ++i)
tree.node[i].x /= scale;
return is_real;
}
function kn_get_node(tree, conf, x, y)
{
if (conf.is_circular) {
for (var i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
var tmp_x = Math.floor(conf.width / 2 + p.x * conf.real_r * Math.cos(p.y * conf.full_arc) + .999);
var tmp_y = Math.floor(conf.height / 2 + p.x * conf.real_r * Math.sin(p.y * conf.full_arc) + .999);
var tmp_l = 2;
if (x >= tmp_x - tmp_l && x <= tmp_x + tmp_l && y >= tmp_y - tmp_l && y <= tmp_y + tmp_l)
return i;
}
} else {
for (var i = 0; i < tree.node.length; ++i) {
var tmp_x = tree.node[i].x * conf.real_x + conf.shift_x;
var tmp_y = tree.node[i].y * conf.real_y + conf.shift_y;
var tmp_l = conf.box_width * .6;
if (x >= tmp_x - tmp_l && x <= tmp_x + tmp_l && y >= tmp_y - tmp_l && y <= tmp_y + tmp_l)
return i;
}
}
return tree.node.length;
}
/* Initialize parameters for tree plotting */
function kn_init_conf()
{
var conf = new Object();
conf.c_box = new Array();
conf.width = 1000;
conf.height = 600;
conf.xmargin = 20;
conf.ymargin = 20;
conf.fontsize = 8;
conf.c_ext = "rgb(0,0,0)";
conf.c_int = "rgb(255,0,0)";
conf.c_line = '#444'; //"rgb(0,20,200)";
conf.c_node = '#666'; //"rgb(20,20,20)";
conf.c_active_node = "rgb(255,128,0)";
conf.c_hl = "rgb(255, 180, 180)";
conf.c_hidden = "rgb(0,200,0)";
conf.c_regex = "rgb(0,128,0)";
// conf.regex = ':S=([^:\\]]+)';
conf.regex = ':B=([^:\\]]+)';
conf.xskip = 3.0;
conf.yskip = 14;
conf.box_width = 6.0;
conf.old_nh = null;
conf.is_real = true;
conf.is_circular = false;
conf.show_dup = true;
conf.runtime = 0;
return conf;
}
/* Plot the tree in the "canvas". Both node.x and node.y MUST BE precomputed by kn_calxy */
function kn_plot_core(canvas, tree, conf)
{
if (conf.is_circular) {
kn_plot_core_O(canvas, tree, conf);
return;
}
var ctx = canvas.getContext("2d");
// ctx.font = "10px Sans";
ctx.strokeStyle = ctx.fillStyle = "white";
ctx.fillRect(0, 0, conf.width, conf.height);
CanvasTextFunctions.enable(ctx);
// get maximum name length
var max_namelen, i;
for (i = 0, max_namelen = 0; i < tree.node.length; ++i) {
if (tree.node[i].child.length)
continue;
var tmp = ctx.measureText(conf.font, conf.fontsize, tree.node[i].name);
if (tmp > max_namelen)
max_namelen = tmp;
}
// set transformation
var real_x, real_y, shift_x, shift_y;
conf.real_x = real_x = conf.width - 2 * conf.xmargin - max_namelen;
conf.real_y = real_y = conf.height - 2 * conf.ymargin - conf.fontsize;
conf.shift_x = shift_x = conf.xmargin;
conf.shift_y = shift_y = conf.ymargin + conf.fontsize / 2;
// plot background boxes
for (i = tree.node.length - 1; i >= 0; --i) {
if (tree.node[i].box) {
var p = tree.node[i];
var x = p.x * real_x + shift_x - conf.box_width / 2;
ctx.strokeStyle = ctx.fillStyle = tree.node[i].box;
ctx.fillRect(x, p.miny * real_y + shift_y - conf.yskip / 2,
conf.width - conf.xmargin - x, (p.maxy - p.miny) * real_y + conf.yskip);
}
}
// leaf name
ctx.strokeStyle = conf.c_ext;
ctx.fillStyle = conf.c_hl;
for (i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
if (p.child.length === 0 || p.hidden) {
if (p.hl) {
var tmp = ctx.measureText(conf.font, conf.fontsize, tree.node[i].name);
ctx.fillRect(p.x * real_x + conf.xskip * 2 + shift_x, p.y * real_y + shift_y - conf.fontsize * .8,
tmp, conf.fontsize * 1.5);
}
// ctx.fillText(p.name, p.x * real_x + conf.xskip * 2 + shift_x, p.y * real_y + shift_y + conf.fontsize / 3);
ctx.drawText(conf.font, conf.fontsize, p.x * real_x + conf.xskip * 2 + shift_x,
p.y * real_y + shift_y + conf.fontsize / 3, p.name);
}
}
// internal name
ctx.strokeStyle = conf.c_int;
for (i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
if (p.child.length && p.name.length > 0 && !p.hidden) {
var l = ctx.measureText(conf.font, conf.fontsize, p.name);
ctx.drawText(conf.font, conf.fontsize, p.x * real_x - conf.xskip + shift_x - l,
p.y * real_y + shift_y - conf.fontsize / 3, p.name);
}
}
// internal name 2
if (conf.regex && conf.regex.indexOf('(') >= 0) {
var re = new RegExp(conf.regex);
if (re) {
ctx.strokeStyle = conf.c_regex;
for (i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
if (p.child.length && p.meta) {
var m = re.exec(p.meta);
if (m.length > 1) {
var l = ctx.measureText(conf.font, conf.fontsize, m[1]);
ctx.drawText(conf.font, conf.fontsize, p.x * real_x - conf.xskip + shift_x - l,
p.y * real_y + shift_y + conf.fontsize * 1.33, m[1]);
}
}
}
}
}
// horizontal lines
var y;
ctx.strokeStyle = conf.c_line;
ctx.beginPath();
y = tree.node[tree.node.length - 1].y * real_y + shift_y;
ctx.moveTo(shift_x, y);
ctx.lineTo(tree.node[tree.node.length - 1].x * real_x + shift_x, y);
for (i = 0; i < tree.node.length - 1; ++i) {
var p = tree.node[i];
y = p.y * real_y + shift_y;
ctx.moveTo(p.parent.x * real_x + shift_x, y);
ctx.lineTo(p.x * real_x + shift_x, y);
}
// vertical lines
var x;
for (i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
if (p.child.length === 0 || p.hidden)
continue;
x = p.x * real_x + shift_x;
ctx.moveTo(x, p.child[0].y * real_y + shift_y);
ctx.lineTo(x, p.child[p.child.length - 1].y * real_y + shift_y);
}
ctx.stroke();
ctx.closePath();
// nodes
for (i = 0; i < tree.node.length; ++i) {
var tmp_x, tmp_y, tmp_l;
var p = tree.node[i];
tmp_x = p.x * real_x + shift_x;
tmp_y = p.y * real_y + shift_y;
tmp_l = conf.box_width / 2;
if (p.hidden)
ctx.fillStyle = conf.c_hidden;
else if (conf.show_dup && /:D=Y/i.test(p.meta))
ctx.fillStyle = conf.c_dup;
else
ctx.fillStyle = conf.c_node;
ctx.fillRect(tmp_x - tmp_l, tmp_y - tmp_l, conf.box_width, conf.box_width);
}
}
function kn_plot_core_O(canvas, tree, conf)
{
var ctx = canvas.getContext("2d");
ctx.strokeStyle = ctx.fillStyle = "white";
ctx.fillRect(0, 0, conf.width, conf.height);
CanvasTextFunctions.enable(ctx);
// get the maximum name length
var max_namelen, max_namechr, i;
for (i = 0, max_namelen = max_namechr = 0; i < tree.node.length; ++i) {
if (tree.node[i].child.length)
continue;
var tmp = ctx.measureText(conf.font, conf.fontsize, tree.node[i].name);
if (tmp > max_namelen)
max_namelen = tmp;
}
// set transformation and estimate the font size
var real_r, full = 2 * Math.PI * (350 / 360), fontsize;
fontsize = (conf.width / 2 - conf.xmargin - 1 * tree.n_tips / full) / (max_namelen / conf.fontsize + tree.n_tips / full);
if (fontsize > conf.fontsize)
fontsize = conf.fontsize;
max_namelen *= fontsize / conf.fontsize;
conf.real_r = real_r = conf.width / 2 - conf.xmargin - max_namelen;
conf.full_arc = full;
ctx.save();
ctx.translate(conf.width / 2, conf.height / 2);
// plot background boxes
for (i = tree.node.length - 1; i >= 0; --i) {
if (tree.node[i].box) {
var p = tree.node[i];
var x = (p.parent ? (p.parent.x + p.x) / 2 : 0) * real_r;
var miny, maxy;
ctx.strokeStyle = ctx.fillStyle = tree.node[i].box;
ctx.beginPath();
miny = p.miny - 1. / tree.n_tips / 2;
maxy = p.maxy + 1. / tree.n_tips / 2;
ctx.moveTo(x * Math.cos(miny * full), x * Math.sin(miny * full));
ctx.arc(0, 0, x, miny * full, maxy * full, false);
ctx.lineTo(x * Math.cos(maxy * full), x * Math.sin(maxy * full));
ctx.arc(0, 0, real_r, maxy * full, miny * full, true);
ctx.closePath();
ctx.fill();
}
}
// leaf names
ctx.strokeStyle = conf.c_ext;
ctx.fillStyle = conf.c_hl;
for (i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
if (p.child.length)
continue;
ctx.save();
var tmp;
if (p.hl)
tmp = ctx.measureText(conf.font, fontsize, tree.node[i].name);
if (p.y * full > Math.PI * .5 && p.y * full < Math.PI * 1.5) {
ctx.rotate(p.y * full - Math.PI);
if (p.hl)
ctx.fillRect(-(real_r + fontsize / 2), -fontsize * .8, -tmp, fontsize * 1.5);
ctx.drawTextRight(conf.font, fontsize, -(real_r + fontsize / 2), fontsize / 3, p.name);
} else {
ctx.rotate(p.y * full);
if (p.hl)
ctx.fillRect(real_r + fontsize / 2, -fontsize * .8, tmp, fontsize * 1.5);
ctx.drawText(conf.font, fontsize, real_r + fontsize / 2, fontsize / 3, p.name);
}
ctx.restore();
}
// straight lines
ctx.strokeStyle = "black";
ctx.beginPath();
var root = tree.node[tree.node.length - 1];
ctx.moveTo(0, 0);
ctx.lineTo(root.x * real_r * Math.cos(root.y * full), root.x * real_r * Math.sin(root.y * full));
for (i = 0; i < tree.node.length - 1; ++i) {
var p = tree.node[i];
var cos = Math.cos(p.y * full), sin = Math.sin(p.y * full);
ctx.moveTo(p.parent.x * real_r * cos, p.parent.x * real_r * sin);
ctx.lineTo(p.x * real_r * cos, p.x * real_r * sin);
}
ctx.stroke();
ctx.closePath();
// lines towards the tips
ctx.strokeStyle = "lightgray";
ctx.beginPath();
for (i = 0; i < tree.node.length - 1; ++i) {
var p = tree.node[i];
if (p.child.length)
continue;
var cos = Math.cos(p.y * full), sin = Math.sin(p.y * full);
ctx.moveTo(p.x * real_r * cos, p.x * real_r * sin);
ctx.lineTo(real_r * cos, real_r * sin);
}
ctx.stroke();
ctx.closePath();
// arcs
ctx.strokeStyle = "black";
ctx.beginPath();
for (i = 0; i < tree.node.length; ++i) {
var p = tree.node[i];
if (p.child.length === 0 || p.hidden)
continue;
var r = p.x * real_r;
ctx.moveTo(r * Math.cos(p.child[0].y * full), r * Math.sin(p.child[0].y * full));
ctx.arc(0, 0, r, p.child[0].y * full, p.child[p.child.length - 1].y * full, false); // arcTo is preferred, but may have compatibility issues.
}
ctx.stroke();
ctx.closePath();
ctx.restore();
}
/* Plot the tree "str" in the Newick format in the "canvas" */
function kn_plot_str(canvas, str, conf)
{
var tree = kn_parse(str);
if (tree.error)
return tree;
conf.is_real = kn_calxy(tree, conf.is_real);
conf.height = conf.is_circular ? conf.width : conf.ymargin * 2 + tree.n_tips * conf.yskip;
canvas.width = conf.width;
canvas.height = conf.height;
kn_plot_core(canvas, tree, conf);
return tree;
}
/******************************************************************
******************************************************************
***** The library ends here. The following are DOM specific. *****
******************************************************************
******************************************************************/
//var kn_g_tree = null;
//var kn_g_conf = kn_init_conf();
/*****************
* Event handler *
*****************/
function KN_Actions (canvas, textarea, kn_g_conf, kn_g_tree) {
var self = this;
var id;
this.set_id = function (_id) {
id = _id;
};
this.plot = function (str) {
var time_beg = new Date().getTime();
if (str) {
var tree = kn_plot_str(canvas, str, kn_g_conf);
if (tree.error & 1)
alert("Parsing ERROR: missing left parenthesis!");
else if (tree.error & 2)
alert("Parsing ERROR: missing right parenthesis!");
else if (tree.error & 4)
alert("Parsing ERROR: missing brackets!");
kn_g_tree = tree;
} else
kn_plot_core(canvas, kn_g_tree, kn_g_conf);
kn_g_conf.runtime = (new Date().getTime() - time_beg) / 1000.0;
/*
$('.zoom-in').click(function() {
console.log('zoom in')
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d')
ctx.save();
ctx.scale(1.1,1.1); //zoom-in
kn_plot_str(canvas, str, kn_g_conf)
ctx.restore();
})
$('.zoom-out').click(function() {
console.log('zoomout')
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d')
ctx.save();
ctx.scale(.9,.9); //zoom-in
kn_plot_str(canvas, str, kn_g_conf)
ctx.restore();
})
*/
};
this.plot_str = function () {
this.plot(textarea.value);
};
this.undo_redo = function () {
var tmp = kn_g_conf.old_nh;
kn_g_conf.old_nh = textarea.value;
textarea.value = tmp;
kn_g_tree = kn_parse(textarea.value);
kn_g_conf.is_real = kn_calxy(kn_g_tree, kn_g_conf.is_real);
kn_plot_core(canvas, kn_g_tree, kn_g_conf);
};
var set_undo = function (conf, str) {
conf.old_nh = textarea.value;
textarea.value = str;
};
this.get = function (x, y) {
var id = kn_get_node(kn_g_tree, kn_g_conf, x, y);
return (id >= 0 && id < kn_g_tree.node.length) ? id : -1;
};
this.swap = function () {
var tree = kn_g_tree, conf = kn_g_conf, i = id;
if (i < tree.node.length && tree.node[i].child.length) {
var p = tree.node[i];
var q = p.child[0];
for (j = 0; j < p.child.length - 1; ++j)
p.child[j] = p.child[j + 1];
p.child[p.child.length - 1] = q;
tree.node = kn_expand_node(tree.node[tree.node.length - 1]);
conf.is_real = kn_calxy(tree, conf.is_real);
kn_g_tree = tree;
kn_g_conf = conf;
kn_plot_core(canvas, tree, conf);
set_undo(conf, kn_write_nh(tree));
}
};
this.sort = function () {
var tree = kn_g_tree, conf = kn_g_conf, i = id;
if (i < tree.node.length && tree.node[i].child.length) {
kn_reorder(tree.node[i]);
tree.node = kn_expand_node(tree.node[tree.node.length - 1]);
conf.is_real = kn_calxy(tree, conf.is_real);
kn_g_tree = tree;
kn_g_conf = conf;
kn_plot_core(canvas, tree, conf);
set_undo(conf, kn_write_nh(tree));
}
};
this.reroot = function () {
var tree = kn_g_tree, conf = kn_g_conf, i = id;
if (i < tree.node.length) {
var new_root = kn_reroot(tree.node[tree.node.length - 1], tree.node[i], -1.0);
tree.node = kn_expand_node(new_root);
kn_g_tree = tree;
conf.is_real = kn_calxy(tree, conf.is_real);
kn_plot_core(canvas, tree, conf);
set_undo(conf, kn_write_nh(tree));
}
};
this.collapse = function () {
var tree = kn_g_tree, conf = kn_g_conf, i = id;
if (i < tree.node.length && tree.node[i].child.length) {
tree.node[i].hidden = !tree.node[i].hidden;
var nn = tree.node.length;
tree.node = kn_expand_node(tree.node[tree.node.length - 1]);
kn_count_tips(tree);
conf.is_real = kn_calxy(tree, conf.is_real);
kn_g_tree = tree;
kn_g_conf = conf;
kn_plot_core(canvas, tree, conf);
}
};
this.remove = function () {
var tree = kn_g_tree, conf = kn_g_conf, i = id;
if (i < tree.node.length) {
var new_root = kn_remove_node(tree, tree.node[i]);
tree.node = kn_expand_node(new_root);
kn_count_tips(tree);
kn_g_tree = tree;
conf.is_real = kn_calxy(tree, conf.is_real);
kn_plot_core(canvas, tree, conf);
set_undo(conf, kn_write_nh(tree));
// document.getElementById("n_leaves").innerHTML = "#leaves: "+tree.n_tips+";";
}
};
this.multifurcate = function () {
var tree = kn_g_tree, conf = kn_g_conf, i = id;
if (i < tree.node.length && tree.node[i].child.length) {
kn_multifurcate(tree.node[i]);
tree.node = kn_expand_node(tree.node[tree.node.length - 1]);
conf.is_real = kn_calxy(tree, conf.is_real);
kn_g_tree = tree;
kn_g_conf = conf;
kn_plot_core(canvas, tree, conf);
set_undo(conf, kn_write_nh(tree));
}
};
function move_clear_mark(tree, conf) {
if (tree.active_node !== null && tree.active_node < tree.node.length) {
var p = tree.node[tree.active_node];
tree.active_node = null;
var ctx = canvas.getContext("2d");
ctx.fillStyle = (conf.show_dup && /:D=Y/i.test(p.meta)) ? conf.c_dup : conf.c_node;
ctx.fillRect(p.x * conf.real_x + conf.shift_x - conf.box_width / 2,
p.y * conf.real_y + conf.shift_y - conf.box_width / 2, conf.box_width, conf.box_width);
}
};
this.move = function () {
var tree = kn_g_tree, conf = kn_g_conf, i = id;
if (i < tree.node.length) {
if (tree.active_node !== null && tree.active_node < tree.node.length) {
//alert(tree.active_node + " -> " + i);
if (tree.node[tree.active_node].parent === tree.node[i]) {
alert("Error: cannot move a child to its parent!");
} else {
var new_root = kn_move_node(tree, tree.node[tree.active_node], tree.node[i]);
if (new_root) {
tree.node = kn_expand_node(new_root);
kn_g_tree = tree;
conf.is_real = kn_calxy(tree, conf.is_real);
kn_plot_core(canvas, tree, conf);
set_undo(conf, kn_write_nh(tree));
} else
alert("Error: Invalid move!");
}
move_clear_mark(tree, conf);
} else {
tree.active_node = i;
var p = tree.node[i];
var tmp = conf.box_width - 2;
var ctx = self.canvas.getContext("2d");
ctx.fillStyle = conf.c_active_node;
ctx.fillRect(p.x * conf.real_x + conf.shift_x - tmp / 2,
p.y * conf.real_y + conf.shift_y - tmp / 2, tmp, tmp);
}
} else
move_clear_mark(tree, conf);
};
this.highlight = function (color) {
var tree = kn_g_tree, conf = kn_g_conf, i = id;
var lookup = {white: '#FFFFFF', red: '#FFD8D0', green: '#D8FFC0', blue: '#C0D8FF',
yellow: '#FFFFC8', pink: '#FFD8FF', cyan: '#D8FFFF', none: 'none'};
if (lookup[color])
color = lookup[color];
if (i < tree.node.length) {
// mark the clade to be highlighted
var time_beg = new Date().getTime();
var c = color;
if (c === 'none')
c = null;
if (c !== tree.node[i].box) {
tree.node[i].box = c;
kn_g_tree = tree;
kn_g_conf = conf;
kn_plot_core(canvas, tree, conf);
}
// highlight text
var selbeg, selend;
o = textarea;
if (tree.node[i].child.length === 0) {
selbeg = o.value.indexOf(tree.node[i].name);
selend = selbeg + tree.node[i].name.length;
} else {
var left, leftd, str = o.value;
left = tree.node[i];
leftd = 0;
while (left.child.length)
++leftd, left = left.child[0]; // descend to the leftmost child
selbeg = str.indexOf(left.name);
for (--selbeg; selbeg >= 0; --selbeg) {
if (str.charAt(selbeg) === '(')
--leftd;
if (leftd === 0)
break;
}
var rght, rghtd;
rght = tree.node[i];
rghtd = 0;
while (rght.child.length)
++rghtd, rght = rght.child[rght.child.length - 1];
selend = str.indexOf(rght.name) + rght.name.length;
for (; selend < str.length; ++selend) {
if (str.charAt(selend) === ')')
--rghtd;
if (rghtd === 0)
break;
}
++selend;
}
//o.focus();
if (o.setSelectionRange) {
var j, nn, h = o.clientHeight / o.rows;
var str = o.value.substr(0, selbeg);
for (j = nn = 0; j < selbeg && j < str.length; ++j)
if (str.charAt(j) === '\n')
++nn;
o.scrollTop = nn * h;
o.setSelectionRange(selbeg, selend);
} else { // for IE
var j, nn, r = o.createTextRange();
var str = o.value.substr(0, selend);
for (j = nn = 0; j < selbeg; ++j)
if (str.charAt(j) === '\n')
++nn;
selbeg -= nn;
for (; j < selend; ++j)
if (str.charAt(j) === '\n')
++nn;
selend -= nn;
r.collapse(true);
r.moveEnd('character', selend);
r.moveStart('character', selbeg);
r.select();
}
}
};
/*
this.zoom_in = function() {
var ctx = self.canvas.getContext("2d");
ctx.scale(2, 2);
}*/
return this;
};
var knhx_init = function (canvasId, textareaId, kn_g_conf, kn_g_tree) {
var canvas = document.getElementById(canvasId);
var textarea = document.getElementById(textareaId);
var kn_actions = new KN_Actions(canvas, textarea, kn_g_conf, kn_g_tree);
var kn_actions_html = '<h4>Actions</h4>'
+ '<div id="knhx_action_menu_'+canvasId+'">'
+ '<a href="javascript:void(0);" xonClick="kn_actions.swap();">Swap</a><br>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.sort();">Ladderize</a><br>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.collapse();">Collapse</a><br>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.reroot();">Reroot</a><br>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.move();">Move</a><br>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.multifurcate();">Multifurcate</a><br>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.remove();">Remove</a><br>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.highlight(\'none\');" class="alt"> </a>'
+ '<a href="javascript:void(0);" xclass="alt" xonClick="kn_actions.highlight(\'red\');" style="background-color:#FFD8D0;"> </a>'
+ '<a href="javascript:void(0);" class="alt" xonClick="kn_actions.highlight(\'green\');" style="background-color:#D0FFC0;"> </a>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.highlight(\'blue\');" class="alt" style="background-color:#C0D8FF;"> </a>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.highlight(\'yellow\');" class="alt" style="background-color:#FFFFC8;"> </a>'
+ '<a href="javascript:void(0);" xonClick="kn_actions.highlight(\'cyan\');" class="alt" style="background-color:#D8FFFF;"> </a>'
+ '</div>';
function ev_canvas(ev) {
if (ev.layerX || ev.layerX === 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX === 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
if (navigator.appName === "Microsoft Internet Explorer") { // for IE8
/* When we click a node on the IE8 canvas, ev.offsetX gives
* the offset inside the node instead of inside the canvas.
* We have to do something nasty here... */
var d = document.body;
var o = document.getElementById("canvasContainer");
ev._x = ev.clientX - (o.offsetLeft - d.scrollLeft) - 3;
ev._y = ev.clientY - (o.offsetTop - d.scrollTop) - 3;
}
if (kn_g_tree) {
var id = kn_actions.get(ev._x, ev._y);
console.log(id);
if (id >= 0) {
kn_actions.set_id(id);
if (kn_g_tree.active_node === null) {
console.log('i want to pop');
popmenu.show(ev, kn_actions_html, "98px", function (e) {
console.log('clicked!');
});
} else {
kn_actions.move();
}
} //else popmenu.show(ev, menu_html()); // Don't show menu
} //else popmenu.show(ev, menu_html());
}
if (canvas.addEventListener) {
canvas.addEventListener('click', ev_canvas, false);
} else {
canvas.attachEvent('onclick', ev_canvas);
}
return this;
/*
var insert_elements = function () {
// put the canvas in a container
var o = document.createElement("div");
o.setAttribute('id', 'canvasContainer');
o.setAttribute('style', 'position: relative;');
var canvas_parent = canvas.parentNode || canvas.parent;
canvas_parent.removeChild(canvas);
canvas_parent.appendChild(o);
o.appendChild(canvas);
};
insert_elements();
*/
};
/********************************
* Cross-domain request via YQL *
********************************/
function xss_query_core(jsurl) {
var script_id, script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', jsurl);
script.setAttribute('id', 'script_id');
script_id = document.getElementById('script_id');
if (script_id) {
document.getElementsByTagName('head')[0].removeChild(script_id);
}
document.getElementsByTagName('head')[0].appendChild(script);
// document.getElementById('nhx').value = jsurl;
};
function xss_query(url) {
document.getElementById('nhx').value = "Please wait while the tree being retrieved...\n";
xss_query_core("http://query.yahooapis.com/v1/public/yql?callback=xss_callback&q="
+ encodeURIComponent('select * from html where url="' + url + '"'));
}
function xss_callback(data) {
var str = data.results[0];
var beg = str.indexOf('('), end = str.lastIndexOf(')');
document.getElementById('nhx').value = str.substr(beg, end - beg + 1).replace(/&/ig, "&")
.replace(/\n +/g, "\n").replace(/"/, '"').replace(/</g, "<").replace(/>/g, ">");
}
/*
var render = (function(global) {
var docStyle = document.documentElement.style;
var engine;
if (global.opera && Object.prototype.toString.call(opera) === '[object Opera]') {
engine = 'presto';
} else if ('MozAppearance' in docStyle) {
engine = 'gecko';
} else if ('WebkitAppearance' in docStyle) {
engine = 'webkit';
} else if (typeof navigator.cpuClass === 'string') {
engine = 'trident';
}
var vendorPrefix = {
trident: 'ms',
gecko: 'Moz',
webkit: 'Webkit',
presto: 'O'
}[engine];
var helperElem = document.createElement("div");
var undef;
var perspectiveProperty = vendorPrefix + "Perspective";
var transformProperty = vendorPrefix + "Transform";
if (helperElem.style[perspectiveProperty] !== undef) {
return function(left, top, zoom) {
content.style[transformProperty] = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0) scale(' + zoom + ')';
};
} else if (helperElem.style[transformProperty] !== undef) {
return function(left, top, zoom) {
content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px) scale(' + zoom + ')';
};
} else {
return function(left, top, zoom) {
content.style.marginLeft = left ? (-left/zoom) + 'px' : '';
content.style.marginTop = top ? (-top/zoom) + 'px' : '';
content.style.zoom = zoom || '';
};
}
})(this);
*/
return {
kn_parse: kn_parse,
kn_plot_core: kn_plot_core,
kn_count_tips: kn_count_tips,
kn_calxy: kn_calxy,
kn_get_node: kn_get_node,
knhx_init: knhx_init
};
});
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'pastetext', 'id', {
button: 'Tempel sebagai teks polos',
pasteNotification: 'Press %1 to paste. Your browser doesn‘t support pasting with the toolbar button or context menu option.', // MISSING
title: 'Tempel sebagai Teks Polos'
} );
|
var dbus_8c =
[
[ "mux_get_socket_path", "dbus_8c.html#ad5fe4fea41ad5ccc75d8799c6b6c96e2", null ]
];
|
module.exports = {
ERROR: {
INTERNAL: 'INTERNAL_ERROR'
},
HTTP_METHOD: {
POST: 'POST',
GET: 'GET',
PUT: 'PUT'
}
};
|
"use strict";
const CONTENTS_URL = "data/adventures.json";
let adventures;
window.onload = function load () {
BookUtil.renderArea = $(`#pagecontent`);
BookUtil.renderArea.append(EntryRenderer.utils.getBorderTr());
if (window.location.hash.length) BookUtil.renderArea.append(`<tr><td colspan="6" class="initial-message">Loading...</td></tr>`);
else BookUtil.renderArea.append(`<tr><td colspan="6" class="initial-message">Select an adventure to begin</td></tr>`);
BookUtil.renderArea.append(EntryRenderer.utils.getBorderTr());
DataUtil.loadJSON(CONTENTS_URL).then(onJsonLoad);
};
function onJsonLoad (data) {
adventures = data.adventure;
const adventuresList = $("ul.contents");
adventuresList.append($(`
<li>
<a href='adventures.html'>
<span class='name'>\u21FD All Adventures</span>
</a>
</li>
`));
let tempString = "";
for (let i = 0; i < adventures.length; i++) {
const adv = adventures[i];
tempString +=
`<li class="contents-item" data-bookid="${UrlUtil.encodeForHash(adv.id)}" style="display: none;">
<a id="${i}" href='#${adv.id},0' title='${adv.name}'>
<span class='name'>${adv.name}</span>
</a>
${BookUtil.makeContentsBlock({book: adv, addOnclick: true, defaultHeadersHidden: true})}
</li>`;
}
adventuresList.append(tempString);
BookUtil.addHeaderHandles(true);
const list = new List("listcontainer", {
valueNames: ['name'],
listClass: "contents"
});
BookUtil.baseDataUrl = "data/adventure/adventure-";
BookUtil.bookIndex = adventures;
window.onhashchange = BookUtil.booksHashChange;
if (window.location.hash.length) {
BookUtil.booksHashChange();
} else {
$(`.contents-item`).show();
}
}
|
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets */
define(function (require, exports, module) {
"use strict";
var EditorManager = brackets.getModule("editor/EditorManager");
var Lines = require("lines"),
Paragraphs = require("paragraphs"),
Selections = require("selections"),
Dialogs = require("dialogs");
/**
* Regular expressions do most of the heavy lifting, here
* and everywhere.
*
* Note that the heading items allow for the possibility
* that the heading is preceded by a bullet. This seems
* odd but it also works, at least in Markdown Preview,
* and it is a plausible edge case.
*
* Numbering in front of a heading just displays a bullet,
* so it didn't seem worth preserving.
*
* Also note that there is a limit on white space before
* a heading, as four lines equals raw monospace text.
* But there isn't a similar limitation on bullets, because
* it would interfere with bullets at level 3+.
*/
var MATCH_H1 = /^(\s{0,3}|\s*\*\s*)(#\s)/;
var MATCH_H2 = /^(\s{0,3}|\s*\*\s*)(##\s)/;
var MATCH_H3 = /^(\s{0,3}|\s*\*\s*)(###\s)/;
var MATCH_H4 = /^(\s{0,3}|\s*\*\s*)(####\s)/;
var MATCH_H5 = /^(\s{0,3}|\s*\*\s*)(#####\s)/;
var MATCH_H6 = /^(\s{0,3}|\s*\*\s*)(######\s)/;
var MATCH_HD = /^(\s{0,3}|\s*\*\s*)(#+\s)/;
var MATCH_BULLET = /^\s*\*\s/;
var MATCH_NUMBERED = /^\s*\d\.\s/;
var MATCH_QUOTE = /^\s*>\s/;
var MATCH_LIST = /^\s*(\*|>|\d\.)\s/;
/**
* Check initial conditions for any buttons. Make sure
* we have an editor, are in a Markdown document, and
* have a cursor.
*/
function check(editor) {
if (!editor) {
return false;
}
var mode = editor._getModeFromDocument();
if (mode !== "gfm" && mode !== "markdown") {
return false;
}
var cursor = editor.getCursorPos(false, "to");
if (!cursor.line) {
return false;
}
return true;
}
/**
* Generic function to handle line-based tasks (headings and
* lists). For simple cases, this is a toggle. However, if
* multiple lines are selected, and the toggle is on for only
* some lines, it is turned on for all lines where it is off.
*
* This seems like the most intuitive behavior as it allows
* things like selecting across a bunch of lines, some already
* bulleted, and making them all bulleted. Even in that case,
* one extra click will then remove all the bullets.
*/
function handleLineButton(regexp, replace, after, insert) {
var editor = EditorManager.getActiveEditor();
if (!check(editor)) {
return;
}
if (!Lines.allLinesOn(editor, regexp)) {
Lines.turnLinesOn(editor, regexp, replace, after, insert);
} else {
Lines.turnLinesOff(editor, regexp, after);
}
}
/**
* Generic function to handle selection-based tasks (bold,
* italic, strikethrough). Behaves similarly to line behavior
* above.
*/
function handleSelectionButton(match, badMatch) {
var editor = EditorManager.getActiveEditor();
if (!check(editor)) {
return;
}
if (!Selections.allSelectionsOn(editor, match, badMatch)) {
Selections.turnSelectionsOn(editor, match, badMatch);
} else {
Selections.turnSelectionsOff(editor, match, badMatch);
}
}
// Define the exports; these are the functions that get wired
// into toolbar buttons when the toolbar is created.
exports.h1 = function () {
handleLineButton(MATCH_H1, MATCH_HD, MATCH_BULLET, "# ");
};
exports.h2 = function () {
handleLineButton(MATCH_H2, MATCH_HD, MATCH_BULLET, "## ");
};
exports.h3 = function () {
handleLineButton(MATCH_H3, MATCH_HD, MATCH_BULLET, "### ");
};
exports.h4 = function () {
handleLineButton(MATCH_H4, MATCH_HD, MATCH_BULLET, "#### ");
};
exports.h5 = function () {
handleLineButton(MATCH_H5, MATCH_HD, MATCH_BULLET, "##### ");
};
exports.h6 = function () {
handleLineButton(MATCH_H6, MATCH_HD, MATCH_BULLET, "###### ");
};
exports.bold = function () {
handleSelectionButton("**", "");
};
exports.italic = function () {
handleSelectionButton("*", "**");
};
exports.strikethrough = function () {
handleSelectionButton("~~", "");
};
exports.code = function () {
handleSelectionButton("`", "");
};
exports.image = function () {
var editor = EditorManager.getActiveEditor();
if (!check(editor)) {
return;
}
Dialogs.image(editor);
};
exports.link = function () {
var editor = EditorManager.getActiveEditor();
if (!check(editor)) {
return;
}
Dialogs.link(editor);
};
exports.bullet = function () {
handleLineButton(MATCH_BULLET, MATCH_LIST, null, "* ");
};
exports.numbered = function () {
handleLineButton(MATCH_NUMBERED, MATCH_LIST, null, "1. ");
};
exports.quote = function () {
handleLineButton(MATCH_QUOTE, MATCH_LIST, null, "> ");
};
exports.codeblock = function () {
var editor = EditorManager.getActiveEditor();
if (!check(editor)) {
return;
}
Paragraphs.codeblock(editor);
};
exports.paragraph = function () {
var editor = EditorManager.getActiveEditor();
if (!check(editor)) {
return;
}
Paragraphs.paragraph(editor);
};
exports.reflow = function () {
var editor = EditorManager.getActiveEditor();
if (!check(editor)) {
return;
}
Paragraphs.reflow(editor);
};
});
|
'use strict';
/**
* Module dependencies.
*/
var errorHandler = require('./errors.server.controller'),
db = require('../../config/sequelize'),
_ = require('lodash');
/**
* Create a product
*/
exports.create = function(req, res) {
// Init Variables
var product = db.Product.build(req.body);
req.body.status = 'APPROVED';
// Then save the product
product.save()
.then(function() {
res.json(product);
}, function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
/**
* Show the current product
*/
exports.get = function(req, res) {
res.json(req.product);
};
/**
* Update a product
*/
exports.update = function(req, res) {
var product = req.product;
product = _.extend(product, req.body);
product.save()
.then(function() {
res.json(product);
}, function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
/**
* Delete an product
*/
exports.delete = function(req, res) {
var product = req.product;
product.status = 'DELETED';
product.save()
.then(function() {
res.send(product);
}, function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
/**
* List of products
*/
exports.list = function(req, res) {
var $promise = null;
if(req.user.role === 'ADMIN') {
$promise = db.Product.scope('not_deleted').findAll({ include: [{ model: db.User, required: false}]});
}
else {
$promise = db.Product.scope('approved').findAll({ include: [{ model: db.User, required: false}]});
}
$promise
.then(function(products) {
res.send(products);
}, function(err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
});
};
/**
* product middleware
*/
exports.productByID = function(req, res, next, id) {
db.Product.scope('not_deleted').findById(id, { include: [{ model: db.User, required: false}]})
.then(function(product) {
if (!product) return next(new Error('Failed to load product ' + id));
req.product = product;
next();
}, function(err) {
return next(err);
});
};
exports.hasAuthorization = function(permission) {
return function(req, res, next) {
if(req.user.role === 'ADMIN') {
next();
}
else if(permission == 'READ') {
next();
}
else if(permission == 'WRITE' && req.product.userId == req.user.id) {
next();
}
else {
return res.status(403).send({
message: 'User is not authorized'
});
}
};
};
|
var VisaApp = angular.module('VisaApp', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/views/first.html'
})
.when('/aloitus', {
controller: 'StartController',
templateUrl: 'app/views/aloitus.html'
})
.when('/kysymys', {
controller: 'QuestionController',
templateUrl: 'app/views/question.html'
})
.when('/finaali', {
controller: 'FinalController',
templateUrl: 'app/views/final.html'
});
}]);
|
/*
Project: angular-gantt v1.2.7 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
'use strict';
angular.module('gantt', ['gantt.templates', 'angularMoment'])
.directive('gantt', ['Gantt', 'ganttEnableNgAnimate', '$timeout', '$templateCache', function(Gantt, enableNgAnimate, $timeout, $templateCache) {
return {
restrict: 'A',
transclude: true,
templateUrl: function(tElement, tAttrs) {
var templateUrl;
if (tAttrs.templateUrl === undefined) {
templateUrl = 'template/gantt.tmpl.html';
} else {
templateUrl = tAttrs.templateUrl;
}
if (tAttrs.template !== undefined) {
$templateCache.put(templateUrl, tAttrs.template);
}
return templateUrl;
},
scope: {
sortMode: '=?',
filterTask: '=?',
filterTaskComparator: '=?',
filterRow: '=?',
filterRowComparator: '=?',
viewScale: '=?',
columnWidth: '=?',
expandToFit: '=?',
shrinkToFit: '=?',
showSide: '=?',
allowSideResizing: '=?',
fromDate: '=?',
toDate: '=?',
currentDateValue: '=?',
currentDate: '=?',
daily: '=?',
autoExpand: '=?',
taskOutOfRange: '=?',
taskContent: '=?',
rowContent: '=?',
maxHeight: '=?',
sideWidth: '=?',
headers: '=?',
headersFormats: '=?',
timeFrames: '=?',
dateFrames: '=?',
timeFramesWorkingMode: '=?',
timeFramesNonWorkingMode: '=?',
timespans: '=?',
columnMagnet: '=?',
shiftColumnMagnet: '=?',
timeFramesMagnet: '=?',
data: '=?',
api: '=?',
options: '=?'
},
controller: ['$scope', '$element', function($scope, $element) {
for (var option in $scope.options) {
$scope[option] = $scope.options[option];
}
// Disable animation if ngAnimate is present, as it drops down performance.
enableNgAnimate($element, false);
$scope.gantt = new Gantt($scope, $element);
this.gantt = $scope.gantt;
}],
link: function(scope, element) {
scope.gantt.api.directives.raise.new('gantt', scope, element);
scope.$on('$destroy', function() {
scope.gantt.api.directives.raise.destroy('gantt', scope, element);
});
$timeout(function() {
scope.gantt.initialized();
});
}
};
}]);
}());
// This file is adapted from Angular UI ngGrid project
// MIT License
// https://github.com/angular-ui/ng-grid/blob/v3.0.0-rc.20/src/js/core/factories/GridApi.js
(function() {
'use strict';
angular.module('gantt')
.factory('GanttApi', ['$q', '$rootScope', 'ganttUtils',
function($q, $rootScope, utils) {
/**
* @ngdoc function
* @name gantt.class:GanttApi
* @description GanttApi provides the ability to register public methods events inside the gantt and allow
* for other components to use the api via featureName.raise.methodName and featureName.on.eventName(function(args){}.
* @param {object} gantt gantt that owns api
*/
var GanttApi = function GanttApi(gantt) {
this.gantt = gantt;
this.listeners = [];
this.apiId = utils.newId();
};
/**
* @ngdoc function
* @name gantt.class:suppressEvents
* @methodOf gantt.class:GanttApi
* @description Used to execute a function while disabling the specified event listeners.
* Disables the listenerFunctions, executes the callbackFn, and then enables
* the listenerFunctions again
* @param {object} listenerFuncs listenerFunc or array of listenerFuncs to suppress. These must be the same
* functions that were used in the .on.eventName method
* @param {object} callBackFn function to execute
* @example
* <pre>
* var navigate = function (newRowCol, oldRowCol){
* //do something on navigate
* }
*
* ganttApi.cellNav.on.navigate(scope,navigate);
*
*
* //call the scrollTo event and suppress our navigate listener
* //scrollTo will still raise the event for other listeners
* ganttApi.suppressEvents(navigate, function(){
* ganttApi.cellNav.scrollTo(aRow, aCol);
* });
*
* </pre>
*/
GanttApi.prototype.suppressEvents = function(listenerFuncs, callBackFn) {
var self = this;
var listeners = angular.isArray(listenerFuncs) ? listenerFuncs : [listenerFuncs];
//find all registered listeners
var foundListeners = [];
listeners.forEach(function(l) {
foundListeners = self.listeners.filter(function(lstnr) {
return l === lstnr.handler;
});
});
//deregister all the listeners
foundListeners.forEach(function(l) {
l.dereg();
});
callBackFn();
//reregister all the listeners
foundListeners.forEach(function(l) {
l.dereg = registerEventWithAngular(l.eventId, l.handler, self.gantt, l._this);
});
};
/**
* @ngdoc function
* @name registerEvent
* @methodOf gantt.class:GanttApi
* @description Registers a new event for the given feature. The event will get a
* .raise and .on prepended to it
* <br>
* .raise.eventName() - takes no arguments
* <br/>
* <br/>
* .on.eventName(scope, callBackFn, _this)
* <br/>
* scope - a scope reference to add a deregister call to the scopes .$on('destroy')
* <br/>
* callBackFn - The function to call
* <br/>
* _this - optional this context variable for callbackFn. If omitted, gantt.api will be used for the context
* <br/>
* .on.eventName returns a dereg funtion that will remove the listener. It's not necessary to use it as the listener
* will be removed when the scope is destroyed.
* @param {string} featureName name of the feature that raises the event
* @param {string} eventName name of the event
*/
GanttApi.prototype.registerEvent = function(featureName, eventName) {
var self = this;
if (!self[featureName]) {
self[featureName] = {};
}
var feature = self[featureName];
if (!feature.on) {
feature.on = {};
feature.raise = {};
}
var eventId = 'event:gantt:' + this.apiId + ':' + featureName + ':' + eventName;
// Creating raise event method featureName.raise.eventName
feature.raise[eventName] = function() {
$rootScope.$emit.apply($rootScope, [eventId].concat(Array.prototype.slice.call(arguments)));
};
// Creating on event method featureName.oneventName
feature.on[eventName] = function(scope, handler, _this) {
var deregAngularOn = registerEventWithAngular(eventId, handler, self.gantt, _this);
//track our listener so we can turn off and on
var listener = {
handler: handler,
dereg: deregAngularOn,
eventId: eventId,
scope: scope,
_this: _this
};
self.listeners.push(listener);
var removeListener = function() {
listener.dereg();
var index = self.listeners.indexOf(listener);
self.listeners.splice(index, 1);
};
//destroy tracking when scope is destroyed
scope.$on('$destroy', function() {
removeListener();
});
return removeListener;
};
};
function registerEventWithAngular(eventId, handler, gantt, _this) {
return $rootScope.$on(eventId, function() {
var args = Array.prototype.slice.call(arguments);
args.splice(0, 1); //remove evt argument
handler.apply(_this ? _this : gantt.api, args);
});
}
/**
* @ngdoc function
* @name registerEventsFromObject
* @methodOf gantt.class:GanttApi
* @description Registers features and events from a simple objectMap.
* eventObjectMap must be in this format (multiple features allowed)
* <pre>
* {featureName:
* {
* eventNameOne:function(args){},
* eventNameTwo:function(args){}
* }
* }
* </pre>
* @param {object} eventObjectMap map of feature/event names
*/
GanttApi.prototype.registerEventsFromObject = function(eventObjectMap) {
var self = this;
var features = [];
angular.forEach(eventObjectMap, function(featProp, featPropName) {
var feature = {name: featPropName, events: []};
angular.forEach(featProp, function(prop, propName) {
feature.events.push(propName);
});
features.push(feature);
});
features.forEach(function(feature) {
feature.events.forEach(function(event) {
self.registerEvent(feature.name, event);
});
});
};
/**
* @ngdoc function
* @name registerMethod
* @methodOf gantt.class:GanttApi
* @description Registers a new event for the given feature
* @param {string} featureName name of the feature
* @param {string} methodName name of the method
* @param {object} callBackFn function to execute
* @param {object} _this binds callBackFn 'this' to _this. Defaults to ganttApi.gantt
*/
GanttApi.prototype.registerMethod = function(featureName, methodName, callBackFn, _this) {
if (!this[featureName]) {
this[featureName] = {};
}
var feature = this[featureName];
feature[methodName] = utils.createBoundedWrapper(_this || this.gantt, callBackFn);
};
/**
* @ngdoc function
* @name registerMethodsFromObject
* @methodOf gantt.class:GanttApi
* @description Registers features and methods from a simple objectMap.
* eventObjectMap must be in this format (multiple features allowed)
* <br>
* {featureName:
* {
* methodNameOne:function(args){},
* methodNameTwo:function(args){}
* }
* @param {object} eventObjectMap map of feature/event names
* @param {object} _this binds this to _this for all functions. Defaults to ganttApi.gantt
*/
GanttApi.prototype.registerMethodsFromObject = function(methodMap, _this) {
var self = this;
var features = [];
angular.forEach(methodMap, function(featProp, featPropName) {
var feature = {name: featPropName, methods: []};
angular.forEach(featProp, function(prop, propName) {
feature.methods.push({name: propName, fn: prop});
});
features.push(feature);
});
features.forEach(function(feature) {
feature.methods.forEach(function(method) {
self.registerMethod(feature.name, method.name, method.fn, _this);
});
});
};
return GanttApi;
}]);
})();
(function() {
'use strict';
angular.module('gantt').factory('GanttOptions', [function() {
var GanttOptions = function(values, defaultValues) {
this.defaultValues = defaultValues;
this.values = values;
this.defaultValue = function(optionName) {
var defaultValue = this.defaultValues[optionName];
if (angular.isFunction(defaultValue)) {
defaultValue = defaultValue();
}
return defaultValue;
};
this.sanitize = function(optionName, optionValue) {
if (!optionValue) {
var defaultValue = this.defaultValue(optionName);
if (defaultValue !== undefined) {
if (optionValue !== undefined && typeof defaultValue === 'boolean') {
return optionValue;
}
return defaultValue;
}
}
return optionValue;
};
this.value = function(optionName) {
return this.sanitize(optionName, this.values[optionName]);
};
this.set = function(optionName, optionValue) {
this.values[optionName] = optionValue;
};
this.initialize = function() {
for (var optionName in this.values) {
var optionValue = this.values[optionName];
if (this.values.hasOwnProperty(optionName)) {
this.values[optionName] = this.value(optionName, optionValue);
}
}
return this.values;
};
};
return GanttOptions;
}]);
}());
(function(){
'use strict';
/**
* Calendar factory is used to define working periods, non working periods, and other specific period of time,
* and retrieve effective timeFrames for each day of the gantt.
*/
angular.module('gantt').factory('GanttCalendar', ['$filter', 'moment', function($filter, moment) {
/**
* TimeFrame represents time frame in any day. parameters are given using options object.
*
* @param {moment|string} start start of timeFrame. If a string is given, it will be parsed as a moment.
* @param {moment|string} end end of timeFrame. If a string is given, it will be parsed as a moment.
* @param {boolean} working is this timeFrame flagged as working.
* @param {boolean} magnet is this timeFrame will magnet.
* @param {boolean} default is this timeFrame will be used as default.
* @param {color} css color attached to this timeFrame.
* @param {string} classes css classes attached to this timeFrame.
*
* @constructor
*/
var TimeFrame = function(options) {
if (options === undefined) {
options = {};
}
this.start = options.start;
this.end = options.end;
this.working = options.working;
this.magnet = options.magnet !== undefined ? options.magnet : true;
this.default = options.default;
this.color = options.color;
this.classes = options.classes;
this.internal = options.internal;
};
TimeFrame.prototype.updateView = function() {
if (this.$element) {
var cssStyles = {};
if (this.left !== undefined) {
cssStyles.left = this.left + 'px';
} else {
cssStyles.left = '';
}
if (this.width !== undefined) {
cssStyles.width = this.width + 'px';
} else {
cssStyles.width = '';
}
if (this.color !== undefined) {
cssStyles['background-color'] = this.color;
} else {
cssStyles['background-color'] = '';
}
this.$element.css(cssStyles);
var classes = ['gantt-timeframe' + (this.working ? '' : '-non') + '-working'];
if (this.classes) {
classes = classes.concat(this.classes);
}
for (var i = 0, l = classes.length; i < l; i++) {
this.$element.toggleClass(classes[i], true);
}
}
};
TimeFrame.prototype.getDuration = function() {
if (this.end !== undefined && this.start !== undefined) {
return this.end.diff(this.start, 'milliseconds');
}
};
TimeFrame.prototype.clone = function() {
return new TimeFrame(this);
};
/**
* TimeFrameMapping defines how timeFrames will be placed for each days. parameters are given using options object.
*
* @param {function} func a function with date parameter, that will be evaluated for each distinct day of the gantt.
* this function must return an array of timeFrame names to apply.
* @constructor
*/
var TimeFrameMapping = function(func) {
this.func = func;
};
TimeFrameMapping.prototype.getTimeFrames = function(date) {
var ret = this.func(date);
if (!(ret instanceof Array)) {
ret = [ret];
}
return ret;
};
TimeFrameMapping.prototype.clone = function() {
return new TimeFrameMapping(this.func);
};
/**
* A DateFrame is date range that will use a specific TimeFrameMapping, configured using a function (evaluator),
* a date (date) or a date range (start, end). parameters are given using options object.
*
* @param {function} evaluator a function with date parameter, that will be evaluated for each distinct day of the gantt.
* this function must return a boolean representing matching of this dateFrame or not.
* @param {moment} date date of dateFrame.
* @param {moment} start start of date frame.
* @param {moment} end end of date frame.
* @param {array} targets array of TimeFrameMappings/TimeFrames names to use for this date frame.
* @param {boolean} default is this dateFrame will be used as default.
* @constructor
*/
var DateFrame = function(options) {
this.evaluator = options.evaluator;
if (options.date) {
this.start = moment(options.date).startOf('day');
this.end = moment(options.date).endOf('day');
} else {
this.start = options.start;
this.end = options.end;
}
if (options.targets instanceof Array) {
this.targets = options.targets;
} else {
this.targets = [options.targets];
}
this.default = options.default;
};
DateFrame.prototype.dateMatch = function(date) {
if (this.evaluator) {
return this.evaluator(date);
} else if (this.start && this.end) {
return date >= this.start && date <= this.end;
} else {
return false;
}
};
DateFrame.prototype.clone = function() {
return new DateFrame(this);
};
/**
* Register TimeFrame, TimeFrameMapping and DateMapping objects into Calendar object,
* and use Calendar#getTimeFrames(date) function to retrieve effective timeFrames for a specific day.
*
* @constructor
*/
var Calendar = function() {
this.timeFrames = {};
this.timeFrameMappings = {};
this.dateFrames = {};
};
/**
* Remove all objects.
*/
Calendar.prototype.clear = function() {
this.timeFrames = {};
this.timeFrameMappings = {};
this.dateFrames = {};
};
/**
* Register TimeFrame objects.
*
* @param {object} timeFrames with names of timeFrames for keys and TimeFrame objects for values.
*/
Calendar.prototype.registerTimeFrames = function(timeFrames) {
angular.forEach(timeFrames, function(timeFrame, name) {
this.timeFrames[name] = new TimeFrame(timeFrame);
}, this);
};
/**
* Removes TimeFrame objects.
*
* @param {array} timeFrames names of timeFrames to remove.
*/
Calendar.prototype.removeTimeFrames = function(timeFrames) {
angular.forEach(timeFrames, function(name) {
delete this.timeFrames[name];
}, this);
};
/**
* Remove all TimeFrame objects.
*/
Calendar.prototype.clearTimeFrames = function() {
this.timeFrames = {};
};
/**
* Register TimeFrameMapping objects.
*
* @param {object} mappings object with names of timeFrames mappings for keys and TimeFrameMapping objects for values.
*/
Calendar.prototype.registerTimeFrameMappings = function(mappings) {
angular.forEach(mappings, function(timeFrameMapping, name) {
this.timeFrameMappings[name] = new TimeFrameMapping(timeFrameMapping);
}, this);
};
/**
* Removes TimeFrameMapping objects.
*
* @param {array} mappings names of timeFrame mappings to remove.
*/
Calendar.prototype.removeTimeFrameMappings = function(mappings) {
angular.forEach(mappings, function(name) {
delete this.timeFrameMappings[name];
}, this);
};
/**
* Removes all TimeFrameMapping objects.
*/
Calendar.prototype.clearTimeFrameMappings = function() {
this.timeFrameMappings = {};
};
/**
* Register DateFrame objects.
*
* @param {object} dateFrames object with names of dateFrames for keys and DateFrame objects for values.
*/
Calendar.prototype.registerDateFrames = function(dateFrames) {
angular.forEach(dateFrames, function(dateFrame, name) {
this.dateFrames[name] = new DateFrame(dateFrame);
}, this);
};
/**
* Remove DateFrame objects.
*
* @param {array} mappings names of date frames to remove.
*/
Calendar.prototype.removeDateFrames = function(dateFrames) {
angular.forEach(dateFrames, function(name) {
delete this.dateFrames[name];
}, this);
};
/**
* Removes all DateFrame objects.
*/
Calendar.prototype.clearDateFrames = function() {
this.dateFrames = {};
};
var filterDateFrames = function(inputDateFrames, date) {
var dateFrames = [];
angular.forEach(inputDateFrames, function(dateFrame) {
if (dateFrame.dateMatch(date)) {
dateFrames.push(dateFrame);
}
});
if (dateFrames.length === 0) {
angular.forEach(inputDateFrames, function(dateFrame) {
if (dateFrame.default) {
dateFrames.push(dateFrame);
}
});
}
return dateFrames;
};
/**
* Retrieves TimeFrame objects for a given date, using whole configuration for this Calendar object.
*
* @param {moment} date
*
* @return {array} an array of TimeFrame objects.
*/
Calendar.prototype.getTimeFrames = function(date) {
var timeFrames = [];
var dateFrames = filterDateFrames(this.dateFrames, date);
angular.forEach(dateFrames, function(dateFrame) {
if (dateFrame !== undefined) {
angular.forEach(dateFrame.targets, function(timeFrameMappingName) {
var timeFrameMapping = this.timeFrameMappings[timeFrameMappingName];
if (timeFrameMapping !== undefined) {
// If a timeFrame mapping is found
timeFrames.push(timeFrameMapping.getTimeFrames());
} else {
// If no timeFrame mapping is found, try using direct timeFrame
var timeFrame = this.timeFrames[timeFrameMappingName];
if (timeFrame !== undefined) {
timeFrames.push(timeFrame);
}
}
}, this);
}
}, this);
var dateYear = date.year();
var dateMonth = date.month();
var dateDate = date.date();
var validatedTimeFrames = [];
if (timeFrames.length === 0) {
angular.forEach(this.timeFrames, function(timeFrame) {
if (timeFrame.default) {
timeFrames.push(timeFrame);
}
});
}
angular.forEach(timeFrames, function(timeFrame) {
timeFrame = timeFrame.clone();
if (timeFrame.start !== undefined) {
timeFrame.start.year(dateYear);
timeFrame.start.month(dateMonth);
timeFrame.start.date(dateDate);
}
if (timeFrame.end !== undefined) {
timeFrame.end.year(dateYear);
timeFrame.end.month(dateMonth);
timeFrame.end.date(dateDate);
if (moment(timeFrame.end).startOf('day') === timeFrame.end) {
timeFrame.end.add(1, 'day');
}
}
validatedTimeFrames.push(timeFrame);
});
return validatedTimeFrames;
};
/**
* Solve timeFrames.
*
* Smaller timeFrames have priority over larger one.
*
* @param {array} timeFrames Array of timeFrames to solve
* @param {moment} startDate
* @param {moment} endDate
*/
Calendar.prototype.solve = function(timeFrames, startDate, endDate) {
var color;
var classes;
var minDate;
var maxDate;
angular.forEach(timeFrames, function(timeFrame) {
if (minDate === undefined || minDate > timeFrame.start) {
minDate = timeFrame.start;
}
if (maxDate === undefined || maxDate < timeFrame.end) {
maxDate = timeFrame.end;
}
if (color === undefined && timeFrame.color) {
color = timeFrame.color;
}
if (timeFrame.classes !== undefined) {
if (classes === undefined) {
classes = [];
}
classes = classes.concat(timeFrame.classes);
}
});
if (startDate === undefined) {
startDate = minDate;
}
if (endDate === undefined) {
endDate = maxDate;
}
var solvedTimeFrames = [new TimeFrame({start: startDate, end: endDate, internal: true})];
timeFrames = $filter('filter')(timeFrames, function(timeFrame) {
return (timeFrame.start === undefined || timeFrame.start < endDate) && (timeFrame.end === undefined || timeFrame.end > startDate);
});
angular.forEach(timeFrames, function(timeFrame) {
if (!timeFrame.start) {
timeFrame.start = startDate;
}
if (!timeFrame.end) {
timeFrame.end = endDate;
}
});
var orderedTimeFrames = $filter('orderBy')(timeFrames, function(timeFrame) {
return -timeFrame.getDuration();
});
angular.forEach(orderedTimeFrames, function(timeFrame) {
var tmpSolvedTimeFrames = solvedTimeFrames.slice();
var i=0;
var dispatched = false;
var treated = false;
angular.forEach(solvedTimeFrames, function(solvedTimeFrame) {
if (!treated) {
if (!timeFrame.end && !timeFrame.start) {
// timeFrame is infinite.
tmpSolvedTimeFrames.splice(i, 0, timeFrame);
treated = true;
dispatched = false;
} else if (timeFrame.end > solvedTimeFrame.start && timeFrame.start < solvedTimeFrame.end) {
// timeFrame is included in this solvedTimeFrame.
// solvedTimeFrame:|ssssssssssssssssssssssssssssssssss|
// timeFrame: |tttttt|
// result:|sssssssss|tttttt|sssssssssssssssss|
var newSolvedTimeFrame = solvedTimeFrame.clone();
solvedTimeFrame.end = moment(timeFrame.start);
newSolvedTimeFrame.start = moment(timeFrame.end);
tmpSolvedTimeFrames.splice(i + 1, 0, timeFrame.clone(), newSolvedTimeFrame);
treated = true;
dispatched = false;
} else if (!dispatched && timeFrame.start < solvedTimeFrame.end) {
// timeFrame is dispatched on two solvedTimeFrame.
// First part
// solvedTimeFrame:|sssssssssssssssssssssssssssssssssss|s+1;s+1;s+1;s+1;s+1;s+1|
// timeFrame: |tttttt|
// result:|sssssssssssssssssssssssssssssss|tttttt|;s+1;s+1;s+1;s+1;s+1|
solvedTimeFrame.end = moment(timeFrame.start);
tmpSolvedTimeFrames.splice(i + 1, 0, timeFrame.clone());
dispatched = true;
} else if (dispatched && timeFrame.end > solvedTimeFrame.start) {
// timeFrame is dispatched on two solvedTimeFrame.
// Second part
solvedTimeFrame.start = moment(timeFrame.end);
dispatched = false;
treated = true;
}
i++;
}
});
solvedTimeFrames = tmpSolvedTimeFrames;
});
solvedTimeFrames = $filter('filter')(solvedTimeFrames, function(timeFrame) {
return !timeFrame.internal &&
(timeFrame.start === undefined || timeFrame.start < endDate) &&
(timeFrame.end === undefined || timeFrame.end > startDate);
});
return solvedTimeFrames;
};
return Calendar;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttCurrentDateManager', ['moment', function(moment) {
var GanttCurrentDateManager = function(gantt) {
var self = this;
this.gantt = gantt;
this.date = undefined;
this.position = undefined;
this.currentDateColumn = undefined;
this.gantt.$scope.simplifyMoment = function(d) {
return moment.isMoment(d) ? d.unix() : d;
};
this.gantt.$scope.$watchGroup(['currentDate', 'simplifyMoment(currentDateValue)'], function(newValues, oldValues) {
if (newValues !== oldValues) {
self.setCurrentDate(self.gantt.options.value('currentDateValue'));
}
});
};
GanttCurrentDateManager.prototype.setCurrentDate = function(currentDate) {
this.date = currentDate;
var oldColumn = this.currentDateColumn;
var newColumn;
if (this.date !== undefined && this.gantt.options.value('currentDate') === 'column') {
newColumn = this.gantt.columnsManager.getColumnByDate(this.date, true);
}
this.currentDateColumn = newColumn;
if (oldColumn !== newColumn) {
if (oldColumn !== undefined) {
oldColumn.currentDate = false;
oldColumn.updateView();
}
if (newColumn !== undefined) {
newColumn.currentDate = true;
newColumn.updateView();
}
}
this.position = this.gantt.getPositionByDate(this.date, true);
};
return GanttCurrentDateManager;
}]);
}());
(function() {
'use strict';
angular.module('gantt').factory('GanttColumn', ['moment', function(moment) {
// Used to display the Gantt grid and header.
// The columns are generated by the column generator.
var Column = function(date, endDate, left, width, calendar, timeFramesWorkingMode, timeFramesNonWorkingMode) {
this.date = date;
this.endDate = endDate;
this.left = left;
this.width = width;
this.calendar = calendar;
this.duration = this.endDate.diff(this.date, 'milliseconds');
this.timeFramesWorkingMode = timeFramesWorkingMode;
this.timeFramesNonWorkingMode = timeFramesNonWorkingMode;
this.timeFrames = [];
this.currentDate = false;
this.visibleTimeFrames = [];
this.daysTimeFrames = {};
this.cropped = false;
this.originalSize = {left: this.left, width: this.width};
this.updateTimeFrames();
};
var getDateKey = function(date) {
return date.year() + '-' + date.month() + '-' + date.date();
};
Column.prototype.updateView = function() {
if (this.$element) {
if (this.currentDate) {
this.$element.addClass('gantt-foreground-col-current-date');
} else {
this.$element.removeClass('gantt-foreground-col-current-date');
}
this.$element.css({'left': this.left + 'px', 'width': this.width + 'px'});
for (var i = 0, l = this.timeFrames.length; i < l; i++) {
this.timeFrames[i].updateView();
}
}
};
Column.prototype.updateTimeFrames = function() {
var self = this;
if (self.calendar !== undefined && (self.timeFramesNonWorkingMode !== 'hidden' || self.timeFramesWorkingMode !== 'hidden')) {
var buildPushTimeFrames = function(timeFrames, startDate, endDate) {
return function(timeFrame) {
var start = timeFrame.start;
if (start === undefined) {
start = startDate;
}
var end = timeFrame.end;
if (end === undefined) {
end = endDate;
}
if (start < self.date) {
start = self.date;
}
if (end > self.endDate) {
end = self.endDate;
}
timeFrame = timeFrame.clone();
timeFrame.start = moment(start);
timeFrame.end = moment(end);
timeFrames.push(timeFrame);
};
};
var cDate = self.date;
var cDateStartOfDay = moment(cDate).startOf('day');
var cDateNextDay = cDateStartOfDay.add(1, 'day');
while (cDate < self.endDate) {
var timeFrames = self.calendar.getTimeFrames(cDate);
var nextCDate = moment.min(cDateNextDay, self.endDate);
timeFrames = self.calendar.solve(timeFrames, cDate, nextCDate);
var cTimeFrames = [];
angular.forEach(timeFrames, buildPushTimeFrames(cTimeFrames, cDate, nextCDate));
self.timeFrames = self.timeFrames.concat(cTimeFrames);
var cDateKey = getDateKey(cDate);
self.daysTimeFrames[cDateKey] = cTimeFrames;
cDate = nextCDate;
cDateStartOfDay = moment(cDate).startOf('day');
cDateNextDay = cDateStartOfDay.add(1, 'day');
}
angular.forEach(self.timeFrames, function(timeFrame) {
var positionDuration = timeFrame.start.diff(self.date, 'milliseconds');
var position = positionDuration / self.duration * self.width;
var timeFrameDuration = timeFrame.end.diff(timeFrame.start, 'milliseconds');
var timeFramePosition = timeFrameDuration / self.duration * self.width;
var hidden = false;
if (timeFrame.working && self.timeFramesWorkingMode !== 'visible') {
hidden = true;
} else if (!timeFrame.working && self.timeFramesNonWorkingMode !== 'visible') {
hidden = true;
}
if (!hidden) {
self.visibleTimeFrames.push(timeFrame);
}
timeFrame.hidden = hidden;
timeFrame.left = position;
timeFrame.width = timeFramePosition;
timeFrame.originalSize = {left: timeFrame.left, width: timeFrame.width};
});
if (self.timeFramesNonWorkingMode === 'cropped' || self.timeFramesWorkingMode === 'cropped') {
var timeFramesWidth = 0;
angular.forEach(self.timeFrames, function(timeFrame) {
if (!timeFrame.working && self.timeFramesNonWorkingMode !== 'cropped' ||
timeFrame.working && self.timeFramesWorkingMode !== 'cropped') {
timeFramesWidth += timeFrame.width;
}
});
if (timeFramesWidth !== self.width) {
var croppedRatio = self.width / timeFramesWidth;
var croppedWidth = 0;
var originalCroppedWidth = 0;
var allCropped = true;
angular.forEach(self.timeFrames, function(timeFrame) {
if (!timeFrame.working && self.timeFramesNonWorkingMode !== 'cropped' ||
timeFrame.working && self.timeFramesWorkingMode !== 'cropped') {
timeFrame.left = (timeFrame.left - croppedWidth) * croppedRatio;
timeFrame.width = timeFrame.width * croppedRatio;
timeFrame.originalSize.left = (timeFrame.originalSize.left - originalCroppedWidth) * croppedRatio;
timeFrame.originalSize.width = timeFrame.originalSize.width * croppedRatio;
timeFrame.cropped = false;
allCropped = false;
} else {
croppedWidth += timeFrame.width;
originalCroppedWidth += timeFrame.originalSize.width;
timeFrame.left = undefined;
timeFrame.width = 0;
timeFrame.originalSize = {left: undefined, width: 0};
timeFrame.cropped = true;
}
});
self.cropped = allCropped;
} else {
self.cropped = false;
}
}
}
};
Column.prototype.clone = function() {
return new Column(moment(this.date), moment(this.endDate), this.left, this.width, this.calendar);
};
Column.prototype.containsDate = function(date) {
return date > this.date && date <= this.endDate;
};
Column.prototype.equals = function(other) {
return this.date === other.date;
};
Column.prototype.roundTo = function(date, unit, offset, midpoint) {
// Waiting merge of https://github.com/moment/moment/pull/1794
if (unit === 'day') {
// Inconsistency in units in momentJS.
unit = 'date';
}
offset = offset || 1;
var value = date.get(unit);
switch (midpoint) {
case 'up':
value = Math.ceil(value / offset);
break;
case 'down':
value = Math.floor(value / offset);
break;
default:
value = Math.round(value / offset);
break;
}
var units = ['millisecond', 'second', 'minute', 'hour', 'date', 'month', 'year'];
date.set(unit, value * offset);
var indexOf = units.indexOf(unit);
for (var i = 0; i < indexOf; i++) {
date.set(units[i], 0);
}
return date;
};
Column.prototype.getMagnetDate = function(date, magnetValue, magnetUnit, timeFramesMagnet) {
if (magnetValue > 0 && magnetUnit !== undefined) {
var initialDate = date;
date = moment(date);
if (magnetUnit === 'column') {
// Snap to column borders only.
var position = this.getPositionByDate(date);
if (position < this.width / 2) {
date = moment(this.date);
} else {
date = moment(this.endDate);
}
} else {
// Round the value
date = this.roundTo(date, magnetUnit, magnetValue);
// Snap to column borders if date overflows.
if (date < this.date) {
date = moment(this.date);
} else if (date > this.endDate) {
date = moment(this.endDate);
}
}
if (timeFramesMagnet) {
var maxTimeFrameDiff = Math.abs(initialDate.diff(date, 'milliseconds'));
var currentTimeFrameDiff;
for (var i=0; i<this.timeFrames.length; i++) {
var timeFrame = this.timeFrames[i];
if (timeFrame.magnet) {
var previousTimeFrame = this.timeFrames[i-1];
var nextTimeFrame = this.timeFrames[i+1];
var timeFrameDiff;
if (previousTimeFrame === undefined || previousTimeFrame.working !== timeFrame.working) {
timeFrameDiff = Math.abs(initialDate.diff(timeFrame.start, 'milliseconds'));
if (timeFrameDiff < maxTimeFrameDiff && (currentTimeFrameDiff === undefined || timeFrameDiff < currentTimeFrameDiff)) {
currentTimeFrameDiff = timeFrameDiff;
date = timeFrame.start;
}
}
if (nextTimeFrame === undefined || nextTimeFrame.working !== timeFrame.working) {
timeFrameDiff = Math.abs(initialDate.diff(timeFrame.end, 'milliseconds'));
if (timeFrameDiff < maxTimeFrameDiff && (currentTimeFrameDiff === undefined || timeFrameDiff < currentTimeFrameDiff)) {
currentTimeFrameDiff = timeFrameDiff;
date = timeFrame.end;
}
}
}
}
}
}
return date;
};
Column.prototype.getDateByPositionUsingTimeFrames = function(position) {
for (var i = 0, l = this.timeFrames.length; i < l; i++) {
// TODO: performance optimization could be done.
var timeFrame = this.timeFrames[i];
if (!timeFrame.cropped && position >= timeFrame.left && position <= timeFrame.left + timeFrame.width) {
var positionDuration = timeFrame.getDuration() / timeFrame.width * (position - timeFrame.left);
var date = moment(timeFrame.start).add(positionDuration, 'milliseconds');
return date;
}
}
};
Column.prototype.getDateByPosition = function(position, magnetValue, magnetUnit, timeFramesMagnet) {
var positionDuration;
var date;
if (position < 0) {
position = 0;
}
if (position > this.width) {
position = this.width;
}
if (this.timeFramesNonWorkingMode === 'cropped' || this.timeFramesWorkingMode === 'cropped') {
date = this.getDateByPositionUsingTimeFrames(position);
}
if (date === undefined) {
positionDuration = this.duration / this.width * position;
date = moment(this.date).add(positionDuration, 'milliseconds');
}
date = this.getMagnetDate(date, magnetValue, magnetUnit, timeFramesMagnet);
return date;
};
Column.prototype.getDayTimeFrame = function(date) {
var dtf = this.daysTimeFrames[getDateKey(date)];
if (dtf === undefined) {
return [];
}
return dtf;
};
Column.prototype.getPositionByDate = function(date) {
var positionDuration;
var position;
if (this.timeFramesNonWorkingMode === 'cropped' || this.timeFramesWorkingMode === 'cropped') {
var croppedDate = date;
var timeFrames = this.getDayTimeFrame(croppedDate);
for (var i = 0; i < timeFrames.length; i++) {
var timeFrame = timeFrames[i];
if (croppedDate >= timeFrame.start && croppedDate <= timeFrame.end) {
if (timeFrame.cropped) {
if (timeFrames.length > i + 1) {
croppedDate = timeFrames[i + 1].start;
} else {
croppedDate = timeFrame.end;
}
} else {
positionDuration = croppedDate.diff(timeFrame.start, 'milliseconds');
position = positionDuration / timeFrame.getDuration() * timeFrame.width;
return this.left + timeFrame.left + position;
}
}
}
}
positionDuration = date.diff(this.date, 'milliseconds');
position = positionDuration / this.duration * this.width;
if (position < 0) {
position = 0;
}
if (position > this.width) {
position = this.width;
}
return this.left + position;
};
return Column;
}]);
}());
(function() {
'use strict';
angular.module('gantt').factory('GanttColumnGenerator', ['GanttColumn', 'moment', function(Column, moment) {
var ColumnGenerator = function(columnsManager) {
var self = this;
this.columnsManager = columnsManager;
// Generates one column for each time unit between the given from and to date.
self.generate = function(from, to, maximumWidth, leftOffset, reverse) {
if (!to && !maximumWidth) {
throw 'to or maximumWidth must be defined';
}
var viewScale = self.columnsManager.gantt.options.value('viewScale');
viewScale = viewScale.trim();
if (viewScale.charAt(viewScale.length - 1) === 's') {
viewScale = viewScale.substring(0, viewScale.length - 1);
}
var viewScaleValue;
var viewScaleUnit;
var splittedViewScale;
if (viewScale) {
splittedViewScale = viewScale.split(' ');
}
if (splittedViewScale && splittedViewScale.length > 1) {
viewScaleValue = parseFloat(splittedViewScale[0]);
viewScaleUnit = splittedViewScale[splittedViewScale.length - 1];
} else {
viewScaleValue = 1;
viewScaleUnit = viewScale;
}
var calendar = self.columnsManager.gantt.calendar;
var timeFramesWorkingMode = self.columnsManager.gantt.options.value('timeFramesWorkingMode');
var timeFramesNonWorkingMode = self.columnsManager.gantt.options.value('timeFramesNonWorkingMode');
var columnWidth = self.columnsManager.getColumnsWidth();
var excludeTo = false;
from = moment(from).startOf(viewScaleUnit);
if (to) {
excludeTo = isToDateToExclude(to);
to = moment(to).startOf(viewScaleUnit);
}
var left = 0;
var date = moment(from).startOf(viewScaleUnit);
if (reverse) {
date.add(-viewScaleValue, viewScaleUnit);
left -= columnWidth;
}
var generatedCols = [];
while (true) {
if (maximumWidth && Math.abs(left) > maximumWidth + columnWidth) {
break;
}
var startDate = moment(date);
var endDate = moment(startDate).add(viewScaleValue, viewScaleUnit);
ensureNoUnitOverflow(viewScaleUnit, startDate, endDate);
var column = new Column(startDate, endDate, leftOffset ? left + leftOffset : left, columnWidth, calendar, timeFramesWorkingMode, timeFramesNonWorkingMode);
if (!column.cropped) {
generatedCols.push(column);
if (reverse) {
left -= columnWidth;
} else {
left += columnWidth;
}
if (to) {
if (reverse) {
if (excludeTo && date < to || !excludeTo && date <= to) {
break;
}
} else {
if (excludeTo && date > to || !excludeTo && date >= to) {
break;
}
}
}
}
if (reverse) {
date.add(-viewScaleValue, viewScaleUnit);
ensureNoUnitOverflow(viewScaleUnit, date, startDate);
} else {
date.add(viewScaleValue, viewScaleUnit);
ensureNoUnitOverflow(viewScaleUnit, startDate, date);
}
}
if (reverse) {
if (isToDateToExclude(from, viewScaleValue, viewScaleUnit)) {
generatedCols.shift();
}
generatedCols.reverse();
}
return generatedCols;
};
// Columns are generated including or excluding the to date.
// If the To date is the first day of month and the time is 00:00 then no new column is generated for this month.
var isToDateToExclude = function(to, value, unit) {
return moment(to).add(value, unit).startOf(unit) === to;
};
var ensureNoUnitOverflow = function(unit, startDate, endDate) {
var v1 = startDate.get(unit);
var v2 = endDate.get(unit);
var firstValue = getFirstValue(unit);
if (firstValue !== undefined && v2 !== firstValue && v2 < v1) {
endDate.set(unit, firstValue);
}
};
var getFirstValue = function(unit) {
if (['hour', 'minute', 'second', 'millisecond'].indexOf(unit) >= 0) {
return 0;
}
};
};
return ColumnGenerator;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttColumnHeader', [ 'moment', 'GanttColumn', function(moment, Column) {
// Used to display the Gantt grid and header.
// The columns are generated by the column generator.
var ColumnHeader = function(date, viewScaleValue, viewScaleUnit, left, width, labelFormat) {
var startDate = moment(date);
var endDate = moment(startDate).add(viewScaleValue, viewScaleUnit);
var column = new Column(startDate, endDate, left, width);
column.unit = viewScaleUnit;
column.label = angular.isFunction(labelFormat) ? labelFormat(column): startDate.format(labelFormat);
return column;
};
return ColumnHeader;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttColumnsManager', ['GanttColumnGenerator', 'GanttHeaderGenerator', '$filter', '$timeout', 'ganttLayout', 'ganttBinarySearch', 'moment', function(ColumnGenerator, HeaderGenerator, $filter, $timeout, layout, bs, moment) {
var ColumnsManager = function(gantt) {
var self = this;
this.gantt = gantt;
this.from = undefined;
this.to = undefined;
this.columns = [];
this.visibleColumns = [];
this.previousColumns = [];
this.nextColumns = [];
this.headers = [];
this.visibleHeaders = [];
this.scrollAnchor = undefined;
// Add a watcher if a view related setting changed from outside of the Gantt. Update the gantt accordingly if so.
// All those changes need a recalculation of the header columns
this.gantt.$scope.$watchGroup(['viewScale', 'columnWidth', 'timeFramesWorkingMode', 'timeFramesNonWorkingMode', 'fromDate', 'toDate', 'autoExpand', 'taskOutOfRange'], function(newValues, oldValues) {
if (newValues !== oldValues && self.gantt.rendered) {
self.generateColumns();
}
});
this.gantt.$scope.$watchCollection('headers', function(newValues, oldValues) {
if (newValues !== oldValues && self.gantt.rendered) {
self.generateColumns();
}
});
this.gantt.$scope.$watchCollection('headersFormats', function(newValues, oldValues) {
if (newValues !== oldValues && self.gantt.rendered) {
self.generateColumns();
}
});
this.gantt.$scope.$watchGroup(['ganttElementWidth', 'showSide', 'sideWidth', 'maxHeight', 'daily'], function(newValues, oldValues) {
if (newValues !== oldValues && self.gantt.rendered) {
self.updateColumnsMeta();
}
});
this.gantt.api.data.on.load(this.gantt.$scope, function() {
if ((self.from === undefined || self.to === undefined ||
self.from > self.gantt.rowsManager.getDefaultFrom() ||
self.to < self.gantt.rowsManager.getDefaultTo()) && self.gantt.rendered) {
self.generateColumns();
}
self.gantt.rowsManager.sortRows();
});
this.gantt.api.data.on.remove(this.gantt.$scope, function() {
self.gantt.rowsManager.sortRows();
});
this.gantt.api.registerMethod('columns', 'clear', this.clearColumns, this);
this.gantt.api.registerMethod('columns', 'generate', this.generateColumns, this);
this.gantt.api.registerMethod('columns', 'refresh', this.updateColumnsMeta, this);
this.gantt.api.registerMethod('columns', 'getColumnsWidth', this.getColumnsWidth, this);
this.gantt.api.registerMethod('columns', 'getColumnsWidthToFit', this.getColumnsWidthToFit, this);
this.gantt.api.registerMethod('columns', 'getDateRange', this.getDateRange, this);
this.gantt.api.registerEvent('columns', 'clear');
this.gantt.api.registerEvent('columns', 'generate');
this.gantt.api.registerEvent('columns', 'refresh');
};
ColumnsManager.prototype.setScrollAnchor = function() {
if (this.gantt.scroll.$element && this.columns.length > 0) {
var el = this.gantt.scroll.$element[0];
var center = el.scrollLeft + el.offsetWidth / 2;
this.scrollAnchor = this.gantt.getDateByPosition(center);
}
};
ColumnsManager.prototype.scrollToScrollAnchor = function() {
var self = this;
if (this.columns.length > 0 && this.scrollAnchor !== undefined) {
// Ugly but prevents screen flickering (unlike $timeout)
this.gantt.$scope.$$postDigest(function() {
self.gantt.api.scroll.toDate(self.scrollAnchor);
});
}
};
ColumnsManager.prototype.clearColumns = function() {
this.setScrollAnchor();
this.from = undefined;
this.to = undefined;
this.columns = [];
this.visibleColumns = [];
this.previousColumns = [];
this.nextColumns = [];
this.headers = [];
this.visibleHeaders = [];
this.gantt.api.columns.raise.clear();
};
ColumnsManager.prototype.generateColumns = function(from, to) {
if (!from) {
from = this.gantt.options.value('fromDate');
}
if (!to) {
to = this.gantt.options.value('toDate');
}
if (!from || (moment.isMoment(from) && !from.isValid())) {
from = this.gantt.rowsManager.getDefaultFrom();
if (!from) {
return false;
}
}
if (!to || (moment.isMoment(to) && !to.isValid())) {
to = this.gantt.rowsManager.getDefaultTo();
if (!to) {
return false;
}
}
if (from !== undefined && !moment.isMoment(from)) {
from = moment(from);
}
if (to !== undefined && !moment.isMoment(to)) {
to = moment(to);
}
if (this.gantt.options.value('taskOutOfRange') === 'expand') {
from = this.gantt.rowsManager.getExpandedFrom(from);
to = this.gantt.rowsManager.getExpandedTo(to);
}
this.setScrollAnchor();
this.from = from;
this.to = to;
var columnGenerator = new ColumnGenerator(this);
var headerGenerator = new HeaderGenerator(this);
this.columns = columnGenerator.generate(from, to);
this.headers = headerGenerator.generate(this.columns);
this.previousColumns = [];
this.nextColumns = [];
this.updateColumnsMeta();
this.scrollToScrollAnchor();
this.gantt.api.columns.raise.generate(this.columns, this.headers);
};
ColumnsManager.prototype.updateColumnsMeta = function() {
this.gantt.isRefreshingColumns = true;
var lastColumn = this.getLastColumn();
this.gantt.originalWidth = lastColumn !== undefined ? lastColumn.originalSize.left + lastColumn.originalSize.width : 0;
var columnsWidthChanged = this.updateColumnsWidths(this.columns, this.headers, this.previousColumns, this.nextColumns);
this.gantt.width = lastColumn !== undefined ? lastColumn.left + lastColumn.width : 0;
var showSide = this.gantt.options.value('showSide');
var sideShown = this.gantt.side.isShown();
var sideVisibilityChanged = showSide !== sideShown;
if (sideVisibilityChanged && !showSide) {
// Prevent unnecessary v-scrollbar if side is hidden here
this.gantt.side.show(false);
}
this.gantt.rowsManager.updateTasksPosAndSize();
this.gantt.timespansManager.updateTimespansPosAndSize();
this.updateVisibleColumns(columnsWidthChanged);
this.gantt.rowsManager.updateVisibleObjects();
var currentDateValue = this.gantt.options.value('currentDateValue');
this.gantt.currentDateManager.setCurrentDate(currentDateValue);
if (sideVisibilityChanged && showSide) {
// Prevent unnecessary v-scrollbar if side is shown here
this.gantt.side.show(true);
}
this.gantt.isRefreshingColumns = false;
this.gantt.api.columns.raise.refresh(this.columns, this.headers);
};
// Returns the last Gantt column or undefined
ColumnsManager.prototype.getLastColumn = function(extended) {
var columns = this.columns;
if (extended) {
columns = this.nextColumns;
}
if (columns && columns.length > 0) {
return columns[columns.length - 1];
} else {
return undefined;
}
};
// Returns the first Gantt column or undefined
ColumnsManager.prototype.getFirstColumn = function(extended) {
var columns = this.columns;
if (extended) {
columns = this.previousColumns;
}
if (columns && columns.length > 0) {
return columns[0];
} else {
return undefined;
}
};
// Returns the column at the given or next possible date
ColumnsManager.prototype.getColumnByDate = function(date, disableExpand) {
if (!disableExpand) {
this.expandExtendedColumnsForDate(date);
}
var extendedColumns = this.previousColumns.concat(this.columns, this.nextColumns);
var columns = bs.get(extendedColumns, date, function(c) {
return c.date;
}, true);
return columns[0] !== undefined ? columns[0] : columns[1];
};
// Returns the column at the given position x (in em)
ColumnsManager.prototype.getColumnByPosition = function(x, disableExpand) {
if (!disableExpand) {
this.expandExtendedColumnsForPosition(x);
}
var extendedColumns = this.previousColumns.concat(this.columns, this.nextColumns);
var columns = bs.get(extendedColumns, x, function(c) {
return c.left;
}, true);
return columns[0] === undefined ? columns[1]: columns[0];
};
ColumnsManager.prototype.updateColumnsWidths = function(columns, headers, previousColumns, nextColumns) {
var columnWidth = this.gantt.options.value('columnWidth');
var expandToFit = this.gantt.options.value('expandToFit');
var shrinkToFit = this.gantt.options.value('shrinkToFit');
if (columnWidth === undefined || expandToFit || shrinkToFit) {
var newWidth = this.gantt.getBodyAvailableWidth();
var lastColumn = this.gantt.columnsManager.getLastColumn(false);
if (lastColumn !== undefined) {
var currentWidth = lastColumn.originalSize.left + lastColumn.originalSize.width;
if (expandToFit && currentWidth < newWidth ||
shrinkToFit && currentWidth > newWidth ||
columnWidth === undefined
) {
var widthFactor = newWidth / currentWidth;
layout.setColumnsWidthFactor(columns, widthFactor);
angular.forEach(headers, function(header) {
layout.setColumnsWidthFactor(header, widthFactor);
});
// previous and next columns will be generated again on need.
previousColumns.splice(0, this.previousColumns.length);
nextColumns.splice(0, this.nextColumns.length);
return true;
}
}
}
return false;
};
ColumnsManager.prototype.getColumnsWidth = function() {
var columnWidth = this.gantt.options.value('columnWidth');
if (columnWidth === undefined) {
if (this.gantt.width <= 0) {
columnWidth = 20;
} else {
columnWidth = this.gantt.width / this.columns.length;
}
}
return columnWidth;
};
ColumnsManager.prototype.getColumnsWidthToFit = function() {
return this.gantt.getBodyAvailableWidth() / this.columns.length;
};
ColumnsManager.prototype.expandExtendedColumnsForPosition = function(x) {
if (x < 0) {
var firstColumn = this.getFirstColumn();
var from = firstColumn.date;
var firstExtendedColumn = this.getFirstColumn(true);
if (!firstExtendedColumn || firstExtendedColumn.left > x) {
this.previousColumns = new ColumnGenerator(this).generate(from, undefined, -x, 0, true);
}
return true;
} else if (x > this.gantt.width) {
var lastColumn = this.getLastColumn();
var endDate = lastColumn.getDateByPosition(lastColumn.width);
var lastExtendedColumn = this.getLastColumn(true);
if (!lastExtendedColumn || lastExtendedColumn.left + lastExtendedColumn.width < x) {
this.nextColumns = new ColumnGenerator(this).generate(endDate, undefined, x - this.gantt.width, this.gantt.width, false);
}
return true;
}
return false;
};
ColumnsManager.prototype.expandExtendedColumnsForDate = function(date) {
var firstColumn = this.getFirstColumn();
var from;
if (firstColumn) {
from = firstColumn.date;
}
var lastColumn = this.getLastColumn();
var endDate;
if (lastColumn) {
endDate = lastColumn.getDateByPosition(lastColumn.width);
}
if (from && date < from) {
var firstExtendedColumn = this.getFirstColumn(true);
if (!firstExtendedColumn || firstExtendedColumn.date > date) {
this.previousColumns = new ColumnGenerator(this).generate(from, date, undefined, 0, true);
}
return true;
} else if (endDate && date >= endDate) {
var lastExtendedColumn = this.getLastColumn(true);
if (!lastExtendedColumn || lastExtendedColumn.date < endDate) {
this.nextColumns = new ColumnGenerator(this).generate(endDate, date, undefined, this.gantt.width, false);
}
return true;
}
return false;
};
// Returns the number of active headers
ColumnsManager.prototype.getActiveHeadersCount = function() {
return this.headers.length;
};
ColumnsManager.prototype.updateVisibleColumns = function(includeViews) {
this.visibleColumns = $filter('ganttColumnLimit')(this.columns, this.gantt);
this.visibleHeaders = [];
angular.forEach(this.headers, function(header) {
this.visibleHeaders.push($filter('ganttColumnLimit')(header, this.gantt));
}, this);
if (includeViews) {
angular.forEach(this.visibleColumns, function(c) {
c.updateView();
});
angular.forEach(this.visibleHeaders, function(headerRow) {
angular.forEach(headerRow, function(header) {
header.updateView();
});
});
}
var currentDateValue = this.gantt.options.value('currentDateValue');
this.gantt.currentDateManager.setCurrentDate(currentDateValue);
};
var defaultHeadersFormats = {'year': 'YYYY', 'quarter': '[Q]Q YYYY', month: 'MMMM YYYY', week: 'w', day: 'D', hour: 'H', minute:'HH:mm'};
var defaultDayHeadersFormats = {day: 'LL', hour: 'H', minute:'HH:mm'};
var defaultYearHeadersFormats = {'year': 'YYYY', 'quarter': '[Q]Q', month: 'MMMM'};
ColumnsManager.prototype.getHeaderFormat = function(unit) {
var format;
var headersFormats = this.gantt.options.value('headersFormats');
if (headersFormats !== undefined) {
format = headersFormats[unit];
}
if (format === undefined) {
var viewScale = this.gantt.options.value('viewScale');
viewScale = viewScale.trim();
if (viewScale.charAt(viewScale.length - 1) === 's') {
viewScale = viewScale.substring(0, viewScale.length - 1);
}
var viewScaleUnit;
var splittedViewScale;
if (viewScale) {
splittedViewScale = viewScale.split(' ');
}
if (splittedViewScale && splittedViewScale.length > 1) {
viewScaleUnit = splittedViewScale[splittedViewScale.length - 1];
} else {
viewScaleUnit = viewScale;
}
if (['millisecond', 'second', 'minute', 'hour'].indexOf(viewScaleUnit) > -1) {
format = defaultDayHeadersFormats[unit];
} else if (['month', 'quarter', 'year'].indexOf(viewScaleUnit) > -1) {
format = defaultYearHeadersFormats[unit];
}
if (format === undefined) {
format = defaultHeadersFormats[unit];
}
}
return format;
};
ColumnsManager.prototype.getDateRange = function(visibleOnly) {
var firstColumn, lastColumn;
if (visibleOnly) {
if (this.visibleColumns && this.visibleColumns.length > 0) {
firstColumn = this.visibleColumns[0];
lastColumn = this.visibleColumns[this.visibleColumns.length - 1];
}
} else {
firstColumn = this.getFirstColumn();
lastColumn = this.getLastColumn();
}
return firstColumn && lastColumn ? [firstColumn.date, lastColumn.endDate]: undefined;
};
return ColumnsManager;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttHeaderGenerator', ['GanttColumnHeader', function(ColumnHeader) {
var generateHeader = function(columnsManager, columns, viewScale) {
var generatedHeaders = [];
var header;
var prevColDateVal;
var viewScaleValue;
var viewScaleUnit;
var splittedViewScale;
if (viewScale) {
splittedViewScale = viewScale.split(' ');
}
if (splittedViewScale && splittedViewScale.length > 1) {
viewScaleValue = parseFloat(splittedViewScale[0]);
viewScaleUnit = splittedViewScale[splittedViewScale.length - 1];
} else {
viewScaleValue = 1;
viewScaleUnit = viewScale;
}
for (var i = 0, l = columns.length; i < l; i++) {
var col = columns[i];
var colDateVal = col.date.get(viewScaleUnit);
if (i === 0 || prevColDateVal !== colDateVal) {
prevColDateVal = colDateVal;
var labelFormat = columnsManager.getHeaderFormat(viewScaleUnit);
header = new ColumnHeader(col.date, viewScaleValue, viewScaleUnit, col.originalSize.left, col.originalSize.width, labelFormat);
header.left = col.left;
header.width = col.width;
generatedHeaders.push(header);
} else {
header.originalSize.width += col.originalSize.width;
header.width += col.width;
}
}
return generatedHeaders;
};
return function(columnsManager) {
this.generate = function(columns) {
var units = [];
if (columnsManager.gantt.options.value('headers') === undefined) {
var viewScale = columnsManager.gantt.options.value('viewScale');
viewScale = viewScale.trim();
if (viewScale.charAt(viewScale.length - 1) === 's') {
viewScale = viewScale.substring(0, viewScale.length - 1);
}
var viewScaleUnit;
var splittedViewScale;
if (viewScale) {
splittedViewScale = viewScale.split(' ');
}
if (splittedViewScale && splittedViewScale.length > 1) {
viewScaleUnit = splittedViewScale[splittedViewScale.length - 1];
} else {
viewScaleUnit = viewScale;
}
if (['quarter','month'].indexOf(viewScaleUnit) > -1) {
units.push('year');
}
if (['day', 'week'].indexOf(viewScaleUnit) > -1) {
units.push('month');
}
if (['day'].indexOf(viewScaleUnit) > -1) {
units.push('week');
}
if (['hour'].indexOf(viewScaleUnit) > -1) {
units.push('day');
}
if (['minute', 'second'].indexOf(viewScaleUnit) > -1) {
units.push('hour');
}
if (['second'].indexOf(viewScaleUnit) > -1) {
units.push('minute');
}
units.push(viewScale);
} else {
units = columnsManager.gantt.options.value('headers');
}
var headers = [];
angular.forEach(units, function(unit) {
headers.push(generateHeader(columnsManager, columns, unit));
});
return headers;
};
};
}]);
}());
(function() {
'use strict';
angular.module('gantt').factory('Gantt', [
'GanttApi', 'GanttOptions', 'GanttCalendar', 'GanttScroll', 'GanttBody', 'GanttRowHeader', 'GanttHeader', 'GanttSide', 'GanttObjectModel', 'GanttRowsManager', 'GanttColumnsManager', 'GanttTimespansManager', 'GanttCurrentDateManager', 'ganttArrays', 'moment', '$document', '$timeout',
function(GanttApi, Options, Calendar, Scroll, Body, RowHeader, Header, Side, ObjectModel, RowsManager, ColumnsManager, TimespansManager, CurrentDateManager, arrays, moment, $document, $timeout) {
// Gantt logic. Manages the columns, rows and sorting functionality.
var Gantt = function($scope, $element) {
var self = this;
this.$scope = $scope;
this.$element = $element;
this.options = new Options($scope, {
'api': angular.noop,
'data': [],
'timespans': [],
'viewScale': 'day',
'columnMagnet': '15 minutes',
'timeFramesMagnet': true,
'showSide': true,
'allowSideResizing': true,
'currentDate': 'line',
'currentDateValue': moment,
'autoExpand': 'none',
'taskOutOfRange': 'truncate',
'taskContent': '{{task.model.name}}',
'rowContent': '{{row.model.name}}',
'maxHeight': 0,
'timeFrames': [],
'dateFrames': [],
'timeFramesWorkingMode': 'hidden',
'timeFramesNonWorkingMode': 'visible'
});
this.api = new GanttApi(this);
this.api.registerEvent('core', 'ready');
this.api.registerEvent('core', 'rendered');
this.api.registerEvent('directives', 'controller');
this.api.registerEvent('directives', 'preLink');
this.api.registerEvent('directives', 'postLink');
this.api.registerEvent('directives', 'new');
this.api.registerEvent('directives', 'destroy');
this.api.registerEvent('data', 'change');
this.api.registerEvent('data', 'load');
this.api.registerEvent('data', 'remove');
this.api.registerEvent('data', 'clear');
this.api.registerMethod('core', 'getDateByPosition', this.getDateByPosition, this);
this.api.registerMethod('core', 'getPositionByDate', this.getPositionByDate, this);
this.api.registerMethod('data', 'load', this.loadData, this);
this.api.registerMethod('data', 'remove', this.removeData, this);
this.api.registerMethod('data', 'clear', this.clearData, this);
this.api.registerMethod('data', 'get', this.getData, this);
this.calendar = new Calendar(this);
this.calendar.registerTimeFrames(this.options.value('timeFrames'));
this.calendar.registerDateFrames(this.options.value('dateFrames'));
this.api.registerMethod('timeframes', 'registerTimeFrames', this.calendar.registerTimeFrames, this.calendar);
this.api.registerMethod('timeframes', 'clearTimeframes', this.calendar.clearTimeFrames, this.calendar);
this.api.registerMethod('timeframes', 'registerDateFrames', this.calendar.registerDateFrames, this.calendar);
this.api.registerMethod('timeframes', 'clearDateFrames', this.calendar.clearDateFrames, this.calendar);
this.api.registerMethod('timeframes', 'registerTimeFrameMappings', this.calendar.registerTimeFrameMappings, this.calendar);
this.api.registerMethod('timeframes', 'clearTimeFrameMappings', this.calendar.clearTimeFrameMappings, this.calendar);
$scope.$watchGroup(['timeFrames', 'dateFrames'], function(newValues, oldValues) {
if (newValues !== oldValues) {
var timeFrames = newValues[0];
var dateFrames = newValues[1];
var oldTimeFrames = oldValues[0];
var oldDateFrames = oldValues[1];
var framesChanged = false;
if (!angular.equals(timeFrames, oldTimeFrames)) {
self.calendar.clearTimeFrames();
self.calendar.registerTimeFrames(timeFrames);
framesChanged = true;
}
if (!angular.equals(dateFrames, oldDateFrames)) {
self.calendar.clearDateFrames();
self.calendar.registerDateFrames(dateFrames);
framesChanged = true;
}
if (framesChanged) {
self.columnsManager.generateColumns();
}
}
});
$scope.$watch('columnMagnet', function() {
var splittedColumnMagnet;
var columnMagnet = self.options.value('columnMagnet');
if (columnMagnet) {
splittedColumnMagnet = columnMagnet.trim().split(' ');
}
if (splittedColumnMagnet && splittedColumnMagnet.length > 1) {
self.columnMagnetValue = parseFloat(splittedColumnMagnet[0]);
self.columnMagnetUnit = moment.normalizeUnits(splittedColumnMagnet[splittedColumnMagnet.length - 1]);
} else {
self.columnMagnetValue = 1;
self.columnMagnetUnit = moment.normalizeUnits(columnMagnet);
}
});
$scope.$watchGroup(['shiftColumnMagnet', 'viewScale'], function() {
var splittedColumnMagnet;
var shiftColumnMagnet = self.options.value('shiftColumnMagnet');
if (shiftColumnMagnet) {
splittedColumnMagnet = shiftColumnMagnet.trim().split(' ');
}
if (splittedColumnMagnet !== undefined && splittedColumnMagnet.length > 1) {
self.shiftColumnMagnetValue = parseFloat(splittedColumnMagnet[0]);
self.shiftColumnMagnetUnit = moment.normalizeUnits(splittedColumnMagnet[splittedColumnMagnet.length - 1]);
} else {
self.shiftColumnMagnetValue = 1;
self.shiftColumnMagnetUnit = moment.normalizeUnits(shiftColumnMagnet);
}
});
var keyHandler = function(e) {
self.shiftKey = e.shiftKey;
return true;
};
$document.on('keyup keydown', keyHandler);
$scope.$on('$destroy', function() {
$document.off('keyup keydown', keyHandler);
});
this.scroll = new Scroll(this);
this.body = new Body(this);
this.header = new Header(this);
this.side = new Side(this);
this.objectModel = new ObjectModel(this.api);
this.rowsManager = new RowsManager(this);
this.columnsManager = new ColumnsManager(this);
this.timespansManager = new TimespansManager(this);
this.currentDateManager = new CurrentDateManager(this);
this.originalWidth = 0;
this.width = 0;
if (angular.isFunction(this.$scope.api)) {
this.$scope.api(this.api);
}
var hasRowModelOrderChanged = function(data1, data2) {
if (data2 === undefined || data1.length !== data2.length) {
return true;
}
for (var i = 0, l = data1.length; i < l; i++) {
if (data1[i].id !== data2[i].id) {
return true;
}
}
return false;
};
$scope.$watchCollection('data', function(newData, oldData) {
if (oldData !== undefined) {
var toRemoveIds = arrays.getRemovedIds(newData, oldData);
if (toRemoveIds.length === oldData.length) {
self.rowsManager.removeAll();
// DEPRECATED
self.api.data.raise.clear();
} else {
for (var i = 0, l = toRemoveIds.length; i < l; i++) {
var toRemoveId = toRemoveIds[i];
self.rowsManager.removeRow(toRemoveId);
}
// DEPRECATED
var removedRows = [];
angular.forEach(oldData, function(removedRow) {
if (toRemoveIds.indexOf(removedRow.id) > -1) {
removedRows.push(removedRow);
}
});
self.api.data.raise.remove(removedRows);
}
}
if (newData !== undefined) {
var modelOrderChanged = hasRowModelOrderChanged(newData, oldData);
if (modelOrderChanged) {
self.rowsManager.resetNonModelLists();
}
for (var j = 0, k = newData.length; j < k; j++) {
var rowData = newData[j];
self.rowsManager.addRow(rowData, modelOrderChanged);
}
self.api.data.raise.change(newData, oldData);
// DEPRECATED
self.api.data.raise.load(newData);
}
});
};
// Returns the exact column date at the given position x (in em)
Gantt.prototype.getDateByPosition = function(x, magnet, disableExpand) {
var column = this.columnsManager.getColumnByPosition(x, disableExpand);
if (column !== undefined) {
var magnetValue;
var magnetUnit;
if (magnet) {
if (this.shiftKey) {
if (this.shiftColumnMagnetValue !== undefined && this.shiftColumnMagnetUnit !== undefined) {
magnetValue = this.shiftColumnMagnetValue;
magnetUnit = this.shiftColumnMagnetUnit;
} else {
var viewScale = this.options.value('viewScale');
viewScale = viewScale.trim();
var viewScaleValue;
var viewScaleUnit;
var splittedViewScale;
if (viewScale) {
splittedViewScale = viewScale.split(' ');
}
if (splittedViewScale && splittedViewScale.length > 1) {
viewScaleValue = parseFloat(splittedViewScale[0]);
viewScaleUnit = moment.normalizeUnits(splittedViewScale[splittedViewScale.length - 1]);
} else {
viewScaleValue = 1;
viewScaleUnit = moment.normalizeUnits(viewScale);
}
magnetValue = viewScaleValue * 0.25;
magnetUnit = viewScaleUnit;
}
} else {
magnetValue = this.columnMagnetValue;
magnetUnit = this.columnMagnetUnit;
}
}
return column.getDateByPosition(x - column.left, magnetValue, magnetUnit, this.options.value('timeFramesMagnet'));
} else {
return undefined;
}
};
Gantt.prototype.getBodyAvailableWidth = function() {
var scrollWidth = this.getWidth() - this.side.getWidth();
var borderWidth = this.scroll.getBordersWidth();
var availableWidth = scrollWidth - (borderWidth !== undefined ? this.scroll.getBordersWidth() : 0);
// Remove 1 pixel because of rounding issue in some cases.
availableWidth = availableWidth - 1;
return availableWidth;
};
// Returns the position inside the Gantt calculated by the given date
Gantt.prototype.getPositionByDate = function(date, disableExpand) {
if (date === undefined) {
return undefined;
}
if (!moment.isMoment(moment)) {
date = moment(date);
}
var column = this.columnsManager.getColumnByDate(date, disableExpand);
if (column !== undefined) {
return column.getPositionByDate(date);
} else {
return undefined;
}
};
// DEPRECATED - Use $data instead.
Gantt.prototype.loadData = function(data) {
if (!angular.isArray(data)) {
data = data !== undefined ? [data] : [];
}
if (this.$scope.data === undefined) {
this.$scope.data = data;
} else {
for (var i = 0, l = data.length; i < l; i++) {
var row = data[i];
var j = arrays.indexOfId(this.$scope.data, row.id);
if (j > -1) {
this.$scope.data[j] = row;
} else {
this.$scope.data.push(row);
}
}
}
var w = this.side.getWidth();
if (w > 0) {
this.options.set('sideWidth', w);
}
};
Gantt.prototype.getData = function() {
return this.$scope.data;
};
// DEPRECATED - Use $data instead.
Gantt.prototype.removeData = function(data) {
if (!angular.isArray(data)) {
data = data !== undefined ? [data] : [];
}
if (this.$scope.data !== undefined) {
for (var i = 0, l = data.length; i < l; i++) {
var rowToRemove = data[i];
var j = arrays.indexOfId(this.$scope.data, rowToRemove.id);
if (j > -1) {
if (rowToRemove.tasks === undefined || rowToRemove.tasks.length === 0) {
// Remove complete row
this.$scope.data.splice(j, 1);
} else {
// Remove single tasks
var row = this.$scope.data[j];
for (var ti = 0, tl = rowToRemove.tasks.length; ti < tl; ti++) {
var taskToRemove = rowToRemove.tasks[ti];
var tj = arrays.indexOfId(row.tasks, taskToRemove.id);
if (tj > -1) {
row.tasks.splice(tj, 1);
}
}
}
}
}
}
};
// DEPRECATED - Use $data instead.
Gantt.prototype.clearData = function() {
this.$scope.data = undefined;
};
Gantt.prototype.getWidth = function() {
return this.$scope.ganttElementWidth;
};
Gantt.prototype.initialized = function() {
// Gantt is initialized. Signal that the Gantt is ready.
this.api.core.raise.ready(this.api);
this.rendered = true;
this.columnsManager.generateColumns();
var gantt = this;
var renderedFunction = function() {
var w = gantt.side.getWidth();
if (w > 0) {
gantt.options.set('sideWidth', w);
}
gantt.api.core.raise.rendered(gantt.api);
};
$timeout(renderedFunction);
};
return Gantt;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttObjectModel', ['ganttUtils', 'moment', function(utils, moment) {
var ObjectModel = function(api) {
this.api = api;
this.api.registerEvent('tasks', 'clean');
this.api.registerEvent('rows', 'clean');
this.api.registerEvent('timespans', 'clean');
};
ObjectModel.prototype.cleanTask = function(model) {
if (model.id === undefined) {
model.id = utils.randomUuid();
}
if (model.from !== undefined && !moment.isMoment(model.from)) {
model.from = moment(model.from);
}
if (model.to !== undefined && !moment.isMoment(model.to)) {
model.to = moment(model.to);
}
this.api.tasks.raise.clean(model);
};
ObjectModel.prototype.cleanRow = function(model) {
if (model.id === undefined) {
model.id = utils.randomUuid();
}
if (model.from !== undefined && !moment.isMoment(model.from)) {
model.from = moment(model.from);
}
if (model.to !== undefined && !moment.isMoment(model.to)) {
model.to = moment(model.to);
}
this.api.rows.raise.clean(model);
};
ObjectModel.prototype.cleanTimespan = function(model) {
if (model.id === undefined) {
model.id = utils.randomUuid();
}
if (model.from !== undefined && !moment.isMoment(model.from)) {
model.from = moment(model.from);
}
if (model.to !== undefined && !moment.isMoment(model.to)) {
model.to = moment(model.to);
}
this.api.timespans.raise.clean(model);
};
return ObjectModel;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttRow', ['GanttTask', 'moment', '$filter', function(Task, moment, $filter) {
var Row = function(rowsManager, model) {
this.rowsManager = rowsManager;
this.model = model;
this.from = undefined;
this.to = undefined;
this.tasksMap = {};
this.tasks = [];
this.filteredTasks = [];
this.visibleTasks = [];
};
Row.prototype.addTaskImpl = function(task, viewOnly) {
this.tasksMap[task.model.id] = task;
this.tasks.push(task);
if (!viewOnly) {
if (this.model.tasks === undefined) {
this.model.tasks = [];
}
if (this.model.tasks.indexOf(task.model) === -1) {
this.model.tasks.push(task.model);
}
}
};
// Adds a task to a specific row. Merges the task if there is already one with the same id
Row.prototype.addTask = function(taskModel, viewOnly) {
// Copy to new task (add) or merge with existing (update)
var task, isUpdate = false;
this.rowsManager.gantt.objectModel.cleanTask(taskModel);
if (taskModel.id in this.tasksMap) {
task = this.tasksMap[taskModel.id];
if (task.model === taskModel) {
return task;
}
task.model = taskModel;
isUpdate = true;
} else {
task = new Task(this, taskModel);
this.addTaskImpl(task, viewOnly);
}
this.sortTasks();
this.setFromToByTask(task);
if (!viewOnly) {
if (isUpdate) {
this.rowsManager.gantt.api.tasks.raise.change(task);
} else {
this.rowsManager.gantt.api.tasks.raise.add(task);
}
}
return task;
};
// Removes the task from the existing row and adds it to he current one
Row.prototype.moveTaskToRow = function(task, viewOnly) {
var oldRow = task.row;
oldRow.removeTask(task.model.id, viewOnly, true);
task.row = this;
this.addTaskImpl(task, viewOnly);
this.sortTasks();
this.setFromToByTask(task);
task.updatePosAndSize();
this.updateVisibleTasks();
if (!viewOnly) {
this.rowsManager.gantt.api.tasks.raise.rowChange(task, oldRow);
}
};
Row.prototype.updateVisibleTasks = function() {
var filterTask = this.rowsManager.gantt.options.value('filterTask');
if (filterTask) {
if (typeof(filterTask) === 'object') {
filterTask = {model: filterTask};
}
var filterTaskComparator = this.rowsManager.gantt.options.value('filterTaskComparator');
if (typeof(filterTaskComparator) === 'function') {
filterTaskComparator = function(actual, expected) {
return filterTaskComparator(actual.model, expected.model);
};
}
this.filteredTasks = $filter('filter')(this.tasks, filterTask, filterTaskComparator);
} else {
this.filteredTasks = this.tasks.slice(0);
}
this.visibleTasks = $filter('ganttTaskLimit')(this.filteredTasks, this.rowsManager.gantt);
};
Row.prototype.updateTasksPosAndSize = function() {
for (var j = 0, k = this.tasks.length; j < k; j++) {
this.tasks[j].updatePosAndSize();
}
};
// Remove the specified task from the row
Row.prototype.removeTask = function(taskId, viewOnly, silent) {
if (taskId in this.tasksMap) {
var removedTask = this.tasksMap[taskId];
var task;
var i;
for (i = this.tasks.length - 1; i >= 0; i--) {
task = this.tasks[i];
if (task.model.id === taskId) {
this.tasks.splice(i, 1); // Remove from array
// Update earliest or latest date info as this may change
if (this.from - task.model.from === 0 || this.to - task.model.to === 0) {
this.setFromTo();
}
break;
}
}
for (i = this.filteredTasks.length - 1; i >= 0; i--) {
task = this.filteredTasks[i];
if (task.model.id === taskId) {
this.filteredTasks.splice(i, 1); // Remove from filtered array
break;
}
}
for (i = this.visibleTasks.length - 1; i >= 0; i--) {
task = this.visibleTasks[i];
if (task.model.id === taskId) {
this.visibleTasks.splice(i, 1); // Remove from visible array
break;
}
}
if (!viewOnly) {
delete this.tasksMap[taskId]; // Remove from map
if (this.model.tasks !== undefined) {
var taskIndex = this.model.tasks.indexOf(removedTask.model);
if (taskIndex > -1) {
this.model.tasks.splice(taskIndex, 1);
}
}
if (!silent) {
this.rowsManager.gantt.api.tasks.raise.remove(removedTask);
}
}
return removedTask;
}
};
Row.prototype.removeAllTasks = function() {
this.from = undefined;
this.to = undefined;
this.tasksMap = {};
this.tasks = [];
this.filteredTasks = [];
this.visibleTasks = [];
};
// Calculate the earliest from and latest to date of all tasks in a row
Row.prototype.setFromTo = function() {
this.from = undefined;
this.to = undefined;
for (var j = 0, k = this.tasks.length; j < k; j++) {
this.setFromToByTask(this.tasks[j]);
}
};
Row.prototype.setFromToByTask = function(task) {
this.setFromToByValues(task.model.from, task.model.to);
};
Row.prototype.setFromToByValues = function(from, to) {
if (from !== undefined) {
if (this.from === undefined) {
this.from = moment(from);
} else if (from < this.from) {
this.from = moment(from);
}
}
if (to !== undefined) {
if (this.to === undefined) {
this.to = moment(to);
} else if (to > this.to) {
this.to = moment(to);
}
}
};
Row.prototype.sortTasks = function() {
this.tasks.sort(function(t1, t2) {
return t1.left - t2.left;
});
};
Row.prototype.clone = function() {
var clone = new Row(this.rowsManager, angular.copy(this));
for (var i = 0, l = this.tasks.length; i < l; i++) {
clone.addTask(this.tasks[i].model);
}
return clone;
};
return Row;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttRowHeader', [function() {
var RowHeader = function(gantt) {
this.gantt = gantt;
};
return RowHeader;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttRowsManager', ['GanttRow', 'ganttArrays', '$filter', '$timeout', 'moment', function(Row, arrays, $filter, $timeout, moment) {
var RowsManager = function(gantt) {
var self = this;
this.gantt = gantt;
this.rowsMap = {};
this.rows = [];
this.sortedRows = [];
this.filteredRows = [];
this.customFilteredRows = [];
this.visibleRows = [];
this.rowsTaskWatchers = [];
this._defaultFilterImpl = function(sortedRows, filterRow, filterRowComparator) {
return $filter('filter')(sortedRows, filterRow, filterRowComparator);
};
this.filterImpl = this._defaultFilterImpl;
this.customRowSorters = [];
this.customRowFilters = [];
this.gantt.$scope.$watchGroup(['filterTask', 'filterTaskComparator'], function(newValues, oldValues) {
if (newValues !== oldValues) {
self.updateVisibleTasks();
}
});
this.gantt.$scope.$watchGroup(['filterRow', 'filterRowComparator'], function(newValues, oldValues) {
if (newValues !== oldValues) {
self.updateVisibleRows();
}
});
this.gantt.$scope.$watch('sortMode', function(newValue, oldValue) {
if (newValue !== oldValue) {
self.sortRows();
}
});
// Listen to vertical scrollbar visibility changes to update columns width
var _oldVScrollbarVisible = this.gantt.scroll.isVScrollbarVisible();
this.gantt.$scope.$watchGroup(['maxHeight', 'gantt.rowsManager.visibleRows.length'], function(newValue, oldValue) {
if (newValue !== oldValue) {
$timeout(function() {
var newVScrollbarVisible = self.gantt.scroll.isVScrollbarVisible();
if (newVScrollbarVisible !== _oldVScrollbarVisible) {
_oldVScrollbarVisible = newVScrollbarVisible;
self.gantt.columnsManager.updateColumnsMeta();
}
});
}
});
this.gantt.api.registerMethod('rows', 'sort', RowsManager.prototype.sortRows, this);
this.gantt.api.registerMethod('rows', 'applySort', RowsManager.prototype.applySort, this);
this.gantt.api.registerMethod('rows', 'refresh', RowsManager.prototype.updateVisibleObjects, this);
this.gantt.api.registerMethod('rows', 'removeRowSorter', RowsManager.prototype.removeCustomRowSorter, this);
this.gantt.api.registerMethod('rows', 'addRowSorter', RowsManager.prototype.addCustomRowSorter, this);
this.gantt.api.registerMethod('rows', 'removeRowFilter', RowsManager.prototype.removeCustomRowFilter, this);
this.gantt.api.registerMethod('rows', 'addRowFilter', RowsManager.prototype.addCustomRowFilter, this);
this.gantt.api.registerMethod('rows', 'setFilterImpl', RowsManager.prototype.setFilterImpl, this);
this.gantt.api.registerEvent('tasks', 'add');
this.gantt.api.registerEvent('tasks', 'change');
this.gantt.api.registerEvent('tasks', 'viewChange');
this.gantt.api.registerEvent('tasks', 'rowChange');
this.gantt.api.registerEvent('tasks', 'remove');
this.gantt.api.registerEvent('tasks', 'filter');
this.gantt.api.registerEvent('rows', 'add');
this.gantt.api.registerEvent('rows', 'change');
this.gantt.api.registerEvent('rows', 'remove');
this.gantt.api.registerEvent('rows', 'move');
this.gantt.api.registerEvent('rows', 'filter');
this.updateVisibleObjects();
};
RowsManager.prototype.resetNonModelLists = function() {
this.rows = [];
this.sortedRows = [];
this.filteredRows = [];
this.customFilteredRows = [];
this.visibleRows = [];
};
RowsManager.prototype.addRow = function(rowModel, modelOrderChanged) {
// Copy to new row (add) or merge with existing (update)
var row, i, l, isUpdate = false;
this.gantt.objectModel.cleanRow(rowModel);
if (rowModel.id in this.rowsMap) {
row = this.rowsMap[rowModel.id];
if (modelOrderChanged) {
this.rows.push(row);
this.sortedRows.push(row);
this.filteredRows.push(row);
this.customFilteredRows.push(row);
this.visibleRows.push(row);
}
if (row.model === rowModel) {
return;
}
var toRemoveIds = arrays.getRemovedIds(rowModel.tasks, row.model.tasks);
for (i= 0, l=toRemoveIds.length; i<l; i++) {
var toRemoveId = toRemoveIds[i];
row.removeTask(toRemoveId);
}
row.model = rowModel;
isUpdate = true;
} else {
row = new Row(this, rowModel);
this.rowsMap[rowModel.id] = row;
this.rows.push(row);
this.sortedRows.push(row);
this.filteredRows.push(row);
this.customFilteredRows.push(row);
this.visibleRows.push(row);
}
if (rowModel.tasks !== undefined && rowModel.tasks.length > 0) {
for (i = 0, l = rowModel.tasks.length; i < l; i++) {
var taskModel = rowModel.tasks[i];
row.addTask(taskModel);
}
row.updateVisibleTasks();
}
if (isUpdate) {
this.gantt.api.rows.raise.change(row);
} else {
this.gantt.api.rows.raise.add(row);
}
if (!isUpdate) {
var watcher = this.gantt.$scope.$watchCollection(function() {return rowModel.tasks;}, function(newTasks, oldTasks) {
if (newTasks !== oldTasks) {
var i, l;
var toRemoveIds = arrays.getRemovedIds(newTasks, oldTasks);
for (i= 0, l = toRemoveIds.length; i<l; i++) {
var toRemove = toRemoveIds[i];
row.removeTask(toRemove);
}
if (newTasks !== undefined) {
for (i= 0, l = newTasks.length; i<l; i++) {
var toAdd = newTasks[i];
row.addTask(toAdd);
}
row.updateVisibleTasks();
}
}
});
this.rowsTaskWatchers.push(watcher);
}
return isUpdate;
};
RowsManager.prototype.removeRow = function(rowId) {
if (rowId in this.rowsMap) {
delete this.rowsMap[rowId]; // Remove from map
var removedRow;
var row;
var indexOf = arrays.indexOfId(this.rows, rowId, ['model', 'id']);
if (indexOf > -1) {
removedRow = this.rows.splice(indexOf, 1)[0]; // Remove from array
var deregisterFunction = this.rowsTaskWatchers.splice(indexOf, 1)[0]; // Remove watcher
deregisterFunction();
}
arrays.removeId(this.sortedRows, rowId, ['model', 'id']);
arrays.removeId(this.filteredRows, rowId, ['model', 'id']);
arrays.removeId(this.customFilteredRows, rowId, ['model', 'id']);
arrays.removeId(this.visibleRows, rowId, ['model', 'id']);
this.gantt.api.rows.raise.remove(removedRow);
return row;
}
return undefined;
};
RowsManager.prototype.removeAll = function() {
this.rowsMap = {};
this.rows = [];
this.sortedRows = [];
this.filteredRows = [];
this.customFilteredRows = [];
this.visibleRows = [];
for (var i= 0, l=this.rowsTaskWatchers.length; i<l; i++) {
var deregisterFunction = this.rowsTaskWatchers[i];
deregisterFunction();
}
this.rowsTaskWatchers = [];
};
RowsManager.prototype.sortRows = function() {
var expression = this.gantt.options.value('sortMode');
if (expression !== undefined) {
var reverse = false;
if (angular.isString(expression) && expression.charAt(0) === '-') {
reverse = true;
expression = expression.substr(1);
}
var angularOrderBy = $filter('orderBy');
this.sortedRows = angularOrderBy(this.rows, expression, reverse);
} else {
this.sortedRows = this.rows.slice();
}
this.sortedRows = this.applyCustomRowSorters(this.sortedRows);
this.updateVisibleRows();
};
RowsManager.prototype.removeCustomRowSorter = function(sorterFunction) {
var i = this.customRowSorters.indexOf(sorterFunction);
if (i > -1) {
this.customRowSorters.splice(i, 1);
}
};
RowsManager.prototype.addCustomRowSorter = function(sorterFunction) {
this.customRowSorters.push(sorterFunction);
};
RowsManager.prototype.applyCustomRowSorters = function(sortedRows) {
angular.forEach(this.customRowSorters, function(sorterFunction) {
sortedRows = sorterFunction(sortedRows);
});
return sortedRows;
};
/**
* Applies current view sort to data model.
*/
RowsManager.prototype.applySort = function() {
var data = this.gantt.$scope.data;
data.splice(0, data.length); // empty data.
var rows = [];
for (var i = 0, l = this.sortedRows.length; i < l; i++) {
data.push(this.sortedRows[i].model);
rows.push(this.sortedRows[i]);
}
this.rows = rows;
};
RowsManager.prototype.moveRow = function(row, targetRow) {
var sortMode = this.gantt.options.value('sortMode');
if (sortMode !== undefined) {
// Apply current sort to model
this.applySort();
this.gantt.options.set('sortMode', undefined);
}
var targetRowIndex = this.rows.indexOf(targetRow);
var rowIndex = this.rows.indexOf(row);
if (targetRowIndex > -1 && rowIndex > -1 && targetRowIndex !== rowIndex) {
arrays.moveToIndex(this.rows, rowIndex, targetRowIndex);
arrays.moveToIndex(this.rowsTaskWatchers, rowIndex, targetRowIndex);
arrays.moveToIndex(this.gantt.$scope.data, rowIndex, targetRowIndex);
this.gantt.api.rows.raise.change(row);
this.gantt.api.rows.raise.move(row, rowIndex, targetRowIndex);
this.updateVisibleObjects();
this.sortRows();
}
};
RowsManager.prototype.updateVisibleObjects = function() {
this.updateVisibleRows();
this.updateVisibleTasks();
};
RowsManager.prototype.updateVisibleRows = function() {
var oldFilteredRows = this.filteredRows;
var filterRow = this.gantt.options.value('filterRow');
if (filterRow) {
if (typeof(filterRow) === 'object') {
filterRow = {model: filterRow};
}
var filterRowComparator = this.gantt.options.value('filterRowComparator');
if (typeof(filterRowComparator) === 'function') {
//fix issue this.gantt is undefined
//
var gantt = this.gantt;
filterRowComparator = function(actual, expected) {
//fix actual.model is undefined
return gantt.options.value('filterRowComparator')(actual, expected);
};
}
this.filteredRows = this.filterImpl(this.sortedRows, filterRow, filterRowComparator);
} else {
this.filteredRows = this.sortedRows.slice(0);
}
var raiseEvent = !angular.equals(oldFilteredRows, this.filteredRows);
this.customFilteredRows = this.applyCustomRowFilters(this.filteredRows);
// TODO: Implement rowLimit like columnLimit to enhance performance for gantt with many rows
this.visibleRows = this.customFilteredRows;
if (raiseEvent) {
this.gantt.api.rows.raise.filter(this.sortedRows, this.filteredRows);
}
};
RowsManager.prototype.removeCustomRowFilter = function(filterFunction) {
var i = this.customRowFilters.indexOf(filterFunction);
if (i > -1) {
this.customRowFilters.splice(i, 1);
}
};
RowsManager.prototype.addCustomRowFilter = function(filterFunction) {
this.customRowFilters.push(filterFunction);
};
RowsManager.prototype.applyCustomRowFilters = function(filteredRows) {
angular.forEach(this.customRowFilters, function(filterFunction) {
filteredRows = filterFunction(filteredRows);
});
return filteredRows;
};
RowsManager.prototype.setFilterImpl = function(filterImpl) {
if (!filterImpl) {
this.filterImpl = this._defaultFilterImpl;
} else {
this.filterImpl = filterImpl;
}
};
RowsManager.prototype.updateVisibleTasks = function() {
var oldFilteredTasks = [];
var filteredTasks = [];
var tasks = [];
angular.forEach(this.rows, function(row) {
oldFilteredTasks = oldFilteredTasks.concat(row.filteredTasks);
row.updateVisibleTasks();
filteredTasks = filteredTasks.concat(row.filteredTasks);
tasks = tasks.concat(row.tasks);
});
var filterEvent = !angular.equals(oldFilteredTasks, filteredTasks);
if (filterEvent) {
this.gantt.api.tasks.raise.filter(tasks, filteredTasks);
}
};
// Update the position/size of all tasks in the Gantt
RowsManager.prototype.updateTasksPosAndSize = function() {
for (var i = 0, l = this.rows.length; i < l; i++) {
this.rows[i].updateTasksPosAndSize();
}
};
RowsManager.prototype.getExpandedFrom = function(from) {
from = from ? moment(from) : from;
var minRowFrom = from;
angular.forEach(this.rows, function(row) {
if (minRowFrom === undefined || minRowFrom > row.from) {
minRowFrom = row.from;
}
});
if (minRowFrom && (!from || minRowFrom < from)) {
return minRowFrom;
}
return from;
};
RowsManager.prototype.getExpandedTo = function(to) {
to = to ? moment(to) : to;
var maxRowTo = to;
angular.forEach(this.rows, function(row) {
if (maxRowTo === undefined || maxRowTo < row.to) {
maxRowTo = row.to;
}
});
var toDate = this.gantt.options.value('toDate');
if (maxRowTo && (!toDate || maxRowTo > toDate)) {
return maxRowTo;
}
return to;
};
RowsManager.prototype.getDefaultFrom = function() {
var defaultFrom;
angular.forEach(this.rows, function(row) {
if (defaultFrom === undefined || row.from < defaultFrom) {
defaultFrom = row.from;
}
});
return defaultFrom;
};
RowsManager.prototype.getDefaultTo = function() {
var defaultTo;
angular.forEach(this.rows, function(row) {
if (defaultTo === undefined || row.to > defaultTo) {
defaultTo = row.to;
}
});
return defaultTo;
};
return RowsManager;
}]);
}());
(function() {
'use strict';
angular.module('gantt').factory('GanttTask', ['moment', function(moment) {
var Task = function(row, model) {
this.rowsManager = row.rowsManager;
this.row = row;
this.model = model;
this.truncatedLeft = false;
this.truncatedRight = false;
};
Task.prototype.isMilestone = function() {
return !this.model.to || this.model.from - this.model.to === 0;
};
Task.prototype.isOutOfRange = function() {
var firstColumn = this.rowsManager.gantt.columnsManager.getFirstColumn();
var lastColumn = this.rowsManager.gantt.columnsManager.getLastColumn();
return (firstColumn === undefined || this.model.to < firstColumn.date ||
lastColumn === undefined || this.model.from > lastColumn.endDate);
};
// Updates the pos and size of the task according to the from - to date
Task.prototype.updatePosAndSize = function() {
var oldViewLeft = this.left;
var oldViewWidth = this.width;
var oldTruncatedRight = this.truncatedRight;
var oldTruncatedLeft = this.truncatedLeft;
if (!this.isMoving && this.isOutOfRange()) {
this.modelLeft = undefined;
this.modelWidth = undefined;
} else {
this.modelLeft = this.rowsManager.gantt.getPositionByDate(this.model.from);
this.modelWidth = this.rowsManager.gantt.getPositionByDate(this.model.to) - this.modelLeft;
}
var lastColumn = this.rowsManager.gantt.columnsManager.getLastColumn();
var maxModelLeft = lastColumn ? lastColumn.left + lastColumn.width : 0;
var modelLeft = this.modelLeft;
var modelWidth = this.modelWidth;
if (this.rowsManager.gantt.options.value('daily')) {
modelLeft = this.rowsManager.gantt.getPositionByDate(moment(this.model.from).startOf('day'));
modelWidth = this.rowsManager.gantt.getPositionByDate(moment(this.model.to).endOf('day')) - modelLeft;
}
if (modelLeft === undefined || modelWidth === undefined ||
modelLeft + modelWidth < 0 || modelLeft > maxModelLeft) {
this.left = undefined;
this.width = undefined;
} else {
this.left = Math.min(Math.max(modelLeft, 0), this.rowsManager.gantt.width);
if (modelLeft < 0) {
this.truncatedLeft = true;
if (modelWidth + modelLeft > this.rowsManager.gantt.width) {
this.truncatedRight = true;
this.width = this.rowsManager.gantt.width;
} else {
this.truncatedRight = false;
this.width = modelWidth + modelLeft;
}
} else if (modelWidth + modelLeft > this.rowsManager.gantt.width) {
this.truncatedRight = true;
this.truncatedLeft = false;
this.width = this.rowsManager.gantt.width - modelLeft;
} else {
this.truncatedLeft = false;
this.truncatedRight = false;
this.width = modelWidth;
}
if (this.width < 0) {
this.left = this.left + this.width;
this.width = -this.width;
}
}
this.updateView();
if (!this.rowsManager.gantt.isRefreshingColumns &&
(oldViewLeft !== this.left ||
oldViewWidth !== this.width ||
oldTruncatedRight !== this.truncatedRight ||
oldTruncatedLeft !== this.truncatedLeft)) {
this.rowsManager.gantt.api.tasks.raise.viewChange(this);
}
};
Task.prototype.updateView = function() {
if (this.$element) {
if (this.left === undefined || this.width === undefined) {
this.$element.css('display', 'none');
} else {
this.$element.css({'left': this.left + 'px', 'width': this.width + 'px', 'display': ''});
if (this.model.priority > 0) {
var priority = this.model.priority;
angular.forEach(this.$element.children(), function(element) {
angular.element(element).css('z-index', priority);
});
}
this.$element.toggleClass('gantt-task-milestone', this.isMilestone());
}
}
};
Task.prototype.getBackgroundElement = function() {
if (this.$element !== undefined) {
var backgroundElement = this.$element[0].querySelector('.gantt-task-background');
if (backgroundElement !== undefined) {
backgroundElement = angular.element(backgroundElement);
}
return backgroundElement;
}
};
Task.prototype.getContentElement = function() {
if (this.$element !== undefined) {
var contentElement = this.$element[0].querySelector('.gantt-task-content');
if (contentElement !== undefined) {
contentElement = angular.element(contentElement);
}
return contentElement;
}
};
Task.prototype.getForegroundElement = function() {
if (this.$element !== undefined) {
var foregroundElement = this.$element[0].querySelector('.gantt-task-foreground');
if (foregroundElement !== undefined) {
foregroundElement = angular.element(foregroundElement);
}
return foregroundElement;
}
};
// Expands the start of the task to the specified position (in em)
Task.prototype.setFrom = function(x, magnetEnabled) {
this.model.from = this.rowsManager.gantt.getDateByPosition(x, magnetEnabled);
this.row.setFromTo();
this.updatePosAndSize();
};
// Expands the end of the task to the specified position (in em)
Task.prototype.setTo = function(x, magnetEnabled) {
this.model.to = this.rowsManager.gantt.getDateByPosition(x, magnetEnabled);
this.row.setFromTo();
this.updatePosAndSize();
};
// Moves the task to the specified position (in em)
Task.prototype.moveTo = function(x, magnetEnabled) {
var newTaskRight;
var newTaskLeft;
if (x > this.modelLeft) {
// Driven by right/to side.
this.model.to = this.rowsManager.gantt.getDateByPosition(x + this.modelWidth, magnetEnabled);
newTaskRight = this.rowsManager.gantt.getPositionByDate(this.model.to);
newTaskLeft = newTaskRight - this.modelWidth;
this.model.from = this.rowsManager.gantt.getDateByPosition(newTaskLeft, false);
} else {
// Drive by left/from side.
this.model.from = this.rowsManager.gantt.getDateByPosition(x, magnetEnabled);
newTaskLeft = this.rowsManager.gantt.getPositionByDate(this.model.from);
newTaskRight = newTaskLeft + this.modelWidth;
this.model.to = this.rowsManager.gantt.getDateByPosition(newTaskRight, false);
}
this.row.setFromTo();
this.updatePosAndSize();
};
Task.prototype.clone = function() {
return new Task(this.row, angular.copy(this.model));
};
return Task;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttBody', ['GanttBodyColumns', 'GanttBodyRows', 'GanttBodyBackground', 'GanttBodyForeground', function(BodyColumns, BodyRows, BodyBackground, BodyForeground) {
var Body= function(gantt) {
this.gantt = gantt;
this.background = new BodyBackground(this);
this.foreground = new BodyForeground(this);
this.columns = new BodyColumns(this);
this.rows = new BodyRows(this);
};
return Body;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttBodyBackground', [function() {
var GanttBodyBackground = function(body) {
this.body = body;
};
return GanttBodyBackground;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttBodyColumns', [function() {
var BodyColumns = function(body) {
this.body = body;
};
return BodyColumns;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttBodyForeground', [function() {
var GanttBodyForeground = function(body) {
this.body = body;
};
return GanttBodyForeground;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttBodyRows', [function() {
var BodyRows = function(body) {
this.body = body;
};
return BodyRows;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttHeader', ['GanttHeaderColumns', function(HeaderColumns) {
var Header = function(gantt) {
this.gantt = gantt;
this.columns = new HeaderColumns(this);
this.getHeight = function() {
return this.$element[0].offsetHeight;
};
};
return Header;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttHeaderColumns', [function() {
var HeaderColumns = function($element) {
this.$element = $element;
};
return HeaderColumns;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttScroll', [function() {
var Scroll = function(gantt) {
this.gantt = gantt;
this.gantt.api.registerEvent('scroll', 'scroll');
this.gantt.api.registerMethod('scroll', 'to', Scroll.prototype.scrollTo, this);
this.gantt.api.registerMethod('scroll', 'toDate', Scroll.prototype.scrollToDate, this);
this.gantt.api.registerMethod('scroll', 'left', Scroll.prototype.scrollToLeft, this);
this.gantt.api.registerMethod('scroll', 'right', Scroll.prototype.scrollToRight, this);
this.gantt.api.registerMethod('scroll', 'setWidth', Scroll.prototype.setWidth, this);
};
Scroll.prototype.getScrollLeft = function() {
if (this.$element === undefined) {
return undefined;
} else {
if (this.cachedScrollLeft === undefined) {
this.cachedScrollLeft = this.$element[0].scrollLeft;
}
return this.cachedScrollLeft;
}
};
Scroll.prototype.getScrollWidth = function() {
return this.$element === undefined ? undefined : this.$element[0].scrollWidth;
};
Scroll.prototype.getWidth = function() {
return this.$element === undefined ? undefined : this.$element[0].offsetWidth;
};
Scroll.prototype.setWidth = function(width) {
if (this.$element[0]) {
this.$element[0].offsetWidth = width;
}
};
Scroll.prototype.getBordersWidth = function() {
return this.$element === undefined ? undefined : (this.$element[0].offsetWidth - this.$element[0].clientWidth);
};
Scroll.prototype.getBordersHeight = function() {
return this.$element === undefined ? undefined : (this.$element[0].offsetHeight - this.$element[0].clientHeight);
};
Scroll.prototype.isVScrollbarVisible = function () {
if (this.$element !== undefined) {
return this.$element[0].scrollHeight > this.$element[0].offsetHeight;
}
};
Scroll.prototype.isHScrollbarVisible = function () {
if (this.$element !== undefined) {
return this.$element[0].scrollWidth > this.$element[0].offsetWidth;
}
};
/**
* Scroll to a position
*
* @param {number} position Position to scroll to.
*/
Scroll.prototype.scrollTo = function(position) {
this.$element[0].scrollLeft = position;
this.$element.triggerHandler('scroll');
};
/**
* Scroll to the left side
*
* @param {number} offset Offset to scroll.
*/
Scroll.prototype.scrollToLeft = function(offset) {
this.$element[0].scrollLeft -= offset;
this.$element.triggerHandler('scroll');
};
/**
* Scroll to the right side
*
* @param {number} offset Offset to scroll.
*/
Scroll.prototype.scrollToRight = function(offset) {
this.$element[0].scrollLeft += offset;
this.$element.triggerHandler('scroll');
};
/**
* Scroll to a date
*
* @param {moment} date moment to scroll to.
*/
Scroll.prototype.scrollToDate = function(date) {
var position = this.gantt.getPositionByDate(date);
if (position !== undefined) {
this.$element[0].scrollLeft = position - this.$element[0].offsetWidth / 2;
}
};
return Scroll;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttSide', [function() {
var Side= function(gantt) {
this.gantt = gantt;
};
Side.prototype.getWidth = function() {
if (this.gantt.options.value('showSide')) {
var width = this.gantt.options.value('sideWidth');
if (width === undefined && this.$element !== undefined) {
if (this.$element.css('width') !== undefined) {
this.$element.css('width', '');
}
width = this.$element[0].offsetWidth;
}
if (width !== undefined) {
return width;
}
}
return 0;
};
Side.prototype.show = function(value) {
if (this.$element !== undefined) {
this.$element.toggleClass('ng-hide', !value);
}
};
Side.prototype.isShown = function() {
if (this.$element !== undefined) {
return !this.$element.hasClass('ng-hide');
}
};
return Side;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttTimespan', [function() {
var Timespan = function(gantt, model) {
this.gantt = gantt;
this.model = model;
};
// Updates the pos and size of the timespan according to the from - to date
Timespan.prototype.updatePosAndSize = function() {
this.modelLeft = this.gantt.getPositionByDate(this.model.from);
this.modelWidth = this.gantt.getPositionByDate(this.model.to) - this.modelLeft;
var lastColumn = this.gantt.columnsManager.getLastColumn();
var maxModelLeft = lastColumn ? lastColumn.left + lastColumn.width : 0;
if (this.modelLeft + this.modelWidth < 0 || this.modelLeft > maxModelLeft) {
this.left = undefined;
this.width = undefined;
} else {
this.left = Math.min(Math.max(this.modelLeft, 0), this.gantt.width);
if (this.modelLeft < 0) {
this.truncatedLeft = true;
if (this.modelWidth + this.modelLeft > this.gantt.width) {
this.truncatedRight = true;
this.width = this.gantt.width;
} else {
this.truncatedRight = false;
this.width = this.modelWidth + this.modelLeft;
}
} else if (this.modelWidth + this.modelLeft > this.gantt.width) {
this.truncatedRight = true;
this.truncatedLeft = false;
this.width = this.gantt.width - this.modelLeft;
} else {
this.truncatedLeft = false;
this.truncatedRight = false;
this.width = this.modelWidth;
}
if (this.width < 0) {
this.left = this.left + this.width;
this.width = -this.width;
}
}
this.updateView();
};
Timespan.prototype.updateView = function() {
if (this.$element) {
if (this.left === undefined || this.width === undefined) {
this.$element.css('display', 'none');
} else {
this.$element.css('display', '');
this.$element.css('left', this.left + 'px');
this.$element.css('width', this.width + 'px');
}
}
};
// Expands the start of the timespan to the specified position (in em)
Timespan.prototype.setFrom = function(x) {
this.from = this.gantt.getDateByPosition(x);
this.updatePosAndSize();
};
// Expands the end of the timespan to the specified position (in em)
Timespan.prototype.setTo = function(x) {
this.to = this.gantt.getDateByPosition(x);
this.updatePosAndSize();
};
// Moves the timespan to the specified position (in em)
Timespan.prototype.moveTo = function(x) {
this.from = this.gantt.getDateByPosition(x);
this.to = this.gantt.getDateByPosition(x + this.width);
this.updatePosAndSize();
};
Timespan.prototype.clone = function() {
return new Timespan(this.gantt, angular.copy(this.model));
};
return Timespan;
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttTimespansManager', ['GanttTimespan', function(Timespan) {
var GanttTimespansManager = function(gantt) {
var self = this;
this.gantt = gantt;
this.timespansMap = {};
this.timespans = [];
this.gantt.$scope.$watchCollection('timespans', function(newValue) {
self.clearTimespans();
self.loadTimespans(newValue);
});
this.gantt.api.registerMethod('timespans', 'load', this.loadTimespans, this);
this.gantt.api.registerMethod('timespans', 'remove', this.removeTimespans, this);
this.gantt.api.registerMethod('timespans', 'clear', this.clearTimespans, this);
this.gantt.api.registerEvent('timespans', 'add');
this.gantt.api.registerEvent('timespans', 'remove');
this.gantt.api.registerEvent('timespans', 'change');
};
// Adds or updates timespans
GanttTimespansManager.prototype.loadTimespans = function(timespans) {
if (!angular.isArray(timespans)) {
timespans = timespans !== undefined ? [timespans] : [];
}
this.gantt.$scope.timespans = timespans;
for (var i = 0, l = timespans.length; i < l; i++) {
var timespanModel = timespans[i];
this.gantt.objectModel.cleanTimespan(timespanModel);
this.loadTimespan(timespanModel);
}
};
// Adds a timespan or merges the timespan if there is already one with the same id
GanttTimespansManager.prototype.loadTimespan = function(timespanModel) {
// Copy to new timespan (add) or merge with existing (update)
var timespan, isUpdate = false;
if (timespanModel.id in this.timespansMap) {
timespan = this.timespansMap[timespanModel.id];
timespan.model = timespanModel;
isUpdate = true;
this.gantt.api.timespans.raise.change(timespan);
} else {
timespan = new Timespan(this.gantt, timespanModel);
this.timespansMap[timespanModel.id] = timespan;
this.timespans.push(timespan);
this.gantt.api.timespans.raise.add(timespan);
}
timespan.updatePosAndSize();
return isUpdate;
};
GanttTimespansManager.prototype.removeTimespans = function(timespans) {
if (!angular.isArray(timespans)) {
timespans = [timespans];
}
for (var i = 0, l = timespans.length; i < l; i++) {
var timespanData = timespans[i];
// Delete the timespan
this.removeTimespan(timespanData.id);
}
this.updateVisibleObjects();
};
GanttTimespansManager.prototype.removeTimespan = function(timespanId) {
if (timespanId in this.timespansMap) {
delete this.timespansMap[timespanId]; // Remove from map
var removedTimespan;
var timespan;
for (var i = this.timespans.length - 1; i >= 0; i--) {
timespan = this.timespans[i];
if (timespan.model.id === timespanId) {
removedTimespan = timespan;
this.timespans.splice(i, 1); // Remove from array
break;
}
}
this.gantt.api.timespans.raise.remove(removedTimespan);
return removedTimespan;
}
return undefined;
};
// Removes all timespans
GanttTimespansManager.prototype.clearTimespans = function() {
this.timespansMap = {};
this.timespans = [];
};
GanttTimespansManager.prototype.updateTimespansPosAndSize = function() {
for (var i = 0, l = this.timespans.length; i < l; i++) {
this.timespans[i].updatePosAndSize();
}
};
return GanttTimespansManager;
}]);
}());
(function(){
'use strict';
angular.module('gantt').service('ganttArrays', [function() {
return {
moveToIndex: function(array, oldIndex, newIndex) {
if (newIndex >= array.length) {
var k = newIndex - array.length;
while ((k--) + 1) {
array.push(undefined);
}
}
array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
return array;
},
getRemovedIds: function(newArray, oldArray, idProperty) {
if (idProperty === undefined) {
idProperty = 'id';
}
var i, l;
var removedIds = [];
if (oldArray !== undefined) {
for (i = 0, l = oldArray.length; i < l; i++) {
removedIds.push(oldArray[i][idProperty]);
}
}
if (newArray !== undefined) {
for (i = 0, l = newArray.length; i < l; i++) {
var newObject = newArray[i];
if (newObject[idProperty] !== undefined) {
var newObjectIndex = removedIds.indexOf(newObject[idProperty]);
if (newObjectIndex > -1) {
removedIds.splice(newObjectIndex, 1);
}
}
}
}
return removedIds;
},
indexOfId: function(array, value, idProperties) {
var i;
if (idProperties === undefined) {
idProperties = 'id';
} else if (idProperties instanceof Array) {
for (i = array.length - 1; i >= 0; i--) {
var arrayValue = array[i];
for (var k = 0, l = idProperties.length; k < l; k++) {
arrayValue = arrayValue[idProperties[k]];
}
if (arrayValue === value) {
return i;
}
}
return -1;
}
for (i = array.length - 1; i >= 0; i--) {
if (array[i][idProperties] === value) {
return i;
}
}
return -1;
},
removeId: function(array, value, idProperties) {
var indexOf = this.indexOfId(array, value, idProperties);
if (indexOf > -1) {
return array.splice(indexOf, 1)[0];
}
},
remove: function(array, value) {
var index = array.indexOf(value);
if (index > -1) {
array.splice(index, 1);
return true;
}
return false;
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').service('ganttBinarySearch', [ function() {
// Returns the object on the left and right in an array using the given cmp function.
// The compare function defined which property of the value to compare (e.g.: c => c.left)
return {
getIndicesOnly: function(input, value, comparer, strict) {
var lo = -1, hi = input.length;
while (hi - lo > 1) {
var mid = Math.floor((lo + hi) / 2);
if (strict ? comparer(input[mid]) < value : comparer(input[mid]) <= value) {
lo = mid;
} else {
hi = mid;
}
}
if (!strict && input[lo] !== undefined && comparer(input[lo]) === value) {
hi = lo;
}
return [lo, hi];
},
get: function(input, value, comparer, strict) {
var res = this.getIndicesOnly(input, value, comparer, strict);
return [input[res[0]], input[res[1]]];
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('GanttHierarchy', [function() {
var Hierarchy = function () {
var self = this;
var nameToRow = {};
var idToRow = {};
var nameToChildren = {};
var idToChildren = {};
var nameToParent = {};
var idToParent = {};
var registerChildRow = function(row, childRow) {
if (childRow !== undefined) {
var nameChildren = nameToChildren[row.model.name];
if (nameChildren === undefined) {
nameChildren = [];
nameToChildren[row.model.name] = nameChildren;
}
nameChildren.push(childRow);
var idChildren = idToChildren[row.model.id];
if (idChildren === undefined) {
idChildren = [];
idToChildren[row.model.id] = idChildren;
}
idChildren.push(childRow);
nameToParent[childRow.model.name] = row;
idToParent[childRow.model.id] = row;
}
};
this.refresh = function(rows) {
nameToRow = {};
idToRow = {};
nameToChildren = {};
idToChildren = {};
nameToParent = {};
idToParent = {};
angular.forEach(rows, function(row) {
nameToRow[row.model.name] = row;
idToRow[row.model.id] = row;
});
angular.forEach(rows, function(row) {
if (row.model.parent !== undefined) {
var parentRow = nameToRow[row.model.parent];
if (parentRow === undefined) {
parentRow = idToRow[row.model.parent];
}
if (parentRow !== undefined) {
registerChildRow(parentRow, row);
}
}
if (row.model.children !== undefined) {
angular.forEach(row.model.children, function(childRowNameOrId) {
var childRow = nameToRow[childRowNameOrId];
if (childRow === undefined) {
childRow = idToRow[childRowNameOrId];
}
if (childRow !== undefined) {
registerChildRow(row, childRow);
}
});
}
});
var rootRows = [];
angular.forEach(rows, function(row) {
if (self.parent(row) === undefined) {
rootRows.push(row);
}
});
return rootRows;
};
this.children = function(row) {
var children = idToChildren[row.model.id];
return children;
};
this.descendants = function(row) {
var descendants = [];
var children = self.children(row);
descendants.push.apply(descendants, children);
if (children !== undefined) {
angular.forEach(children, function(child) {
var childDescendants = self.descendants(child);
descendants.push.apply(descendants, childDescendants);
});
}
return descendants;
};
this.parent = function(row) {
var parent = idToParent[row.model.id];
return parent;
};
this.ancestors = function(row) {
var ancestors = [];
var parent = self.parent(row);
while (parent !== undefined) {
ancestors.push(parent);
parent = self.parent(parent);
}
return ancestors;
};
};
return Hierarchy;
}]);
}());
(function() {
'use strict';
angular.module('gantt').service('ganttUtils', [function() {
return {
createBoundedWrapper: function(object, method) {
return function() {
return method.apply(object, arguments);
};
},
firstProperty: function(objects, propertyName, defaultValue) {
for (var i = 0, l = objects.length; i < l; i++) {
var object = objects[i];
if (object !== undefined && propertyName in object) {
if (object[propertyName] !== undefined) {
return object[propertyName];
}
}
}
return defaultValue;
},
random4: function() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
},
randomUuid: function() {
return this.random4() + this.random4() + '-' + this.random4() + '-' + this.random4() + '-' +
this.random4() + '-' + this.random4() + this.random4() + this.random4();
},
newId: (function() {
var seedId = new Date().getTime();
return function() {
return seedId += 1;
};
})()
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').filter('ganttColumnLimit', [ 'ganttBinarySearch', function(bs) {
// Returns only the columns which are visible on the screen
var leftComparator = function(c) {
return c.left;
};
return function(input, gantt) {
var scrollLeft = gantt.scroll.getScrollLeft();
var scrollContainerWidth = gantt.getWidth() - gantt.side.getWidth();
if (scrollContainerWidth > 0) {
var start = bs.getIndicesOnly(input, scrollLeft, leftComparator)[0];
var end = bs.getIndicesOnly(input, scrollLeft + scrollContainerWidth, leftComparator)[1];
return input.slice(start, end);
} else {
return input.slice();
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').filter('ganttTaskLimit', [function() {
// Returns only the tasks which are visible on the screen
// Use the task width and position to decide if a task is still visible
return function(input, gantt) {
var firstColumn = gantt.columnsManager.getFirstColumn();
var lastColumn = gantt.columnsManager.getLastColumn();
if (firstColumn !== undefined && lastColumn !== undefined) {
var fromDate = firstColumn.date;
var toDate = lastColumn.endDate;
var res = [];
var scrollLeft = gantt.scroll.getScrollLeft();
var scrollContainerWidth = gantt.getWidth() - gantt.side.getWidth();
for (var i = 0, l = input.length; i < l; i++) {
var task = input[i];
if (task.active) {
res.push(task);
} else {
// If the task can be drawn with gantt columns only.
if (task.model.to >= fromDate && task.model.from <= toDate) {
if (task.left === undefined) {
task.updatePosAndSize();
}
// If task has a visible part on the screen
if (!scrollContainerWidth ||
task.left >= scrollLeft && task.left <= scrollLeft + scrollContainerWidth ||
task.left + task.width >= scrollLeft && task.left + task.width <= scrollLeft + scrollContainerWidth ||
task.left < scrollLeft && task.left + task.width > scrollLeft + scrollContainerWidth) {
res.push(task);
}
}
}
}
return res;
} else {
return input.splice();
}
};
}]);
}());
(function() {
'use strict';
angular.module('gantt').directive('ganttResizer', ['$document', '$parse', '$timeout', 'ganttMouseOffset', function($document, $parse, $timeout, mouseOffset) {
return {
restrict: 'A',
require: '^gantt',
scope: {
targetElement: '=ganttResizer',
enabled: '@?ganttResizerEnabled'
},
link: function ($scope, $element, $attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
var eventTopic = $attrs.ganttResizerEventTopic;
if ($scope.enabled === undefined) {
$scope.enabled = true;
}
$attrs.$observe('ganttResizerEnabled', function(value) {
$scope.enabled = $parse(value)();
});
$scope.$watch('enabled', function (value) {
if (value === undefined) {
value = true;
}
$element.toggleClass('gantt-resizer-enabled', value);
if (value) {
$element.on('dblclick', dblclick);
$element.on('mousedown', mousedown);
} else {
$element.off('dblclick', dblclick);
$element.off('mousedown', mousedown);
}
});
function dblclick(event) {
event.preventDefault();
setWidth(undefined);
}
function mousedown(event) {
event.preventDefault();
if (eventTopic !== undefined) {
api[eventTopic].raise.resizeBegin(getWidth());
}
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
}
function mousemove(event) {
$scope.$evalAsync(function (){
var offset = mouseOffset.getOffsetForElement($scope.targetElement[0], event);
var maxWidth = ganttCtrl.gantt.getWidth()-ganttCtrl.gantt.scroll.getBordersWidth();
var width = Math.min(Math.max(offset.x, 0), maxWidth);
setWidth(width);
});
}
function mouseup() {
if (eventTopic !== undefined) {
api[eventTopic].raise.resizeEnd(getWidth());
}
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
$scope.$watch(function() {
return getWidth();
}, function(newValue, oldValue) {
if (newValue !== oldValue) {
$scope.targetElement.css('width', newValue + 'px');
// Setting width again is required when min-width of max-width is set on targetElement.
// This avoid going to a smaller or bigger value than targetElement capabilities.
// Call of 'offsetWidth' is slow. Behaviour needs to be improved.
if ($scope.targetElement[0].offsetWidth > 0) {
setWidth($scope.targetElement[0].offsetWidth);
}
}
});
function setWidth(width) {
if (width !== getWidth()) {
ganttCtrl.gantt.options.set($attrs.resizerWidth, width);
if (eventTopic !== undefined) {
api[eventTopic].raise.resize(width);
}
$timeout(function() {
ganttCtrl.gantt.columnsManager.updateColumnsMeta();
});
}
}
function getWidth() {
return ganttCtrl.gantt.options.value($attrs.resizerWidth);
}
if (eventTopic) {
api.registerEvent(eventTopic, 'resize');
api.registerEvent(eventTopic, 'resizeBegin');
api.registerEvent(eventTopic, 'resizeEnd');
api.registerMethod(eventTopic, 'setWidth', setWidth, this);
api.registerMethod(eventTopic, 'getWidth', getWidth, this);
}
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttHorizontalScrollReceiver', function() {
// The element with this attribute will scroll at the same time as the scrollSender element
return {
restrict: 'A',
require: '^ganttScrollManager',
link: function(scope, element, attrs, ganttScrollManagerCtrl) {
ganttScrollManagerCtrl.registerHorizontalReceiver(element);
}
};
});
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttScrollManager', function() {
// The element with this attribute will scroll at the same time as the scrollSender element
return {
restrict: 'A',
scope: {},
controller: ['$scope', function($scope) {
$scope.horizontal = [];
$scope.vertical = [];
this.registerVerticalReceiver = function (element) {
element.css('position', 'relative');
$scope.vertical.push(element[0]);
};
this.registerHorizontalReceiver = function (element) {
element.css('position', 'relative');
$scope.horizontal.push(element[0]);
};
this.getHorizontalRecievers = function() {
return $scope.horizontal;
};
this.getVerticalRecievers = function() {
return $scope.vertical;
};
}]
};
});
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttScrollSender', [function() {
// Updates the element which are registered for the horizontal or vertical scroll event
return {
restrict: 'A',
require: ['^gantt', '^ganttScrollManager'],
link: function(scope, element, attrs, controllers) {
var el = element[0];
var updateListeners = function() {
var i, l;
var vertical = controllers[1].getVerticalRecievers();
for (i = 0, l = vertical.length; i < l; i++) {
var vElement = vertical[i];
if (vElement.parentNode.scrollTop !== el.scrollTop) {
vElement.parentNode.scrollTop = el.scrollTop;
}
}
var horizontal = controllers[1].getHorizontalRecievers();
for (i = 0, l = horizontal.length; i < l; i++) {
var hElement = horizontal[i];
if (hElement.parentNode.scrollLeft !== el.scrollLeft) {
hElement.parentNode.scrollLeft = el.scrollLeft;
}
}
};
element.bind('scroll', updateListeners);
scope.$watch(function() {
return controllers[0].gantt.width;
}, function(newValue, oldValue) {
if (newValue !== oldValue) {
var horizontal = controllers[1].getHorizontalRecievers();
for (var i = 0, l = horizontal.length; i < l; i++) {
var hElement = horizontal[i];
hElement.style.width = newValue + 'px';
}
}
});
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttScrollable', ['GanttDirectiveBuilder', '$timeout', 'ganttDebounce', 'moment', function(Builder, $timeout, debounce, moment) {
var builder = new Builder('ganttScrollable');
builder.controller = function($scope, $element) {
$scope.gantt.scroll.$element = $element;
var lastScrollLeft;
var autoExpandTimer;
var autoExpandColumns = function(el, date, direction) {
var autoExpand = $scope.gantt.options.value('autoExpand');
if (autoExpand !== 'both' && autoExpand !== true && autoExpand !== direction) {
return;
}
var from, to;
var viewScale = $scope.gantt.options.value('viewScale');
viewScale = viewScale.trim();
if (viewScale.charAt(viewScale.length - 1) === 's') {
viewScale = viewScale.substring(0, viewScale.length - 1);
}
var viewScaleValue;
var viewScaleUnit;
var splittedViewScale;
if (viewScale) {
splittedViewScale = viewScale.split(' ');
}
if (splittedViewScale && splittedViewScale.length > 1) {
viewScaleValue = parseFloat(splittedViewScale[0]);
viewScaleUnit = splittedViewScale[splittedViewScale.length - 1];
} else {
viewScaleValue = 1;
viewScaleUnit = viewScale;
}
if (direction === 'left') {
from = moment(date).add(-5 * viewScaleValue, viewScaleUnit);
$scope.fromDate = from;
} else {
to = moment(date).add(5 * viewScaleValue, viewScaleUnit);
$scope.toDate = to;
}
$scope.gantt.api.scroll.raise.scroll(el.scrollLeft, date, direction);
};
$element.bind('scroll', debounce(function() {
var el = $element[0];
var currentScrollLeft = el.scrollLeft;
var direction;
var date;
$scope.gantt.scroll.cachedScrollLeft = currentScrollLeft;
$scope.gantt.columnsManager.updateVisibleColumns();
$scope.gantt.rowsManager.updateVisibleObjects();
if (currentScrollLeft < lastScrollLeft && currentScrollLeft === 0) {
direction = 'left';
date = $scope.gantt.columnsManager.from;
} else if (currentScrollLeft > lastScrollLeft && el.offsetWidth + currentScrollLeft >= el.scrollWidth - 1) {
direction = 'right';
date = $scope.gantt.columnsManager.to;
}
lastScrollLeft = currentScrollLeft;
if (date !== undefined) {
if (autoExpandTimer) {
$timeout.cancel(autoExpandTimer);
}
autoExpandTimer = $timeout(function() {
autoExpandColumns(el, date, direction);
}, 300);
} else {
$scope.gantt.api.scroll.raise.scroll(currentScrollLeft);
}
}, 5));
$scope.getScrollableCss = function() {
var css = {};
var maxHeight = $scope.gantt.options.value('maxHeight');
if (maxHeight > 0) {
css['max-height'] = maxHeight - $scope.gantt.header.getHeight() + 'px';
css['overflow-y'] = 'auto';
if ($scope.gantt.scroll.isVScrollbarVisible()) {
css['border-right'] = 'none';
}
}
var columnWidth = this.gantt.options.value('columnWidth');
var bodySmallerThanGantt = $scope.gantt.width === 0 ? false: $scope.gantt.width < $scope.gantt.getWidth() - $scope.gantt.side.getWidth();
if (columnWidth !== undefined && bodySmallerThanGantt) {
css.width = ($scope.gantt.width + this.gantt.scroll.getBordersWidth()) + 'px';
}
return css;
};
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttVerticalScrollReceiver', function() {
// The element with this attribute will scroll at the same time as the scrollSender element
return {
restrict: 'A',
require: '^ganttScrollManager',
link: function(scope, element, attrs, ganttScrollManagerCtrl) {
ganttScrollManagerCtrl.registerVerticalReceiver(element);
}
};
});
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttElementHeightListener', [function() {
return {
restrict: 'A',
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
var scopeVariable = $attrs.ganttElementHeightListener;
if (scopeVariable === '') {
scopeVariable = 'ganttElementHeight';
}
var effectiveScope = $scope;
while(scopeVariable.indexOf('$parent.') === 0) {
scopeVariable = scopeVariable.substring('$parent.'.length);
effectiveScope = effectiveScope.$parent;
}
effectiveScope.$watch(function() {
return $element[0].offsetHeight;
}, function(newValue) {
if (newValue > 0) {
effectiveScope[scopeVariable] = newValue;
}
});
}]
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttElementWidthListener', [function() {
return {
restrict: 'A',
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
var scopeVariable = $attrs.ganttElementWidthListener;
if (scopeVariable === '') {
scopeVariable = 'ganttElementWidth';
}
var effectiveScope = $scope;
while(scopeVariable.indexOf('$parent.') === 0) {
scopeVariable = scopeVariable.substring('$parent.'.length);
effectiveScope = effectiveScope.$parent;
}
effectiveScope.$watch(function() {
return $element[0].offsetWidth;
}, function(newValue) {
if (newValue > 0) {
effectiveScope[scopeVariable] = newValue;
}
});
}]
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttBody', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttBody');
builder.controller = function($scope, $element) {
$scope.gantt.body.$element = $element;
$scope.gantt.body.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttBodyBackground', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttBodyBackground');
builder.controller = function($scope, $element) {
$scope.gantt.body.background.$element = $element;
$scope.gantt.body.background.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttBodyColumns', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttBodyColumns');
builder.controller = function($scope, $element) {
$scope.gantt.body.columns.$element = $element;
$scope.gantt.body.background.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttBodyForeground', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttBodyForeground');
builder.controller = function($scope, $element) {
$scope.gantt.body.foreground.$element = $element;
$scope.gantt.body.foreground.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttBodyRows', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttBodyRows');
builder.controller = function($scope, $element) {
$scope.gantt.body.rows.$element = $element;
$scope.gantt.body.rows.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttColumn', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttColumn');
builder.controller = function($scope, $element) {
$scope.column.$element = $element;
$scope.column.$scope = $scope;
$scope.column.updateView();
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttColumnHeader', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttColumnHeader');
builder.controller = function($scope, $element) {
$scope.column.$element = $element;
$scope.column.$scope = $scope;
$scope.column.updateView();
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttHeader', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttHeader');
builder.controller = function($scope, $element) {
$scope.gantt.header.$element = $element;
$scope.gantt.header.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttHeaderColumns', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttHeaderColumns');
builder.controller = function($scope, $element) {
$scope.gantt.header.columns.$element = $element;
$scope.gantt.header.columns.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttRow', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttRow');
builder.controller = function($scope, $element) {
$scope.row.$element = $element;
$scope.row.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttRowBackground', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttRowBackground');
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttRowLabel', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttRowLabel');
builder.restrict = 'A';
builder.templateUrl = undefined;
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttScrollableHeader', ['GanttDirectiveBuilder', 'ganttLayout', function(Builder, layout) {
var builder = new Builder('ganttScrollableHeader');
builder.controller = function($scope) {
var scrollBarWidth = layout.getScrollBarWidth();
//var oldMaxHeightActivated = false;
$scope.getScrollableHeaderCss = function() {
var css = {};
var maxHeightActivated = $scope.gantt.scroll.isVScrollbarVisible();
var vScrollbarWidth = maxHeightActivated ? scrollBarWidth: 0;
var columnWidth = this.gantt.options.value('columnWidth');
var bodySmallerThanGantt = $scope.gantt.width === 0 ? false: $scope.gantt.width < $scope.gantt.getWidth() - $scope.gantt.side.getWidth();
if (columnWidth !== undefined && bodySmallerThanGantt) {
css.width = ($scope.gantt.width - vScrollbarWidth + this.gantt.scroll.getBordersWidth()) + 'px';
} else if (maxHeightActivated) {
css.width = $scope.gantt.getWidth() - $scope.gantt.side.getWidth() - vScrollbarWidth + 'px';
}
/*
if (oldMaxHeightActivated !== maxHeightActivated) {
oldMaxHeightActivated = maxHeightActivated;
$scope.gantt.columnsManager.updateColumnsMeta();
}
*/
return css;
};
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttSide', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttSide');
builder.controller = function($scope, $element) {
$scope.gantt.side.$element = $element;
$scope.gantt.side.$scope = $scope;
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttSideBackground', ['GanttDirectiveBuilder', 'ganttLayout', function(Builder, layout) {
var builder = new Builder('ganttSideBackground');
builder.controller = function($scope) {
var hScrollBarHeight = layout.getScrollBarHeight();
$scope.getMaxHeightCss = function() {
var css = {};
if ($scope.maxHeight) {
var bodyScrollBarHeight = $scope.gantt.scroll.isHScrollbarVisible() ? hScrollBarHeight : 0;
css['max-height'] = $scope.maxHeight - bodyScrollBarHeight - $scope.gantt.header.getHeight() + 'px';
}
return css;
};
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttSideContent', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttSideContent');
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttTask', ['GanttDirectiveBuilder', 'moment', function(Builder, moment) {
var builder = new Builder('ganttTask');
builder.controller = function($scope, $element) {
$scope.task.$element = $element;
$scope.task.$scope = $scope;
$scope.getTaskContent = function() {
if ($scope.task.model.content !== undefined) {
return $scope.task.model.content;
}
return $scope.task.rowsManager.gantt.options.value('taskContent');
};
$scope.simplifyMoment = function(d) {
return moment.isMoment(d) ? d.unix() : d;
};
$scope.$watchGroup(['simplifyMoment(task.model.from)', 'simplifyMoment(task.model.to)'], function() {
$scope.task.updatePosAndSize();
});
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttTaskBackground', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttTaskBackground');
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttTaskContent', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttTaskContent');
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttTaskForeground', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttTaskForeground');
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttTimeFrame', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttTimeFrame');
builder.controller = function($scope, $element) {
$scope.timeFrame.$element = $element;
$scope.timeFrame.$scope = $scope;
$scope.timeFrame.updateView();
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').directive('ganttTimespan', ['GanttDirectiveBuilder', function(Builder) {
var builder = new Builder('ganttTimespan');
builder.controller = function($scope, $element) {
$scope.timespan.$element = $element;
$scope.timespan.$scope = $scope;
$scope.timespan.updateView();
};
return builder.build();
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('ganttDebounce', ['$timeout', function($timeout) {
function debounce(fn, timeout, invokeApply) {
var nthCall = 0;
return function() {
var self = this;
var argz = arguments;
nthCall++;
var later = (function(version) {
return function() {
if (version === nthCall) {
return fn.apply(self, argz);
}
};
})(nthCall);
return $timeout(later, timeout, invokeApply === undefined ? true: invokeApply);
};
}
return debounce;
}]);
}());
(function(){
'use strict';
angular.module('gantt').service('GanttDirectiveBuilder', ['$templateCache', function($templateCache) {
var DirectiveBuilder = function DirectiveBuilder(directiveName, templateUrl, require, restrict) {
var self = this;
this.directiveName = directiveName;
this.templateUrl = templateUrl === undefined ? 'template/' + directiveName + '.tmpl.html' : templateUrl;
this.require = require === undefined ? '^gantt' : require;
this.restrict = restrict === undefined ? 'E' : restrict;
this.scope = false;
this.transclude = true;
this.replace = true;
this.build = function() {
var directiveName = self.directiveName;
var templateUrl = self.templateUrl;
var controllerFunction = self.controller;
var directive = {
restrict: self.restrict,
require: self.require,
transclude: self.transclude,
replace: self.replace,
scope: self.scope,
templateUrl: function(tElement, tAttrs) {
if (tAttrs.templateUrl !== undefined) {
templateUrl = tAttrs.templateUrl;
}
if (tAttrs.template !== undefined) {
$templateCache.put(templateUrl, tAttrs.template);
}
return templateUrl;
},
compile: function () {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
scope.gantt.api.directives.raise.preLink(directiveName, scope, iElement, iAttrs, controller);
},
post: function postLink(scope, iElement, iAttrs, controller) {
scope.gantt.api.directives.raise.postLink(directiveName, scope, iElement, iAttrs, controller);
}
};
},
controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
var controller = this;
if (controllerFunction !== undefined) {
controllerFunction($scope, $element, $attrs, controller);
}
$scope.gantt.api.directives.raise.controller(directiveName, $scope, $element, $attrs, controller);
$scope.$on('$destroy', function() {
$scope.gantt.api.directives.raise.destroy(directiveName, $scope, $element, $attrs, controller);
});
$scope.$evalAsync(function() {
$scope.gantt.api.directives.raise.new(directiveName, $scope, $element, $attrs, controller);
});
}]
};
if (!templateUrl) {
delete directive.templateUrl;
delete directive.replace;
delete directive.transclude;
}
return directive;
};
};
return DirectiveBuilder;
}]);
}());
(function() {
'use strict';
angular.module('gantt').service('ganttDom', ['$document', function($document) {
return {
elementFromPoint: function(x, y) {
return $document[0].elementFromPoint(x, y);
},
elementsFromPoint: function(x, y, depth) {
var elements = [], previousPointerEvents = [], cDepth = 0, current, i, l, d;
// get all elements via elementFromPoint, and remove them from hit-testing in order
while ((current = this.elementFromPoint(x, y)) && elements.indexOf(current) === -1 && current !== null &&
(depth === undefined || cDepth < depth)) {
// push the element and its current style
elements.push(current);
previousPointerEvents.push({
value: current.style.getPropertyValue('visibility'),
priority: current.style.getPropertyPriority('visibility')
});
// add "pointer-events: none", to get to the underlying element
current.style.setProperty('visibility', 'hidden', 'important');
cDepth++;
}
// restore the previous pointer-events values
for (i = 0, l = previousPointerEvents.length; i < l; i++) {
d = previousPointerEvents[i];
elements[i].style.setProperty('visibility', d.value ? d.value : '', d.priority);
}
return elements;
},
findElementFromPoint: function(x, y, checkFunction) {
var elements = [], previousPointerEvents = [], cDepth = 0, current, found, i, l, d;
// get all elements via elementFromPoint, and remove them from hit-testing in order
while ((current = this.elementFromPoint(x, y)) && elements.indexOf(current) === -1 && current !== null) {
// push the element and its current style
elements.push(current);
previousPointerEvents.push({
value: current.style.getPropertyValue('visibility'),
priority: current.style.getPropertyPriority('visibility')
});
// add "visibility: hidden", to get to the underlying element.
// Would be better with pointer-events: none, but IE<11 doesn't support this.
current.style.setProperty('visibility', 'hidden', 'important');
cDepth++;
if (checkFunction(current)) {
found = current;
break;
}
}
// restore the previous pointer-events values
for (i = 0, l = previousPointerEvents.length; i < l; i++) {
d = previousPointerEvents[i];
elements[i].style.setProperty('visibility', d.value ? d.value : '', d.priority);
}
return found;
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').service('ganttEnableNgAnimate', ['$injector', function($injector) {
var ngAnimate;
try {
ngAnimate = $injector.get('$animate');
} catch (e) {
}
if (ngAnimate !== undefined) {
return function(element, enabled) {
if (angular.version.major >= 1 && angular.version.minor >= 4) {
// AngularJS 1.4 breaking change, arguments are flipped.
ngAnimate.enabled(element, enabled);
} else {
ngAnimate.enabled(enabled, element);
}
};
} else {
return angular.noop;
}
}]);
}());
(function() {
'use strict';
angular.module('gantt').directive('ganttBindCompileHtml', ['$compile', function($compile) {
return {
restrict: 'A',
require: '^gantt',
link: function(scope, element, attrs, ganttCtrl) {
scope.scope = ganttCtrl.gantt.$scope.$parent;
scope.$watch(function() {
return scope.$eval(attrs.ganttBindCompileHtml);
}, function(value) {
element.html(value);
$compile(element.contents())(scope);
});
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').service('ganttLayout', ['$document', function($document) {
return {
/**
* Compute the width of scrollbar.
*
* @returns {number} width of the scrollbar, in px.
*/
getScrollBarWidth: function() {
var inner = $document[0].createElement('p');
inner.style.width = '100%';
inner.style.height = '200px';
var outer = $document[0].createElement('div');
outer.style.position = 'absolute';
outer.style.top = '0px';
outer.style.left = '0px';
outer.style.visibility = 'hidden';
outer.style.width = '200px';
outer.style.height = '150px';
outer.style.overflow = 'hidden';
outer.appendChild (inner);
$document[0].body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 === w2) {
w2 = outer.clientWidth;
}
$document[0].body.removeChild (outer);
return (w1 - w2);
},
/**
* Compute the height of scrollbar.
*
* @returns {number} height of the scrollbar, in px.
*/
getScrollBarHeight: function() {
var inner = $document[0].createElement('p');
inner.style.width = '200px;';
inner.style.height = '100%';
var outer = $document[0].createElement('div');
outer.style.position = 'absolute';
outer.style.top = '0px';
outer.style.left = '0px';
outer.style.visibility = 'hidden';
outer.style.width = '150px';
outer.style.height = '200px';
outer.style.overflow = 'hidden';
outer.appendChild (inner);
$document[0].body.appendChild (outer);
var h1 = inner.offsetHeight;
outer.style.overflow = 'scroll';
var h2 = inner.offsetHeight;
if (h1 === h2) {
h2 = outer.clientHeight;
}
$document[0].body.removeChild (outer);
return (h1 - h2);
},
setColumnsWidthFactor: function(columns, widthFactor, originalLeftOffset) {
if (!columns) {
return;
}
if (!originalLeftOffset) {
originalLeftOffset = 0;
}
angular.forEach(columns, function(column) {
column.left = (widthFactor * (column.originalSize.left + originalLeftOffset)) - originalLeftOffset;
column.width = widthFactor * column.originalSize.width;
angular.forEach(column.timeFrames, function(timeFrame) {
timeFrame.left = widthFactor * timeFrame.originalSize.left;
timeFrame.width = widthFactor * timeFrame.originalSize.width;
});
});
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').service('ganttMouseButton', [ function() {
// Mouse button cross browser normalization
return {
getButton: function(e) {
e = e || window.event;
if (!e.which) {
if (e.button === undefined) {
return 1;
}
return e.button < 2 ? 1 : e.button === 4 ? 2 : 3;
} else {
return e.which;
}
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').service('ganttMouseOffset', [ function() {
// Mouse offset support for lesser browsers (read IE 8)
return {
getTouch: function(evt) {
if (evt.touches !== undefined) {
return evt.touches[0];
}
return evt;
},
getOffset: function(evt) {
if (evt.offsetX && evt.offsetY) {
return { x: evt.offsetX, y: evt.offsetY };
}
if (evt.layerX && evt.layerY) {
return { x: evt.layerX, y: evt.layerY };
}
return this.getOffsetForElement(evt.target, evt);
},
getOffsetForElement: function(el, evt) {
var bb = el.getBoundingClientRect();
return { x: evt.clientX - bb.left, y: evt.clientY - bb.top };
}
};
}]);
}());
(function(){
'use strict';
angular.module('gantt').factory('ganttSmartEvent', [function() {
// Auto released the binding when the scope is destroyed. Use if an event is registered on another element than the scope.
function smartEvent($scope, $element, event, fn) {
$scope.$on('$destroy', function() {
$element.unbind(event, fn);
});
return {
bindOnce: function() {
$element.one(event, fn);
},
bind: function() {
$element.bind(event, fn);
},
unbind: function() {
$element.unbind(event, fn);
}
};
}
return smartEvent;
}]);
}());
angular.module('gantt.templates', []).run(['$templateCache', function($templateCache) {
$templateCache.put('template/gantt.tmpl.html',
'<div class="gantt unselectable" ng-cloak gantt-scroll-manager gantt-element-width-listener="ganttElementWidth">\n' +
' <gantt-side>\n' +
' <gantt-side-background>\n' +
' </gantt-side-background>\n' +
' <gantt-side-content>\n' +
' </gantt-side-content>\n' +
' <div gantt-resizer="gantt.side.$element" gantt-resizer-event-topic="side" gantt-resizer-enabled="{{$parent.gantt.options.value(\'allowSideResizing\')}}" resizer-width="sideWidth" class="gantt-resizer">\n' +
' <div ng-show="$parent.gantt.options.value(\'allowSideResizing\')" class="gantt-resizer-display"></div>\n' +
' </div>\n' +
' </gantt-side>\n' +
' <gantt-scrollable-header>\n' +
' <gantt-header gantt-element-height-listener="$parent.ganttHeaderHeight">\n' +
' <gantt-header-columns>\n' +
' <div ng-repeat="header in gantt.columnsManager.visibleHeaders track by $index">\n' +
' <div class="gantt-header-row" ng-class="{\'gantt-header-row-last\': $last, \'gantt-header-row-first\': $first}">\n' +
' <gantt-column-header ng-repeat="column in header"></gantt-column-header>\n' +
' </div>\n' +
' </div>\n' +
' </gantt-header-columns>\n' +
' </gantt-header>\n' +
' </gantt-scrollable-header>\n' +
' <gantt-scrollable>\n' +
' <gantt-body>\n' +
' <gantt-body-background>\n' +
' <gantt-row-background ng-repeat="row in gantt.rowsManager.visibleRows track by row.model.id"></gantt-row-background>\n' +
' </gantt-body-background>\n' +
' <gantt-body-foreground>\n' +
' <div class="gantt-current-date-line" ng-show="currentDate === \'line\' && gantt.currentDateManager.position >= 0 && gantt.currentDateManager.position <= gantt.width" ng-style="{\'left\': gantt.currentDateManager.position + \'px\' }"></div>\n' +
' </gantt-body-foreground>\n' +
' <gantt-body-columns>\n' +
' <gantt-column ng-repeat="column in gantt.columnsManager.visibleColumns">\n' +
' <gantt-time-frame ng-repeat="timeFrame in column.visibleTimeFrames"></gantt-time-frame>\n' +
' </gantt-column>\n' +
' </gantt-body-columns>\n' +
' <div ng-if="gantt.columnsManager.visibleColumns == 0" style="background-color: #808080"></div>\n' +
' <gantt-body-rows>\n' +
' <gantt-timespan ng-repeat="timespan in gantt.timespansManager.timespans track by timespan.model.id"></gantt-timespan>\n' +
' <gantt-row ng-repeat="row in gantt.rowsManager.visibleRows track by row.model.id">\n' +
' <gantt-task ng-repeat="task in row.visibleTasks track by task.model.id">\n' +
' </gantt-task>\n' +
' </gantt-row>\n' +
' </gantt-body-rows>\n' +
' </gantt-body>\n' +
' </gantt-scrollable>\n' +
'\n' +
' <!-- Plugins -->\n' +
' <ng-transclude></ng-transclude>\n' +
'\n' +
' <!--\n' +
' ******* Inline templates *******\n' +
' You can specify your own templates by either changing the default ones below or by\n' +
' adding an attribute template-url="<url to your template>" on the specific element.\n' +
' -->\n' +
'\n' +
' <!-- Body template -->\n' +
' <script type="text/ng-template" id="template/ganttBody.tmpl.html">\n' +
' <div ng-transclude class="gantt-body" ng-style="{\'width\': gantt.width > 0 ? gantt.width +\'px\' : undefined}"></div>\n' +
' </script>\n' +
'\n' +
' <!-- Header template -->\n' +
' <script type="text/ng-template" id="template/ganttHeader.tmpl.html">\n' +
' <div ng-transclude class="gantt-header"\n' +
' ng-show="gantt.columnsManager.columns.length > 0 && gantt.columnsManager.headers.length > 0"></div>\n' +
' </script>\n' +
'\n' +
' <!-- Side template -->\n' +
' <script type="text/ng-template" id="template/ganttSide.tmpl.html">\n' +
' <div ng-transclude class="gantt-side" style="width: auto;"></div>\n' +
' </script>\n' +
'\n' +
' <!-- Side content template-->\n' +
' <script type="text/ng-template" id="template/ganttSideContent.tmpl.html">\n' +
' <div class="gantt-side-content">\n' +
' </div>\n' +
' </script>\n' +
'\n' +
' <!-- Header columns template -->\n' +
' <script type="text/ng-template" id="template/ganttHeaderColumns.tmpl.html">\n' +
' <div ng-transclude class="gantt-header-columns"\n' +
' gantt-horizontal-scroll-receiver></div>\n' +
' </script>\n' +
'\n' +
' <script type="text/ng-template" id="template/ganttColumnHeader.tmpl.html">\n' +
' <div class="gantt-column-header" ng-class="{\'gantt-column-header-last\': $last, \'gantt-column-header-first\': $first}">{{::column.label}}</div>\n' +
' </script>\n' +
'\n' +
' <!-- Body background template -->\n' +
' <script type="text/ng-template" id="template/ganttBodyBackground.tmpl.html">\n' +
' <div ng-transclude class="gantt-body-background"></div>\n' +
' </script>\n' +
'\n' +
' <!-- Body foreground template -->\n' +
' <script type="text/ng-template" id="template/ganttBodyForeground.tmpl.html">\n' +
' <div ng-transclude class="gantt-body-foreground"></div>\n' +
' </script>\n' +
'\n' +
' <!-- Body columns template -->\n' +
' <script type="text/ng-template" id="template/ganttBodyColumns.tmpl.html">\n' +
' <div ng-transclude class="gantt-body-columns"></div>\n' +
' </script>\n' +
'\n' +
' <script type="text/ng-template" id="template/ganttColumn.tmpl.html">\n' +
' <div ng-transclude class="gantt-column gantt-foreground-col" ng-class="{\'gantt-column-last\': $last, \'gantt-column-first\': $first}"></div>\n' +
' </script>\n' +
'\n' +
' <script type="text/ng-template" id="template/ganttTimeFrame.tmpl.html">\n' +
' <div class="gantt-timeframe"></div>\n' +
' </script>\n' +
'\n' +
' <!-- Scrollable template -->\n' +
' <script type="text/ng-template" id="template/ganttScrollable.tmpl.html">\n' +
' <div ng-transclude class="gantt-scrollable" gantt-scroll-sender ng-style="getScrollableCss()"></div>\n' +
' </script>\n' +
'\n' +
' <script type="text/ng-template" id="template/ganttScrollableHeader.tmpl.html">\n' +
' <div ng-transclude class="gantt-scrollable-header" ng-style="getScrollableHeaderCss()"></div>\n' +
' </script>\n' +
'\n' +
' <!-- Rows template -->\n' +
' <script type="text/ng-template" id="template/ganttBodyRows.tmpl.html">\n' +
' <div ng-transclude class="gantt-body-rows"></div>\n' +
' </script>\n' +
'\n' +
' <!-- Timespan template -->\n' +
' <script type="text/ng-template" id="template/ganttTimespan.tmpl.html">\n' +
' <div class="gantt-timespan" ng-class="timespan.model.classes">\n' +
' </div>\n' +
' </script>\n' +
'\n' +
' <!-- Task template -->\n' +
' <script type="text/ng-template" id="template/ganttTask.tmpl.html">\n' +
' <div class="gantt-task" ng-class="task.model.classes">\n' +
' <gantt-task-background></gantt-task-background>\n' +
' <gantt-task-foreground></gantt-task-foreground>\n' +
' <gantt-task-content></gantt-task-content>\n' +
' </div>\n' +
' </script>\n' +
'\n' +
' <script type="text/ng-template" id="template/ganttTaskBackground.tmpl.html">\n' +
' <div class="gantt-task-background" ng-style="{\'background-color\': task.model.color}"></div>\n' +
' </script>\n' +
'\n' +
' <script type="text/ng-template" id="template/ganttTaskForeground.tmpl.html">\n' +
' <div class="gantt-task-foreground">\n' +
' <div ng-if="task.truncatedRight" class="gantt-task-truncated-right">></div>\n' +
' <div ng-if="task.truncatedLeft" class="gantt-task-truncated-left"><</div>\n' +
' </div>\n' +
' </script>\n' +
'\n' +
' <!-- Task content template -->\n' +
' <script type="text/ng-template" id="template/ganttTaskContent.tmpl.html">\n' +
' <div class="gantt-task-content" unselectable="on"><span unselectable="on" gantt-bind-compile-html="getTaskContent()"/></div>\n' +
' </script>\n' +
'\n' +
'\n' +
' <!-- Row background template -->\n' +
' <script type="text/ng-template" id="template/ganttRowBackground.tmpl.html">\n' +
' <div class="gantt-row gantt-row-height"\n' +
' ng-class="row.model.classes"\n' +
' ng-class-odd="\'gantt-row-odd\'"\n' +
' ng-class-even="\'gantt-row-even\'"\n' +
' ng-style="{\'height\': row.model.height}">\n' +
' <div class="gantt-row-background"\n' +
' ng-style="{\'background-color\': row.model.color}">\n' +
' </div>\n' +
' </div>\n' +
' </script>\n' +
'\n' +
' <!-- Row template -->\n' +
' <script type="text/ng-template" id="template/ganttRow.tmpl.html">\n' +
' <div class="gantt-row gantt-row-height"\n' +
' ng-class="row.model.classes"\n' +
' ng-class-odd="\'gantt-row-odd\'"\n' +
' ng-class-even="\'gantt-row-even\'"\n' +
' ng-style="{\'height\': row.model.height}">\n' +
' <div ng-transclude class="gantt-row-content"></div>\n' +
' </div>\n' +
' </script>\n' +
'\n' +
' <!-- Side background template -->\n' +
' <script type="text/ng-template" id="template/ganttSideBackground.tmpl.html">\n' +
' <div class="gantt-side-background">\n' +
' <div class="gantt-side-background-header" ng-style="{height: $parent.ganttHeaderHeight + \'px\'}">\n' +
' <div ng-show="$parent.ganttHeaderHeight" class="gantt-header-row gantt-side-header-row"></div>\n' +
' </div>\n' +
' <div class="gantt-side-background-body" ng-style="getMaxHeightCss()">\n' +
' <div gantt-vertical-scroll-receiver>\n' +
' <div class="gantt-row gantt-row-height "\n' +
' ng-class-odd="\'gantt-row-odd\'"\n' +
' ng-class-even="\'gantt-row-even\'"\n' +
' ng-class="row.model.classes"\n' +
' ng-repeat="row in gantt.rowsManager.visibleRows track by row.model.id"\n' +
' ng-style="{\'height\': row.model.height}">\n' +
' <div gantt-row-label class="gantt-row-label gantt-row-background"\n' +
' ng-style="{\'background-color\': row.model.color}">\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
' </div>\n' +
' </script>\n' +
'</div>\n' +
'');
}]);
//# sourceMappingURL=angular-gantt.js.map
|
search_result['4075']=["topic_00000000000009C9_events--.html","TemplatesResponseDto Events",""];
|
var express = require("express");
var router = express.Router();
//var imageController = require("../controllers/imagecontroller");
var path = require("path");
var fs = require("fs");
var processorsWithAdminInterfaces = [];
/* GET home page. */
router.get('/processors', function(req, res) {
var output = {id: req.path, title: "Processorer", processors: processorsWithAdminInterfaces};
res.render("processors", output);
});
function appendProcessorsRoutes(router) {
var postProcessorsAdminInterfacesPath = path.join(__dirname, "..", "postprocessors", "admininterfaces");
var preProcessorsAdminInterfacesPath = path.join(__dirname, "..", "preprocessors", "admininterfaces");
if (fs.existsSync(postProcessorsAdminInterfacesPath) && fs.statSync(postProcessorsAdminInterfacesPath).isDirectory()) {
var files = fs.readdirSync(postProcessorsAdminInterfacesPath);
for (var i = 0; i < files.length; i++) {
var adminInterfacePath = path.join(postProcessorsAdminInterfacesPath, files[i]);
if (fs.statSync(adminInterfacePath).isDirectory()) {
var processorPath = path.join(adminInterfacePath, "processor.js");
if (fs.statSync(processorPath).isFile()) {
var processor = require(processorPath);
var baseRoute = processor.addRoutes(router);
processorsWithAdminInterfaces.push(baseRoute);
}
}
}
}
if (fs.existsSync(preProcessorsAdminInterfacesPath) && fs.statSync(preProcessorsAdminInterfacesPath).isDirectory()) {
var files = fs.readdirSync(preProcessorsAdminInterfacesPath);
for (var i = 0; i < files.length; i++) {
var adminInterfacePath = path.join(preProcessorsAdminInterfacesPath, files[i]);
if (fs.statSync(adminInterfacePath).isDirectory()) {
var processorPath = path.join(adminInterfacePath, "processor.js");
if (fs.statSync(processorPath).isFile()) {
var processor = require(processorPath);
var baseRoute = processor.addRoutes(router);
processorsWithAdminInterfaces.push(baseRoute);
}
}
}
}
}
/*
//Find correct view for each type of content
router.get('/processors/*', function(req, res) {
var baseUrl = req.path;
var output = {id: req.path, title: "Processorer"};
res.render("processors", output);
procController.getContent(baseUrl, function(err, data) {
if (err) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
} else {
var output = {id: baseUrl, title: baseUrl};
if (data.type === "dir") {
output.content = data.list;
res.render('images', output);
} else if (data.type === "image") {
output.data = data;
res.render('image', output);
} else {
res.render('error', {
message: baseUrl + " is of unknown type",
error: new Error()
});
}
}
});
});
*/
appendProcessorsRoutes(router);
module.exports = router;
|
/**
* This package transforms an indented string into a Javascript array,
* where nodes are arrays and items are strings.
*
* @license <https://spdx.org/licenses/MIT.html> The MIT License
* @contributor Eliakim Zacarias <https://github.com/ezaca>
*/
var Options = require ('./Options')
var Node, Leaf
{
let Items = require ('./NodeLeaf')
Node = Items.Node
Leaf = Items.Leaf
}
var IndentManager = require ('./IndentManager')
var Cache = require ('./cache')
var StringReader = require('./StringReader')
var TreeBuilder = require ('./TreeBuilder')
var createInterceptor = require ('./createInterceptor')
function SowString(userGivenText, userGivenOptions)
{
var options = new Options (userGivenOptions)
var lines = new StringReader (userGivenText, options)
var result = new TreeBuilder (options)
var indents = new IndentManager (options)
var cache = new Cache (options)
var leaf, node, interceptor, interceptorResult, hasIndentError
function discardOrCache () {
if (interceptorResult.cache)
cache.push(leaf)
return interceptorResult.discard || interceptorResult.cache
}
while (lines.next ()) {
interceptorResult = null
interceptor = null
// ----------------------------
// Empty nodes
// ----------------------------
if (lines.currentIsEmpty)
{
leaf = new Leaf (lines.lineNum, lines.currentIndent, '')
cache.push (leaf)
continue
}
leaf = new Leaf (lines.lineNum, lines.currentIndent, lines.currentLine)
leaf.level = indents.getLevelFromIndent (leaf.indent)
// ----------------------------
// Interceptor
// ----------------------------
if (options.intercept)
{
interceptorResult = {}
interceptor = createInterceptor (leaf, indents, interceptorResult)
options.intercept.call (interceptor)
if (discardOrCache())
continue
}
hasIndentError = !(
indents.isValidLevel (leaf.level) ||
indents.isValidIndent (leaf.indent)
)
// ----------------------------
// Indent errors
// ----------------------------
if (hasIndentError && options.error) {
if (! interceptor) {
interceptorResult = {}
interceptor = createInterceptor (leaf, indents, interceptorResult)
}
options.error.call (interceptor)
if (discardOrCache())
continue
}
if (leaf.level === null) {
if (leaf.indent === null)
throw new Error ('Line has no valid indent or level value')
leaf.level = indents.getLevelFromIndent (leaf.indent)
}
if (leaf.indent === null) {
leaf.indent = indents.getIndentFromLevel (leaf.level)
}
if (! indents.isValidLevel (leaf.level))
{
if (! options.fixIndent)
throw new Error ('Invalid indent on line '+lines.lineNum)
cache.push (leaf)
continue
}
// ----------------------------
// Node passed
// ----------------------------
if (indents.isSibling (leaf.level)) {
cache.flush (result)
result.push (leaf)
continue
} else
if (indents.isChild (leaf.level)) {
var node = new Node (lines.lineNum)
node.level = indents.currentLevel
result.checkHeadingSetup (node)
result.enter (node)
indents.enter (leaf.indent)
cache.flush (result)
result.push (leaf)
continue
} else
if (indents.isParent (leaf.level)) {
cache.flush (result)
while (! indents.isLevel (leaf.level)) {
indents.leave ()
result.leave ()
}
result.push (leaf)
} else
throw new Error ('SowString crashed (a node is not child, parent or sibling)')
}
cache.flush (result)
return result.tree
}
SowString.Node = Node
SowString.Leaf = Leaf
if (typeof window !== "undefined")
{
window.SowString = SowString
}
if ((typeof module !== "undefined") && (module.exports))
{
module.exports.SowString = SowString
}
|
/**
* Bootstrap Altair instances based on a config
*/
require(['altair/Altair',
'require',
'altair/cartridges/Foundry',
'altair/facades/mixin',
'altair/facades/home',
'altair/plugins/node!debug',
'altair/plugins/node!path',
'altair/plugins/node!fs',
'altair/plugins/node!module',
'altair/plugins/node!config-extend',
'lodash',
'altair/plugins/config!core/config/altair.json?env=' + global.env],
function (Altair, require, Foundry, mixin, home, debugUtil, path, fs, Module, extend, _, config) {
/**
* Simple debug logging
*/
debugUtil.enable(config.debug);
debug = debugUtil('altair:Altair');
require.log = debug; //overrides the require.log used by dojo to provide much better high level reporting
/**
* Make sure our CWD is set
*/
if(global.cwd !== process.cwd()) {
process.chdir(global.cwd);
}
/**
* NPM has zero dependency injection so it's easier to create a central place for altair to manage
* all node dependencies than it is to configure npm (at all). This is where all the dependencies
* for altair modules/themes/widgets/sites will be installed.
*/
var homePath = path.join(home(), '.altair'),
homeConfigPath = path.join(homePath, 'altair.json'),
homePackagePath = path.join(homePath, 'package.json'),
appConfigPath = path.join(process.cwd(), 'altair.json');
//does our run dir exist? move this to better installer
try {
fs.statSync(homePath);
} catch (e) {
debug('altair first run, creating ' + homePath);
//create home
fs.mkdirSync(homePath);
fs.writeFileSync(homeConfigPath, JSON.stringify({
description: 'See https://github.com/liquidg3/altair/blob/master/docs/config.md for help on configuring altair.',
'default': {
paths: {
core: 'core'
}
}
}, null, 4));
fs.writeFileSync(homePackagePath, JSON.stringify({
name: 'altair-global',
description: 'Placeholder altair config to hold dependencies of all installed modules.'
}, null, 4));
}
/**
* Mixin config from app/config/altair.json if there is one
*/
require([
'altair/plugins/config!' + appConfigPath + '?env=' + global.env,
'altair/plugins/config!' + homeConfigPath + '?env=' + global.env
], function (appConfig, homeConfig) {
var paths = [],
altair,
app,
foundry;
config.paths.home = homePath; //always have a home path
//inform us about our environment
debug('current environment is "' + global.env + '".');
//mixin configs, cwd config wins!
if(appConfig) {
//if the cwdConfig exists, it is our new "home" folder and everything will run/install from there
debug('app detected - loading config @ ' + appConfigPath);
extend(config, appConfig);
//our new home (also make sure it's in the paths)
app = process.cwd();
config.paths.app = app;
} else {
debug('loading config @ ' + homeConfigPath);
config = mixin(config, homeConfig);
}
/**
* Lets you configure how much error reporting to do.
*
* @type {number}
*/
Error.stackTraceLimit = config.stackTraceLimit || Infinity;
//set debug config again
debugUtil.names = [];
debugUtil.skips = [];
debugUtil.enable(config.debug);
/**
* Make sure npm can look at our current app directory, fallback to home. But NEVER both.
*
* @type {string}
*/
process.env['NODE_PATH'] += ":" + path.join(homePath, 'node_modules');
if(app) { //app (which is cwd if altair.json exists) is a valid lookup spot
process.env['NODE_PATH'] += ":" + path.join(app, 'node_modules');
}
Module._initPaths(); // terrible
/**
* Bring in the packages from the config, this should point to at least app and core. Even though core is not
* needed, this array is also used to build our lookup paths in altair. Altair only needs their names since
* dojo's define() and require() can map it to their paths.
*/
require({
paths: config.paths
});
//cartridges are given a key in the config so they can be overridden easier.
config.cartridges = _.toArray(config.cartridges);
//paths by name for altair
Object.keys(config.paths).forEach(function (name) {
paths.push(name);
});
/**
* Startup the cartridge factory and create the cartridges, then add
* them to altair.
*/
altair = new Altair({ paths: paths, safeMode: global.safe, home: homePath });
foundry = new Foundry(altair);
if (altair.safeMode) {
debug('-- starting altair in safe mode --');
}
debug('creating cartridge foundry. adding ' + config.cartridges.length + ' cartridges.');
foundry.build(config.cartridges).then(function (cartridges) {
debug('cartridges created. adding to altair for startup.');
/**
* Add cartridges
*/
return altair.addCartridges(cartridges).then(function () {
debug('cartridges started.');
});
}).otherwise(debug);
});
});
|
import React from 'react'
import Liform from 'liform-react'
const schema={
'properties': {
'email': {
'title':'E-mail',
'type':'string',
'widget':'email',
'format':'email'
}
},
'required':[ 'email' ]
}
const Example = (props) => (
<Liform schema={schema}
onSubmit={props.onSubmit}
/>
)
export default Example
|
define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
},
DocCommentHighlightRules.getTagRule(),
{
defaultToken : "comment.doc",
caseInsensitive: true
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getTagRule = function(start) {
return {
token : "comment.doc.tag.storage.type",
regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b"
};
}
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
define("ace/mode/jsx_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JsxHighlightRules = function() {
var keywords = lang.arrayToMap(
("break|do|instanceof|typeof|case|else|new|var|catch|finally|return|void|continue|for|switch|default|while|function|this|" +
"if|throw|" +
"delete|in|try|" +
"class|extends|super|import|from|into|implements|interface|static|mixin|override|abstract|final|" +
"number|int|string|boolean|variant|" +
"log|assert").split("|")
);
var buildinConstants = lang.arrayToMap(
("null|true|false|NaN|Infinity|__FILE__|__LINE__|undefined").split("|")
);
var reserved = lang.arrayToMap(
("debugger|with|" +
"const|export|" +
"let|private|public|yield|protected|" +
"extern|native|as|operator|__fake__|__readonly__").split("|")
);
var identifierRe = "[a-zA-Z_][a-zA-Z0-9_]*\\b";
this.$rules = {
"start" : [
{
token : "comment",
regex : "\\/\\/.*$"
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
regex : "\\/\\*",
next : "comment"
}, {
token : "string.regexp",
regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F]+\\b"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "constant.language.boolean",
regex : "(?:true|false)\\b"
}, {
token : [
"storage.type",
"text",
"entity.name.function"
],
regex : "(function)(\\s+)(" + identifierRe + ")"
}, {
token : function(value) {
if (value == "this")
return "variable.language";
else if (value == "function")
return "storage.type";
else if (keywords.hasOwnProperty(value) || reserved.hasOwnProperty(value))
return "keyword";
else if (buildinConstants.hasOwnProperty(value))
return "constant.language";
else if (/^_?[A-Z][a-zA-Z0-9_]*$/.test(value))
return "language.support.class";
else
return "identifier";
},
regex : identifierRe
}, {
token : "keyword.operator",
regex : "!|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
}, {
token : "punctuation.operator",
regex : "\\?|\\:|\\,|\\;|\\."
}, {
token : "paren.lparen",
regex : "[[({<]"
}, {
token : "paren.rparen",
regex : "[\\])}>]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
regex : ".+"
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
};
oop.inherits(JsxHighlightRules, TextHighlightRules);
exports.JsxHighlightRules = JsxHighlightRules;
});
define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
return line.match(/^\s*/)[0];
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");
var SAFE_INSERT_IN_TOKENS =
["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
["text", "paren.rparen", "punctuation.operator", "comment"];
var context;
var contextCache = {};
var initContext = function(editor) {
var id = -1;
if (editor.multiSelect) {
id = editor.selection.index;
if (contextCache.rangeCount != editor.multiSelect.rangeCount)
contextCache = {rangeCount: editor.multiSelect.rangeCount};
}
if (contextCache[id])
return context = contextCache[id];
context = contextCache[id] = {
autoInsertedBrackets: 0,
autoInsertedRow: -1,
autoInsertedLineEnd: "",
maybeInsertedBrackets: 0,
maybeInsertedRow: -1,
maybeInsertedLineStart: "",
maybeInsertedLineEnd: ""
};
};
var CstyleBehaviour = function() {
this.add("braces", "insertion", function(state, action, editor, session, text) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (text == '{') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
return {
text: '{' + selected + '}',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
CstyleBehaviour.recordAutoInsert(editor, session, "}");
return {
text: '{}',
selection: [1, 1]
};
} else {
CstyleBehaviour.recordMaybeInsert(editor, session, "{");
return {
text: '{',
selection: [1, 1]
};
}
}
} else if (text == '}') {
initContext(editor);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n" || text == "\r\n") {
initContext(editor);
var closing = "";
if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
CstyleBehaviour.clearMaybeInsertedClosing();
}
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar === '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
if (!openBracePos)
return null;
var next_indent = this.$getIndent(session.getLine(openBracePos.row));
} else if (closing) {
var next_indent = this.$getIndent(line);
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
return;
}
var indent = next_indent + session.getTabString();
return {
text: '\n' + indent + '\n' + next_indent + closing,
selection: [1, indent.length, 1, indent.length]
};
} else {
CstyleBehaviour.clearMaybeInsertedClosing();
}
});
this.add("braces", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
} else {
context.maybeInsertedBrackets--;
}
}
});
this.add("parens", "insertion", function(state, action, editor, session, text) {
if (text == '(') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '(' + selected + ')',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, ")");
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("brackets", "insertion", function(state, action, editor, session, text) {
if (text == '[') {
initContext(editor);
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && editor.getWrapBehavioursEnabled()) {
return {
text: '[' + selected + ']',
selection: false
};
} else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
CstyleBehaviour.recordAutoInsert(editor, session, "]");
return {
text: '[]',
selection: [1, 1]
};
}
} else if (text == ']') {
initContext(editor);
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ']') {
var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
CstyleBehaviour.popAutoInsertedClosing();
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("brackets", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '[') {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ']') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
if (text == '"' || text == "'") {
initContext(editor);
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
if (leftChar == '\\') {
return null;
}
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
if (!CstyleBehaviour.isSaneInsertion(editor, session))
return;
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
initContext(editor);
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == selected) {
range.end.column++;
return range;
}
}
});
};
CstyleBehaviour.isSaneInsertion = function(editor, session) {
var cursor = editor.getCursorPosition();
var iterator = new TokenIterator(session, cursor.row, cursor.column);
if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
return false;
}
iterator.stepForward();
return iterator.getCurrentTokenRow() !== cursor.row ||
this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};
CstyleBehaviour.$matchTokenType = function(token, types) {
return types.indexOf(token.type || token) > -1;
};
CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
context.autoInsertedBrackets = 0;
context.autoInsertedRow = cursor.row;
context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
context.autoInsertedBrackets++;
};
CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
if (!this.isMaybeInsertedClosing(cursor, line))
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = cursor.row;
context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
context.maybeInsertedLineEnd = line.substr(cursor.column);
context.maybeInsertedBrackets++;
};
CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
return context.autoInsertedBrackets > 0 &&
cursor.row === context.autoInsertedRow &&
bracket === context.autoInsertedLineEnd[0] &&
line.substr(cursor.column) === context.autoInsertedLineEnd;
};
CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
return context.maybeInsertedBrackets > 0 &&
cursor.row === context.maybeInsertedRow &&
line.substr(cursor.column) === context.maybeInsertedLineEnd &&
line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};
CstyleBehaviour.popAutoInsertedClosing = function() {
context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
context.autoInsertedBrackets--;
};
CstyleBehaviour.clearMaybeInsertedClosing = function() {
if (context) {
context.maybeInsertedBrackets = 0;
context.maybeInsertedRow = -1;
}
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
);
}
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all")
range = null;
}
return range;
}
if (foldStyle === "markbegin")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
this.getSectionRange = function(session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1)
continue;
if (startIndent > indent)
break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
};
}).call(FoldMode.prototype);
});
define("ace/mode/jsx",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/jsx_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var JsxHighlightRules = require("./jsx_highlight_rules").JsxHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
function Mode() {
this.HighlightRules = JsxHighlightRules;
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
}
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = {start: "/*", end: "*/"};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.getTokenizer().getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
if (match) {
indent += tab;
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.$id = "ace/mode/jsx";
}).call(Mode.prototype);
exports.Mode = Mode;
});
|
/*
* Copyright 2013 Lauren Sperber
* https://github.com/lauren/lauren-sperber-dot-com/blob/master/LICENSE
*/$(document).ready(function(){(function(){$(".navbar").scrollspy({}),$(".nav li a").click(function(){var e=$(this),t=e.attr("href"),n=$(t).offset().top,r=100,i=n-r;$(window).width()<767&&(i=n),$("html, body").animate({scrollTop:i},500)});var e;$("input").focus(function(){var t=$(this);e=t.val(),t.val("")}).blur(function(){var t=$(this);t.val().match(/^\s+$|^$/)&&t.val(e)})})()});
|
// ==UserScript==
// @name Brolink Embed
// @namespace http://use.i.E.your.homepage/
// @version 0.1
// @description enter something useful
// @match http://localhost:3000/*
// @copyright 2012+, You
// ==/UserScript==
var src = document.createElement("script");
src.src = "http://127.0.0.1:9001/js/socket.js";
src.async = true;
document.head.appendChild(src);
|
(function () {
'use strict';
angular
.module('password.recovery')
.config(configureRecoveryRoutes);
function configureRecoveryRoutes($routeProvider) {
$routeProvider
.when('/recovery-method/add', buildConfig('email'))
.when('/recovery-method/add-phone', buildConfig('phone'))
.when('/recovery-method/verify-phone/:methodId', {
title: 'Verify phone',
templateUrl: 'recovery/verify-phone.html',
controller: 'VerifyPhoneController',
controllerAs: 'vm',
protected: true
}).when('/recovery-method/verify-email/:methodId', {
title: 'Verify email',
templateUrl: 'recovery/verify-email.html',
controller: 'VerifyEmailController',
controllerAs: 'vm',
protected: true
});
//////////////////////////////////////////////////////////////////
function buildConfig(type) {
return {
title: 'Add password recovery method',
templateUrl: 'recovery/add-method.html',
controller: 'AddMethodController',
controllerAs: 'vm',
protected: true,
resolve: {
type: function () {
return type;
}
}
};
}
}
})();
|
(function () {
'use strict';
var controllerId = 'invitations';
angular.module('app').controller(controllerId, ['$interval', '$route', '$rootScope', '$scope', '$location', 'common', 'datacontext', 'backendHubProxy', 'userService', invitations]);
function invitations($interval, $route, $rootScope, $scope, $location, common, datacontext, backendFactory, userService) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
vm.sendInvitation = function add() {
var invite = {
email: $scope.email,
communityKey:localStorage.getItem('community')
}
datacontext.invite(invite);
}
activate();
function activate() {
common.activateController([], controllerId)
.then(function() {});
}
}
})();
|
export function a() {
return "ok";
}
export function test() {
function file1_js_a() {
return "fail";
}
return a();
}
|
/*jslint indent: 2*/
/*global require: true, module: true*/
module.exports = require('require-directory')(module);
|
/**
* @license Copyright (c) 2003-2014, 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/3fbd7430c5ae23bca5707ed2ab706bdf
* Visit online builder to build CKEditor, starting with the same setup as before.
*
* (3) http://ckeditor.com/builder/download/3fbd7430c5ae23bca5707ed2ab706bdf
* 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: 'moono',
preset: 'basic',
ignore: [
'dev',
'.gitignore',
'.gitattributes',
'README.md',
'.mailmap'
],
plugins : {
'about' : 1,
'basicstyles' : 1,
'clipboard' : 1,
'enterkey' : 1,
'entities' : 1,
'floatingspace' : 1,
'indentlist' : 1,
'link' : 1,
'list' : 1,
'toolbar' : 1,
'undo' : 1,
'wysiwygarea' : 1
},
languages : {
'af' : 1,
'ar' : 1,
'bg' : 1,
'bn' : 1,
'bs' : 1,
'ca' : 1,
'cs' : 1,
'cy' : 1,
'da' : 1,
'de' : 1,
'el' : 1,
'en' : 1,
'en-au' : 1,
'en-ca' : 1,
'en-gb' : 1,
'eo' : 1,
'es' : 1,
'et' : 1,
'eu' : 1,
'fa' : 1,
'fi' : 1,
'fo' : 1,
'fr' : 1,
'fr-ca' : 1,
'gl' : 1,
'gu' : 1,
'he' : 1,
'hi' : 1,
'hr' : 1,
'hu' : 1,
'id' : 1,
'is' : 1,
'it' : 1,
'ja' : 1,
'ka' : 1,
'km' : 1,
'ko' : 1,
'ku' : 1,
'lt' : 1,
'lv' : 1,
'mk' : 1,
'mn' : 1,
'ms' : 1,
'nb' : 1,
'nl' : 1,
'no' : 1,
'pl' : 1,
'pt' : 1,
'pt-br' : 1,
'ro' : 1,
'ru' : 1,
'si' : 1,
'sk' : 1,
'sl' : 1,
'sq' : 1,
'sr' : 1,
'sr-latn' : 1,
'sv' : 1,
'th' : 1,
'tr' : 1,
'tt' : 1,
'ug' : 1,
'uk' : 1,
'vi' : 1,
'zh' : 1,
'zh-cn' : 1
}
};
|
/**
* @license
* Copyright Google Inc. 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
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
if (n === 0) return 0;
if (n === 1) return 1;
if (n === 2) return 2;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 3 && n % 100 <= 10) return 3;
if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 99) return 4;
return 5;
}
root.ng.common.locales['ar-ye'] = [
'ar-YE',
[['ص', 'م'], u, u],
[['ص', 'م'], u, ['صباحًا', 'مساءً']],
[
['ح', 'ن', 'ث', 'ر', 'خ', 'ج', 'س'],
[
'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس',
'الجمعة', 'السبت'
],
u,
['أحد', 'إثنين', 'ثلاثاء', 'أربعاء', 'خميس', 'جمعة', 'سبت']
],
u,
[
['ي', 'ف', 'م', 'أ', 'و', 'ن', 'ل', 'غ', 'س', 'ك', 'ب', 'د'],
[
'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو',
'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر'
],
u
],
u,
[['ق.م', 'م'], u, ['قبل الميلاد', 'ميلادي']],
0,
[5, 6],
['d\u200f/M\u200f/y', 'dd\u200f/MM\u200f/y', 'd MMMM y', 'EEEE، d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1} {0}', u, u, u],
[
'.', ',', ';', '\u200e%\u200e', '\u200e+', '\u200e-', 'E', '×', '‰', '∞',
'ليس رقمًا', ':'
],
['#,##0.###', '#,##0%', '¤ #,##0.00', '#E0'],
'ر.ي.\u200f',
'ريال يمني',
{
'AED': ['د.إ.\u200f'],
'ARS': [u, 'AR$'],
'AUD': ['AU$'],
'BBD': [u, 'BB$'],
'BHD': ['د.ب.\u200f'],
'BMD': [u, 'BM$'],
'BND': [u, 'BN$'],
'BSD': [u, 'BS$'],
'BZD': [u, 'BZ$'],
'CAD': ['CA$'],
'CLP': [u, 'CL$'],
'CNY': ['CN¥'],
'COP': [u, 'CO$'],
'CUP': [u, 'CU$'],
'DOP': [u, 'DO$'],
'DZD': ['د.ج.\u200f'],
'EGP': ['ج.م.\u200f', 'E£'],
'FJD': [u, 'FJ$'],
'GBP': ['UK£'],
'GYD': [u, 'GY$'],
'HKD': ['HK$'],
'IQD': ['د.ع.\u200f'],
'IRR': ['ر.إ.'],
'JMD': [u, 'JM$'],
'JOD': ['د.أ.\u200f'],
'JPY': ['JP¥'],
'KWD': ['د.ك.\u200f'],
'KYD': [u, 'KY$'],
'LBP': ['ل.ل.\u200f', 'L£'],
'LRD': [u, '$LR'],
'LYD': ['د.ل.\u200f'],
'MAD': ['د.م.\u200f'],
'MRU': ['أ.م.'],
'MXN': ['MX$'],
'NZD': ['NZ$'],
'OMR': ['ر.ع.\u200f'],
'QAR': ['ر.ق.\u200f'],
'SAR': ['ر.س.\u200f'],
'SBD': [u, 'SB$'],
'SDD': ['د.س.\u200f'],
'SDG': ['ج.س.'],
'SRD': [u, 'SR$'],
'SYP': ['ل.س.\u200f', '£'],
'THB': ['฿'],
'TND': ['د.ت.\u200f'],
'TTD': [u, 'TT$'],
'TWD': ['NT$'],
'USD': ['US$'],
'UYU': [u, 'UY$'],
'XXX': ['***'],
'YER': ['ر.ي.\u200f']
},
plural,
[
[
[
'فجرًا', 'صباحًا', 'ظهرًا', 'بعد الظهر', 'مساءً',
'منتصف الليل', 'ليلاً'
],
[
'فجرًا', 'ص', 'ظهرًا', 'بعد الظهر', 'مساءً',
'منتصف الليل', 'ليلاً'
],
[
'فجرًا', 'صباحًا', 'ظهرًا', 'بعد الظهر', 'مساءً',
'منتصف الليل', 'ليلاً'
]
],
u,
[
['03:00', '06:00'], ['06:00', '12:00'], ['12:00', '13:00'], ['13:00', '18:00'],
['18:00', '24:00'], ['00:00', '01:00'], ['01:00', '03:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
'use strict';
(function(module) {
try {
module = angular.module('tink.modal');
} catch (e) {
module = angular.module('tink.modal', []);
}
module.provider('$modal', function() {
var defaults = this.defaults = {
element: null,
backdrop: false,
keyboard: true
};
var openInstance = null;
this.$get = function($http,$q,$rootScope,$templateCache,$compile,$animate,$window,$controller,$injector) {
var bodyElement = angular.element($window.document.body);
var htmlElement = $('html');
var $modal = { isOpen: false };
var options = $modal.$options = angular.extend({}, defaults);
var linker;
//for fetching the template that exist
var fetchPromises = {};
function fetchTemplate(template) {
if(fetchPromises[template]) {return fetchPromises[template];}
return (fetchPromises[template] = $http.get(template, {cache: $templateCache}).then(function(res) {
return res.data;
}));
}
function fetchResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function (value) {
if (angular.isFunction(value)) {
promisesArr.push($q.when($injector.invoke(value)));
}else{
promisesArr.push($q.when(value));
}
});
return promisesArr;
}
/*$modal.$promise = fetchTemplate(options.template);
//when the templated is loaded start everyting
$modal.$promise.then(function(template) {
linker = $compile(template);
//$modal.show()
});*/
$modal.show = function() {
$modal.$element = linker(options.scope, function() {});
enterModal();
};
$modal.hide = function() {
leaveModal();
};
$modal.open = function(config){
//create the promises for opening and result
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
//Create an instance for the modal
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
close: function (result) {
leaveModal(null).then(function(){
modalResultDeferred.resolve(result);
});
},
dismiss: function (reason) {
leaveModal(null).then(function(){
modalResultDeferred.reject(reason);
});
}
};
var resolveIter = 1;
//config variable
config = defaults = angular.extend({}, defaults, config);
config.resolve = config.resolve || {};
// Check for ESC key parameter
if(config.resolve.keyboard !== undefined) {
defaults.keyboard = config.resolve.keyboard;
}
// Check for backdrop parameter
if(config.resolve.backdrop !== undefined) {
defaults.backdrop = config.resolve.backdrop;
}
var templateAndResolvePromise;
if(angular.isDefined(config.templateUrl)){
templateAndResolvePromise = $q.all([fetchTemplate(config.templateUrl)].concat(fetchResolvePromises(config.resolve)));
}else{
templateAndResolvePromise = $q.all([config.template].concat(fetchResolvePromises(config.resolve)));
}
//Wacht op de template en de resloved variable
templateAndResolvePromise.then(function success(tplAndVars){
//Get the modal scope or create one
var modalScope = (config.scope || $rootScope).$new();
//add the close and dismiss to to the scope
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
var ctrlInstance,ctrlConstant={};
ctrlConstant.$scope = modalScope;
ctrlConstant.$modalInstance = modalScope;
angular.forEach(config.resolve, function (value, key) {
ctrlConstant[key] = tplAndVars[resolveIter++];
});
if (config.controller) {
ctrlInstance = $controller(config.controller, ctrlConstant);
}
if (config.controllerAs) {
modalScope[config.controllerAs] = ctrlInstance;
}
enterModal(modalInstance,{
scope:modalScope,
content: tplAndVars[0],
windowTemplateUrl: config.template
});
});
return modalInstance;
};
function createModalWindow(content){
var modelView = angular.element('<div class="modal" tabindex="-1" role="dialog">'+
'<div class="modal-dialog">'+
'<div class="modal-content">'+
'</div>'+
'</div>'+
'</div>');
modelView.find('.modal-content').html(content);
return modelView;
}
function enterModal(model,instance){
function show(){
var linker = $compile(createModalWindow(instance.content));
var content = linker(instance.scope, function() {});
model.$element = content;
$(htmlElement).addClass('has-open-modal');
$modal.isOpen = true;
bodyElement.bind('keyup',function(e){
instance.scope.$apply(function(){
if(e.which === 27){
if(defaults.keyboard){
model.dismiss('esc');
}
}
});
});
model.$element.bind('click',function(e){
var view = $(this);
instance.scope.$apply(function(){
if(e.target === view.get(0)){
if(defaults.backdrop){
model.dismiss('backdrop');
}
}
});
});
$animate.enter(content, bodyElement, null);
openInstance = {element:content,scope:instance.scope};
}
if(openInstance !== null){
leaveModal(openInstance).then(function(){
show();
});
}else{
show();
}
}
function leaveModal(modal){
bodyElement.unbind('keyup');
var q = $q.defer();
if(modal === null){
modal = openInstance;
}
$(htmlElement).removeClass('has-open-modal');
$modal.isOpen = false;
$animate.leave(modal.element).then(function() {
openInstance = null;
q.resolve('ended');
});
return q.promise;
}
return $modal;
};
});
})();
;
|
(function ($, window) {
/**
* Enable thumbnail support for Swiper
* @param swiper (pass swiper element)
* @param settings (pass custom options)
*/
window.swiperThumbs = function (swiper, settings) {
/**
* Loop over swiper instances
*/
$(swiper).each(function () {
var _this = this;
/**
* Default settings
*/
var options = {
element: 'swiper-thumbnails',
activeClass: 'is-active',
scope: undefined
};
/**
* Merge user settings and default settings
*/
$.extend(options, settings);
var element;
if (typeof options.scope !== "undefined") {
element = $(_this.wrapperEl).closest(options.scope).find('.' + options.element);
} else {
element = $('.' + options.element);
}
/**
* Get real activeIndex
* @returns {*}
*/
var realIndex = function (index) {
// if index doesn't exist set index to activeIndex of swiper
if (index === undefined) index = _this.activeIndex;
// Check if swiper instance has loop before getting real index
if (_this.params.loop) {
return parseInt(_this.slides.eq(index).attr('data-swiper-slide-index'));
} else {
return index;
}
};
var app = {
init: function () {
app.bindUIevents();
app.updateActiveClasses(realIndex(_this.activeIndex));
},
bindUIevents: function () {
/**
* Bind click events to thumbs
*/
element.children().each(function () {
$(this).on('click', function () {
// Get clicked index
var index = parseInt($(this).index());
// Get difference between item clicked and current real active index.
var difference = (index - realIndex());
// Move to slide that makes sense for the user by
// checking what the current active slide is and adding the difference
// this makes sure the swiper moves to a natural direction the user expects.
app.moveToSlide(_this.activeIndex + difference);
})
});
/**
* Update thumbs on slideChange
*/
_this.on('slideChange', function (swiper) {
app.updateActiveClasses(realIndex())
});
},
moveToSlide: function (index) {
_this.slideTo(index);
},
updateActiveClasses: function (index) {
element.children().removeClass(options.activeClass);
element.children().eq(index).addClass(options.activeClass);
}
};
app.init();
});
};
}(jQuery, window));
|
/*
* grunt-premailer
* https://github.com/dwightjack/grunt-premailer
*
* Copyright (c) 2013-2016 Marco Solazzi
* Licensed under the MIT license.
*/
'use strict';
module.exports = function gruntPremailer(grunt) {
var dargs = require('dargs'),
path = require('path'),
fs = require('fs'),
async = require('async'),
isUtf8 = require('is-utf8'),
_ = require('lodash'),
warnLevels;
warnLevels = {
none: 0,
safe: 1,
poor: 2,
risky: 3
};
grunt.registerMultiTask('premailer', 'Grunt wrapper task for premailer', function taskRegistration() {
// Merge task-specific and/or target-specific options with these defaults.
var args = {},
done = this.async(),
options = this.options({
baseUrl: null,
bundleExec: false,
queryString: '',
css: [],
removeClasses: false,
removeScripts: false,
removeComments: false,
preserveStyles: false,
preserveStyleAttribute: false,
lineLength: 65,
ioException: false,
verbose: false,
mode: 'html',
warnLevel: 'safe',
removeIds: false,
replaceHtmlEntities: false,
escapeUrlAttributes: true
}),
keys,
cmd;
keys = Object.keys(options);
// Remove bundleExec from arguments
keys.splice(keys.indexOf('bundleExec'), 1);
//clean-up falsy options and parse template-like values
keys.forEach(function keyIterator(key) {
var val = options[key];
if (typeof val === 'string') {
val = grunt.template.process(val);
}
//warn level could be 0, preserve it
if ((typeof val === 'object' && !_.isEmpty(val)) || (typeof val !== 'object' && !!val)) {
args[key] = val;
}
});
//convert warn level
args.warnLevel = _.has(warnLevels, args.warnLevel) ? warnLevels[args.warnLevel] : 0;
//also manage properly the css option
if (_.has(args, 'css') && Array.isArray(args.css)) {
args.css = _(args.css)
.map(function mapFn(csspath) {
return grunt.config.process(csspath);
})
.reduce(function reduceFn(paths, csspath) {
var expanded = grunt.file.expand({
filter: function expandFilterFn(src) {
return grunt.file.isFile(src) && (path.extname(src) === '.css');
}
}, csspath);
return paths.concat(expanded);
}, [])
.valueOf()
.join(',');
}
// Arguments
args = dargs(args);
args.unshift(path.join(__dirname, '..', 'lib', 'premailer.rb'));
// Command to run
if (options.bundleExec) {
cmd = 'bundle';
args.unshift('exec', 'ruby');
} else {
cmd = 'ruby' + (process.platform === 'win32' ? '.exe' : '');
}
// Asynchronously iterate over all specified file groups.
async.eachLimit(this.files, 10, function asyncIterator(f, next) {
// Concat specified files.
var srcFile,
batchArgs,
premailer,
tmpFile;
srcFile = f.src.filter(function filterFn(sFile) {
return grunt.file.isFile(sFile);
}).shift();
if (!srcFile) {
//skip!
grunt.log.writeln('Input file not found');
next(null);
}
if (!isUtf8(fs.readFileSync(srcFile))) {
//skip!
grunt.log.writeln('Input file must have utf8 encoding');
next(null);
}
if (srcFile === f.dest) {
//generate a temp dest file
tmpFile = path.join(path.dirname(f.dest), _.uniqueId('.premailer-') + '.tmp');
grunt.file.write(tmpFile, '');
grunt.verbose.writeln('Creating temporary file ' + tmpFile);
} else {
grunt.file.write(f.dest, ''); // Create empty destination file
}
// Premailer expects absolute paths
batchArgs = args.concat(['--file-in', path.resolve(srcFile.toString()), '--file-out', path.resolve((tmpFile || f.dest).toString())]);
premailer = grunt.util.spawn({
cmd: cmd,
args: batchArgs
}, function premailerCb(err/*, result, code*/) {
if (err) {
grunt.fail.fatal(err);
}
if (tmpFile) {
grunt.file.copy(tmpFile, f.dest);
grunt.file.delete(tmpFile);
grunt.verbose.writeln('Removing temporary file ' + tmpFile);
}
next(err);
});
premailer.stdout.pipe( process.stdout );
premailer.stderr.pipe( process.stderr );
}, done);
});
};
|
define('ajax_setup', function (require) {
var store = require('store');
(function setAjax () {
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var dfd = $.Deferred();
jqXHR.done(function (data) {
var dataCheck = options.dataCheck;
if ($.isFunction(dataCheck) && !dataCheck(data)) {
originalOptions.url = originalOptions.backup;
originalOptions.dataCheck = null;
originalOptions.forceBackup = true;
dfd.rejectWith(originalOptions, arguments);
} else {
processStoreData(data);
dfd.resolveWith(originalOptions, arguments);
}
});
jqXHR.fail(dfd.reject);
function processStoreData (data) {
var needStore = options.needStore;
var storeKey = options.storeKey;
var storeCheck = options.storeCheck;
needStore = needStore ? store.enabled : false;
if (needStore) {
var storeData = store.get(storeKey);
if (!storeData || !storeCheck(storeData)) {
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) {
data = {};
}
}
store.set(storeKey, data);
}
}
}
jqXHR.retry = function (opts) {
if (opts.timeout) {
this.timeout = opts.timeout;
}
if (opts.statusCodes) {
this.statusCodes = opts.statusCodes;
}
if (opts.backup) {
if (!$.isArray(opts.backup)) {
opts.backup = [opts.backup];
} else {
opts.backup = Array.prototype.slice.call(opts.backup);
}
}
return this.pipe(null, pipeFailRetry(this, opts));
};
return dfd.promise(jqXHR);
});
$.ajaxTransport('+script', function (options) {
var needStore = options.needStore;
var storeKey = options.storeKey;
var storeCheck = options.storeCheck;
var dataType = options.dataType;
var forceStore = options.forceStore;
needStore = needStore ? store.enabled : false;
if (needStore) {
var storeData = store.get(storeKey);
if (storeData && (storeCheck(storeData) || forceStore)) {
return {
send: function (headers, completeCallback) {
var response = {};
response[dataType] = options.jsonpCallback + '(' + JSON.stringify(storeData) + ')';
completeCallback(200, 'success', response, '');
},
abort: function () {
_.console.log('abort ajax transport for local cache');
}
};
}
}
});
function pipeFailRetry(jqXHR, opts) {
var times = opts.times;
var timeout = jqXHR.timeout;
var timer = null;
return function (input, status, msg) {
var ajaxOptions = this;
var output = new $.Deferred();
var retryAfter = jqXHR.getResponseHeader('Retry-After');
timer && clearTimeout(timer);
function nextRequest(options) {
if (options.isBackup) {
options.cache = true;
_.eventCenter.trigger(ajaxOptions.jsonpCallback + ':backup', options.url);
}
ajaxOptions.data = ajaxOptions.__data || { };
$.extend(ajaxOptions, {
url: ajaxOptions.originalUrl,
forceStore: false
}, options);
$.ajax(ajaxOptions)
.retry({
times: options.times,
timeout: opts.timeout,
statusCodes: opts.statusCodes,
backup: opts.backup
})
.pipe(output.resolve, output.reject);
}
function useStore() {
var storeData = store.get(ajaxOptions.storeKey);
if (storeData) {
nextRequest({
forceStore: true,
times: 0
});
} else {
output.rejectWith(this, arguments);
}
}
if (ajaxOptions.forceBackup) {
times = 0;
}
if (times > 0 && (!jqXHR.statusCodes || $.inArray(input.status, jqXHR.statusCodes) > -1)) {
if (retryAfter) {
if (isNaN(retryAfter)) {
timeout = new Date(retryAfter).getTime() - $.now();
} else {
timeout = parseInt(retryAfter, 10) * 1000;
}
if (isNaN(timeout) || timeout < 0) {
timeout = jqXHR.timeout;
}
}
if (timeout !== undefined && times !== opts.times) {
timer = setTimeout(function () {
nextRequest({
times: times - 1
});
}, timeout);
} else {
nextRequest({
times: times - 1
});
}
} else {
if (times === 0) {
if (opts.backup && opts.backup.length) {
nextRequest({
url: opts.backup.shift(),
times: 0,
isBackup: true
});
} else {
useStore();
}
}
}
return output;
};
}
})();
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:e7732647edc9eb434fd21cba0638455b5231d4c7d976c91e71f5d1fa8c4c0661
size 2336
|
$(document).ready(function(){
$("input[type='checkbox'],input[type='radio']")
.parent()
.prepend("<svg class='lcars-svg'><rect class='lcars-control'></rect></svg>");
$(".lcars-select-label").click(function(){
$(this).children("select").focus();
});
$(".lcars-accordion-heading")
.append(" <span class='fa fa-caret-down'></span>")
.click(function(){
$(this).parent().children(".lcars-accordion-content").slideToggle(200);
});
$(".dropdown").click(function(){
$(this).children(".lcars-dropdown").slideToggle(200).
mouseleave(function(){
$(this).slideUp(200);
});
})
$("input[type='checkbox']")
.change(function(){
if($(this).prop("checked")) {
$(this).parent().addClass("checked");
$(this).parent().find("rect").css("fill","yellow");
} else {
$(this).parent().removeClass("checked");
$(this).parent().find("rect").css("fill","black");
}
});
$("input[type='radio']").change(function(){
$(this).parent().parent().find("rect").css("fill","black");
$(this).parent().find("rect").css("fill","yellow");
});
});
|
'use strict';
module.exports = {
main: {
src: 'app/scripts/**/*.js',
options: {
config: '.jscsrc',
requireCurlyBraces: [ 'if' ]
}
},
test: {
src: 'test/**/*.js',
options: {
config: 'test/.jscsrc',
requireCurlyBraces: [ 'if' ]
}
}
};
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import TodoList from './TodoList'
import FetchError from './FetchError'
import { connect } from '../lib/react-redux'
import * as actions from '../actions'
import { withRouter } from 'react-router-dom'
import { getVisibleTodos, getIsFetching, getErrorMessage } from '../reducers'
class VisibleTodoList extends Component {
static propTypes = {
todos: PropTypes.array.isRequired,
filter: PropTypes.oneOf(['all', 'active', 'completed']).isRequired,
isFetching: PropTypes.bool.isRequired,
fetchTodos: PropTypes.func.isRequired,
toggleTodo: PropTypes.func.isRequired,
errorMessage: PropTypes.string
}
componentDidMount() {
this.fetchData()
}
componentDidUpdate(prevProps) {
if (this.props.filter !== prevProps.filter) {
this.fetchData()
}
}
fetchData = () => {
const { filter, fetchTodos } = this.props
fetchTodos(filter)
};
render() {
const { todos, errorMessage, isFetching } = this.props
if (isFetching && !todos.length) {
return <p>Loading...</p>
}
if (errorMessage && !todos.length) {
return (
<FetchError
message={errorMessage}
onRetry={this.fetchData}
/>
)
}
return (
<TodoList
{...this.props}
/>
)
}
}
const mapStateToProps = (state, { match: { params } }) => {
const filter = params.filter || 'all'
return {
todos: getVisibleTodos(state, filter),
isFetching: getIsFetching(state, filter),
errorMessage: getErrorMessage(state, filter),
filter
}
}
export default withRouter(connect(
mapStateToProps,
actions
)(VisibleTodoList))
|
'use strict';
const _ = require('lodash');
const httpConst = require('http-const');
const utils = require('./utils');
const InvalidMessageError = require('./invalid-message-error');
const boundaryRegexp = /boundary=-+\w+/im;
const paramRegexp = /Content-Disposition:\s*form-data;\s*name="\w+"/im;
const paramNameRegexp = /name="\w+"/im;
const quoteRegexp = /"/g;
class HttpRequestParser {
static parse(params) {
let instance = new HttpRequestParser(params);
return instance.parse();
}
constructor(requestMsg, eol = '\n') {
this.requestMsg = requestMsg;
this.eol = eol;
}
parse() {
if (!this.requestMsg) {
throw new InvalidMessageError('Request must be not undefined');
}
let requestMsgLines = this._parseRequestForLines();
let header = this._parseHeaderLine(requestMsgLines.header);
let host = this._parseHostLine(requestMsgLines.host);
let headers = this._parseHeadersLines(requestMsgLines.headers);
let cookie = this._parseCookieLine(requestMsgLines.cookie);
let contentTypeHeader = this._getContentTypeHeader(headers);
let body = this._parseBody(requestMsgLines.body, contentTypeHeader);
return {
method: header.method,
protocol: header.protocol,
url: header.url,
protocolVersion: header.protocolVersion,
host: host,
headers: headers,
cookie: cookie,
body: body
};
}
_parseRequestForLines() {
let headersAndBodySeparator = this.eol + this.eol;
let headersAndBodySeparatorIndex = this.requestMsg.indexOf(headersAndBodySeparator);
if (headersAndBodySeparatorIndex === -1) {
throw new InvalidMessageError(
'Request must contain headers and body, separated by two break lines');
}
let headers = this.requestMsg.substr(0, headersAndBodySeparatorIndex);
let body = this.requestMsg.substr(headersAndBodySeparatorIndex + headersAndBodySeparator.length);
let headersLines = _.split(headers, this.eol);
if (headersLines.length === 0) {
throw new InvalidMessageError('No headers');
}
let cookieIndex = _.findIndex(headersLines, (line) => {
return _.startsWith(line, 'Cookie:');
});
let cookieLine;
if (cookieIndex !== -1) {
cookieLine = headersLines[cookieIndex];
headersLines.splice(cookieIndex, 1);
}
return {
header: headersLines[0],
host: headersLines[1],
headers: headersLines.splice(2),
cookie: cookieLine,
body: body
};
}
_parseHeaderLine(line) {
let methodUrlProtocolVer = _.split(line, ' ');
if (methodUrlProtocolVer.length !== 3) {
throw new InvalidMessageError('Header must have format: [Method] [Url] [Protocol]', line);
}
let protocolAndUrl = utils.splitIntoTwoParts(methodUrlProtocolVer[1], '://');
if (!protocolAndUrl) {
throw new InvalidMessageError(
'Url in header must have format: [Protocol]://[Address]',
methodUrlProtocolVer[1]
);
}
return {
method: methodUrlProtocolVer[0].toUpperCase(),
protocol: protocolAndUrl[0].toUpperCase(),
url: protocolAndUrl[1].toLowerCase(),
protocolVersion: methodUrlProtocolVer[2].toUpperCase()
};
}
_parseHostLine(line) {
let headerAndValue = utils.splitIntoTwoParts(line, ':');
if (!headerAndValue) {
throw new InvalidMessageError('Host line must have format: [Host]: [Value]', line);
}
return headerAndValue[1];
}
_parseHeadersLines(lines) {
// TODO: add check for duplicate headers
return _.map(lines, line => {
let headerAndValues = utils.splitIntoTwoParts(line, ':');
if (!headerAndValues) {
throw new InvalidMessageError('Header line must have format: [HeaderName]: [HeaderValues]', line);
}
let headerName = headerAndValues[0];
let values = _.split(headerAndValues[1], ',');
if (!headerName || values.length === 0 || _.some(values, val => _.isEmpty(val))) {
throw new InvalidMessageError('Header line must have format: [HeaderName]: [HeaderValues]', line);
}
let valuesAndParams = _.map(values, (value) => {
let valueAndParams = _.split(value, ';');
return {
value: _.trim(valueAndParams[0]),
params: valueAndParams.length > 1 ? _.trim(valueAndParams[1]) : null
};
});
return {
name: headerName,
values: valuesAndParams
};
});
}
_parseCookieLine(line) {
if (!line) {
return null;
}
let headerAndValues = utils.splitIntoTwoParts(line, ':');
if (!headerAndValues) {
throw new InvalidMessageError('Cookie line must have format: Cookie: [Name1]=[Value1]...', line);
}
let nameValuePairs = _.split(headerAndValues[1], ';');
if (nameValuePairs.length === 0) {
throw new InvalidMessageError('Cookie line must have format: Cookie: [Name1]=[Value1]...', line);
}
return _.chain(nameValuePairs)
.map((nameValuePair) => {
let nameValue = _.split(nameValuePair, '=');
return !nameValue[0] ?
null :
{
name: _.trim(nameValue[0]),
value: nameValue.length > 1 ? _.trim(nameValue[1]) : null
};
})
.compact()
.value();
}
_parseBody(lines, contentTypeHeader) {
if (!lines) {
return null;
}
let body = {};
if (!contentTypeHeader) {
this._parsePlainBody(lines, body);
return body;
}
body.contentType = contentTypeHeader.value;
switch (body.contentType) {
case httpConst.contentTypes.formData:
this._parseFormDataBody(lines, body, contentTypeHeader.params);
break;
case httpConst.contentTypes.xWwwFormUrlencoded:
this._parseXwwwFormUrlencodedBody(lines, body);
break;
case httpConst.contentTypes.json:
this._parseJsonBody(lines, body);
break;
default:
this._parsePlainBody(lines, body);
break;
}
return body;
}
_parseFormDataBody(lines, body, contentTypeHeadeParams) {
body.boundary = this._getBoundaryParameter(contentTypeHeadeParams);
let params = _.split(lines, `-----------------------${body.boundary}`);
body.formDataParams = _.chain(params)
.slice(1, params.length - 1)
.map(param => {
let paramMatch = param.match(paramRegexp);
if (!paramMatch) {
throw new InvalidMessageError('Invalid formData parameter', param);
}
let paramNameMatch = paramMatch.toString().match(paramNameRegexp); // TODO: refactor to remove toString
if (!paramNameMatch) {
throw new InvalidMessageError('formData parameter name must have format: [Name]="[Value]"', param);
}
let paramNameParts = _.split(paramNameMatch, '=');
if (paramNameParts.length !== 2) {
throw new InvalidMessageError('formData parameter name must have format: [Name]="[Value]"', param);
}
let paramName = paramNameParts[1];
let paramValue = param.replace(paramMatch, '').trim(this.eol);
return {
name: paramName.toString().replace(quoteRegexp, ''), // TODO: refactor to remove toString
value: paramValue
};
})
.value();
}
_parseXwwwFormUrlencodedBody(lines, body) {
let params = _.split(lines, '&');
body.formDataParams = _.chain(params)
.map(param => {
let paramValue = _.split(param, '=');
if (paramValue.length !== 2) {
throw new InvalidMessageError('Invalid x-www-form-url-encode parameter', param);
}
return !paramValue[0] ?
null :
{
name: paramValue[0],
value: paramValue.length > 1 ? paramValue[1] : null
};
})
.compact()
.value();
}
_parseJsonBody(lines, body) {
body.json = lines;
}
_parsePlainBody(lines, body) {
body.plain = lines;
}
_getContentTypeHeader(headers) {
let contentTypeHeader = _.find(headers, { name: httpConst.headers.contentType });
if (!contentTypeHeader) {
return null;
}
return contentTypeHeader.values[0];
}
_getBoundaryParameter(contentTypeHeaderParams) {
if (!contentTypeHeaderParams) {
throw new InvalidMessageError('Request with ContentType=FormData must have a header with boundary');
}
let boundaryMatch = contentTypeHeaderParams.match(boundaryRegexp);
if (!boundaryMatch) {
throw new InvalidMessageError('Boundary param must have format: [boundary]=[value]', contentTypeHeaderParams);
}
let boundaryAndValue = _.split(boundaryMatch, '=');
if (boundaryAndValue.length !== 2) {
throw new InvalidMessageError('Boundary param must have format: [boundary]=[value]', contentTypeHeaderParams);
}
let boundaryValue = _.trim(boundaryAndValue[1]);
if (!boundaryValue) {
throw new InvalidMessageError('Boundary param must have format: [boundary]=[value]', contentTypeHeaderParams);
}
return boundaryValue;
}
}
module.exports = HttpRequestParser;
|
/* jshint node: true */
// Database controllers and configurations
module.exports = {
url: 'mongodb://localhost/' + 'chat_njs_db'
};
|
(function () {
'use strict';
angular
.module('porttare.directives')
.directive('showError', showError);
function showError() {
var directive = {
restrict: 'EA',
templateUrl: 'templates/directives/show-error/show-error.html',
controller: ShowErrorController,
scope: {
arrayMessages: '='
},
controllerAs: 'seVm',
bindToController: true
};
return directive;
}
function ShowErrorController() {
}
})();
|
import styled from 'styled-components'
import Divider from 'material-ui/Divider'
import { Tabs, Tab } from 'material-ui/Tabs'
import { Login, Register, Connect } from '~/components/auth'
import { centered } from '~/components/elements/styles'
const AuthPanel = styled.div`
${centered()}
width: 400px;
max-width: 90%;
`
export default () => (
<AuthPanel>
<Tabs>
<Tab label="Login">
<Login />
</Tab>
<Tab label="Register">
<Register />
</Tab>
</Tabs>
<Divider />
<Connect label="Connect using Google" />
</AuthPanel>
)
|
var Topogo = require("topogo").Topogo;
var River = require("da_river").River;
var table = "";
var m = module.exports = {};
m.migrate = function (dir, r) {
if (dir === 'down') {
Topogo.run('DROP TABLE IF EXISTS ' + table + ';', [], r);
} else {
var sql = 'CREATE TABLE IF NOT EXISTS ' + table + " ( \
\
);";
Topogo.run(sql, [], r);
}
};
|
// Generated by CoffeeScript 1.6.1
(function() {
var ColorScheme,
__slice = [].slice,
__hasProp = {}.hasOwnProperty;
ColorScheme = (function() {
var clone, typeIsArray, word, _i, _len, _ref;
typeIsArray = Array.isArray || function(value) {
return {}.toString.call(value) === '[object Array]';
};
ColorScheme.SCHEMES = {};
_ref = "mono monochromatic contrast triade tetrade analogic".split(/\s+/);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
word = _ref[_i];
ColorScheme.SCHEMES[word] = true;
}
ColorScheme.PRESETS = {
"default": [-1, -1, 1, -0.7, 0.25, 1, 0.5, 1],
pastel: [0.5, -0.9, 0.5, 0.5, 0.1, 0.9, 0.75, 0.75],
soft: [0.3, -0.8, 0.3, 0.5, 0.1, 0.9, 0.5, 0.75],
light: [0.25, 1, 0.5, 0.75, 0.1, 1, 0.5, 1],
hard: [1, -1, 1, -0.6, 0.1, 1, 0.6, 1],
pale: [0.1, -0.85, 0.1, 0.5, 0.1, 1, 0.1, 0.75]
};
ColorScheme.COLOR_WHEEL = {
0: [255, 0, 0, 100],
15: [255, 51, 0, 100],
30: [255, 102, 0, 100],
45: [255, 128, 0, 100],
60: [255, 153, 0, 100],
75: [255, 178, 0, 100],
90: [255, 204, 0, 100],
105: [255, 229, 0, 100],
120: [255, 255, 0, 100],
135: [204, 255, 0, 100],
150: [153, 255, 0, 100],
165: [51, 255, 0, 100],
180: [0, 204, 0, 80],
195: [0, 178, 102, 70],
210: [0, 153, 153, 60],
225: [0, 102, 178, 70],
240: [0, 51, 204, 80],
255: [25, 25, 178, 70],
270: [51, 0, 153, 60],
285: [64, 0, 153, 60],
300: [102, 0, 153, 60],
315: [153, 0, 153, 60],
330: [204, 0, 153, 80],
345: [229, 0, 102, 90]
};
function ColorScheme() {
var colors, _j;
colors = [];
for (_j = 1; _j <= 4; _j++) {
colors.push(new ColorScheme.mutablecolor(60));
}
this.col = colors;
this._scheme = 'mono';
this._distance = 0.5;
this._web_safe = false;
this._add_complement = false;
}
/*
colors()
Returns an array of 4, 8, 12 or 16 colors in RRGGBB hexidecimal notation
(without a leading "#") depending on the color scheme and addComplement
parameter. For each set of four, the first is usually the most saturated color,
the second a darkened version, the third a pale version and fourth
a less-pale version.
For example: With a contrast scheme, "colors()" would return eight colors.
Indexes 1 and 5 could be background colors, 2 and 6 could be foreground colors.
Trust me, it's much better if you check out the Color Scheme web site, whose
URL is listed in "Description"
*/
ColorScheme.prototype.colors = function() {
var dispatch, h, i, j, output, used_colors, _j, _k, _ref1,
_this = this;
used_colors = 1;
h = this.col[0].get_hue();
dispatch = {
mono: function() {},
contrast: function() {
used_colors = 2;
_this.col[1].set_hue(h);
return _this.col[1].rotate(180);
},
triade: function() {
var dif;
used_colors = 3;
dif = 60 * _this._distance;
_this.col[1].set_hue(h);
_this.col[1].rotate(180 - dif);
_this.col[2].set_hue(h);
return _this.col[2].rotate(180 + dif);
},
tetrade: function() {
var dif;
used_colors = 4;
dif = 90 * _this._distance;
_this.col[1].set_hue(h);
_this.col[1].rotate(180);
_this.col[2].set_hue(h);
_this.col[2].rotate(180 + dif);
_this.col[3].set_hue(h);
return _this.col[3].rotate(dif);
},
analogic: function() {
var dif;
used_colors = _this._add_complement ? 4 : 3;
dif = 60 * _this._distance;
_this.col[1].set_hue(h);
_this.col[1].rotate(dif);
_this.col[2].set_hue(h);
_this.col[2].rotate(360 - dif);
_this.col[3].set_hue(h);
return _this.col[3].rotate(180);
}
};
dispatch['monochromatic'] = dispatch['mono'];
if (dispatch[this._scheme] != null) {
dispatch[this._scheme]();
} else {
throw "Unknown color scheme name: " + this._scheme;
}
output = [];
for (i = _j = 0, _ref1 = used_colors - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) {
for (j = _k = 0; _k <= 3; j = ++_k) {
output[i * 4 + j] = this.col[i].get_hex(this._web_safe, j);
}
}
return output;
};
/*
colorset()
Returns a list of lists of the colors in groups of four. This method simply
allows you to reference a color in the scheme by its group isntead of its
absolute index in the list of colors. I am assuming that "colorset()"
will make it easier to use this module with the templating systems that are
out there.
For example, if you were to follow the synopsis, say you wanted to retrieve
the two darkest colors from the first two groups of the scheme, which is
typically the second color in the group. You could retrieve them with
"colors()"
first_background = (scheme.colors())[1];
second_background = (scheme.colors())[5];
Or, with this method,
first_background = (scheme.colorset())[0][1]
second_background = (scheme.colorset())[1][1]
*/
ColorScheme.prototype.colorset = function() {
var flat_colors, grouped_colors;
flat_colors = clone(this.colors());
grouped_colors = [];
while (flat_colors.length > 0) {
grouped_colors.push(flat_colors.splice(0, 4));
}
return grouped_colors;
};
/*
from_hue( degrees )
Sets the base color hue, where 'degrees' is an integer. (Values greater than
359 and less than 0 wrap back around the wheel.)
The default base hue is 0, or bright red.
*/
ColorScheme.prototype.from_hue = function(h) {
if (h == null) {
throw "from_hue needs an argument";
}
this.col[0].set_hue(h);
return this;
};
ColorScheme.prototype.rgb2hsv = function() {
var b, d, g, h, max, min, r, rgb, s, v;
rgb = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if ((rgb[0] != null) && typeIsArray(rgb[0])) {
rgb = rgb[0];
}
r = rgb[0], g = rgb[1], b = rgb[2];
min = Math.min.apply(Math, [r, g, b]);
max = Math.max.apply(Math, [r, g, b]);
d = max - min;
v = max;
s;
if (d > 0) {
s = d / max;
} else {
return [0, 0, v];
}
h = (r === max ? (g - b) / d : (g === max ? 2 + (b - r) / d : 4 + (r - g) / d));
h *= 60;
h %= 360;
return [h, s, v];
};
/*
from_hex( color )
Sets the base color to the given color, where 'color' is in the hexidecimal
form RRGGBB. 'color' should not be preceded with a hash (#).
The default base color is the equivalent of #ff0000, or bright red.
*/
ColorScheme.prototype.from_hex = function(hex) {
var b, c, g, h, h0, h1, h2, hsv, hsv1, i, i1, i2, k, num, r, rgbcap, s, v, wheelKeys, _ref1, _ref2;
if (hex == null) {
throw "from_hex needs an argument";
}
if (!/^([0-9A-F]{2}){3}$/im.test(hex)) {
throw "from_hex(" + hex + ") - argument must be in the form of RRGGBB";
}
rgbcap = /(..)(..)(..)/.exec(hex).slice(1, 4);
_ref1 = (function() {
var _j, _len1, _results;
_results = [];
for (_j = 0, _len1 = rgbcap.length; _j < _len1; _j++) {
num = rgbcap[_j];
_results.push(parseInt(num, 16));
}
return _results;
})(), r = _ref1[0], g = _ref1[1], b = _ref1[2];
hsv = this.rgb2hsv((function() {
var _j, _len1, _ref2, _results;
_ref2 = [r, g, b];
_results = [];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
i = _ref2[_j];
_results.push(i / 255);
}
return _results;
})());
h0 = hsv[0];
h1 = 0;
h2 = 1000;
i1 = null;
i2 = null;
h = null;
s = null;
v = null;
wheelKeys = [];
_ref2 = ColorScheme.COLOR_WHEEL;
for (i in _ref2) {
if (!__hasProp.call(_ref2, i)) continue;
wheelKeys.push(i);
}
for (i in wheelKeys.sort(function(a, b) {
return a - b;
})) {
c = ColorScheme.COLOR_WHEEL[wheelKeys[i]];
hsv1 = this.rgb2hsv((function() {
var _j, _len1, _ref3, _results;
_ref3 = c.slice(0, 3);
_results = [];
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
i = _ref3[_j];
_results.push(i / 255);
}
return _results;
})());
h = hsv1[0];
if (h >= h1 && h <= h0) {
h1 = h;
i1 = i;
}
if (h <= h2 && h >= h0) {
h2 = h;
i2 = i;
}
}
if (h2 === 0 || h2 > 360) {
h2 = 360;
i2 = 360;
}
k = h2 !== h1 ? (h0 - h1) / (h2 - h1) : 0;
h = Math.round(i1 + k * (i2 - i1));
h %= 360;
s = hsv[1];
v = hsv[2];
this.from_hue(h);
this._set_variant_preset([s, v, s, v * 0.7, s * 0.25, 1, s * 0.5, 1]);
return this;
};
/*
add_complement( BOOLEAN )
If BOOLEAN is true, an extra set of colors will be produced using the
complement of the selected color.
This only works with the analogic color scheme. The default is false.
*/
ColorScheme.prototype.add_complement = function(b) {
if (b == null) {
throw "add_complement needs an argument";
}
this._add_complement = b;
return this;
};
/*
web_safe( BOOL )
Sets whether the colors returned by L<"colors()"> or L<"colorset()"> will be
web-safe.
The default is false.
*/
ColorScheme.prototype.web_safe = function(b) {
if (b == null) {
throw "web_safe needs an argument";
}
this._web_safe = b;
return this;
};
/*
distance( FLOAT )
'FLOAT'> must be a value from 0 to 1. You might use this with the "triade"
"tetrade" or "analogic" color schemes.
The default is 0.5.
*/
ColorScheme.prototype.distance = function(d) {
if (d == null) {
throw "distance needs an argument";
}
if (d < 0) {
throw "distance(" + d + ") - argument must be >= 0";
}
if (d > 1) {
throw "distance(" + d + ") - argument must be <= 1";
}
this._distance = d;
return this;
};
/*
scheme( name )
'name' must be a valid color scheme name. See "Color Schemes". The default
is "mono"
*/
ColorScheme.prototype.scheme = function(name) {
if (name == null) {
throw "scheme needs an argument";
}
if (ColorScheme.SCHEMES[name] == null) {
throw "'" + name + "' isn't a valid scheme name";
}
this._scheme = name;
return this;
};
/*
variation( name )
'name' must be a valid color variation name. See "Color Variations"
*/
ColorScheme.prototype.variation = function(v) {
if (v == null) {
throw "variation needs an argument";
}
if (ColorScheme.PRESETS[v] == null) {
throw "'$v' isn't a valid variation name";
}
this._set_variant_preset(ColorScheme.PRESETS[v]);
return this;
};
ColorScheme.prototype._set_variant_preset = function(p) {
var i, _j, _results;
_results = [];
for (i = _j = 0; _j <= 3; i = ++_j) {
_results.push(this.col[i].set_variant_preset(p));
}
return _results;
};
clone = function(obj) {
var flags, key, newInstance;
if ((obj == null) || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof RegExp) {
flags = '';
if (obj.global != null) {
flags += 'g';
}
if (obj.ignoreCase != null) {
flags += 'i';
}
if (obj.multiline != null) {
flags += 'm';
}
if (obj.sticky != null) {
flags += 'y';
}
return new RegExp(obj.source, flags);
}
newInstance = new obj.constructor();
for (key in obj) {
newInstance[key] = clone(obj[key]);
}
return newInstance;
};
ColorScheme.mutablecolor = (function() {
mutablecolor.prototype.hue = 0;
mutablecolor.prototype.saturation = [];
mutablecolor.prototype.value = [];
mutablecolor.prototype.base_red = 0;
mutablecolor.prototype.base_green = 0;
mutablecolor.prototype.base_saturation = 0;
mutablecolor.prototype.base_value = 0;
function mutablecolor(hue) {
if (hue == null) {
throw "No hue specified";
}
this.saturation = [];
this.value = [];
this.base_red = 0;
this.base_green = 0;
this.base_blue = 0;
this.base_saturation = 0;
this.base_value = 0;
this.set_hue(hue);
this.set_variant_preset(ColorScheme.PRESETS['default']);
}
mutablecolor.prototype.get_hue = function() {
return this.hue;
};
mutablecolor.prototype.set_hue = function(h) {
var avrg, color, colorset1, colorset2, d, derivative1, derivative2, en, i, k;
avrg = function(a, b, k) {
return a + Math.round((b - a) * k);
};
this.hue = Math.round(h % 360);
d = this.hue % 15 + (this.hue - Math.floor(this.hue));
k = d / 15;
derivative1 = this.hue - Math.floor(d);
derivative2 = (derivative1 + 15) % 360;
colorset1 = ColorScheme.COLOR_WHEEL[derivative1];
colorset2 = ColorScheme.COLOR_WHEEL[derivative2];
en = {
red: 0,
green: 1,
blue: 2,
value: 3
};
for (color in en) {
i = en[color];
this["base_" + color] = avrg(colorset1[i], colorset2[i], k);
}
this.base_saturation = avrg(100, 100, k) / 100;
return this.base_value /= 100;
};
mutablecolor.prototype.rotate = function(angle) {
var newhue;
newhue = (this.hue + angle) % 360;
return this.set_hue(newhue);
};
mutablecolor.prototype.get_saturation = function(variation) {
var s, x;
x = this.saturation[variation];
s = x < 0 ? -x * this.base_saturation : x;
if (s > 1) {
s = 1;
}
if (s < 0) {
s = 0;
}
return s;
};
mutablecolor.prototype.get_value = function(variation) {
var v, x;
x = this.value[variation];
v = x < 0 ? -x * this.base_value : x;
if (v > 1) {
v = 1;
}
if (v < 0) {
v = 0;
}
return v;
};
mutablecolor.prototype.set_variant = function(variation, s, v) {
this.saturation[variation] = s;
return this.value[variation] = v;
};
mutablecolor.prototype.set_variant_preset = function(p) {
var i, _j, _results;
_results = [];
for (i = _j = 0; _j <= 3; i = ++_j) {
_results.push(this.set_variant(i, p[2 * i], p[2 * i + 1]));
}
return _results;
};
mutablecolor.prototype.get_hex = function(web_safe, variation) {
var c, color, formatted, i, k, max, min, rgb, rgbVal, s, str, v, _j, _k, _len1, _len2, _ref1;
max = Math.max.apply(Math, (function() {
var _j, _len1, _ref1, _results;
_ref1 = ['red', 'green', 'blue'];
_results = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
color = _ref1[_j];
_results.push(this["base_" + color]);
}
return _results;
}).call(this));
min = Math.min.apply(Math, (function() {
var _j, _len1, _ref1, _results;
_ref1 = ['red', 'green', 'blue'];
_results = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
color = _ref1[_j];
_results.push(this["base_" + color]);
}
return _results;
}).call(this));
v = (variation < 0 ? this.base_value : this.get_value(variation)) * 255;
s = variation < 0 ? this.base_saturation : this.get_saturation(variation);
k = max > 0 ? v / max : 0;
rgb = [];
_ref1 = ['red', 'green', 'blue'];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
color = _ref1[_j];
rgbVal = Math.min.apply(Math, [255, Math.round(v - (v - this["base_" + color] * k) * s)]);
rgb.push(rgbVal);
}
if (web_safe) {
rgb = (function() {
var _k, _len2, _results;
_results = [];
for (_k = 0, _len2 = rgb.length; _k < _len2; _k++) {
c = rgb[_k];
_results.push(Math.round(c / 51) * 51);
}
return _results;
})();
}
formatted = "";
for (_k = 0, _len2 = rgb.length; _k < _len2; _k++) {
i = rgb[_k];
str = i.toString(16);
if (str.length < 2) {
str = "0" + str;
}
formatted += str;
}
return formatted;
};
return mutablecolor;
})();
return ColorScheme;
})();
if ((typeof module !== "undefined" && module !== null) && (module.exports != null)) {
module.exports = ColorScheme;
} else {
if (typeof define === 'function' && define.amd) {
define([], function() {
return ColorScheme;
});
} else {
window.ColorScheme = ColorScheme;
}
}
}).call(this);
|
describe('@get', function () {
//Using assert method
it('should return a 200 OK status code for PostID 1', function (done) {
utils.httpGET('/posts/1', {})
.set('content-type', 'application/json; charset=utf-8')
.expect(function (res) {
const response = res.body;
//console.log(response);
return assert.deepEqual(response,
{
"id": "1",
"title": "foo",
"body": "bar",
"userId": 1
})
})
.expect(200, done);
});
//Using expect method
it('should return a 200 OK status code for PostID 1 using expect method', function (done) {
utils.httpGET('/posts/1', {})
.set('content-type', 'application/json; charset=utf-8')
.expect(function (res) {
const response = res.body;
//console.log(response);
expect(response).to.have.property('id');
expect(response).to.have.property('title');
expect(response).to.have.property('body');
expect(response).to.have.property('userId');
expect(response.id).to.equal('1');
})
.expect(200, done);
});
});
|
/*
Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
(function(){CKEDITOR.plugins.add("selectall",{lang:"af,ar,az,bg,bn,bs,ca,cs,cy,da,de,de-ch,el,en,en-au,en-ca,en-gb,eo,es,es-mx,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,oc,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn",icons:"selectall",hidpi:!0,init:function(b){b.addCommand("selectAll",{modes:{wysiwyg:1,source:1},exec:function(a){var b=a.editable();if(b.is("textarea"))a=b.$,CKEDITOR.env.ie&&a.createTextRange?a.createTextRange().execCommand("SelectAll"):
(a.selectionStart=0,a.selectionEnd=a.value.length),a.focus();else{if(b.is("body"))a.document.$.execCommand("SelectAll",!1,null);else{var c=a.createRange();c.selectNodeContents(b);c.select()}a.forceNextSelectionCheck();a.selectionChange()}},canUndo:!1});b.ui.addButton&&b.ui.addButton("SelectAll",{label:b.lang.selectall.toolbar,command:"selectAll",toolbar:"selection,10"})}})})();
|
/**
* @license Highstock JS v8.1.0 (2020-05-05)
* @module highcharts/indicators/indicators
* @requires highcharts
* @requires highcharts/modules/stock
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Pawel Fus, Sebastian Bochan
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../indicators/indicators.src.js';
|
//
// http://24ways.org/2013/grunt-is-not-weird-and-hard/
//
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
connect: {
test: {
options: {
port: 8612,
hostname: 'localhost'
}
},
keepalive: {
options: {
port: 8619,
host: "localhost",
keepalive: true,
open: "http://localhost:8619/test/SpecRunner.html"
}
}
},
mocha: {
test: {
options: {
log: true,
logErrors: true,
reporter: "Spec",
run: false,
timeout: 10000,
urls: ["http://localhost:8612/test/SpecRunner.html"]
}
}
}
});
grunt.loadNpmTasks("grunt-mocha");
grunt.loadNpmTasks("grunt-contrib-connect");
grunt.registerTask("serve", ["connect:keepalive"]);
grunt.registerTask("test", ["connect:test", "mocha:test"]);
};
|
import {EntityManager} from '../src/aurelia-orm';
import {Container} from 'aurelia-dependency-injection';
import {WithResource} from './resources/entity/with-resource';
import {WithCustomRepository} from './resources/entity/with-custom-repository';
import {SimpleCustom} from './resources/repository/simple-custom';
import {DefaultRepository} from '../src/default-repository';
import {Entity} from '../src/entity';
describe('EntityManager', function() {
describe('.registerEntities()', function() {
it('Should register entities with the manager', function() {
let entityManager = new EntityManager(new Container());
entityManager.registerEntities([WithResource]);
expect(entityManager.entities).toEqual({'with-resource': WithResource});
});
it('Should return self.', function() {
let entityManager = new EntityManager(new Container());
expect(entityManager.registerEntities([WithResource])).toBe(entityManager);
});
});
describe('.registerEntity()', function() {
it('Should return self.', function() {
let entityManager = new EntityManager(new Container());
expect(entityManager.registerEntity(WithResource)).toBe(entityManager);
});
it('Should register an entity with the manager', function() {
let entityManager = new EntityManager(new Container());
entityManager.registerEntity(WithResource);
expect(entityManager.entities).toEqual({'with-resource': WithResource});
});
});
describe('.getRepository()', function() {
it('Should return the default repository when no custom specified. (Entity resource)', function() {
let entityManager = new EntityManager(new Container());
entityManager.registerEntity(WithResource);
expect(entityManager.getRepository('with-resource') instanceof DefaultRepository).toBe(true);
});
it('Should return the default repository when no custom specified. (Entity reference)', function() {
let entityManager = new EntityManager(new Container());
entityManager.registerEntity(WithResource);
expect(entityManager.getRepository(WithResource) instanceof DefaultRepository).toBe(true);
});
it('Should return the custom repository when specified.', function() {
let entityManager = new EntityManager(new Container());
entityManager.registerEntity(WithCustomRepository);
expect(entityManager.getRepository(WithCustomRepository) instanceof SimpleCustom).toBe(true);
});
it('Should return the default repository when no custom specified. (bullshit resource)', function() {
let entityManager = new EntityManager(new Container());
expect(entityManager.getRepository('does-not-exist') instanceof DefaultRepository).toBe(true);
});
it('Should cache the repository if it was composed from the DefaultRepository.', function() {
let entityManager = new EntityManager(new Container());
// No cache
expect(entityManager.repositories['please-cache-this'] instanceof DefaultRepository).toBe(false);
// Get, and set cache
expect(entityManager.getRepository('please-cache-this') instanceof DefaultRepository).toBe(true);
// Verify cache
expect(entityManager.repositories['please-cache-this'] instanceof DefaultRepository).toBe(true);
// Verify cache gets used
expect(entityManager.getRepository('please-cache-this') === entityManager.repositories['please-cache-this']).toBe(true);
});
it('Should throw an error when given an object without resource metadata.', function() {
let entityManager = new EntityManager(new Container());
expect(function() {
entityManager.getRepository(function() {});
}).toThrowError(Error, 'Unable to find resource for entity.');
});
});
describe('.resolveEntityReference()', function() {
it('Should resolve to the correct entityReference. (Custom Entity reference)', function() {
let entityManager = new EntityManager(new Container());
entityManager.registerEntity(WithResource);
expect(entityManager.resolveEntityReference(WithResource) === WithResource).toBe(true);
});
it('Should resolve to the correct entityReference. (Custom Entity resource)', function() {
let entityManager = new EntityManager(new Container());
entityManager.registerEntity(WithResource);
expect(entityManager.resolveEntityReference('with-resource') === WithResource).toBe(true);
});
it('Should resolve to the correct entityReference. (Entity reference)', function() {
let entityManager = new EntityManager(new Container());
expect(entityManager.resolveEntityReference(Entity) === Entity).toBe(true);
});
it('Should resolve to the correct entityReference. (Entity resource)', function() {
let entityManager = new EntityManager(new Container());
expect(entityManager.resolveEntityReference('foo') === Entity).toBe(true);
});
it('Should throw an error on invalid input type.', function() {
let entityManager = new EntityManager(new Container());
expect(function() {
entityManager.resolveEntityReference({});
}).toThrowError(Error, 'Unable to resolve to entity reference. Expected string or function.');
});
});
describe('.getEntity()', function() {
it('Should return a new `WithResource` instance (Entity reference).', function() {
let entityManager = new EntityManager(new Container());
expect(entityManager.getEntity(WithResource) instanceof WithResource).toBe(true);
});
it('Should return a new `WithResource` instance (Entity resource).', function() {
let entityManager = new EntityManager(new Container());
entityManager.registerEntity(WithResource);
expect(entityManager.getEntity('with-resource') instanceof WithResource).toBe(true);
});
it('Should return a new `Entity` instance.', function() {
let entityManager = new EntityManager(new Container());
expect(entityManager.getEntity('cake') instanceof Entity).toBe(true);
});
it('Should throw an error for entity without a resource.', function() {
let entityManager = new EntityManager(new Container());
expect(function() {
entityManager.getEntity(Entity);
}).toThrowError(Error, 'Unable to find resource for entity.');
});
});
});
|
"use strict"
var QM = (function(QM){
function ActiveGameData(campaign){
this.campaign = campaign;
this.activeLevel = 0;
this.activeMapSprites = [];
this.activeTeam = 0;
this.activeCreature = 0;
this.activeCreatureSprites = {};
this.activeMap = new QM.API.Map(this.campaign.levels[this.activeLevel].mapData.map);
console.log(this.activeMap);
this.turn = 0;
this.creatures = loadCreatures(this.campaign, this.activeLevel);
};
function loadCreatures(campaign, activeLevel){
var creatures = [];
var cTemplate = campaign.creatureTemplates;
for(var n = 0; n < campaign.levels[activeLevel].teams.length; n++){
creatures[n] = [];
for(var c = 0; c < campaign.levels[activeLevel].teams[n].creatures.length; c++){
creatures[n][c] = new QM.API.Creature();
creatures[n][c].team = campaign.levels[activeLevel].teams[n].name;
creatures[n][c].templateID = campaign.levels[activeLevel].teams[n].creatures[c].templateID;
creatures[n][c].name = cTemplate[campaign.levels[activeLevel].teams[n].creatures[c].templateID].name
creatures[n][c].body.base = cTemplate[campaign.levels[activeLevel].teams[n].creatures[c].templateID].body
creatures[n][c].mind.base = cTemplate[campaign.levels[activeLevel].teams[n].creatures[c].templateID].mind;
creatures[n][c].attackDice = cTemplate[campaign.levels[activeLevel].teams[n].creatures[c].templateID].attackDice;
creatures[n][c].defendDice = cTemplate[campaign.levels[activeLevel].teams[n].creatures[c].templateID].defendDice;
creatures[n][c].moveDice = cTemplate[campaign.levels[activeLevel].teams[n].creatures[c].templateID].moveDice;
creatures[n][c].moveTotal = cTemplate[campaign.levels[activeLevel].teams[n].creatures[c].templateID].moveTotal;
//creatures[n][c].leftHand = undefined;
//creatures[n][c].rightHand = undefined;
//creaures[n][c].chest = undefined;
//creatures[n][c].head = undefined;
creatures[n][c].posX = campaign.levels[activeLevel].teams[n].creatures[c].posX;
creatures[n][c].posY = campaign.levels[activeLevel].teams[n].creatures[c].posY;
if(creatures[n][c].team == "Zargon"){
creatures[n][c].active = false;
} else {
creatures[n][c].active = true;
}
console.log(creatures[n][c].team);
}
}
return creatures;
}
ActiveGameData.prototype.loadMapSprites = function(){
for(var key in this.campaign.levels[this.activeLevel].mapData.spriteIndex){
try{
this.activeMapSprites[key] = LoadImage(this.campaign.levels[this.activeLevel].mapData.spriteIndex[key]);
} catch (e) { console.log(e); };
}
};
ActiveGameData.prototype.loadCreatureSprites = function(){
for(var key in this.campaign.creatureTemplates){
this.activeCreatureSprites[key] = LoadImage(this.campaign.creatureTemplates[key].sprite);
}
}
ActiveGameData.prototype.getActiveCreature = function(){
return this.creatures[this.activeTeam][this.activeCreature];
}
QM.ActiveGameData = ActiveGameData;
return QM;
})(QM || {});
|
define({main:{"be-BY":{identity:{version:{_cldrVersion:"24",_number:"$Revision: 9061 $"},generation:{_date:"$Date: 2013-07-20 12:27:45 -0500 (Sat, 20 Jul 2013) $"},language:"be",territory:"BY"},dates:{calendars:{gregorian:{months:{format:{abbreviated:{1:"сту",2:"лют",3:"сак",4:"кра",5:"мая",6:"чэр",7:"ліп",8:"жні",9:"вер",10:"кас",11:"ліс",12:"сне"},narrow:{1:"с",2:"л",3:"с",4:"к",5:"м",6:"ч",7:"л",8:"ж",9:"в",10:"к",11:"л",12:"с"},wide:{1:"студзеня",2:"лютага",3:"сакавіка",4:"красавіка",5:"мая",
6:"чэрвеня",7:"ліпеня",8:"жніўня",9:"верасня",10:"кастрычніка",11:"лістапада",12:"снежня"}},"stand-alone":{abbreviated:{1:"сту",2:"лют",3:"сак",4:"кра",5:"май",6:"чэр",7:"ліп",8:"жні",9:"вер",10:"кас",11:"ліс",12:"сне"},narrow:{1:"с",2:"л",3:"с",4:"к",5:"м",6:"ч",7:"л",8:"ж",9:"в",10:"к",11:"л",12:"с"},wide:{1:"студзень",2:"люты",3:"сакавік",4:"красавік",5:"май",6:"чэрвень",7:"ліпень",8:"жнівень",9:"верасень",10:"кастрычнік",11:"лістапад",12:"снежань"}}},days:{format:{abbreviated:{sun:"нд",mon:"пн",
tue:"аў",wed:"ср",thu:"чц",fri:"пт",sat:"сб"},narrow:{sun:"н",mon:"п",tue:"а",wed:"с",thu:"ч",fri:"п",sat:"с"},wide:{sun:"нядзеля",mon:"панядзелак",tue:"аўторак",wed:"серада",thu:"чацвер",fri:"пятніца",sat:"субота"}},"stand-alone":{abbreviated:{sun:"нд",mon:"пн",tue:"аў",wed:"ср",thu:"чц",fri:"пт",sat:"сб"},narrow:{sun:"н",mon:"п",tue:"а",wed:"с",thu:"ч",fri:"п",sat:"с"},wide:{sun:"нядзеля",mon:"панядзелак",tue:"аўторак",wed:"серада",thu:"чацвер",fri:"пятніца",sat:"субота"}}},dayPeriods:{format:{wide:{am:"да палудня",
pm:"пасля палудня"}}},eras:{eraAbbr:{0:"да н.э.",1:"н.э."}},dateFormats:{full:"EEEE, d MMMM y","long":"d MMMM y",medium:"d.M.y","short":"d.M.yy"},timeFormats:{full:"HH.mm.ss zzzz","long":"HH.mm.ss z",medium:"HH.mm.ss","short":"HH.mm"},dateTimeFormats:{full:"{1} {0}","long":"{1} {0}",medium:"{1} {0}","short":"{1} {0}",availableFormats:{d:"d",Ed:"d, E",Ehm:"E h:mm a",EHm:"E HH:mm",Ehms:"E h:mm:ss a",EHms:"E HH:mm:ss",Gy:"y G",GyMMM:"LLL y G",GyMMMd:"d MMM y G",GyMMMEd:"E, d MMM y G",h:"h a",H:"HH",
hm:"h.mm a",Hm:"HH.mm",hms:"h.mm.ss a",Hms:"HH.mm.ss",M:"L",Md:"d.M",MEd:"E, d.M",MMM:"LLL",MMMd:"d MMM",MMMEd:"E, d MMM",MMMMd:"d MMMM",MMMMEd:"E, d MMMM",ms:"mm.ss",y:"y",yM:"M.y",yMd:"d.M.y",yMEd:"E, d.M.y",yMMM:"LLL y",yMMMd:"d MMM y",yMMMEd:"E, d MMM y",yMMMM:"LLLL y",yQQQ:"QQQ y",yQQQQ:"QQQQ y"}}}},fields:{era:{displayName:"эра"},year:{displayName:"год","relative-type--1":"last year","relative-type-0":"this year","relative-type-1":"next year"},month:{displayName:"месяц","relative-type--1":"last month",
"relative-type-0":"this month","relative-type-1":"next month"},week:{displayName:"тыдзень","relative-type--1":"last week","relative-type-0":"this week","relative-type-1":"next week"},day:{displayName:"дзень","relative-type--1":"учора","relative-type-0":"сёння","relative-type-1":"заўтра"},weekday:{displayName:"дзень тыдня"},dayperiod:{displayName:"ДП/ПП"},hour:{displayName:"гадзіна"},minute:{displayName:"хвіліна"},second:{displayName:"секунда"},zone:{displayName:"Zone"}}},numbers:{defaultNumberingSystem:"latn",
otherNumberingSystems:{"native":"latn"},"symbols-numberSystem-latn":{decimal:",",group:" ",list:";",percentSign:"%",plusSign:"+",minusSign:"-",exponential:"E",perMille:"‰",infinity:"∞",nan:"NaN"},"decimalFormats-numberSystem-latn":{standard:"#,##0.###","long":{decimalFormat:{"1000-count-other":"0K","10000-count-other":"00K","100000-count-other":"000K","1000000-count-other":"0M","10000000-count-other":"00M","100000000-count-other":"000M","1000000000-count-other":"0G","10000000000-count-other":"00G",
"100000000000-count-other":"000G","1000000000000-count-other":"0T","10000000000000-count-other":"00T","100000000000000-count-other":"000T"}},"short":{decimalFormat:{"1000-count-other":"0K","10000-count-other":"00K","100000-count-other":"000K","1000000-count-other":"0M","10000000-count-other":"00M","100000000-count-other":"000M","1000000000-count-other":"0G","10000000000-count-other":"00G","100000000000-count-other":"000G","1000000000000-count-other":"0T","10000000000000-count-other":"00T","100000000000000-count-other":"000T"}}},
"percentFormats-numberSystem-latn":{standard:"#,##0%"},"currencyFormats-numberSystem-latn":{standard:"¤#,##0.00","unitPattern-count-other":"{0} {1}"},currencies:{AUD:{displayName:"аўстралійскі даляр",symbol:"A$"},BRL:{displayName:"бразільскі рэал",symbol:"R$"},CAD:{displayName:"CAD",symbol:"CA$"},CHF:{displayName:"CHF",symbol:"CHF"},CNY:{displayName:"кітайскі юань",symbol:"CN¥"},DKK:{displayName:"DKK",symbol:"DKK"},EUR:{displayName:"еўра",symbol:"€"},GBP:{displayName:"англійскі фунт",symbol:"£"},
HKD:{displayName:"HKD",symbol:"HK$"},IDR:{displayName:"IDR",symbol:"IDR"},INR:{displayName:"індыйская рупія",symbol:"₹"},JPY:{displayName:"японская іена",symbol:"¥"},KRW:{displayName:"KRW",symbol:"₩"},MXN:{displayName:"MXN",symbol:"MX$"},NOK:{displayName:"нарвэская крона",symbol:"NOK"},PLN:{displayName:"PLN",symbol:"PLN"},RUB:{displayName:"рускі рубель",symbol:"рас. руб."},SAR:{displayName:"SAR",symbol:"SAR"},SEK:{displayName:"SEK",symbol:"SEK"},THB:{displayName:"THB",symbol:"฿"},TRY:{displayName:"TRY",
symbol:"TRY"},TWD:{displayName:"TWD",symbol:"NT$"},USD:{displayName:"долар ЗША",symbol:"$"},ZAR:{displayName:"ZAR",symbol:"ZAR"}}}}}});
|
//UUID/Guid Generator
//http://frugalcoder.us/post/2012/01/13/javascript-guid-uuid-generator.aspx
// use: UUID.create() or UUID.createSequential()
// convenience: UUID.empty, UUID.tryParse(string)
(function(w){
// From http://baagoe.com/en/RandomMusings/javascript/
// Johannes Baagøe <baagoe@baagoe.com>, 2010
function Mash() {
var n = 0xefc8249d;
var mash = function(data) {
data = data.toString();
for (var i = 0; i < data.length; i++) {
n += data.charCodeAt(i);
var h = 0.02519603282416938 * n;
n = h >>> 0;
h -= n;
h *= n;
n = h >>> 0;
h -= n;
n += h * 0x100000000; // 2^32
}
return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
};
mash.version = 'Mash 0.9';
return mash;
}
// From http://baagoe.com/en/RandomMusings/javascript/
function Kybos() {
return (function(args) {
// Johannes Baagøe <baagoe@baagoe.com>, 2010
var s0 = 0;
var s1 = 0;
var s2 = 0;
var c = 1;
var s = [];
var k = 0;
var mash = Mash();
var s0 = mash(' ');
var s1 = mash(' ');
var s2 = mash(' ');
for (var j = 0; j < 8; j++) {
s[j] = mash(' ');
}
if (args.length == 0) {
args = [+new Date];
}
for (var i = 0; i < args.length; i++) {
s0 -= mash(args[i]);
if (s0 < 0) {
s0 += 1;
}
s1 -= mash(args[i]);
if (s1 < 0) {
s1 += 1;
}
s2 -= mash(args[i]);
if (s2 < 0) {
s2 += 1;
}
for (var j = 0; j < 8; j++) {
s[j] -= mash(args[i]);
if (s[j] < 0) {
s[j] += 1;
}
}
}
var random = function() {
var a = 2091639;
k = s[k] * 8 | 0;
var r = s[k];
var t = a * s0 + c * 2.3283064365386963e-10; // 2^-32
s0 = s1;
s1 = s2;
s2 = t - (c = t | 0);
s[k] -= s2;
if (s[k] < 0) {
s[k] += 1;
}
return r;
};
random.uint32 = function() {
return random() * 0x100000000; // 2^32
};
random.fract53 = function() {
return random() +
(random() * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
};
random.addNoise = function() {
for (var i = arguments.length - 1; i >= 0; i--) {
for (j = 0; j < 8; j++) {
s[j] -= mash(arguments[i]);
if (s[j] < 0) {
s[j] += 1;
}
}
}
};
random.version = 'Kybos 0.9';
random.args = args;
return random;
} (Array.prototype.slice.call(arguments)));
};
var rnd = Kybos();
// UUID/GUID implementation from http://frugalcoder.us/post/2012/01/13/javascript-guid-uuid-generator.aspx
var UUID = {
"empty": "00000000-0000-0000-0000-000000000000"
,"parse": function(input) {
var ret = input.toString().trim().toLowerCase().replace(/^[\s\r\n]+|[\{\}]|[\s\r\n]+$/g, "");
if ((/[a-f0-9]{8}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{4}\-[a-f0-9]{12}/).test(ret))
return ret;
else
throw new Error("Unable to parse UUID");
}
,"createSequential": function() {
var ret = new Date().valueOf().toString(16).replace("-","")
for (;ret.length < 12; ret = "0" + ret);
ret = ret.substr(ret.length-12,12); //only least significant part
for (;ret.length < 32;ret += Math.floor(rnd() * 0xffffffff).toString(16));
return [ret.substr(0,8), ret.substr(8,4), "4" + ret.substr(12,3), "89AB"[Math.floor(Math.random()*4)] + ret.substr(16,3), ret.substr(20,12)].join("-");
}
,"create": function() {
var ret = "";
for (;ret.length < 32;ret += Math.floor(rnd() * 0xffffffff).toString(16));
return [ret.substr(0,8), ret.substr(8,4), "4" + ret.substr(12,3), "89AB"[Math.floor(Math.random()*4)] + ret.substr(16,3), ret.substr(20,12)].join("-");
}
,"random": function() {
return rnd();
}
,"tryParse": function(input) {
try {
return UUID.parse(input);
} catch(ex) {
return UUID.empty;
}
}
};
UUID["new"] = UUID.create;
w.UUID = w.Guid = UUID;
}(window || this));
|
'use strict';
/**
* Module dependencies
*/
var fs = require('fs');
var utils = require('lazy-cache')(require);
var fn = require;
require = utils;
/**
* Lazily required module dependencies
*/
require('async-each', 'each');
require('bluebird', 'Promise');
require('extend-shallow', 'extend');
require('file-contents', 'contents');
require('glob-parent');
require('graceful-fs', 'fs');
require('has-glob');
require('is-absolute');
require('matched', 'glob');
require('mkdirp');
require('resolve-dir', 'resolve');
require('to-file');
require = fn;
/**
* Gets the file stats for a File object.
*
* @param {Object} `file` File object that has a `path` property.
* @return {Object} `fs.stat` object if successful. Otherwise an empty object.
*/
utils.stat = function(file) {
try {
return fs.lstatSync(file.path);
} catch (err) {}
return {};
};
/**
* Checks if the file is a directory using `fs.lstatSync`.
*
* @param {String|Object} `file` filepath as a string or a file object with a `path` property.
* @return {Boolean} Returns `true` when the filepath is a directory.
*/
utils.isDirectory = function(file) {
if (typeof file === 'string') {
file = {path: file}
}
var stat = utils.stat(file);
if (stat.isDirectory) {
return stat.isDirectory();
}
return false;
};
/**
* Get the base filepath from a glob.
*
* @param {Array|String} `patterns`
* @return {String}
*/
utils.parent = function(patterns) {
if (Array.isArray(patterns)) {
return utils.globParent(patterns[0]);
}
return utils.globParent(patterns);
};
/**
* Cast `val` to an array.
*
* @param {any} val
* @return {Array}
*/
utils.arrayify = function(val) {
return val ? (Array.isArray(val) ? val : [val]) : [];
};
/**
* Expose `utils` modules
*/
module.exports = utils;
|
import Vue from 'vue';
import VueResource from 'vue-resource';
Vue.use(VueResource);
export default class PipelineService {
constructor(endpoint) {
this.pipeline = Vue.resource(endpoint);
}
getPipeline() {
return this.pipeline.get();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.