code stringlengths 2 1.05M |
|---|
import * as actions from 'redux/actions'
import _ from 'lodash'
export default (
institutionId,
adjudicator,
index,
dispatch
) => {
let arrayConflictedInstitutionId = adjudicator.institutionConflicts.map(i => i)
arrayConflictedInstitutionId.splice(index, 1)
let body = _.cloneDeep(adjudicator)
body.institutionConflicts = arrayConflictedInstitutionId
dispatch(actions.asians.adjudicators.update(adjudicator._tournament, adjudicator._id, body))
}
|
var ray_8hpp =
[
[ "ray", "dd/d62/classstd_1_1math_1_1ray.html", "dd/d62/classstd_1_1math_1_1ray" ],
[ "operator!=", "db/d1d/ray_8hpp.html#a8fafcb6fe8bc04807f9131e9d2f56b52", null ],
[ "operator==", "db/d1d/ray_8hpp.html#a215a737a63e14a75759768c56de69568", null ]
]; |
'use strict';
/**
* Dependencies
*/
var should = require('should');
var _ = require('lodash');
var path = require('path');
var commander = require(path.join(process.cwd(), 'bin', 'koan'));
describe('Program', function() {
it('should have a command to display the version number', function(done) {
_.map(commander.commands, function(command) {
return command._name;
}).should.containEql('version');
_.map(commander.options, function(option) {
return option.short;
}).should.containEql('-v');
_.map(commander.options, function(option) {
return option.long;
}).should.containEql('--version');
done();
});
it('should have a command to display the usage', function(done) {
_.map(commander.commands, function(command) {
return command._name;
}).should.containEql('help');
done();
});
it('should have a command to generate a new application', function(done) {
_.map(commander.commands, function(command) {
return command._name;
}).should.containEql('new');
done();
});
it('should have a command to start the application', function(done) {
_.map(commander.commands, function(command) {
return command._name;
}).should.containEql('start');
done();
});
it('should have a command to generate a new controller', function(done) {
_.map(commander.commands, function(command) {
return command._name;
}).should.containEql('controller');
done();
});
it('should have a command to generate a new model', function(done) {
_.map(commander.commands, function(command) {
return command._name;
}).should.containEql('model');
done();
});
it('should have a command to generate a new RESTful resource', function(done) {
_.map(commander.commands, function(command) {
return command._name;
}).should.containEql('resource');
done();
});
});
|
$(function(){
var $grid = $('.grid');
$grid.on('after-displaying-grid-data.xg', function (e, data) {
var event = new Event('resize');
window.dispatchEvent(event);
$(window).trigger('resize')
});
}); |
version https://git-lfs.github.com/spec/v1
oid sha256:282458a85e1669512cbc54e0bfa05bb2ec8a4aad851c8be6e6e5d63b3065863b
size 1633
|
/*jslint browser: true, vars: true, indent: 2, maxlen: 120 */
/*global define */
//----------------------------------------------------------------------------------------------------------------------
define(
'SetBased/Abc/Core/OverviewTable',
['jquery', 'SetBased/Abc/Table/OverviewTable'],
function ($, BaseOverviewTable) {
"use strict";
//------------------------------------------------------------------------------------------------------------------
/**
* Object constructor.
*
* @param table
* @constructor
*/
function OverviewTable(table) {
// Use parent constructor.
BaseOverviewTable.call(this, table);
}
//------------------------------------------------------------------------------------------------------------------
// Extend OverviewTable from BaseOverviewTable.
OverviewTable.prototype = Object.create(BaseOverviewTable.prototype);
// Set constructor for OverviewTable.
OverviewTable.constructor = OverviewTable;
//------------------------------------------------------------------------------------------------------------------
OverviewTable.prototype.filterHook = function () {
var all;
var visible;
all = this.$myTable.children('tbody').children('tr').length;
visible = this.$myTable.children('tbody').children('tr:visible').length;
if (all === visible) {
this.$myTable.find('span.row_count').text(all);
} else {
this.$myTable.find('span.row_count').text(visible + '/' + all);
}
};
//------------------------------------------------------------------------------------------------------------------
/**
* Registers tables that matches a jQuery selector as a BaseOverviewTable (and OverviewTable).
*
* @param selector The jQuery selector.
*/
OverviewTable.registerTable = function (selector) {
// Register all overview tables as a BaseOverviewTable (and OverviewTable).
BaseOverviewTable.registerTable(selector, 'OverviewTable');
};
//------------------------------------------------------------------------------------------------------------------
return BaseOverviewTable;
}
);
//----------------------------------------------------------------------------------------------------------------------
|
define(["js/data/Collection", "app/model/Todo", "flow"], function (Collection, Todo, flow) {
return Collection.inherit("app.collection.TodoList", {
$modelFactory: Todo,
areAllComplete: function () {
if (this.$items.length === 0) {
return false;
}
for (var i = 0; i < this.$items.length; i++) {
if (!this.$items[i].isCompleted()) {
return false;
}
}
return true;
}.on('change', 'add', 'remove'),
clearCompleted: function () {
var self = this;
// remove all completed todos in a sequence
flow().seqEach(this.$items,function (todo, cb) {
if (todo.isCompleted()) {
// remove the todo
todo.remove(null, function (err) {
if (!err) {
self.remove(todo);
}
cb(err);
});
} else {
cb();
}
}).exec();
},
size: function(){
return this.$items.length;
}.on('change', 'add', 'remove'),
numOpenTodos: function () {
var num = 0;
for (var i = 0; i < this.$items.length; i++) {
if (!this.$items[i].isCompleted()) {
num++;
}
}
return num;
}.on('change', 'add', 'remove'),
numCompletedTodos: function () {
var num = 0;
for (var i = 0; i < this.$items.length; i++) {
if (this.$items[i].isCompleted()) {
num++;
}
}
return num;
}.on('change', 'add', 'remove'),
hasCompletedTodos: function () {
return this.numCompletedTodos() > 0;
}.on('change', 'add', 'remove')
});
}); |
/* globals $ */
/*
Create a function that takes a selector and COUNT, then generates inside a UL with COUNT LIs:
* The UL must have a class `items-list`
* Each of the LIs must:
* have a class `list-item`
* content "List item #INDEX"
* The indices are zero-based
* If the provided selector does not selects anything, do nothing
* Throws if
* COUNT is a `Number`, but is less than 1
* COUNT is **missing**, or **not convertible** to `Number`
* _Example:_
* Valid COUNT values:
* 1, 2, 3, '1', '4', '1123'
* Invalid COUNT values:
* '123px' 'John', {}, []
*/
function solve() {
function isConvertibleToNumber(num, callerID) {
if (isNaN(+num) || num === null || num === '') {
return false;
} else {
return true;
}
}
return function(selector, count) {
var $ul,
i,
$matchedElements;
if (typeof selector !== 'string') {
throw new Error('Selector must be string');
}
if (!isConvertibleToNumber(count)) {
throw new Error('Argument must be convertible to number');
}
if (count < 1) {
throw new Error('Count must be greater than or equal to 1');
}
$ul = $('<ul />').addClass('items-list');
count = parseInt(count);
for (i = 0; i < count; i += 1) {
$ul.append($('<li />').addClass('list-item').html('List item #' + i));
}
$matchedElements = $(selector);
if ($matchedElements) {
$matchedElements.append($ul);
}
};
}
module.exports = solve; |
$(function () {
console.log("ESAT Microsites");
//////////////////////////
// Imantación apartados //
//////////////////////////
// $("ul.content").snapscroll({
// 'scrollEndSpeed': '600',
// 'topPadding': '250',
// 'scrollOptions': {
// 'interrupt': 'true'
// }
// });
/////////////////////
// Menu navegación //
/////////////////////
/* $("nav ul li a").click(function () {
$("nav ul li").removeClass("active");
$(this).parent().addClass("active");
});*/
////////////////////////////////
// Menu show / hide on scroll //
////////////////////////////////
/* var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();
$(window).scroll(function (event) {
didScroll = true;
});
setInterval(function () {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
// Make sure they scroll more than delta
if (Math.abs(lastScrollTop - st) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight) {
// Scroll Down
$('header').removeClass('nav-down').addClass('nav-up');
} else {
// Scroll Up
if (st + $(window).height() < $(document).height()) {
$('header').removeClass('nav-up').addClass('nav-down');
}
}
lastScrollTop = st;
}*/
//$('#menu2').slicknav();
//////////////////
// Share Social //
//////////////////
$('#twitter').sharrre({
share: {
twitter: true
},
template: '<button type="button" class="btn btn-default btn-lg"><i class="custom-icon"></i>{total}</button>',
enableHover: false,
enableTracking: true,
buttons: {
twitter: {
via: '_JulienH'
}
},
click: function (api, options) {
api.simulateClick();
api.openPopup('twitter');
}
});
$('#facebook').sharrre({
share: {
facebook: true
},
template: '<button type="button" class="btn btn-default btn-lg"><i class="custom-icon"></i>{total}</button>',
enableHover: false,
enableTracking: true,
click: function (api, options) {
api.simulateClick();
api.openPopup('facebook');
}
});
$('#linkedin').sharrre({
share: {
linkedin: true
},
template: '<button type="button" class="btn btn-default btn-lg"><i class="custom-icon"></i>{total}</button>',
enableHover: false,
enableTracking: true,
click: function (api, options) {
api.simulateClick();
api.openPopup('googlePlus');
}
});
/////////////////////////////////////
// Scroll to content on click menu //
/////////////////////////////////////
$('a[href*=#]:not([href=#])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 90
}, 1000);
return false;
}
}
});
////////////////////////////////////
// Owl Carousel - Galería escuela //
////////////////////////////////////
$('#apartado3 .owl-carousel').owlCarousel({
animateOut: 'fadeOut',
animateIn: 'fadeIn',
items: 1,
margin: 20,
stagePadding: 0,
smartSpeed: 450
});
$('#apartado4 .owl-carousel').owlCarousel({
items: 1,
margin: 0,
stagePadding: 0,
smartSpeed: 450
});
//$( ".owl-stage-outer " ).wrap( "<div class='bordeOwl'></div>" );
/////////////////
// Tooltipster //
/////////////////
$('#apartado4 .owl-dot').addClass('_tooltip');
$('#apartado4 .owl-dot:eq(0)').attr('title', '1º Año');
$('#apartado4 .owl-dot:eq(1)').attr('title', '2º Año');
$('#apartado4 .owl-dot:eq(2)').attr('title', '3º Año');
$('#apartado4 .owl-dot:eq(3)').attr('title', '4º Año (Opcional)');
$('._tooltip').tooltipster({
theme: 'tooltipster-shadow'
});
//////////////////////
// VENTANAS MODALES //
//////////////////////
$('#btn-legal').on('click', function (e) {
e.preventDefault();
Custombox.open({
target: '#modal-legal',
effect: 'blur'
});
return false;
});
$('#btn-sobreESAT').on('click', function (e) {
e.preventDefault();
Custombox.open({
target: '#modal-sobreESAT',
effect: 'blur'
});
return false;
});
$('#btn-INFO').on('click', function (e) {
e.preventDefault();
Custombox.open({
target: '#modal-INFO',
effect: 'blur'
});
return false;
});
/////////////////////////////
// Scroll to Top & Reserva //
/////////////////////////////
$("#goUp").click(function () {
$('html,body').animate({
scrollTop: $("#apartado1").offset().top
}, 1000);
});
$("#btn-RESERVA ,#btn-RESERVA2").click(function () {
$('html,body').animate({
scrollTop: $("#apartado7").offset().top
}, 1000);
});
$(window).scroll(function () {
if ($(this).scrollTop()) {
$('#goUp:hidden').stop(true, true).fadeIn();
} else {
$('#goUp').stop(true, true).fadeOut();
}
});
$('.itemInView').bind('inview', function (event, isInView, visiblePartX, visiblePartY) {
if (isInView) {
// element is now visible in the viewport
if (visiblePartY == 'top') {
// top part of element is visible
//console.log($(this).attr('id'));
//var _index = $(this).attr('id').substring(8, 9);
} else if (visiblePartY == 'bottom') {
// bottom part of element is visible
} else {
// whole part of element is visible
$("nav ul li").removeClass("active");
var _index = $(this).data("apartado");
var index = _index - 1;
$("nav ul li:eq(" + index + ")").addClass("active");
console.log(this);
}
} else {
}
});
//////////////////////////
// ANIMA OBJETOS INVIEW //
//////////////////////////
$('.itemAnimaInView').bind('inview', function (event, isInView, visiblePartX, visiblePartY) {
if (isInView) {
// element is now visible in the viewport
if (visiblePartY == 'top') {
// top part of element is visible
} else if (visiblePartY == 'bottom') {
// bottom part of element is visible
} else {
// whole part of element is visible
$(this).addClass("animated fadeInUp");
}
} else {
if ($(this).hasClass("fadeInUp")) {
$(this).css("opacity", 0);
$(this).removeClass("animated fadeInUp");
}
}
});
////////////////
// FORMULARIO //
////////////////
$('#formContacto').validator().on('submit', function (e) {
if (e.isDefaultPrevented()) {
// handle the invalid form...
} else {
// everything looks good!
e.preventDefault();
Custombox.open({
target: '#modal-formulario',
effect: 'blur',
position: ['center', 'center']
});
// Envio formulario mediante PHP
var parametros = {
"_nombre": $("#input-nombre").val(),
"_apellidos": $("#input-apellidos").val(),
"_telefono": $("#input-telefono").val(),
"_email": $("#input-email").val(),
"_mensaje": $("#input-mensaje").val()
};
$.ajax({
data: parametros,
url: 'php/sendFormEmail.php',
type: 'post',
beforeSend: function () {
//alert("Enviado");
},
success: function (response) {
//alert("Error");
}
});
return false;
}
})
////////////
// VIDEOS //
////////////
var vid = document.getElementById("bgvid");
var vid2 = document.getElementById("bgvid2");
var vid_ = $("#bgvid");
var vid2_ = $("#bgvid2");
var pauseButton = document.querySelector("#apartado2 .video-controls button");
var pauseButton2 = document.querySelector("#apartado5 .video-controls button");
var titulo;
var titulo2;
var subtitulo;
var subtitulo2;
var tempPlayPause;
var tempPlayPause2;
var timeout = null;
var timeout2 = null;
var moviendo = false;
var moviendo2 = false;
var hoverButton = false;
var hoverButton2 = false;
$("#apartado2 .video-controls button").hover(
function () {
hoverButton = true;
},
function () {
hoverButton = false;
}
);
$("#apartado5 .video-controls button").hover(
function () {
hoverButton2 = true;
},
function () {
hoverButton2 = false;
}
);
function vidFade() {
vid.classList.add("stopfade");
}
function vidFade2() {
vid2.classList.add("stopfade");
}
vid.addEventListener('ended', function () {
// only functional if "loop" is removed
vid.pause();
// to capture IE10
vidFade();
$("#apartado2 .video-controls").fadeOut();
});
vid2.addEventListener('ended', function () {
// only functional if "loop" is removed
vid2.pause();
// to capture IE10
vidFade2();
$("#apartado5 .video-controls").fadeOut();
});
$("#apartado2").on("click", function () {
titulo = $(this).find("h1");
subtitulo = $(this).find("p");
vid.classList.toggle("stopfade");
if (vid.paused) {
vid.play();
vid_.css('opacity', '1');
$("#apartado2 .imgPlay").fadeIn(0);
$("#apartado2 .imgPlayPause").attr("src", "img/play-icon.png");
titulo.fadeOut(300);
subtitulo.fadeOut(300);
tempPlayPause = setInterval(function () {
showHidePlayPause()
}, 100);
} else {
$("#apartado2 .video-controls").fadeIn(300);
vid.pause();
vid_.css('opacity', '0.5');
$("#apartado2 .imgPlayPause").attr("src", "img/pause-icon.png");
titulo.fadeIn(300);
subtitulo.fadeIn(300);
if (tempPlayPause) {
clearInterval(tempPlayPause);
}
}
});
$("#apartado5").on("click", function () {
titulo2 = $(this).find("h1");
subtitulo2 = $(this).find("p");
vid2.classList.toggle("stopfade");
if (vid2.paused) {
vid2.play();
vid2_.css('opacity', '1');
$("#apartado5 .imgPlay").fadeIn(0);
$("#apartado5 .imgPlayPause").attr("src", "img/play-icon.png");
titulo2.fadeOut(300);
subtitulo2.fadeOut(300);
tempPlayPause2 = setInterval(function () {
showHidePlayPause2()
}, 100);
} else {
$("#apartado5 .video-controls").fadeIn(300);
vid2.pause();
vid2_.css('opacity', '0.5');
$("#apartado5 .imgPlayPause").attr("src", "img/pause-icon.png");
titulo2.fadeIn(300);
subtitulo2.fadeIn(300);
if (tempPlayPause2) {
clearInterval(tempPlayPause2);
}
}
});
$("#apartado2").on('mousemove', function () {
moviendo = true;
clearTimeout(timeout);
timeout = setTimeout(function () {
moviendo = false;
}, 1000);
});
$("#apartado5").on('mousemove', function () {
moviendo2 = true;
clearTimeout(timeout2);
timeout2 = setTimeout(function () {
moviendo2 = false;
}, 1000);
});
function showHidePlayPause() {
if (!$("#apartado2 .video-controls").is(":animated") && moviendo) {
$(".video-controls").fadeIn(300);
}
if (moviendo == false && hoverButton == false) {
$("#apartado2 .video-controls").fadeOut(300);
}
}
function showHidePlayPause2() {
if (!$("#apartado5 .video-controls").is(":animated") && moviendo2) {
$("#apartado5 .video-controls").fadeIn(300);
}
if (moviendo2 == false && hoverButton2 == false) {
$("#apartado5 .video-controls").fadeOut(300);
}
}
$(window).resize(function () {
var size = $("#bgvid").height();
$("#apartado2").css("height", size + 'px');
$("#apartado5").css("height", size + 'px');
});
var size = $("#bgvid").height();
$("#apartado2").css("height", size + 'px');
$("#apartado5").css("height", size + 'px');
////////////////////////////////
// Cookies & Google Analytics //
////////////////////////////////
$.cookieBar({
message: 'Este sitio web utiliza cookies propias y de terceros para mejorar la experiencia de navegación, adaptarse a sus preferencias y realizar labores analíticas. Si continua navegando consideramos que acepta su uso.', //Message displayed on bar
acceptButton: true, //Set to true to show accept/enable button
acceptText: 'Acepto', //Text on accept/enable button
acceptFunction: activateGoogleAnalytics, //Callback function that triggers when user accepts
declineButton: false, //Set to true to show decline/disable button
declineText: 'Desactivar', //Text on decline/disable button
declineFunction: false, //Callback function that triggers when user declines
policyButton: true, //Set to true to show Privacy Policy button
policyText: 'Leer más', //Text on Privacy Policy button
policyFunction: showAvisoLegal, //Callback function that triggers before redirect when user clicks policy button
policyURL: '', //URL of Privacy Policy
autoEnable: true, //Set to true for cookies to be accepted automatically. Banner still shows
acceptOnContinue: false, //Set to true to silently accept cookies when visitor moves to another page
expireDays: 365, //Number of days for cookieBar cookie to be stored for
forceShow: false, //Force cookieBar to show regardless of user cookie preference
effect: 'slide', //Options: slide, fade, hide
element: 'body', //Element to append/prepend cookieBar to. Remember "." for class or "#" for id.
append: false, //Set to true for cookieBar HTML to be placed at base of website. YMMV
fixed: true, //Set to true to add the class "fixed" to the cookie bar. Default CSS should fix the position
bottom: true, //Force CSS when fixed, so bar appears at bottom of website
customClass: '', // Optional cookie bar class. Target #cookiebar.<customClass> to avoid !important overwrites and separate multiple classes by spaces
zindex: '', //Can be set in CSS, although some may prefer to set here
redirect: false, //Current location. Setting to false stops redirect
domain: String(window.location.hostname), //Location of privacy policy
referrer: String(document.referrer) //Where visitor has come from
});
function showAvisoLegal(e) {
Custombox.open({
target: '#modal-legal',
effect: 'blur'
});
}
function activateGoogleAnalytics() {
/*var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-X']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();*/
}
}); |
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'js/**/*.js'],
options: {
jshintrc: '.jshintrc'
}
},
cssmin: {
dist: {
files: {
'css/icon.min.css': [
'css/bootstrap.min.css',
'css/bootflat.css',
'css/site-icons.css'
],
'src/css/angularicons.min.css': 'src/css/angularicons.css'
}
}
},
sass: {
dist: {
files: {
'src/css/angularicons.css': 'src/scss/angularicons.scss'
},
options: {
style: 'expanded',
sourcemap: 'true'
}
}
},
pkg: grunt.file.readJSON('package.json')
});
require('load-grunt-tasks')(grunt);
grunt.registerTask('default', [
'jshint',
'sass',
'cssmin'
]);
}; |
$(function () {
var mdInput = document.getElementById('mdInput');
var mdPreview = document.getElementById('mdPreview');
var mdlink = document.getElementById('mdLink');
var $mdInput = $(mdInput);
var $mdLinkBtn = $('#mdConfirm');
var $mdLinkWrap = $('.md-link');
var $mdInputWrap = $('.md-input');
var cookieKey = "mdCache";
marked.setOptions({
highlight: function (code) {
return hljs.highlightAuto(code).value;
}
});
// md input
mdInput.addEventListener('keyup', function (e) {
$$.cookie.set(cookieKey, mdInput.value);
mdPreview.innerHTML = marked(mdInput.value);
});
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0];
$(window).resize(function () {
var h = (w.innerHeight || e.clientHeight || g.clientHeight) - 120;
$mdInputWrap.height(h);
$mdInput.height(h - 42);
});
$(window).resize();
// md link
$mdLinkWrap.tip({
content: "Copy remote Markdown file path here",
orientation: "right",
css: {
"width": "220px",
"font-family": "Calibri"
}
});
$mdLinkBtn.click(function () {
$.ajax({
url: mdlink.value,
timeout: 5000,
success: function (data) {
try {
mdPreview.innerHTML = marked(data);
} catch (e) {
}
}
});
});
// init
mdlink.value = "https://raw.githubusercontent.com/Rendxx/Markdown-Editor/master/README.md";
$mdLinkBtn.click();
var recover = $$.cookie.get(cookieKey);
if (recover != null) {
$$.info.check2("Do you want to load previous content?", "Recovery", false, "rgba(0, 0, 0, 0.6)"
, function () {
mdInput.value = recover;
mdPreview.innerHTML = marked(recover);
}
, function () {
$$.cookie.del(cookieKey);
});
}
}); |
/*
script.js for bresenham_line
author: thibaut voirand
*/
/*Declaring variables*******************************************************************************
***************************************************************************************************/
// canvas related variables
var canvas = document.getElementById('canvasId');
var canvasContext = canvas.getContext('2d');
var canvasData = canvasContext.getImageData(0, 0, canvas.width, canvas.height);
// pixel color and transparency
var rPixel = 255; // red
var gPixel = 0; // green
var bPixel = 0; // blue
var aPixel = 255; // transparency
// input coordinates
var x0;
var y0;
var x1;
var y1;
/*Functions*****************************************************************************************
***************************************************************************************************/
function drawPixel(x, y, r, g, b, a) {
var index = (x + y * canvas.width) * 4;
canvasData.data[index + 0] = r;
canvasData.data[index + 1] = g;
canvasData.data[index + 2] = b;
canvasData.data[index + 3] = a;
}
function updateCanvas() {
canvasContext.putImageData(canvasData, 0, 0);
}
function clearCanvas() {
var j;
for (j = 0; j < canvasData.data.length; j++) {
canvasData.data[j] = 0;
}
updateCanvas();
}
function getOctant(dx, dy) {
/*
Returns the octant in which a line is, in the following scheme, with starting point at center:
\2|1/
3\|/0
---+---
4/|\7
/5|6\
*/
var octant = 0;
if (dx >= 0 && dy >= 0 && dx <= dy) {
// octant 1
octant = 1;
} else if (dx <= 0 && dy >= 0 && -dx <= dy) {
// octant 2
octant = 2;
} else if (dx <= 0 && dy >= 0 && -dx >= dy) {
// octant 3
octant = 3;
} else if (dx <= 0 && dy <= 0 && -dx >= -dy) {
// octant 4
octant = 4;
} else if (dx <= 0 && dy <= 0 && -dx <= -dy) {
// octant 5
octant = 5;
} else if (dx >= 0 && dy <= 0 && dx <= -dy) {
// octant 6
octant = 6;
} else if (dx >= 0 && dy <= 0 && dx >= -dy) {
// octant 7
octant = 7;
}
return octant;
}
function switchToOctantZeroFrom(octant, x, y) {
/*
Function to apply on starting and ending points coordinates, to move the line's from original
octant to octant zero
*/
if (octant == 0) {
return [x, y];
} else if (octant == 1) {
return [y, x];
} else if (octant == 2) {
return [y, -x];
} else if (octant == 3) {
return [-x, y];
} else if (octant == 4) {
return [-x, -y];
} else if (octant == 5) {
return [-y, -x];
} else if (octant == 6) {
return [-y, x];
} else if (octant == 7) {
return [x, -y];
}
}
function switchFromOctantZeroTo(octant, x, y) {
/*
Function to apply on starting and ending points coordinates, to move the line's from octant zero
back to original octant
*/
if (octant == 0) {
return [x, y];
} else if (octant == 1) {
return [y, x];
} else if (octant == 2) {
return [-y, x];
} else if (octant == 3) {
return [-x, y];
} else if (octant == 4) {
return [-x, -y];
} else if (octant == 5) {
return [-y, -x];
} else if (octant == 6) {
return [y, -x];
} else if (octant == 7) {
return [x, -y];
}
}
function drawBresenhamLine(x0, y0, x1, y1, octant) {
[x0, y0] = switchToOctantZeroFrom(octant, x0, y0);
[x1, y1] = switchToOctantZeroFrom(octant, x1, y1);
var dx = x1 - x0;
var dy = y1 - y0;
var D = 2 * dy - dx;
var y = y0; //
for (x = x0; x < x1; x++) {
// switching back to starting octant and drawing pixels
drawPixel(
switchFromOctantZeroTo(octant, x, y)[0],
switchFromOctantZeroTo(octant, x, y)[1],
rPixel,
gPixel,
bPixel,
aPixel
);
if (D > 0) {
y = y + 1;
D = D - 2 * dx;
}
D = D + 2 * dy;
}
}
function getInputCoordinates() {
/*
This function assigns user-entered coordinates to the corresponding variables
*/
x0 = parseInt(document.getElementById('x0Input').value);
y0 = parseInt(document.getElementById('y0Input').value);
x1 = parseInt(document.getElementById('x1Input').value);
y1 = parseInt(document.getElementById('y1Input').value);
}
/*User-Interaction**********************************************************************************
***************************************************************************************************/
document.getElementById('drawButton').onclick = function drawButton() {
getInputCoordinates();
var dx = x1 - x0;
var dy = y1 - y0;
// case of a single point
if (dx == 0 && dy == 0) {
drawPixel(x0, y0, rPixel, gPixel, bPixel, aPixel);
updateCanvas();
return;
}
var octant = getOctant(dx, dy);
drawBresenhamLine(x0, y0, x1, y1, octant);
updateCanvas();
};
document.getElementById('clearButton').onclick = function() {
clearCanvas();
};
|
// import './utils.js';
// import './callbacks.js';
// import './settings.js';
// import './collections.js';
import './deep.js';
import './deep_extend.js';
// import './intl_polyfill.js';
// import './graphql.js';
import './icons.js';
export * from './config';
export * from './graphql/';
export * from './graphql_templates/index.js';
export * from './components.js';
export * from './collections.js';
export * from './callbacks.js';
export * from './routes.js';
export * from './utils.js';
export * from './settings.js';
export * from './headtags.js';
export * from './fragments.js';
export * from './apollo-common';
export * from './dynamic_loader.js';
export * from './admin.js';
export * from './fragment_matcher.js';
export * from './debug.js';
export * from './startup.js';
export * from './errors.js';
export * from './intl.js';
export * from './validation.js';
export * from './handleOptions.js';
export * from './ui_utils.js';
export * from './schema_utils.js';
export * from './simpleSchema_utils.js';
// export * from './resolvers.js';
export * from './random_id.js';
export * from './mongoParams';
export * from './reactive-state.js';
|
import Mesh from 'Engine/Mesh';
import {Tree as Shader} from 'Shaders';
import {glMatrix, vec3, quat} from 'gl-matrix';
class Tree extends Mesh {
constructor(model, origin) {
origin && (origin[1] += model.bounds.length * .3);
const rotation = quat.setAxisAngle(quat.create(), vec3.fromValues(1, 0, 0), glMatrix.toRadian(-90 + Math.floor(Math.random() * 31) - 15));
quat.rotateY(rotation, rotation, glMatrix.toRadian(Math.floor(Math.random() * 31) - 15));
super(model, Shader, origin, rotation);
}
};
export default Tree;
|
import React, { PropTypes } from 'react';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import * as styles from '../global/styles';
class Header extends React.Component {
constructor(props) {
super(props);
}
render () {
let { titleText } = this.props;
return (
<AppBar
style={styles.appBar.root}
titleStyle={styles.appBar.title}
title={titleText}
showMenuIconButton={false}
iconElementRight={
<IconMenu
style={styles.appBar.menuIcon}
iconButtonElement={
<IconButton><MoreVertIcon /></IconButton>
}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem href="https://github.com/johnstew/cdnjs-ext" primaryText="Fork Me" />
</IconMenu>
}
/>
);
}
}
Header.propTypes = {
titleText: PropTypes.string.isRequired
};
export default Header;
|
import webpack from 'webpack';
import path from 'path';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
const GLOBALS = {
'process.env.NODE_ENV': JSON.stringify('development'),
__DEV__: true
};
export default {
debug: true,
devtool: 'cheap-module-eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
noInfo: true, // set to false to see a list of every file being bundled.
entry: [
'webpack-hot-middleware/client?reload=true',
'bootstrap-loader',
'./src/index'
],
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
path: `${__dirname}/dist`, // Note: Physical files are only output by the production build task `npm run build`.
publicPath: 'http://localhost:3000/', // Use absolute paths to avoid the way that URLs are resolved by Chrome when they're parsed from a dynamically loaded CSS blob. Note: Only necessary in Dev.
filename: 'bundle.js'
},
plugins: [
new webpack.DefinePlugin(GLOBALS), // Tells React to build in prod mode. https://facebook.github.io/react/downloads.htmlnew webpack.HotModuleReplacementPlugin());
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
}),
new ExtractTextPlugin('app.css', { allChunks: true }),
new webpack.ProvidePlugin({
"window.Tether": "tether"
})
],
module: {
loaders: [
{test: /\.js$/, include: path.join(__dirname, 'src'), loaders: ['babel']},
//Alternate font loaders in case we need them in the future
//for font-awesome
//{
//test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
//// Limiting the size of the woff fonts breaks font-awesome ONLY for the extract text plugin
//// loader: "url?limit=10000"
//loader: "url"
//},
//{
//test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
//loader: 'file'
//},
{test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
{test: /\.(woff|woff2)$/, loader: 'file-loader?prefix=font/&limit=5000'},
{test: /\.ttf(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+.\d+.\d+)?$/, loader: 'file-loader?limit=10000&mimetype=image/svg+xml'},
{test: /\.(jpe?g|png|gif)$/i, loaders: ['file']},
{test: /\.ico$/, loader: 'file-loader?name=[name].[ext]'},
{test: /(\.css|\.scss)$/, loaders: ['style', 'css?sourceMap', 'sass?sourceMap']},
{test: /jquery[\\\/]src[\\\/]selector\.js$/, loader: 'amd-define-factory-patcher-loader' },
{test: /\.json$/, loader: 'json-loader'}
]
}
};
|
export { default } from 'ember-theater/pods/components/ember-theater/menu-bar/rewind/menu/component'; |
(function() {
'use strict'
angular.module('formobject')
.directive('foFieldToolbox', Directive);
function Directive() {
return {
restrict: 'E',
templateUrl: 'formobject/fo-field-toolbox.tpl.html',
replace: true
}
}
})();
|
var it = require('../tools/it.js');
function arrayEquals(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
return arr2.every(function(element, index) {
return element == arr2[index];
});
}
function arrayToList(values) {
var list = null;
while(values.length > 0) {
list = {
value: values.pop(),
next: list
};
}
return list;
}
function listToArray(list) {
var current = list;
var result = [];
do {
result.push(current.value);
current = current.next;
} while(current != null);
return result;
}
function listNth(aList, position) {
var current = 1;
while(current < position) {
if(aList.next == null) {
return;
}
aList = aList.next;
current++;
}
return aList.value;
}
var aList = arrayToList([1]);
it('Creates a list from array with 1 value', aList.value == 1 && aList.next == null);
var aList = arrayToList([1, 2]);
it('Creates a list from array with 2 values', (aList.value == 1) && (aList.next.value == 2) && aList.next.next == null);
var aList = arrayToList([1, 2, 3]);
it('Creates a list from array with 3 values', (aList.value == 1) && (aList.next.value == 2) && aList.next.next.value == 3);
aList = {value: 1, next: null};
it('Creates an array from a 1 member list', arrayEquals(listToArray(aList),[1]));
aList = {value: 1, next: {value: 2, next: null}};
it('Creates an array from a 2 members list', arrayEquals(listToArray(aList),[1, 2]));
aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Creates an array from a 3 members list', arrayEquals(listToArray(aList),[1, 2, 3]));
aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Can return the 1st element value', listNth(aList, 1) == 1);
aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Can return the 2nd element value', listNth(aList, 2) == 2);
aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Can return the 3rd element value', listNth(aList, 3) == 3);
aList = {value: 1, next: {value: 2, next: {value: 3, next: null}}};
it('Returns undefined if not found', typeof listNth(aList, 5) == 'undefined'); |
import { adminContactListsReducer, SET_CAMPAIGN_FORM_CONTACT_LIST, SET_CURRENT_CONTACT_LIST } from '../../../public/src/reducers/admin_contact_lists';
import fixtures from '../client_fixtures';
// TO-DO: this needs to become the contact list reducer test since this is all this is testing.
const { listFixture: contactListFixtures,
defaultContactLists: initialState,
mapFixture: contactListFixture } = fixtures.contactListFixtures;
const mockCampaignFormActions = [
{
type: SET_CAMPAIGN_FORM_CONTACT_LIST,
payload: contactListFixtures
},
{
type: SET_CURRENT_CONTACT_LIST,
payload: contactListFixture
},
{
type: 'RANDOM_TYPE',
payload: 'nothing'
}
];
const [contactList, currentContactList, fake] = mockCampaignFormActions;
const expectedContactListProps = Object.keys(contactListFixtures);
const expectedCurrentContactList = Object.keys(contactListFixture);
describe('adminContactListsReducer tests: ', () => {
// describe('default behavior', () => {
// will become default testing for the contacct list reducer
// });
let testResult;
describe('should populate contactList array when "SET_CAMPAIGN_FORM_CONTACT_LIST" is called', () => {
testResult = adminContactListsReducer(initialState, contactList);
const { contact_lists } = testResult;
const [first, second, third] = contact_lists;
it('contact_lists should be a non-empty array', () => {
expect(contact_lists.length).toBe(expectedContactListProps.length);
});
it('contact_lists name should correspond to mock data', () => {
expect(first.name).toBe(contactListFixtures[0].name);
expect(second.name).toBe(contactListFixtures[1].name);
expect(third.name).toBe(contactListFixtures[2].name);
});
});
describe('should populate current_contact_list when "SET_CURRENT_CONTACT_LIST" is called', () => {
testResult = adminContactListsReducer(initialState, currentContactList);
const { current_contact_list } = testResult;
it('should set current_contact_list as an object', () => {
expect(Array.isArray(current_contact_list)).toBe(false);
expect(typeof current_contact_list).toBe('object');
});
it('should have all of expected properties', () => {
expect(Object.keys(current_contact_list)).toEqual(expectedCurrentContactList);
});
});
describe('it should handle non-matching action types: ', () => {
it('should return the default if action type doesn\'t match', () => {
testResult = adminContactListsReducer(initialState, fake);
expect(testResult).toEqual(initialState);
});
});
});
|
var group___c_m_s_i_s__core___debug_functions =
[
[ "ITM_RXBUFFER_EMPTY", "group___c_m_s_i_s__core___debug_functions.html#gaa822cb398ee022b59e9e6c5d7bbb228a", null ],
[ "ITM_CheckChar", "group___c_m_s_i_s__core___debug_functions.html#gae61ce9ca5917735325cd93b0fb21dd29", null ],
[ "ITM_ReceiveChar", "group___c_m_s_i_s__core___debug_functions.html#gac3ee2c30a1ac4ed34c8a866a17decd53", null ],
[ "ITM_SendChar", "group___c_m_s_i_s__core___debug_functions.html#gac90a497bd64286b84552c2c553d3419e", null ],
[ "ITM_RxBuffer", "group___c_m_s_i_s__core___debug_functions.html#ga12e68e55a7badc271b948d6c7230b2a8", null ]
]; |
module.exports = {
"env": {
"browser": true,
"es6": true
},
"parser": "babel-eslint",
"plugins": [
"react"
],
"rules": {
//write your rules here!
"comma-dangle": ["error", "only-multiline"],
"quotes": ["error", "single", { "allowTemplateLiterals": true }],
"indent": ["error", 2, { "SwitchCase": 1 }],
"object-curly-spacing": ["error", "always"]
}
}; |
import React, { Component } from 'react';
import './SystemMessage.css';
const classNames = require('classnames');
export class SystemMessage extends Component {
render() {
return (
<div className={classNames("rce-container-smsg", this.props.className)}>
<div
className='rce-smsg'>
<div className="rce-smsg-text">
{this.props.text}
</div>
</div>
</div>
);
}
}
export default SystemMessage;
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'
import VueAxios from 'vue-axios'
//import App from './App.vue'
import Table from './Table.vue'
import Home from './Home.vue'
import Budget from './Budget.vue'
import Bucket from './Bucket.vue'
import Transactions from './Transactions.vue'
import global from './global'
Vue.use(VueRouter);
Vue.use(VueAxios, axios)
const router = new VueRouter({
mode: "hash",
base: __dirname,
routes: [
{ path:"/", component: Home },
{ path:"/budget", component: Budget },
{ path:"/bucket", component: Bucket },
{ path:"/transactions", component: Transactions }
]
});
new Vue({
el: '#app',
router,
components: {
'edi-table': Table
},
data: {
keys: {
"date": "date",
"amount": "money",
"desc": "text"
},
rows: [],
global: global
},
methods: {
save: function () {
console.log("saving...");
this.$http.get("/").then((response) => {
console.log(response);
});
}
},
// render: h => h(Table)
})
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { withKnobs, number } from '@storybook/addon-knobs';
import { host } from 'storybook-host';
import VolleyNet from '../components/lineup/VolleyNet';
import VolleyCourt from '../components/lineup/VolleyCourt';
import Lineup from '../components/lineup/Lineup';
const lineupStory = storiesOf('Lineup', module);
lineupStory.addDecorator(
host({
title: 'Lineup.',
align: 'center center',
height: '80%',
width: 1000,
background: '#444444',
}),
);
lineupStory.addDecorator(withKnobs);
const numberRange = (label, min, max, def = 0) =>
number(
label,
def,
{
range: true,
min,
max,
step: 1,
default: 1,
},
1,
);
lineupStory.add('net only', () =>
(<VolleyNet
width={numberRange('court width', 500, 900, 600)}
netHeight={numberRange('net height', 224, 243, 243)}
/>),
);
lineupStory.add('court with net', () =>
(<VolleyCourt
height={numberRange('height', 200, 800, 300)}
width={numberRange('width', 300, 1000, 400)}
/>),
);
lineupStory.add('full lineup', () => <Lineup />);
|
import React, {Component} from 'react';
import {
View,
StyleSheet,
Navigator,
TouchableOpacity,
Text,
DatePickerAndroid,
TimePickerAndroid,
ScrollView,
ToastAndroid,
TouchableHighlight,
Modal,
CameraRoll,
Animated,
TextInput,
ActivityIndicator,
ActionSheetIOS,
BackAndroid,
Dimensions,
Image
} from 'react-native';
import SelectPoeple from './SelectPoeple';
import Icon from 'react-native-vector-icons/Ionicons';
import ImageViewer from 'react-native-image-zoom-viewer';
import RNFS from 'react-native-fs';
var dataImpor = [];
let aa=[];
var images = [];
export default class Bxm extends Component {
constructor(props) {
super(props);
this._pressButton = this._pressButton.bind(this);
BackAndroid.addEventListener('hardwareBackPress', this._pressButton);
this.state = {
datas:{},
bottoms: new Animated.Value(-110),
datasx:{},
Status:'',
statu:false,
statur:false,
stat:'暂无',
infos:'',
product:[],
poepledata:{},
modalshow:false,
modalshows:false,
modalpoeple:false,
zidan:[],
zidan_id:'',
tj:'提交',
tp:false,
tjstatus:true,
textaera:'',
textaeras:'',
bcimg:'',
historydata:[],
imgs:[],
imgsx:[],
loaded:false,
loadedst:false,
url:'',
};
}
componentDidMount() {
this.timer = setTimeout(
() => { this.fetchDataa(data.data.domain + this.props.data.checkInfo.detail_url+ '&access_token=' + data.data.token);
this.fetchDatab(data.data.domain + this.props.data.checkInfo.check_history_url+ '&access_token=' + data.data.token);
},800);
aa=[];
}
componentWillUnmount() {
this.timer && clearTimeout(this.timer);
this.timerx && clearTimeout(this.timerx);
BackAndroid.removeEventListener('hardwareBackPress', this._pressButton);
}
toQueryString(obj) {
return obj ? Object.keys(obj).sort().map(function (key) {
var val = obj[key];
if (Array.isArray(val)) {
return val.sort().map(function (val2) {
return encodeURIComponent(key) + '=' + encodeURIComponent(val2);
}).join('&');
}
return encodeURIComponent(key) + '=' + encodeURIComponent(val);
}).join('&') : '';
}
fetchDataa(url) {
var that=this;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: this.toQueryString({
'id': this.props.data.con_id,
'notify_id': this.props.data.id,
})
})
.then(function (response) {
return response.json();
})
.then(function (result) {
if(result.data.pj.data.length>0){
result.data.pj.data.forEach((datas,i)=>{
var IMG={uri: data.data.domain.slice(0,-6)+datas.fileid.slice(1)};
aa.push(IMG);
that.setState({
imgs:aa,
});
})
}
that.setState({
loaded:true,
loadedst:true,
datas: result.data,
datasx:result,
});
})
.catch((error) => {
that.setState({
loaded:true,
statu:true,
infos:'加载失败'
})
that.timerx = setTimeout(() => {
that.setState({
statu:false,
})
},1000)
});
}
fetchDatab(url) {
var that=this;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: this.toQueryString({
'id': this.props.data.con_id,
'notify_id': this.props.data.id,
})
})
.then(function (response) {
return response.json();
})
.then(function (result) {
that.setState({
historydata: result.data.slice(0,-1),
});
var aa=[];
if(result.data != null){
result.data.forEach((img, i) => {
key={i}
var IMG = {uri:data.data.domain.slice(0,-6)+ img.img.slice(1)}
aa.push(IMG)
that.setState({
imgsx: aa,
});
})
}
})
}
_pressButton() {
dataImpor = [];
var { navigator } = this.props;
if(navigator) {
//很熟悉吧,入栈出栈~ 把当前的页面pop掉,这里就返回到了上一个页面了
navigator.pop();
return true;
}
return false;
}
_lxr(visible){
this.setState({modalshow: visible,url:''});
}
_xz(url){
this.setState({modalshow: true,url:url});
}
_lxrs(visible){
this.setState({modalshows: visible,poepledata:{},});
}
_xzs(visible){
this.setState({modalshows: visible,});
}
_lmodalpoeple(visible){
this.setState({modalpoeple: visible,modalshows: true});
}
_xmodalpoeple(visible){
this.setState({modalpoeple: visible,modalshows: false});
}
_select(data){
this.setState({
modalpoeple: false,
modalshows: true,
poepledata:data,
});
}
_delets(){
this.setState({
poepledata:{},
});
}
tijiao(){
var that=this;
this.setState({
tj:'正在提交...',
tjstatus:false,
});
fetch(this.state.url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: this.toQueryString({
'id': this.props.data.con_id,
'reply_text': this.state.textaera,
'next_uid':0,
})
})
.then(function (response) {
return response.json();
})
.then(function (result) {
that.setState({
modalshow:false,
tj:'提交',
tjstatus:true,
loadedst:false,
statu:true,
infos:'审批成功'
});
that.timerx = setTimeout(() => {
that.setState({
statu:false,
})
},1000);
if(that.props.getUser) {
let user = true;
that.props.getUser(user);
}
that.fetchDatab(data.data.domain + that.props.data.checkInfo.check_history_url+ '&access_token=' + data.data.token);
})
.catch((error) => {
that.setState({
tjstatus:true,
statu:true,
tj:'提交',
infos:'审批失败'
})
that.timerx = setTimeout(() => {
that.setState({
statu:false,
})
},1000)
});
}
tijiaos(){
var that=this;
if(JSON.stringify(this.state.poepledata) == "{}"){
this.setState({
statur:true,
infos:'请选择审批人'
});
this.timerx = setTimeout(() => {
this.setState({
statur:false,
})
},1500)
}else{
this.setState({
tj:'正在提交...',
tjstatus:false,
});
fetch(data.data.domain + this.props.data.checkInfo.next_check_url + '&access_token=' + data.data.token, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: this.toQueryString({
'id': this.props.data.con_id,
'reply_text': this.state.textaeras,
'next_uid':this.state.poepledata.uid,
})
})
.then(function (response) {
return response.json();
})
.then(function (result) {
if(result.status == 0){
that.setState({
tj:'提交',
tjstatus:true,
statur:true,
infos:'此人没有审核权限'
});
that.timerx = setTimeout(() => {
that.setState({
statur:false,
})
},1000)
}else{
that.setState({
modalshows:false,
tj:'提交',
tjstatus:true,
poepledata:{},
statu:true,
loadedst:false,
infos:'审批成功'
});
if(that.props.getUser) {
let user = true;
that.props.getUser(user);
}
that.fetchDatab(data.data.domain + that.props.data.checkInfo.check_history_url+ '&access_token=' + data.data.token);
}
that.timerx = setTimeout(() => {
that.setState({
statu:false,
})
},1000)
})
.catch((error) => {
that.setState({
tjstatus:true,
statu:true,
tj:'提交',
infos:'审批失败'
})
that.timerx = setTimeout(() => {
that.setState({
statu:false,
})
},1000)
});
}
}
closest(){
if(this.state.bottoms._value == 0){
Animated.timing(
this.state.bottoms,
{toValue: -110},
).start();
}else{
this.setState({
tp:false,
})
}
}
cancels(){
Animated.timing(
this.state.bottoms,
{toValue: -110},
).start();
}
tup(img){
var ims={url:img.uri};
images=[];
images.push(ims)
this.setState({tp:true,bcimg:img.uri})
}
sures(){
var that=this;
const downloadDest = `${RNFS.ExternalStorageDirectoryPath}/DCIM/Camera/${(new Date().getTime())}.jpg`;
var files = 'file://' + downloadDest;
RNFS.downloadFile({ fromUrl: this.state.bcimg, toFile: downloadDest}).promise.then(res => {
CameraRoll.saveToCameraRoll(files);
that.setState({
statu:true,
infos:'保存成功'
})
Animated.timing(
this.state.bottoms,
{toValue: -110},
).start();
that.timerx = setTimeout(() => {
that.setState({
statu:false,
})
},1000)
}).catch(err => {
that.setState({
statu:true,
infos:'保存失败'
})
Animated.timing(
this.state.bottoms,
{toValue: -110},
).start();
that.timerx = setTimeout(() => {
that.setState({
statu:false,
})
},1000)
});
}
showActionSheet() {
var that=this;
Animated.timing(
this.state.bottoms,
{toValue: 0},
).start();
}
render() {
return (
<View style={{flex:1,flexDirection:'column',backgroundColor:'#fff'}}>
<View style={styles.card}>
<View style={{flex:1,justifyContent:'center'}}>
<TouchableOpacity onPress={this._pressButton.bind(this)}>
<View style={{justifyContent:'flex-start',flexDirection:'row',alignItems:'center',}}>
<Image source={require('./imgs/back.png')} style={{width: 25, height: 25,marginLeft:5,}} />
<Text style={{color:'white',fontSize:16,marginLeft:-5,}} allowFontScaling={false} adjustsFontSizeToFit={false}>返回</Text>
</View>
</TouchableOpacity>
</View>
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
<View style={{justifyContent:'center',flexDirection:'row',alignItems:'center'}}>
<Text style={{color:'white',fontSize:16}} allowFontScaling={false} adjustsFontSizeToFit={false}>审批</Text>
</View>
</View>
<View style={{flex:1,justifyContent:'center'}}>
<TouchableOpacity>
<View style={{justifyContent:'flex-end',flexDirection:'row',alignItems:'center'}}>
</View>
</TouchableOpacity>
</View>
</View>
{!this.state.loaded ? <View style={{justifyContent: 'center',alignItems: 'center',flex:1,flexDirection:'column',backgroundColor:'#ececec'}}>
<View style={styles.loading}>
<ActivityIndicator color="white"/>
<Text style={styles.loadingTitle} allowFontScaling={false} adjustsFontSizeToFit={false}>加载中……</Text>
</View>
</View> : <ScrollView style={{flex:1,flexDirection:'column',backgroundColor:'#ececec'}}>
<View style={{flexDirection:'row',height:50,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,marginTop:0}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>操作人</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,height:50,}}>
<View style={{flex:1,}}>
<Text allowFontScaling={false} adjustsFontSizeToFit={false} style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}}>
{this.props.data.from_name}
</Text>
</View>
</View>
</View>
<View style={{flexDirection:'row',height:50,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>来自</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,height:50,}}>
<View style={{flex:1,}}>
{this.props.data.app_name ? <Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.props.data.app_name}
</Text> : <Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.state.stat}
</Text>
}
</View>
</View>
</View>
<View style={{flexDirection:'row',height:50,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>创建日期</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,height:50,}}>
<View style={{flex:1,}}>
<Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.state.datas.bx.time}
</Text>
</View>
</View>
</View>
<View style={{flexDirection:'row',height:50,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,marginTop:15,}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>报销名</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,height:50,}}>
<View style={{flex:1,}}>
<Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.state.datas.bx.expensename}
</Text>
</View>
</View>
</View>
<View style={{flexDirection:'row',height:50,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>报销金额</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,height:50,}}>
<View style={{flex:1,}}>
<Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.state.datas.bx.money}
</Text>
</View>
</View>
</View>
<View style={{flexDirection:'row',height:50,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>报销人</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,height:50,}}>
<View style={{flex:1,}}>
<Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.state.datas.bx.userid}
</Text>
</View>
</View>
</View>
<View style={{flexDirection:'row',height:50,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>报销状态</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,height:50,}}>
<View style={{flex:1,}}>
<Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.state.datasx.audit_status}
</Text>
</View>
</View>
</View>
<View style={{flexDirection:'row',paddingTop:18,paddingBottom:18,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>时间</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,}}>
<View style={{flex:1,}}>
<Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.state.datas.bx.time}
</Text>
</View>
</View>
</View>
<View style={{flexDirection:'row',paddingTop:18,paddingBottom:18,backgroundColor:'#fff',alignItems:'center',justifyContent:'center',borderBottomWidth:1,borderColor:'#dcdcdc',paddingLeft:10,}}>
<Text style={{fontSize:14,color:'#666',}} allowFontScaling={false} adjustsFontSizeToFit={false}>备注</Text>
<View style={{flex:1,marginLeft:15,flexDirection:'row',alignItems:'center',paddingRight:10,}}>
<View style={{flex:1,}}>
<Text style={{fontSize:14,textAlign:'right',paddingRight:15, alignItems:'center'}} allowFontScaling={false} adjustsFontSizeToFit={false}>
{this.state.datas.bx.bz}
</Text>
</View>
</View>
</View>
<Modal visible={this.state.tp}
animationType={"fade"}
onRequestClose={() => {console.log("Modal has been closed.")}}
transparent={true}>
<ImageViewer saveToLocalByLongPress={false} onClick={this.closest.bind(this)} imageUrls={images}/>
<TouchableOpacity onPress={this.showActionSheet.bind(this)} style={{position:'absolute',bottom:0,right:30}}>
<View ><Icon name="ios-list-outline" color="#fff"size={50} /></View>
</TouchableOpacity>
{this.state.statu ? <Animated.View style={{ padding:10,width:200,backgroundColor:'rgba(23, 22, 22, 0.7)',justifyContent:'flex-start',alignItems:'center',position:'absolute',top:(Dimensions.get('window').height-150)/2,left:(Dimensions.get('window').width-200)/2,}}>
<Icon name="ios-checkmark-outline" color="#fff"size={50} />
<Text style={{fontSize:16,color:'#fff',marginTop:20,}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.infos}</Text>
</Animated.View> : null}
<Animated.View style={{bottom:this.state.bottoms,left:0,width:Dimensions.get('window').width,backgroundColor:'#fff',position:'absolute',justifyContent:'center',alignItems:'center',position:'absolute',}}>
<TouchableOpacity onPress={this.sures.bind(this)} style={{width:Dimensions.get('window').width,}}>
<View style={{borderColor:'#ccc',borderBottomWidth:1,width:Dimensions.get('window').width,justifyContent:'center',alignItems:'center',}}>
<Text style={{fontSize:18,paddingTop:15,paddingBottom:15,}}>保存到手机</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.cancels.bind(this)} style={{width:Dimensions.get('window').width,}}>
<View style={{width:Dimensions.get('window').width,justifyContent:'center',alignItems:'center',}}>
<Text style={{fontSize:18,paddingTop:15,paddingBottom:15,}}>取消</Text>
</View>
</TouchableOpacity>
</Animated.View>
</Modal>
<View style={{marginTop:15,backgroundColor:'#fff'}}>
{this.state.datas.pj.count > 0 ? this.state.datas.pj.data.map((data,i)=>{
return <View key={i} style={{flexDirection:'column',borderBottomWidth:1,borderColor:'#ccc'}}>
<View style={{flexDirection:'row',justifyContent:'space-between',paddingLeft:10,paddingRight:10,paddingTop:7,paddingBottom:7,alignItems:'center',borderBottomWidth:1,borderColor:'#ececec'}}>
<Text style={{fontSize:14,color:'#aaa'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{data.documentsname}</Text>
<Text style={{fontSize:14,color:'#aaa'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{data.time}</Text>
</View>
<View style={{flexDirection:'row',padding:10}}>
<TouchableOpacity onPress={this.tup.bind(this,this.state.imgs[i])}><View style={{height:60,width:60,overflow:'hidden'}}><Image source={this.state.imgs[i]} style={{height:60,width:60,}} /></View></TouchableOpacity>
<View style={{marginLeft:10,flexDirection:'column',justifyContent:'space-between'}}>
<Text style={{fontSize:14}} allowFontScaling={false} adjustsFontSizeToFit={false}>票据号:{data.documentsid}</Text>
<Text style={{fontSize:14}} allowFontScaling={false} adjustsFontSizeToFit={false}>来源:{data.projectid}</Text>
<Text style={{fontSize:14}} allowFontScaling={false} adjustsFontSizeToFit={false}>分类:{data. cateid}</Text>
</View>
</View>
{data.docbz != '无' ? <View style={{paddingRight:10,paddingLeft:10,paddingBottom:10,paddingTop:10,borderTopWidth:1,borderColor:'#ececec',flexDirection:'row'}}>
<Text style={{fontSize:14,}} allowFontScaling={false} adjustsFontSizeToFit={false}>备注:</Text>
<Text style={{fontSize:14,flex:1,}} allowFontScaling={false} adjustsFontSizeToFit={false}>{data.docbz}</Text>
</View> : null}
</View>
}) : null}
</View>
<View style={{marginTop:15,backgroundColor:'#fff',}}>
{this.state.historydata.length > 0 ? <View style={{paddingLeft:10,paddingRight:10,paddingTop:7,paddingBottom:7,borderBottomWidth:1,borderColor:'#ececec',flexDirection:'row',justifyContent:'space-between'}}>
<Text style={{fontSize:14}} allowFontScaling={false} adjustsFontSizeToFit={false}> 评论</Text>
<Text style={{fontSize:14}} allowFontScaling={false} adjustsFontSizeToFit={false}>共有{this.state.historydata.length}条评论</Text>
</View> : null}
{this.state.historydata.length > 0 ? this.state.historydata.map((data,i) => {
return <View key={i} style={{flexDirection:'row',paddingTop:15,paddingLeft:15,}}>
<View style={{width: 40, height: 40,borderRadius:20,backgroundColor:'#718DC1',alignItems:'center', justifyContent:'center'}}>
<Image source={this.state.imgsx[i]} style={{width: 40, height: 40,borderRadius:20,}} />
</View>
<View style={{flexDirection:'column',marginLeft:15,flex:1, borderBottomWidth:1,borderColor:'#ececec',paddingBottom:15,paddingRight:15,}}>
<View style={{flexDirection:'row',alignItems:'center', justifyContent:'space-between'}}>
<Text allowFontScaling={false} adjustsFontSizeToFit={false}>{data.apply_name}</Text>
<Text allowFontScaling={false} adjustsFontSizeToFit={false}>{data.inserttime}</Text>
</View>
<Text style={{color:'#aaa',fontSize:14,flexWrap:'wrap',flex:1,paddingTop:5,}} allowFontScaling={false} adjustsFontSizeToFit={false}>{data.reply_text}
</Text>
</View>
</View>
}) : null}
</View>
</ScrollView>}
{this.state.loadedst ? <View style={{height:50,flexDirection:'row',justifyContent:'space-around',alignItems:'center',borderTopWidth:0.5,borderColor:'#ccc'}}>
<TouchableOpacity onPress={this._xz.bind(this,data.data.domain + this.props.data.checkInfo.check_url + '&access_token=' + data.data.token)} style={{flex:1,}}>
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
<Text style={{fontSize:16,color:'#4385f4'}} allowFontScaling={false} adjustsFontSizeToFit={false}>审核通过</Text>
</View>
</TouchableOpacity>
<View style={{width:1,height:17,backgroundColor:'#4385f4'}}></View>
<TouchableOpacity style={{flex:1,}} onPress={this._xz.bind(this,data.data.domain + this.props.data.checkInfo.reject_url + '&access_token=' + data.data.token)}>
<View style={{alignItems:'center',justifyContent:'center'}}>
<Text style={{fontSize:16,color:'#4385f4'}} allowFontScaling={false} adjustsFontSizeToFit={false}>驳回</Text>
</View>
</TouchableOpacity>
<View style={{width:1,height:17,backgroundColor:'#4385f4'}}></View>
<TouchableOpacity style={{flex:1,paddingRight:10,paddingLeft:10}} onPress={this._xzs.bind(this,true)}>
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
<Text style={{fontSize:16,color:'#4385f4'}} allowFontScaling={false} adjustsFontSizeToFit={false}>提交下一步</Text>
</View>
</TouchableOpacity>
</View> : null}
<View>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.modalshow}
onRequestClose={() => {console.log("Modal has been closed.")}}
>
<View style={styles.card}>
<TouchableOpacity onPress={this._lxr.bind(this,false)} style={{flex:1}}>
<View style={{flex:1,justifyContent:'center'}}>
<View style={{justifyContent:'flex-start',flexDirection:'row',alignItems:'center',}}>
<Text style={{color:'white',fontSize:16,paddingLeft:10,}} allowFontScaling={false} adjustsFontSizeToFit={false}>取消</Text>
</View>
</View>
</TouchableOpacity>
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
<Text style={{color:'white',fontSize:16}} allowFontScaling={false} adjustsFontSizeToFit={false}>审批</Text>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'flex-end',}}>
</View>
</View>
<ScrollView style={{flex:1,backgroundColor:'#ececec'}}>
<View style={{padding:10,backgroundColor:'#fff'}}>
<TextInput
onChangeText={(textaera) => this.setState({textaera})}
multiline={true}
numberOfLines={5}
placeholderTextColor={'#ccc'}
style={{ color:'#666',fontSize:14,textAlignVertical:'top',height:170,}}
placeholder='不说点什么...'
underlineColorAndroid={'transparent'}
/>
</View>
{this.state.tjstatus ? <TouchableHighlight onPress={this.tijiao.bind(this)} underlayColor="rgba(82, 132, 216,0.7)" style={{marginLeft:10,marginRight:10,marginTop:40, borderWidth:1,borderColor:'#ececec',borderRadius:5,paddingTop:10,paddingBottom:10, justifyContent:'center',alignItems:'center',backgroundColor:'#4385f4'}}>
<View style={{borderRadius:5, justifyContent:'center',alignItems:'center',}}>
<Text style={{fontSize:18, color:'#fff'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.tj}</Text>
</View>
</TouchableHighlight> : <TouchableHighlight style={{marginLeft:10,marginRight:10,marginTop:40, borderWidth:1,borderColor:'#ececec',borderRadius:5,paddingTop:10,paddingBottom:10, justifyContent:'center',alignItems:'center',backgroundColor:'#4385f4'}}>
<View style={{borderRadius:5, justifyContent:'center',alignItems:'center',}}>
<Text style={{fontSize:18, color:'#fff'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.tj}</Text>
</View>
</TouchableHighlight>}
</ScrollView>
{this.state.statu ? <Animated.View style={{ padding:10,width:200,backgroundColor:'rgba(23, 22, 22, 0.7)',justifyContent:'flex-start',alignItems:'center',position:'absolute',top:(Dimensions.get('window').height-150)/2,left:(Dimensions.get('window').width-200)/2,}}>
<Icon name="ios-close-outline" color="#fff"size={36} />
<Text style={{fontSize:16,color:'#fff',marginTop:20,}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.infos}</Text>
</Animated.View> : null}
</Modal>
</View>
<View>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.modalshows}
onRequestClose={() => {console.log("Modal has been closed.")}}
>
<View style={styles.card}>
<TouchableOpacity onPress={this._lxrs.bind(this,false)} style={{flex:1}}>
<View style={{flex:1,justifyContent:'center'}}>
<View style={{justifyContent:'flex-start',flexDirection:'row',alignItems:'center',}}>
<Text style={{color:'white',fontSize:16,paddingLeft:10,}} allowFontScaling={false} adjustsFontSizeToFit={false}>取消</Text>
</View>
</View>
</TouchableOpacity>
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
<Text style={{color:'white',fontSize:16}} allowFontScaling={false} adjustsFontSizeToFit={false}>审批</Text>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'flex-end',}}>
</View>
</View>
<ScrollView style={{flex:1,backgroundColor:'#ececec'}}>
<View style={{padding:10,backgroundColor:'#fff'}}>
<TextInput
onChangeText={(textaeras) => this.setState({textaeras})}
multiline={true}
numberOfLines={5}
placeholderTextColor={'#ccc'}
style={{ color:'#666',fontSize:14,textAlignVertical:'top',height:170,}}
placeholder='不说点什么...'
underlineColorAndroid={'transparent'}
/>
</View>
<View style={{backgroundColor:'#fff',marginTop:15,flexDirection:'column',paddingLeft:10,paddingTop:10,paddingBottom:10,}}>
<View style={{flexDirection:'row',alignItems:'center'}}>
<Text style={{fontSize:16}} allowFontScaling={false} adjustsFontSizeToFit={false}>审批人</Text>
<Text style={{fontSize:12,color:'#bbb',marginLeft:5}} allowFontScaling={false} adjustsFontSizeToFit={false}>(点击姓名可删除)</Text>
</View>
<View style={{marginTop:15,flexDirection:'row',alignItems:'center',}}>
{this.state.poepledata.name ? <TouchableOpacity onPress={this._delets.bind(this)} activeOpacity={1}><View style={{backgroundColor:'#60a9e8',paddingBottom:8,paddingTop:8,paddingLeft:10,paddingRight:10,marginRight:10,borderRadius:3}}>
<Text style={{color:'#fff'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.poepledata.name}</Text>
</View></TouchableOpacity> : null}
<TouchableOpacity style={{width:46,height:46,marginTop:5,alignItems:'center',justifyContent:'center'}} onPress={this._xmodalpoeple.bind(this,true)}>
<Icon name="ios-add-circle-outline" color="#ccc"size={46} />
</TouchableOpacity>
</View>
</View>
{this.state.tjstatus ? <TouchableHighlight onPress={this.tijiaos.bind(this)} underlayColor="rgba(82, 132, 216,0.7)" style={{marginLeft:10,marginRight:10,marginTop:40, borderWidth:1,borderColor:'#ececec',borderRadius:5,paddingTop:10,paddingBottom:10, justifyContent:'center',alignItems:'center',backgroundColor:'#4385f4'}}>
<View style={{borderRadius:5, justifyContent:'center',alignItems:'center',}}>
<Text style={{fontSize:18, color:'#fff'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.tj}</Text>
</View>
</TouchableHighlight> : <TouchableHighlight style={{marginLeft:10,marginRight:10,marginTop:40, borderWidth:1,borderColor:'#ececec',borderRadius:5,paddingTop:10,paddingBottom:10, justifyContent:'center',alignItems:'center',backgroundColor:'#4385f4'}}>
<View style={{borderRadius:5, justifyContent:'center',alignItems:'center',}}>
<Text style={{fontSize:18, color:'#fff'}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.tj}</Text>
</View>
</TouchableHighlight>}
</ScrollView>
{this.state.statur ? <Animated.View style={{ padding:10,width:200,backgroundColor:'rgba(23, 22, 22, 0.7)',justifyContent:'flex-start',alignItems:'center',position:'absolute',top:(Dimensions.get('window').height-150)/2,left:(Dimensions.get('window').width-200)/2,}}>
<Icon name="ios-close-outline" color="#fff"size={36} />
<Text style={{fontSize:16,color:'#fff',marginTop:20,}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.infos}</Text>
</Animated.View> : null}
</Modal>
</View>
<View>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.modalpoeple}
onRequestClose={() => {console.log("Modal has been closed.")}}
>
<View style={styles.card}>
<TouchableOpacity onPress={this._lmodalpoeple.bind(this,false)} style={{flex:1}}>
<View style={{flex:1,justifyContent:'center'}}>
<View style={{justifyContent:'flex-start',flexDirection:'row',alignItems:'center',}}>
<Text style={{color:'white',fontSize:16,paddingLeft:10,}} allowFontScaling={false} adjustsFontSizeToFit={false}>取消</Text>
</View>
</View>
</TouchableOpacity>
<View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
<Text style={{color:'white',fontSize:16}} allowFontScaling={false} adjustsFontSizeToFit={false}>选择审批人</Text>
</View>
<View style={{flex:1,justifyContent:'center',alignItems:'flex-end',}}>
</View>
</View>
<View style={{flex:1}}>
<SelectPoeple _select={this._select.bind(this)}/>
</View>
</Modal>
</View>
{this.state.statu ? <Animated.View style={{ padding:10,width:200,backgroundColor:'rgba(23, 22, 22, 0.7)',justifyContent:'flex-start',alignItems:'center',position:'absolute',top:(Dimensions.get('window').height-150)/2,left:(Dimensions.get('window').width-200)/2,}}>
<Icon name="ios-close-outline" color="#fff"size={36} />
<Text style={{fontSize:16,color:'#fff',marginTop:20,}} allowFontScaling={false} adjustsFontSizeToFit={false}>{this.state.infos}</Text>
</Animated.View> : null}
</View>
);
}
}
const styles = StyleSheet.create({
tabView: {
flex: 1,
flexDirection: 'column',
backgroundColor:'#fafafa',
},
card: {
height:45,
backgroundColor:'#4385f4',
flexDirection:'row'
},
default: {
height: 37,
borderWidth: 0,
borderColor: 'rgba(0,0,0,0.55)',
flex: 1,
fontSize: 13,
},
loading: {
backgroundColor: 'gray',
height: 80,
width: 100,
borderRadius: 10,
justifyContent: 'center',
alignItems: 'center',
},
loadingTitle: {
marginTop: 10,
fontSize: 14,
color: 'white'
},
}); |
import PropTypes from 'prop-types';
import React, { useEffect, useState } from 'react';
import Cover from './Cover';
import Body from './Body';
import ErrorBoundary from 'components/Wrappers/ErrorBoundary';
import { css } from 'emotion';
import { connect } from 'react-redux';
import {
changeProfileTheme,
checkValidUsername
} from 'redux/actions/UserActions';
import { setTheme } from 'helpers/requestHelpers';
import NotFound from 'components/NotFound';
import Loading from 'components/Loading';
Profile.propTypes = {
changeProfileTheme: PropTypes.func.isRequired,
checkValidUsername: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
history: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
match: PropTypes.object.isRequired,
profile: PropTypes.object.isRequired,
userId: PropTypes.number,
username: PropTypes.string
};
function Profile({
changeProfileTheme,
checkValidUsername,
dispatch,
history,
location,
match,
profile,
profile: { unavailable },
userId,
username
}) {
const [selectedTheme, setSelectedTheme] = useState('logoBlue');
const [loading, setLoading] = useState(false);
useEffect(() => {
if (history.action === 'PUSH' || !profile.id) {
init();
}
async function init() {
setLoading(true);
await checkValidUsername(match.params.username);
setLoading(false);
}
}, [match.params.username]);
useEffect(() => {
if (match.params.username === 'undefined' && userId && unavailable) {
history.push(`/${username}`);
}
setSelectedTheme(profile?.profileTheme || 'logoBlue');
}, [match.params.username, profile, userId]);
return (
<ErrorBoundary style={{ minHeight: '10rem' }}>
{!unavailable ? (
<>
{loading && <Loading text="Loading Profile..." />}
{!loading && profile.id && (
<div
className={css`
a {
white-space: pre-wrap;
overflow-wrap: break-word;
word-break: break-word;
}
`}
style={{
position: 'relative'
}}
>
<Cover
profile={profile}
onSelectTheme={theme => {
setSelectedTheme(theme);
}}
selectedTheme={selectedTheme}
onSetTheme={onSetTheme}
/>
<Body
history={history}
location={location}
match={match}
profile={profile}
selectedTheme={selectedTheme}
/>
</div>
)}
</>
) : (
<NotFound
title={!userId ? 'For Registered Users Only' : ''}
text={!userId ? 'Please Log In or Sign Up' : ''}
/>
)}
</ErrorBoundary>
);
async function onSetTheme() {
await setTheme({ color: selectedTheme, dispatch });
changeProfileTheme(selectedTheme);
}
}
export default connect(
state => ({
userId: state.UserReducer.userId,
username: state.UserReducer.username,
profile: state.UserReducer.profile
}),
dispatch => ({
dispatch,
changeProfileTheme: theme => dispatch(changeProfileTheme(theme)),
checkValidUsername: username => dispatch(checkValidUsername(username))
})
)(Profile);
|
import uop from "./_uop";
export default uop("midicps", a => 440 * Math.pow(2, (a - 69) / 12));
|
'use strict';
/* eslint camelcase: [2, {properties: "never"}], quote-props: 0, max-len: [1, 200] */
var mockfs = require('mock-fs');
var _ = require('lodash');
var mockery = require('mockery');
var path = require('path');
var Promise = require('bluebird');
var sinon = require('sinon');
var tap = require('tap');
var roux = require('../');
var Ingredient = require('../lib/ingredient');
var Pantry = require('../lib/pantry');
var initialize = roux.initialize;
var parseIngredientPath = roux.parseIngredientPath;
var resolve = roux.resolve;
var normalizeConfig = roux.normalizeConfig;
var pantryErrors = roux.errors;
function restoreMockFS() {
mockfs.restore();
}
tap.test('API', function (t) {
t.autoend();
t.type(
roux.Pantry,
'function',
'exports the Pantry class'
);
t.type(
roux.Ingredient,
'function',
'exports the Ingredient class'
);
t.type(
initialize,
'function',
'exports an initialize method'
);
t.test('initialize', function (t) {
t.autoend();
t.test('returns a Promise', function (t) {
mockfs({
'empty-pantry': {
}
});
var promise = initialize({
path: path.resolve('empty-pantry'),
name: 'empty-pantry'
});
t.type(promise, 'object');
t.type(promise.then, 'function');
t.test('resolved with Pantry instance on success', function (t) {
initialize(
{
path: path.resolve('empty-pantry'),
name: 'empty-pantry'
})
.then(function (pantry) {
t.type(pantry, Pantry);
t.end();
});
});
t.test('rejected with error on failure', function (t) {
initialize(
{
path: path.resolve('no-such-pantry'),
name: 'empty-pantry'
})
.catch(function (error) {
t.type(error, Error);
t.end();
});
});
restoreMockFS();
t.end();
});
t.test('accepts a required config object', function (t) {
t.autoend();
t.throws(function () {
initialize();
}, 'throws if config is not passed');
t.throws(function () {
initialize(123);
}, 'throws if config not an object');
t.throws(function () {
initialize(true);
}, 'throws if config not an object');
t.test('config.predicates', function (t) {
t.autoend();
t.test('can be regexes', function (t) {
mockfs({
'entrypoints-pantry': {
'custom-only': {
'ingredient.md': '',
'index.foo': ''
}
}
});
return initialize(
{
path: path.resolve('entrypoints-pantry'),
name: 'entrypoints-pantry',
predicates: {
foo: /^index.foo$/,
bar: /^index.bar$/
}
})
.then(function (pantry) {
t.strictSame(
pantry.ingredients['custom-only'].entryPoints.foo,
{
filename: 'index.foo'
},
'pantry.entryPoints[<predicate name>] is an object if match'
);
t.equal(
pantry.ingredients['custom-only'].entryPoints.bar,
null,
'pantry.entryPoints[<predicate name>] is null if no match'
);
})
.finally(restoreMockFS);
});
t.test('can be synchronous functions', function (t) {
mockfs({
'entrypoints-pantry': {
'custom-only': {
'ingredient.md': '',
'index.foo': ''
}
}
});
return initialize(
{
path: path.resolve('entrypoints-pantry'),
name: 'entrypoints-pantry',
predicates: {
foo: function (filename) {
return filename === 'index.foo';
},
bar: function (filename) {
return filename === 'index.bar';
},
}
})
.then(function (pantry) {
t.strictSame(
pantry.ingredients['custom-only'].entryPoints.foo,
{
filename: 'index.foo'
},
'pantry.entryPoints[<predicate name>] is an object if match'
);
t.equal(
pantry.ingredients['custom-only'].entryPoints.bar,
null,
'pantry.entryPoints[<predicate name>] is null if no match'
);
})
.finally(restoreMockFS);
});
t.test('can be asynchronous functions', function (t) {
mockfs({
'entrypoints-pantry': {
'custom-only': {
'ingredient.md': '',
'index.foo': ''
}
}
});
return initialize(
{
path: path.resolve('entrypoints-pantry'),
name: 'entrypoints-pantry',
predicates: {
foo: function (filename) {
return Promise.resolve(filename === 'index.foo');
},
bar: function (filename) {
return Promise.resolve(filename === 'index.bar');
},
}
})
.then(function (pantry) {
t.strictSame(
pantry.ingredients['custom-only'].entryPoints.foo,
{
filename: 'index.foo'
},
'pantry.entryPoints[<predicate name>] is an object if match'
);
t.equal(
pantry.ingredients['custom-only'].entryPoints.bar,
null,
'pantry.entryPoints[<predicate name>] is null if no match'
);
})
.finally(restoreMockFS);
});
t.test('can override default predicates', function (t) {
mockfs({
'entrypoints-pantry': {
'js-only': {
'ingredient.md': '',
'index.js': ''
},
'override-only': {
'ingredient.md': '',
'main.js': ''
}
}
});
return initialize(
{
path: path.resolve('entrypoints-pantry'),
name: 'entrypoints-pantry',
predicates: {
javaScript: /^main.js$/
}
})
.then(function (pantry) {
t.ok(
pantry.ingredients['override-only'].entryPoints.javaScript,
'pantry.entryPoints.javaScript is truthy if match'
);
t.notOk(
pantry.ingredients['js-only'].entryPoints.javaScript,
'pantry.entryPoints.javaScript is falsy if no match'
);
})
.finally(restoreMockFS);
});
});
});
t.test('accepts an optional node callback', function (t) {
t.autoend();
t.test('called with Pantry instance on success', function (t) {
mockfs({
'empty-pantry': {}
});
initialize(
{
path: path.resolve('empty-pantry'),
name: 'empty-pantry'
},
function (error, pantry) {
t.equals(error, null, 'error should be null');
t.type(pantry, Pantry);
t.end();
})
.finally(restoreMockFS);
});
t.test('called with error on failure', function (t) {
mockfs({
'empty-pantry': {}
});
initialize(
{
path: path.resolve('no-such-pantry'),
name: 'empty-pantry'
},
function (error, pantry) {
t.type(error, Error);
t.equals(pantry, undefined, 'pantry should be undefined');
})
.catch(function (e) {
if (!e.message.match(/Pantry .* does not exist\.$/)) {
throw e;
}
})
.finally(function () {
restoreMockFS();
t.end();
});
});
});
t.test('Pantry.ingredients', function (t) {
t.autoend();
t.test('is an object', function (t) {
mockfs({
'empty-pantry': {}
});
return initialize(
{
path: path.resolve('empty-pantry'),
name: 'empty-pantry'
})
.then(function (pantry) {
return t.type(pantry.ingredients, 'object');
})
.finally(restoreMockFS);
});
t.test('is an empty object if the pantry has no ingredients',
function (t) {
mockfs({
'empty-pantry': {}
});
return initialize(
{
path: path.resolve('empty-pantry'),
name: 'empty-pantry'
})
.then(function (pantry) {
return t.same(pantry.ingredients, {});
})
.finally(restoreMockFS);
});
t.test('has a key for each valid ingredient in the pantry', function (t) {
mockfs({
'simple-pantry': {
one: {
'ingredient.md': ''
},
two: {
'ingredient.md': ''
},
path: {
to: {
three: {
'ingredient.md': ''
}
}
}
}
});
return initialize(
{
path: path.resolve('simple-pantry'),
name: 'simple-pantry'
})
.then(function (pantry) {
return t.same(
_.keys(pantry.ingredients).sort(),
['one', 'two', 'path/to/three'].sort()
);
})
.finally(restoreMockFS);
});
t.test('ignores nested ingredients', function (t) {
mockfs({
'nested-pantry': {
'path': {
'ingredient.md': '',
'to': {
'three': {
'ingredient.md': ''
}
}
},
'prefix': {
'ingredient.md': ''
},
'prefixed': {
'ingredient.md': ''
},
'prefixedpath': {
'to': {
'another': {
'ingredient.md': ''
},
'anotherone': {
'ingredient.md': ''
}
}
}
}
});
return initialize(
{
path: path.resolve('nested-pantry'),
name: 'nested-pantry'
})
.then(function (pantry) {
return t.same(
_.keys(pantry.ingredients).sort(),
[
'prefix',
'prefixed',
'prefixedpath/to/another',
'prefixedpath/to/anotherone',
'path'
].sort()
);
})
.finally(restoreMockFS);
});
t.test('doesn\'t behave differently when package.json exists and roux.pantryRoot property is missing', function (t) {
mockfs({
'simple-pantry': {
'package.json': '{}',
one: {
'ingredient.md': ''
},
pantry: {
two: {
'ingredient.md': ''
},
path: {
to: {
three: {
'ingredient.md': ''
}
}
}
}
}
});
return initialize(
{
path: path.resolve('simple-pantry'),
name: 'simple-pantry'
})
.then(function (pantry) {
t.same(pantry.path, path.resolve('simple-pantry'), 'pantry path is unchanged');
t.same(
_.keys(pantry.ingredients).sort(),
['one', 'pantry/two', 'pantry/path/to/three'].sort(),
'ingredients are unchanged'
);
})
.finally(restoreMockFS);
});
t.test('doesn\'t behave differently when package.json exists and roux.pantryRoot property is set to a non-string value', function (t) {
mockfs({
'simple-pantry': {
'package.json': JSON.stringify({
roux: {
pantryRoot: 8675309
}
}),
one: {
'ingredient.md': ''
},
pantry: {
two: {
'ingredient.md': ''
},
path: {
to: {
three: {
'ingredient.md': ''
}
}
}
}
}
});
return initialize(
{
path: path.resolve('simple-pantry'),
name: 'simple-pantry'
})
.then(function (pantry) {
t.same(pantry.path, path.resolve('simple-pantry'), 'pantry path is unchanged');
t.same(
_.keys(pantry.ingredients).sort(),
['one', 'pantry/two', 'pantry/path/to/three'].sort(),
'ingredients are unchanged'
);
})
.finally(restoreMockFS);
});
t.test('respects custom pantry directory when package.json exists and contains a string value for roux.pantryRoot', function (t) {
mockfs({
'simple-pantry': {
'package.json': JSON.stringify({
roux: {
pantryRoot: 'pantry'
}
}),
one: {
'ingredient.md': ''
},
pantry: {
two: {
'ingredient.md': ''
},
path: {
to: {
three: {
'ingredient.md': ''
}
}
}
}
}
});
return initialize(
{
path: path.resolve('simple-pantry'),
name: 'simple-pantry'
})
.then(function (pantry) {
t.same(pantry.path, path.resolve('simple-pantry', 'pantry'), 'pantry path is updated');
t.same(
_.keys(pantry.ingredients).sort(),
['two', 'path/to/three'].sort(),
'ingredient paths are updated'
);
})
.finally(restoreMockFS);
});
t.test('respects custom pantry directory when package.json exists and contains a string value for roux.pantryRoot and pantry sub-directory doesn\'t exist', function (t) {
mockfs({
'simple-pantry': {
'package.json': JSON.stringify({
roux: {
pantryRoot: 'notPantry'
}
}),
one: {
'ingredient.md': ''
},
pantry: {
two: {
'ingredient.md': ''
},
path: {
to: {
three: {
'ingredient.md': ''
}
}
}
}
}
});
return initialize(
{
path: path.resolve('simple-pantry'),
name: 'simple-pantry'
})
.then(function (pantry) {
t.same(pantry.path, path.resolve('simple-pantry', 'notPantry'), 'pantry path is updated');
t.same(
_.keys(pantry.ingredients).sort(),
[],
'no ingredients are found in non-existent directory'
);
})
.finally(restoreMockFS);
});
t.test('each value is an Ingredient instance', function (t) {
mockfs({
'simple-pantry': {
one: {
'ingredient.md': ''
},
two: {
'ingredient.md': ''
},
path: {
to: {
three: {
'ingredient.md': ''
}
}
}
}
});
return initialize(
{
path: path.resolve('simple-pantry'),
name: 'simple-pantry'
})
.then(function (pantry) {
return t.ok(_.every(pantry.ingredients, function (ingredient) {
return ingredient instanceof Ingredient;
}), 'all ingredients should Ingredient instances');
})
.finally(restoreMockFS);
});
t.test('Pantry.ingredients[i].entryPoints', function (t) {
t.autoend();
t.test('is an object', function (t) {
mockfs({
'simple-pantry': {
one: {
'ingredient.md': ''
},
two: {
'ingredient.md': ''
},
path: {
to: {
three: {
'ingredient.md': ''
}
}
}
}
});
return initialize(
{
path: path.resolve('simple-pantry'),
name: 'simple-pantry'
})
.then(function (pantry) {
return t.ok(_.every(pantry.ingredients, function (ingredient) {
return typeof ingredient.entryPoints === 'object';
}), 'Pantry.ingredients[i].entryPoints should be an object');
})
.finally(restoreMockFS);
});
t.test('Pantry.ingredients[i].entryPoints.javaScript', function (t) {
mockfs({
'entrypoints-pantry': {
'js-only': {
'ingredient.md': '',
'index.js': ''
},
'sass-only': {
'ingredient.md': '',
'index.scss': ''
}
}
});
return initialize(
{
path: path.resolve('entrypoints-pantry'),
name: 'entrypoints-pantry'
})
.then(function (pantry) {
t.strictSame(
pantry.ingredients['js-only'].entryPoints.javaScript,
{
filename: 'index.js'
},
'is an object if ingredient has a JS entrypoint'
);
t.equal(
pantry.ingredients['sass-only'].entryPoints.javaScript,
null,
'null if ingredient does not have a JS entrypoint'
);
})
.finally(restoreMockFS);
});
t.test('Pantry.ingredients[i].entryPoints.sass', function (t) {
mockfs({
'entrypoints-pantry': {
'js-only': {
'ingredient.md': '',
'index.js': ''
},
'sass-only': {
'ingredient.md': '',
'index.scss': ''
}
}
});
return initialize(
{
path: path.resolve('entrypoints-pantry'),
name: 'entrypoints-pantry'
})
.then(function (pantry) {
t.strictSame(
pantry.ingredients['sass-only'].entryPoints.sass,
{
filename: 'index.scss'
},
'is an object if ingredient has a Sass entrypoint'
);
t.equal(
pantry.ingredients['js-only'].entryPoints.sass,
null,
'null if ingredient does not have a Sass entrypoint'
);
})
.finally(restoreMockFS);
});
});
});
});
t.type(
parseIngredientPath,
'function',
'exports a parseIngredientPath method'
);
t.test('parseIngredientPath', function (t) {
t.autoend();
t.test('ingredientPath', function (t) {
_.forEach(
[
0,
123,
true,
false,
null,
undefined,
[],
{}
],
function (arg) {
t.throws(function () {
parseIngredientPath({
pantries: arg
});
}, 'must be a string');
});
t.end();
});
t.equal(parseIngredientPath('foo'), null, 'null if <1 slash');
var expected = 'ingredient';
try {
sinon.spy(Ingredient, 'isValidName');
parseIngredientPath('pantry/ingredient');
t.ok(
Ingredient.isValidName.calledWithExactly(expected),
'the ingredient name is passed to `Ingredient.isValidName`'
);
Ingredient.isValidName.resetHistory();
parseIngredientPath('@namespace/pantry/ingredient');
t.ok(
Ingredient.isValidName.calledWithExactly(expected),
'the ingredient name is passed to `Ingredient.isValidName`'
);
} finally {
Ingredient.isValidName.restore();
}
try {
expected = 'pantry';
sinon.spy(Pantry, 'isValidName');
parseIngredientPath('pantry/ingredient');
t.ok(
Pantry.isValidName.calledWithExactly(expected),
'the pantry name is passed to `Pantry.isValidName`'
);
Pantry.isValidName.resetHistory();
expected = '@namespace/pantry';
parseIngredientPath('@namespace/pantry/ingredient');
t.ok(
Pantry.isValidName.calledWithExactly(expected),
'the pantry name is passed to `Pantry.isValidName`'
);
} finally {
Pantry.isValidName.restore();
}
try {
sinon.stub(Ingredient, 'isValidName');
sinon.stub(Pantry, 'isValidName');
Ingredient.isValidName.returns(false);
Pantry.isValidName.returns(true);
t.equal(
parseIngredientPath('pantry/ingredient'),
null,
'returns null if ingredient name is invalid'
);
Ingredient.isValidName.returns(true);
Pantry.isValidName.returns(false);
t.equal(
parseIngredientPath('pantry/ingredient'),
null,
'returns null if pantry name is invalid'
);
Ingredient.isValidName.returns(false);
Pantry.isValidName.returns(false);
t.equal(
parseIngredientPath('pantry/ingredient'),
null,
'returns null if both names are invalid'
);
Ingredient.isValidName.returns(true);
Pantry.isValidName.returns(true);
t.same(
parseIngredientPath('pantry/ingredient'),
{
pantry: 'pantry',
ingredient: 'ingredient'
},
'returns parsed name if both are valid'
);
} finally {
Ingredient.isValidName.restore();
Pantry.isValidName.restore();
}
t.same(
parseIngredientPath('@namespace/pantry/path/to/ingredient'),
{
pantry: '@namespace/pantry',
ingredient: 'path/to/ingredient'
},
'parses nested ingredients'
);
});
t.type(normalizeConfig, 'function', 'exports a normalizeConfig method');
t.test('normalizeConfig', function (t) {
t.autoend();
t.test('arguments', function (t) {
t.autoend();
testConfigArgValidation(t, 'config', normalizeConfig);
testConfigArgValidation(t, 'defaults', normalizeConfig.bind(null, undefined));
t.test('honors verious permutations of {config,defaults}', function (t) {
t.autoend();
t.test('new defaults for pantrySearchPaths', function (t) {
t.autoend();
var config = undefined;
var defaults = {
pantrySearchPaths: ['test/']
};
var normalized = normalizeConfig(config, defaults);
t.same(normalized.pantrySearchPaths, defaults.pantrySearchPaths);
});
t.test('config honored over new defaults for pantrySearchPaths', function (t) {
t.autoend();
var config = {
pantrySearchPaths: ['testing/']
};
var defaults = {
pantrySearchPaths: ['test/']
};
var normalized = normalizeConfig(config, defaults);
t.same(normalized.pantrySearchPaths, config.pantrySearchPaths);
});
t.test('new defaults for pantries', function (t) {
t.autoend();
var config = undefined;
var defaults = {
pantrySearchPaths: ['test/']
};
var normalized = normalizeConfig(config, defaults);
t.same(normalized.pantrySearchPaths, defaults.pantrySearchPaths);
});
t.test('config honored over new defaults for pantries', function (t) {
t.autoend();
var config = {
pantries: {testing: {}},
};
var defaults = {
pantries: {test: {}},
};
var normalized = normalizeConfig(config, defaults);
t.same(normalized.pantries, config.pantries);
});
});
});
});
t.type(resolve, 'function', 'exports a resolve method');
t.test('resolve', function (t) {
t.autoend();
t.test('arguments', function (t) {
t.autoend();
t.test('pantry', function (t) {
t.throws(function () {
resolve();
}, 'is required');
_.forEach(
[
0,
123,
true,
false,
null,
[],
{}
],
function (arg) {
t.throws(function () {
resolve(arg, 'ingredient', 'entryPoint', {});
}, 'must be a string');
});
_.forEach(
[
'',
'@foo',
'./foo',
'/foo',
'../foo/bar',
'foo:bar'
],
function (arg) {
t.throws(function () {
resolve(arg);
}, 'must be a valid npm package name ' + arg);
});
t.end();
});
t.test('ingredient', function (t) {
t.doesNotThrow(function () {
resolve('pantry').catch(_.noop);
}, 'is optional');
_.forEach(
[
0,
123,
true,
false,
null,
[],
{}
],
function (arg) {
t.throws(function () {
resolve('pantry', arg, 'entryPoint', {});
}, 'must be a string, not ' + arg);
});
t.end();
});
t.test('entryPoint', function (t) {
t.doesNotThrow(function () {
resolve('pantry', 'ingredient').catch(_.noop);
}, 'is optional');
_.forEach(
[
0,
123,
true,
false,
null,
[],
{}
],
function (arg) {
t.throws(function () {
resolve('pantry', 'ingredient', arg, {});
}, 'must be a string, not ' + arg);
});
t.end();
});
t.test('config', function (t) {
t.doesNotThrow(function () {
resolve('pantry', 'ingredient', 'entryPoint').catch(_.noop);
}, 'is optional');
_.forEach(
[
'',
'foo',
0,
123,
true,
false
],
function (arg) {
if (!_.isString(arg)) {
t.throws(function () {
resolve('pantry', arg);
}, 'must be an object, not ' + arg);
t.throws(function () {
resolve('pantry', 'ingredient', arg);
}, 'must be an object, not ' + arg);
}
t.throws(function () {
resolve('pantry', 'ingredient', 'entryPoint', arg);
}, 'must be an object, not ' + arg);
});
t.autoend();
t.test('config.pantries', function (t) {
t.doesNotThrow(function () {
resolve('pantry', {}).catch(_.noop);
resolve('pantry', 'ingredient', {}).catch(_.noop);
resolve('pantry', 'ingredient', 'entryPoint', {}).catch(_.noop);
}, 'is optional');
_.forEach(
[
'',
'foo',
0,
123,
true,
false
],
function (arg) {
t.throws(function () {
resolve('pantry', {pantries: arg});
}, 'must be an object, not ' + arg);
t.throws(function () {
resolve('pantry', 'ingredient', {pantries: arg});
}, 'must be an object, not ' + arg);
t.throws(function () {
resolve(
'pantry', 'ingredient', 'entryPoint', {pantries: arg});
}, 'must be an object, not ' + arg);
});
t.end();
});
t.test('config.pantrySearchPaths', function (t) {
t.doesNotThrow(function () {
resolve('pantry', {}).catch(_.noop);
resolve('pantry', 'ingredient', {}).catch(_.noop);
resolve('pantry', 'ingredient', 'entryPoint', {}).catch(_.noop);
}, 'is optional');
_.forEach(
[
'',
'foo',
0,
123,
true,
false,
{}
],
function (arg) {
t.throws(function () {
resolve('pantry', {pantrySearchPaths: arg});
}, 'must be an array, not ' + arg);
t.throws(function () {
resolve('pantry', 'ingredient', {pantrySearchPaths: arg});
}, 'must be an array, not ' + arg);
t.throws(function () {
resolve(
'pantry',
'ingredient',
'entryPoint',
{
pantrySearchPaths: arg
}
);
}, 'must be an array, not ' + arg);
});
t.autoend();
t.test('defaults to `["$CWD/node_modules"]`', function (t) {
mockfs({
node_modules: {
pantry: {
ingredient: {
'ingredient.md': ''
}
}
}
});
var expectedPath = path.resolve('node_modules', 'pantry');
return resolve('pantry', {})
.then(function (actual) {
t.type(actual, Pantry, 'looks up pantry in node_modules');
t.equal(actual.path, expectedPath);
})
.finally(restoreMockFS);
});
});
});
});
t.test('returns a promise', function (t) {
_.forEach(
[
resolve('pantry'),
resolve('pantry', {}),
resolve('pantry', 'ingredient'),
resolve('pantry', 'ingredient', {}),
resolve('pantry', 'ingredient', 'entry point'),
resolve('pantry', 'ingredient', 'entry point', {})
],
function (returnValue) {
t.type(returnValue.then, 'function', 'return value is a promise');
returnValue.catch(_.noop);
});
t.end();
});
t.test('if passed a pantry only', function (t) {
t.autoend();
t.test('returns pantry from `config.pantries` if present', function (t) {
var expected = new Pantry({
ingredients: {}
});
return resolve('pantry', {
pantries: {
pantry: expected
}
})
.then(function (actual) {
t.same(actual, expected, 'resolves to cached pantry');
});
});
t.test('looks up pantry in search paths if not cached', function (t) {
t.autoend();
t.test('resolves if found', function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': ''
}
}
}
});
return resolve('pantry', {
pantrySearchPaths: [path.resolve('resolve')]
})
.then(function (actual) {
t.type(actual, Pantry, 'looks up pantry in search paths');
})
.finally(restoreMockFS);
});
t.test('rejects if not found', function (t) {
mockfs({
resolve: {}
});
return resolve('no-such-pantry', {
pantrySearchPaths: [path.resolve('resolve')]
})
.catch(function (error) {
t.type(error, Error, 'resolves with an error if not found');
})
.finally(restoreMockFS);
});
});
});
t.test('if passed a string', function (t) {
t.autoend();
t.test('initializes to the specified location on the file system', function (t) {
t.autoend();
t.test('resolves if found', function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': ''
}
}
}
});
return resolve('pantry', {
pantries: {
pantry: path.resolve('resolve/pantry')
}
})
.then(function (actual) {
t.type(actual, Pantry, 'resolves string to pantry');
})
.finally(restoreMockFS);
});
t.test('modifies the pantry', function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': ''
}
}
}
});
var config = {
pantries: {
pantry: path.resolve('resolve/pantry')
}
};
return resolve('pantry', config)
.then(function (actual) {
t.type(config.pantries.pantry, Pantry, 'modifies the cache');
t.same(config.pantries.pantry, actual, 'modifies the cache');
})
.finally(restoreMockFS);
});
});
});
t.test('if passed a pantry and ingredient only', function (t) {
t.autoend();
t.test('looks up ingredient in `config.pantries`',
function (t) {
var expected = new Pantry({
ingredients: {
ingredient: {}
}
});
return resolve('pantry', 'ingredient', {
pantries: {
pantry: expected
}
})
.then(function (actual) {
t.same(
actual,
expected.ingredients.ingredient,
'resolves to ingredient from cached pantry'
);
});
});
t.test('looks up ingredient in `config.pantrySearchPaths`', function (t) {
mockfs({
resolve: {
pantry: {
path: {
to: {
ingredient: {
'ingredient.md': ''
}
}
}
}
}
});
return resolve('pantry', 'path/to/ingredient', {
pantrySearchPaths: [path.resolve('resolve')]
})
.then(function (actual) {
t.type(actual, Ingredient, 'looks up ingredient in search paths');
})
.finally(restoreMockFS);
});
t.test('rejects if not found', function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': ''
}
}
}
});
return resolve('pantry', 'no-such-ingredient', {
pantrySearchPaths: [path.resolve('resolve')]
})
.catch(function (error) {
t.type(error, Error, 'resolves with an error if not found');
})
.finally(restoreMockFS);
});
t.test('rejects with PantryDoesNotExistError if the pantry is not found', function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': ''
}
},
pantryTwo: {
ingredient: {
'ingredient.md': ''
}
}
}
});
return resolve('no-such-pantry', 'ingredient', {
pantrySearchPaths: [path.resolve('resolve')]
})
.catch(function (error) {
t.type(error, pantryErrors.PantryDoesNotExistError, 'rejects with a PantryDoesNotExistError if pantry not found');
})
.finally(restoreMockFS);
});
t.test('rejects with PantryNotADirectoryError if the pantry is found but not a directory', function (t) {
mockfs({
resolve: {
pantry: 'this is a file'
}
});
return resolve('pantry', 'ingredient', {
pantrySearchPaths: [path.resolve('resolve')]
})
.catch(function (error) {
t.type(error, pantryErrors.PantryNotADirectoryError, 'rejects with a PantryNotADirectoryError if pantry found but not a directory');
})
.finally(restoreMockFS);
});
t.test('rejects with IngredientDoesNotExistError if the ingredient is not found', function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': ''
}
}
}
});
return resolve('pantry', 'no-such-ingredient', {
pantrySearchPaths: [path.resolve('resolve')]
})
.catch(function (error) {
t.type(error, pantryErrors.IngredientDoesNotExistError, 'rejects with a IngredientDoesNotExistError if ingredient not found');
})
.finally(restoreMockFS);
});
t.test('rejects with IngredientHasNoSuchEntrypointError if' +
'ingredient entryPoint not found',
function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': ''
}
}
}
});
return resolve('pantry', 'ingredient', 'handlebars', {
pantrySearchPaths: [path.resolve('resolve')]
})
.catch(function (error) {
t.type(
error,
pantryErrors.IngredientHasNoSuchEntrypointError,
'rejects with a IngredientHasNoSuchEntrypointError if' +
'the ingredient has no such entrypoint'
);
})
.finally(restoreMockFS);
}
);
});
t.test('if passed a pantry, ingredient, and entry point', function (t) {
t.autoend();
t.test('returns entry point path from `config.pantries` if present',
function (t) {
var expected = '/path/to/pantry/and/ingredient/index.foo';
return resolve('pantry', 'ingredient', 'entryPoint', {
pantries: {
pantry: new Pantry({
ingredients: {
ingredient: {
path: '/path/to/pantry/and/ingredient',
entryPoints: {
entryPoint: {
filename: 'index.foo'
}
}
}
}
})
}
})
.then(function (actual) {
t.same(
actual,
expected,
'resolves to the entry point from the cached pantry'
);
});
});
t.test('looks up entry point in `config.pantrySearchPaths`',
function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': '',
'index.js': ''
}
}
}
});
var expected =
path.resolve('resolve', 'pantry', 'ingredient', 'index.js');
return resolve('pantry', 'ingredient', 'javaScript', {
pantrySearchPaths: [path.resolve('resolve')]
})
.then(function (actual) {
t.equal(actual, expected, 'looks up entry point in search paths');
})
.finally(restoreMockFS);
});
t.test('rejects if not found', function (t) {
mockfs({
resolve: {
pantry: {
ingredient: {
'ingredient.md': ''
}
}
}
});
return resolve('pantry', 'ingredient', 'no-such-entry-point', {
pantrySearchPaths: [path.resolve('resolve')]
})
.catch(function (error) {
t.type(error, Error, 'resolves with an error if not found');
})
.finally(restoreMockFS);
});
});
});
});
tap.test('Ingredient', function (t) {
t.autoend();
t.type(
Ingredient.isValidName,
'function',
'provides a static `isValidName` method'
);
t.test('Ingredient.isValidName', function (t) {
t.autoend();
var Ingredient = require('../lib/ingredient');
t.ok(Ingredient.isValidName('ingredient'));
t.ok(Ingredient.isValidName('ingredient2'));
t.ok(Ingredient.isValidName('ingredient_Two'));
t.ok(Ingredient.isValidName('ingredient-two'));
t.ok(Ingredient.isValidName('ingredient-two_3Four'));
t.ok(Ingredient.isValidName('ingredient/one-1/Two_2/3'));
t.notOk(Ingredient.isValidName('@ingredient'));
t.notOk(Ingredient.isValidName('an ingredient'));
});
});
tap.test('Pantry', function (t) {
t.autoend();
t.type(
Pantry.isValidName,
'function',
'provides a static `isValidName` method'
);
t.test('Pantry.isValidName', function (t) {
mockery.enable({
useCleanCache: true,
warnOnUnregistered: false
});
mockery.registerMock('validate-npm-package-name', sinon.stub().returns({
validForOldPackages: false,
validForNewPackages: true
}));
var mockValidateNpmPackageName = require('validate-npm-package-name');
var Pantry = require('../lib/pantry');
var expected = 'ingredient-name';
try {
Pantry.isValidName(expected);
t.ok(
mockValidateNpmPackageName.calledWithExactly(expected),
'delegates to `validate-npm-package-name`'
);
mockValidateNpmPackageName.returns({
validForOldPackages: false,
validForNewPackages: true
});
t.equal(
Pantry.isValidName(expected),
true,
'returns the `validForNewPackages` property value from the result of ' +
'calling `validate-npm-package-name`'
);
mockValidateNpmPackageName.returns({
validForOldPackages: true,
validForNewPackages: false
});
t.equal(
Pantry.isValidName(expected),
false,
'returns the `validForNewPackages` property value from the result of ' +
'calling `validate-npm-package-name`'
);
} finally {
mockery.deregisterMock('validate-npm-package-name');
mockery.disable();
t.end();
}
});
t.type(
Pantry.isPantry,
'function',
'provides a static `isPantry` method'
);
t.test('Pantry.isPantry', function (t) {
t.notOk(Pantry.isPantry('foo'));
t.notOk(Pantry.isPantry(1));
t.notOk(Pantry.isPantry(null));
t.notOk(Pantry.isPantry({}));
t.notOk(Pantry.isPantry(function () {}));
t.ok(Pantry.isPantry(new Pantry({})));
t.end();
});
});
function testConfigArgValidation(t, argName, methodToTest) {
t.test(argName, function (t) {
t.autoend();
t.test('does not mutate the original argument', function (t) {
t.autoend();
var obj = {};
methodToTest(obj);
t.same(obj, {});
});
_.forEach(
[
'',
'foo',
0,
123,
true,
false
],
function (arg) {
t.throws(function () {
methodToTest(arg);
}, 'must be an object, not ' + arg);
});
t.test(argName + '.pantries', function (t) {
t.doesNotThrow(function () {
methodToTest({});
}, 'is optional');
_.forEach(
[
'',
'foo',
0,
123,
true,
false
],
function (arg) {
t.throws(function () {
methodToTest({pantries: arg});
}, 'must be an object, not ' + arg);
});
t.end();
});
t.test(argName + '.pantrySearchPaths', function (t) {
t.autoend();
t.doesNotThrow(function () {
methodToTest({});
}, 'is optional');
_.forEach(
[
'',
'foo',
0,
123,
true,
false,
{}
],
function (arg) {
t.throws(function () {
methodToTest({pantrySearchPaths: arg});
}, 'must be an array, not ' + arg);
});
t.test('defaults to `["$CWD/node_modules"]`', function (t) {
t.autoend();
var expectedPath = path.resolve('node_modules');
var normalized = methodToTest({});
t.equal(normalized.pantrySearchPaths[0], expectedPath);
});
});
});
}
|
'use strict';
import Model from './model';
import storage from './storage';
function IW(type, id) {
if (!IW.adapter) {
IW.useAdapter('JSON', [IW.base || '/']);
}
return new Model(type, id, null, IW.adapter);
}
/**
* Instantiate an adapter so ironwing will use it
* @param {String} adapterName The adapter's name (eg. JSON)
* @param {Array} args An array of arguments
*/
IW.useAdapter = function(adapterName, args) {
var adapter;
if (IW.adapters && IW.adapters.hasOwnProperty(adapterName)) {
adapter = IW.adapters[adapterName];
adapter.init.apply(adapter, args);
IW.adapter = adapter;
}
};
IW.create = function(type, attr) {
return Model.create(type, attr, IW.adapter);
};
IW.storage = storage;
export default IW;
|
var RT = RT || {};
RT.result = (function () {
var rootElem,
startDate,
startTime,
targetTime,
endDate,
endTime,
hideBtn;
function init() {
rootElem = RT.core.getElem("result"),
startDate = RT.core.getElem("r-start-date");
startTime = RT.core.getElem("r-start-time");
targetTime = RT.core.getElem("r-target");
endDate = RT.core.getElem("r-end-date");
endTime = RT.core.getElem("r-end-time");
hideBtn = RT.core.getElem("r-hide");
RT.events.add("show:result", calculateAndShow);
hideBtn.on("click", hide);
}
function calculateAndShow(result) {
var targetDate = calculate(result);
startDate.html(formatDate(result.startDate));
startTime.html(formatTime({
hours: result.startDate.getHours(),
minutes: result.startDate.getMinutes()
}));
targetTime.html(formatTime(result.targetTime));
endDate.html(formatDate(targetDate));
endTime.html(formatTime({
hours: targetDate.getHours(),
minutes: targetDate.getMinutes()
}));
show();
}
function show() {
rootElem.show();
}
function hide() {
rootElem.hide();
}
function calculate(data) {
var temp = data.startDate.getTime();
temp = temp + data.targetTime.hours * 60 * 60 * 1000 + data.targetTime.minutes * 60 * 1000;
return new Date(temp);
}
function formatDate(date) {
return format(date.getDate()) + "/" + format(date.getMonth() + 1) + "/" + format(date.getFullYear());
}
function formatTime(time) {
return format(time.hours) + ":" + format(time.minutes);
}
function format(val) {
val = parseInt(val);
if (val < 10) {
return "0" + val;
} else {
return val;
}
}
return {
init: init
};
})();
|
"use strict";
module.exports = {
friendIds: {},
add: function(friendIds) {
if (typeof friendIds === "number") {
friendIds = [friendIds];
}
for (var i = 0; i < friendIds.length; i++) {
var friendId = friendIds[i];
this.friendIds[friendId] = true;
}
},
remove: function(friendId) {
delete this.friendIds[friendId];
},
isFriend: function(friendId) {
return !!this.friendIds[friendId];
}
};
|
var questionData= require('../questions.json')
var currentClass= require('../currentClass.json');
exports.view = function(req, res) {
console.log(currentClass);
var className={'class':req.query.class};
res.render('queue', {'data':[currentClass,questionData]});
} |
/// <reference path="../../typings/jQuery/jQuery.d.ts" />
var Told;
(function (Told) {
(function (TableMath) {
(function (Data) {
var UserSettings_LocalStorage = (function () {
function UserSettings_LocalStorage() {
}
/*
* Get User Settings from local storage provider
*
* @param key which setting to retrieve
* @returns the value, or null if not found
*/
UserSettings_LocalStorage.getUserSetting = function (key) {
var value = localStorage.getItem(key);
console.log("Get User Setting:" + key + "=" + value);
return value;
};
UserSettings_LocalStorage.setUserSetting = function (key, value) {
localStorage.setItem(key, value);
console.log("Set User Setting:" + key + "=" + value);
};
Object.defineProperty(UserSettings_LocalStorage.prototype, "userList", {
get: function () {
var valueStr = UserSettings_LocalStorage.getUserSetting("userList");
var names = (valueStr || "").split(";");
names = names.map(function (n, i) {
return n.trim().length === 0 ? "Player " + (i + 1) : n.trim();
});
return names;
},
set: function (value) {
var valueStr = value.join(";");
UserSettings_LocalStorage.setUserSetting("userList", valueStr);
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserSettings_LocalStorage.prototype, "currentUserId", {
get: function () {
var valueStr = UserSettings_LocalStorage.getUserSetting("currentUserId");
var id = parseInt(valueStr || "0");
id = id < 0 ? 0 : id;
id = id > this.userList.length - 1 ? 0 : id;
return id;
},
set: function (value) {
var valueStr = "" + value;
UserSettings_LocalStorage.setUserSetting("currentUserId", valueStr);
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserSettings_LocalStorage.prototype, "currentUserName", {
get: function () {
return this.userList[this.currentUserId];
},
set: function (value) {
var users = this.userList;
var userId = users.indexOf(value);
this.currentUserId = userId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserSettings_LocalStorage.prototype, "currentUserState", {
get: function () {
var userId = this.currentUserId;
var valueStr = UserSettings_LocalStorage.getUserSetting("User" + userId + "_State") || JSON.stringify({ levels: [] });
return JSON.parse(valueStr);
},
set: function (value) {
var userId = this.currentUserId;
var valueStr = JSON.stringify(value);
UserSettings_LocalStorage.setUserSetting("User" + userId + "_State", valueStr);
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserSettings_LocalStorage.prototype, "hasModifiedUsers", {
get: function () {
var users = this.userList;
return users.length !== 1 || users[0] !== "Player 1";
},
enumerable: true,
configurable: true
});
return UserSettings_LocalStorage;
})();
Data.UserSettings_LocalStorage = UserSettings_LocalStorage;
})(TableMath.Data || (TableMath.Data = {}));
var Data = TableMath.Data;
})(Told.TableMath || (Told.TableMath = {}));
var TableMath = Told.TableMath;
})(Told || (Told = {}));
|
export default {
fontFamily: 'HelveticaNeue',
letterSpacing: 1
};
|
import fs from "fs";
import babel from "rollup-plugin-babel";
import commonjs from "rollup-plugin-commonjs";
import nodeResolve from "rollup-plugin-node-resolve";
import replace from "rollup-plugin-replace";
let babelrc = JSON.parse(fs.readFileSync(".babelrc", "utf8"));
babelrc.presets[babelrc.presets.indexOf("es2015")] = "es2015-rollup";
babelrc.babelrc = false;
let config = {
entry : "src/index.js",
dest : "www/build/bundle.js",
format : "iife",
sourceMap : true,
plugins : [
replace({
"process.env.NODE_ENV": JSON.stringify("production")
}),
nodeResolve({
jsnext : true,
main : true,
browser : true
}),
commonjs({
include : ["node_modules/**"],
namedExports : {
"node_modules/react/react.js" : ["Component", "Children", "createElement", "PropTypes"],
"node_modules/react-dom/index.js" : ["render"]
}
}),
babel(babelrc)
]
};
export default config; |
version https://git-lfs.github.com/spec/v1
oid sha256:8c622616eb5441b856e518cc34965edcfc1d4c061353e78cc10722e0b2de9ede
size 52677
|
System.register(['@angular/core'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
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 core_1;
var AutoEllipsesPipe;
return {
setters:[
function (core_1_1) {
core_1 = core_1_1;
}],
execute: function() {
AutoEllipsesPipe = (function () {
function AutoEllipsesPipe() {
}
//---------------------------------------------------------------------------
AutoEllipsesPipe.prototype.transform = function (text, maxLength, useAsPrefix) {
// If there is no max-length (-1) or the the text is short enough, don't trim.
if (maxLength == -1 ||
text.length < maxLength) {
return text;
}
// Trim and place ellipses either before or after text.
if (useAsPrefix) {
return '...' + text.substring(text.length - maxLength);
}
else {
return text.substring(0, maxLength).trim() + '...';
}
};
AutoEllipsesPipe = __decorate([
core_1.Pipe({
name: 'autoEllipses'
}),
__metadata('design:paramtypes', [])
], AutoEllipsesPipe);
return AutoEllipsesPipe;
}());
exports_1("AutoEllipsesPipe", AutoEllipsesPipe);
}
}
});
//# sourceMappingURL=autoEllipses.pipe.js.map |
var SelectGroup = (function() {
"use strict";
var SelectGroup = function(host) {
this.host(host);
this._elements = $([]);
this._selected = $([]);
};
function select(ctx, element) {
var selected = ctx._selected;
var elements = ctx._elements;
var max = ctx.max();
var autodeselect = ctx.autodeselect();
if( max === -1 || selected.length < max ) {
//console.log('select(1)', element);
selected.add(element);
ctx._host.fire('selectgroup.selected', {item:element, index:elements.indexOf(element)});
} else if( autodeselect && selected.length >= max ) {
//console.log('select(2)', element);
var min = ctx.min();
if( (selected.length + 1) > min ) {
var desel = selected[0];
selected.remove(desel);
ctx._host.fire('selectgroup.deselected', {item:desel, index:elements.indexOf(desel)});
}
selected.add(element);
ctx._host.fire('selectgroup.selected', {item:element, index:elements.indexOf(element)});
}
}
function deselect(ctx, element) {
var selected = ctx._selected;
var min = ctx.min();
if( selected.length > min ) {
selected.remove(element);
ctx._host.fire('selectgroup.deselected', {item:element, index:elements.indexOf(element)});
}
}
SelectGroup.prototype = {
// properties
host: function(host) {
if( !arguments.length ) return this._host;
if( !host ) return console.error('illegal arguments', host);
this._host = host;
return this;
},
min: function(min) {
if( !arguments.length ) return typeof(this._min) === 'number' ? this._min : 0;
if( typeof(min) !== 'number' ) return console.error('illegal arguments', min);
this._min = min;
return this;
},
max: function(max) {
if( !arguments.length ) return typeof(this._max) === 'number' ? this._max : -1;
if( typeof(max) !== 'number' ) return console.error('illegal arguments', max);
this._max = max;
return this;
},
autoselect: function(autoselect) {
if( !arguments.length ) return this._autoselect === true ? true : false;
if( typeof(autoselect) !== 'boolean' ) return console.error('illegal arguments', autoselect);
this._autoselect = autoselect;
return this;
},
autodeselect: function(autodeselect) {
if( !arguments.length ) return this._autodeselect === true ? true : false;
if( typeof(autodeselect) !== 'boolean' ) return console.error('illegal arguments', autodeselect);
this._autodeselect = autodeselect;
return this;
},
// evaluation
all: function() {
return this._elements.slice();
},
isSelected: function(element) {
return ~this._selected.indexOf(element) ? true : false;
},
selected: function() {
return this._selected.slice();
},
selectedCount: function() {
return this._selected.length;
},
// handling
add: function(elements) {
if( !elements ) return console.error('illegal arguments', elements);
if( !isArrayType(elements) ) elements = [elements];
var self = this;
for(var i=0; i < elements.length; i++) {
var el = elements[i];
if( !isElement(el) ) continue;
this._elements.add(el);
$(el).on('selected', function() {
select(self, this);
}).on('deselected', function() {
deselect(self, this);
});
var selected = el.getAttribute('selected');
if( selected === '' || selected ) select(this, el);
else if( this.autoselect() && this.min() > this.selectedCount() ) select(this, el);
}
return this;
}
};
return SelectGroup;
})();
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights and
* limitations under the License.
*
* The Original Code is Bespin.
*
* The Initial Developer of the Original Code is Mozilla.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Bespin Team (bespin@mozilla.com)
*
* ***** END LICENSE BLOCK ***** */
dojo.provide("bespin.editor.editor");
dojo.require("bespin.editor.clipboard");
/**
* some state mgmt. for scrollbars; not a true component
*/
dojo.declare("bespin.editor.Scrollbar", null, {
HORIZONTAL: "horizontal",
VERTICAL: "vertical",
MINIMUM_HANDLE_SIZE: 20,
constructor: function(ui, orientation, rect, value, min, max, extent) {
this.ui = ui;
this.orientation = orientation; // "horizontal" or "vertical"
this.rect = rect; // position/size of the scrollbar track
this.value = value; // current offset value
this.min = min; // minimum offset value
this.max = max; // maximum offset value
this.extent = extent; // size of the current visible subset
this.mousedownScreenPoint; // used for scroll bar dragging tracking; point at which the mousedown first occurred
this.mousedownValue; // value at time of scroll drag start
},
// return a Rect for the scrollbar handle
getHandleBounds: function() {
var sx = (this.isH()) ? this.rect.x : this.rect.y;
var sw = (this.isH()) ? this.rect.w : this.rect.h;
var smultiple = this.extent / (this.max + this.extent);
var asw = smultiple * sw;
if (asw < this.MINIMUM_HANDLE_SIZE) asw = this.MINIMUM_HANDLE_SIZE;
sx += (sw - asw) * (this.value / (this.max - this.min));
return (this.isH()) ? new bespin.editor.Rect(Math.floor(sx), this.rect.y, asw, this.rect.h) : new bespin.editor.Rect(this.rect.x, sx, this.rect.w, asw);
},
isH: function() {
return (!(this.orientation == this.VERTICAL));
},
fixValue: function(value) {
if (value < this.min) value = this.min;
if (value > this.max) value = this.max;
return value;
},
onmousewheel: function(e) {
// We need to move the editor unless something else needs to scroll.
// We need a clean way to define that behaviour, but for now we hack and put in other elements that can scroll
var command_output = dojo.byId("command_output");
var target = e.target || e.originalTarget;
if (command_output && (target.id == "command_output" || bespin.util.contains(command_output, target))) return;
if (!this.ui.editor.focus) return;
var wheel = bespin.util.mousewheelevent.wheel(e);
//console.log("Wheel speed: ", wheel);
var axis = bespin.util.mousewheelevent.axis(e);
if (this.orientation == this.VERTICAL && axis == this.VERTICAL) {
this.setValue(this.value + (wheel * this.ui.lineHeight));
} else if (this.orientation == this.HORIZONTAL && axis == this.HORIZONTAL) {
this.setValue(this.value + (wheel * this.ui.charWidth));
}
},
onmousedown: function(e) {
var clientY = e.clientY - this.ui.getTopOffset();
var clientX = e.clientX - this.ui.getLeftOffset();
var bar = this.getHandleBounds();
if (bar.contains({ x: clientX, y: clientY })) {
this.mousedownScreenPoint = (this.isH()) ? e.screenX : e.screenY;
this.mousedownValue = this.value;
} else {
var p = (this.isH()) ? clientX : clientY;
var b1 = (this.isH()) ? bar.x : bar.y;
var b2 = (this.isH()) ? bar.x2 : bar.y2;
if (p < b1) {
this.setValue(this.value -= this.extent);
} else if (p > b2) {
this.setValue(this.value += this.extent);
}
}
},
onmouseup: function(e) {
this.mousedownScreenPoint = null;
this.mousedownValue = null;
if (this.valueChanged) this.valueChanged(); // make the UI responsive when the user releases the mouse button (in case arrow no longer hovers over scrollbar)
},
onmousemove: function(e) {
if (this.mousedownScreenPoint) {
var diff = ((this.isH()) ? e.screenX : e.screenY) - this.mousedownScreenPoint;
var multiplier = diff / (this.isH() ? this.rect.w : this.rect.h);
this.setValue(this.mousedownValue + Math.floor(((this.max + this.extent) - this.min) * multiplier));
}
},
setValue: function(value) {
this.value = this.fixValue(value);
if (this.valueChanged) this.valueChanged();
}
});
/**
* treat as immutable (pretty please)
*/
dojo.declare("bespin.editor.Rect", null, {
constructor: function(x, y, w, h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.x2 = x + w;
this.y2 = y + h;
},
// inclusive of bounding lines
contains: function(point) {
if (!this.x) return false;
return ((this.x <= point.x) && ((this.x + this.w) >= point.x) && (this.y <= point.y) && ((this.y + this.h) >= point.y));
}
});
/**
*
*/
dojo.declare("bespin.editor.SelectionHelper", null, {
constructor: function(editor) {
this.editor = editor;
},
// returns an object with the startCol and endCol of the selection.
// If the col is -1 on the endPos, the selection goes for the entire line
// returns undefined if the row has no selection
getRowSelectionPositions: function(rowIndex) {
var startCol;
var endCol;
var selection = this.editor.getSelection();
if (!selection) return undefined;
if ((selection.endPos.row < rowIndex) || (selection.startPos.row > rowIndex)) return undefined;
startCol = (selection.startPos.row < rowIndex) ? 0 : selection.startPos.col;
endCol = (selection.endPos.row > rowIndex) ? -1 : selection.endPos.col;
return { startCol: startCol, endCol: endCol };
}
});
/**
* Mess with positions mainly
*/
dojo.mixin(bespin.editor, { utils: {
buildArgs: function(oldPos) {
return { pos: bespin.editor.utils.copyPos(oldPos || bespin.get('editor').getCursorPos()) };
},
changePos: function(args, pos) {
return { pos: bespin.editor.utils.copyPos(oldPos || bespin.get('editor').getCursorPos()) };
},
copyPos: function(oldPos) {
return { row: oldPos.row, col: oldPos.col };
},
posEquals: function(pos1, pos2) {
if (pos1 == pos2) return true;
if (!pos1 || !pos2) return false;
return (pos1.col == pos2.col) && (pos1.row == pos2.row);
},
diffObjects: function(o1, o2) {
var diffs = {};
if (!o1 || !o2) return undefined;
for (var key in o1) {
if (o2[key]) {
if (o1[key] != o2[key]) {
diffs[key] = o1[key] + " => " + o2[key];
}
} else {
diffs[key] = "o1: " + key + " = " + o1[key];
}
}
for (var key2 in o2) {
if (!o1[key2]) {
diffs[key2] = "o2: " + key2 + " = " + o2[key2];
}
}
return diffs;
}
}});
/**
* Core key listener to decide which actions to run
*/
dojo.declare("bespin.editor.DefaultEditorKeyListener", null, {
constructor: function(editor) {
this.editor = editor;
this.actions = editor.ui.actions;
this.skipKeypress = false;
this.defaultKeyMap = {};
// Allow for multiple key maps to be defined
this.keyMap = this.defaultKeyMap;
this.keyMapDescriptions = {};
},
bindKey: function(keyCode, metaKey, ctrlKey, altKey, shiftKey, action, name) {
this.defaultKeyMap[[keyCode, metaKey, ctrlKey, altKey, shiftKey]] =
(typeof action == "string") ?
function() {
var toFire = bespin.events.toFire(action);
bespin.publish(toFire.name, toFire.args);
} : dojo.hitch(this.actions, action);
if (name) this.keyMapDescriptions[[keyCode, metaKey, ctrlKey, altKey, shiftKey]] = name;
},
bindKeyForPlatform: function(keysForPlatforms, action, name, isSelectable) {
var platform = bespin.util.getOS();
// default to Windows (e.g. Linux often the same)
var platformKeys = keysForPlatforms[platform] || keysForPlatforms['WINDOWS'];
if (!platformKeys) return;
var args = bespin.util.keys.fillArguments(platformKeys);
var bindFunction = (isSelectable) ? "bindKeyStringSelectable" : "bindKeyString";
this[bindFunction](args.modifiers, bespin.util.keys.toKeyCode(args.key), action, name);
},
bindKeyString: function(modifiers, keyCode, action, name) {
var ctrlKey = (modifiers.toUpperCase().indexOf("CTRL") != -1);
var altKey = (modifiers.toUpperCase().indexOf("ALT") != -1);
var metaKey = (modifiers.toUpperCase().indexOf("META") != -1) || (modifiers.toUpperCase().indexOf("APPLE") != -1);
var shiftKey = (modifiers.toUpperCase().indexOf("SHIFT") != -1);
// Check for the platform specific key type
// The magic "CMD" means metaKey for Mac (the APPLE or COMMAND key)
// and ctrlKey for Windows (CONTROL)
if (modifiers.toUpperCase().indexOf("CMD") != -1) {
if (bespin.util.isMac()) {
metaKey = true;
} else {
ctrlKey = true;
}
}
return this.bindKey(keyCode, metaKey, ctrlKey, altKey, shiftKey, action, name);
},
bindKeyStringSelectable: function(modifiers, keyCode, action, name) {
this.bindKeyString(modifiers, keyCode, action, name);
this.bindKeyString("SHIFT " + modifiers, keyCode, action);
},
/*
this is taken from th.KeyHelpers
*/
getPrintableChar: function(e) {
if (e.charCode > 255) return false;
if (e.charCode < 32) return false;
if ((e.altKey || e.metaKey || e.ctrlKey) && (e.charCode > 65 && e.charCode < 123)) return false;
return String.fromCharCode(e.charCode);
},
onkeydown: function(e) {
// handle keys only if editor has the focus!
if (!this.editor.focus) return;
var args = { event: e,
pos: bespin.editor.utils.copyPos(this.editor.cursorManager.getCursorPosition()) };
this.skipKeypress = false;
this.returnValue = false;
var action = this.keyMap[[e.keyCode, e.metaKey, e.ctrlKey, e.altKey, e.shiftKey]];
var hasAction = false;
if (dojo.isFunction(action)) {
hasAction = true;
try {
action(args);
} catch (e) {
console.log("Action caused an error! ", e);
}
this.lastAction = action;
}
// If a special key is pressed OR if an action is assigned to a given key (e.g. TAB or BACKSPACE)
if (e.metaKey || e.ctrlKey || e.altKey) {
this.skipKeypress = true;
this.returnValue = true;
}
// stop going, but allow special strokes to get to the browser
if (hasAction || !bespin.util.keys.passThroughToBrowser(e)) dojo.stopEvent(e);
},
onkeypress: function(e) {
// handle keys only if editor has the focus!
if (!this.editor.focus) return;
if ( (e.metaKey || e.ctrlKey) && e.charCode >= 48 /*0*/ && e.charCode <= 57 /*9*/) {
return; // let APPLE || CTRL 0 through 9 get through to the browser
}
var charToPrint = this.getPrintableChar(e);
if (charToPrint) {
this.skipKeypress = false;
} else if (this.skipKeypress) {
if (!bespin.util.keys.passThroughToBrowser(e)) dojo.stopEvent(e);
return this.returnValue;
}
var args = { event: e,
pos: bespin.editor.utils.copyPos(this.editor.cursorManager.getCursorPosition()) };
var actions = this.editor.ui.actions;
if (charToPrint) {
args.newchar = String.fromCharCode(e.charCode);
actions.insertCharacter(args);
} else { // Allow user to move with the arrow continuously
var action = this.keyMap[[e.keyCode, e.metaKey, e.ctrlKey, e.altKey, e.shiftKey]];
if (this.lastAction == action) {
delete this.lastAction;
} else if (typeof action == "function") {
action(args);
}
}
dojo.stopEvent(e);
}
});
/**
* Holds the UI, the editor itself, the syntax highlighter, the actions, and more
*/
dojo.declare("bespin.editor.UI", null, {
constructor: function(editor) {
this.editor = editor;
this.model = this.editor.model;
var settings = bespin.get("settings");
this.syntaxModel = bespin.syntax.Resolver.setEngine("simple").getModel();
this.selectionHelper = new bespin.editor.SelectionHelper(editor);
this.actions = new bespin.editor.Actions(editor);
this.rowLengthCache = [];
this.searchString = null;
this.toggleCursorFullRepaintCounter = 0; // tracks how many cursor toggles since the last full repaint
this.toggleCursorFrequency = 250; // number of milliseconds between cursor blink
this.toggleCursorAllowed = true; // is the cursor allowed to toggle? (used by cursorManager.moveCursor)
// these two canvases are used as buffers for the scrollbar images, which are then composited onto the
// main code view. we could have saved ourselves some misery by just prerendering slices of the scrollbars and
// combining them like sane people, but... meh
this.horizontalScrollCanvas = dojo.create("canvas");
this.verticalScrollCanvas = dojo.create("canvas");
// gutterWidth used to be a constant, but is now dynamically calculated in each paint() invocation. I set it to a silly
// default value here in case some of the code expects it to be populated before the first paint loop kicks in. the
// default value ought to eventually become 0
this.gutterWidth = 54;
this.LINE_HEIGHT = 23;
this.BOTTOM_SCROLL_AFFORDANCE = 30; // if the bottom scrollbar is in the way, allow for a bit of scroll
this.GUTTER_INSETS = { top: 0, left: 6, right: 10, bottom: 6 };
this.LINE_INSETS = { top: 0, left: 5, right: 0, bottom: 6 };
this.FALLBACK_CHARACTER_WIDTH = 10;
this.NIB_WIDTH = 15;
this.NIB_INSETS = { top: Math.floor(this.NIB_WIDTH / 2),
left: Math.floor(this.NIB_WIDTH / 2),
right: Math.floor(this.NIB_WIDTH / 2),
bottom: Math.floor(this.NIB_WIDTH / 2) };
this.NIB_ARROW_INSETS = { top: 3, left: 3, right: 3, bottom: 5 };
this.DEBUG_GUTTER_WIDTH = 18;
this.DEBUG_GUTTER_INSETS = { top: 2, left: 2, right: 2, bottom: 2 };
//this.lineHeight; // reserved for when line height is calculated dynamically instead of with a constant; set first time a paint occurs
//this.charWidth; // set first time a paint occurs
//this.visibleRows; // the number of rows visible in the editor; set each time a paint occurs
//this.firstVisibleRow; // first row that is visible in the editor; set each time a paint occurs
//this.nibup; // rect
//this.nibdown; // rect
//this.nibleft; // rect
//this.nibright; // rect
//this.selectMouseDownPos; // position when the user moused down
//this.selectMouseDetail; // the detail (number of clicks) for the mouse down.
this.xoffset = 0; // number of pixels to translate the canvas for scrolling
this.yoffset = 0;
this.showCursor = true;
this.overXScrollBar = false;
this.overYScrollBar = false;
this.hasFocus = false;
var source = this.editor.container;
this.globalHandles = []; //a collection of global handles to event listeners that will need to be disposed.
dojo.connect(source, "mousemove", this, "handleMouse");
dojo.connect(source, "mouseout", this, "handleMouse");
dojo.connect(source, "click", this, "handleMouse");
dojo.connect(source, "mousedown", this, "handleMouse");
dojo.connect(source, "oncontextmenu", dojo.stopEvent);
dojo.connect(source, "mousedown", this, "mouseDownSelect");
this.globalHandles.push(dojo.connect(window, "mousemove", this, "mouseMoveSelect"));
this.globalHandles.push(dojo.connect(window, "mouseup", this, "mouseUpSelect"));
// painting optimization state
this.lastLineCount = 0;
this.lastCursorPos = null;
this.lastxoffset = 0;
this.lastyoffset = 0;
//if we act as component, onmousewheel should only be listened to inside of the editor canvas.
var scope = editor.opts.actsAsComponent ? editor.canvas : window;
this.xscrollbar = new bespin.editor.Scrollbar(this, "horizontal");
this.xscrollbar.valueChanged = dojo.hitch(this, function() {
this.xoffset = -this.xscrollbar.value;
this.editor.paint();
});
this.globalHandles.push(dojo.connect(window, "mousemove", this.xscrollbar, "onmousemove"));
this.globalHandles.push(dojo.connect(window, "mouseup", this.xscrollbar, "onmouseup"));
this.globalHandles.push(
dojo.connect(scope, (!dojo.isMozilla ? "onmousewheel" : "DOMMouseScroll"), this.xscrollbar, "onmousewheel")
);
this.yscrollbar = new bespin.editor.Scrollbar(this, "vertical");
this.yscrollbar.valueChanged = dojo.hitch(this, function() {
this.yoffset = -this.yscrollbar.value;
this.editor.paint();
});
this.globalHandles.push(dojo.connect(window, "mousemove", this.yscrollbar, "onmousemove"));
this.globalHandles.push(dojo.connect(window, "mouseup", this.yscrollbar, "onmouseup"));
this.globalHandles.push(
dojo.connect(scope, (!dojo.isMozilla ? "onmousewheel" : "DOMMouseScroll"), this.yscrollbar, "onmousewheel")
);
setTimeout(dojo.hitch(this, function() { this.toggleCursor(this); }), this.toggleCursorFrequency);
},
/**
* col is -1 if user clicked in gutter; clicking below last line maps to last line
*/
convertClientPointToCursorPoint: function(pos) {
var settings = bespin.get("settings");
var x, y;
if (pos.y < 0) { //ensure line >= first
y = 0;
} else if (pos.y >= (this.lineHeight * this.editor.model.getRowCount())) { //ensure line <= last
y = this.editor.model.getRowCount() - 1;
} else {
var ty = pos.y;
y = Math.floor(ty / this.lineHeight);
}
if (pos.x <= (this.gutterWidth + this.LINE_INSETS.left)) {
x = -1;
} else {
var tx = pos.x - this.gutterWidth - this.LINE_INSETS.left;
// round vs floor so we can pick the left half vs right half of a character
x = Math.round(tx / this.charWidth);
// With strictlines turned on, don't select past the end of the line
if ((settings && settings.isSettingOn('strictlines'))) {
var maxcol = this.getRowScreenLength(y);
if (x >= maxcol) {
x = this.getRowScreenLength(y);
}
}
}
return { row: y, col: x };
},
mouseDownSelect: function(e) {
// only select if the editor has the focus!
if (!this.editor.focus) return;
if (e.button == 2) {
dojo.stopEvent(e);
return false;
}
var clientY = e.clientY - this.getTopOffset();
var clientX = e.clientX - this.getLeftOffset();
if (this.overXScrollBar || this.overYScrollBar) return;
if (this.editor.debugMode) {
if (clientX < this.DEBUG_GUTTER_WIDTH) {
console.log("Clicked in debug gutter");
var point = { x: clientX, y: clientY };
point.y += Math.abs(this.yoffset);
var p = this.convertClientPointToCursorPoint(point);
var editSession = bespin.get("editSession");
if (p && editSession) {
bespin.getComponent("breakpoints", function(breakpoints) {
breakpoints.toggleBreakpoint({ project: editSession.project, path: editSession.path, lineNumber: p.row });
this.editor.paint(true);
}, this);
}
return;
}
}
this.selectMouseDetail = e.detail;
if (e.shiftKey) {
this.selectMouseDownPos = (this.editor.selection) ? this.editor.selection.startPos : this.editor.getCursorPos();
this.setSelection(e);
} else {
var point = { x: clientX, y: clientY };
// happens first, because scroll bars are not relative to scroll position
if ((this.xscrollbar.rect.contains(point)) || (this.yscrollbar.rect.contains(point))) return;
// now, compensate for scroll position.
point.x += Math.abs(this.xoffset);
point.y += Math.abs(this.yoffset);
this.selectMouseDownPos = this.convertClientPointToCursorPoint(point);
}
},
mouseMoveSelect: function(e) {
// only select if the editor has the focus!
if (!this.editor.focus) return;
this.setSelection(e);
},
mouseUpSelect: function(e) {
// only select if the editor has the focus!
if (!this.editor.focus) return;
this.setSelection(e);
this.selectMouseDownPos = undefined;
this.selectMouseDetail = undefined;
},
setSelection: function(e) {
var clientY = e.clientY - this.getTopOffset();
var clientX = e.clientX - this.getLeftOffset();
if (!this.selectMouseDownPos) return;
var down = bespin.editor.utils.copyPos(this.selectMouseDownPos);
var point = { x: clientX, y: clientY };
point.x += Math.abs(this.xoffset);
point.y += Math.abs(this.yoffset);
var up = this.convertClientPointToCursorPoint(point);
if (down.col == -1) {
down.col = 0;
// clicked in gutter; show appropriate lineMarker message
var lineMarker = bespin.get("parser").getLineMarkers()[down.row + 1];
if (lineMarker) {
bespin.get("commandLine").showHint(lineMarker.msg);
}
}
if (up.col == -1) up.col = 0;
//we'll be dealing with the model directly, so we need model positions.
var modelstart = this.editor.getModelPos(down);
var modelend = this.editor.getModelPos(up);
//to make things simpler, go ahead and check if it is reverse
var backwards = false;
if (modelend.row < modelstart.row || (modelend.row == modelstart.row && modelend.col < modelstart.col)) {
backwards = true; //need to know so that we can maintain direction for shift-click select
var temp = modelstart;
modelstart = modelend;
modelend = temp;
}
//validate
if (!this.editor.model.hasRow(modelstart.row)) {
modelstart.row = this.editor.model.getRowCount() - 1;
}
if (!this.editor.model.hasRow(modelend.row)) {
modelend.row = this.editor.model.getRowCount() - 1;
}
//get detail
var detail = this.selectMouseDetail;
//single click
if (detail == 1) {
if (bespin.editor.utils.posEquals(modelstart, modelend)) {
this.editor.setSelection(undefined);
} else {
//we could use raw "down" and "up", but that would skip validation.
this.editor.setSelection({
startPos: this.editor.getCursorPos(backwards ? modelend : modelstart),
endPos: this.editor.getCursorPos(backwards ? modelstart : modelend)
});
}
this.editor.moveCursor(this.editor.getCursorPos(backwards ? modelstart : modelend));
} else if (detail == 2) { //double click
var row = this.editor.model.rows[modelstart.row];
var cursorAt = row[modelstart.col];
// the following is an ugly hack. We should have a syntax-specific set of "delimiter characters"
// which are treated like whitespace for findBefore and findAfter.
// to keep it at least a LITTLE neat, I have moved the comparator for double-click into its own function,
// and have left model alone.
var isDelimiter = function(item) {
var delimiters = ["=", " ", "\t", ">", "<", ".", "(", ")", "{", "}", ":", '"', "'", ";"];
if (delimiters.indexOf(item) > -1)
return true;
return false;
};
if (!cursorAt) {
// nothing to see here. We must be past the end of the line.
// Per Gordon's suggestion, let's have double-click EOL select the line, excluding newline
this.editor.setSelection({
startPos: this.editor.getCursorPos({row: modelstart.row, col: 0}),
endPos: this.editor.getCursorPos({row: modelstart.row, col: row.length})
});
} else if (isDelimiter(cursorAt.charAt(0))) { // see above. Means empty space or =, >, <, etc. that we want to be clever with
var comparator = function(letter) {
if (isDelimiter(letter))
return false;
return true;
};
var startPos = this.editor.model.findBefore(modelstart.row, modelstart.col, comparator);
var endPos = this.editor.model.findAfter(modelend.row, modelend.col, comparator);
this.editor.setSelection({
startPos: this.editor.getCursorPos(backwards ? endPos : startPos),
endPos: this.editor.getCursorPos(backwards ? startPos : endPos)
});
//set cursor so that it is at selection end (even if mouse wasn't there)
this.editor.moveCursor(this.editor.getCursorPos(backwards ? startPos : endPos));
} else {
var comparator = function(letter) {
if (isDelimiter(letter))
return true;
return false;
};
var startPos = this.editor.model.findBefore(modelstart.row, modelstart.col, comparator);
var endPos = this.editor.model.findAfter(modelend.row, modelend.col, comparator);
this.editor.setSelection({
startPos: this.editor.getCursorPos(backwards ? endPos : startPos),
endPos: this.editor.getCursorPos(backwards ? startPos : endPos)
});
//set cursor so that it is at selection end (even if mouse wasn't there)
this.editor.moveCursor(this.editor.getCursorPos(backwards ? startPos : endPos));
}
} else if (detail > 2) { //triple plus duluxe
// select the line
var startPos = {row: modelstart.row, col: 0};
var endPos = {row: modelend.row, col: 0};
if (this.editor.model.hasRow(endPos.row + 1)) {
endPos.row = endPos.row + 1;
} else {
endPos.col = this.editor.model.getRowArray(endPos.row).length;
}
startPos = this.editor.getCursorPos(startPos);
endPos = this.editor.getCursorPos(endPos);
this.editor.setSelection({
startPos: backwards ? endPos : startPos,
endPos: backwards ? startPos: endPos
});
this.editor.moveCursor(backwards ? startPos : endPos);
}
//finally, and the LAST thing we should do (otherwise we'd mess positioning up)
//scroll down, up, right, or left a bit if needed.
//up and down. optimally, we should have a timeout or something to keep checking...
if (clientY < 0) {
this.yoffset = Math.min(1, this.yoffset + (-clientY));
} else if (clientY >= this.getHeight()) {
var virtualHeight = this.lineHeight * this.editor.model.getRowCount();
this.yoffset = Math.max(-(virtualHeight - this.getHeight() - this.BOTTOM_SCROLL_AFFORDANCE), this.yoffset - clientY - this.getHeight());
}
this.editor.paint();
},
toggleCursor: function(ui) {
if (ui.toggleCursorAllowed) {
ui.showCursor = !ui.showCursor;
} else {
ui.toggleCursorAllowed = true;
}
if (++this.toggleCursorFullRepaintCounter > 0) {
this.toggleCursorFullRepaintCounter = 0;
ui.editor.paint(true);
} else {
ui.editor.paint();
}
setTimeout(function() { ui.toggleCursor(ui); }, ui.toggleCursorFrequency);
},
ensureCursorVisible: function(softEnsure) {
if ((!this.lineHeight) || (!this.charWidth)) return; // can't do much without these
if(bespin.get('settings')) {
var pageScroll = parseFloat(bespin.get('settings').get('pagescroll')) || 0;
} else {
var pageScroll = 0;
}
pageScroll = (!softEnsure ? Math.max(0, Math.min(1, pageScroll)) : 0.25);
var y = this.lineHeight * this.editor.cursorManager.getCursorPosition().row;
var x = this.charWidth * this.editor.cursorManager.getCursorPosition().col;
var cheight = this.getHeight();
var cwidth = this.getWidth() - this.gutterWidth;
if (Math.abs(this.yoffset) > y) { // current row before top-most visible row
this.yoffset = Math.min(-y + cheight * pageScroll, 0);
} else if ((Math.abs(this.yoffset) + cheight) < (y + this.lineHeight)) { // current row after bottom-most visible row
this.yoffset = -((y + this.lineHeight) - cheight * (1 - pageScroll));
this.yoffset = Math.max(this.yoffset, cheight - this.lineHeight * this.model.getRowCount());
}
if (Math.abs(this.xoffset) > x) { // current col before left-most visible col
this.xoffset = -x;
} else if ((Math.abs(this.xoffset) + cwidth) < (x + (this.charWidth * 2))) { // current col after right-most visible col
this.xoffset = -((x + (this.charWidth * 2)) - cwidth);
}
},
handleFocus: function(e) {
this.editor.model.clear();
this.editor.model.insertCharacters({ row: 0, col: 0 }, e.type);
},
handleMouse: function(e) {
// Right click for pie menu
if (e.button == 2) {
bespin.getComponent("piemenu", function(piemenu) {
piemenu.show(null, false, e.clientX, e.clientY);
});
dojo.stopEvent(e);
return false;
}
var clientY = e.clientY - this.getTopOffset();
var clientX = e.clientX - this.getLeftOffset();
var oldX = this.overXScrollBar;
var oldY = this.overYScrollBar;
var scrolled = false;
var w = this.editor.container.clientWidth;
var h = this.editor.container.clientHeight;
var sx = w - this.NIB_WIDTH - this.NIB_INSETS.right; // x start of the vert. scroll bar
var sy = h - this.NIB_WIDTH - this.NIB_INSETS.bottom; // y start of the hor. scroll bar
var p = { x: clientX, y:clientY };
if (e.type == "mousedown") {
// dispatch to the scrollbars
if ((this.xscrollbar) && (this.xscrollbar.rect.contains(p))) {
this.xscrollbar.onmousedown(e);
} else if ((this.yscrollbar) && (this.yscrollbar.rect.contains(p))) {
this.yscrollbar.onmousedown(e);
}
}
if (e.type == "mouseout") {
this.overXScrollBar = false;
this.overYScrollBar = false;
}
if ((e.type == "mousemove") || (e.type == "click")) {
//and only true IF the scroll bar is visible, obviously.
this.overYScrollBar = (p.x > sx) && this.yscrollbarVisible;
this.overXScrollBar = (p.y > sy) && this.xscrollbarVisible;
}
if (e.type == "click") {
if ((typeof e.button != "undefined") && (e.button == 0)) {
var button;
if (this.nibup.contains(p)) {
button = "up";
} else if (this.nibdown.contains(p)) {
button = "down";
} else if (this.nibleft.contains(p)) {
button = "left";
} else if (this.nibright.contains(p)) {
button = "right";
}
if (button == "up") {
this.yoffset += this.lineHeight;
scrolled = true;
} else if (button == "down") {
this.yoffset -= this.lineHeight;
scrolled = true;
} else if (button == "left") {
this.xoffset += this.charWidth * 2;
scrolled = true;
} else if (button == "right") {
this.xoffset -= this.charWidth * 2;
scrolled = true;
}
}
}
//mousing over the scroll bars requires a full refresh
if ((oldX != this.overXScrollBar) || (oldY != this.overYScrollBar) || scrolled)
this.editor.paint(true);
},
installKeyListener: function(listener) {
var Key = bespin.util.keys.Key; // alias
if (this.oldkeydown) dojo.disconnect(this.oldkeydown);
if (this.oldkeypress) dojo.disconnect(this.oldkeypress);
this.oldkeydown = dojo.hitch(listener, "onkeydown");
this.oldkeypress = dojo.hitch(listener, "onkeypress");
var scope = this.editor.opts.actsAsComponent ? this.editor.canvas : window;
dojo.connect(scope, "keydown", this, "oldkeydown");
dojo.connect(scope, "keypress", this, "oldkeypress");
// Modifiers, Key, Action
listener.bindKeyStringSelectable("", Key.LEFT_ARROW, this.actions.moveCursorLeft, "Move Cursor Left");
listener.bindKeyStringSelectable("", Key.RIGHT_ARROW, this.actions.moveCursorRight, "Move Cursor Right");
listener.bindKeyStringSelectable("", Key.UP_ARROW, this.actions.moveCursorUp, "Move Cursor Up");
listener.bindKeyStringSelectable("", Key.DOWN_ARROW, this.actions.moveCursorDown, "Move Cursor Down");
// Move Left: Mac = Alt+Left, Win/Lin = Ctrl+Left
listener.bindKeyForPlatform({
MAC: "ALT LEFT_ARROW",
WINDOWS: "CTRL LEFT_ARROW"
}, this.actions.moveWordLeft, "Move Word Left", true /* selectable */);
// Move Right: Mac = Alt+Right, Win/Lin = Ctrl+Right
listener.bindKeyForPlatform({
MAC: "ALT RIGHT_ARROW",
WINDOWS: "CTRL RIGHT_ARROW"
}, this.actions.moveWordRight, "Move Word Right", true /* selectable */);
// Start of line: All platforms support HOME. Mac = Apple+Left, Win/Lin = Alt+Left
listener.bindKeyStringSelectable("", Key.HOME, this.actions.moveToLineStart, "Move to start of line");
listener.bindKeyForPlatform({
MAC: "APPLE LEFT_ARROW",
WINDOWS: "ALT LEFT_ARROW"
}, this.actions.moveToLineStart, "Move to start of line", true /* selectable */);
// End of line: All platforms support END. Mac = Apple+Right, Win/Lin = Alt+Right
listener.bindKeyStringSelectable("", Key.END, this.actions.moveToLineEnd, "Move to end of line");
listener.bindKeyForPlatform({
MAC: "APPLE RIGHT_ARROW",
WINDOWS: "ALT RIGHT_ARROW"
}, this.actions.moveToLineEnd, "Move to end of line", true /* selectable */);
listener.bindKeyString("CTRL", Key.K, this.actions.killLine, "Kill entire line");
listener.bindKeyString("CMD", Key.L, this.actions.gotoLine, "Goto Line");
listener.bindKeyString("CTRL", Key.L, this.actions.moveCursorRowToCenter, "Move cursor to center of page");
listener.bindKeyStringSelectable("", Key.BACKSPACE, this.actions.backspace, "Backspace");
listener.bindKeyStringSelectable("CTRL", Key.BACKSPACE, this.actions.deleteWordLeft, "Delete a word to the left");
listener.bindKeyString("", Key.DELETE, this.actions.deleteKey, "Delete");
listener.bindKeyString("CTRL", Key.DELETE, this.actions.deleteWordRight, "Delete a word to the right");
listener.bindKeyString("", Key.ENTER, this.actions.newline, "Insert newline");
listener.bindKeyString("CMD", Key.ENTER, this.actions.newlineBelow, "Insert newline at end of current line");
listener.bindKeyString("", Key.TAB, this.actions.insertTab, "Indent / insert tab");
listener.bindKeyString("SHIFT", Key.TAB, this.actions.unindent, "Unindent");
listener.bindKeyString("CMD", Key.SQUARE_BRACKET_CLOSE, this.actions.indent, "Indent");
listener.bindKeyString("CMD", Key.SQUARE_BRACKET_OPEN, this.actions.unindent, "Unindent");
listener.bindKeyString("", Key.ESCAPE, this.actions.escape, "Clear fields and dialogs");
listener.bindKeyString("CMD", Key.A, this.actions.selectAll, "Select All");
// handle key to jump between editor and other windows / commandline
listener.bindKeyString("CMD", Key.I, this.actions.toggleQuickopen, "Toggle Quickopen");
listener.bindKeyString("CMD", Key.J, this.actions.focusCommandline, "Open Command line");
listener.bindKeyString("CMD", Key.O, this.actions.focusFileBrowser, "Open File Browser");
listener.bindKeyString("CMD", Key.F, this.actions.cmdFilesearch, "Search in this file");
listener.bindKeyString("CMD", Key.G, this.actions.findNext, "Find Next");
listener.bindKeyString("SHIFT CMD", Key.G, this.actions.findPrev, "Find Previous");
listener.bindKeyString("CTRL", Key.M, this.actions.togglePieMenu, "Open Pie Menu");
listener.bindKeyString("CMD", Key.Z, this.actions.undo, "Undo");
listener.bindKeyString("SHIFT CMD", Key.Z, this.actions.redo, "Redo");
listener.bindKeyString("CMD", Key.Y, this.actions.redo, "Redo");
listener.bindKeyStringSelectable("CMD", Key.UP_ARROW, this.actions.moveToFileTop, "Move to top of file");
listener.bindKeyStringSelectable("CMD", Key.DOWN_ARROW, this.actions.moveToFileBottom, "Move to bottom of file");
listener.bindKeyStringSelectable("CMD", Key.HOME, this.actions.moveToFileTop, "Move to top of file");
listener.bindKeyStringSelectable("CMD", Key.END, this.actions.moveToFileBottom, "Move to bottom of file");
listener.bindKeyStringSelectable("", Key.PAGE_UP, this.actions.movePageUp, "Move a page up");
listener.bindKeyStringSelectable("", Key.PAGE_DOWN, this.actions.movePageDown, "Move a page down");
// For now we are punting and doing a page down, but in the future we will tie to outline mode and move in block chunks
listener.bindKeyStringSelectable("ALT", Key.UP_ARROW, this.actions.movePageUp, "Move up a block");
listener.bindKeyStringSelectable("ALT", Key.DOWN_ARROW, this.actions.movePageDown, "Move down a block");
listener.bindKeyString("CMD ALT", Key.LEFT_ARROW, this.actions.previousFile);
listener.bindKeyString("CMD ALT", Key.RIGHT_ARROW, this.actions.nextFile);
// Other key bindings can be found in commands themselves.
// For example, this:
// Refactor warning: Below used to have an action - publish to "editor:newfile",
// cahnged to this.editor.newfile but might not work as assumed.
// listener.bindKeyString("CTRL SHIFT", Key.N, this.editor.newfile, "Create a new file");
// has been moved to the 'newfile' command withKey
// Also, the clipboard.js handles C, V, and X
},
getWidth: function() {
return parseInt(dojo.style(this.editor.canvas.parentNode, "width"));
},
getHeight: function() {
return parseInt(dojo.style(this.editor.canvas.parentNode, "height"));
},
getTopOffset: function() {
return dojo.coords(this.editor.canvas.parentNode).y || this.editor.canvas.parentNode.offsetTop;
},
getLeftOffset: function() {
return dojo.coords(this.editor.canvas.parentNode).x || this.editor.canvas.parentNode.offsetLeft;
},
getCharWidth: function(ctx) {
if (ctx.measureText) {
return ctx.measureText("M").width;
} else {
return this.FALLBACK_CHARACTER_WIDTH;
}
},
getLineHeight: function(ctx) {
var lh = -1;
if (ctx.measureText) {
var t = ctx.measureText("M");
if (t.ascent) lh = Math.floor(t.ascent * 2.8);
}
if (lh == -1) lh = this.LINE_HEIGHT;
return lh;
},
resetCanvas: function() { // forces a resize of the canvas
dojo.attr(dojo.byId(this.editor.canvas), { width: this.getWidth(), height: this.getHeight() });
},
/*
* Wrap the normal fillText for the normal case
*/
fillText: function(ctx, text, x, y) {
ctx.fillText(text, x, y);
},
/*
* Set the transparency to 30% for the fillText (e.g. readonly mode uses this)
*/
fillTextWithTransparency: function(ctx, text, x, y) {
ctx.globalAlpha = 0.3;
ctx.fillText(text, x, y);
ctx.globalAlpha = 1.0;
},
/**
* This is where the editor is painted from head to toe.
* The optional "fullRefresh" argument triggers a complete repaint of the
* editor canvas; otherwise, pitiful tricks are used to draw as little as possible.
*/
paint: function(ctx, fullRefresh) {
// DECLARE VARIABLES
// these are convenience references so we don't have to type so much
var ed = this.editor;
var c = dojo.byId(ed.canvas);
var theme = ed.theme;
// these are commonly used throughout the rendering process so are defined up here to make it clear they are shared
var x, y;
var cy;
var currentLine;
var lastLineToRender;
var Rect = bespin.editor.Rect;
// SETUP STATE
var refreshCanvas = fullRefresh; // if the user explicitly requests a full refresh, give it to 'em
if (!refreshCanvas) refreshCanvas = (this.selectMouseDownPos);
if (!refreshCanvas) refreshCanvas = (this.lastLineCount != ed.model.getRowCount()); // if the line count has changed, full refresh
this.lastLineCount = ed.model.getRowCount(); // save the number of lines for the next time paint
// get the line and character metrics; calculated for each paint because this value can change at run-time
ctx.font = theme.editorTextFont;
this.charWidth = this.getCharWidth(ctx);
this.lineHeight = this.getLineHeight(ctx);
// cwidth and cheight are set to the dimensions of the parent node of the canvas element; we'll resize the canvas element
// itself a little bit later in this function
var cwidth = this.getWidth();
var cheight = this.getHeight();
// adjust the scrolling offsets if necessary; negative values are good, indicate scrolling down or to the right (we look for overflows on these later on)
// positive values are bad; they indicate scrolling up past the first line or to the left past the first column
if (this.xoffset > 0) this.xoffset = 0;
if (this.yoffset > 0) this.yoffset = 0;
// only paint those lines that can be visible
this.visibleRows = Math.ceil(cheight / this.lineHeight);
this.firstVisibleRow = Math.floor(Math.abs(this.yoffset / this.lineHeight));
lastLineToRender = this.firstVisibleRow + this.visibleRows;
if (lastLineToRender > (ed.model.getRowCount() - 1)) lastLineToRender = ed.model.getRowCount() - 1;
var virtualheight = this.lineHeight * ed.model.getRowCount(); // full height based on content
// virtual width *should* be based on every line in the model; however, with the introduction of tab support, calculating
// the width of a line is now expensive, so for the moment we will only calculate the width of the visible rows
//var virtualwidth = this.charWidth * (Math.max(this.getMaxCols(), ed.cursorManager.getCursorPosition().col) + 2); // full width based on content plus a little padding
var virtualwidth = this.charWidth * (Math.max(this.getMaxCols(this.firstVisibleRow, lastLineToRender), ed.cursorManager.getCursorPosition().col) + 2);
// calculate the gutter width; for now, we'll make it fun and dynamic based on the lines visible in the editor.
this.gutterWidth = this.GUTTER_INSETS.left + this.GUTTER_INSETS.right; // first, add the padding space
this.gutterWidth += ("" + lastLineToRender).length * this.charWidth; // make it wide enough to display biggest line number visible
if (this.editor.debugMode) this.gutterWidth += this.DEBUG_GUTTER_WIDTH;
// these next two blocks make sure we don't scroll too far in either the x or y axis
if (this.xoffset < 0) {
if ((Math.abs(this.xoffset)) > (virtualwidth - (cwidth - this.gutterWidth))) this.xoffset = (cwidth - this.gutterWidth) - virtualwidth;
}
if (this.yoffset < 0) {
if ((Math.abs(this.yoffset)) > (virtualheight - (cheight - this.BOTTOM_SCROLL_AFFORDANCE))) this.yoffset = cheight - (virtualheight - this.BOTTOM_SCROLL_AFFORDANCE);
}
// if the current scrolled positions are different than the scroll positions we used for the last paint, refresh the entire canvas
if ((this.xoffset != this.lastxoffset) || (this.yoffset != this.lastyoffset)) {
refreshCanvas = true;
this.lastxoffset = this.xoffset;
this.lastyoffset = this.yoffset;
}
// these are boolean values indicating whether the x and y (i.e., horizontal or vertical) scroll bars are visible
var xscroll = ((cwidth - this.gutterWidth) < virtualwidth);
var yscroll = (cheight < virtualheight);
// the scroll bars are rendered off-screen into their own canvas instances; these values are used in two ways as part of
// this process:
// 1. the x position of the vertical scroll bar image when painted onto the canvas and the y position of the horizontal
// scroll bar image (both images span 100% of the width/height in the other dimension)
// 2. the amount * -1 to translate the off-screen canvases used by the scrollbars; this lets us flip back to rendering
// the scroll bars directly on the canvas with relative ease (by omitted the translations and passing in the main context
// reference instead of the off-screen canvas context)
var verticalx = cwidth - this.NIB_WIDTH - this.NIB_INSETS.right - 2;
var horizontaly = cheight - this.NIB_WIDTH - this.NIB_INSETS.bottom - 2;
// these are boolean values that indicate whether special little "nibs" should be displayed indicating more content to the
// left, right, top, or bottom
var showLeftScrollNib = (xscroll && (this.xoffset != 0));
var showRightScrollNib = (xscroll && (this.xoffset > ((cwidth - this.gutterWidth) - virtualwidth)));
var showUpScrollNib = (yscroll && (this.yoffset != 0));
var showDownScrollNib = (yscroll && (this.yoffset > (cheight - virtualheight)));
// check and see if the canvas is the same size as its immediate parent in the DOM; if not, resize the canvas
if (((dojo.attr(c, "width")) != cwidth) || (dojo.attr(c, "height") != cheight)) {
refreshCanvas = true; // if the canvas changes size, we'll need a full repaint
dojo.attr(c, { width: cwidth, height: cheight });
}
// get debug metadata
var breakpoints = {};
var lineMarkers = bespin.get("parser").getLineMarkers();
if (this.editor.debugMode && bespin.get("editSession")) {
bespin.getComponent("breakpoints", function(bpmanager) {
var points = bpmanager.getBreakpoints(bespin.get('editSession').project, bespin.get('editSession').path);
dojo.forEach(points, function(point) {
breakpoints[point.lineNumber] = point;
});
delete points;
});
}
// IF YOU WANT TO FORCE A COMPLETE REPAINT OF THE CANVAS ON EVERY PAINT, UNCOMMENT THE FOLLOWING LINE:
//refreshCanvas = true;
// START RENDERING
// if we're not doing a full repaint, work out which rows are "dirty" and need to be repainted
if (!refreshCanvas) {
var dirty = ed.model.getDirtyRows();
// if the cursor has changed rows since the last paint, consider the previous row dirty
if ((this.lastCursorPos) && (this.lastCursorPos.row != ed.cursorManager.getCursorPosition().row)) dirty[this.lastCursorPos.row] = true;
// we always repaint the current line
dirty[ed.cursorManager.getCursorPosition().row] = true;
}
// save this state for the next paint attempt (see above for usage)
this.lastCursorPos = bespin.editor.utils.copyPos(ed.cursorManager.getCursorPosition());
// if we're doing a full repaint...
if (refreshCanvas) {
// ...paint the background color over the whole canvas and...
ctx.fillStyle = theme.backgroundStyle;
ctx.fillRect(0, 0, c.width, c.height);
// ...paint the gutter
ctx.fillStyle = theme.gutterStyle;
ctx.fillRect(0, 0, this.gutterWidth, c.height);
}
// translate the canvas based on the scrollbar position; for now, just translate the vertical axis
ctx.save(); // take snapshot of current context state so we can roll back later on
// the Math.round(this.yoffset) makes the painting nice and not to go over 2 pixels
// see for more informations:
// - https://developer.mozilla.org/en/Canvas_tutorial/Applying_styles_and_colors, section "Line styles"
// - https://developer.mozilla.org/@api/deki/files/601/=Canvas-grid.png
ctx.translate(0, Math.round(this.yoffset));
// paint the line numbers
if (refreshCanvas) {
//line markers first
if (bespin.get("parser")) {
for (currentLine = this.firstVisibleRow; currentLine <= lastLineToRender; currentLine++) {
if (lineMarkers[currentLine]) {
y = this.lineHeight * (currentLine - 1);
cy = y + (this.lineHeight - this.LINE_INSETS.bottom);
ctx.fillStyle = this.editor.theme["lineMarker" + lineMarkers[currentLine].type + "Color"];
ctx.fillRect(0, y, this.gutterWidth, this.lineHeight);
}
}
}
y = (this.lineHeight * this.firstVisibleRow);
for (currentLine = this.firstVisibleRow; currentLine <= lastLineToRender; currentLine++) {
x = 0;
// if we're in debug mode...
if (this.editor.debugMode) {
// ...check if the current line has a breakpoint
if (breakpoints[currentLine]) {
var bpx = x + this.DEBUG_GUTTER_INSETS.left;
var bpy = y + this.DEBUG_GUTTER_INSETS.top;
var bpw = this.DEBUG_GUTTER_WIDTH - this.DEBUG_GUTTER_INSETS.left - this.DEBUG_GUTTER_INSETS.right;
var bph = this.lineHeight - this.DEBUG_GUTTER_INSETS.top - this.DEBUG_GUTTER_INSETS.bottom;
var bpmidpointx = bpx + parseInt(bpw / 2);
var bpmidpointy = bpy + parseInt(bph / 2);
ctx.strokeStyle = "rgb(128, 0, 0)";
ctx.fillStyle = "rgb(255, 102, 102)";
ctx.beginPath();
ctx.arc(bpmidpointx, bpmidpointy, bpw / 2, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
// ...and push the line number to the right, leaving a space for breakpoint stuff
x += this.DEBUG_GUTTER_WIDTH;
}
x += this.GUTTER_INSETS.left;
cy = y + (this.lineHeight - this.LINE_INSETS.bottom);
ctx.fillStyle = theme.lineNumberColor;
ctx.font = this.editor.theme.lineNumberFont;
//console.log(currentLine + " " + x + " " + cy);
ctx.fillText(currentLine + 1, x, cy);
y += this.lineHeight;
}
}
// and now we're ready to translate the horizontal axis; while we're at it, we'll setup a clip to prevent any drawing outside
// of code editor region itself (protecting the gutter). this clip is important to prevent text from bleeding into the gutter.
ctx.save();
ctx.beginPath();
ctx.rect(this.gutterWidth, -this.yoffset, cwidth - this.gutterWidth, cheight);
ctx.closePath();
ctx.translate(this.xoffset, 0);
ctx.clip();
// calculate the first and last visible columns on the screen; these values will be used to try and avoid painting text
// that the user can't actually see
var firstColumn = Math.floor(Math.abs(this.xoffset / this.charWidth));
var lastColumn = firstColumn + (Math.ceil((cwidth - this.gutterWidth) / this.charWidth));
// create the state necessary to render each line of text
y = (this.lineHeight * this.firstVisibleRow);
var cc; // the starting column of the current region in the region render loop below
var ce; // the ending column in the same loop
var ri; // counter variable used for the same loop
var regionlen; // length of the text in the region; used in the same loop
var tx, tw, tsel;
var settings = bespin.get("settings");
var searchStringLength = (this.searchString ? this.searchString.length : -1);
// paint each line
for (currentLine = this.firstVisibleRow; currentLine <= lastLineToRender; currentLine++) {
x = this.gutterWidth;
// if we aren't repainting the entire canvas...
if (!refreshCanvas) {
// ...don't bother painting the line unless it is "dirty" (see above for dirty checking)
if (!dirty[currentLine]) {
y += this.lineHeight;
continue;
}
// setup a clip for the current line only; this makes drawing just that piece of the scrollbar easy
ctx.save(); // this is restore()'d in another if (!refreshCanvas) block at the end of the loop
ctx.beginPath();
ctx.rect(x + (Math.abs(this.xoffset)), y, cwidth, this.lineHeight);
ctx.closePath();
ctx.clip();
if ((currentLine % 2) == 1) { // only repaint the line background if the zebra stripe won't be painted into it
ctx.fillStyle = theme.backgroundStyle;
ctx.fillRect(x + (Math.abs(this.xoffset)), y, cwidth, this.lineHeight);
}
}
// if highlight line is on, paint the highlight color
if ((settings && settings.isSettingOn('highlightline')) &&
(currentLine == ed.cursorManager.getCursorPosition().row)) {
ctx.fillStyle = theme.highlightCurrentLineColor;
ctx.fillRect(x + (Math.abs(this.xoffset)), y, cwidth, this.lineHeight);
// if not on highlight, see if we need to paint the zebra
} else if ((currentLine % 2) == 0) {
ctx.fillStyle = theme.zebraStripeColor;
ctx.fillRect(x + (Math.abs(this.xoffset)), y, cwidth, this.lineHeight);
}
x += this.LINE_INSETS.left;
cy = y + (this.lineHeight - this.LINE_INSETS.bottom);
// paint the selection bar if the line has selections
var selections = this.selectionHelper.getRowSelectionPositions(currentLine);
if (selections) {
tx = x + (selections.startCol * this.charWidth);
tw = (selections.endCol == -1) ? (lastColumn - firstColumn) * this.charWidth : (selections.endCol - selections.startCol) * this.charWidth;
ctx.fillStyle = theme.editorSelectedTextBackground;
ctx.fillRect(tx, y, tw, this.lineHeight);
}
var lineMetadata = this.model.getRowMetadata(currentLine);
var lineText = lineMetadata.lineText;
var searchIndices = lineMetadata.searchIndices;
// the following two chunks of code do the same thing; only one should be uncommented at a time
// CHUNK 1: this code just renders the line with white text and is for testing
// ctx.fillStyle = "white";
// ctx.fillText(this.editor.model.getRowArray(currentLine).join(""), x, cy);
// CHUNK 2: this code uses the SyntaxModel API to render the line
// syntax highlighting
var lineInfo = this.syntaxModel.getSyntaxStylesPerLine(lineText, currentLine, this.editor.language);
// Define a fill that is aware of the readonly attribute and fades out if applied
var readOnlyAwareFill = ed.readonly ? this.fillTextWithTransparency : this.fillText;
for (ri = 0; ri < lineInfo.regions.length; ri++) {
var styleInfo = lineInfo.regions[ri];
for (var style in styleInfo) {
if (!styleInfo.hasOwnProperty(style)) continue;
var thisLine = "";
var styleArray = styleInfo[style];
var currentColumn = 0; // current column, inclusive
for (var si = 0; si < styleArray.length; si++) {
var range = styleArray[si];
for ( ; currentColumn < range.start; currentColumn++) thisLine += " ";
thisLine += lineInfo.text.substring(range.start, range.stop);
currentColumn = range.stop;
}
ctx.fillStyle = this.editor.theme[style] || "white";
ctx.font = this.editor.theme.editorTextFont;
readOnlyAwareFill(ctx, thisLine, x, cy);
}
}
// highlight search string
if (searchIndices) {
// in some cases the selections are -1 => set them to a more "realistic" number
if (selections) {
tsel = { startCol: 0, endCol: lineText.length };
if (selections.startCol != -1) tsel.startCol = selections.startCol;
if (selections.endCol != -1) tsel.endCol = selections.endCol;
} else {
tsel = false;
}
for (var i = 0; i < searchIndices.length; i++) {
var index = ed.cursorManager.getCursorPosition({col: searchIndices[i], row: currentLine}).col;
tx = x + index * this.charWidth;
// highlight the area
ctx.fillStyle = this.editor.theme.searchHighlight;
ctx.fillRect(tx, y, searchStringLength * this.charWidth, this.lineHeight);
// figure out, whether the selection is in this area. If so, colour it different
if (tsel) {
var indexStart = index;
var indexEnd = index + searchStringLength;
if (tsel.startCol < indexEnd && tsel.endCol > indexStart) {
indexStart = Math.max(indexStart, tsel.startCol);
indexEnd = Math.min(indexEnd, tsel.endCol);
ctx.fillStyle = this.editor.theme.searchHighlightSelected;
ctx.fillRect(x + indexStart * this.charWidth, y, (indexEnd - indexStart) * this.charWidth, this.lineHeight);
}
}
// print the overpainted text again
ctx.fillStyle = this.editor.theme.editorTextColor || "white";
ctx.fillText(lineText.substring(index, index + searchStringLength), tx, cy);
}
}
// paint tab information, if applicable and the information should be displayed
if (settings && (settings.isSettingOn("tabarrow") || settings.isSettingOn("tabshowspace"))) {
if (lineMetadata.tabExpansions.length > 0) {
for (var i = 0; i < lineMetadata.tabExpansions.length; i++) {
var expansion = lineMetadata.tabExpansions[i];
// the starting x position of the tab character; the existing value of y is fine
var lx = x + (expansion.start * this.charWidth);
// check if the user wants us to highlight tabs; useful if you need to mix tabs and spaces
var showTabSpace = settings && settings.isSettingOn("tabshowspace");
if (showTabSpace) {
var sw = (expansion.end - expansion.start) * this.charWidth;
ctx.fillStyle = this.editor.theme["tabSpace"] || "white";
ctx.fillRect(lx, y, sw, this.lineHeight);
}
var showTabNib = settings && settings.isSettingOn("tabarrow");
if (showTabNib) {
// the center of the current character position's bounding rectangle
var cy = y + (this.lineHeight / 2);
var cx = lx + (this.charWidth / 2);
// the width and height of the triangle to draw representing the tab
var tw = 4;
var th = 6;
// the origin of the triangle
var tx = parseInt(cx - (tw / 2));
var ty = parseInt(cy - (th / 2));
// draw the rectangle
ctx.globalAlpha = 0.3; // make the tab arrow subtle
ctx.beginPath();
ctx.fillStyle = this.editor.theme["plain"] || "white";
ctx.moveTo(tx, ty);
ctx.lineTo(tx, ty + th);
ctx.lineTo(tx + tw, ty + parseInt(th / 2));
ctx.closePath();
ctx.fill();
ctx.globalAlpha = 1.0;
}
}
}
}
if (!refreshCanvas) {
ctx.drawImage(this.verticalScrollCanvas, verticalx + Math.abs(this.xoffset), Math.abs(this.yoffset));
ctx.restore();
}
y += this.lineHeight;
}
// paint the cursor
if (this.editor.focus) {
if (this.showCursor) {
if (ed.theme.cursorType == "underline") {
x = this.gutterWidth + this.LINE_INSETS.left + ed.cursorManager.getCursorPosition().col * this.charWidth;
y = (ed.getCursorPos().row * this.lineHeight) + (this.lineHeight - 5);
ctx.fillStyle = ed.theme.cursorStyle;
ctx.fillRect(x, y, this.charWidth, 3);
} else {
x = this.gutterWidth + this.LINE_INSETS.left + ed.cursorManager.getCursorPosition().col * this.charWidth;
y = (ed.cursorManager.getCursorPosition().row * this.lineHeight);
ctx.fillStyle = ed.theme.cursorStyle;
ctx.fillRect(x, y, 1, this.lineHeight);
}
}
} else {
x = this.gutterWidth + this.LINE_INSETS.left + ed.cursorManager.getCursorPosition().col * this.charWidth;
y = (ed.cursorManager.getCursorPosition().row * this.lineHeight);
ctx.fillStyle = ed.theme.unfocusedCursorFillStyle;
ctx.strokeStyle = ed.theme.unfocusedCursorStrokeStyle;
ctx.fillRect(x, y, this.charWidth, this.lineHeight);
ctx.strokeRect(x, y, this.charWidth, this.lineHeight);
}
// TODO: This is a hacky way to paint other users cursors.
// I've commented it out because there are a number of issues:
// - We're re-painting our own cursor. We need to re-establish sending
// the mobwrite window id from the server and then processing this
// in session.js to mark an editSession to say "this is me"
// - We really need to get the concept of serverData nailed
// - The UI sucks
// Paint the cursors of other users
var session = bespin.get("editSession");
var self = this;
if (session) {
var userEntries = session.getUserEntries();
if (userEntries) {
userEntries.forEach(function(userEntry) {
if (!userEntry.clientData.isMe) {
x = self.gutterWidth + self.LINE_INSETS.left + userEntry.clientData.cursor.start.col * self.charWidth;
y = userEntry.clientData.cursor.start.row * self.lineHeight;
ctx.fillStyle = "#ee8c00";
ctx.fillRect(x, y, 1, self.lineHeight);
var prevFont = ctx.font;
ctx.font = "6pt Monaco, Lucida Console, monospace";
ctx.fillText(userEntry.handle, x + 3, y + self.lineHeight + 4);
ctx.font = prevFont;
}
});
};
}
// scroll bars - x axis
ctx.restore();
// scrollbars - y axis
ctx.restore();
// paint scroll bars unless we don't need to :-)
if (!refreshCanvas) return;
// temporary disable of scrollbars
//if (this.xscrollbar.rect) return;
if (this.horizontalScrollCanvas.width != cwidth) this.horizontalScrollCanvas.width = cwidth;
if (this.horizontalScrollCanvas.height != this.NIB_WIDTH + 4) this.horizontalScrollCanvas.height = this.NIB_WIDTH + 4;
if (this.verticalScrollCanvas.height != cheight) this.verticalScrollCanvas.height = cheight;
if (this.verticalScrollCanvas.width != this.NIB_WIDTH + 4) this.verticalScrollCanvas.width = this.NIB_WIDTH + 4;
var hctx = this.horizontalScrollCanvas.getContext("2d");
hctx.clearRect(0, 0, this.horizontalScrollCanvas.width, this.horizontalScrollCanvas.height);
hctx.save();
var vctx = this.verticalScrollCanvas.getContext("2d");
vctx.clearRect(0, 0, this.verticalScrollCanvas.width, this.verticalScrollCanvas.height);
vctx.save();
var ythemes = (this.overYScrollBar) || (this.yscrollbar.mousedownValue != null) ?
{ n: ed.theme.fullNibStyle, a: ed.theme.fullNibArrowStyle, s: ed.theme.fullNibStrokeStyle } :
{ n: ed.theme.partialNibStyle, a: ed.theme.partialNibArrowStyle, s: ed.theme.partialNibStrokeStyle };
var xthemes = (this.overXScrollBar) || (this.xscrollbar.mousedownValue != null) ?
{ n: ed.theme.fullNibStyle, a: ed.theme.fullNibArrowStyle, s: ed.theme.fullNibStrokeStyle } :
{ n: ed.theme.partialNibStyle, a: ed.theme.partialNibArrowStyle, s: ed.theme.partialNibStrokeStyle };
var midpoint = Math.floor(this.NIB_WIDTH / 2);
this.nibup = new Rect(cwidth - this.NIB_INSETS.right - this.NIB_WIDTH,
this.NIB_INSETS.top, this.NIB_WIDTH, this.NIB_WIDTH);
this.nibdown = new Rect(cwidth - this.NIB_INSETS.right - this.NIB_WIDTH,
cheight - (this.NIB_WIDTH * 2) - (this.NIB_INSETS.bottom * 2),
this.NIB_INSETS.top,
this.NIB_WIDTH, this.NIB_WIDTH);
this.nibleft = new Rect(this.gutterWidth + this.NIB_INSETS.left, cheight - this.NIB_INSETS.bottom - this.NIB_WIDTH,
this.NIB_WIDTH, this.NIB_WIDTH);
this.nibright = new Rect(cwidth - (this.NIB_INSETS.right * 2) - (this.NIB_WIDTH * 2),
cheight - this.NIB_INSETS.bottom - this.NIB_WIDTH,
this.NIB_WIDTH, this.NIB_WIDTH);
vctx.translate(-verticalx, 0);
hctx.translate(0, -horizontaly);
if (xscroll && ((this.overXScrollBar) || (this.xscrollbar.mousedownValue != null))) {
hctx.save();
hctx.beginPath();
hctx.rect(this.nibleft.x + midpoint + 2, 0, this.nibright.x - this.nibleft.x - 1, cheight); // y points don't matter
hctx.closePath();
hctx.clip();
hctx.fillStyle = ed.theme.scrollTrackFillStyle;
hctx.fillRect(this.nibleft.x, this.nibleft.y - 1, this.nibright.x2 - this.nibleft.x, this.nibleft.h + 1);
hctx.strokeStyle = ed.theme.scrollTrackStrokeStyle;
hctx.strokeRect(this.nibleft.x, this.nibleft.y - 1, this.nibright.x2 - this.nibleft.x, this.nibleft.h + 1);
hctx.restore();
}
if (yscroll && ((this.overYScrollBar) || (this.yscrollbar.mousedownValue != null))) {
vctx.save();
vctx.beginPath();
vctx.rect(0, this.nibup.y + midpoint + 2, cwidth, this.nibdown.y - this.nibup.y - 1); // x points don't matter
vctx.closePath();
vctx.clip();
vctx.fillStyle = ed.theme.scrollTrackFillStyle;
vctx.fillRect(this.nibup.x - 1, this.nibup.y, this.nibup.w + 1, this.nibdown.y2 - this.nibup.y);
vctx.strokeStyle = ed.theme.scrollTrackStrokeStyle;
vctx.strokeRect(this.nibup.x - 1, this.nibup.y, this.nibup.w + 1, this.nibdown.y2 - this.nibup.y);
vctx.restore();
}
if (yscroll) {
// up arrow
if ((showUpScrollNib) || (this.overYScrollBar) || (this.yscrollbar.mousedownValue != null)) {
vctx.save();
vctx.translate(this.nibup.x + midpoint, this.nibup.y + midpoint);
this.paintNib(vctx, ythemes.n, ythemes.a, ythemes.s);
vctx.restore();
}
// down arrow
if ((showDownScrollNib) || (this.overYScrollBar) || (this.yscrollbar.mousedownValue != null)) {
vctx.save();
vctx.translate(this.nibdown.x + midpoint, this.nibdown.y + midpoint);
vctx.rotate(Math.PI);
this.paintNib(vctx, ythemes.n, ythemes.a, ythemes.s);
vctx.restore();
}
}
if (xscroll) {
// left arrow
if ((showLeftScrollNib) || (this.overXScrollBar) || (this.xscrollbar.mousedownValue != null)) {
hctx.save();
hctx.translate(this.nibleft.x + midpoint, this.nibleft.y + midpoint);
hctx.rotate(Math.PI * 1.5);
this.paintNib(hctx, xthemes.n, xthemes.a, xthemes.s);
hctx.restore();
}
// right arrow
if ((showRightScrollNib) || (this.overXScrollBar) || (this.xscrollbar.mousedownValue != null)) {
hctx.save();
hctx.translate(this.nibright.x + midpoint, this.nibright.y + midpoint);
hctx.rotate(Math.PI * 0.5);
this.paintNib(hctx, xthemes.n, xthemes.a, xthemes.s);
hctx.restore();
}
}
// the bar
var sx = this.nibleft.x2 + 4;
var sw = this.nibright.x - this.nibleft.x2 - 9;
this.xscrollbar.rect = new Rect(sx, this.nibleft.y - 1, sw, this.nibleft.h + 1);
this.xscrollbar.value = -this.xoffset;
this.xscrollbar.min = 0;
this.xscrollbar.max = virtualwidth - (cwidth - this.gutterWidth);
this.xscrollbar.extent = cwidth - this.gutterWidth;
if (xscroll) {
var fullonxbar = (((this.overXScrollBar) && (virtualwidth > cwidth)) || ((this.xscrollbar) && (this.xscrollbar.mousedownValue != null)));
if (!fullonxbar) hctx.globalAlpha = 0.3;
this.paintScrollbar(hctx, this.xscrollbar);
hctx.globalAlpha = 1.0;
}
var sy = this.nibup.y2 + 4;
var sh = this.nibdown.y - this.nibup.y2 - 9;
this.yscrollbar.rect = new Rect(this.nibup.x - 1, sy, this.nibup.w + 1, sh);
this.yscrollbar.value = -this.yoffset;
this.yscrollbar.min = 0;
this.yscrollbar.max = virtualheight - (cheight - this.BOTTOM_SCROLL_AFFORDANCE);
this.yscrollbar.extent = cheight;
if (yscroll) {
var fullonybar = ((this.overYScrollBar) && (virtualheight > cheight)) || ((this.yscrollbar) && (this.yscrollbar.mousedownValue != null));
if (!fullonybar) vctx.globalAlpha = 0.3;
this.paintScrollbar(vctx, this.yscrollbar);
vctx.globalAlpha = 1;
}
// composite the scrollbars
ctx.drawImage(this.verticalScrollCanvas, verticalx, 0);
ctx.drawImage(this.horizontalScrollCanvas, 0, horizontaly);
hctx.restore();
vctx.restore();
// clear the unusued nibs
if (!showUpScrollNib) this.nibup = new Rect();
if (!showDownScrollNib) this.nibdown = new Rect();
if (!showLeftScrollNib) this.nibleft = new Rect();
if (!showRightScrollNib) this.nibright = new Rect();
//set whether scrollbars are visible, so mouseover and such can pass through if not.
this.xscrollbarVisible = xscroll;
this.yscrollbarVisible = yscroll;
},
paintScrollbar: function(ctx, scrollbar) {
var bar = scrollbar.getHandleBounds();
var alpha = (ctx.globalAlpha) ? ctx.globalAlpha : 1;
if (!scrollbar.isH()) {
ctx.save(); // restored in another if (!scrollbar.isH()) block at end of function
ctx.translate(bar.x + Math.floor(bar.w / 2), bar.y + Math.floor(bar.h / 2));
ctx.rotate(Math.PI * 1.5);
ctx.translate(-(bar.x + Math.floor(bar.w / 2)), -(bar.y + Math.floor(bar.h / 2)));
// if we're vertical, the bar needs to be re-worked a bit
bar = new bespin.editor.Rect(bar.x - Math.floor(bar.h / 2) + Math.floor(bar.w / 2),
bar.y + Math.floor(bar.h / 2) - Math.floor(bar.w / 2), bar.h, bar.w);
}
var halfheight = bar.h / 2;
ctx.beginPath();
ctx.arc(bar.x + halfheight, bar.y + halfheight, halfheight, Math.PI / 2, 3 * (Math.PI / 2), false);
ctx.arc(bar.x2 - halfheight, bar.y + halfheight, halfheight, 3 * (Math.PI / 2), Math.PI / 2, false);
ctx.lineTo(bar.x + halfheight, bar.y + bar.h);
ctx.closePath();
var gradient = ctx.createLinearGradient(bar.x, bar.y, bar.x, bar.y + bar.h);
gradient.addColorStop(0, this.editor.theme.scrollBarFillGradientTopStart.replace(/%a/, alpha));
gradient.addColorStop(0.4, this.editor.theme.scrollBarFillGradientTopStop.replace(/%a/, alpha));
gradient.addColorStop(0.41, this.editor.theme.scrollBarFillStyle.replace(/%a/, alpha));
gradient.addColorStop(0.8, this.editor.theme.scrollBarFillGradientBottomStart.replace(/%a/, alpha));
gradient.addColorStop(1, this.editor.theme.scrollBarFillGradientBottomStop.replace(/%a/, alpha));
ctx.fillStyle = gradient;
ctx.fill();
ctx.save();
ctx.clip();
ctx.fillStyle = this.editor.theme.scrollBarFillStyle.replace(/%a/, alpha);
ctx.beginPath();
ctx.moveTo(bar.x + (halfheight * 0.4), bar.y + (halfheight * 0.6));
ctx.lineTo(bar.x + (halfheight * 0.9), bar.y + (bar.h * 0.4));
ctx.lineTo(bar.x, bar.y + (bar.h * 0.4));
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(bar.x + bar.w - (halfheight * 0.4), bar.y + (halfheight * 0.6));
ctx.lineTo(bar.x + bar.w - (halfheight * 0.9), bar.y + (bar.h * 0.4));
ctx.lineTo(bar.x + bar.w, bar.y + (bar.h * 0.4));
ctx.closePath();
ctx.fill();
ctx.restore();
ctx.beginPath();
ctx.arc(bar.x + halfheight, bar.y + halfheight, halfheight, Math.PI / 2, 3 * (Math.PI / 2), false);
ctx.arc(bar.x2 - halfheight, bar.y + halfheight, halfheight, 3 * (Math.PI / 2), Math.PI / 2, false);
ctx.lineTo(bar.x + halfheight, bar.y + bar.h);
ctx.closePath();
ctx.strokeStyle = this.editor.theme.scrollTrackStrokeStyle;
ctx.stroke();
if (!scrollbar.isH()) {
ctx.restore();
}
},
paintNib: function(ctx, nibStyle, arrowStyle, strokeStyle) {
var midpoint = Math.floor(this.NIB_WIDTH / 2);
ctx.fillStyle = nibStyle;
ctx.beginPath();
ctx.arc(0, 0, Math.floor(this.NIB_WIDTH / 2), 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = strokeStyle;
ctx.stroke();
ctx.fillStyle = arrowStyle;
ctx.beginPath();
ctx.moveTo(0, -midpoint + this.NIB_ARROW_INSETS.top);
ctx.lineTo(-midpoint + this.NIB_ARROW_INSETS.left, midpoint - this.NIB_ARROW_INSETS.bottom);
ctx.lineTo(midpoint - this.NIB_ARROW_INSETS.right, midpoint - this.NIB_ARROW_INSETS.bottom);
ctx.closePath();
ctx.fill();
},
/**
* returns metadata about the string that represents the row;
* converts tab characters to spaces
*/
getRowString: function(row) {
return this.model.getRowMetadata(row).lineText;
},
getRowScreenLength: function(row) {
return this.getRowString(row).length;
},
/**
* returns the maximum number of display columns across all rows
*/
getMaxCols: function(firstRow, lastRow) {
var cols = 0;
for (var i = firstRow; i <= lastRow; i++) {
cols = Math.max(cols, this.getRowScreenLength(i));
}
return cols;
},
setSearchString: function(str) {
if (str && str != '') {
this.searchString = str;
} else {
delete this.searchString;
}
this.model.searchStringChanged(this.searchString);
this.editor.paint(true);
},
dispose: function() {
for (var i = 0; i < this.globalHandles.length; i++) {
dojo.disconnect(this.globalHandles[i]);
}
}
});
/**
* bespin.editor.API is the root object, the API that others should be able to
* use
*/
dojo.declare("bespin.editor.API", null, {
constructor: function(container, opts) {
this.opts = opts || {};
// fixme: this stuff may not belong here
this.debugMode = false;
this.container = dojo.byId(container);
this.model = new bespin.editor.DocumentModel(this);
this.container.innerHTML = '<canvas id="canvas" moz-opaque="true" tabindex="-1"></canvas>';
this.canvas = this.container.firstChild;
while (this.canvas && this.canvas.nodeType != 1) this.canvas = this.canvas.nextSibling;
this.cursorManager = new bespin.editor.CursorManager(this);
this.ui = new bespin.editor.UI(this);
this.theme = bespin.themes['default'];
this.editorKeyListener = new bespin.editor.DefaultEditorKeyListener(this);
this.historyManager = new bespin.editor.HistoryManager(this);
this.customEvents = new bespin.editor.Events(this);
this.ui.installKeyListener(this.editorKeyListener);
this.model.insertCharacters({ row: 0, col: 0 }, " ");
dojo.connect(this.canvas, "blur", dojo.hitch(this, function(e) { this.setFocus(false); }));
dojo.connect(this.canvas, "focus", dojo.hitch(this, function(e) { this.setFocus(true); }));
bespin.editor.clipboard.setup(this);
this.paint();
if (!this.opts.dontfocus) {
this.setFocus(true);
}
},
/**
* ensures that the start position is before the end position; reading
* directly from the selection property makes no such guarantee
*/
getSelection: function(selection) {
selection = (selection != undefined) ? selection : this.selection;
if (!selection) return undefined;
var startPos = selection.startPos;
var endPos = selection.endPos;
// ensure that the start position is always before the end position
if ((endPos.row < startPos.row) || ((endPos.row == startPos.row) && (endPos.col < startPos.col))) {
var foo = startPos;
startPos = endPos;
endPos = foo;
}
return {
startPos: bespin.editor.utils.copyPos(startPos),
endPos: bespin.editor.utils.copyPos(endPos),
startModelPos: this.getModelPos(startPos),
endModelPos: this.getModelPos(endPos)
};
},
/**
*
*/
getCursorPos: function(modelPos) {
return this.cursorManager.getCursorPosition(modelPos);
},
/**
*
*/
getModelPos: function(pos) {
return this.cursorManager.getModelPosition(pos);
},
/**
*
*/
moveCursor: function(pos) {
this.cursorManager.moveCursor(pos);
},
/**
* restore the state of the editor
*/
resetView: function(data) {
this.cursorManager.moveCursor(data.cursor);
this.setSelection(data.selection);
this.ui.yoffset = data.offset.y;
this.ui.xoffset = data.offset.x;
},
basicView: function() {
this.cursorManager.moveCursor({row: 0, col: 0});
this.setSelection(undefined);
this.ui.yoffset = 0;
this.ui.xoffset = 0;
},
getCurrentView: function() {
return {
cursor: this.getCursorPos(),
offset: {
x: this.ui.xoffset,
y: this.ui.yoffset
},
selection: this.selection
};
},
getState: function() {
return { cursor: this.getCursorPos(), selection: this.getSelection() };
},
setState: function(data) {
this.cursorManager.moveCursor(data.cursor);
this.setSelection(data.selection);
this.ui.ensureCursorVisible();
this.paint(false);
},
/**
* be gentle trying to get the tabstop from settings
*/
getTabSize: function() {
var settings = bespin.get("settings");
var size = bespin.defaultTabSize; // default
if (settings) {
var tabsize = parseInt(settings.get("tabsize"));
if (tabsize > 0) size = tabsize;
}
return size;
},
/**
* helper to get text
*/
getSelectionAsText: function() {
var selectionText = '';
var selectionObject = this.getSelection();
if (selectionObject) {
selectionText = this.model.getChunk(selectionObject);
}
return selectionText;
},
setSelection: function(selection) {
this.selection = selection;
},
paint: function(fullRefresh) {
var ctx = bespin.util.canvas.fix(this.canvas.getContext("2d"));
this.ui.paint(ctx, fullRefresh);
},
changeKeyListener: function(newKeyListener) {
this.ui.installKeyListener(newKeyListener);
this.editorKeyListener = newKeyListener;
},
/**
* This does not set focus to the editor; it indicates that focus has been
* set to the underlying canvas
*/
setFocus: function(focus) {
this.focus = focus;
// force it if you have too
if (focus) {
this.canvas.focus();
}
},
/**
* Prevent user edits
*/
setReadOnly: function(readonly) {
this.readonly = readonly;
},
/**
* Anything that this editor creates should be gotten rid of.
* Useful when you will be creating and destroying editors more than once.
*/
dispose: function() {
// TODO: Isn't bespin.editor == this?
bespin.editor.clipboard.uninstall();
this.ui.dispose();
},
/**
* Add key listeners
* e.g. bindkey('moveCursorLeft', 'ctrl b');
*/
bindKey: function(action, keySpec, selectable) {
console.warn("Use of editor.bindKey(", action, keySpec, selectable, ") seems doomed to fail");
var keyObj = bespin.util.keys.fillArguments(keySpec);
var key = keyObj.key;
var modifiers = keyObj.modifiers;
if (!key) {
// TODO: shouldn't we complain or something?
return;
}
var keyCode = bespin.util.keys.toKeyCode(key);
// -- try an editor action first, else fire off a command
var actionDescription = "Execute command: '" + action + "'";
var action = this.ui.actions[action] || function() {
bespin.get('commandLine').executeCommand(command, true);
};
if (keyCode && action) {
if (selectable) {
// register the selectable binding too (e.g. SHIFT + what you passed in)
this.editorKeyListener.bindKeyStringSelectable(modifiers, keyCode, action, actionDescription);
} else {
this.editorKeyListener.bindKeyString(modifiers, keyCode, action, actionDescription);
}
}
},
/**
* Ensure that a given command is executed on each keypress
*/
bindCommand: function(command, keySpec) {
var keyObj = bespin.util.keys.fillArguments(keySpec);
var keyCode = bespin.util.keys.toKeyCode(keyObj.key);
var action = function() {
bespin.getComponent("commandLine", function(cli) {
cli.executeCommand(command, true);
});
};
var actionDescription = "Execute command: '" + command + "'";
this.editorKeyListener.bindKeyString(keyObj.modifiers, keyCode, action, actionDescription);
},
/**
* Observe a request to move the editor to a given location and center it
* TODO: There is probably a better location for this. Move it.
*/
moveAndCenter: function(row) {
if (!row) return; // short circuit
var linenum = row - 1; // move it up a smidge
this.cursorManager.moveCursor({ row: linenum, col: 0 });
// If the line that we are moving to is off screen, center it, else just move in place
if ((linenum < this.ui.firstVisibleRow) ||
(linenum >= this.ui.firstVisibleRow + this.ui.visibleRows)) {
this.ui.actions.moveCursorRowToCenter();
}
},
/**
* Observe a request for a new file to be created
*/
newFile: function(project, path, content) {
project = project || bespin.get('editSession').project;
path = path || "new.txt";
var self = this;
var onSuccess = function() {
// If collaboration is turned on, then session.js takes care of
// updating the editor with contents, setting it here might break
// the synchronization process.
// See the note at the top of session.js:EditSession.startSession()
if (bespin.get("settings").isSettingOff("collaborate")) {
self.model.insertDocument(content || "");
self.cursorManager.moveCursor({ row: 0, col: 0 });
self.setFocus(true);
}
bespin.publish("editor:openfile:opensuccess", {
project: project,
file: {
name: path,
content: content || "",
timestamp: new Date().getTime()
}
});
bespin.publish("editor:dirty");
};
bespin.get('files').newFile(project, path, onSuccess);
},
/**
* Observe a request for a file to be saved and start the cycle:
* <ul>
* <li>Send event that you are about to save the file (savebefore)
* <li>Get the last operation from the sync helper if it is up and running
* <li>Ask the file system to save the file
* <li>Change the page title to have the new filename
* <li>Tell the command line to show the fact that the file is saved
* </ul>
*/
saveFile: function(project, filename, onSuccess, onFailure) {
project = project || bespin.get('editSession').project;
filename = filename || bespin.get('editSession').path; // default to what you have
// saves the current state of the editor to a cookie
dojo.cookie('viewData_' + project + '_' + filename.split('/').join('_'), dojo.toJson(bespin.get('editor').getCurrentView()), { expires: 7 });
var file = {
name: filename,
content: this.model.getDocument(),
timestamp: new Date().getTime()
};
var newOnSuccess = function() {
document.title = filename + ' - editing with Bespin';
var commandLine = bespin.get("commandLine");
if (commandLine) commandLine.showHint('Saved file: ' + file.name);
bespin.publish("editor:clean");
if (dojo.isFunction(onSuccess)) {
onSuccess();
}
};
var newOnFailure = function(xhr) {
var commandLine = bespin.get("commandLine");
if (commandLine) commandLine.showHint('Save failed: ' + xhr.responseText);
if (dojo.isFunction(onFailure)) {
onFailure();
}
};
bespin.publish("editor:savefile:before", { filename: filename });
bespin.get('files').saveFile(project, file, newOnSuccess, newOnFailure);
},
/**
* Observe a request for a file to be opened and start the cycle.
* <ul>
* <li>Send event that you are opening up something (openbefore)
* <li>Ask the file system to load a file (editFile)
* <li>If the file is loaded send an opensuccess event
* <li>If the file fails to load, send an openfail event
* </ul>
* @param project The project that contains the file to open. null implies
* the current project
* @param filename The path to a file inside the given project
* @param options Object that determines how the file is opened. Values
* should be under one of the following keys:<ul>
* <li>fromFileHistory: If a file is opened from the file history then it
* will not be added to the history.
* TODO: Surely it should be the job of the history mechanism to avoid
* duplicates, and potentially promote recently opened files to the top of
* the list however they were opened?
* <li>reload: Normally a request to open the current file will be ignored
* unless 'reload=true' is specified in the options
* <li>line: The line number to place the cursor at
* <li>force: If true, will open the file even if it does not exist
* <li>content: if force===true and the file does not exist then the given
* content will be used to populate the new file
* </ul>
* TODO: Should we have onSuccess and onFailure callbacks?
*/
openFile: function(project, filename, options) {
var session = bespin.get('editSession');
var commandLine = bespin.get('commandLine');
var self = this;
var project = project || session.project;
var filename = filename || session.path;
var options = options || {};
var fromFileHistory = options.fromFileHistory || false;
// Short circuit if we are already open at the requested file
if (session.checkSameFile(project, filename) && !options.reload) {
if (options.line) {
commandLine.executeCommand('goto ' + options.line, true);
}
return;
}
// If the current buffer is dirty, for now, save it
if (this.dirty && !session.shouldCollaborate()) {
var onFailure = function(xhr) {
commandLine.showHint("Trying to save current file. Failed: " + xhr.responseText);
};
var onSuccess = function() {
self.openFile(project, filename, options);
};
this.saveFile(null, null, onSuccess, onFailure);
return;
}
if (options.force) {
bespin.get('files').whenFileDoesNotExist(project, filename, {
execute: function() {
self.newFile(project, filename, options.content || "");
},
elseFailed: function() {
// TODO: clone options to avoid changing original
options.force = false;
self.openFile(project, filename, options);
}
});
return;
}
var onFailure = function() {
bespin.publish("editor:openfile:openfail", { project: project, filename: filename });
};
var onSuccess = function(file) {
// TODO: We shouldn't need to to this but originally there was
// no onFailure, and this is how failure was communicated
if (!file) {
onFailure();
return;
}
// If collaboration is turned on, we won't know the file contents
if (file.content !== undefined) {
self.model.insertDocument(file.content);
self.cursorManager.moveCursor({ row: 0, col: 0 });
self.setFocus(true);
}
session.setProjectPath(project, filename);
if (options.line) {
commandLine.executeCommand('goto ' + options.line, true);
}
self._addHistoryItem(project, filename, fromFileHistory);
bespin.publish("editor:openfile:opensuccess", { project: project, file: file });
};
bespin.publish("editor:openfile:openbefore", { project: project, filename: filename });
bespin.get('files').editFile(project, filename, onSuccess, onFailure);
},
/**
* Manage the file history.
* TODO: The responsibility for managing history is split between here and
* session. It's not totally clear where it should live. Refactor.
*/
_addHistoryItem: function(project, filename, fromFileHistory) {
var settings = bespin.get("settings");
// Get the array of lastused files
var lastUsed = settings.getObject("_lastused");
if (!lastUsed) {
lastUsed = [];
}
// We want to add this to the top
var newItem = { project: project, filename: filename };
if (!fromFileHistory) {
bespin.get('editSession').addFileToHistory(newItem);
}
// Remove newItem from down in the list and place at top
var cleanLastUsed = [];
dojo.forEach(lastUsed, function(item) {
if (item.project != newItem.project || item.filename != newItem.filename) {
cleanLastUsed.unshift(item);
}
});
cleanLastUsed.unshift(newItem);
lastUsed = cleanLastUsed;
// Trim to 10 members
if (lastUsed.length > 10) {
lastUsed = lastUsed.slice(0, 10);
}
// Maybe this should have a _ prefix: but then it does not persist??
settings.setObject("_lastused", lastUsed);
}
});
/**
* If the debugger is reloaded, we need to make sure the module is in memory
* if we're in debug mode.
*/
bespin.subscribe("extension:loaded:bespin.debugger", function(ext) {
var settings = bespin.get("settings");
if (settings && settings.get("debugmode")) {
ext.load();
}
});
|
var Backbone = require('backbone'),
$ = require('jquery'),
Handlebars = require('handlebars'),
EntryForm = require('../forms/entryform'),
landingTemplate = require("../../templates/landing.hbs");
Backbone.$ = $;
/**
* Landing View
*/
var LandingView = Backbone.View.extend({
/**
* Template
* @type {Object}
*/
template: Handlebars.compile(landingTemplate),
/**
* [events description]
* @type {Object}
*/
events: {
'submit #entryform' : 'handleFormSubmit'
},
/**
* Handle form submit
* @param {Object} evt
* @return {undefined}
*/
handleFormSubmit: function(evt) {
var errors = EntryForm.commit();
evt.preventDefault();
if (!errors) {
var saveModel = EntryForm.model.save();
return this.redirectToSuccessPage();
}
this.handleFormErrors(errors);
},
/**
* Handle form errors
* @param {Object} errors
* @return {undefined}
*/
handleFormErrors: function(errors) {
$('.error-message').empty();
for (var key in errors) {
var errorContainer = $("#entryform").find("[data-editors='" + key + "']").next('.error-message');
if (errors.hasOwnProperty(key)) {
var messages = errors[key];
errorContainer.empty().text(messages.message);
}
}
},
/**
* Redirect to the success page
* @return {undefined}
*/
redirectToSuccessPage: function() {
Backbone.history.navigate('/success', { trigger: true });
return this;
},
/**
* [render description]
* @return {undefined}
*/
render: function() {
this.$el.html(this.template({ greeting: "Welcome to Backbone!" }));
this.$el.find('#form').html(EntryForm.render().el);
return this;
}
});
module.exports = LandingView; |
// We only stub on the client to prevent errors if putting in common code
Security.Rule = class {
constructor(types) {}
collections(collections) {
return this;
}
allowInClientCode() {}
allow() {
return true;
}
}
|
(function () {
$.mockjaxSettings.logging = 0; // only critical error messages
// persisted data
var frozenTrafficStatus = null;
// var maxConnections = (function() {
// var cache = [0, 1];
// return function(nodes) {
// if (!cache[nodes]) {
// for (var i = cache.length; i <= nodes; i++) {
// cache.push(cache[i - 1] * i);
// }
// }
// return cache[nodes];
// };
// })();
function getResponderWithFailureRate(url, urlParams, responseFunc, failureRate) {
return function(requestSettings) {
var service = requestSettings.url.match(url);
if (service) {
var mockDefinition = {
type: "GET",
url: url,
urlParams: urlParams,
contentType: "application/json"
};
if (Math.random() < failureRate) {
mockDefinition = _.assign(mockDefinition, {
status: 500,
response: "An Internal Server Error!!!"
});
} else {
mockDefinition = _.assign(mockDefinition, {
status: 200,
response: responseFunc
});
}
return mockDefinition;
}
return;
};
}
function getTrafficStatusResponse(startTime, endTime) {
var records = [],
constants = {
types: [
"type1",
"type2",
"type3",
"type4"
]
},
objects = [],
throughputUpperBound = 20000,
packetUpperBound = 1000,
totalObjs = _.random(10, 19), // 10 ~ 19 objects in total
remainingObjs = new Set(),
timeTag = "Generating Traffic Status Records";
for (var i = 0; i < totalObjs; i++) {
objects.push({
id: "obj" + (i + 1),
type: constants.types[_.random(4)]
});
remainingObjs.add("obj" + (i + 1));
}
var connections = new Set(),
totalRecords = _.random(100, 199); // 100 ~ 199 records
console.time(timeTag);
var i = 0, counter = 0, maxTrial = 600;
while (i < totalRecords && counter < maxTrial) {
var pair = _.sampleSize(objects, 2),
serialized = JSON.stringify(pair);
if (!connections.has(serialized)) {
records.push({
srcObj: pair[0].id,
srcType: pair[0].type,
destObj: pair[1].id,
destType: pair[1].type,
traffic: _.random(throughputUpperBound),
packets: _.random(packetUpperBound)
});
connections.add(serialized);
remainingObjs.delete(pair[0].id);
remainingObjs.delete(pair[1].id);
i++;
}
counter++;
}
if (i < totalRecords) {
console.warn(["A immature response generated! with", i, "records!!"].join(" "));
console.warn(["Attempted to generate a size of", totalRecords].join(" "));
}
console.timeEnd(timeTag);
remainingObjs.forEach(function(val) {
var pair = [_.find(objects, function(object) {
return object.id === val;
}), _.sample(_.filter(objects, function(object) {
return object.id !== val;
}))],
serialized = JSON.stringify(pair);
records.push({
srcObj: pair[0].id,
srcType: pair[0].type,
destObj: pair[1].id,
destType: pair[1].type,
traffic: _.random(throughputUpperBound),
packets: _.random(packetUpperBound)
});
connections.add(serialized);
});
remainingObjs.clear();
return {
header: {
time_range: {
start: new Date(startTime).toISOString(),
end: new Date(endTime).toISOString()
},
recordsCount: totalRecords
},
data: records
};
}
function logger(title, settings, response) {
console.info("\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/");
console.info("| Request URL", settings.url);
console.info("| ", title, response);
console.info("/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\");
}
var handler = getResponderWithFailureRate(
/^\/traffic_status\/?(?:(.*))$/,
["dataStatus"],
function(settings) {
if (!settings.urlParams.dataStatus
|| settings.urlParams.dataStatus !== "frozen") {
var st = new Date(),
et = new Date(st.getTime() + 10 * 1000);
this.responseText = getTrafficStatusResponse(st, et);
} else {
if (!frozenTrafficStatus) {
var st = new Date(),
et = new Date(st.getTime() + 10 * 1000);
frozenTrafficStatus = getTrafficStatusResponse(st, et);
}
this.responseText = frozenTrafficStatus;
}
logger("Traffic Status Response", settings, this.responseText);
},
0.2
);
$.mockjax(handler);
})();
|
import React from 'react';
const Single = React.createClass({
render() {
return (
<div className="single-quiz">
<h1>
Single Quiz Page
</h1>
</div>
)
}
});
export default Single;
|
(function (a) {
var userAggregate;
function userFactory (userJson) {
userJson = userJson || {};
var user_id = userJson.user_id || 0;
var uni_id = userJson.uni_id || 0;
var uni_name = userJson.uni_name || "";
var user_name = userJson.user_name || "";
var elem = $('<div style="display:none" class="record user">');
elem.append('<h4><a href="'+a.siteRoot+'user/'+user_id+'">'+user_name+'</a></h4>');
var img = a.util.loadEntityPic({type: 'users', id: user_id, style: 'medium', link: true});
elem.append(img);
elem.append('<div>Currently attending <a href="' + a.siteRoot + 'university/' + uni_id + '">' + uni_name + '</a></div>');
window.setTimeout(function () {
elem.fadeIn();
elem.addClass('loaded');
}, 100);
return elem;
}
pollUsers = function () {
var uni_id = a.scope.uni_id || 0;
var start = paginate.start;
var end = paginate.end;
userAggregate.addClass('loading');
a.getStudentList({uni_id: uni_id, start: start, end: end}, function (data) {
data = data || '[]';
data = JSON.parse(data);
if (data.fail) {
userAggregate.html('<p class="notice">There are no more students to view at your university at this time.</p>');
}
else {
userAggregate.html("");
}
paginatePrompt.text( 'Viewing ' + paginate.start + ' - ' + paginate.end);
userAggregate.removeClass('loading');
for (var i = 0; i < data.length; i++) {
var userJson = data[i];
userAggregate.append(userFactory(userJson));
}
});
};
var paginatePrompt;
var paginate = {
start: 0,
end: 9,
range: 10,
next: function () {
this.start += this.range;
this.end += this.range;
pollUsers();
},
prev: function () {
// don't go into negative pagination
if (this.start - this.range < 0) {
return;
}
else {
this.start -= this.range;
this.end -= this.range;
}
pollUsers();
},
set_range: function (range) {
this.range = range;
}
}
$(function () {
paginatePrompt = $('span.prompt.paginate');
userAggregate = $('div.view-all-users.aggregate.users')
pollUsers();
$('div.button.prev').click(function () {
paginate.prev();
});
$('div.button.next').click(function () {
paginate.next();
});
});
})(app);
|
var searchData=
[
['tuner_372',['Tuner',['../classktt_1_1_tuner.html',1,'ktt']]],
['tuningduration_373',['TuningDuration',['../classktt_1_1_tuning_duration.html',1,'ktt']]],
['tuningmanipulator_374',['TuningManipulator',['../classktt_1_1_tuning_manipulator.html',1,'ktt']]]
];
|
require('dotenv').config({silent: true});
const _ = require('underscore-plus');
const gulp = require('gulp');
const gutil = require('gulp-util');
const shell = require('shelljs');
const Client = require('ssh2').Client;
const fs = require('fs');
const os = require('os');
const path = require('path');
const decompress = require('decompress');
const request = require('request');
const del = require('del');
const runSequence = require('run-sequence');
const cp = require('./utils/child-process-wrapper');
const pkg = require('./package.json')
var buildBeta;
var buildDir = path.join(__dirname, 'build')
console.log('build directory', buildDir)
function productName() {
var name = 'Mastermind IDE';
if (buildBeta) {
name += ' Beta';
}
return name;
}
function executableName() {
var name = productName().toLowerCase();
return name.replace(/ /g, '_');
}
function windowsInstallerName() {
return productName().replace(/ /g, '') + 'Setup.exe';
}
gulp.task('default', ['ws:start']);
gulp.task('setup', function() {
shell.cp('./.env.example', './.env');
});
gulp.task('download-atom', function(done) {
var tarballURL = `https://github.com/atom/atom/archive/v${ pkg.atomVersion }.tar.gz`
console.log(`Downloading Atom from ${ tarballURL }`)
var tarballPath = path.join(buildDir, 'atom.tar.gz')
var r = request(tarballURL)
r.on('end', function() {
decompress(tarballPath, buildDir, {strip: 1}).then(function(files) {
fs.unlinkSync(tarballPath)
done()
}).catch(function(err) {
console.error(err)
})
})
r.pipe(fs.createWriteStream(tarballPath))
})
gulp.task('build-atom', function(done) {
process.chdir(buildDir)
var cmd = path.join(buildDir, 'script', 'build')
var args = []
switch (process.platform) {
case 'win32':
args.push('--create-windows-installer');
break;
case 'darwin':
args.push('--compress-artifacts');
args.push('--code-sign');
break;
case 'linux':
args.push('--create-rpm-package');
args.push('--create-debian-package');
break;
}
if (process.platform == 'win32') {
args = ['/s', '/c', cmd].concat(args);
cmd = 'cmd';
}
console.log('running command: ' + cmd + ' ' + args.join(' '))
cp.safeSpawn(cmd, args, function() {
done()
})
})
gulp.task('reset', function() {
del.sync(['build/**/*', '!build/.gitkeep'], {dot: true})
})
gulp.task('sleep', function(done) {
setTimeout(function() { done() }, 1000 * 60)
})
gulp.task('inject-packages', function() {
function rmPackage(name) {
var packageJSON = path.join(buildDir, 'package.json')
var packages = JSON.parse(fs.readFileSync(packageJSON))
delete packages.packageDependencies[name]
fs.writeFileSync(packageJSON, JSON.stringify(packages, null, ' '))
}
function injectPackage(name, version) {
var packageJSON = path.join(buildDir, 'package.json')
var packages = JSON.parse(fs.readFileSync(packageJSON))
packages.packageDependencies[name] = version
fs.writeFileSync(packageJSON, JSON.stringify(packages, null, ' '))
}
var pkg = require('./package.json')
rmPackage('welcome')
rmPackage('tree-view')
rmPackage('about')
injectPackage(pkg.name, pkg.version)
_.each(pkg.packageDependencies, (version, name) => {
injectPackage(name, version)
})
})
gulp.task('replace-files', function() {
var iconSrc = path.join('resources', 'app-icons', '**', '*');
var iconDest = path.join(buildDir, 'resources', 'app-icons', 'stable')
gulp.src([iconSrc]).pipe(gulp.dest(iconDest));
var winSrc = path.join('resources', 'win', '**', '*');
var winDest = path.join(buildDir, 'resources', 'win');
gulp.src([winSrc]).pipe(gulp.dest(winDest));
var scriptSrc = path.join('resources', 'script-replacements', '**', '*');
var scriptDest = path.join(buildDir, 'script', 'lib')
gulp.src([scriptSrc]).pipe(gulp.dest(scriptDest));
})
gulp.task('alter-files', function() {
function replaceInFile(filepath, replaceArgs) {
var data = fs.readFileSync(filepath, 'utf8');
replaceArgs.forEach(function(args) {
data = data.replace(args[0], args[1]);
});
fs.writeFileSync(filepath, data)
}
replaceInFile(path.join(buildDir, 'script', 'lib', 'create-windows-installer.js'), [
[
'https://raw.githubusercontent.com/atom/atom/master/resources/app-icons/${CONFIG.channel}/atom.ico',
'https://raw.githubusercontent.com/learn-co/learn-ide/master/resources/app-icons/atom.ico'
]
])
replaceInFile(path.join(buildDir, 'script', 'lib', 'create-rpm-package.js'), [
['atom.${generatedArch}.rpm', executableName() + '.${generatedArch}.rpm'],
[/'Atom Beta' : 'Atom'/g, "'" + productName() + "' : '" + productName() + "'"]
]);
replaceInFile(path.join(buildDir, 'script', 'lib', 'create-debian-package.js'), [
['atom-${arch}.deb', executableName() + '-${arch}.deb'],
[/'Atom Beta' : 'Atom'/g, "'" + productName() + "' : '" + productName() + "'"]
]);
replaceInFile(path.join(buildDir, 'script', 'lib', 'package-application.js'), [
[/'Atom Beta' : 'Atom'/g, "'" + productName() + "' : '" + productName() + "'"]
]);
replaceInFile(path.join(buildDir, 'script', 'lib', 'package-application.js'), [
[/'Atom'/g, `'${productName()}'`]
]);
if (process.platform != 'linux') {
replaceInFile(path.join(buildDir, 'script', 'lib', 'package-application.js'), [
[/return 'atom'/, "return '" + executableName() + "'"],
[/'atom-beta' : 'atom'/g, "'" + executableName() + "' : '" + executableName() + "'"]
]);
}
replaceInFile(path.join(buildDir, 'script', 'lib', 'compress-artifacts.js'), [
[/atom-/g, executableName() + '-']
]);
replaceInFile(path.join(buildDir, 'src', 'main-process', 'atom-application.coffee'), [
[
/options.socketPath = "\\\\\\\\.\\\\pipe\\\\atom-#{options.version}-#{userNameSafe}-#{process.arch}-sock"/,
'options.socketPath = "\\\\\\\\.\\\\pipe\\\\' + executableName() + '-#{options.version}-#{userNameSafe}-#{process.arch}-sock"'
],
[
'options.socketPath = path.join(os.tmpdir(), "atom-#{options.version}-#{process.env.USER}.sock")',
'options.socketPath = path.join(os.tmpdir(), "' + executableName() + '-#{options.version}-#{process.env.USER}.sock")'
]
]);
replaceInFile(path.join(buildDir, 'resources', 'mac', 'atom-Info.plist'), [
[
/(CFBundleURLSchemes.+\n.+\n.+)(atom)(.+)/,
'$1learn-ide$3'
]
]);
replaceInFile(path.join(buildDir, 'src', 'main-process', 'atom-protocol-handler.coffee'), [
[
/(registerFileProtocol.+)(atom)(.+)/,
'$1learn-ide$3'
]
]);
replaceInFile(path.join(buildDir, 'src', 'main-process', 'parse-command-line.js'), [
[
/(urlsToOpen.+)/,
"$1\n if (args['url-to-open']) { urlsToOpen.push(args['url-to-open']) }\n"
],
[
/(const args)/,
"options.string('url-to-open')\n $1"
]
]);
replaceInFile(path.join(buildDir, 'menus', 'darwin.cson'), [
[
"{ label: 'Check for Update', command: 'application:check-for-update', visible: false}",
"{ label: 'Check for Update', command: 'learn-ide:update-check'}"
],
[
"{ label: 'VERSION', enabled: false }\n { label: 'Restart and Install Update', command: 'application:install-update', visible: false}",
"{ label: 'View Version', command: 'learn-ide:view-version'}"
],
[/About Atom/, 'About'],
[/application:about/, 'learn-ide:about']
]);
replaceInFile(path.join(buildDir, 'menus', 'win32.cson'), [
[
"{ label: 'Check for Update', command: 'application:check-for-update', visible: false}",
"{ label: 'Check for Update', command: 'learn-ide:update-check'}"
],
[
"{ label: 'VERSION', enabled: false }\n { label: 'Restart and Install Update', command: 'application:install-update', visible: false}",
"{ label: 'View Version', command: 'learn-ide:view-version'}"
],
[
"\n { label: 'Checking for Update', enabled: false, visible: false}\n { label: 'Downloading Update', enabled: false, visible: false}",
''
],
[/About Atom/, 'About'],
[/application:about/, 'learn-ide:about']
]);
replaceInFile(path.join(buildDir, 'menus', 'linux.cson'), [
[/About Atom/, 'About'],
[
'{ label: "VERSION", enabled: false }',
"{ label: 'View Version', command: 'learn-ide:view-version'}"
],
[/application:about/, 'learn-ide:about']
]);
replaceInFile(path.join(buildDir, 'src', 'config-schema.js'), [
[
"automaticallyUpdate: {\n description: 'Automatically update Atom when a new release is available.',\n type: 'boolean',\n default: true\n }",
"automaticallyUpdate: {\n description: 'Automatically update Atom when a new release is available.',\n type: 'boolean',\n default: false\n }",
],
[
"openEmptyEditorOnStart: {\n description: 'When checked opens an untitled editor when loading a blank environment (such as with _File > New Window_ or when \"Restore Previous Windows On Start\" is unchecked); otherwise no editor is opened when loading a blank environment. This setting has no effect when restoring a previous state.',\n type: 'boolean',\n default: true",
"openEmptyEditorOnStart: {\n description: 'When checked opens an untitled editor when loading a blank environment (such as with _File > New Window_ or when \"Restore Previous Windows On Start\" is unchecked); otherwise no editor is opened when loading a blank environment. This setting has no effect when restoring a previous state.',\n type: 'boolean',\n default: false"
],
[
"restorePreviousWindowsOnStart: {\n description: 'When checked restores the last state of all Atom windows when started from the icon or `atom` by itself from the command line; otherwise a blank environment is loaded.',\n type: 'boolean',\n default: true",
"restorePreviousWindowsOnStart: {\n description: 'When checked restores the last state of all Atom windows when started from the icon or `atom` by itself from the command line; otherwise a blank environment is loaded.',\n type: 'boolean',\n default: false"
],
[
"['one-dark-ui', 'one-dark-syntax']", "['learn-ide-material-ui', 'atom-material-syntax']"
]
]);
})
gulp.task('update-package-json', function() {
var packageJSON = path.join(buildDir, 'package.json')
var atomPkg = JSON.parse(fs.readFileSync(packageJSON))
var learnPkg = require('./package.json')
atomPkg.name = executableName()
atomPkg.productName = productName()
atomPkg.version = learnPkg.version
atomPkg.description = learnPkg.description
fs.writeFileSync(packageJSON, JSON.stringify(atomPkg, null, ' '))
})
gulp.task('rename-installer', function(done) {
var src = path.join(buildDir, 'out', productName() + 'Setup.exe');
var des = path.join(buildDir, 'out', windowsInstallerName());
fs.rename(src, des, function (err) {
if (err) {
console.log('error while renaming: ', err.message)
}
done()
})
})
gulp.task('sign-installer', function() {
var certPath = process.env.FLATIRON_P12KEY_PATH;
var password = process.env.FLATIRON_P12KEY_PASSWORD;
if (!certPath || !password) {
console.log('unable to sign installer, must provide FLATIRON_P12KEY_PATH and FLATIRON_P12KEY_PASSWORD environment variables')
return
}
var cmd = path.join(buildDir, 'script', 'node_modules', 'electron-winstaller', 'vendor', 'signtool.exe')
var installer = path.join(buildDir, 'out', windowsInstallerName());
args = ['sign', '/a', '/f', certPath, '/p', "'" + password + "'", installer]
console.log('running command: ' + cmd + ' ' + args.join(' '))
cp.safeSpawn(cmd, args, function() {
done()
})
})
gulp.task('cleanup', function(done) {
switch (process.platform) {
case 'win32':
runSequence('rename-installer', 'sign-installer', done)
break;
case 'darwin':
done()
break;
case 'linux':
done()
break;
}
})
gulp.task('prep-build', function(done) {
runSequence(
'inject-packages',
'replace-files',
'alter-files',
'update-package-json',
done
)
})
gulp.task('build', function(done) {
var pkg = require('./package.json')
if (pkg.version.match(/beta/)) { buildBeta = true }
runSequence(
'reset',
'download-atom',
'prep-build',
'build-atom',
'cleanup',
done
)
})
gulp.task('mastermind', function(done) {
// update package.json
var pkg = require('./package.json')
pkg.name = 'mastermind'
pkg.description = 'The Learn IDE\'s evil twin that we use for testing'
pkg.packageDependencies['mirage'] = 'learn-co/mirage#master'
pkg.repository = pkg.repository.replace('learn-ide', 'mastermind')
delete pkg.packageDependencies['learn-ide-tree']
fs.writeFileSync('./package.json', JSON.stringify(pkg, null, ' '))
// update gulpfile
var gf = fs.readFileSync('./gulpfile.js', 'utf-8')
var updated = gf.replace('Learn IDE', 'Mastermind IDE')
fs.writeFileSync('./gulpfile.js', updated)
// update menus
var menu = fs.readFileSync('./menus/learn-ide.cson', 'utf-8')
var updated = menu.replace(/Learn IDE/g, 'Mastermind')
fs.writeFileSync('./menus/learn-ide.cson', updated)
})
|
module.exports = {
"key": "togepi",
"moves": [
{
"learn_type": "tutor",
"name": "covet"
},
{
"learn_type": "tutor",
"name": "hyper-voice"
},
{
"learn_type": "machine",
"name": "work-up"
},
{
"learn_type": "level up",
"level": 25,
"name": "bestow"
},
{
"learn_type": "machine",
"name": "incinerate"
},
{
"learn_type": "egg move",
"name": "stored-power"
},
{
"learn_type": "machine",
"name": "echoed-voice"
},
{
"learn_type": "machine",
"name": "round"
},
{
"learn_type": "level up",
"level": 53,
"name": "after-you"
},
{
"learn_type": "machine",
"name": "telekinesis"
},
{
"learn_type": "machine",
"name": "psyshock"
},
{
"learn_type": "egg move",
"name": "morning-sun"
},
{
"learn_type": "egg move",
"name": "extrasensory"
},
{
"learn_type": "tutor",
"name": "magic-coat"
},
{
"learn_type": "tutor",
"name": "heal-bell"
},
{
"learn_type": "tutor",
"name": "zen-headbutt"
},
{
"learn_type": "tutor",
"name": "signal-beam"
},
{
"learn_type": "tutor",
"name": "endeavor"
},
{
"learn_type": "tutor",
"name": "trick"
},
{
"learn_type": "tutor",
"name": "uproar"
},
{
"learn_type": "machine",
"name": "grass-knot"
},
{
"learn_type": "machine",
"name": "captivate"
},
{
"learn_type": "egg move",
"name": "nasty-plot"
},
{
"learn_type": "level up",
"level": 51,
"name": "last-resort"
},
{
"learn_type": "egg move",
"name": "lucky-chant"
},
{
"learn_type": "egg move",
"name": "psycho-shift"
},
{
"learn_type": "machine",
"name": "fling"
},
{
"learn_type": "machine",
"name": "natural-gift"
},
{
"learn_type": "level up",
"level": 21,
"name": "ancientpower"
},
{
"learn_type": "level up",
"level": 41,
"name": "baton-pass"
},
{
"learn_type": "tutor",
"name": "softboiled"
},
{
"learn_type": "tutor",
"name": "mimic"
},
{
"learn_type": "tutor",
"name": "thunder-wave"
},
{
"learn_type": "tutor",
"name": "seismic-toss"
},
{
"learn_type": "tutor",
"name": "counter"
},
{
"learn_type": "tutor",
"name": "body-slam"
},
{
"learn_type": "tutor",
"name": "mega-kick"
},
{
"learn_type": "tutor",
"name": "mega-punch"
},
{
"learn_type": "machine",
"name": "water-pulse"
},
{
"learn_type": "machine",
"name": "shock-wave"
},
{
"learn_type": "machine",
"name": "secret-power"
},
{
"learn_type": "level up",
"level": 16,
"name": "yawn"
},
{
"learn_type": "level up",
"level": 31,
"name": "wish"
},
{
"learn_type": "level up",
"level": 26,
"name": "follow-me"
},
{
"learn_type": "machine",
"name": "facade"
},
{
"learn_type": "egg move",
"name": "substitute"
},
{
"learn_type": "machine",
"name": "reflect"
},
{
"learn_type": "machine",
"name": "light-screen"
},
{
"learn_type": "tutor",
"name": "flamethrower"
},
{
"learn_type": "machine",
"name": "rock-smash"
},
{
"learn_type": "egg move",
"name": "future-sight"
},
{
"learn_type": "machine",
"name": "shadow-ball"
},
{
"learn_type": "machine",
"name": "psych-up"
},
{
"learn_type": "machine",
"name": "sunny-day"
},
{
"learn_type": "machine",
"name": "rain-dance"
},
{
"learn_type": "machine",
"name": "hidden-power"
},
{
"learn_type": "level up",
"level": 25,
"name": "encore"
},
{
"learn_type": "level up",
"level": 31,
"name": "safeguard"
},
{
"learn_type": "machine",
"name": "frustration"
},
{
"learn_type": "egg move",
"name": "present"
},
{
"learn_type": "machine",
"name": "return"
},
{
"learn_type": "machine",
"name": "sleep-talk"
},
{
"learn_type": "machine",
"name": "attract"
},
{
"learn_type": "machine",
"name": "swagger"
},
{
"learn_type": "machine",
"name": "rollout"
},
{
"learn_type": "level up",
"level": 1,
"name": "charm"
},
{
"learn_type": "machine",
"name": "endure"
},
{
"learn_type": "machine",
"name": "detect"
},
{
"learn_type": "egg move",
"name": "foresight"
},
{
"learn_type": "machine",
"name": "zap-cannon"
},
{
"learn_type": "machine",
"name": "mud-slap"
},
{
"learn_type": "level up",
"level": 18,
"name": "sweet-kiss"
},
{
"learn_type": "machine",
"name": "protect"
},
{
"learn_type": "machine",
"name": "curse"
},
{
"learn_type": "machine",
"name": "snore"
},
{
"learn_type": "machine",
"name": "rest"
},
{
"learn_type": "machine",
"name": "flash"
},
{
"learn_type": "machine",
"name": "dream-eater"
},
{
"learn_type": "machine",
"name": "swift"
},
{
"learn_type": "machine",
"name": "fire-blast"
},
{
"learn_type": "egg move",
"name": "mirror-move"
},
{
"learn_type": "level up",
"level": 7,
"name": "metronome"
},
{
"learn_type": "machine",
"name": "defense-curl"
},
{
"learn_type": "machine",
"name": "double-team"
},
{
"learn_type": "machine",
"name": "psychic"
},
{
"learn_type": "machine",
"name": "toxic"
},
{
"learn_type": "machine",
"name": "solarbeam"
},
{
"learn_type": "egg move",
"name": "peck"
},
{
"learn_type": "level up",
"level": 1,
"name": "growl"
},
{
"learn_type": "level up",
"level": 38,
"name": "double-edge"
},
{
"learn_type": "machine",
"name": "headbutt"
}
]
}; |
var gulp = require('gulp');
var sass = require('gulp-sass');
var concat = require('gulp-concat-util');
// var replace = require('gulp-replace');
var tap = require('gulp-tap');
var path = require('path');
var polymer = '../bower_components/polymer/polymer.html';
gulp.task('default', ['css-index-compile', 'css-compile']);
function setToCorrectFontPath(file) {
file.contents = new Buffer(String(file.contents)
.replace(/url\('/g, "url('/fonts" + file.path.replace(/.*\/fonts/g, '').replace(new RegExp(path.posix.basename(file.path)), ''))
);
}
// ### Custom tasks
// Take all the fontcss stylesheets and concat them into a single SCSS file
gulp.task ('font-css', function() {
return gulp.src(['fonts/**/stylesheet.css']) //Gather up all the 'stylesheet.css' files
.pipe(tap(setToCorrectFontPath))
.pipe(concat('main.scss')) //Concat them all into a single file
.pipe(concat.header('/* !!! WARNING !!! \nThis file is auto-generated. \nDo not edit it or else you will lose changes next time you compile! */\n\n'))
.pipe(gulp.dest('src/sass/fonts/')); // Put them in the assets/styles/components folder
});
gulp.task('css-index-compile', ['font-css'], function() {
return gulp.src('src/sass/index.scss')
.pipe(sass().on('error', sass.logError))
.pipe(concat('index.css'))
.pipe(gulp.dest('src/'));
});
gulp.task('css-compile', function() {
return gulp.src('src/sass/core-styles.scss')
.pipe(sass().on('error', sass.logError))
.pipe(concat('core-styles.html'))
.pipe(concat.header('<link rel="import" href="' + polymer + '">\n\n<dom-module id="core-styles">\n<template>\n<style>\n'))
.pipe(concat.footer('\n</style>\n</template>\n</dom-module>'))
.pipe(gulp.dest('src/'));
});
var fontWatcher = gulp.watch(['fonts/**/*', 'src/sass/base/*'], ['css-index-compile']);
fontWatcher.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});
var watcher = gulp.watch(['src/sass/**/*'], ['css-compile']);
watcher.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
}); |
import './styles/base.less';
import {Confirm, Alert, Toast, Notify, Loading} from './components/dialog';
import {Layout} from './components/layout';
import {Button, ButtonGroup} from './components/button';
import {NavBar, NavBarBackIcon, NavBarNextIcon} from './components/navbar';
import {CellItem, CellGroup} from './components/cell';
import {Switch} from './components/switch';
import {GridsItem, GridsGroup} from './components/grids';
import {Icons} from './components/icons';
import {ListTheme, ListItem, ListOther} from './components/list';
import {InfiniteScroll} from './components/infinitescroll';
import {PullRefresh} from './components/pullrefresh';
import {Badge, BadgeRadius} from './components/badge';
import {TabBar, TabBarItem, TabBarOther} from './components/tabbar';
import {Tab, TabPanel} from './components/tab';
import {ScrollTab, ScrollTabPanel} from './components/scrolltab';
import {ActionSheet} from './components/actionsheet';
import {SendCode} from './components/sendcode';
import {KeyBoard} from './components/keyboard';
import {Slider, SliderItem} from './components/slider';
import {Spinner} from './components/spinner';
import {CitySelect} from './components/cityselect';
import {ProgressBar} from './components/progressbar';
import {CountDown} from './components/countdown';
import {Rate} from './components/rate';
import {TextArea} from './components/textarea';
import {Popup} from './components/popup';
import {CountUp} from './components/countup';
import {RollNotice, RollNoticeItem} from './components/rollnotice';
import {Input} from './components/input';
import {FlexBox, FlexBoxItem} from './components/flexbox';
import {Radio, RadioGroup} from './components/radio';
import {CheckBox, CheckBoxGroup} from './components/checkbox';
import {BackTop} from './components/backtop';
import {Accordion, AccordionItem} from './components/accordion';
import {DateTime} from './components/datetime';
import {LightBox, LightBoxImg, LightBoxTxt} from './components/lightbox';
import {TimeLine, TimeLineItem} from './components/timeline';
import {Step, StepItem} from './components/step';
import {CheckList, CheckListItem} from './components/checklist';
import {Search} from './components/search';
import {ScrollNav, ScrollNavPanel} from './components/scrollnav';
import {Preview, PreviewHeader, PreviewItem} from './components/preview';
window.document.addEventListener('touchstart', function (event) {
/* Do Nothing */
}, false);
const install = function (Vue) {
Vue.component(Layout.name, Layout);
Vue.component(Button.name, Button);
Vue.component(ButtonGroup.name, ButtonGroup);
Vue.component(NavBar.name, NavBar);
Vue.component(NavBarBackIcon.name, NavBarBackIcon);
Vue.component(NavBarNextIcon.name, NavBarNextIcon);
Vue.component(CellGroup.name, CellGroup);
Vue.component(CellItem.name, CellItem);
Vue.component(Switch.name, Switch);
Vue.component(GridsItem.name, GridsItem);
Vue.component(GridsGroup.name, GridsGroup);
Vue.component(Icons.name, Icons);
Vue.component(ListTheme.name, ListTheme);
Vue.component(ListItem.name, ListItem);
Vue.component(ListOther.name, ListOther);
Vue.component(InfiniteScroll.name, InfiniteScroll);
Vue.component(PullRefresh.name, PullRefresh);
Vue.component(Badge.name, Badge);
Vue.component(TabBar.name, TabBar);
Vue.component(TabBarItem.name, TabBarItem);
Vue.component(TabBarOther.name, TabBarOther);
Vue.component(Tab.name, Tab);
Vue.component(TabPanel.name, TabPanel);
Vue.component(ScrollTab.name, ScrollTab);
Vue.component(ScrollTabPanel.name, ScrollTabPanel);
Vue.component(ActionSheet.name, ActionSheet);
Vue.component(SendCode.name, SendCode);
Vue.component(KeyBoard.name, KeyBoard);
Vue.component(Slider.name, Slider);
Vue.component(SliderItem.name, SliderItem);
Vue.component(Spinner.name, Spinner);
Vue.component(CitySelect.name, CitySelect);
Vue.component(ProgressBar.name, ProgressBar);
Vue.component(CountDown.name, CountDown);
Vue.component(Rate.name, Rate);
Vue.component(TextArea.name, TextArea);
Vue.component(Popup.name, Popup);
Vue.component(CountUp.name, CountUp);
Vue.component(RollNotice.name, RollNotice);
Vue.component(RollNoticeItem.name, RollNoticeItem);
Vue.component(Input.name, Input);
Vue.component(FlexBox.name, FlexBox);
Vue.component(FlexBoxItem.name, FlexBoxItem);
Vue.component(Radio.name, Radio);
Vue.component(RadioGroup.name, RadioGroup);
Vue.component(CheckBox.name, CheckBox);
Vue.component(CheckBoxGroup.name, CheckBoxGroup);
Vue.component(BackTop.name, BackTop);
Vue.component(Accordion.name, Accordion);
Vue.component(AccordionItem.name, AccordionItem);
Vue.component(DateTime.name, DateTime);
Vue.component(LightBox.name, LightBox);
Vue.component(LightBoxImg.name, LightBoxImg);
Vue.component(LightBoxTxt.name, LightBoxTxt);
Vue.component(TimeLine.name, TimeLine);
Vue.component(TimeLineItem.name, TimeLineItem);
Vue.component(Step.name, Step);
Vue.component(StepItem.name, StepItem);
Vue.component(CheckList.name, CheckList);
Vue.component(CheckListItem.name, CheckListItem);
Vue.component(Search.name, Search);
Vue.component(ScrollNav.name, ScrollNav);
Vue.component(ScrollNavPanel.name, ScrollNavPanel);
Vue.component(Preview.name, Preview);
Vue.component(PreviewHeader.name, PreviewHeader);
Vue.component(PreviewItem.name, PreviewItem);
Vue.prototype.$dialog = {
confirm: Confirm,
alert: Alert,
toast: Toast,
notify: Notify,
loading: Loading,
};
};
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
export default {
install
};
|
function inherittingToString() {
class Person {
constructor(name, email) {
this.name = name
this.email = email
}
toString() {
let className = this.constructor.name
return `${className} (name: ${this.name}, email: ${this.email})`
}
}
class Teacher extends Person {
constructor(name, email, subject) {
super(name, email)
this.subject = subject
}
toString() {
let className = this.constructor.name
return `${className} (name: ${this.name}, email: ${this.email}, subject: ${this.subject})`
}
}
class Student extends Person {
constructor(name, email, course) {
super(name, email)
this.course = course
}
toString() {
let className = this.constructor.name
return `${className} (name: ${this.name}, email: ${this.email}, course: ${this.course})`
}
}
return {
Person,
Teacher,
Student
}
}
console.log(inherittingToString())
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* throttle.
*
* @param {Function} The throttle function.
* @param {Number} The delay time.
* @param {Number} The minimum interval time.
* @returns {Function} Returns the throttle function.
*/
var throttle = function throttle(fn, delay, mustRunDelay) {
var timer = null;
var t_start = void 0;
return function () {
var context = this,
args = arguments,
t_curr = +new Date();
clearTimeout(timer);
if (!t_start) {
t_start = t_curr;
}
if (t_curr - t_start >= mustRunDelay) {
fn.apply(context, args);
t_start = t_curr;
} else {
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
}
};
};
exports.default = throttle; |
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-06-04 using
// generator-karma 1.0.0
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
// as well as any additional frameworks (requirejs/chai/sinon/...)
frameworks: [
"jasmine"
],
// list of files / patterns to load in the browser
files: [
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/bootstrap/dist/js/bootstrap.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/highlightjs/highlight.pack.js',
'bower_components/angular-mocks/angular-mocks.js',
// endbower
"app/scripts/**/*.js",
"test/mock/**/*.js",
"test/spec/**/*.js"
],
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
"PhantomJS"
],
// Which plugins to enable
plugins: [
"karma-phantomjs-launcher",
"karma-jasmine"
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
|
'use strict';
// Tasks controller
angular.module('tasks').controller('TasksController', ['$scope', '$stateParams', 'Projects', 'Users', 'Teams', '$location', 'Authentication', 'Tasks', '$modal', '$log', '$state',
function($scope, $stateParams, Projects, Users, Teams, $location, Authentication, Tasks, $modal, $log, $state) {
$scope.authentication = Authentication;
//dropdown init
angular.element('select').select2({
width: '100%'
});
$scope.usersForSearch = [];
//Open Modal window for creating tasks
$scope.createModal = function (size) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modules/tasks/views/create-task.client.view.html',
controller: function ($scope, $modalInstance, items) {
console.log('In Modal Controller');
$scope.ok = function () {
//$scope.selected.event
modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
size: size,
resolve: {
items: function () {
//return $scope.events;
}
}
});
//modalInstance.opened.then($scope.initModal);
modalInstance.result.then(function (selectedEvent) {
$scope.selected = selectedEvent;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
//Open Modal window for creating tasks
$scope.taskForProjectModal = function (size) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modules/tasks/views/create-task-proj.client.view.html',
controller: function ($scope, $modalInstance, items) {
console.log('In Modal Controller');
$scope.ok = function () {
//$scope.selected.event
modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
size: size,
resolve: {
items: function () {
//return $scope.events;
}
}
});
//modalInstance.opened.then($scope.initModal);
modalInstance.result.then(function (selectedEvent) {
$scope.selected = selectedEvent;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
//Open Modal window for creating tasks
$scope.taskForTeamModal = function (size) {
$stateParams.projectId = $scope.team.project._id;
console.log("Proj ID: " + $scope.project);
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modules/tasks/views/create-task-proj.client.view.html',
controller: function ($scope, $modalInstance, items) {
console.log('In Modal Controller');
$scope.ok = function () {
//$scope.selected.event
modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
size: size,
resolve: {
items: function () {
//return $scope.events;
}
}
});
//modalInstance.opened.then($scope.initModal);
modalInstance.result.then(function (selectedEvent) {
$scope.selected = selectedEvent;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
//Open Modal window for creating subtasks
$scope.createSubtaskModal = function (size) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modules/tasks/views/create-subtask.client.view.html',
controller: function ($scope, $modalInstance, items) {
console.log('In Modal Controller');
$scope.ok = function () {
//$scope.selected.event
modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
size: size,
resolve: {
items: function () {
//return $scope.events;
}
}
});
//modalInstance.opened.then($scope.initModal);
modalInstance.result.then(function (selectedEvent) {
$scope.selected = selectedEvent;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
//Open Modal window for updating status of a Task
$scope.updateTaskStatus = function (size) {
var modalInstance = $modal.open({
animation: $scope.animationsEnabled,
templateUrl: 'modules/tasks/views/update-status.client.view.html',
controller: function ($scope, $modalInstance, items) {
console.log('In Modal Controller');
$scope.ok = function () {
//$scope.selected.event
modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
},
size: size,
resolve: {
items: function () {
//return $scope.events;
}
}
});
//modalInstance.opened.then($scope.initModal);
modalInstance.result.then(function (selectedEvent) {
$scope.selected = selectedEvent;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
// Create new Task
$scope.create = function() {
// Create new Task object
var task = new Tasks ({
name: this.name,
owners: {
users: this.user_owner,
team: this.team_owner
},
workers: {
users: this.user_assigned,
team: this.team_assigned
},
project: this.project,
deadline: this.deadline,
description: this.description,
parTask: null
});
// Redirect after save
task.$save(function(response) {
$location.path('tasks/' + response._id);
$scope.ok();
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Create new Subtask
$scope.createSubtask = function() {
// Create new Task object
var task = new Tasks ({
name: this.name,
owners: {
users: this.user_owner,
team: this.team_owner
},
workers: {
users: this.user_assigned,
team: this.team_assigned
},
deadline: this.deadline,
description: this.description,
parTask: $stateParams.taskId
});
// Redirect after save
task.$save(function(response) {
$location.path('tasks/' + response._id);
$scope.ok();
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Create new Task for current Project
$scope.createProjTask = function() {
// Create new Task object
var task = new Tasks ({
name: this.name,
owners: {
users: this.user_owner,
team: this.team_owner
},
workers: {
users: this.user_assigned,
team: this.team_assigned
},
project: $stateParams.projectId,
deadline: this.deadline,
description: this.description,
parTask: null
});
// Redirect after save
task.$save(function(response) {
$location.path('tasks/' + response._id);
$scope.ok();
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.updateParTask = function() {
$scope.parentTask = $scope.task._id;
}
// Remove existing Task
$scope.remove = function(task) {
if ( task ) {
task.$remove();
for (var i in $scope.tasks) {
if ($scope.tasks [i] === task) {
$scope.tasks.splice(i, 1);
}
}
} else {
$scope.task.$remove(function() {
$location.path('tasks');
});
}
};
// Update existing Task
$scope.update = function() {
var task = $scope.task;
task.$update(function() {
$location.path('tasks/' + task._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Tasks
$scope.find = function() {
$scope.tasks = Tasks.query();
};
// Find existing Task
$scope.findOne = function() {
$scope.task = Tasks.get({
taskId: $stateParams.taskId
}, $scope.initStuff);
};
$scope.initStuff = function() {
$scope.updateStatus();
}
//Find a list of Projects
$scope.findProjects = function() {
var response = Projects.query();
$scope.projects = response;
};
//Find a list of Teams
$scope.findTeams = function() {
var response = Teams.query();
$scope.teams = response;
};
//Find a list of Users
$scope.findUsers = function() {
var response = Users.query();
$scope.users= response;
};
$scope.setProject = function() {
$scope.task = Tasks.get({
taskId: $stateParams.taskId
}, $scope.setProject2);
}
$scope.setProjectFromProject = function() {
console.log("PROJECT: " + $stateParams.projectId);
$scope.project = $stateParams.projectId;
//If currently on a Team page
if ($stateParams.teamId) {
$scope.stateTeamId = $stateParams.teamId;
console.log("StateTeamId: " + $scope.stateTeamId);
}
}
$scope.setProject2 = function() {
$scope.project = $scope.task.project._id;
}
// Filters
$scope.projectFilter = function(element) {
var filter = true;
if (element.project._id != $scope.project) {
filter = false;
}
return filter;
}
$scope.notOwnerUsers = function(element) {
var filter = true;
if (($scope.user_owner) && (-1 != $scope.user_owner.indexOf(element._id))) {
filter = false;
}
return filter;
}
$scope.notOwnerTeam = function(element) {
var filter = true;
if (element._id == $scope.team_owner) {
filter = false;
}
return filter;
}
$scope.notWorkerUsers = function(element) {
var filter = true;
if (($scope.user_assigned) && (-1 != $scope.user_assigned.indexOf(element._id))) {
filter = false;
}
return filter;
}
$scope.notWorkerTeam = function(element) {
var filter = true;
if (element._id == $scope.team_assigned) {
filter = false;
}
return filter;
}
// DATEPICKER CONFIG
$scope.datepickers = {
earliest: false,
latest: false
};
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$scope.clear = function () {
$scope.dt = null;
};
$scope.toggleMin = function() {
$scope.minDate = $scope.minDate ? null : new Date();
};
$scope.toggleMin();
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
$scope.open1 = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened1 = true;
};
$scope.openWhich = function($event, which) {
$event.preventDefault();
$event.stopPropagation();
for(var datepicker in $scope.datepickers)
{
datepicker = false;
}
$scope.datepickers[which]= true;
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 0,
showWeeks: false
};
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[3];
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 2);
$scope.events =
[
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}
];
$scope.getDayClass = function(date, mode) {
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0,0,0,0);
for (var i=0;i<$scope.events.length;i++){
var currentDay = new Date($scope.events[i].date).setHours(0,0,0,0);
if (dayToCheck === currentDay) {
return $scope.events[i].status;
}
}
}
return '';
};
//Progress Bar
$scope.max = 100;
$scope.random = function() {
var value = Math.floor((Math.random() * 100) + 1);
var type;
if (value < 25) {
type = 'success';
} else if (value < 50) {
type = 'info';
} else if (value < 75) {
type = 'warning';
} else {
type = 'danger';
}
$scope.showWarning = (type === 'danger' || type === 'warning');
$scope.dynamic = value;
$scope.type = type;
};
//$scope.random();
$scope.randomStacked = function() {
$scope.stacked = [];
var types = ['success', 'info', 'warning', 'danger'];
for (var i = 0, n = Math.floor((Math.random() * 4) + 1); i < n; i++) {
var index = Math.floor((Math.random() * 4));
$scope.stacked.push({
value: Math.floor((Math.random() * 30) + 1),
type: types[index]
});
}
};
$scope.randomStacked();
$scope.displayStatus;
$scope.updateStatus = function() {
switch($scope.task.status) {
case "not started":
$scope.displayStatus = "Not Started";
$scope.dynamic = 0;
$scope.type = "warning";
break;
case "in progress":
$scope.displayStatus = "In Progress";
$scope.dynamic = 50;
$scope.type = "info";
break;
case "finished":
$scope.displayStatus = "Finished";
$scope.dynamic = 100;
$scope.type = "success";
break;
case "blocked":
$scope.displayStatus = "Blocked";
$scope.dynamic = 50;
$scope.type = "danger";
break;
}
}
$scope.sendUpateStatus = function(status) {
$scope.task = Tasks.update({
_id: $stateParams.taskId,
status: status
});
$scope.ok();
$scope.updateStatus();
$state.go($state.current.name, $state.params, { reload: true });
};
$scope.getValue = function(status) {
switch(status) {
case "not started":
return 0;
case "in progress":
return 50;
case "finished":
return 100;
case "blocked":
return 50;
}
}
$scope.getType = function(status) {
switch(status) {
case "not started":
return "warning";
case "in progress":
return "info";
case "finished":
return "success";
case "blocked":
return "danger";
}
}
//FILTERS
$scope.userSearch = function(element) {
if ($scope.usersForSearch.length > 0) {
for (var j = 0; j < $scope.usersForSearch.length; j++) {
if (!($scope.checkMembership($scope.usersForSearch[j], element.owners.users) ||
$scope.checkMembership($scope.usersForSearch[j], element.workers.users))) {
return false;
}
}
return true;
} else {
//Search box is empty
return true;
}
}
$scope.searchNameText = function(element) {
if ($scope.nameSearchText == "" || !$scope.nameSearchText) {
return true;
} else if (element.name.toLowerCase().contains($scope.nameSearchText.toLowerCase())){
return true;
} else {
return false;
}
}
$scope.projectSearch = function(element) {
if ($scope.projectForSearch == "" || $scope.projectForSearch == "Any" || !$scope.projectForSearch) {
return true;
} else if (element.project._id == $scope.projectForSearch) {
return true;
} else {
return false;
}
}
$scope.statusSearch = function(element) {
if ($scope.statusForSearch == "" || $scope.statusForSearch == "Any" || !$scope.statusForSearch) {
return true;
} else if (element.status == $scope.statusForSearch) {
return true;
} else {
return false;
}
}
$scope.checkMembership = function(userId, users) {
for (var i = 0; i < users.length; i++) {
//If user is found on the team, we're good
if (users[i].user._id == userId) {
return "notFalse";
}
}
//A user was not found on a team, stop
return false;
}
}
]); |
/*!
* @author Steven Masala [me@smasala.com]
*/
/**
* @module Firebrick.ui.components
* @extends components.fields.Input
* @namespace components.fields
* @class Email
*/
define( [ "./Input" ], function() {
"use strict";
return Firebrick.define( "Firebrick.ui.fields.Email", {
extend: "Firebrick.ui.fields.Input",
/**
* @property sName
* @type {String}
*/
sName: "fields.email",
/**
* @property type
* @type {String}
* @default "'email'"
*/
type: "email",
/**
* @property dataType
* @type {String}
* @default "'text'"
*/
dataType: "text"
});
});
|
var path = require('path');
var filename = path.basename(__filename);
var expect = require('expect.js');
var test_id = Date.now() + '_' + require('shortid').generate();
var Mesh = require('../');
describe(filename, function () {
require('chai').should();
this.timeout(10000);
var mesh1;
var mesh2;
var client1;
var client2;
//require('benchmarket').start();
//after(//require('benchmarket').store());
before(function (done) {
startMesh(8880, function (err, mesh) {
if (err) return done(err);
mesh1 = mesh;
mesh1.exchange.data.set('testval', {val: 1}, done);
})
});
before(function (done) {
startMesh(8881, function (err, mesh) {
if (err) return done(err);
mesh2 = mesh;
mesh2.exchange.data.set('testval', {val: 2}, done);
})
});
before(function (done) {
client1 = new Mesh.MeshClient({
secure: true,
port: 8880
});
client1
.login({username: '_ADMIN', password: test_id})
.then(done)
.catch(done);
});
before(function (done) {
client2 = new Mesh.MeshClient({
secure: true,
port: 8881
});
client2
.login({username: '_ADMIN', password: test_id})
.then(done)
.catch(done);
});
after(function(){
if (mesh1) return mesh1.stop();
});
after(function(){
if (mesh2) return mesh2.stop();
});
it('client2 works after client1 disconnects', function (done) {
var val1;
var val2;
client1.exchange.data.get('testval', function (err, data) {
if (err) return done(err);
val1 = data.val;
client1.disconnect(function () {
client2.exchange.data.get('testval', function (err, data) {
val2 = data.val;
val1.should.eql(1);
val2.should.eql(2);
done();
})
})
})
});
//require('benchmarket').stop();
});
function startMesh(port, callback) {
Mesh.create({
name: filename + '-' + port,
datalayer: {
secure: true,
adminPassword: test_id,
port: port
},
components: {
'data': {}
}
},
callback);
}
|
/**
* Module dependencies.
*/
var express = require('express');
var views = require('./api/controllers/ViewController.js');
var user = require('./api/controllers/UserController.js');
var auth = require('./api/controllers/AuthController.js');
var reference = require('./api/controllers/ReferenceController.js');
var linkedin = require('./api/controllers/LinkedInController.js');
var Users = require('./api/models/Users.js').Users;
var http = require('http');
var path = require('path');
var flash = require('connect-flash');
var secrets = require('./secrets.js');
var swig = require('swig');
swig.setDefaults({ cache: false });
var mongoose = require('mongoose');
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'goodwords',
api_key: secrets.cloudinary.api_key,
api_secret: secrets.cloudinary.api_secret
});
var bcrypt = require('bcrypt-nodejs');
var passport = require('passport')
, LocalStrategy = require('passport-local').Strategy;
var app = express();
app.engine("html", swig.renderFile);
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.cookieParser(secrets.cookieSecret));
app.use(express.session({ cookie: { maxAge: 60000 }, secret:secrets.sessionSecret}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.use(flash());
passport.use(new LocalStrategy(
function(username, password, done) {
Users.findOne({ username: username }, function (err, user) {
if (err) {
console.error('Error in new LocalStrategy: '+JSON.stringify(err));
return done(err);
}
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!bcrypt.compareSync(password,user.password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
Users.findById(id, function(err, user) {
if (err){
console.error('Error in deserializeUser: '+JSON.stringify(err));
done(err, user);
} else {
done(null, user);
}
});
});
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
var connectToMongo = function(host){
mongoose.connect(host);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
console.info('~ Connected to '+host+'.');
});
};
connectToMongo(process.env.MONGOSOUP_URL || 'mongodb://localhost/goodWords');
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', views.index);
app.post('/users/create', user.create);
app.post('/login',
passport.authenticate('local',{failureRedirect:'/#/login'}),
auth.login);
app.get('/logout', auth.logout);
app.get('/users/find', user.find);
app.post('/users/update', user.update);
app.get('/references/find', reference.find);
app.post('/references/create',reference.create);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
var maxolotl = {
species: "Ambystoma mexicanum",
cute: true,
age: 5,
bump: function() {console.log("Bump!")}
}
maxolotl.bump() |
export default class Example {
/* stamp constructor */
constructor() {
}
/* endstamp */
/* ph properties */
get name () {
return this.name;
}
/* endph */
oldMethod() {}
}
|
import EmberObject, { get } from '@ember/object';
import { isBlank } from '@ember/utils';
export default EmberObject.extend({
validate(value, validator) {
if (isBlank(value)) { return; }
let [regex] = get(validator, 'arguments');
if(!regex.test(value)) {
return 'mustMatchRegex';
}
}
});
|
var assert = require('assert')
var flagon = require('../index.es6.js')
var permission = {
NOTHING: 0b0000,
READ: 0b0001,
CREATE: 0b0010,
MODIFY: 0b0100,
DELETE: 0b1000
}
var GUEST = permission.READ
var USER = flagon.merge(permission.READ, permission.MODIFY)
var ADMIN = flagon.merge(USER, permission.CREATE)
var SUPERUSER = flagon.merge(ADMIN, permission.DELETE)
var SUPER_GUEST = flagon.toggle(GUEST, permission.DELETE)
describe('flagon', () => {
it('should merge bit masks', () =>
assert.equal(USER, permission.READ | permission.MODIFY)
)
it('should check if a bitmask contains another bitmask', () => {
assert( flagon.contains(SUPERUSER, ADMIN))
assert.equal( flagon.contains(ADMIN, SUPERUSER), false )
assert( flagon.contains(ADMIN, GUEST))
})
it('should toggle flags in a bit mask that differ from a second bitmask', () => {
assert(flagon.contains(SUPER_GUEST, permission.DELETE))
assert.equal(flagon.toggle(SUPER_GUEST, permission.DELETE), GUEST)
})
it('should be able to chain contains,merge,toggle', () => {
var DELETE_BUT_NOT_READ = flagon(USER)
.merge(permission.DELETE)
.toggle(permission.READ)
assert.equal(
DELETE_BUT_NOT_READ.contains(permission.READ),
false
)
assert(
DELETE_BUT_NOT_READ.contains(permission.DELETE)
)
})
it('flagon.contains should always return true if the second argument is 0', () => {
assert(
flagon.contains(1, 0)
)
assert(
flagon.contains(0, 0)
)
})
}) |
export default function(a, b) {
const alast = a.lastOpened || a.id;
const blast = b.lastOpened || b.id;
if (alast < blast) {
return 1;
} else if (alast > blast) {
return -1;
}
return 0;
}
|
'use strict';
angular.module('trackingSystem.users.register', [])
.controller('RegisterFormController', [
'$scope',
'$route',
'authentication',
'notifier',
function ($scope, $route, authentication, notifier) {
$scope.register = function (user) {
var loginUser = {email: user.email, password: user.password};
authentication.signup(user)
.then(function () {
notifier.success('Register Successful.');
authentication.login(loginUser);
$route.reload();
})
};
}]); |
version https://git-lfs.github.com/spec/v1
oid sha256:e5b76ca20be03019cd59ae9089264950134c967f586267a6f29a2a14922b39d7
size 15793
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createError = createError;
var errors = new Map([[-32000, "Event not provided"], [-32600, "Invalid Request"], [-32601, "Method not found"], [-32602, "Invalid params"], [-32603, "Internal error"], [-32604, "Params not found"], [-32605, "Method forbidden"], [-32700, "Parse error"]]);
/**
* Creates a JSON-RPC 2.0-compliant error.
* @param {Number} code - error code
* @param {String} details - error details
* @return {Object}
*/
function createError(code, details) {
var error = {
code: code,
message: errors.get(code) || "Internal Server Error"
};
if (details) error["data"] = details;
return error;
} |
import { expect } from 'chai'
import getType from './getType'
import isImmutable from './isImmutable'
export default function expectAllExactEqual(data, result, expected) {
expect(result).to.equal(data)
expect(getType(data)).to.equal(getType(expected))
expect(getType(result)).to.equal(getType(expected))
if (isImmutable(expected)) {
expect(data.toJS()).to.deep.equal(expected.toJS())
expect(result.toJS()).to.deep.equal(expected.toJS())
} else {
expect(data).to.deep.equal(expected)
expect(result).to.deep.equal(expected)
}
}
|
var katal = require('katal'),
KAMAR = new katal({ portal: 'kamar-portal.myschool.school.nz' }); //change this to suit your school
KAMAR
.authenticate({
username: 'kyle.h',
password: 'xxxxxxxx'
})
.then((credentials) => KAMAR.getAbsences(credentials))
.then((absencesData) => {
console.log(absencesData);
})
.catch(console.error);
|
/* global $ d3 */
'use strict';
var App = App || {};
// eslint-disable-next-line no-unused-vars
function PixelGlyph(options) {
let self = {
chartMargins: {
top: 10,
bottom: 10,
left: 50,
right: 50
},
colors: {
outline: 'black'
},
nameMapping: {
},
quadrants: {},
graph: null
};
function init(targetDiv) {
let svg = targetDiv.append('svg');
self.graph = svg.append('g').classed('graph-group', true);
self.chartMargins = options.chartMargins || self.chartMargins;
// overall glyph size
let size = $(svg.node()).width() - self.chartMargins.left - self.chartMargins.right;
svg.style('height', `${size + self.chartMargins.top + self.chartMargins.bottom}px`);
if (options.width) {
svg.style('width', options.width);
}
self.graph.content = self.graph.append('g').classed('graph-content', true);
self.graph.background = self.graph.append('rect')
.attr('x', self.chartMargins.left)
.attr('y', self.chartMargins.top)
.attr('width', size).attr('height', size)
.classed('graph-background', true)
.attr('fill', 'none')
.attr('stroke', self.colors.outline).attr('stroke-width', '1px');
self.graph.layout = self.graph.append('g').classed('graph-layout', true);
self.size = size;
initializeQuadrants();
initializeLayout();
}
function initializeQuadrants() {
const quadrants = ['topLeft', 'topRight', 'bottomLeft', 'bottomRight'];
const padding = 6.5;
// quadrant data includes: color, maxValue, name
quadrants.forEach((q,i) => {
self.quadrants[q] = options.quadrants[q];
self.nameMapping[self.quadrants[q].name] = q;
self.quadrants[q].rectangle = self.graph.content.append('rect')
.attr('width', self.size / 2).attr('height', self.size / 2)
.attr('x', self.chartMargins.left + ((i % 2 == 0) ? 0 : (self.size / 2)))
.attr('y', self.chartMargins.top + ((i < 2) ? 0 : (self.size / 2)))
.style('fill', self.quadrants[q].color).attr('id', q)
.attr('stroke', 'none');
self.graph.content.append('rect')
.attr('width', +self.quadrants[q].rectangle.attr('width') - padding)
.attr('height', +self.quadrants[q].rectangle.attr('height') - padding)
.attr('x', +self.quadrants[q].rectangle.attr('x') + padding/2)
.attr('y', +self.quadrants[q].rectangle.attr('y') + padding/2)
.style('fill', 'none').style('stroke', self.quadrants[q].color)
.style('stroke-width', padding);
self.quadrants[q].scale = d3.scaleLinear().domain([0, self.quadrants[q].maxValue]).range([0,1]);
});
}
// eslint-disable-next-line no-unused-vars
function getQuadrant(name) {
return self.nameMapping[name];
}
function getQuadrantName(quadrant) {
return self.quadrants[quadrant].name;
}
function initializeLayout() {
let line = d3.line()
.x(d => d[0]).y(d => d[1]);
let verticalAxis = [
[self.chartMargins.left + self.size / 2, self.chartMargins.top],
[self.chartMargins.left + self.size / 2, self.chartMargins.top + self.size]
];
let horizontalAxis = [
[self.chartMargins.left, self.chartMargins.top + self.size / 2],
[self.chartMargins.left + self.size, self.chartMargins.top + self.size / 2],
];
self.graph.layout.append('path').datum(verticalAxis).attr('d', line)
.attr('stroke', self.colors.outline).attr('stroke-width', '3px');
self.graph.layout.append('path').datum(horizontalAxis).attr('d', line)
.attr('stroke', self.colors.outline).attr('stroke-width', '3px');
drawLabels(false);
}
// based off of http://bl.ocks.org/nitaku/8745933
function addBorderAroundLabel(d3Label, targetGroup, color) {
let bBox = d3Label.node().getBBox();
let ctm = d3Label.node().getCTM();
let setTransform = (element, matrix) => element.transform.baseVal.initialize(element.ownerSVGElement.createSVGTransformFromMatrix(matrix));
const padding = 2;
let borderRect = targetGroup.insert('rect','text')
.attr('x', bBox.x - padding/2).attr('y', bBox.y - padding/2)
.attr('width', bBox.width + padding).attr('height', bBox.height + padding)
.style('stroke', color).style('stroke-width', '2px');
setTransform(borderRect.node(),ctm);
}
function drawLabels(doAddBorder) {
let labelGroup = self.graph.layout.append('g').attr('id', 'label-group');
Object.keys(self.quadrants).forEach((q,i) => {
let quadrant = self.quadrants[q];
let topLeftCoords = [
self.chartMargins.left + ((i % 2 == 0) ? 0 : (self.size / 2)),
self.chartMargins.top + ((i < 2) ? 0 : (self.size / 2))
];
let label = labelGroup.append('text')
.attr('x', topLeftCoords[0] + self.size / 4)
.attr('y', topLeftCoords[1] + self.size / 4)
.style('text-anchor', 'middle').style('dominant-baseline', 'central')
.attr('id', quadrant.name);
if(quadrant.graphLabel){
quadrant.graphLabel.forEach((d,i) => {
label.append('tspan')
.attr('x', label.attr('x')).attr('dy', i == 0 ? `-${quadrant.graphLabel.length/2}em` : '1.2em')
.text(d);
});
}else{
label.text(quadrant.name);
}
if(doAddBorder){
addBorderAroundLabel(label, labelGroup, quadrant.color);
}
});
}
/*
data = {
<name for top left quadrant>: value, // name being something like "Residential", NOT "topLeft"
<name for top right quadrant>: value, // ordering of data doesn't matter
}
*/
function update(panel, data) {
Object.keys(self.quadrants).forEach(q => {
self.quadrants[q].rectangle
.style('opacity', self.quadrants[q].scale(data[getQuadrantName(q)]));
});
}
return {
init,
update
};
}
|
define(['jquery', 'jqueryvalidate', 'messages/bootstrap-tokenfield.min'], function ($) {
var $ = require('jquery');
var jqueryvalidate = require('jqueryvalidate');
//var wysiwyg = require('wysiwyg');
var tokens = require('messages/bootstrap-tokenfield.min');
//var tokens = require('messages/bootstrap-tokenfield.min');
$(document).ready(function () {
//$('.wysiwyg').wysihtml5();
jQuery("#MessageComposeForm").validate({
errorClass: 'text-danger',
rules: {
"body": {
required: true
}
},
messages: {
"body": {
required: "Please enter something."
}
},
errorPlacement: function (error, element) {
error.insertAfter(element.parent('div'));
}
});
scollTopChat();
function scollTopChat(fromNew) {
if (fromNew && typeof (messageDivHeight) !== "undefined") {
$(".chat-msg-inner").scrollTop(messageDivHeight + 100);
} else {
if (typeof ($('.chat-msg-inner div.chat-message:last').offset()) !== "undefined") {
messageDivHeight = $('.chat-msg-inner div.chat-message:last').offset().top;
$(".chat-msg-inner").scrollTop(messageDivHeight);
}
}
}
$('.messageForm').submit(function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
dataType: 'json',
type: 'post',
data: $(this).serialize(),
success: function (data) {
if (data.status) {
//clear old message
//$('.wysiwyg').data('wysihtml5').editor.clear();
//add new message on display
$('.chat-msg-inner').append(data.content);
//scroll top
scollTopChat(true);
//bind delete event
$('.delete-message').unbind('click');
bindDelete();
}
}
});
});
//delete-message
bindDelete();
function bindDelete() {
$('.delete-message').on('click', function (e)
{
e.preventDefault();
var curDiv = $(this);
if (confirm('Do you want to delete this message ?'))
{
$.ajax({
url: curDiv.attr('href'),
dataType: 'json',
success: function (data)
{
if (typeof data.status !== 'undefined' && data.status === 'success')
{
curDiv.parent().addClass('deleted-message-color');
curDiv.parent().html('This message has been removed. <i class="fa fa-trash-o"></i>');
}
}
});
}
});
}
var groupUsers = jQuery('.user-tokens').data('value');
//create token
$('.tokenfield').tokenInput('/gintonic_c_m_s/messages/setUserCommaSepList', {
theme: "facebook",
prePopulate: groupUsers,
preventDuplicates: true,
hintText: "Enter existing user email address",
noResultsText: "No user found.",
searchingText: "Searching..."
});
// $.ajax({
// url:'/messages/messages/setUserCommaSepList',
// dataType:'json',
// success:function(response){
// $('.tokenfield').tokenInput(response, {
// theme: "facebook",
// preventDuplicates: true,
// hintText: "Enter existing user email address",
// noResultsText: "No user found.",
// searchingText: "Searching..."
// });
// },
// error:function(e){
// console.log(e);
// }
// });
//change status
$('.change-message-status').on('click', function (e) {
e.preventDefault();
var curEle = $(this);
var status = $(this).data('status');
alert(status);
params = 0;
if (status == 'read') {
params = 1;
}
$.ajax({
url: $(this).attr('href') + "/" + params,
dataType: 'json',
success: function (data) {
if (typeof data.status !== 'undefined' && data.status === 'success') {
if (status === 'read') {
curEle.parent().removeClass('text-info');
curEle.text('unread');
curEle.data('status', 'unread');
} else {
curEle.parent().addClass('text-info');
curEle.text('read');
curEle.data('status', 'read');
}
}
}
});
});
});
}); |
// Saves options to chrome.storage
function save_options() {
var vyhledavani = document.getElementById('vyhledavani').checked;
var domu = document.getElementById('domu').checked;
var premium = document.getElementById('premium').checked;
var hlavicka = document.getElementById('hlavicka').checked;
var odkazy = document.getElementById('odkazy').checked;
var udalost = document.getElementById('udalost').checked;
var rozpracovane = document.getElementById('rozpracovane').value;
var poznamky = document.getElementById('poznamky').value;
chrome.storage.sync.set({
vyhledavani: vyhledavani,
domu: domu,
premium: premium,
hlavicka: hlavicka,
odkazy: odkazy,
udalost: udalost,
rozpracovane: rozpracovane,
poznamky: poznamky
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Nastavení bylo uloženo';
setTimeout(function() {
status.textContent = '';
}, 2000);
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
// Use default value color = 'red' and likesColor = true.
chrome.storage.sync.get({
vyhledavani: false,
domu: true,
premium: false,
hlavicka: false,
odkazy: true,
udalost: true,
rozpracovane: '',
poznamky: ''
}, function(items) {
document.getElementById('vyhledavani').checked = items.vyhledavani;
document.getElementById("domu").checked = items.domu;
document.getElementById("premium").checked = items.premium;
document.getElementById("hlavicka").checked = items.hlavicka;
document.getElementById("odkazy").checked = items.odkazy;
document.getElementById("udalost").checked = items.udalost;
document.getElementById("rozpracovane").value = items.rozpracovane;
document.getElementById("poznamky").value = items.poznamky;
});
}
function add_textarea (argument) {
var notes = document.querySelectorAll(".notes").length;
var label = document.createElement("label"),
label_text = document.createTextNode("Šablona #"+notes),
textarea = document.createElement("textarea"),
br = document.createElement("br");
textarea.class = "notes";
textarea.name = "poznamky"+notes;
textarea.id = "poznamky"+notes;
var preparedNode = "<label>Šablona #"+notes+"<br><textarea class = \"notes\" name =\"poznamky"+notes+"\" id=\"poznamky"+notes+"\"></textarea></label><br>";
// document.getElementById("poznamka").referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
document.getElementById("poznamky").parentNode.insertBefore(textarea,document.getElementById("poznamka"));
document.getElementById("poznamky").parentNode.insertBefore(br,document.getElementById("poznamka"))
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',
save_options);
document.getElementById('nova').addEventListener('click',
add_textarea); |
import 'babel-polyfill';
import 'ratchet/sass/ratchet.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
;(function () {
"use strict";
angular
.module('RDash')
.controller('loginFormController', [
'$scope',
'loginFormValidator',
function ($scope, formValidator) {
$scope.submit = $scope.submit || function() { console.error('loginFormController>>submit empty'); };
$scope.error = $scope.error || function() { console.error('loginFormController>>error empty'); };
$scope.user = $scope.user || '';
$scope.onSubmit = function() {
var credentials = {
user: $scope.user
};
formValidator
.validate(credentials)
.then($scope.submit, $scope.error);
};
}]);
})();
|
import React from 'react'
// Import non-js files like this, with the extension and an exclamation point:
// import MyComponent from './MyComponent.jsx!'
import AnotherCp from './AnotherComponent.jsx!'
(() => {
React.render(
<AnotherCp name="Luiz" />,
document.body
)
})()
|
import RootValidator from './root'
/**
* @desc Determines whether is an Array
*/
class ObjectValidator extends RootValidator {
constructor(i, options = {}) {
super(i, options)
return this.validate()
}
/**
* Whether or not the object contains a property
* @param {String} k - The property, or key, to check
*/
contains(k) {
if(this.i.hasOwnProperty(k)) return this
return {
err: {
code: 'NO_CONTAINS',
desc: `The item checked is does not have property ${k}.`,
valueChecked: this.i
}
}
}
/**
* Test whether it is a an array
* @see http://stackoverflow.com/a/22482737/586131
*/
is() {
if(this.i instanceof Object && this.i !== null) return this
return {
err: {
code: 'NOT_OBJECT',
desc: `The item checked is not an object.`,
valueChecked: this.i
}
}
}
}
export default ObjectValidator
|
const { Session } = require('..')
const { Profile } = Session
const assert = require('assert')
describe('Session.Profile', () => {
describe('#constructor', () => {
it('should return a Profile', function() {
assert((new Profile()) instanceof Profile)
})
})
describe('#addDecoder', () => {
it('should add a decoder', function(done) {
const profile = new Profile()
profile.addLinkLayer(1, '[eth]')
profile.addDecoder(`
class Diss {
analyze(ctx, layer) {
return true
}
}
Diss
`, { layerHints: ['[eth]'] })
const sess = new Session(profile)
sess.pushFrames([{ data: ethData }], 1)
sess.on('event', (e) => {
if (e.type === 'frames' && e.length === 1) {
sess.close()
done()
}
})
})
it('should throw for wrong arguments', () => {
const profile = new Profile()
assert.throws(() => profile.addDecoder(), TypeError)
assert.throws(() => profile.addDecoder(''), TypeError)
assert.throws(() => profile.addDecoder('', 0), TypeError)
})
})
})
describe('Session', () => {
describe('#constructor', () => {
it('should return a Session', function() {
const profile = new Profile()
const sess = new Session(profile)
assert(sess instanceof Session)
assert.equal(sess.length, 0)
sess.close()
})
it('should throw for wrong arguments', () => {
assert.throws(() => new Session(), TypeError)
assert.throws(() => new Session('aaa'), TypeError)
})
})
describe('#close', () => {
it('should detach the seesion from the event loop', function() {
const profile = new Profile()
const sess = new Session(profile)
sess.close()
sess.close()
sess.close()
})
})
describe('#context', () => {
it('should return a context', () => {
const profile = new Profile()
const sess = new Session(profile)
assert.equal(sess.context.constructor.name, 'Context')
sess.close()
})
})
describe('#pushFrames', () => {
it('pushFrames', function() {
const profile = new Profile()
const sess = new Session(profile)
for (i = 0; i < 100; ++i) {
sess.pushFrames([{ data: ethData }], 1)
}
sess.close()
})
})
describe('#frames', () => {
it('should return an array', function() {
const profile = new Profile()
const sess = new Session(profile)
assert(Array.isArray(sess.frames(0, 0)))
sess.close()
})
it('should throw for wrong arguments', () => {
const profile = new Profile()
const sess = new Session(profile)
assert.throws(() => sess.frames(), TypeError)
assert.throws(() => sess.frames(0), TypeError)
assert.throws(() => sess.frames(0, 'aaa'), TypeError)
sess.close()
})
})
describe('#filteredFrames', () => {
it('should return an array', function() {
const profile = new Profile()
const sess = new Session(profile)
assert(Array.isArray(sess.filteredFrames(0, 0, 0)))
sess.close()
})
it('should throw for wrong arguments', () => {
const profile = new Profile()
const sess = new Session(profile)
assert.throws(() => sess.filteredFrames(), TypeError)
assert.throws(() => sess.filteredFrames(0), TypeError)
assert.throws(() => sess.filteredFrames(0, 'aaa'), TypeError)
assert.throws(() => sess.filteredFrames(0, 0, 'aaa'), TypeError)
sess.close()
})
})
/*
Describe('#setFilter', function() {
it('setFilter', function(done) {
const profile = new Profile()
const sess = new Session(profile)
sess.on('event', (e) => {
if (e.type === 'filtered_frames' && e.length === 50) {
sess.close()
done()
}
})
sess.setFilter('main', 'aaaa')
for (i = 0; i < 100; ++i) {
sess.pushFrames([{ data: ethData }], 1)
}
})
})
*/
})
const ethData = new Buffer([
0xd4, 0xc3, 0xb2, 0xa1, 0x02, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x33, 0xf6, 0x7e, 0x58, 0x88, 0x65,
0x0d, 0x00, 0x42, 0x00, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00, 0xac, 0xbc, 0x32, 0xbc, 0x2a,
0x87, 0x80, 0x13, 0x82, 0x62, 0xa2, 0x45, 0x08, 0x00, 0x45, 0x00, 0x00, 0x34, 0x69, 0xaf,
0x40, 0x00, 0x31, 0x06, 0x01, 0xf7, 0xca, 0xe8, 0xee, 0x28, 0xc0, 0xa8, 0x64, 0x64, 0x00,
0x50, 0xc4, 0x27, 0x22, 0xdd, 0xb1, 0xc0, 0x63, 0x6a, 0x47, 0x9b, 0x80, 0x10, 0x00, 0x72,
0xf7, 0x6c, 0x00, 0x00, 0x01, 0x01, 0x08, 0x0a, 0xf9, 0x28, 0x89, 0x4f, 0x61, 0x8f, 0x78,
0x9d
])
|
import { moduleForModel, test } from 'ember-qunit';
moduleForModel('episode-of-care-diagnosis', 'Unit | Model | EpisodeOfCare_Diagnosis', {
needs: [
'model:meta',
'model:narrative',
'model:resource',
'model:extension',
'model:reference',
'model:codeable-concept'
]
});
test('it exists', function(assert) {
const model = this.subject();
assert.ok(!!model);
}); |
import React, {Component, PropTypes} from "react"
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {AppBar, Drawer, MenuItem, Paper, FlatButton, ListItem} from 'material-ui';
import * as constants from '../../../constant';
import {Link} from 'react-router';
import "./style.scss";
let muiTheme = getMuiTheme({
fontFamily: 'Microsoft YaHei'
});
export default class DashBoard extends Component {
constructor(props) {
super(props);
this.state = {open: false};
}
render() {
let menuList = [];
for (var i = 0; i < constants.menuList.length; i++) {
var subMenu = [];
for (var j = 0; j < constants.menuList[i].childList.length; j++) {
var key = "sub_menu_"+j;
var url = "/" + constants.menuList[i].childList[j]['url'];
var name = constants.menuList[i].childList[j]['name'];
subMenu.push(<MenuItem key={key} containerElement={<Link to={url} />}>{name}</MenuItem>);
}
var key = "menu_" + i;
var text = constants.menuList[i].name;
var initOpen = i == 0 ? true : false;
menuList.push(<ListItem key={key} primaryText={text} initiallyOpen={initOpen} nestedItems={subMenu} />);
}
return (
<MuiThemeProvider muiTheme={muiTheme}>
<div>
<AppBar
title="程序员常用工具集"
onLeftIconButtonTouchTap={ () => this.handleLeftIconButtonTouchTap() }
/>
<Drawer
docked={false}
width={200}
open={this.state.open}
onRequestChange={(open) => this.setState({open})}
>
<MenuItem containerElement={<Link to="/"/>}>首页</MenuItem>
{
menuList
}
</Drawer>
<div className="container">
{this.props.children}
</div>
</div>
</MuiThemeProvider>
)
}
handleLeftIconButtonTouchTap() {
this.setState({open: !this.state.open});
}
} |
// determine if an element can be focused by keyboard (i.e. is part of the document's sequential focus navigation order)
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _platform = require('platform');
var _platform2 = _interopRequireDefault(_platform);
var _utilTabindexValue = require('../util/tabindex-value');
var _utilTabindexValue2 = _interopRequireDefault(_utilTabindexValue);
var _isUtil = require('./is.util');
// Internet Explorer 11 considers fieldset, table, td focusable, but not tabbable
// Internet Explorer 11 considers body to have [tabindex=0], but does not allow tabbing to it
var focusableElementsPattern = /^(fieldset|table|td|body)$/;
exports['default'] = function (element) {
if (element === document) {
element = document.documentElement;
}
if (!element || element.nodeType !== Node.ELEMENT_NODE) {
throw new TypeError('is/tabbable requires an argument of type Element');
}
if (_platform2['default'].name === 'Chrome Mobile' && parseFloat(_platform2['default'].version) > 42 && _platform2['default'].os.family === 'Android') {
// External keyboard support worked fine in CHrome 42, but stopped working in Chrome 45.
// The on-screen keyboard does not provide a way to focus the next input element (like iOS does).
// That leaves us with no option to advance focus by keyboard, ergo nothing is tabbable (keyboard focusable).
return false;
}
var nodeName = element.nodeName.toLowerCase();
var _tabindex = (0, _utilTabindexValue2['default'])(element);
var tabindex = _tabindex === null ? null : _tabindex >= 0;
// NOTE: Firefox 31 considers [contenteditable] to have [tabindex=-1], but allows tabbing to it
// fixed in Firefox 40 the latest - https://bugzilla.mozilla.org/show_bug.cgi?id=1185657
if (element.hasAttribute('contenteditable')) {
// tabbing can still be disabled by explicitly providing [tabindex="-1"]
return tabindex !== false;
}
if (focusableElementsPattern.test(nodeName) && tabindex !== true) {
return false;
}
// in Trident and Gecko SVGElement does not know about the tabIndex property
if (element.tabIndex === undefined) {
return false;
}
if (nodeName === 'audio') {
if (!element.hasAttribute('controls')) {
// In Internet Explorer the <audio> element is focusable, but not tabbable, and tabIndex property is wrong
return false;
} else if (_platform2['default'].name === 'Chrome' || _platform2['default'].name === 'Chrome Mobile') {
// In Chrome <audio controls tabindex="-1"> remains keyboard focusable
return true;
}
}
if (nodeName === 'video') {
if (!element.hasAttribute('controls')) {
if (_platform2['default'].name === 'IE') {
// In Internet Explorer the <video> element is focusable, but not tabbable, and tabIndex property is wrong
return false;
}
} else if (_platform2['default'].name === 'Chrome' || _platform2['default'].name === 'Firefox') {
// In Chrome and Firefox <video controls tabindex="-1"> remains keyboard focusable
return true;
}
}
if (nodeName === 'object') {
if (_platform2['default'].layout === 'Blink' || _platform2['default'].layout === 'WebKit') {
// In all Blink and WebKit based browsers <embed> and <object> are never keyboard focusable, even with tabindex="0" set
return false;
}
}
if (_platform2['default'].name === 'Safari' && parseFloat(_platform2['default'].version) < 10 && _platform2['default'].os.family === 'iOS') {
// iOS 8 only considers a hand full of elements tabbable (keyboard focusable)
// this holds true even with external keyboards
var potentiallyTabbable = nodeName === 'input' && element.type === 'text' || element.type === 'password' || nodeName === 'select' || nodeName === 'textarea' || element.hasAttribute('contenteditable');
if (!potentiallyTabbable) {
var style = window.getComputedStyle(element, null);
potentiallyTabbable = (0, _isUtil.isUserModifyWritable)(style);
}
if (!potentiallyTabbable) {
return false;
}
}
if (_platform2['default'].name === 'Firefox') {
// Firefox considers scrollable containers keyboard focusable,
// even though their tabIndex property is -1
var style = window.getComputedStyle(element, null);
if ((0, _isUtil.hasCssOverflowScroll)(style)) {
// value of tabindex takes precedence
return tabindex !== false;
}
}
if (_platform2['default'].name === 'IE') {
// IE degrades <area> to script focusable, if the image
// using the <map> has been given tabindex="-1"
if (nodeName === 'area') {
var img = (0, _isUtil.getImageOfArea)(element);
if (img && (0, _utilTabindexValue2['default'])(img) < 0) {
return false;
}
}
var style = window.getComputedStyle(element, null);
if ((0, _isUtil.isUserModifyWritable)(style)) {
// prevent being swallowed by the overzealous isScrollableContainer() below
return element.tabIndex >= 0;
}
// IE considers scrollable containers script focusable only,
// even though their tabIndex property is 0
if ((0, _isUtil.isScrollableContainer)(element, nodeName)) {
return false;
}
var _parent = element.parentNode;
// IE considers scrollable bodies script focusable only,
if ((0, _isUtil.isScrollableContainer)(_parent, nodeName)) {
return false;
}
// Children of focusable elements with display:flex are focusable in IE10-11,
// even though their tabIndex property suggests otherwise
var parentStyle = window.getComputedStyle(_parent, null);
if (parentStyle.display.indexOf('flex') > -1) {
return false;
}
}
// http://www.w3.org/WAI/PF/aria-practices/#focus_tabindex
return element.tabIndex >= 0;
};
module.exports = exports['default'];
//# sourceMappingURL=tabbable.js.map |
/* global describe, it */
var should = require('should'),
rewire = require('rewire'),
builder = rewire('../index.js'),
path = require('path'),
_ = require('lodash');
builder.__set__('merge', function (values) {
return values;
});
function join(/* */) {
return path.normalize(path.join.apply(null, arguments));
}
describe('deps', function () {
it('should export interface', function () {
builder.should.have.property('Helper');
builder.should.have.property('init');
});
describe('init', function () {
it('should throw if deps is undefined', function () {
should.throws(function () {
builder.init();
});
});
it('should instantiate a Helper', function () {
var helper = builder.init({});
helper.should.be.instanceof(builder.Helper);
});
it('should correctly use the provided config', function () {
var helper = builder.init({ config: { webroot: 'some' } });
helper.config.should.have.property('webroot', 'some');
});
it('should correctly use the default config', function () {
var helper = builder.init({});
helper.config.should.have.property('webroot', helper.getDefaults().webroot);
});
});
describe('helper', function () {
function process(section, bundleName, config, action) {
if (_.isFunction(config)) {
action = config;
config = {};
}
if (_.isFunction(bundleName)) {
action = bundleName;
bundleName = undefined;
}
if (_.isPlainObject(bundleName)) {
config = bundleName;
bundleName = undefined;
}
var helper = builder.init({
config: config,
section: section
});
helper.process('section', bundleName, function (bundle) {
return action(bundle, helper);
});
}
it('should process all bundles', function () {
var processedBundles = [];
process([{
name: 'vendor',
src: []
}, {
name: 'app',
src: []
}], function (bundle) {
processedBundles.push(bundle);
});
processedBundles.length.should.be.exactly(2);
});
it('should maintain values in the bundle', function () {
process([{
foo: 'bar',
src: []
}], function (bundle) {
bundle.should.have.property('foo', 'bar');
});
});
it('should handle negation', function () {
var deps = {
sec1: [{
name: 'app',
src: ['!src/*.spec.js']
}]
};
var helper = builder.init(deps);
helper.process('sec1', 'app', function (bundle) {
bundle.src[0].should.be.exactly('!' + join('wwwroot', 'src', '*.spec.js'));
});
});
it('should expand src properly when no webroot is provided', function () {
process([{
name: 'app',
src: ['foo.js']
}], function (bundle, helper) {
bundle.src[0].should.be.exactly(join(helper.getDefaults().webroot , 'foo.js'));
});
});
it('should expand src properly when a base is provided', function () {
process([{
name: 'app',
src: ['foo.js']
}], { webroot: './foo/' }, function (bundle) {
bundle.src[0].should.be.exactly(join('foo', 'foo.js'));
});
});
it('should expand src properly when a base is provided in the bundle', function () {
process([{
name: 'app',
base: 'bar',
src: ['foo.js']
}], { webroot: './foo/' }, function (bundle) {
bundle.src[0].should.be.exactly(join('foo', 'bar', 'foo.js'));
});
});
it('should normalize paths', function () {
process([{
name: 'app',
base: 'bar/some/',
dest: 'baz',
src: ['foo.js']
}], { webroot: './foo/' }, function (bundle) {
bundle.dest.should.be.exactly(path.normalize(path.join('foo', 'baz')));
});
});
it('should expand dest properly if provided', function () {
process([{
name: 'app',
base: 'bar/',
dest: '../baz',
src: ['foo.js']
}], { webroot: './foo/some/' }, function (bundle) {
bundle.dest.should.be.exactly(join('foo', 'baz'));
});
});
it('should do destructive edits on a bundle copy instead of the original bundle', function () {
var section = [{
name: 'app',
base: 'bar/',
dest: '../baz',
src: ['foo.js']
}];
process(section, { webroot: './foo/some/' }, function (bundle) {
bundle.foo = 42;
});
section[0].should.not.have.ownProperty('foo');
});
it('should process the bundle if its name is specified', function () {
var section = [{
name: 'app'
}, {
name: 'vendor'
}];
process(section, 'app', function (bundle) {
bundle.name.should.be.exactly('app');
});
});
it('should process the specified bundle names', function () {
var count = 0;
var section = [{
name: 'app'
}, {
name: 'vendor'
}, {
name: 'other'
}];
process(section, ['app', 'other'], function (bundle) {
count++;
});
count.should.be.exactly(2);
});
describe('refs', function () {
it('should process refs', function () {
var deps = {
sec1: [{
name: 'app',
refs: {
section: 'sec2',
bundles: 'app'
},
src: ['bar.js']
}],
sec2: [{
base: 'some',
name: 'app',
src: ['foo.js']
}]
};
var helper = builder.init(deps);
helper.process('sec1', 'app', function (bundle) {
bundle.src.length.should.be.exactly(2);
bundle.src[0].should.be.exactly(join('wwwroot', 'bar.js'));
bundle.src[1].should.be.exactly(join('wwwroot', 'some', 'foo.js'));
});
});
it('should process refs even without src', function () {
var deps = {
sec1: [{
name: 'app',
refs: {
section: 'sec2',
bundles: 'app'
}
}],
sec2: [{
base: 'some',
name: 'app',
src: ['foo.js']
}]
};
var helper = builder.init(deps);
helper.process('sec1', 'app', function (bundle) {
bundle.src.length.should.be.exactly(1);
bundle.src[0].should.be.exactly(join('wwwroot', 'some', 'foo.js'));
});
});
it('should process multi refs', function () {
var deps = {
sec1: [{
name: 'app',
refs: [{
section: 'sec2',
bundles: 'app'
}, {
section: 'sec3',
bundles: 'app'
}]
}],
sec2: [{
base: 'some',
name: 'app',
src: ['foo.js']
}],
sec3: [{
name: 'app',
src: ['baz.js']
}]
};
var helper = builder.init(deps);
helper.process('sec1', 'app', function (bundle) {
bundle.src.length.should.be.exactly(2);
bundle.src[0].should.be.exactly(join('wwwroot', 'some', 'foo.js'));
bundle.src[1].should.be.exactly(join('wwwroot', 'baz.js'));
});
});
it('should use the same section if non is specified', function () {
var deps = {
sec1: [{
name: 'app',
refs: {
bundles: 'vendor'
}
}, {
name: 'vendor',
src: ['foo.js']
}]
};
var helper = builder.init(deps);
helper.process('sec1', 'app', function (bundle) {
bundle.src.length.should.be.exactly(1);
bundle.src[0].should.be.exactly(join('wwwroot', 'foo.js'));
});
});
});
});
});
|
'use strict'
app.factory('loginService',function($http,$location){
return {
login:function(user,scope){
console.log('enter function service'+user)
var $promise=$http.get('http://54.155.30.167:3000/test/fingerprintingUsers?query={"mail":"'+user.mail+'"}');//send data to user php
$promise.then(function(msg){
if(msg.data.length == 1 && msg.data[0].pass==user.pass){
$location.path('/fingerprint')
}
else scope.msgTxt='error login';
})
}
}
}); |
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'serenity',
environment: environment,
baseURL: '/',
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
AgolRestEndpoint: 'https://www.arcgis.com/',
portalBaseUrl: 'https://www.arcgis.com'
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV.baseURL = 'serenity/';
ENV.torii = {
sessionServiceName: 'session',
providers: {
'arcgis-oauth-bearer': {
apiKey: 'oqKL6es0VrspTpEw',
portalUrl: 'https://arcgis.com' //optional - defaults to https://arcgis.com
}
}
}
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.baseURL = 'serenity/';
ENV.torii = {
sessionServiceName: 'session',
providers: {
'arcgis-oauth-bearer': {
apiKey: 'TlUvU2mdC69zOrPr',
portalUrl: 'https://arcgis.com' //optional - defaults to https://arcgis.com
}
}
}
}
return ENV;
};
|
const isProduction = process.env.NODE_ENV === 'production';
const config = isProduction ? require('./webpack.prod.config.js') : require('./webpack.dev.config.js');
module.exports = config;
|
import React from 'react';
import { default as AdagucMapDraw } from './AdagucMapDraw';
import { shallow } from 'enzyme';
const dispatch = () => { /* intentionally left blank */ };
describe('(Component) AdagucMapDraw', () => {
it('Renders a div', () => {
const _component = shallow(<AdagucMapDraw dispatch={dispatch} />);
expect(_component.type()).to.eql('div');
});
});
|
var child_process = require('child_process');
/**
* 默认silent为false,子进程的stdio从父进程继承,如果是true,则直接pipe向子进程的child.stdin,child.stdout
*
*/
// child_process.fork('./child.js',{
// silent:false
// });
//
// //不会打印
// child_process.fork('./silentChild.js',{
// silent:true
// });
//
// var child = child_process.fork('./anotherSilentChild.js',{
// silent:true
// });
//
// child.stdout.setEncoding('utf-8');
// child.stdout.on('data',function(data){
// console.log(data);
// });
var child = child_process.fork('./child.js');
child.on('message',function(m){
console.log('message from child ' + JSON.stringify(m));
});
child.send({from:'parent'});
process.on('message',function(m){
console.log('message from parent:'+ JSON.stringify(m));
});
process.send({from:'child'});
|
/**
* Module dependencies
*/
var client = require('../boot/redis').getClient()
var settings = require('../boot/settings')
var providers = require('../providers')
var bcrypt = require('bcrypt')
var CheckPassword = require('mellt').CheckPassword
var Modinha = require('modinha')
var Document = require('modinha-redis')
var PasswordRequiredError = require('../errors/PasswordRequiredError')
var InsecurePasswordError = require('../errors/InsecurePasswordError')
/**
* User model
*/
var User = Modinha.define('users', {
// OpenID Connect Standard Claims
//
// NOTE: The "sub" claim is stored as `_id`.
// Expose it as `sub` via mappings.
name: { type: 'string' },
givenName: { type: 'string' },
familyName: { type: 'string' },
middleName: { type: 'string' },
nickname: { type: 'string' },
preferredUsername: { type: 'string' },
profile: { type: 'string' },
picture: { type: 'string' },
website: { type: 'string' },
email: {
type: 'string',
// required: true,
unique: true,
format: 'email'
},
emailVerified: { type: 'boolean', default: false },
dateEmailVerified: { type: 'number' },
emailVerifyToken: {
type: 'string',
unique: true
},
gender: { type: 'string' },
birthdate: { type: 'string' },
zoneinfo: { type: 'string' },
locale: { type: 'string' },
phoneNumber: { type: 'string' },
phoneNumberVerified: { type: 'boolean', default: false },
address: { type: 'object' },
// Hashed password
hash: {
type: 'string',
private: true,
set: hashPassword
},
/**
* Each provider object in user.providers should include
* - Provider user/account id
* - Name of provider
* - Protocol of provider
* - Complete authorization response from provider
* - Complete userInfo response from the provider
* - Last login time
* - Last login provider
*/
providers: {
type: 'object',
default: {},
set: function (data) {
var providers = this.providers = this.providers || {}
Object.keys(data.providers || {}).forEach(function (key) {
providers[key] = data.providers[key]
})
}
},
// supports indexing user.providers.PROVIDER.info.id
lastProvider: {
type: 'string'
}
})
/**
* Hash Password Setter
*/
function hashPassword (data) {
var password = data.password
var hash = data.hash
if (password) {
var salt = bcrypt.genSaltSync(10)
hash = bcrypt.hashSync(password, salt)
}
this.hash = hash
}
/**
* UserInfo Mapping
*/
User.mappings.userinfo = {
'_id': 'sub',
'name': 'name',
'givenName': 'given_name',
'familyName': 'family_name',
'middleName': 'middle_name',
'nickname': 'nickname',
'preferredUsername': 'preferred_username',
'profile': 'profile',
'picture': 'picture',
'website': 'website',
'email': 'email',
'emailVerified': 'email_verified',
'gender': 'gender',
'birthdate': 'birthdate',
'zoneinfo': 'zoneinfo',
'locale': 'locale',
'phoneNumber': 'phone_number',
'phoneNumberVerified': 'phone_number_verified',
'address': 'address',
'created': 'joined_at',
'modified': 'updated_at'
}
/**
* Document persistence
*/
User.extend(Document)
User.__client = client
/**
* User intersections
*/
User.intersects('roles')
/**
* Authorized scope
*/
User.prototype.authorizedScope = function (callback) {
var client = User.__client
var defaults = ['openid', 'profile']
client.zrange('users:' + this._id + ':roles', 0, -1, function (err, roles) {
if (err) { return callback(err) }
if (!roles || roles.length === 0) {
return callback(null, defaults)
}
var multi = client.multi()
roles.forEach(function (role) {
multi.zrange('roles:' + role + ':scopes', 0, -1)
})
multi.exec(function (err, results) {
if (err) { return callback(err) }
callback(null, [].concat.apply(defaults, results))
})
})
}
/**
* Verify password
*/
User.prototype.verifyPassword = function (password, callback) {
if (!this.hash) { return callback(null, false) }
bcrypt.compare(password, this.hash, callback)
}
/**
* Verify password strength
*/
User.verifyPasswordStrength = function (password) {
var daysToCrack = providers.password.daysToCrack
if (CheckPassword(password) <= daysToCrack) {
return false
}
return true
}
/**
* Change password
*/
User.changePassword = function (id, password, callback) {
// require a password
if (!password) {
return callback(new PasswordRequiredError())
}
// require password to be strong
if (!User.verifyPasswordStrength(password)) {
return callback(new InsecurePasswordError())
}
User.patch(id,
{ password: password },
{ private: true },
function (err, user) {
if (err) { return callback(err) }
if (!user) { return callback(null, null) }
callback(null, user)
}
)
}
/**
* Create
*/
User.insert = function (data, options, callback) {
var collection = User.collection
if (!callback) {
callback = options
options = {}
}
if (options.password !== false) {
// require a password
if (!data.password) {
return callback(new PasswordRequiredError())
}
// check the password strength
if (!User.verifyPasswordStrength(data.password)) {
return callback(new InsecurePasswordError())
}
}
// create an instance
var user = User.initialize(data, { private: true })
var validation = user.validate()
// pick up mapped values
if (options.mapping) {
user.merge(data, { mapping: options.mapping })
}
// require a valid user
if (!validation.valid) {
return callback(validation)
}
// catch duplicate values
User.enforceUnique(user, function (err) {
if (err) { return callback(err) }
// batch operations
var multi = User.__client.multi()
// store the user
multi.hset(collection, user._id, User.serialize(user))
// index the user
User.index(multi, user)
// execute ops
multi.exec(function (err) {
if (err) { return callback(err) }
callback(null, User.initialize(user))
})
})
}
/**
* Authenticate
*/
User.authenticate = function (email, password, callback) {
User.getByEmail(email, { private: true }, function (err, user) {
if (err) { return callback(err) }
if (!user) {
return callback(null, false, {
message: 'Unknown user.'
})
}
user.verifyPassword(password, function (err, match) {
if (err) { return callback(err) }
if (match) {
callback(null, User.initialize(user), {
message: 'Authenticated successfully!'
})
} else {
callback(null, false, {
message: 'Invalid password.'
})
}
})
})
}
/**
* Lookup
*
* Takes a request object and third party userinfo
* object and provides either an authenticated user
* or attempts to lookup the user based on a provider
* param in the request and a provider id in the
* userinfo.
*/
User.lookup = function (req, info, callback) {
if (req.user) { return callback(null, req.user) }
var provider = req.params.provider || req.body.provider
var index = User.collection + ':provider:' + provider
User.__client.hget(index, info.id, function (err, id) {
if (err) { return callback(err) }
User.get(id, function (err, user) {
if (err) { return callback(err) }
callback(null, user)
})
})
}
/**
* Index provider user id
*
* This index matches a provider's user id to an
* Anvil Connect `user._id` for later lookup by
* that provider identifier.
*
* This is a tricky index to implement, because we
* don't know the full path ahead of time, so we'll
* need to first resolve it.
*
* Support for this requirement was added to modinha-redis
* for this specific index. The nested array that
* defines `field` gets evaluated first. That value at
* that path is then used as a property name to access
* the id.
*/
User.defineIndex({
type: 'hash',
key: [User.collection + ':provider:$', 'lastProvider'],
field: ['$', ['providers.$.info.id', 'lastProvider']],
value: '_id'
})
/**
* Connect
*/
User.connect = function (req, auth, info, callback) {
var provider = providers[req.params.provider || req.body.provider]
// what if there's no provider param?
// Try to find an existing user.
User.lookup(req, info, function (err, user) {
if (err) { return callback(err) }
// Initialize the user data.
var data = {
providers: {},
lastProvider: provider.id
}
// Set the provider object
data.providers[provider.id] = {
provider: provider.id,
protocol: provider.protocol,
auth: auth,
info: info
}
// Update an existing user with the authorization response
// and userinfo from this provider. By default this will not
// update existing OIDC standard claims values. If
// `refresh_userinfo` is set to `true`, in the configuration
// file, claims will be updated.
if (user) {
if (settings.refresh_userinfo || provider.refresh_userinfo) {
Modinha.map(provider.mapping, info, data)
}
User.patch(user._id, data, function (err, user) {
if (err) { return callback(err) }
callback(null, user)
})
// Create a new user based on this provider's response. This
// WILL map from the provider's raw userInfo properties into the
// user's OIDC standard claims.
} else {
Modinha.map(provider.mapping, info, data)
User.insert(data, {
password: false
}, function (error, user) {
// Handle unique email error
if (error && error.message === 'email must be unique') {
// Lookup the existing user
User.getByEmail(data.email, function (err, user) {
if (err || !user) { return callback(err) }
return callback(null, false, {
message: error.message,
providers: user.providers
})
})
// Handle other error
} else if (error) {
return callback(error)
// User registered successfully
} else {
req.sendVerificationEmail = req.provider.emailVerification.enable
req.flash('isNewUser', true)
callback(null, user, { message: 'Registered successfully' })
}
})
}
})
}
/**
* Errors
*/
User.PasswordRequiredError = PasswordRequiredError
User.InsecurePasswordError = InsecurePasswordError
/**
* Exports
*/
module.exports = User
|
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('firesaleApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
/* solicitudes/getautomu/GET - obtieneMuros */
'use strict';
var express = require('express');
var url = require('url'), qs = require('querystring'), _ = require('lodash'), http = require('http'), https = require('https');
var bst = require('better-stack-traces').install();
var querystring = require('querystring');
var globales = require('../../globals.js');
var classdb = require('../../classdb.js');
var router = express.Router();
/* GET Facebook Inbox. */
router.get('/', function(req, res, next) {
function requestGraph(path, callback) {
if (typeof path !== 'undefined' || path !== null || path !== '') {
globales.options_graph.method = 'GET';
globales.options_graph.path = path;
var solicitud = https.request(globales.options_graph, function(resp) {
var chunks = [];
resp.on('data', function(chunk) {
chunks.push(chunk);
}).on('end', function() {
var contenido = JSON.parse(Buffer.concat(chunks));
if (typeof contenido.error !== 'undefined') {
// console.log('solicitudes/getautomu/requestGraph - hubo un error en solicitud al graph: '+ path);
// console.log(JSON.stringify(contenido.error));
return callback('error');
}
else {
return callback(contenido);
}
});
});
solicitud.on('socket', function(socket){
socket.setTimeout(30000);
socket.on('timeout', function(){
solicitud.abort();
});
});
solicitud.end();
solicitud.on('error', function(e){
console.log('solicitudes/getautomu/requestGraph - hubo un error en la conexión al graph: '+e);
return callback('error');
});
}
else {
console.log('solicitudes/getautomu/requestGraph - no hubo path, así que no se puede pedir nada al graph');
return callback('error');
}
}
function obtieneUsuariosDeCuentas(accounts, index, nombres, users, callback) {
var more = index+1;
var cuantasctas = accounts.length;
if (more > cuantasctas) {
return callback(nombres, users);
}
else {
setImmediate(function(){
if (typeof accounts[index] !== 'undefined') {
var userscritere = {
$and:
[
{'cuenta.marca' : accounts[index].nombreSistema},
{additionalProvidersData : {$exists : true}},
{additionalProvidersData : {$ne : ''}},
{'additionalProvidersData.facebook' : {$exists : true}},
{'additionalProvidersData.facebook.accessToken' : {$exists: true}}
]
};
var usersfields = {
'_id' : '',
'displayName' : '',
'cuenta.marca': '',
'additionalProvidersData.facebook.accessToken' : '',
'additionalProvidersData.facebook.name': ''
};
var userssort = {created_time : 1};
classdb.buscarToArrayFields('users', userscritere, usersfields, userssort, 'solicitudes/getautomu/obtieneUsuariosDeCuentas', function(usersarray){
if (usersarray === 'error' || usersarray.length < 1) {
return obtieneUsuariosDeCuentas(accounts, more, nombres, users, callback);
}
else {
var nombrecta = accounts[index].nombreSistema+'*|*'+accounts[index].datosPage.id+'*|*'+accounts[index].created_time;
nombres.push(nombrecta);
users[nombrecta] = usersarray;
return obtieneUsuariosDeCuentas(accounts, more, nombres, users, callback);
}
});
}
else {
return obtieneUsuariosDeCuentas(accounts, more, nombres, users, callback);
}
});
}
}
function tokensDeCuenta(nombreCuenta, usuariosDeCuenta, index, validTokens, callback) {
var more = index+1;
var cuantosusuarios = usuariosDeCuenta.length;
if (more > cuantosusuarios) {
return callback(validTokens);
}
else {
setImmediate(function(){
if (typeof usuariosDeCuenta[index] !== 'undefined') {
var path = globales.fbapiversion+'oauth/access_token_info?client_id='+globales.fb_app_id+'&access_token='+usuariosDeCuenta[index].additionalProvidersData.facebook.accessToken;
requestGraph(path, function(validacion){
if (validacion === 'error') {
return tokensDeCuenta(nombreCuenta, usuariosDeCuenta, more, validTokens, callback);
}
else {
validTokens.push(validacion.access_token);
return tokensDeCuenta(nombreCuenta, usuariosDeCuenta, more, validTokens, callback);
}
});
}
else {
return tokensDeCuenta(nombreCuenta, usuariosDeCuenta, more, validTokens, callback);
}
});
}
}
function getCtaATs(nombreCta, usuariosCta, callback) {
var critere = {'nombre_cta': nombreCta};
var lesort = {created_time: -1};
classdb.buscarToArray('verifica_auto_uat', critere, {}, 'solicitudes/getautocp/getCtaATs', function(items){
if (items === 'error') {
return callback([]);
}
else {
if (items.length < 1) {
// no existen access_tokens en bd, los pedimos a fb
tokensDeCuenta(nombreCta, usuariosCta, 0, [], function(vtokens){
if (vtokens.length < 1) {
// no hay tokens para esta cuenta
return callback([]);
}
else {
var objeto = {
nombre_cta: nombreCta,
created_time: new Date(),
valid_tokens: vtokens
};
classdb.inserta('verifica_auto_uat', objeto, 'solicitudes/getautocp/getCtaATs', function(insertao){
return callback(vtokens);
});
}
});
}
else {
var ts = items[0].created_time.getTime();
var tsm1 = (ts) + 3600000;
var ahora = new Date().getTime();
if (tsm1 < ahora) {
tokensDeCuenta(nombreCta, usuariosCta, 0, [], function(vtokens){
if (vtokens.length < 1) {
// no hay tokens para esta cuenta
return callback([]);
}
else {
var criterio_actualizacion = {nombre_cta: items[0].nombre_cta};
var objeto = {
nombre_cta: nombreCta,
created_time: new Date(),
valid_tokens: vtokens
};
classdb.actualiza('verifica_auto_uat', criterio_actualizacion, objeto, 'solicitudes/getautocp/getCtaATs', function(actualizao){
return callback(vtokens);
});
}
});
}
else {
// y sigue vigente
return callback(items[0].valid_tokens);
}
}
}
});
}
function checaAccessTokens(accounts, accountusers, index, ctascvat, userscvat, callback) {
var more = index+1;
var cuantasctas = accounts.length;
if (more > cuantasctas) {
return callback(ctascvat, userscvat);
}
else {
setImmediate(function(){
if (typeof accounts[index] !== 'undefined') {
var nombrecta = accounts[index];
getCtaATs(nombrecta, accountusers[nombrecta], function(tdc){
if (tdc.length < 1) {
return checaAccessTokens(accounts, accountusers, more, ctascvat, userscvat, callback);
}
else {
ctascvat.push(nombrecta);
userscvat[nombrecta] = tdc;
return checaAccessTokens(accounts, accountusers, more, ctascvat, userscvat, callback);
}
});
}
else {
return checaAccessTokens(accounts, accountusers, more, ctascvat, userscvat, callback);
}
});
}
}
function procesaSiblings(page_id, account, eltexto, siblings, index, newsiblings, callback) {
var more = index+1;
var cuantossib = siblings.length;
if (more > cuantossib) {
return callback('', newsiblings);
}
else {
if (siblings[index].from.id !== page_id) {
var critere = { id : siblings[index].id };
classdb.existefind(account+'_consolidada', critere, 'solicitudes/getautomu/procesaSiblings', function(existens){
if (existens === 'error' || existens === 'noexiste') {
// error o no está en la base de datos, no hacemos nada
return procesaSiblings(page_id, account, eltexto, siblings, more, newsiblings, callback);
}
else {
classdb.buscarToArray(account+'_consolidada', critere, {}, 'solicitudes/getautomu/procesaSiblings', function(items){
if (items === 'error') {
// error, no hacemos nada
return procesaSiblings(page_id, account, eltexto, siblings, more, newsiblings, callback);
}
else {
if (typeof items[0].respuestas !== 'undefined') {
// comment tiene respuestas
var las_respuestas = items[0].respuestas;
var existerespu = _.findIndex(las_respuestas, function(chr) {
return chr.texto === eltexto;
});
if (existerespu === -1) {
newsiblings.push(siblings[index]);
return procesaSiblings(page_id, account, eltexto, siblings, more, newsiblings, callback);
}
else {
return callback('respondido: comment '+siblings[index]+' ya recibió esa respuesta', newsiblings);
}
}
else {
// comment no tiene respuestas
newsiblings.push(siblings[index]);
return procesaSiblings(page_id, account, eltexto, siblings, more, newsiblings, callback);
}
}
});
}
});
}
else {
// son de la cuenta en cuestión, no deben responderse
return procesaSiblings(page_id, account, eltexto, siblings, more, newsiblings, callback);
}
}
}
function obtenerIdsDeSiblings(token, parent_comment, callback) {
var pathsiblings = globales.fbapiversion+parent_comment+globales.path_siblings+'&access_token='+token;
requestGraph(pathsiblings, function(response_sib) {
if (response_sib === 'error') {
// console.log('hubo un error, no conseguimos siblings');
callback('error');
}
else {
if (typeof response_sib.comments === 'undefined' || response_sib.comments.data < 1) {
callback('error');
}
else {
callback(response_sib.comments.data);
}
}
});
}
function verificaRespuestas(token, nombreSyst, pag_id, comentario_procesado, callback) {
// console.log(comentario_procesado);
if (typeof comentario_procesado.message !== 'undefined' && comentario_procesado.message !== '') {
var vcuenta = nombreSyst;
var colezione = vcuenta+'_consolidada';
var pa_id = pag_id;
var co_id = comentario_procesado.id;
var ctexto = comentario_procesado.message;
var ppos = comentario_procesado.parent_post;
var pcom = comentario_procesado.parent_comment;
// el comentario tiene mensaje, empezamos
if (pcom === ppos) {
// console.log('es respuesta a un comment');
// es un comment en un comment, posiblemente sea respuesta a uno de sus siblings, hay que ver
var criteriopc = { id : pcom };
classdb.existefind(colezione, criteriopc, 'solicitudes/getautomu/verificaRespuesta.comment', function(existia){
if (existia === 'error' || existia === 'noexiste') {
console.log('solicitudes/getautomu/verificaRespuestas - Error: el comment en el que va este comment no existe en la colección');
callback(existia);
}
else {
classdb.buscarToArray(colezione, criteriopc, {}, 'solicitudes/getautomu/verificaRespuesta.comment', function(uncomment){
if (uncomment === 'error') {
callback(uncomment);
}
else {
if (uncomment.length > 0) {
if (typeof uncomment[0].respuestas !== 'undefined') {
// parent_comment tiene respuestas en db
var las_respuestas = uncomment[0].respuestas;
var existerespu = _.findIndex(las_respuestas, function(chr) {
return chr.texto === comentario_procesado.message;
});
if (existerespu === -1) {
obtenerIdsDeSiblings(token, pcom, function(comments_ids){
if (typeof comments_ids.comments !== 'undefined') {
// ya hay comments en el comment
var siblings = _(comments_ids.comments.data).reverse().value();
procesaSiblings(pa_id, vcuenta, ctexto, siblings, 0, [], function(sibst, sibar){
if (sibst !== ''){
console.log(sibst);
callback('ok');
}
else {
if (sibar.length > 0) {
var la_reponse = { user_name : 'facebook', user_id : 'direct-facebook', texto : ctexto, timestamp : new Date(), id_str : co_id };
var criteres = { id : sibar[0].id };
var eladdts = { respuestas : la_reponse };
classdb.actualizaAddToSet(colezione, criteres, eladdts, 'solicitudes/getautomu/verificaRespuesta.comment', function(repondu){
callback(repondu);
});
}
else {
console.log('solicitudes/getautomu/verificaRespuesta.comment - no había sibling comments...');
callback('error');
}
}
});
}
else {
var la_respuesta = {
user_name: 'facebook',
user_id: 'direct-facebook',
texto: ctexto,
timestamp : new Date(),
id_str: co_id
};
classdb.actualizaAddToSet(colezione, criteriopc, { respuestas: la_respuesta }, 'solicitudes/getautomu/verificaRespuesta.comment', function(respondido) {
callback(respondido);
});
}
});
}
else {
console.log('solicitudes/getautomu/verificaRespuesta - Error: la respuesta ya estaba en el comment');
callback('error');
}
}
else {
// no hubo respuestas en el comment de bd
var theanswer = {
user_name: 'facebook',
user_id: 'direct-facebook',
texto: ctexto,
timestamp : new Date(),
id_str: co_id
};
classdb.actualizaAddToSet(colezione, criteriopc, {respuestas: theanswer}, 'solicitudes/getautomu/verificaRespuesta.comment', function(answered) {
callback(answered);
});
}
}
else {
console.log('solicitudes/getautomu/verificaRespuesta.comment - arreglo de comments llegó vacío');
callback('error');
}
}
});
}
});
}
else {
// console.log('es respuesta a un post');
// es un comment a un post buscamos post para adjuntar respuesta
var criteriopp = { id : ppos };
classdb.existefind(colezione, criteriopp, 'solicitudes/getautomu/verificaRespuesta.post', function(exists) {
if (exists === 'error' || exists === 'noexiste') {
console.log('solicitudes/getautomu/verificaRespuesta.post - Error: el post en el que va este comment no existe en la colección');
callback(exists);
}
else {
classdb.buscarToArray(colezione, criteriopp, {}, 'solicitudes/getautomu/verificaRespuesta.post', function(unpost){
if (unpost === 'error') {
callback(unpost);
}
else {
if (unpost.length > 0) {
if (typeof unpost[0].respuestas !== 'undefined') {
// parent_post tiene respuestas en db
var reponses = unpost[0].respuestas;
var existeresp = _.findIndex(reponses, function(chr) {
return chr.texto === ctexto;
});
if (existeresp === -1) {
// esta respuesta no existe dentro de las demás respuestas, la insertamos
var larespuesta = {
user_name: 'facebook',
user_id: 'direct-facebook',
texto: ctexto,
timestamp : new Date(),
id_str: co_id
};
classdb.actualizaAddToSet(colezione, criteriopp, { respuestas : larespuesta }, 'solicitudes/getautomu/verificaRespuesta.post', function(respondido) {
callback(respondido);
});
}
else {
// console.log('solicitudes/getautomu/verificaRespuesta.post - Esta la respuesta ya estaba en el post, no es error');
callback('ok');
}
}
else {
// parent_post aun no tiene respuestas, insertamos
var dieantwort = {
user_name: 'facebook',
user_id: 'direct-facebook',
texto: ctexto,
timestamp : new Date(),
id_str: co_id
};
classdb.actualizaAddToSet(colezione, criteriopp, { respuestas : dieantwort }, 'solicitudes/getautomu/verificaRespuesta.post', function(answered) {
callback(answered);
});
}
}
else {
console.log('solicitudes/getautomu/verificaRespuesta.post - arreglo posts llegó vacío');
callback('error');
}
}
});
}
});
}
}
else {
// comentario no tiene mensaje, mandamos error
console.log('solicitudes/getautomu/verificaRespuesta.main - Error: comentario venía vacío, no hay nada que insertar');
callback('error');
}
}
function nueMens(fecha, tipo, cuenta) {
var dadate = fecha.toString();
var nm_data = querystring.stringify(
{
obj: 'facebook',
tipo: tipo,
created_time: dadate,
cuenta: cuenta
}
);
var nm_options = {
hostname: globales.options_likeable.hostname,
port: 443,
path: '/nuevoMensaje',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Content-Length': nm_data.length
}
};
var nmpost_req = https.request(nm_options, function(resnm) {
resnm.setEncoding('utf8');
resnm.on('data', function (nmchunk) {
});
});
nmpost_req.write(nm_data);
nmpost_req.end();
nmpost_req.on('error', function(e){
console.log('escuchador/post-nuevoMensaje varios error: '+e);
console.log("Error: " +e.message);
console.log( e.stack );
});
}
function guardaBaseComment(token, nombreSistema, p_id, fechacta, comment, cback){
if (!comment.from) {
console.log(comment);
}
else {
var criterio = {'id': comment.id};
var fotopath = globales.fbapiversion+comment.from.id+'/picture?redirect=false';
var coleccion = nombreSistema+'_consolidada';
if (typeof comment.created_time !== 'undefined') {
var created_time = comment.created_time;
}
if (typeof created_time !== 'undefined' && Date.parse(created_time) > Date.parse(fechacta)) {
classdb.existefind(coleccion, criterio, 'solicitudes/geautotmu/guardaBaseComment', function(existe) {
if (existe === 'error' || existe === 'existe') {
return cback(existe);
}
else {
requestGraph(fotopath, function(foto){
if (foto === 'error') {
comment.foto = '';
classdb.inserta(nombreSistema+'_consolidada', comment, 'solicitudes/getautomu/guardaBaseComment', function(inserta) {
if (comment.from && p_id !== comment.from.id) {
nueMens(comment.created_time, 'comment', nombreSistema);
}
return cback(inserta);
});
}
else {
comment.foto = foto.data.url;
classdb.inserta(nombreSistema+'_consolidada', comment, 'solicitudes/getautomu/guardaBaseComment', function(inserta) {
if (comment.from && p_id !== comment.from.id) {
nueMens(comment.created_time, 'comment', nombreSistema);
}
return cback(inserta);
});
}
});
}
});
}
}
}
function procesaCommentsdecom(ns, tk, pid, cm, facta, comentarios, index, callback) {
var more = index+1;
var cuantoscodc = comentarios.length;
if (more > cuantoscodc) {
return callback('ok');
}
else {
setImmediate(function() {
if (typeof comentarios[index] !== 'undefined') {
if (typeof comentarios[index].parent !== 'undefined' &&
typeof comentarios[index].parent.id !== 'undefined') {
comentarios[index].parent_comment = comentarios[index].parent.id;
}
else {
comentarios[index].parent_comment = cm.id;
}
if (typeof comentarios[index].attachment !== 'undefined' &&
typeof comentarios[index].attachment.media !== 'undefined' &&
typeof comentarios[index].attachment.media.image !== 'undefined' &&
typeof comentarios[index].attachment.media.image.src !== 'undefined') {
comentarios[index].image_attachment = comentarios[index].attachment.media.image.src;
}
if (typeof comentarios[index].attachment !== 'undefined' &&
typeof comentarios[index].attachment.target !== 'undefined' &&
typeof comentarios[index].attachment.target.url) {
comentarios[index].link_attachment = comentarios[index].attachment.target.url;
}
if (typeof comentarios[index].from !== 'undefined') {
comentarios[index].from_user_id = ''+comentarios[index].from.id;
comentarios[index].from_user_name = comentarios[index].from.name;
if (pid === comentarios[index].from.id) {
verificaRespuestas(tk, ns, pid, comentarios[index], function(esrespuesta){
if (esrespuesta !== 'ok') {
console.log('verificaRespuesta '+esrespuesta);
}
});
}
}
else {
comentarios[index].from_user_id = 'not_available';
}
comentarios[index].parent_post = pid;
comentarios[index].created_old = comentarios[index].created_time;
comentarios[index].created_time = new Date(comentarios[index].created_time.replace('+','.'));
comentarios[index].obj = 'facebook';
comentarios[index].coleccion_orig = ns+'_fb_comment';
comentarios[index].coleccion = ns+'_consolidada';
comentarios[index].tipo = 'comment';
guardaBaseComment(tk, ns, pid, facta, comentarios[index], function(resp){
if(resp === 'error' || resp === 'existe') {
return procesaCommentsdecom(ns, tk, pid, cm, facta, comentarios, more, callback);
}
else {
return procesaCommentsdecom(ns, tk, pid, cm, facta, comentarios, more, callback);
}
});
}
});
}
}
function obtieneCommentsdeComment(token, commentaire, callback) {
var path = globales.fbapiversion+commentaire.id+globales.path_comments_de_comments+'&access_token='+token;
requestGraph(path, function(haycomments){
if (haycomments === 'error' || typeof haycomments.comments === 'undefined') {
return callback('error');
}
else {
return callback(haycomments.comments.data);
}
});
}
function insertandoComments(nombreSyst, token, page_id, post_id, altacuenta, cmnts, index, callback) {
var more = index+1;
var cuantosco = cmnts.length;
if (more > cuantosco) {
return callback('getautomu - insertac_fin_ok');
}
else {
setImmediate(function() {
if (typeof cmnts[index] !== 'undefined') {
cmnts[index].parent_post = post_id;
cmnts[index].parent_comment = cmnts[index].id;
cmnts[index].created_old = cmnts[index].created_time;
cmnts[index].created_time = new Date(cmnts[index].created_time.replace('+','.'));
cmnts[index].obj = 'facebook';
cmnts[index].coleccion_orig = nombreSyst+'_fb_comment';
cmnts[index].coleccion = nombreSyst+'_consolidada';
cmnts[index].tipo = 'comment';
if (typeof cmnts[index].parent !== 'undefined' &&
typeof cmnts[index].parent.id !== 'undefined') {
cmnts[index].parent_comment = cmnts[index].parent.id;
}
else {
cmnts[index].parent_comment = post_id;
}
if (typeof cmnts[index].attachment !== 'undefined' &&
typeof cmnts[index].attachment.media !== 'undefined' &&
typeof cmnts[index].attachment.media.image !== 'undefined' &&
typeof cmnts[index].attachment.media.image.src !== 'undefined') {
cmnts[index].image_attachment = cmnts[index].attachment.media.image.src;
}
if (typeof cmnts[index].attachment !== 'undefined' &&
typeof cmnts[index].attachment.target !== 'undefined' &&
typeof cmnts[index].attachment.target.url) {
cmnts[index].link_attachment = cmnts[index].attachment.target.url;
}
if (typeof cmnts[index].from !== 'undefined') {
cmnts[index].from_user_id = ''+cmnts[index].from.id;
cmnts[index].from_user_name = cmnts[index].from.name;
if (page_id === cmnts[index].from.id) {
verificaRespuestas(token, nombreSyst, page_id, cmnts[index], function(esrespuesta){
if (esrespuesta !== 'ok') {
console.log('verificaRespuesta '+esrespuesta);
}
});
}
}
else {
cmnts[index].from_user_id = 'not_available';
}
guardaBaseComment(token, nombreSyst, page_id, altacuenta, cmnts[index], function(resp){
if(resp === 'error' || resp === 'existe') {
return insertandoComments(nombreSyst, token, page_id, post_id, altacuenta, cmnts, more, callback);
}
else {
// console.log('insertamos');
obtieneCommentsdeComment(token, cmnts[index], function(tienecomments) {
if (tienecomments !== 'error') {
procesaCommentsdecom(nombreSyst, token, page_id, cmnts[index], altacuenta, _(tienecomments).reverse().value(), 0, function(commentsdecom){
console.log('solicitudes/getautomu/insertandoComments - comments del comment '+cmnts[index].id+' '+commentsdecom);
});
}
});
return insertandoComments(nombreSyst, token, page_id, post_id, altacuenta, cmnts, more, callback);
}
});
}
else{
console.log('solicitudes/getautomu/insertandoComments - comment raro, venía undefined');
return insertandoComments(nombreSyst, token, page_id, post_id, altacuenta, cmnts, more, callback);
}
});
}
}
function insertaPost(nombreSistema, post, page_id, callback) {
var criterio = {'id': post.id};
classdb.existefind(nombreSistema+'_consolidada', criterio, 'solicitudes/getautomu/insertaPost', function(existe){
if (existe === 'error' || existe === 'existe') {
return callback(existe);
}
else {
var fotopath = globales.fbapiversion+post.from.id+'/picture?redirect=false';
requestGraph(fotopath, function(foto) {
if (foto === 'error') {
post.foto = '';
classdb.inserta(nombreSistema+'_consolidada', post, 'solicitudes/getautomu/insertaPost', function(inserta) {
if (post.from && page_id !== post.from.id) {
nueMens(post.created_time, 'post', nombreSistema);
}
return callback(inserta);
});
}
else {
post.foto = foto.data.url;
classdb.inserta(nombreSistema+'_consolidada', post, 'solicitudes/getautomu/guardaBaseMensaje', function(inserta) {
if (post.from && page_id !== post.from.id) {
nueMens(post.created_time, 'post', nombreSistema);
}
return callback(inserta);
});
}
});
}
});
}
function postDeFeed(post, nombreSistema, pagid, altacta, callback) {
var created_time = '';
if (typeof post.created_time !== 'undefined') {
created_time = new Date(post.created_time.replace('+','.'));
}
else {
post.created_time = new Date();
}
if (created_time !== '' && Date.parse(created_time) > Date.parse(altacta)) {
var post_id = post.id;
var comments = [];
post.created_old = post.created_time;
post.created_time = created_time;
if (typeof post.updated_time !== 'undefined') {
post.updated_time = new Date(post.updated_time.replace('+','.'));
}
post.obj = 'facebook';
post.coleccion = nombreSistema+'_consolidada';
post.tipo = 'post';
post.subtipo = post.type;
if (typeof post.attachments !== 'undefined' &&
typeof post.attachments.data !== 'undefined' &&
post.attachments.data[0].length > 0 &&
typeof post.attachments.data[0].media !== 'undefined' &&
typeof post.attachments.data[0].media.image !== 'undefined' &&
typeof post.attachments.data[0].media.image.src !== 'undefined') {
post.image_attachment = post.attachments.data[0].media.image.src;
}
if (typeof post.attachments !== 'undefined' &&
typeof post.attachments.data !== 'undefined' &&
post.attachments.data[0].length > 0 &&
typeof post.attachments.data[0].target !== 'undefined' &&
typeof post.attachments.data[0].target.url !== 'undefined') {
post.link_attachment = post.attachments.data[0].target.url;
}
if (typeof post.from !== 'undefined') {
post.from_user_id = ''+post.from.id;
post.from_user_name = post.from.name;
}
else {
console.log('ERROR: post anónimo, investigar más:');
console.log(post);
return callback('error');
}
insertaPost(nombreSistema, post, pagid, function(postInsertado) {
if (postInsertado === 'error') { return callback('error'); } else { return callback('ok'); }
});
}
}
function procesaFeed(nameSystem, page_token, pageid, alta_cta, elfeed, index, callback) {
if (index !== parseInt(index, 10) || typeof index === 'undefined' || index === null) {
index = 0;
}
var more = index+1;
var cuantosp = elfeed.length;
if (more > cuantosp) {
return callback('getautomu ok');
}
else {
setImmediate(function(){
if (typeof elfeed[index] !== 'undefined' && typeof elfeed[index].id !== 'undefined') {
postDeFeed(elfeed[index], nameSystem, pageid, alta_cta, function(elpost) {
if (elpost === 'error') {
return procesaFeed(nameSystem, page_token, pageid, alta_cta, elfeed, more, callback);
}
else {
if (typeof elfeed[index].comments !== 'undefined'){
var postid = elfeed[index].id;
var loscomentarios = _(elfeed[index].comments.data).reverse().value();
insertandoComments(nameSystem, page_token, pageid, postid, alta_cta, loscomentarios, 0, function(loscomments){
if (loscomments === 'insertc_fin_ok') {
return procesaFeed(nameSystem, page_token, pageid, alta_cta, elfeed, more, callback);
}
else {
return procesaFeed(nameSystem, page_token, pageid, alta_cta, elfeed, more, callback);
}
});
}
else {
return procesaFeed(nameSystem, page_token, pageid, alta_cta, elfeed, more, callback);
}
}
});
}
else {
return procesaFeed(nameSystem, page_token, pageid, alta_cta, elfeed, more, callback);
}
});
}
}
function obtieneFeeds(accounts, accountTokens, index, callback) {
var more = index+1;
var cuantasctas = accounts.length;
if (more > cuantasctas) {
return callback('feeds ok');
}
else {
setImmediate(function(){
if (typeof accounts[index] !== 'undefined') {
var indice = accounts[index];
var acc_elements = indice.split('*|*');
var nombreSistema = acc_elements[0];
var page_id = acc_elements[1];
var fecha_alta_cta = acc_elements[2];
var cta_access_tokens = accountTokens[indice];
var access_token = cta_access_tokens[Math.floor(Math.random()*cta_access_tokens.length)];
var derpath = globales.fbapiversion+page_id+globales.path_feed_limit+'&access_token='+access_token;
var derpathwol = globales.fbapiversion+page_id+globales.path_feed_nolimit+'&access_token='+access_token;
requestGraph(derpath, function(thefeed){
if (thefeed === 'error' || typeof thefeed.data === 'undefined' || thefeed.data.length < 1) {
console.log('solicitudes/getautomu/obtieneFeeds - Error al conseguir feed con limite para: '+nombreSistema);
requestGraph(derpathwol, function(thefeedwol) {
if (thefeedwol === 'error' || typeof thefeedwol.data === 'undefined' || thefeedwol.data.length < 1) {
console.log('solicitudes/getautomu/obtieneFeeds - Error al conseguir feed sin limite para: '+nombreSistema);
return obtieneFeeds(accounts, accountTokens, more, callback);
}
else {
procesaFeed(nombreSistema, access_token, page_id, fecha_alta_cta, _(thefeedwol.data).reverse().value(), 0, function(procesafeed){
console.log(nombreSistema+' '+procesafeed);
return obtieneFeeds(accounts, accountTokens, more, callback);
});
}
});
}
else {
procesaFeed(nombreSistema, access_token, page_id, fecha_alta_cta, _(thefeed.data).reverse().value(), 0, function(procfeed){
console.log(nombreSistema+' '+procfeed);
return obtieneFeeds(accounts, accountTokens, more, callback);
});
}
});
}
else {
return obtieneFeeds(accounts, accountTokens, more, callback);
}
});
}
}
var ctascriterio = {$and: [{datosPage:{$exists: true}}, {datosPage: {$ne: ''}}, {'datosPage.id':{$exists: true}}]};
classdb.buscarToArray('accounts', ctascriterio, {nombreSistema: 1}, 'solicitudes/getautomu.main', function(cuentas){
console.log('**************** solicitudes/getautomu/GET - getFeeds de todas las cuentas conectadas a facebook *****************');
if (cuentas === 'error' || cuentas.length < 1) {
res.jsonp('error');
}
else {
obtieneUsuariosDeCuentas(cuentas, 0, [], {}, function(ctas, ctasusers){
checaAccessTokens(ctas, ctasusers, 0, [], {}, function(accts, acctks) {
obtieneFeeds(accts, acctks, 0, function(resultado) {
console.log('getautomu ok');
});
var texti = 'se pedirán feeds para: '+accts.join();
res.jsonp(texti);
});
});
}
});
});
module.exports = router;
|
angular.module('coderace.test', [])
.controller('testController', ['$scope', 'Race', function($scope, Race){
Race.getLength();//first you invoke the function get length method inside the race factory to retireve the total numebr of tests in databse
$scope.$on('GotLength', function(event, data){//once we recieved the length from the database, we trigger event listener
$scope.tests = Race.dataRef.child('Challenges').push();
$scope.send = function(){ //once the user hits the submit button, the contents will be sent to the database
$scope.tests.set(
{
functionName: $scope.nameContent,
question: $scope.questionContent,
inputs: JSON.parse($scope.inputContent),
answers: JSON.parse($scope.outputContent),
startingCode: $scope.startContent
}
);
//after we sent the database all of our data, we make the input bar an empty string to clear out the data so the user can send soemthing new if they wish
$scope.nameContent = "";
$scope.questionContent = "";
$scope.inputContent = "";
$scope.outputContent = "";
$scope.startContent = "";
}
})
}]);
|
/** @module transaction */
var crypto = require("./crypto.js"),
constants = require("../constants.js"),
slots = require("../time/slots.js");
/**
* @static
* @param {string} recipientId
* @param {number} amount
* @param {string|null} vendorField
* @param {ECPair|string} secret
* @param {ECPair|string} [secondSecret]
* @returns {Transaction}
*/
function createTransaction(recipientId, amount, vendorField, secret, secondSecret) {
if (!recipientId || !amount || !secret) return false;
if(!crypto.validateAddress(recipientId)){
throw new Error("Wrong recipientId");
}
var keys = secret;
if (!crypto.isECPair(secret)) {
keys = crypto.getKeys(secret);
}
if (!keys.publicKey) {
throw new Error("Invalid public key");
}
var transaction = {
type: 0,
amount: amount,
fee: constants.fees.send,
recipientId: recipientId,
timestamp: slots.getTime(),
asset: {}
};
if(vendorField){
transaction.vendorField=vendorField;
if(transaction.vendorField.length > 64){
return null;
}
}
transaction.senderPublicKey = keys.publicKey;
crypto.sign(transaction, keys);
if (secondSecret) {
var secondKeys = secondSecret;
if (!crypto.isECPair(secondSecret)) {
secondKeys = crypto.getKeys(secondSecret);
}
crypto.secondSign(transaction, secondKeys);
}
transaction.id = crypto.getId(transaction);
return transaction;
}
module.exports = {
createTransaction: createTransaction
}
|
describe('RESTAURANT', () => {
let restaurantService, $httpBackend, URLS
let restaurants = mockData.getMockRestaurants()
beforeEach(angular.mock.module('app'))
beforeEach(angular.mock.module('app.restaurant'))
beforeEach(inject((_$httpBackend_, _restaurantService_, _URLS_) => {
restaurantService = _restaurantService_
$httpBackend = _$httpBackend_
URLS = _URLS_
}))
describe('getRestaurants()', () => {
it('restaurantService should be defined', () => {
expect(restaurantService).toBeDefined()
})
it('should hit the correct url', () => {
$httpBackend
.when('GET', URLS.RESTAURANTS)
.respond(200, restaurants)
restaurantService.getRestaurants()
.then((response) => {
expect(response).toBeDefined()
expect(response.status).toEqual(200)
expect(response.data).toEqual(restaurants)
})
$httpBackend.flush()
})
it('should handle request errors', () => {
$httpBackend
.when('GET', URLS.RESTAURANTS)
.respond(500, 'Error ocurred')
restaurantService.getRestaurants()
.then((response) => {
expect(response).toBeDefined()
expect(response.status).toEqual(500)
expect(response.data).toEqual('Error ocurred')
})
$httpBackend.flush()
})
})
})
|
var searchData=
[
['freeglut',['FreeGLUT',['../group__module__freeglut.html',1,'']]]
];
|
import React from 'react';
import { mount } from 'enzyme';
import { JSDOM } from 'jsdom';
import styled from 'styled-components';
// SuT
import ContentEditable from '../react-sane-contenteditable';
// jsDOM
const doc = new JSDOM('<!doctype html><html><body></body></html>');
const mockedRange = {
cloneRange: jest.fn(() => mockedRange),
collapse: jest.fn(),
selectNodeContents: jest.fn(),
setEnd: jest.fn(),
setStart: jest.fn(),
// toString: jest.fn(),
};
global.document = doc;
global.window = doc.defaultView;
global.document.getSelection = jest.fn(() => ({
addRange: jest.fn(),
getRangeAt: jest.fn(() => mockedRange),
rangeCount: 0,
removeAllRanges: jest.fn(),
}));
global.document.createRange = jest.fn(() => mockedRange);
// Helpers
const focusThenBlur = (wrapper, element = 'div') =>
wrapper
.find(element)
.simulate('focus')
.simulate('blur');
// Styled components
const Wrapper = styled.div``;
describe('Default behaviour', () => {
it('renders a div by default', () => {
const wrapper = mount(<ContentEditable />);
expect(wrapper.childAt(0)).toHaveLength(1);
});
it('sets contentEditable', () => {
const wrapper = mount(<ContentEditable />);
expect(wrapper.childAt(0).prop('contentEditable')).toBe(true);
});
it('sets a default style', () => {
const wrapper = mount(<ContentEditable />);
expect(wrapper.childAt(0).prop('style')).toHaveProperty('whiteSpace', 'pre-wrap');
});
it('onInput sets state.value', () => {
const mockHandler = jest.fn();
const wrapper = mount(<ContentEditable content="foo" onChange={mockHandler} />);
const nextInput = 'foo bar';
wrapper.childAt(0).simulate('input', { target: { innerText: nextInput } });
expect(mockHandler.mock.calls).toHaveLength(1);
expect(mockHandler.mock.calls[0][1]).toBe(nextInput);
});
});
describe('Handles props', () => {
it('renders a tagName', () => {
const tag = 'p';
const wrapper = mount(<ContentEditable tagName={tag} />);
expect(wrapper.find(tag)).toHaveLength(1);
});
it('spreads in the style prop', () => {
const wrapper = mount(<ContentEditable style={{ color: 'blue' }} />);
expect(wrapper.childAt(0).prop('style')).toMatchObject({
whiteSpace: 'pre-wrap',
color: 'blue',
});
});
it('renders the props.content', () => {
const content = 'foo';
const wrapper = mount(<ContentEditable content={content} />);
expect(wrapper.childAt(0).text()).toEqual(content);
});
it('renders an updated props.content', () => {
const content = 'foo';
const nextContent = 'foo bar';
const wrapper = mount(<ContentEditable content={content} />);
wrapper.setProps({ content: nextContent });
expect(wrapper.render().text()).toEqual(nextContent);
});
it('toggles "contentEditable" when props.editable={false}', () => {
const wrapper = mount(<ContentEditable editable={false} />);
expect(wrapper.childAt(0).prop('contentEditable')).toBe(false);
});
it('attributes and customProps are passed down', () => {
const wrapper = mount(<ContentEditable foo="bar" />);
expect(wrapper.childAt(0).prop('foo')).toEqual('bar');
});
it('props.styled={false} sets ref handler', () => {
const wrapper = mount(<ContentEditable />);
expect(wrapper.instance().ref).toBeTruthy();
});
it('props.styled={true} sets innerRef handler', () => {
const wrapper = mount(<ContentEditable styled tagName={Wrapper} />);
expect(wrapper.childAt(0).prop('innerRef')).toEqual(expect.any(Function));
});
it('props.content change updates state', () => {
const content = '';
const nextContent = 'foo';
const wrapper = mount(<ContentEditable content={content} />);
wrapper.setProps({ content: nextContent });
expect(wrapper.state('value')).toEqual(nextContent);
});
it('props.focus sets focus on update', () => {
const wrapper = mount(<ContentEditable focus />);
const instance = wrapper.instance();
const ref = instance.ref;
jest.spyOn(ref, 'focus');
instance.componentDidMount();
expect(ref.focus).toHaveBeenCalled();
});
it('renders the props.content respecting maxLength={5} on mount', () => {
const wrapper = mount(<ContentEditable content="foo bar" maxLength={5} />);
expect(wrapper.childAt(0).text()).toEqual('foo b');
});
it('props.focus sets default value for state.caretPosition on mount', () => {
const wrapper = mount(<ContentEditable content="foo" focus />);
expect(wrapper.state('caretPosition')).toEqual(0);
});
it('props.focus & props.caretPosition=end sets state.caretPosition on mount', () => {
const wrapper = mount(<ContentEditable caretPosition="end" content="foo" focus />);
expect(wrapper.state('caretPosition')).toEqual(3);
});
it('props.caretPosition sets state.caretPosition on update', () => {
const wrapper = mount(<ContentEditable caretPosition="start" content="foo" focus />);
expect(wrapper.state('caretPosition')).toEqual(0);
wrapper.setProps({ caretPosition: 'end' });
expect(wrapper.state('caretPosition')).toEqual(3);
});
it('props.focus=false sets state.caretPosition=null on mount', () => {
const wrapper = mount(<ContentEditable content="foo" focus={false} />);
expect(wrapper.state('caretPosition')).toEqual(null);
});
it('props.focus=false sets state.caretPosition=null on update', () => {
const wrapper = mount(<ContentEditable content="foo" focus={false} />);
wrapper.setProps({ content: 'foo bar' });
expect(wrapper.state('caretPosition')).toEqual(null);
});
});
describe('Handles selections', () => {
const mockedSelection = global.document.getSelection();
afterEach(() => {
global.document.getSelection = jest.fn(() => mockedSelection);
});
it('sets state.caretPosition correctly when rangeCount > 0', () => {
const startOffset = 4;
const endOffset = 7;
const content = 'foo-bar';
const nextContent = 'foo-';
global.document.getSelection = jest.fn(() => ({
...mockedSelection,
rangeCount: 1,
getRangeAt: jest.fn(() => ({
...mockedRange,
cloneRange: jest.fn(() => ({
...mockedRange,
toString: jest.fn(() => ({ length: startOffset })),
})),
endOffset,
startOffset,
})),
}));
const wrapper = mount(<ContentEditable content={content} focus />);
wrapper.childAt(0).simulate('input', { target: { innerText: nextContent } });
expect(wrapper.state('caretPosition')).toEqual(startOffset);
expect(wrapper.text()).toEqual(nextContent);
});
});
describe('Sanitisation', () => {
it('does not sanitise when props.sanitise={false}', () => {
const content = 'foo bar';
const wrapper = mount(<ContentEditable content={content} sanitise={false} />);
expect(wrapper.state('value')).toEqual(content);
});
it('removes ', () => {
const wrapper = mount(<ContentEditable content="foo bar" />);
expect(wrapper.text()).toEqual('foo bar');
});
// it('trims leading & trailing whitespace', () => {
// const wrapper = mount(<ContentEditable content=" foo " />);
//
// expect(wrapper.state('value')).toEqual('foo');
// });
it('trims leading & trailing whitespace of each line', () => {
const content = ' foo \n bar ';
const wrapper = mount(<ContentEditable content={content} multiLine />);
expect(wrapper.state('value')).toEqual('foo\nbar');
});
it('removes multiple spaces', () => {
const mockHandler = jest.fn();
const wrapper = mount(<ContentEditable content="foo bar" onChange={mockHandler} />);
expect(wrapper.state('value')).toEqual('foo bar');
});
it('replaces line terminator characters with a space', () => {
const mockHandler = jest.fn();
const content = 'foo\nbar';
const wrapper = mount(<ContentEditable content={content} onChange={mockHandler} />);
expect(wrapper.state('value')).toEqual('foo bar');
});
it('value trimmed when maxLength exceeded', () => {
const maxLength = 5;
const content = 'foo bar';
const wrapper = mount(<ContentEditable content={content} maxLength={maxLength} />);
expect(wrapper.state('value')).toHaveLength(maxLength);
});
it('replaces unicode spaces', () => {
const unicodeChars = [
'\u00a0',
'\u2000',
'\u2001',
'\u2002',
'\u2003',
'\u2004',
'\u2005',
'\u2006',
'\u2007',
'\u2008',
'\u2009',
'\u200a',
'\u200b',
'\u2028',
'\u2029',
'\u202e',
'\u202f',
'\u3000',
].join('');
const wrapper = mount(<ContentEditable content={`foo ${unicodeChars}bar`} />);
expect(wrapper.text()).toEqual('foo bar');
});
it('calls sanitise prop when provided', () => {
const content = 'foo';
const nextContent = 'foo bar';
const sanitise = jest.fn(value => value);
const wrapper = mount(<ContentEditable content={content} />);
wrapper.setProps({ content: nextContent, sanitise });
expect(sanitise).toHaveBeenCalledWith(nextContent, mockedRange);
});
describe('with props.multiLine', () => {
it('limits consecutive line terminator characters to a maximum of 2', () => {
const wrapper = mount(<ContentEditable content={'foo\n\n\nbar'} multiLine />);
expect(wrapper.text()).toEqual('foo\n\nbar');
});
it('removes multiple spaces maintaining newlines', () => {
const wrapper = mount(
<ContentEditable content={'foo bar\f\f \r\rbaz\nqux\t\t quux\v\v quuz'} multiLine />,
);
expect(wrapper.text()).toEqual('foo bar baz\nqux quux quuz');
});
it('replaces ASCII spaces and feeds', () => {
const wrapper = mount(
<ContentEditable content={'foo\f\f bar\r\r baz\t\t qux\v\v quux'} multiLine />,
);
expect(wrapper.text()).toEqual('foo bar baz qux quux');
});
xdescribe('Failing tests to fix in component', () => {
// @todo @fixme: Component should probably be fixed so that this test passes,
// given that it uses dangerouslySetInnerHTML
// the naming of props.sanitise suggests that it will protect against this.
it('protects against XSS input', () => {
const mockHandler = jest.fn();
const content = 'foo';
const wrapper = mount(<ContentEditable content={content} onChange={mockHandler} />);
wrapper.instance()._element.innerText = `foo
<script>console.log('XSS vulnerability')</script>`;
focusThenBlur(wrapper);
expect(wrapper.state('value')).toEqual(content);
});
});
});
});
describe('Calls handlers', () => {
it('props.innerRef called', () => {
const mockHandler = jest.fn();
mount(<ContentEditable innerRef={mockHandler} />);
expect(mockHandler).toHaveBeenCalled();
});
it('props.onBlur called', () => {
const mockHandler = jest.fn();
const content = 'foo';
const wrapper = mount(<ContentEditable content={content} onBlur={mockHandler} />);
wrapper.childAt(0).simulate('blur');
expect(mockHandler).toHaveBeenCalledWith(
expect.objectContaining({
type: 'blur',
}),
content,
);
});
it('props.onChange called', () => {
const mockHandler = jest.fn();
const wrapper = mount(<ContentEditable content="foo" onChange={mockHandler} />);
const nextInput = 'foo bar';
wrapper.childAt(0).simulate('input', { target: { innerText: nextInput } });
expect(mockHandler.mock.calls).toHaveLength(1);
expect(mockHandler.mock.calls[0][1]).toBe(nextInput);
});
it('props.onKeyDown called', () => {
const mockHandler = jest.fn();
const content = 'foo';
const wrapper = mount(<ContentEditable content={content} onKeyDown={mockHandler} />);
wrapper.childAt(0).simulate('keydown', { key: 'Enter', target: { innerText: content } });
expect(mockHandler).toHaveBeenCalledWith(
expect.objectContaining({
type: 'keydown',
nativeEvent: expect.any(Object),
}),
content,
);
});
it('props.onKeyUp called', () => {
const mockHandler = jest.fn();
const content = '';
const nextContent = 'f';
const wrapper = mount(<ContentEditable content={content} onKeyUp={mockHandler} />);
wrapper.childAt(0).simulate('keyup', { target: { innerText: nextContent } });
expect(mockHandler).toHaveBeenCalledWith(
expect.objectContaining({
type: 'keyup',
nativeEvent: expect.any(Object),
}),
nextContent,
);
});
it('onKeyDown event.preventDefault called when maxLength exceeded', () => {
const mockPreventDefault = jest.fn();
const content = 'foo bar';
const wrapper = mount(<ContentEditable content={content} maxLength={content.length} />);
wrapper.childAt(0).simulate('keydown', {
key: 'Enter',
preventDefault: mockPreventDefault,
target: { innerText: content },
});
expect(mockPreventDefault).toHaveBeenCalled();
});
it('onKeyDown (enter) handles caret with multiLine value', () => {
const content = 'foobar';
const nextContent = 'foo\nbar';
const caretPosition = 3;
const wrapper = mount(<ContentEditable content={content} multiLine />);
const instance = wrapper.instance();
// Mock caret and range
jest.spyOn(instance, 'getCaret').mockImplementation(() => caretPosition);
jest.spyOn(instance, 'getRange').mockImplementation(() => ({
...mockedRange,
startOffset: caretPosition,
endOffset: caretPosition,
}));
wrapper.childAt(0).simulate('keydown', { keyCode: 13, target: { innerText: content } });
expect(wrapper.state()).toEqual({ caretPosition: caretPosition + 1, value: nextContent });
});
it('onKeyDown (enter) handles caret with multiLine at end of value', () => {
const content = 'foo';
const nextContent = 'foo\n\n';
const caretPosition = 3;
const wrapper = mount(<ContentEditable content={content} multiLine />);
const instance = wrapper.instance();
// Mock caret and range
jest.spyOn(instance, 'getCaret').mockImplementation(() => caretPosition);
jest.spyOn(instance, 'getRange').mockImplementation(() => ({
...mockedRange,
startOffset: caretPosition,
endOffset: caretPosition,
}));
wrapper.childAt(0).simulate('keydown', { keyCode: 13, target: { innerText: content } });
expect(wrapper.state()).toEqual({ caretPosition: caretPosition + 1, value: nextContent });
});
it('onKeyDown (enter) handles caret (at linebreak) with multiLine value', () => {
const content = 'foo\nbar';
const nextContent = 'foo\n\nbar';
const caretPosition = 3;
const wrapper = mount(<ContentEditable content={content} multiLine />);
const instance = wrapper.instance();
// Mock caret and range
jest.spyOn(instance, 'getCaret').mockImplementation(() => caretPosition);
jest.spyOn(instance, 'getRange').mockImplementation(() => ({
...mockedRange,
startOffset: caretPosition,
endOffset: caretPosition,
}));
wrapper.childAt(0).simulate('keydown', { keyCode: 13, target: { innerText: content } });
expect(wrapper.state()).toEqual({ caretPosition: caretPosition + 1, value: nextContent });
});
it('onKeyDown (enter) triggers blur when props.multiLine = false', () => {
const content = 'foobar';
const wrapper = mount(<ContentEditable content={content} />);
const instance = wrapper.instance();
const onBlur = (instance.ref.blur = jest.fn());
wrapper.childAt(0).simulate('keydown', { keyCode: 13, target: { innerText: content } });
expect(onBlur).toHaveBeenCalled();
});
it('props.onChange not called when maxLength exceeded', () => {
const mockHandler = jest.fn();
const wrapper = mount(<ContentEditable content="foo" maxLength={3} onChange={mockHandler} />);
wrapper.childAt(0).simulate('input', { target: { innerText: 'foob' } });
expect(mockHandler).not.toHaveBeenCalled();
});
it('props.onPaste called', () => {
const mockOnPaste = jest.fn().mockName('onPaste');
const mockExecCommand = jest.fn().mockName('execCommand');
const mockGetClipboardData = jest.fn().mockName('getClipboardData');
const content = 'foo';
const wrapper = mount(<ContentEditable content={content} onPaste={mockOnPaste} />);
const nextInput = 'bar';
wrapper.instance().ref.innerText = '';
document.execCommand = mockExecCommand;
mockGetClipboardData.mockReturnValue(nextInput);
wrapper.childAt(0).simulate('paste', {
clipboardData: { getData: mockGetClipboardData },
});
expect(mockOnPaste).toHaveBeenCalledWith(nextInput);
});
});
|
/**
* API Setup
*/
var
utils = require("../utils"),
mongoose = require("mongoose"),
Content = mongoose.model("Content");
/**
* Get Contents of Content
*/
exports.getContents = function (req, res) {
var
userId = req.cookies ? req.cookies.userId : undefined,
userIdObj = {userId : userId},
contentSortStr = "-updateStamp";
Content
.find(userIdObj)
.sort(contentSortStr)
.exec(function (err, contents) {
if (err) {
return next(err);
}
res.send({
contents : contents
});
});
};
/**
* Create Content
*/
exports.create = function (req, res, next) {
var
content,
contentConfig;
contentConfig = {
userId : req.cookies.userId,
content : req.body.title,
updateStamp : Date.now()
};
content = new Content(contentConfig);
content.save(function (err, content, count) {
if (err) {
return next(err);
}
res.redirect("/");
});
};
/**
* Edit Content
*/
exports.edit = function (req, res, next) {
var
userId = req.cookies ? req.cookies.userId : undefined,
userIdObj = {userId : userId},
contentSortStr = "-updateStamp";
Content.
find(userIdObj).
sort(contentSortStr).
exec(function (err, contents) {
if (err) {
return next(err);
}
res.send({
contents : contents,
});
});
};
/**
* Update Content
*/
exports.update = function (req, res, next) {
Content.findById(req.params.id, function (err, content) {
var userId = req.cookies ? req.cookies.userId : undefined;
/*if (content.userId !== userId) {
return utils.forbidden(res);
}*/
content.content = req.body.content;
content.updateStamp = Date.now();
content.save(function (err, content, count) {
if (err) {
return next(err);
}
res.redirect("/");
});
});
};
/**
* Destroy Content
*/
exports.destroy = function (req, res, next) {
Content.findById( req.params.id, function (err, content) {
var userId = req.cookies ?
req.cookies.userId : undefined;
/*if (content.userId !== req.cookies.userId) {
return utils.forbidden( res );
}*/
content.remove(function (err, content) {
if (err) {
return next(err);
}
res.redirect("/");
});
});
};
/**
* Set Current User
*/
exports.setCurrentUser = function (req, res, next) {
var userId = req.cookies ? req.cookies.userId : undefined;
if (!userId) {
res.cookie("userId", utils.uid(32));
}
next();
}; |
'use strict';
angular.module('whateverApp')
.directive('dialog', function () {
return {
templateUrl: "views/offcosui/dialog.html",
restrict: 'E',
replace: true,
transclude: true,
controller: ["$scope", "$element","$timeout", function ($scope, $element, $timeout) {
$scope.isShow = false;
$scope.selfValue = $scope.value
$scope.$on("valueChange", function (e, value) {
$scope.selfValue = value;
});
$scope.openDialog = function(message, okCb, cancelCb) {
$scope.title = $scope.title || "提示";
if ( message ) {
var html = '<div class="custom-message">' + message + '</div>';
$element.find(".dialog-content").html(html);
}
if ( typeof okCb == "function" ) {
$scope.alertOk = function() {
var ret = okCb();
if ( ret !== false ) {
delete $scope.alertOk;
}
return ret;
}
}
if ( typeof cancelCb == "function" ) {
$scope.alertCancel = function() {
var ret = cancelCb();
if ( ret !== false ) {
delete $scope.alertCancel;
}
return ret;
}
}
$scope.$broadcast("onOpen");
$scope.isShow = true;
};
$scope.$on("opendialog", function() {
$scope.$broadcast("onOpen");
$scope.isShow = true;
});
$scope.$on("closedialog", function () {
$scope.close();
});
$scope.onOk = function () {
var ret = true;
$scope.$emit("onOk", $scope.selfValue);
if( $scope.alertOk ) {
ret = $scope.alertOk();
}
if(ret !== false) {
$scope.close();
}
};
$scope.onCancel = function () {
var ret = true;
$scope.$emit("onCancel");
if( $scope.alertCancel ) {
ret = $scope.alertCancel();
}
if(ret !== false) {
$scope.close();
}
};
$scope.close = function () {
$timeout( function () {
$scope.isShow = false;
$scope.$broadcast("onClose");
}, 500);
delete $scope.alertOk;
delete $scope.alertCancel;
};
}],
link: function postLink(scope, element, attrs) {
scope.type = element.attr("type");
element.click( function ( e ) {
return false;
});
}
};
});
|
var assert = require('assert');
var fs = require('fs');
module.exports = function () {
this.World = require('../support/world.js').World;
// path to visit is set (but we still need to add the parameters to check)
this.Given('I visit "$path"', function (path, callback) {
this.fullPath = this.baseUrl + path;
callback();
});
// add a parameter to check
this.Given('the parameter "$param" is "$val"', function (param, val, callback) {
this.params = this.params || [];
this.params.push({ p: param, v: val });
callback();
});
// compile all parameters and the path to visit, then visit it
this.Given('the page loads', function (callback) {
var browser = this.browser;
// set the path parameters
var full = this.fullPath;
if (this.hasOwnProperty('params')){
if (this.params.length > 0){
var para = this.params[0];
full = full + '?' + para.p + '=' + para.v;
for (var i = 1; i < this.params.length; i++){
para = this.params[i];
full = full + '&' + para.p + '=' + para.v;
}
}
}
browser
.get(full)
.nodeify(callback);
});
this.Given('I go to "$path"', function(path, callback){
this.browser
.get(this.baseUrl + path)
.nodeify(callback);
});
// form fill
this.When('I fill out form "$id"', function (id, callback) {
var mktoForm = this.mktoForm;
var regex = /^\d+/;
var form;
if (regex.exec(id)){
form = this.form = mktoForm + id;
}
else {
form = this.form = id;
}
this.timestamp = (new Date).getTime(); // timestamp for test
var browser = this.browser;
browser
.waitForElementByCss(form + " div", 5000) // wait for the form to load
.nodeify(callback);
});
this.Given('I fill field "$field" as "$value" with timestamp', function(field, value, callback){
var form = this.form;
if (field.toLowerCase().indexOf('email') >= 0){
var email = value.split('@');
value = email[0] + '+' + this.timestamp + '@' + email[1];
}
else {
value = value + this.timestamp;
}
this.browser
.elementByCss(form + ' ' + field).type(value)
.nodeify(callback);
});
this.Given('I fill field "$field" as "$value"', function(field, value, callback){
var form = this.form;
var selector = form + ' ' + field;
this.browser
.elementByCss(selector).type(value)
.nodeify(callback);
});
this.Given('I select field "$field" as "$value"', function(field, value, callback){
var form = this.form;
var selector = form + ' ' + field;
this.browser
.elementByCss(selector).click()
.elementByCss(selector + ' option[value="' + value + '"]').click()
.nodeify(callback);
});
this.Given('I click "$selector"', function(selector, callback){
this.browser
.elementByCss(selector)
.click()
.nodeify(callback);
});
this.Then('I click submit', function(callback){
var form = this.form;
this.browser
.elementByCss(form + ' [type="submit"]')
.click()
.nodeify(callback);
});
// end on thank you page
this.Then('I\'m taken to "$path"', function (path, callback) {
this.browser
.setAsyncScriptTimeout(10000);
this.browser
.waitForCondition('window.location.href.indexOf(\'' + path + '\') > 0', 10000)
.nodeify(callback);
});
};
|
#!/usr/bin/env node
'use strict';
const u = require('install-here/util');
const ih = require('install-here/core');
const mp = require('./core.js');
const a = require('yargs').argv;
u.compose()
.use(mp.init(a, ih))
.use(mp.checkMyPak)
.use(mp.checkOptions)
.use(mp.checkPackage)
.use(ih.retrievePackageVersion)
.use(ih.checkVersion)
.use(ih.checkTest)
.use(ih.deleteTempPath)
.use(ih.createTempPath)
.use(mp.execPre(ih))
.use(ih.install)
.use(mp.checkInfo)
.use(mp.checkPak)
.use(mp.checkPackageJson)
.use(ih.delete)
.use(ih.replace)
.use(ih.replaceDep)
.use(ih.deleteTempPath)
.use(ih.checkGitIgnore)
.use(ih.saveSettings)
.use(mp.execPost(ih))
.run(ih.report);
// mypack >>> aggiorna il package
// mypack mpk-sections-site --name rds >>> installa il package con il nome |
define({
"name": "Documentação - Node Task API",
"template": {
"forceLanguage": "pt_br"
},
"version": "1.0.0",
"description": "API de gestão de tarefas",
"sampleUrl": false,
"apidoc": "0.2.0",
"generator": {
"name": "apidoc",
"time": "2016-12-08T11:34:50.853Z",
"url": "http://apidocjs.com",
"version": "0.16.1"
}
});
|
define(['jquery','datepicker'], function (jQuery) {
/* Azerbaijani (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Jamil Najafov (necefov33@gmail.com). */
jQuery(function($) {
$.datepicker.regional['az'] = {
closeText: 'Bağla',
prevText: '<Geri',
nextText: 'İrəli>',
currentText: 'Bugün',
monthNames: ['Yanvar','Fevral','Mart','Aprel','May','İyun',
'İyul','Avqust','Sentyabr','Oktyabr','Noyabr','Dekabr'],
monthNamesShort: ['Yan','Fev','Mar','Apr','May','İyun',
'İyul','Avq','Sen','Okt','Noy','Dek'],
dayNames: ['Bazar','Bazar ertəsi','Çərşənbə axşamı','Çərşənbə','Cümə axşamı','Cümə','Şənbə'],
dayNamesShort: ['B','Be','Ça','Ç','Ca','C','Ş'],
dayNamesMin: ['B','B','Ç','С','Ç','C','Ş'],
weekHeader: 'Hf',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['az']);
});
}); |
"use strict";
var helpers = require("../../helpers/helpers");
exports["Australia/Brisbane"] = {
"guess:by:offset" : helpers.makeTestGuess("Australia/Brisbane", { offset: true }),
"guess:by:abbr" : helpers.makeTestGuess("Australia/Brisbane", { abbr: true }),
"1916" : helpers.makeTestYear("Australia/Brisbane", [
["1916-12-31T14:00:59+00:00", "00:00:59", "AEST", -600],
["1916-12-31T14:01:00+00:00", "01:01:00", "AEDT", -660]
]),
"1917" : helpers.makeTestYear("Australia/Brisbane", [
["1917-03-24T14:59:59+00:00", "01:59:59", "AEDT", -660],
["1917-03-24T15:00:00+00:00", "01:00:00", "AEST", -600]
]),
"1941" : helpers.makeTestYear("Australia/Brisbane", [
["1941-12-31T15:59:59+00:00", "01:59:59", "AEST", -600],
["1941-12-31T16:00:00+00:00", "03:00:00", "AEDT", -660]
]),
"1942" : helpers.makeTestYear("Australia/Brisbane", [
["1942-03-28T14:59:59+00:00", "01:59:59", "AEDT", -660],
["1942-03-28T15:00:00+00:00", "01:00:00", "AEST", -600],
["1942-09-26T15:59:59+00:00", "01:59:59", "AEST", -600],
["1942-09-26T16:00:00+00:00", "03:00:00", "AEDT", -660]
]),
"1943" : helpers.makeTestYear("Australia/Brisbane", [
["1943-03-27T14:59:59+00:00", "01:59:59", "AEDT", -660],
["1943-03-27T15:00:00+00:00", "01:00:00", "AEST", -600],
["1943-10-02T15:59:59+00:00", "01:59:59", "AEST", -600],
["1943-10-02T16:00:00+00:00", "03:00:00", "AEDT", -660]
]),
"1944" : helpers.makeTestYear("Australia/Brisbane", [
["1944-03-25T14:59:59+00:00", "01:59:59", "AEDT", -660],
["1944-03-25T15:00:00+00:00", "01:00:00", "AEST", -600]
]),
"1971" : helpers.makeTestYear("Australia/Brisbane", [
["1971-10-30T15:59:59+00:00", "01:59:59", "AEST", -600],
["1971-10-30T16:00:00+00:00", "03:00:00", "AEDT", -660]
]),
"1972" : helpers.makeTestYear("Australia/Brisbane", [
["1972-02-26T15:59:59+00:00", "02:59:59", "AEDT", -660],
["1972-02-26T16:00:00+00:00", "02:00:00", "AEST", -600]
]),
"1989" : helpers.makeTestYear("Australia/Brisbane", [
["1989-10-28T15:59:59+00:00", "01:59:59", "AEST", -600],
["1989-10-28T16:00:00+00:00", "03:00:00", "AEDT", -660]
]),
"1990" : helpers.makeTestYear("Australia/Brisbane", [
["1990-03-03T15:59:59+00:00", "02:59:59", "AEDT", -660],
["1990-03-03T16:00:00+00:00", "02:00:00", "AEST", -600],
["1990-10-27T15:59:59+00:00", "01:59:59", "AEST", -600],
["1990-10-27T16:00:00+00:00", "03:00:00", "AEDT", -660]
]),
"1991" : helpers.makeTestYear("Australia/Brisbane", [
["1991-03-02T15:59:59+00:00", "02:59:59", "AEDT", -660],
["1991-03-02T16:00:00+00:00", "02:00:00", "AEST", -600],
["1991-10-26T15:59:59+00:00", "01:59:59", "AEST", -600],
["1991-10-26T16:00:00+00:00", "03:00:00", "AEDT", -660]
]),
"1992" : helpers.makeTestYear("Australia/Brisbane", [
["1992-02-29T15:59:59+00:00", "02:59:59", "AEDT", -660],
["1992-02-29T16:00:00+00:00", "02:00:00", "AEST", -600]
])
}; |
/**
* Created by jibin on 17/7/10.
*/
import React, {Component} from 'react';
import AutosizeInput from '../src/component/AutosizeInput.js';
class TestAutoSizeInput extends Component{
constructor(){
super();
this.state = {
selectedValue : ''
};
}
onChange(event){
console.log(event.target.value);
this.setState({
selectedValue: event.target.value
});
}
render(){
return (
<div>
<AutosizeInput
value={this.state.selectedValue}
onChange={this.onChange.bind(this)}
placeholder="请选择"
placeholderIsMinWidth={true}
/>
</div>
);
}
}
export default TestAutoSizeInput; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.