code
stringlengths 2
1.05M
|
|---|
module.exports = {
name: 'drifter',
version: '1.0.0-beta',
/*
certificate: '',
key: '',
formatters: {
},
spdy: {
}
*/
}
|
Template.card.created = function() {
// TODO: Ugly hack, make it beautiful and safe
var cardType = this.view.parentView.name.split(".")[1];
if(Template[cardType + "Details"] === undefined) {
console.error("Card details template '" + cardType + "Details', doesn't exist");
} else {
TemplateVar.set(this, "cardType", cardType);
}
};
Template.card.helpers({
error: "",
showDetails: function() {
return this.singleCard ? true : TemplateVar.get("showDetails");
},
detailsTemplate: function() {
return Template[TemplateVar.get("cardType") + "Details"];
},
cardType: function() {
return TemplateVar.get("cardType");
}
});
Template.card.events({
"click #showDetails": function(e, template) {
TemplateVar.set(template, "showDetails", !TemplateVar.get("showDetails"));
}
});
|
import compareTranspiled from "./compareTranspiled";
const tests = {
'should change relative paths': "examples/<dir>/relative2relative",
'should change relative paths dynamically': "examples/<dir>/relative2relativeD",
'should change path from a node module to relative': "examples/<dir>/module2relative",
'should dynamically change path from a node module to relative': "examples/<dir>/module2relativeD",
'should change path from a node module to a different node module': "examples/<dir>/module2module",
'should dynamically change path from a node module to a different node module': "examples/<dir>/module2moduleD",
'should change path from relative to a node module': "examples/<dir>/relative2module",
'should dynamically change path from relative to a node module': "examples/<dir>/relative2moduleD",
'should not change when no matching redirect is found': "examples/<dir>/no_match",
'should change even when': {
'file at original relative path doesn\'t exist': "examples/<dir>/original_relative_not_exist",
'file at the final path doesn\'t exist': "examples/<dir>/final_relative_not_exist",
'module at original path doesn\'t exist': "examples/<dir>/original_module_not_exist",
'module at the final path doesn\'t exist': "examples/<dir>/final_module_not_exist"
}
};
export default function runTestsFor(decl) {
function describeTests(tests) {
Object.keys(tests).map(description => {
const dir = tests[description];
if(typeof dir === "object") {
describe(description, () => {
describeTests(dir);
});
} else {
test(description, () => {
return compareTranspiled(dir.replace("<dir>", decl));
});
}
});
}
describeTests(tests);
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:364f6e85f525b75afac578bd6814b307a83724d568792f22c5a305739fd9dc70
size 135328
|
import React from "react";
import renderer from "react-test-renderer";
import Button from "./Button";
it("renders correctly", () => {
expect(renderer.create(<Button>Submit</Button>).toJSON()).toMatchSnapshot();
});
|
var classblackbone_1_1_m_map =
[
[ "MMap", "classblackbone_1_1_m_map.html#a73dce850d2a2b9949c3bcb6ac1ac9abe", null ],
[ "~MMap", "classblackbone_1_1_m_map.html#af0d82aa41970f29d53dfc92ada2beefa", null ],
[ "Cleanup", "classblackbone_1_1_m_map.html#a34bc7201d03a51463824d81b2e68c3b6", null ],
[ "MapImage", "classblackbone_1_1_m_map.html#ac32ee99111f95b472fb95834657f0ac7", null ],
[ "MapImage", "classblackbone_1_1_m_map.html#a5454130bc294fe50ecd63a881ef7917e", null ],
[ "reset", "classblackbone_1_1_m_map.html#af662672364ee90cef246b719b5691ee0", null ],
[ "UnmapAllModules", "classblackbone_1_1_m_map.html#ab2c907908d1db59db079d4d2bfe4dc13", null ]
];
|
/*
* This file is part of the Exposure package.
*
* Copyright 2013 by Sébastien Pujadas
*
* For the full copyright and licence information, please view the LICENCE
* file that was distributed with this source code.
*/
$("a[data-op='bookmark-remove']").click(function(e) {
e.preventDefault() ;
var listItem = $(this).closest('li') ;
var postData = "token=" + $(this).closest('ul').data('token')
+ "&project_id=" + $(this).data("project-id")
+ "&action=project_bookmark_remove" ;
$.post("/", postData, function(result) {
if (result === true) {
listItem.fadeOut() ;
}
});
}) ;
$("a[data-op='bookmark-add']").click(function(e) {
e.preventDefault() ;
var link = $(this) ;
var postData = "token=" + link.data('token')
+ "&project_id=" + link.data('project-id')
+ "&action=project_bookmark_add" ;
$.post("/", postData, function(result) {
if (result === true) {
$('#sponsor-bookmark').text(link.data('success')) ;
}
});
}) ;
|
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.resource("posts");
this.resource("simple");
});
export default Router;
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("a11yhelp", "pt-br", {title: "Instruções de Acessibilidade", contents: "Conteúdo da Ajuda. Para fechar este diálogo pressione ESC.", legend: [
{name: "Geral", items: [
{name: "Barra de Ferramentas do Editor", legend: "Pressione ${toolbarFocus} para navegar para a barra de ferramentas. Mova para o anterior ou próximo grupo de ferramentas com TAB e SHIFT-TAB. Mova para o anterior ou próximo botão com SETA PARA DIREITA or SETA PARA ESQUERDA. Pressione ESPAÇO ou ENTER para ativar o botão da barra de ferramentas."},
{name: "Diálogo do Editor", legend: "Dentro de um diálogo, pressione TAB para navegar para o próximo campo, pressione SHIFT + TAB para mover para o campo anterior, pressione ENTER para enviar o diálogo, pressione ESC para cancelar o diálogo. Para diálogos que tem múltiplas abas, pressione ALT + F10 para navegar para a lista de abas, então mova para a próxima aba com SHIFT + TAB ou SETA PARA ESQUERDA. Pressione ESPAÇO ou ENTER para selecionar a aba."},
{name: "Menu de Contexto do Editor", legend: "Pressione ${contextMenu} ou TECLA DE MENU para abrir o menu de contexto, então mova para a próxima opção com TAB ou SETA PARA BAIXO. Mova para a anterior com SHIFT+TAB ou SETA PARA CIMA. Pressione ESPAÇO ou ENTER para selecionar a opção do menu. Abra o submenu da opção atual com ESPAÇO ou ENTER ou SETA PARA DIREITA. Volte para o menu pai com ESC ou SETA PARA ESQUERDA. Feche o menu de contexto com ESC."},
{name: "Caixa de Lista do Editor", legend: "Dentro de uma caixa de lista, mova para o próximo item com TAB ou SETA PARA BAIXO. Mova para o item anterior com SHIFT + TAB ou SETA PARA CIMA. Pressione ESPAÇO ou ENTER para selecionar uma opção na lista. Pressione ESC para fechar a caixa de lista."},
{name: "Barra de Caminho do Elementos do Editor", legend: "Pressione ${elementsPathFocus} para a barra de caminho dos elementos. Mova para o próximo botão de elemento com TAB ou SETA PARA DIREITA. Mova para o botão anterior com SHIFT+TAB ou SETA PARA ESQUERDA. Pressione ESPAÇO ou ENTER para selecionar o elemento no editor."}
]},
{name: "Comandos", items: [
{name: " Comando Desfazer", legend: "Pressione ${undo}"},
{name: " Comando Refazer", legend: "Pressione ${redo}"},
{name: " Comando Negrito", legend: "Pressione ${bold}"},
{name: " Comando Itálico", legend: "Pressione ${italic}"},
{name: " Comando Sublinhado", legend: "Pressione ${underline}"},
{name: " Comando Link", legend: "Pressione ${link}"},
{name: " Comando Fechar Barra de Ferramentas", legend: "Pressione ${toolbarCollapse}"},
{name: " Access previous focus space command", legend: "Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},
{name: " Access next focus space command", legend: "Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},
{name: " Ajuda de Acessibilidade", legend: "Pressione ${a11yHelp}"}
]}
]});
|
var getPublication = function (slug) {
var pub = Publications.findOne({slug: slug});
if (pub) {
return pub;
}
};
/*****************************************************************************/
/* Detail: Event Handlers */
/*****************************************************************************/
Template.PublicationDetail.events({
});
/*****************************************************************************/
/* Detail: Helpers */
/*****************************************************************************/
Template.PublicationDetail.helpers({
publication: function () {
publication = getPublication(Router.current().params.slug);
if (publication) {
return publication;
}
}
});
/*****************************************************************************/
/* Detail: Lifecycle Hooks */
/*****************************************************************************/
Template.PublicationDetail.created = function () {
};
Template.PublicationDetail.rendered = function () {
var publication = getPublication(Router.current().params.slug);
if (!publication) return;
Meteor.call('trackEvent', 'VIEW', 'Publication', publication);
};
Template.PublicationDetail.destroyed = function () {
};
|
var searchData=
[
['ide',['ide',['../structmob__settings.html#af49f35b823927e40978d94b1f7d42a29',1,'mob_settings']]]
];
|
import './MatchListItem.scss';
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import moment from 'moment';
import { connect } from 'react-redux';
import Icon from '../Icon.js';
import MatchEdit from '../MatchEdit/MatchEdit';
import { updateMatch, deleteMatch } from '../../actions/index';
class MatchListItem extends Component {
static contextTypes = {
router: PropTypes.object
};
constructor () {
super();
this.state = { edit: false, loading: false }
}
onSubmit (match) {
const { date, home_team, location, quest_team, start } = match;
var saveData = {
match_id: this.props.match._id,
date: moment(`${match.date} ${match.start}`, "DD.MM.YYYY HH:mm").format(),
location
};
if (home_team != this.props.match.home_team.team_id) {
saveData.home_team = home_team;
}
if (quest_team != this.props.match.quest_team.team_id) {
saveData.quest_team = quest_team;
}
this.setState({ loading: true });
this.props.updateMatch({ ...saveData }).then((data) => {
this.setState({ edit: !this.state.edit, loading: false });
this.context.router.push(`/match/${data.payload.data.match._id}`);
});
}
toogleActive () {
this.setState({ edit: !this.state.edit });
}
deleteHandler () {
const { match, deleteMatch } = this.props;
this.setState({ loading: true });
deleteMatch({ id: match._id });
}
render () {
const { match } = this.props;
const matchItemRender = () => {
if (this.state.edit) {
return (
<MatchEdit
onSubmit={ this.onSubmit.bind(this) }
onCancel={ this.toogleActive.bind(this) }
title="Edit match"
btn="Save"
match={{ ...match }}
loading={ this.state.loading }
onDelete={ this.deleteHandler.bind(this) }
/>
);
} else {
return (
<div className="info">
<Link to={ `/match/${match._id}` } className="link">
<span className="logos">
<img src={ `./images/${ match.home_team.team_id }.jpg` } alt=""/>
<img src={ `./images/${ match.quest_team.team_id }.jpg` } alt=""/>
</span>
<span className="name">
{ `${ match.home_team.team_name } – ${ match.quest_team.team_name }` }
</span>
<span className="desc">
{ `${ match.location.label } | ${ moment(match.date).format('DD.MM.YYYY HH:mm') }` }
</span>
</Link>
<div className="controls">
<a className="control" onClick={ this.toogleActive.bind(this) }><Icon name="pencil" /></a>
<Link className="control" to={ `/export/${match._id}` }><Icon name="pdf" /></Link>
</div>
</div>
);
}
};
return (
<div className="match-list-item">
{ matchItemRender() }
</div>
);
}
}
function mapStateToProps(state) {
return { };
}
export default connect(mapStateToProps, { updateMatch, deleteMatch })(MatchListItem);
|
var app = app || {};
(function(){
app.TestButton = React.createClass({displayName: "TestButton",
handleClick: function() {
this.props.submitTestTask(this.props.btnType);
},
render: function() {
return ( React.createElement("button", {onClick: this.handleClick,
className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) );
}
});
app.CodeEditor = React.createClass({displayName: "CodeEditor",
handleType:function(){
this.props.updateCode(this.editor.session.getValue());
},
componentDidMount:function(){
this.editor = ace.edit("codeeditor");
this.editor.setTheme("ace/theme/clouds");
this.editor.setOptions({
fontSize: "1.2em"
});
this.editor.session.setMode("ace/mode/"+this.props.language);
},
render:function(){
return (
React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType})
);
}
});
app.TokenEditor = React.createClass({displayName: "TokenEditor",
handleChange:function(){
var new_token = this.refs.tokenInput.value;
this.props.updateToken(new_token);
},
render: function(){
return (
React.createElement("input", {className: "input-url", onChange: this.handleChange, ref: "tokenInput", placeholder: "Input Server Access Token"})
);
}
});
app.UrlEditor = React.createClass({displayName: "UrlEditor",
getInitialState: function(){
return {
url_vaild:true
}
},
handleChange:function(){
//if url valid, update state, if not, warn
var url_str = this.refs.urlInput.value;
if (app.isUrl(url_str)){
this.setState({url_vaild:true});
//this.probs.updateUrl(url_str)
}else{
this.setState({url_vaild:false});
}
this.props.updateUrl(url_str);
},
classNames:function(){
return 'input-url ' + ((this.state.url_vaild) ? 'input-right':'input-error');
},
render: function(){
return (
React.createElement("input", {className: this.classNames(), onChange: this.handleChange, ref: "urlInput", placeholder: "Type Server or App URL"})
);
}
});
var ServerList = app.ServerList = React.createClass({displayName: "ServerList",
getInitialState:function(){
return {chosedServer:-1, currentDisplay:"Servers",servers:[]};
},
componentDidMount:function(){
//get server list
this.serverRequest = $.get('http://localhost:8000/home/servers', function (result) {
if( result.isSuccessful ){
this.setState({servers:result.servers});
}
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
onServerClick:function(event){
this.props.updateServer(event.currentTarget.dataset.serverid);
this.setState({currentDisplay:event.currentTarget.dataset.servername});
},
render:function(){
return (
React.createElement("div", {className: "dropdown server-list"},
React.createElement("button", {ref: "menu_display", className: "btn btn-default dropdown-toggle", type: "button", id: "dropdownMenu1", "data-toggle": "dropdown"},
this.state.currentDisplay,
React.createElement("span", {className: "caret"})
),
React.createElement("ul", {className: "dropdown-menu", role: "menu", "aria-labelledby": "dropdownMenu1"},
this.state.servers.map(function(server){
return React.createElement("li", {role: "presentation"}, React.createElement("a", {"data-serverName": server.name, "data-serverid": server.id, onClick: this.onServerClick, role: "menuitem", tabindex: "-1", href: "#"}, server.name))
}.bind(this))
)
)
);
}
})
var ResultDisplay = app.ResultDisplay = React.createClass({displayName: "ResultDisplay",
getInitialState:function(){
return {'level':-1, test_type:'', 'steps':[]}
},
emptyCurrentDisplay:function(){
this.setState({steps:[]});
},
displayResult:function(res_dict){
console.log(res_dict);
var test_type = res_dict.test_type
var test_type_str = ''
if( test_type == 0 ){
test_type_str = 'Genomics Standard Test'
}else if( test_type == 1 ){
test_type_str = 'Application Test'
}else{
test_type_str = 'Custom Server Test'
}
this.setState({'test_type':test_type_str})
if (test_type == 0){
this.setState({'level':res_dict.level});
}
this.setState({'steps':res_dict['steps']});
},
render: function(){
return (
React.createElement("div", {className: "result-container"},
React.createElement("div", {className: "result-head"}, React.createElement("span", {className: "area-title area-title-black"}, "Test Type: ", this.state.test_type), " ", React.createElement("span", null)),
React.createElement("div", {className: "detail-result"},
React.createElement("div", {className: "result-sum"},
this.state.test_type == 0 ? React.createElement("h3", null, "Level: ", this.state.level) : null
),
this.state.steps.map(function(step){
return React.createElement(StepDisplay, {stepInfo: step})
})
)
)
)
}
});
var StepDisplay = app.StepDisplay = React.createClass({displayName: "StepDisplay",
getInitialState: function(){
return {
is_img_hide:true,
is_modal_show:false,
is_has_image:false,
is_detail_showing:false,
detail_desc:''
}
},
showDetail:function(desc){
if(this.state.detail_desc === desc){
this.setState({is_detail_showing:!this.state.is_detail_showing});
}else{
this.setState({detail_desc:desc, is_detail_showing:true});
}
},
componentDidMount:function(){
if(this.props.stepInfo.addi){
this.setState({is_has_image:true});
}
},
handleTextClick:function(){
if (this.state.is_has_image){
this.setState({is_img_hide:!this.state.is_img_hide});
}
},
handleShowFullImage:function(event){
event.stopPropagation();
this.setState({is_modal_show:true});
},
handleHideModal(){
this.setState({is_modal_show:false});
},
handleShowModal(){
this.setState({is_modal_show: true});
},
render:function(){
return (
React.createElement("div", {className: "step-brief step-brief-success", onClick: this.handleTextClick},
React.createElement("div", null, React.createElement("span", {className: "step-brief-text"}, this.props.stepInfo.desc)),
React.createElement("div", {className: "step-detail-area"},
React.createElement("div", {className: "detail-hint-block"},
this.props.stepInfo.details.map(function(detail){
return React.createElement(StepDetail, {status: detail.status, desc: detail.desc, showDetail: this.showDetail})
}, this)
),
this.state.is_detail_showing ? React.createElement("div", {className: "detail-desc-block"},
this.state.detail_desc
) : null
),
React.createElement("div", {hidden: this.state.is_img_hide && !this.state.is_has_image, className: "step-img-block"},
React.createElement("button", {onClick: this.handleShowFullImage, className: "btn btn-primary"}, "Full Image"),
React.createElement("img", {className: "img-responsive img-rounded step-img", src: this.props.stepInfo.addi})
),
this.state.is_modal_show && this.state.is_has_image ? React.createElement(Modal, {handleHideModal: this.handleHideModal, title: "Step Image", content: React.createElement(FullImageArea, {img_src: this.props.stepInfo.addi})}) : null
)
);
}
});
var StepDetail = app.StepDetail = React.createClass({displayName: "StepDetail",
classes:function(){
return 'btn' + this.props.status ? ' btn-success': ' btn-danger' + ' btn-circle';
},
onBtnClick:function(){
this.props.showDetail(this.props.desc);
},
render:function(){
return (
React.createElement("button", {onClick: this.onBtnClick, className: this.props.status ? 'btn btn-circle btn-success': 'btn btn-circle btn-danger'}, this.props.status ? 'P' : 'F')
)
}
})
app.UserBtnArea = React.createClass({displayName: "UserBtnArea",
handleLogout:function(){
app.showMsg("Logout");
},
render:function(){
return (
React.createElement("div", {className: "user-op"},
React.createElement("button", {className: "btn btn-user", onClick: this.props.history_action}, "History"),
React.createElement("button", {className: "btn btn-user", onClick: this.props.search_action}, "Search Task"),
React.createElement("button", {className: "btn btn-user", onClick: this.handleLogout}, React.createElement("span", {className: "glyphicon glyphicon-off"}))
)
);
}
});
var FullImageArea = app.FullImageArea = React.createClass({displayName: "FullImageArea",
render:function(){
return(
React.createElement("img", {src: this.props.img_src, className: "img-responsive"})
);
}
});
var TaskItem = app.TaskItem = React.createClass({displayName: "TaskItem",
handleClick:function(){
this.props.itemClicked(this.props.task_id);
},
render:function(){
return (
React.createElement("div", {className: "list-item", onClick: this.handleClick},
React.createElement("span", null, "Task ID: "), this.props.task_id,
React.createElement("span", {className: "pull-right"}, " Time: ", this.props.task_time)
)
);
}
});
var TaskList = app.TaskList = React.createClass({displayName: "TaskList",
render:function(){
return (
React.createElement("div", {className: "task-list"},
React.createElement("div", {className: "list-content"},
this.props.tasks.map(function(task_info){
return React.createElement(TaskItem, {itemClicked: this.props.fetchTaskDetail, task_id: task_info.task_id, task_time: task_info.time})
},this)
)
)
);
}
});
var TaskSearchView = app.TaskSearchView = React.createClass({displayName: "TaskSearchView",
getInitialState:function(){
return {keywords:'', tasks:[]}
},
onUserInput:function(){
var self = this;
var postData = {
'keyword':this.refs.keywordField.value
}
$.ajax({
url:'http://localhost:8000/home/search',
type:'POST',
data:JSON.stringify(postData),
dataType:'json',
cache:false,
success:function(data){
if( data.isSuccessful ){
self.setState({tasks:data.tasks});
}
}
});
},
getTaskDetail:function(task_id){
this.refs.res_area.emptyCurrentDisplay();
console.log(task_id);
app.setup_websocket(task_id,2)
},
render:function(){
return (
React.createElement("div", {className: "task-search-area"},
React.createElement("input", {className: "input-url", placeholder: "Search Tasks...", ref: "keywordField", onChange: this.onUserInput}),
React.createElement("div", {className: "history-area"},
React.createElement(TaskList, {fetchTaskDetail: this.getTaskDetail, tasks: this.state.tasks}),
React.createElement(ResultDisplay, {ref: "res_area"})
)
)
)
}
});
var HistoryViewer = app.HistoryViewer = React.createClass({displayName: "HistoryViewer",
getInitialState:function(){
return {tasks:[]};
},
updateTestResult:function(res){
this.refs.res_area.displayResult(res);
},
componentDidMount:function(){
window.hist = this;
var postData = {
token:$.cookie('fhir_token')
};
var self = this;
console.log(postData);
$.ajax({
url:'http://localhost:8000/home/history',
type:'POST',
data:JSON.stringify(postData),
dataType:'json',
cache:false,
success:function(data){
if( data.isSuccessful ){
self.setState({tasks:data.tasks});
}
}
});
},
getTaskDetail:function(task_id){
this.refs.res_area.emptyCurrentDisplay();
console.log(task_id);
app.setup_websocket(task_id,2)
},
render:function(){
return (
React.createElement("div", {className: "history-area"},
React.createElement(TaskList, {fetchTaskDetail: this.getTaskDetail, tasks: this.state.tasks}),
React.createElement(ResultDisplay, {ref: "res_area"})
)
);
}
});
var Modal = app.Modal = React.createClass({displayName: "Modal",
componentDidMount(){
$(ReactDOM.findDOMNode(this)).modal('show');
$(ReactDOM.findDOMNode(this)).on('hidden.bs.modal', this.props.handleHideModal);
},
render:function(){
return (
React.createElement("div", {className: "modal modal-wide fade"},
React.createElement("div", {className: "modal-dialog"},
React.createElement("div", {className: "modal-content"},
React.createElement("div", {className: "modal-header"},
React.createElement("button", {type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close"}, React.createElement("span", {"aria-hidden": "true"}, "×")),
React.createElement("h4", {className: "modal-title"}, this.props.title)
),
React.createElement("div", {className: "modal-body"},
this.props.content
),
React.createElement("div", {className: "modal-footer text-center"},
React.createElement("button", {className: "btn btn-primary center-block", "data-dismiss": "modal"}, "Close")
)
)
)
)
);
}
});
})();
|
$(document).ready(function() {
$("#login").click(function(event){
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
login_auth(username,password);
});
$("#change-password").click(function(event){
event.preventDefault();
$(this).text('Sending..');
$('.error-same-pass').hide();
var confirm_password = $('#confirm_password').val();
var new_password = $('#new_password').val();
var userEmail = $('#userEmail').val();
var userID = $('#userID').val();
if(new_password == "" && confirm_password == ""){
$('#new_password').addClass('has-error');
$('#new_password').next().text("Password is required!");
$('#confirm_password').addClass('has-error');
$('#confirm_password').next().text("Confirm password is required!");
return false;
}else if(confirm_password == ""){
$('#confirm_password').addClass('has-error');
$('#confirm_password').next().text("Confirm password is required!");
return false;
}
if(new_password != confirm_password){
$('#confirm_password').addClass('has-error');
$('#confirm_password').next().text("Password does not match !");
return false;
}else {
var base_url = window.location.origin;
var host = window.location.host;
$.ajax({
url : base_url+"/wetalk/dashboard/password_reset",
method : "post",
data : {
new_password : new_password,
confirm_password : confirm_password,
userEmail : userEmail,
userID : userID
},
success : function (data) {
if(data == 'Message has been sent') {
$('#close-form').text('Close');
$('#change-password').css({'display' : 'none'});
$('.hide-form').css({'display' : 'none'});
$('.success-text').show();
$('.success-text').html('<div class="alert alert-success"><strong>Password has been updated!</strong></div> <br> <strong><em>Note :</em></strong><p> For security purposes, you need to check your email and confirm the changes that you made for your password. Otherwise, you will not be allowed to login if you don\'t confirm this change. Thanks.</p>')
} else {
$('.error-same-pass').show();
$('#change-password').text("Send");
$('.error-same-pass').text(data);
}
}
});
}
});
});
function clear_form(){
$('.form-group').show();
$('.success-text').hide();
$('#change-password').show();
$('#change-password').text("Send");
$('#close-form').text('Cancel');
$('#form')[0].reset();
$('.form-group').removeClass('has-error');
$('.form-group').show();
$('#confirm_password').val("");
$('#new_password').val("");
$('.help-block').empty();
$('#resetPassword').modal('hide');
}
function login_auth(user_name,user_password){
$.ajax({
url : "login/login_auth",
method : "post",
data : {
user_name : user_name,
user_password : user_password,
},
success : function (data) {
if(data == 'failed') {
$('.failed-login').show();
return false;
}
if(data == 'succeeded-admin') {
window.location.href = "dashboard";
}
if(data == 'succeeded-client'){
window.location.href = "profile";
}
return false;
}
});
}
$(document).ready(function() {
$("#login").click(function(event){
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
login_auth(username,password);
});
});
|
/**
* Master Controller
*/
angular.module('RDash')
.controller('MasterCtrl', ['$scope', '$cookieStore', '$http', '$window', MasterCtrl]);
function MasterCtrl($scope, $cookieStore, $http, $window) {
/**
* Sidebar Toggle & Cookie Control
*/
var mobileView = 992;
$scope.hideUserMenu = true;
$http.get("/auth/user")
.success(function(response){
$scope.userJSON = response;
if (response.profiles != null && response.profiles.length > 0){
$scope.hideUserMenu = false;
$scope.userFirstName = response.profiles[0].profile.displayName.split(" ")[0].toUpperCase();
$scope.currentUser = response;
}
});
if($window.innerWidth <= 540){
$scope.isMobile=true;
}
$scope.$watch(function(){
return $window.innerWidth;
}, function(value) {
if(value <= 540){
$scope.isMobile=true;
}else{
$scope.isMobile=false;
}
});
$scope.getWidth = function() {
return window.innerWidth;
};
$scope.$watch($scope.getWidth, function(newValue, oldValue) {
if (newValue >= mobileView) {
if (angular.isDefined($cookieStore.get('toggle'))) {
$scope.toggle = ! $cookieStore.get('toggle') ? false : true;
} else {
$scope.toggle = true;
}
} else {
$scope.toggle = false;
}
});
// $scope.drinkList=function() {
// angular.forEach($scope.drinks, function(drink, index){
// drink.expand=false;
// });
// };
$scope.toggleSidebar = function() {
$scope.toggle = !$scope.toggle;
$cookieStore.put('toggle', $scope.toggle);
};
window.onresize = function() {
$scope.$apply();
};
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const publicSuffixes = require("./public-suffixes");
/**
* Returns the apex domain (domain.com) from a subdomain (www.sub.domain.com)
*/
function apexDomain(domainName) {
const parts = domainName.split('.').reverse();
let curr = publicSuffixes;
const accumulated = [];
for (const part of parts) {
accumulated.push(part);
if (!(part in curr)) {
break;
}
curr = curr[part];
}
return accumulated.reverse().join('.');
}
exports.apexDomain = apexDomain;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbInV0aWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxvREFBcUQ7QUFFckQ7O0dBRUc7QUFDSCxTQUFnQixVQUFVLENBQUMsVUFBa0I7SUFDekMsTUFBTSxLQUFLLEdBQUcsVUFBVSxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQyxPQUFPLEVBQUUsQ0FBQztJQUU5QyxJQUFJLElBQUksR0FBUSxjQUFjLENBQUM7SUFFL0IsTUFBTSxXQUFXLEdBQWEsRUFBRSxDQUFDO0lBQ2pDLEtBQUssTUFBTSxJQUFJLElBQUksS0FBSyxFQUFFO1FBQ3RCLFdBQVcsQ0FBQyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDdkIsSUFBSSxDQUFDLENBQUMsSUFBSSxJQUFJLElBQUksQ0FBQyxFQUFFO1lBQUUsTUFBTTtTQUFFO1FBQy9CLElBQUksR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUM7S0FDckI7SUFDRCxPQUFPLFdBQVcsQ0FBQyxPQUFPLEVBQUUsQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLENBQUM7QUFDM0MsQ0FBQztBQVpELGdDQVlDIn0=
|
module.exports = (root) => {
const mongoose = root.mongoose;
const Schema = mongoose.Schema;
// create a schema
const yourSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
admin: Boolean,
location: String,
meta: {
age: Number,
website: String
},
created_at: Date,
updated_at: Date
});
// create a model using the schema
const yourModel = mongoose.model('yourModel', yourSchema);
module.exports = yourModel;
};
|
import React, { Component, PropTypes } from 'react';
import { Text, View, StyleSheet, TouchableWithoutFeedback } from 'react-native';
export default class Board extends Component {
static propTypes = {
size: PropTypes.number.isRequired,
showNotation: PropTypes.bool,
rowIndex: PropTypes.number.isRequired,
position: PropTypes.string.isRequired,
columnName: PropTypes.string.isRequired,
columnIndex: PropTypes.number.isRequired,
dimension: PropTypes.number.isRequired,
selected: PropTypes.bool,
canMoveHere: PropTypes.bool,
lastMove: PropTypes.bool,
inCheck: PropTypes.bool,
reverseBoard: PropTypes.bool,
onSelected: PropTypes.func.isRequired,
};
onSelected = () => {
const { position, onSelected } = this.props;
onSelected(position);
};
renderNotations(isBlack) {
const {
showNotation,
rowIndex,
columnIndex,
columnName,
dimension,
reverseBoard,
} = this.props;
const notations = [];
const transform = [
{
rotate: reverseBoard ? '180deg' : '0deg',
},
];
if (showNotation) {
if (columnIndex + 1 === dimension) {
notations.push(
<Text
key={'row_notations'}
style={[
styles.notation,
{
color: isBlack ? '#B58863' : '#F0D9B5',
top: 0,
right: 0,
transform,
},
]}
>
{dimension - rowIndex}
</Text>,
);
}
if (rowIndex + 1 === dimension) {
notations.push(
<Text
key={'column_notation'}
style={[
styles.notation,
{
color: isBlack ? '#B58863' : '#F0D9B5',
bottom: 0,
left: 0,
transform,
},
]}
>
{columnName}
</Text>,
);
}
}
return notations;
}
renderMoveIndicator() {
const { canMoveHere } = this.props;
if (canMoveHere) {
return <View style={styles.moveIndicator} />;
}
return null;
}
// verify if square is update before authorize new renderer
shouldComponentUpdate(nextProps, nextState) {
// check props dependencies square renderer
const {selected, lastMove, canMoveHere, inCheck, reverseBoard} = nextProps;
return (
selected !== this.props.selected ||
lastMove !== this.props.lastMove ||
canMoveHere !== this.props.canMoveHere ||
inCheck !== this.props.inCheck ||
reverseBoard !== this.props.reverseBoard
);
}
render() {
const {
size,
rowIndex,
columnIndex,
selected,
lastMove,
inCheck,
canMoveHere,
} = this.props;
const isBlack = (rowIndex + columnIndex) % 2 === 0;
let backgroundColor = isBlack ? '#F0D9B5' : '#B58863';
if (selected) {
backgroundColor = '#656E41';
} else if (lastMove) {
backgroundColor = '#CDD26B';
} else if (inCheck) {
backgroundColor = '#C51B16';
}
return (
<TouchableWithoutFeedback
onPress={this.onSelected}
disabled={!canMoveHere}
>
<View
style={[
styles.container,
{
backgroundColor,
width: size,
height: size,
},
]}
>
{this.renderMoveIndicator()}
{this.renderNotations(isBlack)}
</View>
</TouchableWithoutFeedback>
);
}
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
},
notation: {
position: 'absolute',
fontSize: 11,
fontWeight: 'bold',
},
moveIndicator: {
width: 24,
height: 24,
opacity: 0.3,
backgroundColor: '#208530',
borderRadius: 12,
},
});
|
//了解源码,要了解构造(实例化、原型链、原型链接续、继承机制),核心方法(init工厂方法)
var
// 框架内部通用的jQuery(document)的临时变量
rootjQuery,
// 1.8中DOM ready改成了deferred,这个是ready的执行列表
readyList,
// 使用当前window下的document (沙箱机制)
document = window.document,
location = window.location,
navigator = window.navigator,
// 映射 jQuery 以便重写,主要是在noConflict中用到(line 342)
_jQuery = window.jQuery,
// 映射 $ 以便重写,主要是在noConflict中用到(line 342)
_$ = window.$,
// 一些核心方法的映射,1.8以后,核心变量的变量名也做了优化,前面加了core_前缀
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
//注点1,这个对象准备被window.jQuery外放为jQuery全局变量,同时便于其它功能在其上扩展(如DOM,Event等)
jQuery = function( selector, context ) {
//注点1中调用时,自动构造jQuery对象,而这个jQuery对象,是jQuery.fn.init的一个实例化
//故jQuery实例对象,前面都是没有new的,就是在这里框架内部自动完成了实例化
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
/*
* 第四个有趣的延伸知识点:正则表达式
*
* @知识索引
* 正则表达式 http://www.cnblogs.com/deerchao/archive/2006/08/24/zhengzhe30fengzhongjiaocheng.html
*/
// 捕获1、html字符串(不能以#为前导,防止通过location.has进行xss攻击);2、#开头的id字符串
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// 匹配独立的html标签,标签闭合间没有文本,如<a>xxx</a>,中间有xxx不符合
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON转换用的正则表达式
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// 浏览器检测用正则表达式
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
//驼峰方法jQuery.camelCase中使用
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
/*
* jQuery.fn相当于jQuery.prototype的别名,指向的是同一份内容
* 第二个有趣的延伸知识点:js原型prototype
*
* @知识索引:
* 原型和继承:http://www.cnblogs.com/ljchow/archive/2010/06/08/1753526.html
* prototype和constructor:http://blog.csdn.net/niuyongjie/article/details/4810835
*
* @本处使用的作用
* 主要是为了一些core方法的扩展准备(此处只做init核心方法的注释,其它方法请查看api结合源码了解)。
* 注:按照prototype的概念,只有new jQuery的自身实例化能使用这里的方法,而jQuery对象,不是自身实例化,而是jQuery.fn.init的实例化,用不了这里的方法。
* 有上面的问题,故有后面的原型链接续,使jQuery对象能使用这里的方法
*/
jQuery.fn = jQuery.prototype = {
//构造器,便于内部使用this.constructor这种看起来超类继承的写法,更符合OOP思维
constructor: jQuery,
/*
*
* 第三个有趣的延伸知识点:设计模式之工厂模式
*
* @本处使用的作用
* 1)工厂模式的优点是一“家”工厂,解决各类生产需要,即一“个”jQuery对象,能分配各类调用需要
* 2)“单一”调用的写法,减少学习成本
* 3)jQuery不会因为不好预测使用者会给它传递什么参数,而导致自缚,便于后续扩展建立更多“子生产线”
* 4)使用者只需要关心在按照API要求使用情况下会得到期望结果,不需关心内部运作
*
*/
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// 根据selector不同,返回不同的值
// selector有以下7种分支情况:
// 1、""、null、undefined、false
// 2、DOM元素
// 3、body(优化寻找)1.7中还有,1.8没有,归到了4中,故这里源码没有
// 4、字符串:HTML标签、HTML字符串、#id、选择器表达式
// 5、函数(作为ready回调函数)
// 6、jQuery对象(因为有selector值)
// 7、其它
// 分支1, $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// 分支2, $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// 分支3、4, HTML strings
if ( typeof selector === "string" ) {
// 前后<>匹配,根据html标签规律,<>开闭之间有个标签名,故长度至少是3,节省正则开销
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// match是一个匹配用的变量数组,长度为3,html字符串则第2个有值,id字符串则第3个有值,故这里html字符串第2个有值
match = [ null, selector, null ];
} else {
//正则表达式应用,匹配,子表达式1、html字符串(不能以#为前导,防止通过location.has进行xss攻击);子表达式2、#开头的id字符串
//用了exec,故匹配结果为[整体匹配结果,子表达式1匹配结果,子表达式2匹配结果]
//如#id,匹配结果['#id',undefined,'id'],id字符串则第3个有值
//如<div>,["<div>","<div>",undefined],html字符串第2个有值,但这个结果会在上面分支中处理,不会进入这个分支
//如a<div>,["a<div>","<div>",undefined],html字符串第2个有值
//如#id<div>,结果null,方式location.hash中的xss攻击?
match = rquickExpr.exec( selector );
}
// match条件:
//1、selector为含<>闭合的合适字符串,即match[1]有值
//2、id字符串,但context有一定限制("",null,undefined,false),类似$('#content','#doc')、$('#content',DOMElement)不符合,因为id唯一,后面加上,有点画蛇添足?;
if ( match && (match[1] || !context) ) {
// 分支: html标签字符串,$('<tag>'),这里排除了#id
if ( match[1] ) {
//instanceof判断context是否是jQuery对象,是的话,取jQuery对象第一个
context = context instanceof jQuery ? context[0] : context;
//context ("",null,undefined,false) doc=document
//context (其它),如果context.ownerDocument存在(隐含条件,context为DOM节点,且在文档中),优先用这个,其次才是用context
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// 1.8中改进,将纯标签和html文本字符串两种情况,整合到了parseHTML方法中,1.7的话,实现还是在这块
// 同时scripts暂定true,为后续兼容准备
// parseHTML是转化html字符串为节点数组
selector = jQuery.parseHTML( match[1], doc, true );
//rsingleTag 如果是一个单一的标签(如<a></a>,中间没有html值,非<a>xxx</a>),且context是否纯对象,如果是,则作为新建标签的属性值
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
//merge方法是两个数组合并,合到第一个数组
return jQuery.merge( this, selector );
// 分支: id字符串,$("#id"),这里id使用原生的方法,故context无需画蛇添足
} else {
elem = document.getElementById( match[2] );
// 判断elem.parentNode,是为了黑莓4.6的取回的节点却不在document的特殊问题(#6963)
if ( elem && elem.parentNode ) {
// 判断getElementById返回结果,是否是id的值造成的。(IE和Opera下,name对getElementById也生效的问题)
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// 将结果注入jQuery对象中
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// 分支: context是("",null,undefined,false),或者jQuery对象的情况下,使用find方法(selector是正确的css选择器,则返回能匹配的结果,如果不是,则返回空结果,具体逻辑在find中)
} else if ( !context || context.jquery ) {
//如果("",null,undefined,false),则使用rootjQuery
//如果是jQuery对象,则用context
return ( context || rootjQuery ).find( selector );
// 分支: $(expr, context)
// 这里是context有值,且不为jQuery对象,所以要重新封装下
// 即使用 $(context).find(expr)
} else {
//使this.constructor( context )即jQuery( context )
return this.constructor( context ).find( selector );
}
// 分支: $(function)
// domready简写
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
//如果内部是个jQuery对象,那么不用再次封装,直接简单加工下内部的jQuery对象
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
//把一个像数组的对象(jQuery对象就是这种),处理成一个真实的数组
return jQuery.makeArray( selector, this );
},
// jQuery会记录当前选择器,初始为空
selector: "",
// jQuery当前版本,这里的值是1.8.2,1.9以后,这块使用前面定义的变量
jquery: "@VERSION",
// jQuery对象的长度属性
length: 0,
// jQuery对象的长度方法
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// 将jQuery对象的fn(即prototype)赋给实例化用的init函数的prototype,使得最后返回的jQuery对象的值拥有init中的this以及fn中的值
// 这里是框架中非常重要的一环
// 此处进行了原型链接续,原本,jQuery实例对象,因为它是jQuery.fn.init的实例化,故只能拥有init中的this以及自己的原型链(没有接续前是空)
// 这里这个操作,把jQuery的原型链(fn是原型链别名)接给了jQuery.fn.init,故最后的jQuery实例对象,拥有了init中的this以及自己的原型链(这时候接上了jQuery的原型链)
// 注意,后续被扩展在jQuery原型链上的,也会被jQuery实例对象拥有(如jQuery.extend等)
jQuery.fn.init.prototype = jQuery.fn;
//继承是面向对象中一种非常重要的概念,这里是jQuery的一个实现方案
//jQuery.extend为jQuery本体静态方法扩展入口,jQuery.fn.extend为jQuery实例扩展入口
//这里两种不能的继承基于同一个方法,但是却为后续框架两种扩展留下入口
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
//target是传入的第一个值,表示需要应用继承的目标对象
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// 如果target是boolean(那明显不是需要应用继承的目标对象)
if ( typeof target === "boolean" ) {
//deep用传入值
deep = target;
//target用传入的第二个值,没有则空对象
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// 如果target不是对象且不是函数,那么target是一个空对象{}
// 可能是一个字符串或者其它(可能是一个深层拷贝)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// 进入这个分支的只有1===1(第一个参数有值,且不是boolean)和2===2(第一个是boolean,第二个也有值)
// 只有应用的目标对象,却无参考对象,奇怪?
// 其实不奇怪,这里是jQuery自我继承用的
if ( length === i ) {
//target等于this,即该方法调用者,适应后面jQuery.extend({})的用法,即this为jQuery
target = this;
//自减,这样后面能进一次循环
--i;
}
//从参数有效target之后,开始循环(不包括有效target,jQuery自调用时,有效target变为jQuery,原来的target变为参考对象)
//参考对象可能是多个,故要一个个进行循环,故后面的参考对象,会重新覆盖前面的参考对象同名值
for ( ; i < length; i++ ) {
// 只处理非null和undefined
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// 防止无限循环的死锁,即参考对象中的值又指向目标对象,等于目标对象不停拷贝自己
if ( target === copy ) {
continue;
}
// 启用了deep深层拷贝,且copy非""、null、undefined、false且满足copy(数组或者纯对象)其中的一种情况
// 深层拷贝数组、纯对象
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
//如果是数组
if ( copyIsArray ) {
//重置,使得下次进入时,还能启用外层判断
copyIsArray = false;
//判断目标对象中的原值是否是数组,如果是,克隆目标对象是原值,如果不是,则变为空数组
clone = src && jQuery.isArray(src) ? src : [];
} else {
//判断目标对象中的原值是否是纯对象,如果是,克隆目标对象是原值,如果不是,则变为空的纯对象
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// 递归调用,深层拷贝
target[ name ] = jQuery.extend( deep, clone, copy );
// 非数组、非纯对象,且非null和undefined的其它情况(包括""、false等),这里简单数据结构,不需做深层拷贝,故deep不需要
} else if ( copy !== undefined ) {
//target中对象name的值更新为copy中的值
target[ name ] = copy;
}
}
}
}
// 返回修改后的对象
return target;
};
//这里是扩展在jQuery本体的一些静态方法
jQuery.extend({
//防止和其它框架冲突的方法,使用见api
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// 判断DOM ready是否已经可用,如果已经ready,那么该值会变成true
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// DOM ready也是写在core里面的,1.8以后,这里改成了基于Deffered实现
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
// 如果已经ready 或者 等待状态,但不等于1(1自减1后等于0,即false,非1为true)
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// 确认body存在,为了防止IE下的自作聪明的先帮你完成了,故用了个计时器重新检测,直到body存在(ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// 记录DOM 已经ready的状态
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// 后续代码列表
// 回调对象 Callback(line 985~1211)
// 延迟对象 Deferred(line 1214~1356)
// 浏览器特性检测 Support(line 1359~1662)
// 数据缓存 Data(line 1665~2030)
// 队列 queue(line 2033~2211)
// 属性操作 Attribute(line 2214~2868)
// 事件处理 Event(line 2871~3937)
// 选择器 Sizzle(line 3937~5394)
// DOM遍历 Traversing(line 5395~5716)
// DOM操作 Manipulation(line 5719~6550)
// CSS操作 (line 6553~6967)
// 异步请求 Ajax(line 6970~8358)
// 动画 FX(line 8361~9269)
// 坐标和可视窗口(line 9270~9379)
|
const expect = require('chai').expect
const Poison = require('../lib/poison')
suite('poison', function () {
test('default', function (done) {
var p = new Poison(done)
expect(p.phase).to.be.equal('incoming')
expect(p.isEnabled()).to.be.true
p.handler()()
})
test('state', function (done) {
var p = new Poison(done)
expect(p.isEnabled()).to.be.true
p.disable()
expect(p.isEnabled()).to.be.false
p.enable()
p.handler()()
})
test('nested rule', function (done) {
var p = new Poison(directive)
var req = {}
p.rule(rule)
p.handler()(req, null)
function directive(req, res, next) {
expect(req.rule).to.be.true
done()
}
function rule(req, res, next) {
req.rule = true
next()
}
})
})
|
/*syn@0.4.2#mouse.support*/
define(function (require, exports, module) {
var syn = require('./synthetic');
require('./mouse');
(function checkSupport() {
if (!document.body) {
return syn.schedule(checkSupport, 1);
}
window.__synthTest = function () {
syn.support.linkHrefJS = true;
};
var div = document.createElement('div'), checkbox, submit, form, select;
div.innerHTML = '<form id=\'outer\'>' + '<input name=\'checkbox\' type=\'checkbox\'/>' + '<input name=\'radio\' type=\'radio\' />' + '<input type=\'submit\' name=\'submitter\'/>' + '<input type=\'input\' name=\'inputter\'/>' + '<input name=\'one\'>' + '<input name=\'two\'/>' + '<a href=\'javascript:__synthTest()\' id=\'synlink\'></a>' + '<select><option></option></select>' + '</form>';
document.documentElement.appendChild(div);
form = div.firstChild;
checkbox = form.childNodes[0];
submit = form.childNodes[2];
select = form.getElementsByTagName('select')[0];
syn.trigger(form.childNodes[6], 'click', {});
checkbox.checked = false;
checkbox.onchange = function () {
syn.support.clickChanges = true;
};
syn.trigger(checkbox, 'click', {});
syn.support.clickChecks = checkbox.checked;
checkbox.checked = false;
syn.trigger(checkbox, 'change', {});
syn.support.changeChecks = checkbox.checked;
form.onsubmit = function (ev) {
if (ev.preventDefault) {
ev.preventDefault();
}
syn.support.clickSubmits = true;
return false;
};
syn.trigger(submit, 'click', {});
form.childNodes[1].onchange = function () {
syn.support.radioClickChanges = true;
};
syn.trigger(form.childNodes[1], 'click', {});
syn.bind(div, 'click', function onclick() {
syn.support.optionClickBubbles = true;
syn.unbind(div, 'click', onclick);
});
syn.trigger(select.firstChild, 'click', {});
syn.support.changeBubbles = syn.eventSupported('change');
div.onclick = function () {
syn.support.mouseDownUpClicks = true;
};
syn.trigger(div, 'mousedown', {});
syn.trigger(div, 'mouseup', {});
document.documentElement.removeChild(div);
syn.support.pointerEvents = syn.eventSupported('pointerdown');
syn.support.touchEvents = syn.eventSupported('touchstart');
syn.support.ready++;
}());
});
|
var async = require('async')
var db = require('../db')
var expect = require('chai').expect
var rimraf = require('rimraf')
describe('db', function() {
var dbi
var nonExistantEmail = 'test@example.com'
var existantEmail = 'test-exists@example.com'
var password = 'test123'
var data = { some:"data" }
after(function(done) {
rimraf('level-userdb.db', function() { done() })
})
before(function(done) {
rimraf('level-userdb.db', function() {
dbi = db()
dbi.addUser(existantEmail, password, data, function() {
done()
})
})
})
it('should export correct API', function(done) {
var methods = ['findUser', 'addUser', 'checkPassword', 'changeEmail',
'changePassword', 'deleteUser', 'modifyUser']
methods.forEach(function(method) {
expect(dbi).property(method)
})
done()
})
describe('#findUser', function() {
it('should return NotFoundError on missing user', function(done) {
dbi.findUser(nonExistantEmail, function(err, user) {
expect(err).to.have.property('name', 'NotFoundError')
done()
})
})
it('should return user a well-formed user object for existing user', function(done) {
dbi.findUser(existantEmail, function(err, user) {
expect(err).to.be.null
// verify the metadata is stored
expect(user.data).eql(data)
// verify we parse the ISO8601 timestamps back to JS
expect(user.modifiedDate).to.be.a('Date')
expect(user.createdDate).to.be.a('Date')
// verify we hash the password
expect(user.password).to.not.eql(password)
// verify we have the email in the user object
expect(user.email).to.eql(existantEmail)
done()
})
})
})
describe('#checkPassword', function() {
it('should not error on password match', function(done) {
dbi.checkPassword(existantEmail, password, function(err, res) {
expect(err).to.be.null
expect(res).to.have.property('password')
done()
})
})
it('should throw error on password mis-match', function(done) {
dbi.checkPassword(existantEmail, "BADPASSWORD", function(err, res) {
expect(err).to.eql("password mismatch")
expect(res).to.be.false
done()
})
})
})
describe('#changeEmail', function() {
var origEmail = 'orig@example.com'
var newEmail = 'new@example.com'
var origModifiedTimestamp
var newModifiedTimestamp
before(function(done) {
dbi.addUser(origEmail, password, {some:"data"}, function(err) {
dbi.findUser(origEmail, function(err, user) {
origModifiedTimestamp = user.modifiedTimestamp
done()
})
})
})
it('should update email correctly', function(done) {
dbi.changeEmail(origEmail, newEmail, function(err) {
dbi.findUser(newEmail, function(err, user) {
expect(err).to.be.null
expect(user).to.not.be.null
newModifiedTimestamp = user.modifiedTimestamp
dbi.checkPassword(newEmail, password, function(err, res) {
expect(res.password).to.exist
done()
})
})
})
})
it('should update modifiedTimestamp correctly', function(done) {
expect(newModifiedTimestamp).to.not.eql(origModifiedTimestamp)
done()
})
})
describe('#changePassword', function() {
var origEmail = 'cpemail@example.com'
var origPassword = 'supersecret'
var newPassword = 'blahr'
var user
before(function(done) {
dbi.addUser(origEmail, origPassword, {some:"data"}, function(err) {
dbi.findUser(origEmail, function(err, u) {
user = u
done()
})
})
})
it('should update password correctly', function(done) {
dbi.checkPassword(origEmail, origPassword, function(err, res) {
expect(res.password).to.exist
dbi.changePassword(origEmail, newPassword, function(err, res) {
dbi.checkPassword(origEmail, origPassword, function(err, res) {
expect(err).to.eql('password mismatch')
expect(res).to.be.false
dbi.checkPassword(origEmail, newPassword, function(err, res) {
expect(res.password).to.exist
done()
})
})
})
})
})
})
describe('#deleteUser', function() {
var testEmail = 'cpemail-deleteUser@example.com'
var testPassword = 'supersecret'
it('should successfully delete a user', function(done) {
function add() {
dbi.addUser(testEmail, testPassword, {some:"foobar"}, verifyAdd)
}
function verifyAdd() {
dbi.findUser(testEmail, function(err, user) {
expect(err).to.be.null
expect(user.password).to.not.be.null
del()
})
}
function del() {
dbi.deleteUser(testEmail, verifyDel)
}
function verifyDel() {
dbi.findUser(testEmail, function(err, user) {
expect(err).to.not.be.null
expect(user).to.be.undefined
done()
})
}
add()
})
})
describe('#modifyUser', function() {
var testEmail = 'cpemail-modifyUser@example.com'
var testPassword = 'supersecret'
var data1 = {woot:"foobar", zzz:[1,2,3]}
var data2 = {blah:"blahbalh", deepObj:{some:"data"}}
it("should successfully modify a user's data property", function(done) {
function add() {
dbi.addUser(testEmail, testPassword, data1, verifyAdd)
}
function verifyAdd() {
dbi.findUser(testEmail, function(err, user) {
expect(err).to.be.null
expect(user.password).to.not.be.null
expect(user.data).to.eql(data1)
modify()
})
}
function modify() {
dbi.modifyUser(testEmail, data2, verifyModify)
}
function verifyModify() {
dbi.findUser(testEmail, function(err, user) {
expect(user.data).to.eql(data2)
done()
})
}
add()
})
})
describe('writeQueue', function() {
var testEmail1 = 'writeQueue@example.com'
var testEmail2 = 'writeQueue2@example.com'
var testPassword = 'testblalbha'
var testPassword2 = 'testblalbha2'
var data = {woot:"foo"}
it('should serialize multi-step write-after-read operations', function(done) {
function add() {
dbi.addUser(testEmail1, testPassword, data, modify)
}
// Here we modify the same record in parallel, hoping to create a race condition.
function modify() {
async.parallel([
function(cb) {
dbi.changeEmail(testEmail1, testEmail2, function(err) {
cb(null, err)
})
},
function(cb) {
dbi.changePassword(testEmail1, testPassword2, function(err) {
cb(null, err)
})
},
function(cb) {
dbi.changePassword(testEmail2, testPassword2, function(err) {
cb(null, err)
})
},
], function(err, res) {
var found = 0
res.forEach(function(item) {
if (item && item.name === "NotFoundError") found++
})
expect(found).to.eql(1)
done()
})
}
add()
})
})
describe('#createUserStream', function() {
var baseEmail = 'createUserStream@example.com'
var password = 'mysecret'
var data = {some:"data"}
it('should return a stream of user objects', function(done) {
this.timeout(20000)
// Insert 20 users
var NUM_USERS = 20
var i = 0
async.whilst(
function() { return i < NUM_USERS },
function(cb) {
dbi.addUser(i + '-' + baseEmail, password, data, cb)
i++
},
start
)
var cnt = 0
function start() {
dbi.createUserStream()
.on('data', function(user) {
expect(user).to.exist
expect(user.email).to.be.a('string')
expect(user.password).to.be.a('string')
expect(user.modifiedDate).to.be.a('date')
expect(user.createdDate).to.be.a('date')
expect(user.data).to.be.a('object')
cnt++
})
.on('end', function() {
expect(cnt).to.be.above(NUM_USERS)
done()
})
}
})
})
})
|
const ThenAbilityAction = require('./ThenAbilityAction');
/**
* Translates the methods of a standard game action to one that will take an
* ability context => properties factory method.
*/
class AbilityAdapter {
constructor(action, propertyFactory) {
this.action = action;
this.propertyFactory = propertyFactory;
this.thenExecuteHandlers = [];
}
allow(context) {
let properties = this.resolveProperties(context);
return this.action.allow(properties);
}
createEvent(context) {
const properties = this.resolveProperties(context);
const event = this.action.createEvent(properties);
for(const handler of this.thenExecuteHandlers) {
event.thenExecute(handler);
}
return event;
}
resolveProperties(context) {
let baseProps = (typeof this.propertyFactory === 'function') ? this.propertyFactory(context) : this.propertyFactory;
return Object.assign({ context: context }, baseProps);
}
then(abilityPropertiesFactory) {
return new ThenAbilityAction(this, abilityPropertiesFactory);
}
thenExecute(handler) {
this.thenExecuteHandlers.push(handler);
return this;
}
}
module.exports = AbilityAdapter;
|
Later = Npm.require('later');
var fetchLatestASX = function(){
var limit = 0; //TODO how many new posts to save per every fetch
try{
var url = 'https://www.kimonolabs.com/api/d24n87da?apikey=6CUR6Vw9BNVRomz1pTUSDNK8I8VaruKv';
var result = Meteor.http.get(url);
if (!result.data) {
return 'Response not JSON';
}
if(!result.data.results['ASX ANNOCEMENTS'].length) {
return 'Invalid JSON from Kimono';
}
var announcement;
var added = 0;
var bodyToSave;
for (var i=result.data.results['ASX ANNOCEMENTS'].length - 1; i > 0 ; i--){
if (added > limit) break;
announcement = result.data.results['ASX ANNOCEMENTS'][i];
//saveASXPost
if(!Posts.findOne({ url : announcement.Link.href } )){
bodyToSave = 'Pages(' + announcement.Pages + '), announced at ' + announcement.AnnonceTime;
saveASXPost({
body: bodyToSave,
url: announcement.Link.href,
title: announcement.Annocement
});
added += 1;
}
}
return 'Added ' + added + ' new ASX posts';
}
catch(error){
return 'Connection error or server side error while fetching from Kimono';
}
};
var saveASXPost = function(asxPost){
var properties = {
baseScore: 1,
body: asxPost.body, //'Today is a Sunday',
commentsCount: 0,
createdAt: new Date(),
downvotes: 0,
//htmlBody: ,
inactive: false,
postedAt: new Date(),
score: 0,
status: 2,
sticky: false,
title: asxPost.title,
upvoters: [],
upvotes: 0,
url: asxPost.url,
userId: "hGdywRaQynkC9zdRT", //TODO the ID of the user name under which posts should be posted
};
//Posts.insert(properties);
console.log("Inserted fetched ASX Post ID: ", Posts.insert(properties));
}
SyncedCron.options.log = true;
//console.log('Next run=> ', SyncedCron.nextScheduledAtDate('ASX Posts Fetcher') );
SyncedCron.add({
name: 'ASX Posts Fetcher',
schedule: function(parser){
// parser is a later object
return parser.text('every 2 mins'); //TODO interval between fetches
},
job: function(){
return fetchLatestASX();
}
});
Meteor.startup(function() {
SyncedCron.start();
/*
These routes, I was using them when I was developing. You can delete them
*/
Router.map(function() {
this.route('asx', {
where: 'server',
path: '/asx',
action: function(){
fetchLatestASX();
this.response.end();
try{
var result = Meteor.http.get('https://www.kimonolabs.com/api/d24n87da?apikey=6CUR6Vw9BNVRomz1pTUSDNK8I8VaruKv');
if (!result.data) {
this.response.write('Response not JSON');
this.response.end();
return;
}
if(!result.data.results['ASX ANNOCEMENTS'].length) {
this.response.write('Invalid JSON from Kimono');
this.response.end();
return;
}
var announcement;
var limit = 5;
var considered = 0;
var bodyToSave;
for (var i=result.data.results['ASX ANNOCEMENTS'].length - 1; i > 0 ; i--){
if (considered > limit) break;
announcement = result.data.results['ASX ANNOCEMENTS'][i];
//saveASXPost
if(!Posts.findOne({ url : announcement.Link.href } )){
bodyToSave = 'Pages(' + announcement.Pages + '), announced at ' + announcement.AnnonceTime;
saveASXPost({
body: bodyToSave,
url: announcement.Link.href,
title: announcement.Annocement
});
considered += 1;
//this.response.write('<p>Would have saved '+ announcement.Annocement + ' - ' + announcement.Link.href+'</p>');
this.response.write('<p>Saved [' + announcement.Link.href + '] - '+ announcement.Annocement + ' - ' + bodyToSave +'</p>');
}
}
this.response.end();
}
catch(error){
this.response.write('Paita error ' + JSON.stringify(error));
this.response.end();
}
}
});
});
});
|
/**
* Created by Kane on 15/7/29.
*/
var url = require('url');
var config = require('../config');
var request = require('request');
var vermgr = {
get: function(params, callback) {
var _url = url.resolve(config[params.env].vermgr.url, 'repos/' + params.name);
var opt = {
method: 'GET',
url: _url,
qs: {
owner: params.owner
},
headers: {
Authorization: config[params.env].vermgr.authorization
}
};
request(opt, function(err, res, body) {
var body = JSON.parse(body);
if (!err && res.statusCode == 200) {
callback(null, body);
} else {
callback(new Error(body.msg));
}
});
},
list: function(params, callback) {
var _url = url.resolve(config[params.env].vermgr.url, 'repos');
var opt = {
method: 'GET',
url: _url,
qs: params,
headers: {
Authorization: config[params.env].vermgr.authorization
}
};
request(opt, function(err, res, body) {
var body = JSON.parse(body);
if (!err && res.statusCode == 200) {
callback(null, body.data);
} else {
callback(new Error(body.msg));
}
});
},
update: function(params, callback) {
var _url = url.resolve(config[params.env].vermgr.url, 'repos/' + params.name);
var opt = {
method: 'POST',
url: _url,
form: {
name: params.name,
owner: params.owner,
status: params.status
},
headers: {
Authorization: config[params.env].vermgr.authorization
}
};
request(opt, function(err, res, body) {
var error;
var body = JSON.parse(body);
if (!err && res.statusCode == 200) {
console.log(body);
} else {
error = new Error(body.msg);
}
callback(error);
});
}
};
module.exports = vermgr;
|
export const LOAD_LIST = 'wp/react/LOAD_LIST';
export const LOAD_LIST_SUCCESS = 'wp/react/LOAD_LIST@SUCCESS';
export const LOAD_LIST_FAILURE = 'wp/react/LOAD_LIST@FAILURE';
export const loadList = (args) => {
return {
type: LOAD_LIST,
args
}
}
export const loadListSuccess = (response) => {
return {
type: LOAD_LIST_SUCCESS,
response
}
}
export const loadListFilure = (error) => {
return {
type: LOAD_LIST_FAILURE,
error
}
}
|
/**
* Durandal 2.0.0 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved.
* Available via the MIT license.
* see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
*/
/**
* Serializes and deserializes data to/from JSON.
* @module serializer
* @requires system
*/
define(['durandal/system'], function(system) {
/**
* @class SerializerModule
* @static
*/
return {
/**
* The name of the attribute that the serializer should use to identify an object's type.
* @property {string} typeAttribute
* @default type
*/
typeAttribute: 'type',
/**
* The amount of space to use for indentation when writing out JSON.
* @property {string|number} space
* @default undefined
*/
space:undefined,
/**
* The default replacer function used during serialization. By default properties starting with '_' or '$' are removed from the serialized object.
* @method replacer
* @param {string} key The object key to check.
* @param {object} value The object value to check.
* @return {object} The value to serialize.
*/
replacer: function(key, value) {
if(key){
var first = key[0];
if(first === '_' || first === '$'){
return undefined;
}
}
return value;
},
/**
* Serializes the object.
* @method serialize
* @param {object} object The object to serialize.
* @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults.
* @return {string} The JSON string.
*/
serialize: function(object, settings) {
settings = (settings === undefined) ? {} : settings;
if(system.isString(settings) || system.isNumber(settings)) {
settings = { space: settings };
}
return JSON.stringify(object, settings.replacer || this.replacer, settings.space || this.space);
},
/**
* Gets the type id for an object instance, using the configured `typeAttribute`.
* @method getTypeId
* @param {object} object The object to serialize.
* @return {string} The type.
*/
getTypeId: function(object) {
if (object) {
return object[this.typeAttribute];
}
return undefined;
},
/**
* Maps type ids to object constructor functions. Keys are type ids and values are functions.
* @property {object} typeMap.
*/
typeMap: {},
/**
* Adds a type id/constructor function mampping to the `typeMap`.
* @method registerType
* @param {string} typeId The type id.
* @param {function} constructor The constructor.
*/
registerType: function() {
var first = arguments[0];
if (arguments.length == 1) {
var id = first[this.typeAttribute] || system.getModuleId(first);
this.typeMap[id] = first;
} else {
this.typeMap[first] = arguments[1];
}
},
/**
* The default reviver function used during deserialization. By default is detects type properties on objects and uses them to re-construct the correct object using the provided constructor mapping.
* @method reviver
* @param {string} key The attribute key.
* @param {object} value The object value associated with the key.
* @param {function} getTypeId A custom function used to get the type id from a value.
* @param {object} getConstructor A custom function used to get the constructor function associated with a type id.
* @return {object} The value.
*/
reviver: function(key, value, getTypeId, getConstructor) {
var typeId = getTypeId(value);
if (typeId) {
var ctor = getConstructor(typeId);
if (ctor) {
if (ctor.fromJSON) {
return ctor.fromJSON(value);
}
return new ctor(value);
}
}
return value;
},
/**
* Deserialize the JSON.
* @method deserialize
* @param {string} text The JSON string.
* @param {object} [settings] Settings can specify a reviver, getTypeId function or getConstructor function.
* @return {object} The deserialized object.
*/
deserialize: function(text, settings) {
var that = this;
settings = settings || {};
var getTypeId = settings.getTypeId || function(object) { return that.getTypeId(object); };
var getConstructor = settings.getConstructor || function(id) { return that.typeMap[id]; };
var reviver = settings.reviver || function(key, value) { return that.reviver(key, value, getTypeId, getConstructor); };
return JSON.parse(text, reviver);
}
};
});
|
import routeConfig from './route.config.js'
const genRoutes = (routeConfig)=>{
let routes = []
routeConfig.forEach((categoryConfig)=>{
categoryConfig.list.forEach((pageConfig)=>{
let component = require(`../pages${pageConfig.path}`)
routes.push({
name: pageConfig.name,
path: pageConfig.path,
component: component.default,
meta: {
title: pageConfig.name,
description: pageConfig.desc,
hiddenHeader: pageConfig.hiddenHeader || false
}
})
})
})
return routes
}
let routes = genRoutes(routeConfig)
routes.push({
path: '/',
component: require(`../pages/nav.vue`).default,
meta: {
title: '组件列表',
description: ''
}
})
export default routes
|
/**
* @preserve FastClick: polyfill to remove click delays on browsers with touch UIs.
*
* @version 1.0.2
* @codingstandard ftlabs-jsv2
* @copyright The Financial Times Limited [All Rights Reserved]
* @license MIT License (see LICENSE.txt)
*/
/*jslint browser:true, node:true*/
/*global define, Event, Node*/
/**
* Instantiate fast-clicking listeners on the specified layer.
*
* @constructor
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
function FastClick(layer, options) {
'use strict';
var oldOnClick;
options = options || {};
/**
* Whether a click is currently being tracked.
*
* @type boolean
*/
this.trackingClick = false;
/**
* Timestamp for when click tracking started.
*
* @type number
*/
this.trackingClickStart = 0;
/**
* The element being tracked for a click.
*
* @type EventTarget
*/
this.targetElement = null;
/**
* X-coordinate of touch start event.
*
* @type number
*/
this.touchStartX = 0;
/**
* Y-coordinate of touch start event.
*
* @type number
*/
this.touchStartY = 0;
/**
* ID of the last touch, retrieved from Touch.identifier.
*
* @type number
*/
this.lastTouchIdentifier = 0;
/**
* Touchmove boundary, beyond which a click will be cancelled.
*
* @type number
*/
this.touchBoundary = options.touchBoundary || 10;
/**
* The FastClick layer.
*
* @type Element
*/
this.layer = layer;
/**
* The minimum time between tap(touchstart and touchend) events
*
* @type number
*/
this.tapDelay = options.tapDelay || 200;
if (FastClick.notNeeded(layer)) {
return;
}
// Some old versions of Android don't have Function.prototype.bind
function bind(method, context) {
return function() { return method.apply(context, arguments); };
}
var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel'];
var context = this;
for (var i = 0, l = methods.length; i < l; i++) {
context[methods[i]] = bind(context[methods[i]], context);
}
// Set up event handlers as required
if (deviceIsAndroid) {
layer.addEventListener('mouseover', this.onMouse, true);
layer.addEventListener('mousedown', this.onMouse, true);
layer.addEventListener('mouseup', this.onMouse, true);
}
layer.addEventListener('click', this.onClick, true);
layer.addEventListener('touchstart', this.onTouchStart, false);
layer.addEventListener('touchmove', this.onTouchMove, false);
layer.addEventListener('touchend', this.onTouchEnd, false);
layer.addEventListener('touchcancel', this.onTouchCancel, false);
// Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
// which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick
// layer when they are cancelled.
if (!Event.prototype.stopImmediatePropagation) {
layer.removeEventListener = function(type, callback, capture) {
var rmv = Node.prototype.removeEventListener;
if (type === 'click') {
rmv.call(layer, type, callback.hijacked || callback, capture);
} else {
rmv.call(layer, type, callback, capture);
}
};
layer.addEventListener = function(type, callback, capture) {
var adv = Node.prototype.addEventListener;
if (type === 'click') {
adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) {
if (!event.propagationStopped) {
callback(event);
}
}), capture);
} else {
adv.call(layer, type, callback, capture);
}
};
}
// If a handler is already declared in the element's onclick attribute, it will be fired before
// FastClick's onClick handler. Fix this by pulling out the user-defined handler function and
// adding it as listener.
if (typeof layer.onclick === 'function') {
// Android browser on at least 3.2 requires a new reference to the function in layer.onclick
// - the old one won't work if passed to addEventListener directly.
oldOnClick = layer.onclick;
layer.addEventListener('click', function(event) {
oldOnClick(event);
}, false);
layer.onclick = null;
}
}
/**
* Android requires exceptions.
*
* @type boolean
*/
var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0;
/**
* iOS requires exceptions.
*
* @type boolean
*/
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent);
/**
* iOS 4 requires an exception for select elements.
*
* @type boolean
*/
var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent);
/**
* iOS 6.0(+?) requires the target element to be manually derived
*
* @type boolean
*/
var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent);
/**
* Determine whether a given element requires a native click.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element needs a native click
*/
FastClick.prototype.needsClick = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
// Don't send a synthetic click to disabled inputs (issue #62)
case 'button':
case 'select':
case 'textarea':
if (target.disabled) {
return true;
}
break;
case 'input':
// File inputs need real clicks on iOS 6 due to a browser bug (issue #68)
if ((deviceIsIOS && target.type === 'file') || target.disabled) {
return true;
}
break;
case 'label':
case 'video':
return true;
}
return (/\bneedsclick\b/).test(target.className);
};
/**
* Determine whether a given element requires a call to focus to simulate click into element.
*
* @param {EventTarget|Element} target Target DOM element
* @returns {boolean} Returns true if the element requires a call to focus to simulate native click.
*/
FastClick.prototype.needsFocus = function(target) {
'use strict';
switch (target.nodeName.toLowerCase()) {
case 'textarea':
return true;
case 'select':
return !deviceIsAndroid;
case 'input':
switch (target.type) {
case 'button':
case 'checkbox':
case 'file':
case 'image':
case 'radio':
case 'submit':
return false;
}
// No point in attempting to focus disabled inputs
return !target.disabled && !target.readOnly;
default:
return (/\bneedsfocus\b/).test(target.className);
}
};
/**
* Send a click event to the specified element.
*
* @param {EventTarget|Element} targetElement
* @param {Event} event
*/
FastClick.prototype.sendClick = function(targetElement, event) {
'use strict';
var clickEvent, touch;
// On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24)
if (document.activeElement && document.activeElement !== targetElement) {
document.activeElement.blur();
}
touch = event.changedTouches[0];
// Synthesise a click event, with an extra attribute so it can be tracked
clickEvent = document.createEvent('MouseEvents');
clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null);
clickEvent.forwardedTouchEvent = true;
targetElement.dispatchEvent(clickEvent);
};
FastClick.prototype.determineEventType = function(targetElement) {
'use strict';
//Issue #159: Android Chrome Select Box does not open with a synthetic click event
if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') {
return 'mousedown';
}
return 'click';
};
/**
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.focus = function(targetElement) {
'use strict';
var length;
// Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724.
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time') {
length = targetElement.value.length;
targetElement.setSelectionRange(length, length);
} else {
targetElement.focus();
}
};
/**
* Check whether the given target element is a child of a scrollable layer and if so, set a flag on it.
*
* @param {EventTarget|Element} targetElement
*/
FastClick.prototype.updateScrollParent = function(targetElement) {
'use strict';
var scrollParent, parentElement;
scrollParent = targetElement.fastClickScrollParent;
// Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the
// target element was moved to another parent.
if (!scrollParent || !scrollParent.contains(targetElement)) {
parentElement = targetElement;
do {
if (parentElement.scrollHeight > parentElement.offsetHeight) {
scrollParent = parentElement;
targetElement.fastClickScrollParent = parentElement;
break;
}
parentElement = parentElement.parentElement;
} while (parentElement);
}
// Always update the scroll top tracker if possible.
if (scrollParent) {
scrollParent.fastClickLastScrollTop = scrollParent.scrollTop;
}
};
/**
* @param {EventTarget} targetElement
* @returns {Element|EventTarget}
*/
FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) {
'use strict';
// On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node.
if (eventTarget.nodeType === Node.TEXT_NODE) {
return eventTarget.parentNode;
}
return eventTarget;
};
/**
* On touch start, record the position and scroll offset.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchStart = function(event) {
'use strict';
var targetElement, touch, selection;
// Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111).
if (event.targetTouches.length > 1) {
return true;
}
targetElement = this.getTargetElementFromEventTarget(event.target);
touch = event.targetTouches[0];
if (deviceIsIOS) {
// Only trusted events will deselect text on iOS (issue #49)
selection = window.getSelection();
if (selection.rangeCount && !selection.isCollapsed) {
return true;
}
if (!deviceIsIOS4) {
// Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23):
// when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched
// with the same identifier as the touch event that previously triggered the click that triggered the alert.
// Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an
// immediately preceeding touch event (issue #52), so this fix is unavailable on that platform.
if (touch.identifier === this.lastTouchIdentifier) {
event.preventDefault();
return false;
}
this.lastTouchIdentifier = touch.identifier;
// If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and:
// 1) the user does a fling scroll on the scrollable layer
// 2) the user stops the fling scroll with another tap
// then the event.target of the last 'touchend' event will be the element that was under the user's finger
// when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check
// is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42).
this.updateScrollParent(targetElement);
}
}
this.trackingClick = true;
this.trackingClickStart = event.timeStamp;
this.targetElement = targetElement;
this.touchStartX = touch.pageX;
this.touchStartY = touch.pageY;
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
event.preventDefault();
}
return true;
};
/**
* Based on a touchmove event object, check whether the touch has moved past a boundary since it started.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.touchHasMoved = function(event) {
'use strict';
var touch = event.changedTouches[0], boundary = this.touchBoundary;
if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) {
return true;
}
return false;
};
/**
* Update the last position.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchMove = function(event) {
'use strict';
if (!this.trackingClick) {
return true;
}
// If the touch has moved, cancel the click tracking
if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) {
this.trackingClick = false;
this.targetElement = null;
}
return true;
};
/**
* Attempt to find the labelled control for the given label element.
*
* @param {EventTarget|HTMLLabelElement} labelElement
* @returns {Element|null}
*/
FastClick.prototype.findControl = function(labelElement) {
'use strict';
// Fast path for newer browsers supporting the HTML5 control attribute
if (labelElement.control !== undefined) {
return labelElement.control;
}
// All browsers under test that support touch events also support the HTML5 htmlFor attribute
if (labelElement.htmlFor) {
return document.getElementById(labelElement.htmlFor);
}
// If no for attribute exists, attempt to retrieve the first labellable descendant element
// the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label
return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea');
};
/**
* On touch end, determine whether to send a click event at once.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onTouchEnd = function(event) {
'use strict';
var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement;
if (!this.trackingClick) {
return true;
}
// Prevent phantom clicks on fast double-tap (issue #36)
if ((event.timeStamp - this.lastClickTime) < this.tapDelay) {
this.cancelNextClick = true;
return true;
}
// Reset to prevent wrong click cancel on input (issue #156).
this.cancelNextClick = false;
this.lastClickTime = event.timeStamp;
trackingClickStart = this.trackingClickStart;
this.trackingClick = false;
this.trackingClickStart = 0;
// On some iOS devices, the targetElement supplied with the event is invalid if the layer
// is performing a transition or scroll, and has to be re-detected manually. Note that
// for this to function correctly, it must be called *after* the event target is checked!
// See issue #57; also filed as rdar://13048589 .
if (deviceIsIOSWithBadTarget) {
touch = event.changedTouches[0];
// In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null
targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement;
targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent;
}
targetTagName = targetElement.tagName.toLowerCase();
if (targetTagName === 'label') {
forElement = this.findControl(targetElement);
if (forElement) {
this.focus(targetElement);
if (deviceIsAndroid) {
return false;
}
targetElement = forElement;
}
} else if (this.needsFocus(targetElement)) {
// Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through.
// Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37).
if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) {
this.targetElement = null;
return false;
}
this.focus(targetElement);
this.sendClick(targetElement, event);
// Select elements need the event to go through on iOS 4, otherwise the selector menu won't open.
// Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others)
if (!deviceIsIOS || targetTagName !== 'select') {
this.targetElement = null;
event.preventDefault();
}
return false;
}
if (deviceIsIOS && !deviceIsIOS4) {
// Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled
// and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42).
scrollParent = targetElement.fastClickScrollParent;
if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) {
return true;
}
}
// Prevent the actual click from going though - unless the target node is marked as requiring
// real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted.
if (!this.needsClick(targetElement)) {
event.preventDefault();
this.sendClick(targetElement, event);
}
return false;
};
/**
* On touch cancel, stop tracking the click.
*
* @returns {void}
*/
FastClick.prototype.onTouchCancel = function() {
'use strict';
this.trackingClick = false;
this.targetElement = null;
};
/**
* Determine mouse events which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onMouse = function(event) {
'use strict';
// If a target element was never set (because a touch event was never fired) allow the event
if (!this.targetElement) {
return true;
}
if (event.forwardedTouchEvent) {
return true;
}
// Programmatically generated events targeting a specific element should be permitted
if (!event.cancelable) {
return true;
}
// Derive and check the target element to see whether the mouse event needs to be permitted;
// unless explicitly enabled, prevent non-touch click events from triggering actions,
// to prevent ghost/doubleclicks.
if (!this.needsClick(this.targetElement) || this.cancelNextClick) {
// Prevent any user-added listeners declared on FastClick element from being fired.
if (event.stopImmediatePropagation) {
event.stopImmediatePropagation();
} else {
// Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2)
event.propagationStopped = true;
}
// Cancel the event
event.stopPropagation();
event.preventDefault();
return false;
}
// If the mouse event is permitted, return true for the action to go through.
return true;
};
/**
* On actual clicks, determine whether this is a touch-generated click, a click action occurring
* naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or
* an actual click which should be permitted.
*
* @param {Event} event
* @returns {boolean}
*/
FastClick.prototype.onClick = function(event) {
'use strict';
var permitted;
// It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early.
if (this.trackingClick) {
this.targetElement = null;
this.trackingClick = false;
return true;
}
// Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target.
if (event.target.type === 'submit' && event.detail === 0) {
return true;
}
permitted = this.onMouse(event);
// Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through.
if (!permitted) {
this.targetElement = null;
}
// If clicks are permitted, return true for the action to go through.
return permitted;
};
/**
* Remove all FastClick's event listeners.
*
* @returns {void}
*/
FastClick.prototype.destroy = function() {
'use strict';
var layer = this.layer;
if (deviceIsAndroid) {
layer.removeEventListener('mouseover', this.onMouse, true);
layer.removeEventListener('mousedown', this.onMouse, true);
layer.removeEventListener('mouseup', this.onMouse, true);
}
layer.removeEventListener('click', this.onClick, true);
layer.removeEventListener('touchstart', this.onTouchStart, false);
layer.removeEventListener('touchmove', this.onTouchMove, false);
layer.removeEventListener('touchend', this.onTouchEnd, false);
layer.removeEventListener('touchcancel', this.onTouchCancel, false);
};
/**
* Check whether FastClick is needed.
*
* @param {Element} layer The layer to listen on
*/
FastClick.notNeeded = function(layer) {
'use strict';
var metaViewport;
var chromeVersion;
// Devices that don't support touch don't need FastClick
if (typeof window.ontouchstart === 'undefined') {
return true;
}
// Chrome version - zero for other browsers
chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1];
if (chromeVersion) {
if (deviceIsAndroid) {
metaViewport = document.querySelector('meta[name=viewport]');
if (metaViewport) {
// Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89)
if (metaViewport.content.indexOf('user-scalable=no') !== -1) {
return true;
}
// Chrome 32 and above with width=device-width or less don't need FastClick
if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) {
return true;
}
}
// Chrome desktop doesn't need FastClick (issue #15)
} else {
return true;
}
}
// IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97)
if (layer.style.msTouchAction === 'none') {
return true;
}
return false;
};
/**
* Factory method for creating a FastClick object
*
* @param {Element} layer The layer to listen on
* @param {Object} options The options to override the defaults
*/
FastClick.attach = function(layer, options) {
'use strict';
return new FastClick(layer, options);
};
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
// AMD. Register as an anonymous module.
define(function() {
'use strict';
return FastClick;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = FastClick.attach;
module.exports.FastClick = FastClick;
} else {
window.FastClick = FastClick;
}
|
/**
* @author Kate Compton
*/
define(["common", "threeUtils", "graph", "ui"], function(common, threeUtils, Graph, UI) {
var useMultiMaterial = false;
defaultMaterial = new THREE.MeshNormalMaterial();
var darkMaterial = new THREE.MeshBasicMaterial({
color : 0xffffcc
});
var wireframeMaterial = new THREE.MeshBasicMaterial({
color : 0x000000,
wireframe : true,
transparent : true
});
var phongMat = new THREE.MeshPhongMaterial({
// light
specular : '#a9fcff',
// intermediate
color : '#00abb1',
// dark
emissive : '#006063',
shininess : 100
});
// multiMaterial = [defaultMaterial, wireframeMaterial];
multiMaterial = [phongMat, wireframeMaterial];
defaultMaterial = phongMat;
defaultMaterial.side = THREE.DoubleSide;
// Just one shape, just one swiss geo
var FeatureShape = Class.extend({
init : function(feature, shape) {
console.log("New feature shape");
this.shape = shape;
this.ringCount = 1;
this.shape.idColor = feature.idColor;
this.modgeo = new threeUtils.ModGeo.Swiss({
outerPath : this.shape.outerPath.createLinearPath(3),
innerPaths : this.shape.innerPaths,
ringCount : this.ringCount,
});
var area = Math.abs(this.shape.outerPath.calculateArea());
this.heightOffset = 50 - .004 * Math.pow(area, .8);
console.log("OFFSET: " + area + " " + this.heightOffset);
},
getMesh : function() {
if (useMultiMaterial)
this.mesh = THREE.SceneUtils.createMultiMaterialObject(this.modgeo.createGeometry(), multiMaterial);
else
this.mesh = new THREE.Mesh(this.modgeo.createGeometry(), defaultMaterial);
return this.mesh;
},
});
var featureCount = 0;
var CoinFeature = Class.extend({
init : function(objTypeName, sliders, uiDiv) {
this.idNumber = featureCount;
this.classID = objTypeName;
this.idColor = common.KColor.makeIDColor(this.idNumber * .7);
this.id = objTypeName + this.idNumber;
featureCount++;
this.currentValues = {
};
this.mesh = new THREE.Object3D();
this.shape = new Graph.Shape(objTypeName + this.idNumber);
this.featureShapes = [];
this.buildUI(uiDiv, sliders);
this.ready = true;
console.log("READY " + this);
this.rebuild();
},
update : function(time) {
},
getCurrentValue : function(valueName) {
if (this.currentValues.hasOwnProperty(valueName))
return this.currentValues[valueName];
else
throw (this.id + " has no current value for " + valueName);
},
buildSliders : function(uiDiv, sliders) {
console.log("Build sliders");
var feature = this;
var sliderHolder = $("<div/>", {
id : this.id + "_sliderholder",
"class" : this.classID + "_sliderholder",
});
for (var prop in sliders) {
if (sliders.hasOwnProperty(prop)) {
var setting = sliders[prop];
this.addSlider(sliderHolder, prop, setting);
}
}
uiDiv.append(sliderHolder);
},
addSlider : function(sliderHolder, prop, setting) {
var feature = this;
app.ui.addSlider(sliderHolder, setting.name, setting.defaultVal, setting.min, setting.max, function(key, val) {
feature.currentValues[prop] = val;
// Apply the onchange fxn
feature[setting.onChange]();
});
},
buildUIDetails : function(uiDiv) {
},
buildUI : function(uiDiv, sliders) {
var uiHolder = $("<div/>", {
id : this.id + "_uiholder",
"class" : this.classID + "_uiholder"
});
uiDiv.append(uiHolder);
var bgColor = this.idColor.cloneShade(.5, 1);
uiHolder.css({
"background" : bgColor.toCSS(),
})
// Make an area for UI and an area for sliders,
this.buildUIDetails(uiHolder);
// sliders go at bottom
this.buildSliders(uiHolder, sliders);
},
buildShapeDetails : function() {
},
// Build whatever shape is needed
buildShape : function() {
this.shape.clear();
this.featureShapes = [];
this.buildShapeDetails();
for (var i = 0; i < this.featureShapes.length; i++) {
this.shape.addShape(this.featureShapes[i].shape);
}
},
buildMesh : function() {
// Remove all the featureshapes
for ( i = this.mesh.children.length - 1; i >= 0; i--) {
var obj = this.mesh.children[i];
this.mesh.remove(obj);
}
for (var i = 0; i < this.featureShapes.length; i++) {
this.mesh.add(this.featureShapes[i].getMesh());
}
this.remod();
},
modEdgeVertex : function(p, context) {
var bump = 1 + .05 * Math.sin(context.pctRing * 3);
var i = context.segment;
var node = context.path.nodes[i];
p.x = node.x * bump;
p.y = node.y * bump;
var s = context.featureShape.heightOffset;
p.z = -(1 - context.pctRing) * (this.currentValues.height + s);
},
remod : function() {
var feature = this;
if (this.isReady()) {
console.log("Remod " + this);
for (var i = 0; i < this.featureShapes.length; i++) {
var fs = this.featureShapes[i];
fs.modgeo.modOuterRing(function(p, context) {
context.featureShape = fs;
feature.modEdgeVertex(p, context);
});
fs.modgeo.update();
}
}
},
rebuild : function() {
if (this.isReady()) {
console.log("Rebuild " + this);
this.shape.clear();
this.buildShape();
this.buildMesh();
this.remod();
}
},
isReady : function() {
return this.ready;
},
toString : function() {
var s = this.id;
for (var prop in this.currentValues) {
if (this.currentValues.hasOwnProperty(prop)) {
var p = this.currentValues[prop];
s += " " + prop + ": " + p;
}
}
s += ", " + this.featureShapes.length + " feature shapes";
return s;
}
});
CoinFeature.FeatureShape = FeatureShape;
return CoinFeature;
});
|
'use strict';
module.exports = {
port: 443,
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/joyful-church',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.min.js',
'public/lib/angular-animate/angular-animate.min.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'https://localhost:443/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
import Ember from 'ember';
export default Ember.Route.extend({
indexedDbPromised: Ember.inject.service('indexed-db'),
beforeModel () {
// Create or open Database before default route is loaded
Ember.run.once(() => {
this.get('indexedDbPromised').createIndexedDbStore({
$dbName: 'transportme-favorites',
$dbStore: 'favorites',
$dbVersion: 1,
$keyPath: 'favId'
});
this.get('indexedDbPromised').createIndexedDbStore({
$dbName: 'transportme-recent',
$dbStore: 'recent',
$dbVersion: 1,
$keyPath: 'fromTo',
$index: ['by-date', 'request_time']
});
this.get('indexedDbPromised').createIndexedDbStore({
$dbName: 'transportme-trains',
$dbStore: 'trains',
$dbVersion: 1,
$keyPath: 'station_code',
$index: ['by-date', 'request_time']
});
this.get('indexedDbPromised').createIndexedDbStore({
$dbName: 'transportme-nearby',
$dbStore: 'nearby',
$dbVersion: 1
});
});
}
});
|
import React, { Component, PropTypes } from 'react';
import Portal from '../hoc/Portal';
import classnames from 'classnames';
import { themr } from 'react-css-themr';
import { TOOLTIP } from '../identifiers.js';
import events from '../utils/events';
import utils from '../utils/utils';
const POSITION = {
BOTTOM: 'bottom',
HORIZONTAL: 'horizontal',
LEFT: 'left',
RIGHT: 'right',
TOP: 'top',
VERTICAL: 'vertical'
};
const defaults = {
className: '',
delay: 0,
hideOnClick: true,
position: POSITION.VERTICAL,
theme: {}
};
const tooltipFactory = (options = {}) => {
const {
className: defaultClassName,
delay: defaultDelay,
hideOnClick: defaultHideOnClick,
position: defaultPosition,
theme: defaultTheme
} = {...defaults, ...options};
return ComposedComponent => {
class TooltippedComponent extends Component {
static propTypes = {
children: PropTypes.any,
className: PropTypes.string,
onClick: PropTypes.func,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
theme: PropTypes.shape({
tooltip: PropTypes.string,
tooltipActive: PropTypes.string,
tooltipWrapper: PropTypes.string
}),
tooltip: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node
]),
tooltipDelay: PropTypes.number,
tooltipHideOnClick: PropTypes.bool,
tooltipPosition: PropTypes.oneOf(Object.keys(POSITION).map(key => POSITION[key]))
};
static defaultProps = {
className: defaultClassName,
tooltipDelay: defaultDelay,
tooltipHideOnClick: defaultHideOnClick,
tooltipPosition: defaultPosition
};
state = {
active: false,
position: this.props.tooltipPosition,
visible: false
};
componentWillUnmount () {
if (this.refs.tooltip) {
events.removeEventListenerOnTransitionEnded(this.refs.tooltip, this.onTransformEnd);
}
}
activate ({ top, left, position }) {
if (this.timeout) clearTimeout(this.timeout);
this.setState({ visible: true, position });
this.timeout = setTimeout(() => {
this.setState({ active: true, top, left });
}, this.props.tooltipDelay);
}
deactivate () {
if (this.timeout) clearTimeout(this.timeout);
if (this.state.active) {
events.addEventListenerOnTransitionEnded(this.refs.tooltip, this.onTransformEnd);
this.setState({ active: false });
} else if (this.state.visible) {
this.setState({ visible: false });
}
}
getPosition (element) {
const { tooltipPosition } = this.props;
if (tooltipPosition === POSITION.HORIZONTAL) {
const origin = element.getBoundingClientRect();
const { width: ww } = utils.getViewport();
const toRight = origin.left < ((ww / 2) - origin.width / 2);
return toRight ? POSITION.RIGHT : POSITION.LEFT;
} else if (tooltipPosition === POSITION.VERTICAL) {
const origin = element.getBoundingClientRect();
const { height: wh } = utils.getViewport();
const toBottom = origin.top < ((wh / 2) - origin.height / 2);
return toBottom ? POSITION.BOTTOM : POSITION.TOP;
} else {
return tooltipPosition;
}
}
calculatePosition (element) {
const position = this.getPosition(element);
const { top, left, height, width } = element.getBoundingClientRect();
const xOffset = window.scrollX || window.pageXOffset;
const yOffset = window.scrollY || window.pageYOffset;
if (position === POSITION.BOTTOM) {
return {
top: top + height + yOffset,
left: left + (width / 2) + xOffset,
position
};
} else if (position === POSITION.TOP) {
return {
top: top + yOffset,
left: left + (width / 2) + xOffset,
position
};
} else if (position === POSITION.LEFT) {
return {
top: top + (height / 2) + yOffset,
left: left + xOffset,
position
};
} else if (position === POSITION.RIGHT) {
return {
top: top + (height / 2) + yOffset,
left: left + width + xOffset,
position
};
}
}
onTransformEnd = (e) => {
if (e.propertyName === 'transform') {
events.removeEventListenerOnTransitionEnded(this.refs.tooltip, this.onTransformEnd);
this.setState({ visible: false });
}
};
handleMouseEnter = (event) => {
this.activate(this.calculatePosition(event.target));
if (this.props.onMouseEnter) this.props.onMouseEnter(event);
};
handleMouseLeave = (event) => {
this.deactivate();
if (this.props.onMouseLeave) this.props.onMouseLeave(event);
};
handleClick = (event) => {
if (this.props.tooltipHideOnClick) this.deactivate();
if (this.props.onClick) this.props.onClick(event);
};
render () {
const { active, left, top, position, visible } = this.state;
const positionClass = `tooltip${position.charAt(0).toUpperCase() + position.slice(1)}`;
const {
children,
className,
theme,
tooltip,
tooltipDelay, //eslint-disable-line no-unused-vars
tooltipHideOnClick, //eslint-disable-line no-unused-vars
tooltipPosition, //eslint-disable-line no-unused-vars
...other
} = this.props;
const _className = classnames(theme.tooltip, {
[theme.tooltipActive]: active,
[theme[positionClass]]: theme[positionClass]
});
return (
<ComposedComponent
{...other}
className={className}
onClick={this.handleClick}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
theme={theme}
>
{children ? children : null}
{visible && (
<Portal>
<span ref="tooltip" className={_className} data-react-toolbox="tooltip" style={{top, left}}>
<span className={theme.tooltipInner}>{tooltip}</span>
</span>
</Portal>
)}
</ComposedComponent>
);
}
}
return themr(TOOLTIP, defaultTheme)(TooltippedComponent);
};
};
export default tooltipFactory;
|
import @ from "contracts.js"
@ (x: Pos) -> res:Num | x > (res * res - 0.1) &&
x < (res * res + 0.1)
function bad_square_root(x) {
// oops, square *root* not square!
return x * x;
}
bad_square_root(100);
|
$('#setAstucesMessageAsRead').click(function (e) {
e.preventDefault();
$.ajax({
url: $(this).data('url'),
method: 'GET'
});
});
$('#modal-load-postAtip').click(function (e) {
e.preventDefault();
$('#postAtipContent').html(loadModalHTML);
$.ajax({
url: $(this).data('url'),
method: 'GET'
}).done(function (content) {
$('#postAtipContent').html(content)
})
});
$('.modal-load-postAcomment').click(function (e) {
e.preventDefault();
$('#postAcommentContent').html(loadModalHTML);
$.ajax({
url: $(this).data('url'),
method: 'GET'
}).done(function (content) {
$('#postAcommentContent').html(content)
})
});
$('.thankUserAstuce').click(function (e) {
e.preventDefault();
var that = this;
var data = getProperURLForAstuceThankAction(this, 'thankUserAstuce');
$.ajax({
url: data['url'],
method: 'GET'
}).done(function () {
(data['unThank'] === false) ?
$(that).removeClass('thankUserAstuce').addClass('unThankUserAstuce')
:
$(that).removeClass('unThankUserAstuce').addClass('thankUserAstuce');
});
});
$('.unThankUserAstuce').click(function (e) {
e.preventDefault();
var that = this;
var data = getProperURLForAstuceThankAction(this, 'unThankUserAstuce');
$.ajax({
url: data['url'],
method: 'GET'
}).done(function () {
(data['unThank'] === false) ?
$(that).removeClass('thankUserAstuce').addClass('unThankUserAstuce')
:
$(that).removeClass('unThankUserAstuce').addClass('thankUserAstuce');
});
});
$('.reportAstuce').click(function (e) {
e.preventDefault();
var that = this;
var data = getProperUrlForAstuceReportAction(this, 'reportAstuce');
$.ajax({
url: data['url'],
method: 'GET'
}).done(function () {
(data['unReportAstuce'] === false) ?
$(that).removeClass('reportAstuce').addClass('unReportAstuce')
:
$(that).removeClass('unReportAstuce').addClass('reportAstuce');
});
});
$('.unReportAstuce').click(function (e) {
e.preventDefault();
var that = this;
var data = getProperUrlForAstuceReportAction(this, 'unReportAstuce');
$.ajax({
url: data['url'],
method: 'GET'
}).done(function () {
(data['unReportAstuce'] === false) ?
$(that).removeClass('reportAstuce').addClass('unReportAstuce')
:
$(that).removeClass('unReportAstuce').addClass('reportAstuce');
});
});
$('.shareAstuce').click(function (e) {
e.preventDefault();
FB.ui({
method: 'share',
mobile_iframe: true,
href: 'http://www.you.jobs' + $(this).data('url')
}, function(response){});
});
$('.bookmarkAstuce').click(function (e) {
e.preventDefault();
var that = this;
var data = getProperUrlForAstuceBookmarkAction(this, 'bookmarkAstuce');
$.ajax({
url: data['url'],
method: 'GET'
}).done(function () {
(data['unBookmarkAstuce'] === false) ?
$(that).removeClass('bookmarkAstuce').addClass('unBookmarkAstuce')
:
$(that).removeClass('unBookmarkAstuce').addClass('bookmarkAstuce');
});
});
$('.unBookmarkAstuce').click(function (e) {
e.preventDefault();
var that = this;
var data = getProperUrlForAstuceBookmarkAction(this, 'unBookmarkAstuce');
$.ajax({
url: data['url'],
method: 'GET'
}).done(function () {
(data['unBookmarkAstuce'] === false) ?
$(that).removeClass('bookmarkAstuce').addClass('unBookmarkAstuce')
:
$(that).removeClass('unBookmarkAstuce').addClass('bookmarkAstuce');
});
});
|
/**
* @author Krzysztof Winiarski
* @copyright (c) 2014 Krzysztof Winiarski
* @license MIT
*/
'use strict';
var support = require('../support');
var actionWrapper = require('./action-wrapper');
function validateTypeOfArrayRecords(array, name, type) {
if (!array || !array instanceof Array) {
throw new TypeError('ResourceAction(config.' + name + ') needs to be an Array');
} else {
for (var i = 0, j = array.length; i < j; i++) {
if (typeof array[i] !== type) {
throw new TypeError('ResourceAction(config.' + name + '[' + i + ']) needs to be a ' + type);
}
}
}
}
function validateAction(config) {
if (!config.id || typeof config.id !== 'string' && config.id.length > 0) {
throw new TypeError('ResourceAction(config.id) needs to be a non empty string');
}
if (!config.handler || typeof config.handler !== 'function') {
throw new TypeError('ResourceAction(config.handler) needs to be a function');
}
if (!config.mountPath) {
throw new TypeError('ResourceAction(config.mountPath) is missing');
} else {
if (config.mountPath instanceof Array) {
validateTypeOfArrayRecords(config.mountPath, 'mountPath', 'string');
}
}
validateTypeOfArrayRecords(config.policies, 'policies', 'function');
validateTypeOfArrayRecords(config.methods, 'methods', 'string');
}
/**
* ResourceAction represents single action for selected resource. For example
* POST /resource/mount-path/action-path. Action must have handler function
* (from blueprints or user defined, eventually 404 NotImplemented error handler).
* Additionally ResourceAction may have policies registered.
* @param handler
* @constructor
*/
function ResourceAction(handler) {
if (!handler || typeof handler !== 'function') {
throw new TypeError('ResourceAction(handler) needs to be a function');
}
for (var key in handler) {
if (handler[key]) {
this[key] = handler[key];
}
}
if (!this.mountPath) {
this.mountPath = '/' + support.camelCaseToDash(this.id);
}
this.handler = actionWrapper(handler);
validateAction(this);
}
ResourceAction.prototype.policies = [];
ResourceAction.prototype.methods = ['GET'];
/**
*
* @param {Object} policies
*/
ResourceAction.prototype.registerPolicies = function(policies) {
this.policies = this.policies.concat(policies);
};
module.exports = ResourceAction;
|
export default class Wheel {
constructor(rim, tire) {
this.rim = rim;
this.tire = tire;
}
diameter() {
return this.rim + (this.tire * 2);
}
}
|
module.exports = {
timeout: 5000,
'async-only': true,
'check-leaks': true,
recursive: true,
};
|
// Copyright (c) 2015-2018 Robert Rypuła - https://audio-network.rypula.pl
function transmitSymbol(channelIndex, ofdmIndex, symbol) {
var
pskSize = getIntById('tx-psk-size-' + channelIndex),
symbolDuration = getFloatById('symbol-duration') / 1000
;
transmitAdapter.symbol(channelIndex, ofdmIndex, symbol, pskSize, symbolDuration);
}
function transmitPacket(channelIndex) {
var
dataStr = getStrById('tx-packet-data-' + channelIndex),
syncPreamble = !!document.getElementById('sync-preamble').checked,
pskSize = getIntById('tx-psk-size-' + channelIndex),
symbolDuration = getFloatById('symbol-duration') / 1000,
guardInterval = getFloatById('guard-interval') / 1000,
interpacketGap = getFloatById('interpacket-gap') / 1000,
dataList, mute, symbol, symbolList, symbolListParsed, i, j,
data = [],
amplitude = []
;
dataList = dataStr.split(' ');
for (i = 0; i < dataList.length; i++) {
symbolList = dataList[i].split('.');
symbolListParsed = [];
for (j = 0; j < symbolList.length; j++) {
mute = symbolList[j] === '-';
symbol = mute ? null : parseInt(symbolList[j]);
if (i === 0) {
amplitude.push(getFloatById('tx-amplitude-input-' + channelIndex + '-' + j));
}
symbolListParsed.push(symbol % pskSize);
}
data.push(symbolListParsed.length === 1 ? symbolListParsed[0] : symbolListParsed);
}
transmitAdapter.packet(channelIndex, data, syncPreamble, pskSize, symbolDuration, guardInterval, interpacketGap, amplitude);
}
function transmitSynchronization(channelIndex) {
transmitAdapter.synchronization(channelIndex);
}
|
var child_process = require('child_process');
var q = require('q');
function exec(command, options) {
var deferred = q.defer();
var childProcess;
var args = Array.prototype.slice.call(arguments, 0);
args.push(function(err, stdout, stderr) {
if (err) {
err.message += command + ' (exited with error code ' + err.code + ')';
err.stdout = stdout;
err.stderr = stderr;
deferred.reject(err);
}
else {
deferred.resolve({
childProcess: childProcess,
stdout: stdout,
stderr: stderr
});
}
});
childProcess = child_process.exec.apply(child_process, args);
process.nextTick(function() {
deferred.notify(childProcess);
});
return deferred.promise;
}
function spawn(command, args, options) {
var deferred = q.defer();
var p = child_process.spawn(command, args, options);
process.nextTick(function() { // Make sure the callee had a chance to add listeners
deferred.notify(p);
});
p.on('close', function (code) {
if (code !== 0) {
var commandStr = command + (args.length ? (' ' + args.join(' ')) : '');
deferred.reject('"' + commandStr + '" failed with code ' + code);
}
else {
deferred.resolve();
}
});
return deferred.promise;
}
exports.exec = exec;
exports.spawn = spawn;
|
function normalizeArgs(options, cb) {
let normalizedOptions = options || {};
let callback;
if (typeof cb === "function") {
callback = cb;
} else if (typeof options === "function" && !cb) {
normalizedOptions = {};
callback = options;
}
let returnValue;
if (!callback) {
returnValue = new Promise((resolve, reject) => {
callback = (err, value) => {
if (err) {
reject(err);
} else {
resolve(value);
}
};
});
}
return {
callback,
normalizedOptions,
returnValue,
};
}
async function readableToString(readable) {
let result = "";
for await (const chunk of readable) {
result += chunk;
}
return result;
}
module.exports = {
normalizeArgs,
readableToString,
};
|
/**
* This module is a wrapper for Google's gcloud module that is made specifically
* to interact with the Google Developer Cloud Datastore.
*
* @author Zack Harley @zackharley
*/
'use strict';
var async = require('async');
var gcloud = require('gcloud');
var gcloudDatastore = gcloud.datastore();
var Query = gcloudDatastore.createQuery().constructor;
module.exports = (function() {
/**
* The stack used to store any queries that will be executed.
*
* @type{object}
* @private
*/
var queryStack = [];
/**
* A function used to add an array of queries to the stack.
*
* @param {object} queries - An array of query objects to be added to the
* stack.
* @return {number} The new length of the stack after the queries have been
* inserted.
*
* @example
* var animalQuery = datastore.createQuery('Animal');
* var movieQuery = datastore.createQuery('Movie');
* var queries = [animalQuery, movieQuery];
*
* var queueLength = datastore.addAllQueries(queries);
*/
function addQueries(queries, callback) {
if(!Array.isArray(queries)) {
throw new Error('Input must be an array of Query objects.');
}
queries.forEach(function(query) {
if(query.constructor.toString() !== Query.toString()) {
throw new Error('Expected ' + query.constructor.toString() +
' to equal: ' + Query.toString());
}
});
queryStack = queryStack.concat(queries);
return queryStack.length;
}
/**
* A function used to add one query to the stack.
*
* @param {object} query - A query object to be added to the stack.
* @return {number} The new length of the stack after the query has been
* inserted.
*
* @example
* var animalQuery = datastore.createQuery('Animal');
*
* var queueLength = datastore.addQuery(animalQuery);
*/
function addQuery(query) {
if(query.constructor.toString() === Query.toString()) {
var newLength = queryStack.push(query);
return newLength;
} else {
throw new Error('Expected ' + query.constructor.toString() +
' to equal: ' + Query.toString());
}
}
/**
* A function used to create a new Query object.
*
* Note: This acts exactly like the createQuery method supplied by the
* [gcloud-node API]{@link https://googlecloudplatform.github.io/gcloud-node/#/docs/v0.34.0/datastore?method=createQuery}.
*
* @param {string=} namespace - An optional namespace to use for the query.
* @param {string} kind - The kind to use for the query.
* @return {Query} A new Query object.
*
* @example
* var animalQuery = datastore.createQuery('Animal');
*/
function createQuery(namespace, kind) {
if(typeof namespace === 'string' && !kind) {
kind = namespace;
return gcloudDatastore.createQuery(kind);
} else if(typeof namespace === 'string' && typeof kind === 'string') {
return gcloudDatastore.createQuery(namespace, kind);
} else {
throw new Error('Expected inputs to be of type [String]');
}
}
/**
* A function used to get an array containing all of the queries currently
* in the stack.
*
* @return {object} An array containing all of the queries currently stored
* in the stack.
*
* @example
* var queries = datastore.getAllQueries();
*/
function getAllQueries() {
return queryStack.length > 0 ? queryStack : null;
}
/**
* A function used to get the next query to be run in the stack, based on
* the FIFO model.
*
* @return {Query} The next query to be run in the stack.
*
* @example
* var query = datastore.getNextQuery();
*/
function getNextQuery() {
return queryStack.length > 0 ? queryStack[0] : null;
}
/**
* A function used to get the length of the stack.
*
* @return {number} The length of the stack.
*
* @example
* var queueLength = datastore.getQueueLength();
*/
function getStackLength() {
return queryStack.length;
}
/**
* A function used to remove all of the queries from the stack.
* This function acts in a similar manner to the `getAllQueries` function,
* but empties the stack as well as retrieving all of the queries currently
* in the stack.
*
* @return {object} An array containing all of the queries that were removed
* from the stack.
*
* @example
* var queries = datastore.removeAllQueries();
*/
function removeAllQueries() {
if(queryStack.length > 0) {
var result = queryStack;
queryStack = [];
return result;
} else {
queryStack = [];
return null;
}
}
/**
* A function used to the next query from the stack, based on the FIFO model.
* This function acts in a similar manner to the `getNextQuery` function, but
* removes the next query from the stack as well as retrieving it.
*
* @return {Query} The query object that was removed from the stack.
*
* @example
* var query = datastore.removeNextQuery();
*/
function removeNextQuery() {
if(queryStack.length > 0) {
return queryStack.shift();
} else {
queryStack = [];
return null;
}
}
/**
* A function used to execute all of the queries from the stack against the
* Datastore.
*
* @param {function} callback - A callback function.
* @param {?error} callback.error - The error returned when executing the
* query. May be null.
* @param {?object} callback.result - The result of running the datastore
* queries. May be null.
*
* @example
* datastore.runAllQueries(function(error, result) {
* if(!error){
* // do something
* }
* });
*/
function runAllQueries(callback) {
var queryResults = [];
async.eachSeries(queryStack, function(query, callback) {
gcloudDatastore.runQuery(query, function(error, result) {
if(error) {
return callback(error);
} else {
queryResults.push(result);
return callback();
}
});
}, function(error) {
if(error) {
return callback(error, null);
} else {
queryStack = [];
return callback(null, queryResults);
}
});
}
/**
* A function used to execute the next query from the stack against the
* Datastore.
*
* @param {function} callback - A callback function.
* @param {?error} callback.error - The error returned when executing the
* query. May be null.
* @param {?object} callback.result - The result of running the datastore
* queries. May be null.
*
* @example
* datastore.runNextQuery(function(error, result) {
* if(!error){
* // do something
* }
* });
*/
function runNextQuery(callback) {
gcloudDatastore.runQuery(queryStack[0], function(error, result) {
if(error) {
return callback(error);
} else {
delete queryStack[0];
return callback(null, result);
}
});
}
/**
* A function used to execute the inputted query against the Datastore.
*
* @param {Query} query - A query object to execute.
* @param {function} callback - A callback function.
* @param {?error} callback.error - The error returned when executing the
* query. May be null.
* @param {?object} callback.result - The result of running the datastore
* queries. May be null.
*
* @example
* var query = datastore.createQuery('Animal');
*
* datastore.run(query, function(error, results) {
* if(!error){
* // do something
* }
* });
*/
function runQuery(query, callback) {
gcloud.runQuery(query, function(error, result) {
if(error){
return callback(error);
} else {
return callback(null, result);
}
});
}
return {
addQueries,
addQuery,
allocateIds: gcloudDatastore.allocateIds,
createQuery,
getAllQueries,
getNextQuery,
getStackLength,
key: gcloudDatastore.key,
removeAllQueries,
removeNextQuery,
runAllQueries,
runNextQuery,
runQuery
};
}());
|
var __decorate = this.__decorate || function (decorators, target, key, value) {
var kind = typeof (arguments.length == 2 ? value = target : value);
for (var i = decorators.length - 1; i >= 0; --i) {
var decorator = decorators[i];
switch (kind) {
case "function": value = decorator(value) || value; break;
case "number": decorator(target, key, value); break;
case "undefined": decorator(target, key); break;
case "object": value = decorator(target, key, value) || value; break;
}
}
return value;
};
var AudioProcessor = (function () {
function AudioProcessor(renderer, timeline) {
var _this = this;
this.onProcessing = function () {
var array = new Uint8Array(_this.analyser.frequencyBinCount);
_this.analyser.getByteFrequencyData(array);
_this.renderer.render(array);
_this.timeline.headStep(_this.audioContext.currentTime);
};
this.success = function (decodedBuffer) {
//this.timelineRendere.render(decodedBuffer);
_this.sourceBuffer.buffer = decodedBuffer;
_this.sourceBuffer.start(0);
};
this.timeline = timeline;
//get the audio context
this.audioContext = new AudioContext();
//create the javascript node
this.javascriptNode = this.audioContext.createScriptProcessor(2048, 1, 1);
this.javascriptNode.connect(this.audioContext.destination);
//create the source buffer
this.sourceBuffer = this.audioContext.createBufferSource();
//create the analyser node
this.analyser = this.audioContext.createAnalyser();
this.analyser.smoothingTimeConstant = 0.3;
this.analyser.fftSize = 512;
//connect source to analyser
this.sourceBuffer.connect(this.analyser);
//analyser to speakers
this.analyser.connect(this.javascriptNode);
//connect source to analyser
this.sourceBuffer.connect(this.audioContext.destination);
//this is where we animates the bars
this.javascriptNode.onaudioprocess = this.onProcessing;
this.renderer = renderer;
}
AudioProcessor.prototype.start = function (buffer) {
this.audioContext.decodeAudioData(buffer, this.success, decodeAudioDataFailed);
function decodeAudioDataFailed() {
debugger;
}
};
return AudioProcessor;
})();
exports.AudioProcessor = AudioProcessor;
//# sourceMappingURL=../../components/visualizer/audioProcessor.js.map
|
import 'bootstrap/dist/css/bootstrap.css';
// import 'font-awesome/css/font-awesome.css';
import 'bootstrap/dist/js/bootstrap';
import React from 'react';
import ReactDOM from 'react-dom';
import AppContainer from './containers/app';
import {createStore, applyMiddleware, combineReducers} from 'redux';
import {Provider} from 'react-redux';
import createHistory from 'history/createBrowserHistory';
import {ConnectedRouter, routerReducer, routerMiddleware} from 'react-router-redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
const history = createHistory();
const store = createStore(
combineReducers({routerReducer, ...reducers}),
applyMiddleware(routerMiddleware(history), thunk),
);
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<AppContainer />
</ConnectedRouter>
</Provider>
, document.getElementById('app'));
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app/App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import ErrorGroupsList from './error-groups/list';
import Suites from './suites';
class MainTree extends Component {
static propTypes = {
// from store
groupByError: PropTypes.bool.isRequired
}
render() {
return this.props.groupByError
? <ErrorGroupsList />
: <Suites />;
}
}
export default connect(
({view: {groupByError}}) => ({groupByError})
)(MainTree);
|
/*jshint node:true*/
"use strict";
var program = require('commander');
var npmPackage = require('../package.json');
var JBJ = require('jbj');
var fs = require('fs');
var JSON5 = require('json5');
var JSONStream = require('JSONStream');
var Splitter = require('streaming/splitter.js').Splitter;
var Mapper = require('streaming/mapper.js').Mapper;
var Queue = require('streaming/queue.js').Queue;
var Filter = require('streaming/filter.js').Filter;
var Stringifier = require('streaming/json.js').Stringifier;
var rp = require('request-promise');
var URL = require('url');
function use(val, memo) {
memo.push(val.replace(/^jbj-/,''));
return memo;
}
program
.version(npmPackage.version)
.usage('[options] STYLESHEET {INPUT-FILE | -}')
.option('-u, --use [module]','Name of the JBJ module to use (repeatable)', use, [])
.option('-l, --multi-line', 'apply stylesheet on each line')
.option('-j, --multi-json', 'apply stylesheet on each json')
.option('-p, --json-path <path>', 'use specific path to split json', '.*')
.option('-t, --text-output', 'to force text output')
.option('-e, --encoding [charset]', 'Change charset of input (binary, ascii)', /^(ascii|utf8|binary)$/i, 'utf8')
.parse(process.argv);
var stylesheetPath = program.args[0]; // required
var inputPath = program.args[1]; // filepath or -
if (!stylesheetPath) {
program.help(function (txt) {
return txt + ' STYLESHEET is a required parameter\n\n';
});
}
if (!inputPath) {
program.help(function (txt) {
return txt + ' INPUT-FILE is a required parameter (- is for stdin)\n\n';
});
}
program.use.forEach(function (module) {
JBJ.use(require('jbj-'+module));
});
try {
var stylesheet = JSON5.parse(fs.readFileSync(stylesheetPath, 'utf8'));
}
catch(error) {
if (34 === error.errno) {
console.error('The stylesheet file "' + stylesheetPath + '" does not exist.');
process.exit(2);
}
console.error('Error in stylesheet "' + stylesheetPath + '"',error);
process.exit(3);
}
JBJ.register('http:', function(urlObj, callback) {
rp(URL.format(urlObj))
.then(function (htmlString) {
callback(null, htmlString);
})
.catch(callback);
});
var inputStream = inputPath === '-' ? process.stdin : fs.createReadStream(inputPath, {
encoding: program.encoding
});
inputStream.setEncoding(program.encoding);
if (program.multiJson || program.multiLine) {
var stream = process.stdin;
if (program.jsonPath) {
stream = stream.pipe(JSONStream.parse(program.jsonPath))
}
else {
stream = stream.pipe(new Splitter())
}
stream = stream.pipe(new Filter(function (data) {
data = data.toString()
return data !== '';
}))
stream = stream.pipe(new Queue(5, function (data, encoding, callback) {
if (Buffer.isBuffer(data)) {
data = data.toString()
}
JBJ.render(stylesheet, data, function (error, output) {
if (error) {
callback(error);
}
else {
callback(null, output);
}
});
}, {objectMode: true, decodeStrings: true}))
if (!program.textOutput) {
stream = stream.pipe(JSONStream.stringify())
}
stream.pipe(process.stdout);
}
else {
var input = '';
inputStream.on('readable', function() {
var chunk;
while (null !== (chunk = inputStream.read())) {
input += chunk;
}
});
inputStream.on('end', function () {
input = JSON5.parse(input);
JBJ.render(stylesheet, input, function (error, output) {
if (error) {
console.error(error);
process.exit(4);
}
console.log(output);
});
});
}
inputStream.on('error', function (error) {
if (34 === error.errno) {
console.error('The file "' + inputPath + '" does not exist.');
process.exit(2);
}
console.error(error);
process.exit(1);
});
|
/**
* Gets the repositories of the user from Github
*/
import {take, call, put, select, cancel, takeLatest} from 'redux-saga/effects';
import {LOCATION_CHANGE} from 'react-router-redux';
import {GET_GALLERY, GET_GALLERY_SUCCESS, GET_GALLERY_ERROR, DOWNLOAD_FILE} from './constants';
import {getGallerySuccess, getGalleryError, downloadFileSuccess, downloadFileError} from './actions';
import request from 'utils/request';
import HttpRequest from '../../utils/HttpRequest';
import {sha256} from '../../utils/crypto';
import {makeSelectCurrentUser} from 'containers/App/selectors';
import {makeSelectMediaId} from './selectors'
import {push} from 'react-router-redux';
function fetchGetGallery(token) {
return new HttpRequest().post('/listUserTransactions', {token: token})
}
export function* getGallery() {
const user = yield select(makeSelectCurrentUser());
// const password = yield select(makeSelectPassword());
// let params = {email: email, passwordHash: sha256(password), platform: 'web'}
try {
// Call our request helper (see 'utils/request')
const response = yield call(fetchGetGallery, user.token);
// yield put(reposLoaded(repos, username));
yield put(getGallerySuccess(response))
} catch (err) {
yield put(getGalleryError(err));
}
}
/**
* Root saga manages watcher lifecycle
*/
export function* onGetGallery() {
// Watches for LOAD_REPOS actions and calls getRepos when one comes in.
// By using `takeLatest` only the result of the latest API call is applied.
// It returns task descriptor (just like fork) so we can continue execution
const watcher = yield takeLatest(GET_GALLERY, getGallery);
// Suspend execution until location changes
yield take(LOCATION_CHANGE);
yield cancel(watcher);
}
function fetchDownloadFile(params) {
window.open("http://utadoc.com"+ '/downloadTnxFile/' + params.token + '&' + params.mediaId)
// return new HttpRequest().get('/downloadTnxFile/' + params.token + '&' + params.mediaId, {})
}
export function* downloadFile() {
const user = yield select(makeSelectCurrentUser())
const mediaId = yield select(makeSelectMediaId())
// let params = {email: email, passwordHash: sha256(password), platform: 'web'}
try {
// Call our request helper (see 'utils/request')
const response = yield call(fetchDownloadFile, {token: user.token, mediaId: mediaId});
// yield put(reposLoaded(repos, username));
yield put(downloadFileSuccess(response))
} catch (err) {
yield put(downloadFileError(err));
}
}
/**
* Root saga manages watcher lifecycle
*/
export function* onDownloadFile() {
// Watches for LOAD_REPOS actions and calls getRepos when one comes in.
// By using `takeLatest` only the result of the latest API call is applied.
// It returns task descriptor (just like fork) so we can continue execution
const watcher = yield takeLatest(DOWNLOAD_FILE, downloadFile);
// Suspend execution until location changes
yield take(LOCATION_CHANGE);
yield cancel(watcher);
}
// Bootstrap sagas
export default [
onGetGallery,
onDownloadFile
];
|
var Parser = require('../lib/GuitarProParser.js'),
fs = require('fs'),
expect = require('expect.js');
describe('Parser', function () {
it('Should exists', function () {
expect( Parser ).to.be.a( Function );
});
});
describe('Parsing', function() {
var parser,
parsed;
before( function() {
var data = fs.readFileSync( __dirname + '/files/test.gp4' );
parser = new Parser(data);
parsed = parser.parse();
} );
describe('Header', function() {
it('Should parse file version', function() {
expect( parsed.header.version ).to.match( /FICHIER GUITAR PRO v4./ );
} );
it('Should parse title', function() {
expect( parsed.header.title ).to.be( 'Title' );
} );
it('Should parse subtitle', function(){
expect( parsed.header.subtitle).to.be('Subtitle');
});
it('Should parse artist', function() {
expect( parsed.header.artist ).to.be( 'Artist' );
} );
it('Should parse album', function() {
expect( parsed.header.album ).to.be( 'Album' );
} );
it('Should parse author', function() {
expect( parsed.header.author ).to.be( 'Author' );
} );
it('Should parse copyrights', function() {
expect( parsed.header.copyrights ).to.be( 'Copyright' );
} );
it('Should parse tab author', function() {
expect( parsed.header.tabAuthor ).to.be( 'Tab' );
} );
it('Should parse information', function () {
expect( parsed.header.instruction).to.be('Instruction');
});
it('Should parse notice', function() {
expect( parsed.header.notice1 ).to.be( 'N line 1' );
} );
it('Should parse notice', function() {
expect( parsed.header.notice2 ).to.be( 'N line 2' );
} );
it('Should parse notice', function() {
expect( parsed.header.notice3 ).to.be( 'N line 3' );
} );
it('Should parse notice', function() {
expect( parsed.header.notice4 ).to.be( 'N line 4' );
} );
it('Should parse triplet feel', function() {
expect( parsed.header.tripletFeel ).to.be( false );
} );
} );
describe('Lyrics', function() {
it('Should parse track number that lyrics is bound to', function() {
expect( parsed.lyrics.trackNumber ).to.be(1);
} );
it('Should parse lyrics', function () {
expect(parsed.lyrics.lyric).to.be( '1111\r\n1111\r\n1111\r\n1111\n2222\r\n2222\r\n2222\r\n2222\n3333\r\n3333\r\n3333\n4444\r\n4444\n5555');
});
} );
describe('TechInfo', function() {
it('Should parse tempo', function() {
expect( parsed.technicalInfo.tempo ).to.be(120);
});
it('Should parse key', function() {
expect( parsed.technicalInfo.key ).to.be('G Major');
});
it('Should parse octave', function() {
expect( parsed.technicalInfo.octave ).to.be(0);
});
it('Should parse midi channels to array', function() {
expect( parsed.technicalInfo.midiChannelsArray ).to.be.a( Array );
});
it('Should have 64 midi channels', function() {
expect( parsed.technicalInfo.midiChannelsArray.length ).to.be( 64 );
});
it( 'Should proper parse midi channels', function() {
var midiChannels = parsed.technicalInfo.midiChannelsArray;
expect( midiChannels[0].data.instrument ).to.be( 25 );
expect( midiChannels[1].data.instrument ).to.be( 25 );
for( var i = 2; i < 9; i++ ) {
expect( midiChannels[i].data.instrument ).to.be( 24 );
}
for( i = 10; i < 16; i++ ) {
expect( midiChannels[i].data.instrument ).to.be( 24 );
}
} );
it('Should parse measures', function() {
expect( parsed.technicalInfo.measures ).to.be( 2 );
});
it('Should parse number of tracks', function() {
expect( parsed.technicalInfo.trackNumber ).to.be( 1 );
});
});
} );
|
/**
* A html visual component.
*
* # Basics
* It accommodates all of html elements and some states
* and acts as both View and Control in MVC frameworks.
* It also provides some useful methods to manipulate DOM elements.
*
* The "elem" field is root element of a Presentation and
* a Presentation expects all of queried elements exist in the "elem".
* For example...
* ```javascript
* // This method queries on the "elem" field and bind elements into each fields.
* this.doQueries({ button : ".button", input: ".input" });
* ```
*
* To send requests to abstractions and receive responses from abstractions,
* you can use event method.
* For example...
* ```javascript
* // To send a request to an abstraction
* this.event().raise().load({ name: "test" });
* // To receive a response from an abstraction
* this.event().onAbstraction().change(this.receive); // register a callback method.
* ```
*
* # How to use
* Because Presentation has no rendering logic,
* you must extend it and implement own rendering logic.
* At least, you should override the "doInitialize" method and
* register DOM and framework events.
* For example...
* ```javascript
* // Implements initialization logic
* doInitialize: { value: function() {
* // Load elements into fields.
* this.doQueries({ button: ".button" });
*
* // Register a DOM event
* this.on(button, "click", this.submit);
*
* // Register a framework event on an abstraction
* this.event().onAbstraction().load(this.onLoad);
*
* // Raise a framework event
* this.event().rase().load({ text: "completed!" });
* }}
* ```
*/
this.Presentation = {
/**
* Create a Presentation object.
*
* @param arg The argument. The properties of the argument are following.
* - rootQuery -> The root CSS selector query to obtain the root HTML element of the Presentation object.
* - id -> The object id.
*/
create : function (arg) {
Assert.notNullAll(this, [
[ arg.rootQuery, "arg.rootQuery" ],
[ arg.id, "arg.id" ]
]);
var presentation = Object.create(this, {
elem : { value : null, writable: true },
rootQuery: { value: arg.rootQuery },
id : { value : arg.id },
control : { value : null, writable : true },
eventBuilder : { value : null, writable : true }
});
presentation.eventBuilder = EventBuilder.create(presentation);
Object.defineProperties(presentation, this.fields || {});
for ( var key in arg ) {
presentation[key] == null && (presentation[key] = arg[key]);
}
Object.seal(presentation);
return presentation;
},
/**
* Initialize the object.
* This method will be called from a control.
*
* @param control The control object.
*/
initialize : function (control) {
Assert.notNull(this, control, "control");
this.control = control;
this.elem = this.query(this.rootQuery, control.getElement());
this.doInitialize();
},
/**
* For internal usage.
* You should override this method in inherited objects.
*/
doInitialize : function () {
},
/**
* Get a HTML element by id form the root HTML element of the Presentation object.
*
* @param id The id attribute of the root HTML element.
* @returns {HTMLElement}
*/
getById : function (id) {
Assert.notNull(this, id, "id");
var elemById = this.elem.getElementById(id);
Assert.notNull(this, elemById, "elemById", "id=" + id);
return elemById;
},
/**
* Query a HTML element form the root HTML element of the Presentation object.
*
* @param query The CSS Selector.
* @param target The target HTML element.
* @returns {Node}
*/
query : function (query, target /* can be null! */) {
Assert.notNull(this, query, "query");
target == null && (target = this.elem);
var queriedElem = target.querySelector(query);
Assert.notNull(this, queriedElem, "queriedElem", "query=" + query);
return queriedElem;
},
/**
* Query HTML elements form the root HTML element of the Presentation object.
*
* @param query The CSS Selector.
* @param target The target HTML element.
* @returns {Node}
*/
queryAll : function (query, target /* can be null */) {
Assert.notNull(this, query, "query");
target == null && (target = this.elem);
var queriedElem = target.querySelectorAll(query);
Assert.notNull(this, queriedElem, "queriedElem", "query=" + query);
return queriedElem;
},
/**
* Iterate the HTMLNodeCollection and call the callback.
*
* @param nodeList The HTMLNodeCollection.
* @param func The callback.
*/
forEachNode : function (nodeList, func) {
Assert.notNullAll(this, [
[ nodeList, "nodeList" ],
[ func, "func" ]
]);
Array.prototype.slice.call(nodeList).forEach(func, this);
},
/**
* Bind a callback to a DOM event by event name.
*
* @param elem The target HTML element.
* @param event The event name.
* @param callback The event callback.
*/
on : function (elem, event, callback) {
Assert.notNullAll(this, [
[ elem, "elem" ],
[ event, "event" ],
[ callback, "callback" ]
]);
var me = this;
elem.addEventListener(event, function (event) {
return callback.call(me, event)
});
},
/**
* Bind a callback to a DOM event by CSS selector.
*
* @param query The CSS selector query to obtain a HTML element.
* @param event The event name.
* @param callback The event callback.
*/
onQuery: function(query, event, callback) {
var elem = this.query(query);
this.on(elem, event, callback);
},
/**
* Get the EventBuilder for this object.
* You can use this method for custom logic.
*
* @returns {*|presentation.eventBuilder|c.eventBuilder|proxy.eventBuilder|proxy|eventBuilder}
*/
event : function () {
return this.eventBuilder;
},
/**
* Handle an event.
* The event will be handled by the enclosed EventBuilder object.
*
* @param event The event id.
* @param arg The event argument.
*/
notify : function (event, arg) {
this.event().handle(event, arg);
},
/**
* Bind queried HTML elements into the fields.
*
* It obtains HTML elements by specified CSS selector queries and
* bind these elements into the fields.
* The fields must be defined before invocation.
*
* @param queryMap The CSS selector query to field name map.
*/
doQueries : function (queryMap) {
Assert.notNullAll(this, [
[ queryMap, "queryMap" ]
]);
for ( var key in queryMap ) {
var query = queryMap[key];
this[key] = this.query(query);
}
},
toString : function () {
return "id: " + this.id;
}
};
Object.seal(this.Presentation);
|
import { test, moduleForComponent } from 'ember-qunit';
import Ember from 'ember';
moduleForComponent('repo-actions', 'RepoActionsComponent', {
needs: ['component:build-repo-actions', 'component:job-repo-actions']
});
test('it renders', function() {
var component;
component = this.subject({});
this.render();
return ok(component.$().hasClass('repo-main-tools'), 'component has class');
});
|
/* eslint-disable ember/no-classic-components, ember/require-tagless-components */
/**
* @module ember-paper
*/
import Component from '@ember/component';
/**
* @class PaperToolbarTools
* @extends Ember.Component
*/
export default Component.extend({
classNames: ['md-toolbar-tools']
});
|
var m = require('mraa'); //require mraa
console.log('MRAA Version: ' + m.getVersion()); //write the mraa version to the console
var ledPin = new m.Gpio(0);// pin J17-1
var buttonPin = new m.Gpio(6);// pin J17-7
var led_state = 0; //Boolean to hold the state of the led
buttonPin.dir(m.DIR_IN); //set the gpio direction to input
ledPin.dir(m.DIR_OUT); //set the gpio direction to output
var readState = function () {
var newState = buttonPin.read(); //read the digital value of the pin
newState = newState ? 0 : 1; // Inverts the state so 1 means the button is down.
ledPin.write(newState);
console.log("The LED is in state " + newState);
};
setInterval(readState, 10);
|
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'myApp.routing',
'myApp.datelist',
'myApp.mailchimp',
'ui.bootstrap',
'mailchimp'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);
|
define([
'backbone',
'app/message-dispatcher-client',
'app/view-manager',
'app/app-state'
], function(Backbone, MessageDispatcher, ViewManager, AppState) {
var LoginView = Backbone.View.extend({
templateName: 'login',
className: 'login-view',
initialize: function() {
},
events: {
'click a[data-action="register"]': 'showRegisterForm',
'submit form': 'doLogin'
},
render: function() {
this.$el.html(this.template);
return this;
},
showRegisterForm: function(e) {
e.preventDefault(); // We must call this or the browser URL will be incorrect
ViewManager.trigger('twaddlr:showRegisterView');
},
doLogin: function(e) {
e.preventDefault();
var username = this.$el.find('#username').val();
var password = this.$el.find('#password').val();
MessageDispatcher.once('login:done', $.proxy(function(data) {
console.log("Login sucess! My token: ", data.token);
$.cookie('twaddlr_username', username);
$.cookie('twaddlr_token', data.token);
ViewManager.showNotification('success', "Logged in successfully!", $.proxy(function() {
this.$el.css3Animate('fadeOut', $.proxy(function() {
this.$el.empty();
AppState.set({
username: username,
token: data.token
});
ViewManager.trigger('twaddlr:showChatView');
}, this));
}, this));
}, this));
MessageDispatcher.once('login:error', function(data) {
console.log("Login failed!", data);
if (data.error == 'invalidUsername') {
ViewManager.showNotification('error', "Invalid username!");
} else if (data.error == 'invalidPassword') {
ViewManager.showNotification('error', "Invalid password!");
} else {
ViewManager.showNotification('error', "Login failed!");
}
});
MessageDispatcher.send('login:login', {
username: username,
password: password
});
}
});
//return new LoginView();
return LoginView;
});
|
'use strict';
const { expect } = require('chai');
const character_sheet_reducer = require('../src/components/character_sheet/reducers');
describe('interface.components.character_sheet.reducer', function() {
let action;
let state;
context('on a LOAD_FILE_FULFILLED event', function() {
let sheet;
let filename;
beforeEach(function() {
sheet = { fake: 'sheet' };
filename = 'fake-filename';
action = {
type: 'LOAD_FILE_FULFILLED',
payload: { sheet, filename },
};
});
it('sets the character_sheet', function() {
let new_state = character_sheet_reducer.characterSheet(state, action);
expect(new_state).to.deep.equal({
character_sheet: { fake: 'sheet' },
error: null,
});
});
});
context('on a LOAD_FILE_REJECTED event', function() {
beforeEach(function() {
action = {
type: 'LOAD_FILE_REJECTED',
payload: new Error('fake-file-error'),
};
state = {
error: null,
character_sheet: { fake: 'sheet' },
};
});
it('resets the character_sheet', function() {
let new_state = character_sheet_reducer.characterSheet(state, action);
expect(new_state).to.deep.equal({
character_sheet: null,
error: null,
});
});
});
context('on a CHANGE_STAT event', function() {
let sheet;
beforeEach(function() {
sheet = {
values: {
might: 15,
constitution: 16,
dexterity: 11,
perception: 12,
intellect: 10,
resolve: 11,
},
stat_total: 75,
};
state = {
error: null,
character_sheet: sheet,
}
action = {
type: 'CHANGE_STAT',
payload: {
stat: 'might',
value: 18,
},
};
});
it('updates the stat and total', function() {
let new_state = character_sheet_reducer.characterSheet(state, action);
expect(new_state).to.deep.equal({
character_sheet: {
values: {
might: 18,
constitution: 16,
dexterity: 11,
perception: 12,
intellect: 10,
resolve: 11,
},
stat_total: 78,
},
error: null,
});
});
context('when value is empty', function() {
beforeEach(function() {
action.payload.value = '';
});
it('treats it as a zero', function() {
let new_state = character_sheet_reducer.characterSheet(state, action);
expect(new_state).to.deep.equal({
character_sheet: {
values: {
might: '',
constitution: 16,
dexterity: 11,
perception: 12,
intellect: 10,
resolve: 11,
},
stat_total: 60,
},
error: null,
});
});
});
});
context('on a CHANGE_STAT_FAILURE event', function() {
beforeEach(function() {
state = {
error: null,
character_sheet: { fake: 'sheet' },
};
action = {
type: 'CHANGE_STAT_FAILURE',
payload: new Error('Fake Error'),
};
});
it('sets the error in the state', function() {
let new_state = character_sheet_reducer.characterSheet(state, action);
expect(new_state).to.deep.equal({
character_sheet: { fake: 'sheet' },
error: new Error('Fake Error'),
});
});
});
});
|
const fs = require('fs');
const math = require('mathjs');
var A = JSON.parse(fs.readFileSync('../data/A_1024.json', 'utf8'));
var B = JSON.parse(fs.readFileSync('../data/__B.json', 'utf8'));
var blocks = {
'1024': [{
start: [0, 0],
stop: [511, 511]
}, {
start: [0, 512],
stop: [511, 1023]
}, {
start: [511, 0],
stop: [1023, 511]
}, {
start: [511, 511],
stop: [1023, 1023]
}, ],
'2048': [{
start: [0, 0],
stop: [511, 511]
}, {
start: [0, 512],
stop: [511, 1023]
}, {
start: [0, 1024],
stop: [511, 1535]
}, {
start: [0, 1536],
stop: [511, 2047]
}, {
start: [512, 0],
stop: [1023, 511]
}, {
start: [512, 512],
stop: [1023, 1023]
}, {
start: [512, 1024],
stop: [1023, 1535]
}, {
start: [512, 1536],
stop: [1023, 2047]
}, {
start: [1024, 0],
stop: [1535, 511]
}, {
start: [1024, 512],
stop: [1535, 1023]
}, {
start: [1024, 1024],
stop: [1535, 1535]
}, {
start: [1024, 1536],
stop: [1535, 2047]
}, {
start: [1536, 0],
stop: [2047, 511]
}, {
start: [1536, 512],
stop: [2047, 1023]
}, {
start: [1536, 1024],
stop: [2047, 1535]
}, {
start: [1536, 1536],
stop: [2047, 2047]
}]
}
console.log(math.size(A));
for (let chunk of blocks["2048"]) {
console.log(chunk.start[0], chunk.stop[0])
console.log(chunk.start[1], chunk.stop[1])
let subset = math.subset(A, math.index(math.range(chunk.start[0], chunk.stop[0], true), math.range(chunk.start[1], chunk.stop[1], true)))
console.log(math.size(subset)); // logs "3", "5", "7"
}
|
// Camera setup
// Ship Constructor
function ship() {
THREE.Object3D.call(this);
this.velocity = new THREE.Vector3();
var _this = this;
this.shipModel = new THREE.Mesh();
var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "assets/ship.js", function(geometry, materials) {
var material = new THREE.MeshFaceMaterial( materials );
_this.shipModel = new THREE.Mesh( geometry, material );
_this.shipModel.rotateOnAxis( new THREE.Vector3(1,0,0), Math.PI / 2);
_this.add(_this.shipModel);
});
}
ship.prototype = new THREE.Object3D();
ship.prototype.constructor = ship;
ship.prototype.stats = {
turnRate : 220, // DEGREES PER SECOND
accelRate : 35, // METERS PER SECOND PER SECOND
maxSpeed : 40, // METERS PER SECOND
maxBankAngle : 0.3,
bankAngle: 0 // BANKING ANGLE * GRAPHIC EFFECT ONLY *
};
module.exports = ship;
|
(function(window) {
var Moip = window.Moip || {};
window.Moip = Moip;
function SantanderValidator() {
if ( !( this instanceof SantanderValidator ) ) {
return new SantanderValidator();
}
}
SantanderValidator.prototype = {
agencyNumberIsValid: function(agencyNumber) {
return Moip.CommonBankAccountValidator.agencyNumberIsValid(agencyNumber);
},
agencyCheckNumberIsValid: function(agencyCheckNumber) {
return agencyCheckNumber === undefined || agencyCheckNumber === "";
},
accountNumberIsValid: function(accountNumber) {
return accountNumber.length == this.accountNumberLength() &&
Moip.CommonBankAccountValidator.accountNumberIsValid(accountNumber);
},
accountCheckNumberIsValid: function(accountCheckNumber) {
return Moip.CommonBankAccountValidator.accountCheckNumberIsValid(accountCheckNumber);
},
agencyCheckNumberMatch: function(bankAccount) {
return true;
},
accountCheckNumberMatch: function(bankAccount) {
return true;
},
agencyNumberMsgError: function() {
return Moip.CommonBankAccountValidator.agencyNumberMsgError();
},
agencyCheckNumberMsgError: function() {
return Moip.CommonBankAccountValidator.agencyCheckNumberMsgError();
},
accountNumberMsgError: function() {
return Moip.CommonBankAccountValidator.accountNumberMsgError(this.accountNumberLength());
},
accountNumberLength: function() { return 8; }
};
Moip.SantanderValidator = SantanderValidator();
})(window);
|
import React from 'react';
import { connect } from 'react-redux';
import { Modal, Button, Header, Form } from 'semantic-ui-react';
import copyToClipboard from 'copy-to-clipboard';
import { isModalOpen } from '../../store/selectors/viewModal';
import { selectData } from '../../store/selectors/edited';
import { closeModal } from '../../store/actions/viewModal';
import DownloadFileButton from './DownloadFileButton';
import './styles.css';
const ViewJsonModal = (props) => (
<Modal
size='small'
open={props.isModalOpen}
>
<Header content="JSON Data" />
<Modal.Content className="view-json-modal_content">
<Form size="large">
<Form.Group>
<Form.TextArea
width={16}
disabled
autoHeight
defaultValue={props.data}
/>
</Form.Group>
</Form>
</Modal.Content>
<Modal.Actions>
<Button
icon='paste'
color='green'
basic
content='Copy to Clipboard'
onClick={() => copyToClipboard(props.data)}
/>
<DownloadFileButton fileContent={props.data} />
<Button basic onClick={props.closeModal}>Close</Button>
</Modal.Actions>
</Modal>
);
const mapStateToProps = state => ({
isModalOpen: isModalOpen(state),
data: JSON.stringify(selectData(state, []).toJS(), null, 2),
});
const mapDispatchToProps = {
closeModal,
};
export default connect(mapStateToProps, mapDispatchToProps)(ViewJsonModal);
|
'use strict';
Meteor.methods({
addAccount: function (doc) {
check(doc, app.schemas.addAccountForm);
if(!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
_.extend(doc, { user: Meteor.userId() });
db.accounts.insert(doc);
}
});
|
"use strict";
const os = require("os");
const fs = require("fs-extra-promise");
const Web = require("web");
const { Service } = require("service");
const { ServiceComBus } = require("servicecom");
const Monitor = require("./monitor");
const Configs = require("./controllers/configs");
const Config = require("./types/config");
const ServiceCtrl = require("./controllers/services");
const { Token } = require("auth");
const Db = require("./db");
const { notification } = require("typelib");
class Main extends Service {
constructor(name, version) {
super(name, version);
}
async onSetup() {
await this.provide("REST", {
uri: `http://${os.hostname()}:${this.config.port}`
});
await this.provide("MongoDB", {
uri: this.config.mongo
});
await this.provide("MsgBus", {
uri: this.config.bus.uri
});
// Push msgBus dependency to get rid of circular require dependency
Config.setMb(this.mgr.msgBus);
}
async _createToken() {
const tokenData = {
src: this.name,
priv: [ "*:*" ]
};
const { token } = await Token.instance.createToken(tokenData, {}, Token.TOKEN_TYPE.SERVICE);
return token;
}
async onOnline() {
const dbConfig = {
uri: this.config.mongo,
name: this.name
};
await Db.instance.connect(dbConfig);
this.addDisposable(Db.instance);
let keys;
if (this.config.jwtprivate && this.config.jwtpublic) {
keys = {
private: await fs.readFileAsync(this.config.jwtprivate, "utf8"),
public: await fs.readFileAsync(this.config.jwtpublic, "utf8")
};
Token.instance.setKeys(keys);
Config.setGlobalOpts({ publicKey: keys.public });
}
this.addDisposable(Configs.instance);
const routes = [].concat(Configs.instance.routes, ServiceCtrl.instance.routes, this.routes);
await ServiceComBus.instance.start(Object.assign({
name: this.name,
uri: this.config.bus.uri,
publicKey: keys && keys.public,
token: await Config.createToken(this.name)
}, this.config.servicecom));
this.addDisposable(ServiceComBus.instance);
ServiceComBus.instance.attachControllers([
Configs.instance,
ServiceCtrl.instance,
this.statesControllerInstance
]);
notification.on("config.tagged", Configs.instance.onTagged.bind(Configs.instance));
await Monitor.instance.start();
this.mgr.addMgmtBusListener(Monitor.instance.mgmtBusListener.bind(Monitor.instance));
this.addDisposable(Monitor.instance);
const webOpts = { port: this.config.port };
await Web.instance.start(webOpts, routes);
this.addDisposable(Web.instance);
this.log("info", "I'm online!");
}
async onOffline() {
notification.removeAllListeners("config.tagged");
this.log("info", "I'm offline!");
}
}
module.exports = Main;
|
const Encore = require('@symfony/webpack-encore');
Encore.configureRuntimeEnvironment('dev');
const encoreConfig = require('./webpack-encore-config');
const webpackConfig = encoreConfig('tests/Functional/App/var/karma/build').getWebpackConfig();
delete webpackConfig.entry;
delete webpackConfig.optimization.runtimeChunk;
delete webpackConfig.optimization.splitChunks;
// Replace the mini-css-extract-plugin's loader by the style-loader
const styleExtensions = ['/\\.css$/', '/\\.s[ac]ss$/', '/\\.less$/', '/\\.styl$/'];
for (const rule of webpackConfig.module.rules) {
if (rule.test && rule.oneOf && styleExtensions.includes(rule.test.toString())) {
rule.oneOf.forEach((oneOf) => {
oneOf.use[0] = 'style-loader';
})
}
}
// Karma options
module.exports = function(config) {
config.set({
frameworks: ['jasmine-ajax', 'jasmine'],
browserConsoleLogOptions: {
level: 'log',
terminal: false //Remove console.* logs
},
files: [
'tests/Resources/assets/js/main.js'
],
preprocessors: {
'tests/Resources/assets/js/main.js': ['webpack']
},
webpackMiddleware: {
stats: 'errors-only',
noInfo: true,
},
browsers: ['Firefox'],
reporters: ['spec'],
specReporter: {
suppressPassed: true,
},
webpack: webpackConfig
});
};
|
import {Node} from './data/node';
import {List} from './data/list';
/**
* Add an item to the front of a list.
*
* @example
* const l1 = List.empty();
* const l2 = List.add(1, l2);
* const l3 = List.add(2, l3);
*
* @memberof List
* @param {*} item
* @param {List} list
* @return {List}
*/
export function add(item, list) {
if (item === undefined || item === null) {
return list;
}
const {head} = list;
return new List(new Node(item, head));
}
|
angular
.module('newsRadar')
.component('feedAdd',{
templateUrl: 'assets/news-radar-gui/scripts/feedadd.template.html',
controller: function FeedAddController($http, $rootScope) {
this.addFeed = function(feed) {
$http({
method: 'POST',
url: jsRoutes.controllers.FeedListController.add().url,
data: feed
}).then(function successCallback(response){
$rootScope.$broadcast('feedAddEvent', {
id: response.data,
name: feed.feedName,
address: feed.feedAddress
});
});
};
}
});
|
define('template/helpers/todaysPageViews', ['handlebars'], function (Handlebars) {
function todaysPageViews(items) {
var pageviews = '';
if (items) {
pageviews = parseFloat(items[items.length - 1].pageviews, 10);
if (pageviews > 1000000) {
pageviews = (Math.round(pageviews / 1000000)) + 'M';
} else if (pageviews > 1000) {
pageviews = (Math.round(pageviews / 1000)) + 'K';
}
return pageviews;
}
}
Handlebars.registerHelper('todaysPageViews', todaysPageViews);
return todaysPageViews;
});
|
export default {
key: 'E',
suffix: 'm6',
positions: [
{
frets: '022020',
fingers: '012030'
},
{
frets: '022423',
fingers: '011312',
barres: 2
},
{
frets: 'x75657',
fingers: '031214',
barres: 5,
capo: true
},
{
frets: 'xx9989',
fingers: '002314'
}
]
};
|
function strEqModWhitespace(left, right) {
return left.replace(/\s/g,'') === right.replace(/\s/g,'');
}
export function checkRenderCase(name) {
const result = find(`#result-${name}`).text();
const expected = find(`#expected-${name}`).text();
return strEqModWhitespace(result, expected);
}
|
var Blast = __Protoblast,
Fn = Blast.Bound.Function,
Stage = require('./stage');
/**
* Sputnik class
*
* @constructor
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.0.1
* @version 0.1.0
*
* @param {Object} options
*/
var Sputnik = Fn.inherits('Informer', 'Develry.Sputnik', function Sputnik(options) {
this.options = options || {};
this.stages = new Blast.Classes.Deck();
});
/**
* Is debugging enabled?
*
* @author Jelle De Loecker <jelle@develry.be>
* @since 0.1.0
* @version 0.1.0
*
* @type {Boolean}
*/
Sputnik.setProperty(function debug() {
if (this._debug != null) {
return this._debug;
}
return this.options.debug || false;
}, function setDebug(value) {
this._debug = !!value;
return this._debug;
});
/**
* Log something
*
* @author Jelle De Loecker <jelle@develry.be>
* @since 0.1.0
* @version 0.1.0
*/
Sputnik.setMethod(function log(...args) {
var fnc;
if (this.options.log) {
this.options.log(...args);
} else {
console.log(...args);
}
});
/**
* Add a function to the given stage
*
* @author Jelle De Loecker <jelle@develry.be>
* @since 0.1.0
* @version 0.1.0
*
* @param {String} name Name of the stage
* @param {Function} fnc The function to execute
*
* @return {Stage}
*/
Sputnik.setMethod(function add(name, fnc) {
var stage;
if (typeof name == 'function') {
fnc = name;
name = fnc.name;
}
if (!this.stages.has(name)) {
this.stages.set(name, new Stage(this, name));
}
stage = this.stages.get(name);
if (typeof fnc == 'function' || fnc && fnc.then) {
stage.add(fnc);
}
return stage;
});
/**
* Get a stage, and define it if needed
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.0.2
* @version 0.1.0
*
* @param {String} name The name of the new stage
*
* @returns {Stage} Returns the stage
*/
Sputnik.setMethod(function get(name) {
return this.add(name);
});
/**
* Launch a stage
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.0.1
* @version 0.1.0
*
* @param {String} name The name of the stage
*/
Sputnik.setMethod(function launch(name) {
if (Array.isArray(name)) {
let i;
for (i = 0; i < name.length; i++) {
this.launch(name[i]);
}
return;
}
stage = this.stages.get(name);
if (!stage) {
throw new Error('Unable to start stage "' + name + '": stage not found');
}
let that = this;
this.emit('launching', stage);
stage.start().then(function finished() {
that.emit('launched', stage);
});
});
/**
* Do something after the given stage has finished
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.0.1
* @version 0.1.0
*
* @param {String} name The name of the stage
* @param {Function} callback The function to execute
*
* @return {Pledge}
*/
Sputnik.setMethod(function after(name, callback) {
var result;
if (Array.isArray(name)) {
let tasks = [],
i;
for (i = 0; i < name.length; i++) {
tasks.push(this.after(name[i]));
}
result = Fn.parallel(tasks);
} else {
result = this.get(name).pledge;
}
result.done(callback);
return result;
});
/**
* Do something before the given stage has started
*
* @author Jelle De Loecker <jelle@kipdola.be>
* @since 0.0.1
* @version 0.1.0
*
* @param {String} name The name of the stage
* @param {Function} callback The function to execute
*/
Sputnik.setMethod(function before(name, callback) {
var pledge = new Pledge();
if (Array.isArray(name)) {
return pledge.reject(new Error('`before()` only takes 1 name'));
}
let stage = this.get(name);
stage.before(callback);
return pledge;
});
module.exports = Sputnik;
|
import alt from 'alt'
import axios from 'axios'
import { API_BASE } from 'consts'
// Boilerplate: ExtendedUserActions is for 'extending' a common user for things just this app needs
const ExtendedUserSource = {
fetchCurrent: function(token) {
const instance = axios.create({
headers: { 'Authorization': token }
})
return instance.post(`${API_BASE}/users/current`)
.then(res => res.data)
}
}
export default ExtendedUserSource
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
var _lodash = _interopRequireDefault(require("lodash"));
var _nameClass = _interopRequireDefault(require("../util/nameClass"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _default() {
return function ({
addUtilities,
theme,
variants
}) {
const utilities = _lodash.default.fromPairs(_lodash.default.map(theme('divideOpacity'), (value, modifier) => {
return [`${(0, _nameClass.default)('divide-opacity', modifier)} > :not([hidden]) ~ :not([hidden])`, {
'--tw-divide-opacity': value
}];
}));
addUtilities(utilities, variants('divideOpacity'));
};
}
|
import { realpathSync } from 'fs';
import relative from 'require-relative';
import { handleError } from '../logging.js';
import mergeOptions from './mergeOptions.js';
import batchWarnings from './batchWarnings.js';
import loadConfigFile from './loadConfigFile.js';
import sequence from '../utils/sequence.js';
import build from './build.js';
import watch from './watch.js';
export default function runRollup ( command ) {
if ( command._.length > 1 ) {
handleError({
code: 'ONE_AT_A_TIME',
message: 'rollup can only bundle one file at a time'
});
}
if ( command._.length === 1 ) {
if ( command.input ) {
handleError({
code: 'DUPLICATE_IMPORT_OPTIONS',
message: 'use --input, or pass input path as argument'
});
}
command.input = command._[0];
}
if ( command.environment ) {
command.environment.split( ',' ).forEach( pair => {
const index = pair.indexOf( ':' );
if ( ~index ) {
process.env[ pair.slice( 0, index ) ] = pair.slice( index + 1 );
} else {
process.env[ pair ] = true;
}
});
}
let configFile = command.config === true ? 'rollup.config.js' : command.config;
if ( configFile ) {
if ( configFile.slice( 0, 5 ) === 'node:' ) {
const pkgName = configFile.slice( 5 );
try {
configFile = relative.resolve( `rollup-config-${pkgName}`, process.cwd() );
} catch ( err ) {
try {
configFile = relative.resolve( pkgName, process.cwd() );
} catch ( err ) {
if ( err.code === 'MODULE_NOT_FOUND' ) {
handleError({
code: 'MISSING_EXTERNAL_CONFIG',
message: `Could not resolve config file ${configFile}`
});
}
throw err;
}
}
} else {
// find real path of config so it matches what Node provides to callbacks in require.extensions
configFile = realpathSync( configFile );
}
if (command.watch) process.env.ROLLUP_WATCH = 'true';
loadConfigFile(configFile, command.silent)
.then(normalized => execute( configFile, normalized, command ))
.catch(handleError);
} else {
return execute( configFile, [{}], command );
}
}
function execute ( configFile, configs, command ) {
if ( command.watch ) {
watch( configFile, configs, command, command.silent );
} else {
return sequence( configs, config => {
const { inputOptions, outputOptions, deprecations } = mergeOptions( config, command );
const warnings = batchWarnings();
const onwarn = inputOptions.onwarn;
if ( onwarn ) {
inputOptions.onwarn = warning => {
onwarn( warning, warnings.add );
};
} else {
inputOptions.onwarn = warnings.add;
}
if (deprecations.length) {
inputOptions.onwarn({
code: 'DEPRECATED_OPTIONS',
message: `The following options have been renamed — please update your config: ${deprecations.map(option => `${option.old} -> ${option.new}`).join(', ')}`,
deprecations
});
}
return build( inputOptions, outputOptions, warnings, command.silent );
});
}
}
|
import { useEffect } from 'react';
export default function useHistoryNav(history) {
useEffect(() => {
const handleKeyPress = e => {
if ((e.metaKey || e.altKey) && !e.ctrlKey && !e.shiftKey) {
switch (e.code) {
case 'ArrowLeft':
e.preventDefault();
history.goBack();
break;
case 'ArrowRight':
e.preventDefault();
history.goForward();
break;
default:
// Do nothing
break;
}
}
};
window.addEventListener('keydown', handleKeyPress);
return () => window.removeEventListener('keydown', handleKeyPress);
}, []);
}
|
/**
* Application Config File
*/
'use strict';
var CFG = {
// Paint Area for this application
container: document.getElementById('app'),
// apiPath: 'http://daily-scrum-api.herokuapp.com',
// apiPath: 'http://localhost:5000',
apiPath: 'http://daily-scrum-keystone.herokuapp.com',
estimateList: [
{ value: '0.5', label: '30 mins' },
{ value: '1', label: '1 hour' },
{ value: '1.5', label: '1 hours 30 mins' },
{ value: '2', label: '2 hours' },
{ value: '2.5', label: '2 hours 30 mins' },
{ value: '3', label: '3 hours' },
{ value: '3.5', label: '3 hours 30 mins' },
{ value: '4', label: '4 hours' },
{ value: '4.5', label: '4 hours 30 mins' },
{ value: '5', label: '5 hours' },
{ value: '5.5', label: '5 hours 30 mins' },
{ value: '6', label: '6 hours' },
{ value: '6.5', label: '6 hours 30 mins' },
{ value: '7', label: '7 hours' },
{ value: '7.5', label: '7 hours 30 mins' },
{ value: '8', label: '8 hours' },
]
};
module.exports = CFG;
|
((bbn) => {
let script = document.createElement('script');
script.innerHTML = `<div :class="[componentClass, 'bbn-background', 'bbn-border-box']"
:style="currentStyle"
>
<div :class="['bbn-overlay', $parent.currentOrientation === 'vertical' ? 'bbn-flex-height' : 'bbn-flex-width']">
<div v-if="title"
class="bbn-b bbn-c bbn-header"
v-html="title"
></div>
<div class="bbn-flex-fill">
<div class="bbn-overlay">
<bbn-scroll v-if="scrollable" v-show="!isCollapsed">
<slot></slot>
</bbn-scroll>
<div v-else
v-show="!isCollapsed"
class="bbn-overlay"
:style="{overflow: overflow}"
>
<slot></slot>
</div>
</div>
</div>
</div>
</div>`;
script.setAttribute('id', 'bbn-tpl-component-pane2');
script.setAttribute('type', 'text/x-template');document.body.insertAdjacentElement('beforeend', script);
/**
* @file the bbn-pane component
*
* @description the bbn-pane is a component created to be operated by "bbn-splitter".
* It represents the portion of the single area of the splitter that will contain what the user desires.
*
* @author BBN Solutions
*
* @copyright BBN Solutions
*
* @created 15/02/2017
*/
(function(bbn){
"use strict";
/**
* Classic input with normalized appearance
*/
Vue.component('bbn-pane2', {
mixins: [bbn.vue.basicComponent, bbn.vue.resizerComponent],
props: {
overflow: {
type: String,
default: 'hidden'
},
title: {
type: String
},
size: {
type: [String, Number],
default: ''
},
resizable: {
type: Boolean,
default: undefined
},
collapsible: {
type: Boolean,
default: undefined
},
collapsed: {
type: Boolean,
default: false
},
scrollable: {
type: Boolean,
default: false
},
min: {
type: Number,
default: 40
},
max: {
type: Number,
default: 10000
}
},
data(){
return {
checker: false,
isCollapsed: this.collapsed,
isResizable: this.resizable,
realSize: 0,
lastRealSize: 0,
originalSize: this.size || 'auto',
currentStyle: {}
};
},
computed: {
splitter(){
return this.$parent.$vnode.componentOptions.tag === 'bbn-splitter2' ? this.$parent : false;
}
},
methods: {
getRealSize(){
let rect = this.$el.getBoundingClientRect();
return this.splitter ?
(this.splitter.isVertical ? rect.height : rect.width) :
(rect.height > rect.width ? rect.height : rect.width);
},
getSize(){
return parseInt(this.realSize) + 'px';
},
setSize(size){
if ( this.splitter ){
if ( size < this.min ){
size = this.min;
}
if ( size > this.max ){
size = this.max;
}
this.splitter.setSize(size, this);
}
},
hide(){
this.isCollapsed = true;
},
show(){
this.isCollapsed = false;
},
toggleCollapsed(){
this.isCollapsed = !this.isCollapsed;
},
setStyle(){
let s = {};
if ( this.min ){
s[this.$parent.currentOrientation === 'vertical' ? 'min-height' : 'min-width'] = this.min + 'px';
}
if ( this.max ){
s[this.$parent.currentOrientation === 'vertical' ? 'max-height' : 'max-width'] = this.max + 'px';
}
this.currentStyle = s;
}
},
mounted(){
if ( bbn.fn.isFunction(this.$parent.init) ){
if ( this.resizable === undefined ){
this.isResizable = this.$parent.resizable;
}
this.selfEmit(true);
this.$parent.init();
setTimeout(() => {
this.ready = true;
}, 40)
}
this.$nextTick(() => {
this.setStyle();
this.realSize = this.getRealSize();
this.lastRealSize = this.realSize;
if ( this.splitter ){
this.$watch('splitter.formattedCfg', () => {
this.lastRealSize = this.realSize;
this.realSize = this.getRealSize();
});
this.$watch('splitter.currentOrientation', () => {
this.setStyle();
});
}
})
},
watch:{
collapsed(val){
this.currentHidden = val;
this.isCollapsed = val;
}
}
});
})(bbn);
})(bbn);
|
// vendored from https://github.com/amasad/sane/blob/64ff3a870c42e84f744086884bf55a4f9c22d376/src/node_watcher.js
'use strict';
const EventEmitter = require('events').EventEmitter;
const fs = require('fs');
const platform = require('os').platform();
const path = require('path');
const common = require('./common');
/**
* Constants
*/
const DEFAULT_DELAY = common.DEFAULT_DELAY;
const CHANGE_EVENT = common.CHANGE_EVENT;
const DELETE_EVENT = common.DELETE_EVENT;
const ADD_EVENT = common.ADD_EVENT;
const ALL_EVENT = common.ALL_EVENT;
/**
* Export `NodeWatcher` class.
* Watches `dir`.
*
* @class NodeWatcher
* @param {String} dir
* @param {Object} opts
* @public
*/
module.exports = class NodeWatcher extends EventEmitter {
constructor(dir, opts) {
super();
common.assignOptions(this, opts);
this.watched = Object.create(null);
this.changeTimers = Object.create(null);
this.dirRegistery = Object.create(null);
this.root = path.resolve(dir);
this.watchdir = this.watchdir.bind(this);
this.register = this.register.bind(this);
this.checkedEmitError = this.checkedEmitError.bind(this);
this.watchdir(this.root);
common.recReaddir(
this.root,
this.watchdir,
this.register,
this.emit.bind(this, 'ready'),
this.checkedEmitError,
this.ignored,
);
}
/**
* Register files that matches our globs to know what to type of event to
* emit in the future.
*
* Registery looks like the following:
*
* dirRegister => Map {
* dirpath => Map {
* filename => true
* }
* }
*
* @param {string} filepath
* @return {boolean} whether or not we have registered the file.
* @private
*/
register(filepath) {
const relativePath = path.relative(this.root, filepath);
if (
!common.isFileIncluded(this.globs, this.dot, this.doIgnore, relativePath)
) {
return false;
}
const dir = path.dirname(filepath);
if (!this.dirRegistery[dir]) {
this.dirRegistery[dir] = Object.create(null);
}
const filename = path.basename(filepath);
this.dirRegistery[dir][filename] = true;
return true;
}
/**
* Removes a file from the registery.
*
* @param {string} filepath
* @private
*/
unregister(filepath) {
const dir = path.dirname(filepath);
if (this.dirRegistery[dir]) {
const filename = path.basename(filepath);
delete this.dirRegistery[dir][filename];
}
}
/**
* Removes a dir from the registery.
*
* @param {string} dirpath
* @private
*/
unregisterDir(dirpath) {
if (this.dirRegistery[dirpath]) {
delete this.dirRegistery[dirpath];
}
}
/**
* Checks if a file or directory exists in the registery.
*
* @param {string} fullpath
* @return {boolean}
* @private
*/
registered(fullpath) {
const dir = path.dirname(fullpath);
return (
this.dirRegistery[fullpath] ||
(this.dirRegistery[dir] &&
this.dirRegistery[dir][path.basename(fullpath)])
);
}
/**
* Emit "error" event if it's not an ignorable event
*
* @param error
* @private
*/
checkedEmitError(error) {
if (!isIgnorableFileError(error)) {
this.emit('error', error);
}
}
/**
* Watch a directory.
*
* @param {string} dir
* @private
*/
watchdir(dir) {
if (this.watched[dir]) {
return;
}
const watcher = fs.watch(
dir,
{persistent: true},
this.normalizeChange.bind(this, dir),
);
this.watched[dir] = watcher;
watcher.on('error', this.checkedEmitError);
if (this.root !== dir) {
this.register(dir);
}
}
/**
* Stop watching a directory.
*
* @param {string} dir
* @private
*/
stopWatching(dir) {
if (this.watched[dir]) {
this.watched[dir].close();
delete this.watched[dir];
}
}
/**
* End watching.
*
* @public
*/
close() {
Object.keys(this.watched).forEach(this.stopWatching, this);
this.removeAllListeners();
return Promise.resolve();
}
/**
* On some platforms, as pointed out on the fs docs (most likely just win32)
* the file argument might be missing from the fs event. Try to detect what
* change by detecting if something was deleted or the most recent file change.
*
* @param {string} dir
* @param {string} event
* @param {string} file
* @public
*/
detectChangedFile(dir, event, callback) {
if (!this.dirRegistery[dir]) {
return;
}
let found = false;
let closest = {mtime: 0};
let c = 0;
Object.keys(this.dirRegistery[dir]).forEach(function (file, i, arr) {
fs.lstat(path.join(dir, file), (error, stat) => {
if (found) {
return;
}
if (error) {
if (isIgnorableFileError(error)) {
found = true;
callback(file);
} else {
this.emit('error', error);
}
} else {
if (stat.mtime > closest.mtime) {
stat.file = file;
closest = stat;
}
if (arr.length === ++c) {
callback(closest.file);
}
}
});
}, this);
}
/**
* Normalize fs events and pass it on to be processed.
*
* @param {string} dir
* @param {string} event
* @param {string} file
* @public
*/
normalizeChange(dir, event, file) {
if (!file) {
this.detectChangedFile(dir, event, actualFile => {
if (actualFile) {
this.processChange(dir, event, actualFile);
}
});
} else {
this.processChange(dir, event, path.normalize(file));
}
}
/**
* Process changes.
*
* @param {string} dir
* @param {string} event
* @param {string} file
* @public
*/
processChange(dir, event, file) {
const fullPath = path.join(dir, file);
const relativePath = path.join(path.relative(this.root, dir), file);
fs.lstat(fullPath, (error, stat) => {
if (error && error.code !== 'ENOENT') {
this.emit('error', error);
} else if (!error && stat.isDirectory()) {
// win32 emits usless change events on dirs.
if (event !== 'change') {
this.watchdir(fullPath);
if (
common.isFileIncluded(
this.globs,
this.dot,
this.doIgnore,
relativePath,
)
) {
this.emitEvent(ADD_EVENT, relativePath, stat);
}
}
} else {
const registered = this.registered(fullPath);
if (error && error.code === 'ENOENT') {
this.unregister(fullPath);
this.stopWatching(fullPath);
this.unregisterDir(fullPath);
if (registered) {
this.emitEvent(DELETE_EVENT, relativePath);
}
} else if (registered) {
this.emitEvent(CHANGE_EVENT, relativePath, stat);
} else {
if (this.register(fullPath)) {
this.emitEvent(ADD_EVENT, relativePath, stat);
}
}
}
});
}
/**
* Triggers a 'change' event after debounding it to take care of duplicate
* events on os x.
*
* @private
*/
emitEvent(type, file, stat) {
const key = type + '-' + file;
const addKey = ADD_EVENT + '-' + file;
if (type === CHANGE_EVENT && this.changeTimers[addKey]) {
// Ignore the change event that is immediately fired after an add event.
// (This happens on Linux).
return;
}
clearTimeout(this.changeTimers[key]);
this.changeTimers[key] = setTimeout(() => {
delete this.changeTimers[key];
if (type === ADD_EVENT && stat.isDirectory()) {
// Recursively emit add events and watch for sub-files/folders
common.recReaddir(
path.resolve(this.root, file),
function emitAddDir(dir, stats) {
this.watchdir(dir);
this.rawEmitEvent(ADD_EVENT, path.relative(this.root, dir), stats);
}.bind(this),
function emitAddFile(file, stats) {
this.register(file);
this.rawEmitEvent(ADD_EVENT, path.relative(this.root, file), stats);
}.bind(this),
function endCallback() {},
this.checkedEmitError,
this.ignored,
);
} else {
this.rawEmitEvent(type, file, stat);
}
}, DEFAULT_DELAY);
}
/**
* Actually emit the events
*/
rawEmitEvent(type, file, stat) {
this.emit(type, file, this.root, stat);
this.emit(ALL_EVENT, type, file, this.root, stat);
}
};
/**
* Determine if a given FS error can be ignored
*
* @private
*/
function isIgnorableFileError(error) {
return (
error.code === 'ENOENT' ||
// Workaround Windows node issue #4337.
(error.code === 'EPERM' && platform === 'win32')
);
}
|
import mapValues from 'lodash/mapValues';
import snakeCase from 'lodash/snakeCase';
function ensureTypeSnakeCase(value) {
if (typeof value === 'string') {
return snakeCase(value);
}
return value;
}
export function assessmentMetaDataState(data) {
const blankState = {
assessment: false,
assessmentIds: [],
masteryModel: null,
randomize: false,
};
if (typeof data.assessmentmetadata === 'undefined') {
return blankState;
}
// Data is from a serializer for a one to many key, so it will return an array of length 0 or 1
const assessmentMetaData = data.assessmentmetadata[0];
if (!assessmentMetaData) {
return blankState;
}
const assessmentIds = assessmentMetaData.assessment_item_ids;
const masteryModel = mapValues(assessmentMetaData.mastery_model, ensureTypeSnakeCase);
if (!assessmentIds.length || !Object.keys(masteryModel).length) {
return blankState;
}
return {
assessment: true,
assessmentIds,
masteryModel,
randomize: assessmentMetaData.randomize,
};
}
|
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(require("./components/Check/index"));
//# sourceMappingURL=Check.js.map
|
export default Ember.Route.extend({
beforeModel: function(trans) {
trans.send('event', null);
}
});
|
import alt from '../alt';
import AuthorSource from '../sources/AuthorSource';
class AuthorListActions {
constructor() {
this.generateActions(
'onSuccess',
'onFailure'
);
}
getAuthor(page, limit) {
AuthorSource.getAuthor(page, limit).then((data) => this.onSuccess(data));
}
getMoreAuthor(page, limit, params) {
return AuthorSource.getAuthor(page, limit, params).then(function(data){
return data
});
}
updateAuthor(author){
return AuthorSource.updateAuthor(author).then(function(data){
return data;
});
}
}
export default alt.createActions(AuthorListActions);
|
(function () {
// Mock repository
let adverts = [
{
_id: 0,
_acl: {
creator: 0
},
title: "XBoss 1080",
description: "Modded gaming console",
publisher: "Pesho",
datePublished: "2017-06-04",
price: 100,
image: "./static/fuze-f1.png"
}
];
let users = [{
_kmd: {
authtoken: "mock_token0"
},
_id: 0,
username: "Pesho",
password: "p"
},
{
_kmd: {
authtoken: "mock_token1"
},
_id: 1,
username: "Gosho",
password: "g"
},
{
_kmd: {
authtoken: "mock_token2"
},
_id: 2,
username: "Maria",
password: "m"
}
];
// User login
$.mockjax(function(requestSettings) {
if (requestSettings.url === "https://mock.api.com/user/kid_rk/login") {
return {
response: function(origSettings) {
if (requestSettings.headers["Authorization"] === "Basic a2lkX3JrOjczNjgwNGE2Njg=") {
let target = users.filter(u => u.username === requestSettings.data.username && u.password === requestSettings.data.password);
if (target.length === 0) {
this.status = 403;
this.responseText = "You are not authorized";
} else {
this.responseText = target[0];
}
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
// User create
$.mockjax(function(requestSettings) {
if (requestSettings.url === "https://mock.api.com/user/kid_rk/" &&
requestSettings.method === "POST") {
return {
response: function(origSettings) {
if (requestSettings.headers["Authorization"] === "Basic a2lkX3JrOjczNjgwNGE2Njg=") {
let data = requestSettings.data;
let lastId = 0;
if (users.length > 0) {
lastId = users.map(u => u._id).sort((a, b) => b - a)[0];
}
let user = {
_kmd: {
authtoken: `mock_token${lastId}`
},
_id: lastId,
username: data.username,
password: data.password
};
users.push(user);
this.responseText = user;
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
// Get user info
$.mockjax(function(requestSettings) {
if (requestSettings.url.match(/https:\/\/mock\.api\.com\/user\/kid_rk\/(.+)/)) {
let userId = requestSettings.url.match(/https:\/\/mock\.api\.com\/user\/kid_rk\/(.+)/)[1];
return {
response: function(origSettings) {
if (requestSettings.headers["Authorization"].includes("Kinvey mock_token")) {
let target = users.filter(u => u._id === Number(userId));
this.responseText = target.shift();
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
// Loading of adverts
$.mockjax(function(requestSettings) {
if (requestSettings.url === "https://mock.api.com/appdata/kid_rk/adverts" &&
requestSettings.method === "GET") {
return {
response: function(origSettings) {
if (requestSettings.headers["Authorization"].includes("Kinvey mock_token")) {
this.responseText = adverts;
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
// Create advert
$.mockjax(function(requestSettings) {
if (requestSettings.url === "https://mock.api.com/appdata/kid_rk/adverts" &&
requestSettings.method === "POST") {
return {
response: function(origSettings) {
if (requestSettings.headers["Authorization"].includes("Kinvey mock_token")) {
let data = requestSettings.data;
let lastId = 0;
if (adverts.length > 0) {
lastId = adverts.map(a => a._id).sort((a, b) => b - a)[0];
}
let token = requestSettings.headers["Authorization"].replace("Kinvey ", "");
let creator = users.filter(u => u._kmd.authtoken === token)[0]._id;
let advert = {
_id: ++lastId,
_acl: {
creator: creator
},
title: data.title,
description: data.description,
publisher: data.publisher,
datePublished: data.datePublished,
price: data.price
};
adverts.push(advert);
this.responseText = advert;
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
// Delete advert
$.mockjax(function(requestSettings) {
if (requestSettings.url.match(/https:\/\/mock\.api\.com\/appdata\/kid_rk\/adverts\/(.+)/) &&
requestSettings.method === "DELETE") {
let advertId = Number(requestSettings.url.match(/https:\/\/mock\.api\.com\/appdata\/kid_rk\/adverts\/(.+)/)[1]);
return {
response: function(origSettings) {
if (requestSettings.headers["Authorization"].includes("Kinvey mock_token")) {
adverts = adverts.filter(a => a._id !== advertId);
this.responseText = adverts;
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
// Edit advert
$.mockjax(function(requestSettings) {
if (requestSettings.url.match(/https:\/\/mock\.api\.com\/appdata\/kid_rk\/adverts\/(.+)/) &&
requestSettings.method === "PUT") {
let advertId = Number(requestSettings.url.match(/https:\/\/mock\.api\.com\/appdata\/kid_rk\/adverts\/(.+)/)[1]);
return {
response: function(origSettings) {
if (requestSettings.headers["Authorization"].includes("Kinvey mock_token")) {
let advert = adverts.filter(a => a._id === advertId);
let data = requestSettings.data;
if (advert.length > 0) {
advert = advert[0];
advert.title = data.title;
advert.description = data.description;
advert.publisher = data.publisher;
advert.datePublished = data.datePublished;
advert.price = data.price;
advert.image = data.image;
this.responseText = advert;
}
this.responseText = {};
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
// Loading of adverts
$.mockjax(function (requestSettings) {
if (requestSettings.url==="https://mock.api.com/appdata/kid_rk/adverts" &&
requestSettings.method === "GET") {
return {
response: function (origSettings) {
if (requestSettings.headers["Authorization"].includes("Kinvey mock_token")) {
this.responseText = adverts;
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
// Load single advert
$.mockjax(function (requestSettings) {
if (requestSettings.url.match(/https:\/\/mock\.api\.com\/appdata\/kid_rk\/adverts\/(.+)/) &&
requestSettings.method === "GET") {
let advertId = Number(requestSettings.url.match(/https:\/\/mock\.api\.com\/appdata\/kid_rk\/adverts\/(.+)/)[1]);
return {
response: function (origSettings) {
if (requestSettings.headers["Authorization"].includes("Kinvey mock_token")) {
let advert = adverts.filter(a => a._id === advertId);
this.responseText = advert.shift();
} else {
this.status = 403;
this.responseText = "You are not authorized";
}
}
};
}
});
})();
|
'use strict';
var assert = require('assert');
var runProcess = require('./../../lib/util/run-process').runProcess;
var resolve = require('path').resolve;
var Q = require('q');
var readFile = Q.denodeify(require('fs').readFile);
var CONFIG_PATH = require('./../../package.json').CONFIG_PATH;
var splitInPairs, config;
describe('Coffee / Work options', function() {
beforeEach(function () {
config = config || require(resolve(CONFIG_PATH));
splitInPairs = require('./../../lib/util/formats/' + config.FORMAT).splitInPairs;
});
afterEach(function () {
config = undefined;
});
it('should log coffee breaks', function (done) {
runProcess('fxc', ['--coffee'])
.then(function (output) {
assert.equal(output, 'Logged: \'---- COFFEE BREAK ----\'\n');
return readFile(resolve(config.LOG_PATH), 'utf-8');
})
.then(function (data) {
data = splitInPairs(data, false, config);
assert.equal(data[data.length - 1][1], '---- COFFEE BREAK ----');
})
.done(done);
});
it('should toggle work message', function (done) {
var verb;
runProcess('fxc', ['--work'])
.then(function (output) {
verb = /---- WORK ([A-Z]{4,5}) ----/.exec(output);
verb = verb && verb[1];
assert.ok(verb);
return runProcess('fxc', ['-w']);
})
.then(function (output) {
var otherVerb = /---- WORK ([A-Z]{4,5}) ----/.exec(output);
otherVerb = otherVerb && otherVerb[1];
assert.ok(otherVerb);
assert.ok(verb !== otherVerb);
return readFile(resolve(config.LOG_PATH), 'utf-8');
})
.then(function (data) {
var result = [];
data = splitInPairs(data, false, config);
result.push(data.pop()[1]);
result.push(data.pop()[1]);
result = result.filter(function (item) {
return /---- WORK [A-Z]{4,5} ----/.test(item);
});
assert.equal(result.length, 2);
})
.done(done);
});
});
|
//************ Êèǹ ¤ØÂà¤ÇÊ / à´Ô¹ / â´´´èÒ¹ *************
function FoundCombat(ppid){
}
function FinishBattle(){
}
function Logon(){
}
function PlayerCurrentOnline(uid){
}
|
module.exports = function() {
require('./users')
}
|
Monocle = {
VERSION: "2.3.1"
};
Monocle.pieceLoaded = function (piece) {
if (typeof onMonoclePiece == 'function') {
onMonoclePiece(piece);
}
}
Monocle.defer = function (fn, time) {
if (fn && typeof fn == "function") {
return setTimeout(fn, time || 0);
}
}
Monocle.Dimensions = {}
Monocle.Controls = {};
Monocle.Flippers = {};
Monocle.Panels = {};
Monocle.pieceLoaded("core/monocle");
Monocle.Env = function () {
var API = { constructor: Monocle.Env }
var k = API.constants = API.constructor;
var p = API.properties = {
// Assign to a function before running survey in order to get
// results as they come in. The function should take two arguments:
// testName and value.
resultCallback: null
}
// These are private variables so they don't clutter up properties.
var css = Monocle.Browser.css;
var activeTestName = null;
var frameLoadCallback = null;
var testFrame = null;
var testFrameCntr = null;
var testFrameSize = 100;
var surveyCallback = null;
function survey(cb) {
surveyCallback = cb;
runNextTest();
}
function runNextTest() {
var test = envTests.shift();
if (!test) { return completed(); }
activeTestName = test[0];
try { test[1](); } catch (e) { result(e); }
}
// Each test should call this to say "I'm finished, run the next test."
//
function result(val) {
//console.log("["+activeTestName+"] "+val);
API[activeTestName] = val;
if (p.resultCallback) { p.resultCallback(activeTestName, val); }
runNextTest();
return val;
}
// Invoked after all tests have run.
//
function completed() {
// Remove the test frame after a slight delay (otherwise Gecko spins).
Monocle.defer(removeTestFrame);
if (typeof surveyCallback == "function") {
surveyCallback(API);
}
}
// A bit of sugar for simplifying a detection pattern: does this
// function exist?
//
// Pass a string snippet of JavaScript to be evaluated.
//
function testForFunction(str) {
return function () { result(typeof eval(str) == "function"); }
}
// A bit of sugar to indicate that the detection function for this test
// hasn't been written yet...
//
// Pass the value you want assigned for the test until it is implemented.
//
function testNotYetImplemented(rslt) {
return function () { result(rslt); }
}
// Loads (or reloads) a hidden iframe so that we can test browser features.
//
// cb is the callback that is fired when the test frame's content is loaded.
//
// src is optional, in which case it defaults to 4. If provided, it can be
// a number (specifying the number of pages of default content), or a string,
// which will be loaded as a URL.
//
function loadTestFrame(cb, src) {
if (!testFrame) { testFrame = createTestFrame(); }
frameLoadCallback = cb;
src = src || 4;
if (typeof src == "number") {
var pgs = [];
for (var i = 1, ii = src; i <= ii; ++i) {
pgs.push("<div>Page "+i+"</div>");
}
var divStyle = [
"display:inline-block",
"line-height:"+testFrameSize+"px",
"width:"+testFrameSize+"px"
].join(";");
src = "javascript:'<!DOCTYPE html><html>"+
'<head><meta name="time" content="'+(new Date()).getTime()+'" />'+
'<style>div{'+divStyle+'}</style></head>'+
'<body>'+pgs.join("")+'</body>'+
"</html>'";
}
testFrame.src = src;
}
// Creates the hidden test frame and returns it.
//
function createTestFrame() {
testFrameCntr = document.createElement('div');
testFrameCntr.style.cssText = [
"width:"+testFrameSize+"px",
"height:"+testFrameSize+"px",
"overflow:hidden",
"position:absolute",
"visibility:hidden"
].join(";");
document.body.appendChild(testFrameCntr);
var fr = document.createElement('iframe');
testFrameCntr.appendChild(fr);
fr.setAttribute("scrolling", "no");
fr.style.cssText = [
"width:100%",
"height:100%",
"border:none",
"background:#900"
].join(";");
fr.addEventListener(
"load",
function () {
if (!fr.contentDocument || !fr.contentDocument.body) { return; }
var bd = fr.contentDocument.body;
bd.style.cssText = ([
"margin:0",
"padding:0",
"position:absolute",
"height:100%",
"width:100%",
"-webkit-column-width:"+testFrameSize+"px",
"-webkit-column-gap:0",
"-webkit-column-fill:auto",
"-moz-column-width:"+testFrameSize+"px",
"-moz-column-gap:0",
"-moz-column-fill:auto",
"-o-column-width:"+testFrameSize+"px",
"-o-column-gap:0",
"-o-column-fill:auto",
"column-width:"+testFrameSize+"px",
"column-gap:0",
"column-fill:auto"
].join(";"));
if (bd.scrollHeight > testFrameSize) {
bd.style.cssText += ["min-width:200%", "overflow:hidden"].join(";");
if (bd.scrollHeight <= testFrameSize) {
bd.className = "column-force";
} else {
bd.className = "column-failed "+bd.scrollHeight;
}
}
frameLoadCallback(fr);
},
false
);
return fr;
}
function removeTestFrame() {
if (testFrameCntr && testFrameCntr.parentNode) {
testFrameCntr.parentNode.removeChild(testFrameCntr);
}
}
function columnedWidth(fr) {
var bd = fr.contentDocument.body;
var de = fr.contentDocument.documentElement;
return Math.max(bd.scrollWidth, de.scrollWidth);
}
var envTests = [
// TEST FOR REQUIRED CAPABILITIES
["supportsW3CEvents", testForFunction("window.addEventListener")],
["supportsCustomEvents", testForFunction("document.createEvent")],
["supportsColumns", function () {
result(css.supportsPropertyWithAnyPrefix('column-width'));
}],
["supportsTransform", function () {
result(css.supportsProperty([
'transformProperty',
'WebkitTransform',
'MozTransform',
'OTransform',
'msTransform'
]));
}],
// TEST FOR OPTIONAL CAPABILITIES
// Does it do CSS transitions?
["supportsTransition", function () {
result(css.supportsPropertyWithAnyPrefix('transition'))
}],
// Can we find nodes in a document with an XPath?
//
["supportsXPath", testForFunction("document.evaluate")],
// Can we find nodes in a document natively with a CSS selector?
//
["supportsQuerySelector", testForFunction("document.querySelector")],
// Can we do 3d transforms?
//
["supportsTransform3d", function () {
result(
css.supportsMediaQueryProperty('transform-3d') &&
css.supportsProperty([
'perspectiveProperty',
'WebkitPerspective',
'MozPerspective',
'OPerspective',
'msPerspective'
])
);
}],
// CHECK OUT OUR CONTEXT
// Does the device have a MobileSafari-style touch interface?
//
["touch", function () {
result(
('ontouchstart' in window) ||
css.supportsMediaQueryProperty('touch-enabled')
);
}],
// Is the Reader embedded, or in the top-level window?
//
["embedded", function () { result(top != self) }],
// TEST FOR CERTAIN RENDERING OR INTERACTION BUGS
// iOS (at least up to version 4.1) makes a complete hash of touch events
// when an iframe is overlapped by other elements. It's a dog's breakfast.
// See test/bugs/ios-frame-touch-bug for details.
//
["brokenIframeTouchModel", function () {
result(Monocle.Browser.iOSVersionBelow("4.2"));
}],
// In early versions of iOS (up to 4.1), MobileSafari would send text-select
// activity to the first iframe, even if that iframe is overlapped by a
// "higher" iframe.
//
["selectIgnoresZOrder", function () {
result(Monocle.Browser.iOSVersionBelow("4.2"));
}],
// Webkit-based browsers put floated elements in the wrong spot when
// columns are used -- they appear way down where they would be if there
// were no columns. Presumably the float positions are calculated before
// the columns. A bug has been lodged, and it's fixed in recent WebKits.
//
["floatsIgnoreColumns", function () {
if (!Monocle.Browser.is.WebKit) { return result(false); }
match = navigator.userAgent.match(/AppleWebKit\/([\d\.]+)/);
if (!match) { return result(false); }
return result(match[1] < "534.30");
}],
// The latest engines all agree that if a body is translated leftwards,
// its scrollWidth is shortened. But some older WebKits (notably iOS4)
// do not subtract translateX values from scrollWidth. In this case,
// we should not add the translate back when calculating the width.
//
["widthsIgnoreTranslate", function () {
loadTestFrame(function (fr) {
var firstWidth = columnedWidth(fr);
var s = fr.contentDocument.body.style;
var props = css.toDOMProps("transform");
for (var i = 0, ii = props.length; i < ii; ++i) {
s[props[i]] = "translateX(-600px)";
}
var secondWidth = columnedWidth(fr);
for (i = 0, ii = props.length; i < ii; ++i) {
s[props[i]] = "none";
}
result(secondWidth == firstWidth);
});
}],
// On Android browsers, if the component iframe has a relative width (ie,
// 100%), the width of the entire browser will keep expanding and expanding
// to fit the width of the body of the iframe (which, with columns, is
// massive). So, 100% is treated as "of the body content" rather than "of
// the parent dimensions". In this scenario, we need to give the component
// iframe a fixed width in pixels.
//
// In iOS, the frame is clipped by overflow:hidden, so this doesn't seem to
// be a problem.
//
["relativeIframeExpands", function () {
result(navigator.userAgent.indexOf("Android 2") >= 0);
}],
// iOS3 will pause JavaScript execution if it gets a style-change + a
// scroll change on a component body. Weirdly, this seems to break GBCR
// in iOS4.
//
["scrollToApplyStyle", function () {
result(Monocle.Browser.iOSVersionBelow("4"));
}],
// TEST FOR OTHER QUIRKY BROWSER BEHAVIOUR
// Older versions of WebKit (iOS3, Kindle3) need a min-width set on the
// body of the iframe at 200%. This forces columns. But when this
// min-width is set, it's more difficult to recognise 1 page components,
// so we generally don't want to force it unless we have to.
//
["forceColumns", function () {
loadTestFrame(function (fr) {
var bd = fr.contentDocument.body;
result(bd.className ? true : false);
});
}],
// A component iframe's body is absolutely positioned. This means that
// the documentElement should have a height of 0, since it contains nothing
// other than an absolutely positioned element.
//
// But for some browsers (Gecko and Opera), the documentElement is as
// wide as the full columned content, and the body is only as wide as
// the iframe element (ie, the first column).
//
// It gets weirder. Gecko sometimes behaves like WebKit (not clipping the
// body) IF the component has been loaded via HTML/JS/Nodes, not URL. Still
// can't reproduce outside Monocle.
//
// FIXME: If we can figure out a reliable behaviour for Gecko, we should
// use it to precalculate the workaround. At the moment, this test isn't
// used, but it belongs in src/dimensions/columns.js#columnedDimensions().
//
// ["iframeBodyWidthClipped", function () {
// loadTestFrame(function (fr) {
// var doc = fr.contentDocument;
// result(
// doc.body.scrollWidth <= testFrameSize &&
// doc.documentElement.scrollWidth > testFrameSize
// );
// })
// }],
// Finding the page that a given HTML node is on is typically done by
// calculating the offset of its rectange from the body's rectangle.
//
// But if this information isn't provided by the browser, we need to use
// node.scrollIntoView and check the scrollOffset. Basically iOS3 is the
// only target platform that doesn't give us the rectangle info.
//
["findNodesByScrolling", function () {
result(typeof document.body.getBoundingClientRect !== "function");
}],
// In MobileSafari browsers, iframes are rendered at the width and height
// of their content, rather than having scrollbars. So in that case, it's
// the containing element (the "sheaf") that must be scrolled, not the
// iframe body.
//
["sheafIsScroller", function () {
loadTestFrame(function (fr) {
result(fr.parentNode.scrollWidth > testFrameSize);
});
}],
// For some reason, iOS MobileSafari sometimes loses track of a page after
// slideOut -- it thinks it has an x-translation of 0, rather than -768 or
// whatever. So the page gets "stuck" there, until it is given a non-zero
// x-translation. The workaround is to set a non-zero duration on the jumpIn,
// which seems to force WebKit to recalculate the x of the page. Weird, yeah.
//
["stickySlideOut", function () {
result(Monocle.Browser.is.MobileSafari);
}]
];
function isCompatible() {
return (
API.supportsW3CEvents &&
API.supportsCustomEvents &&
// API.supportsColumns && // This is coming in 3.0!
API.supportsTransform
);
}
API.survey = survey;
API.isCompatible = isCompatible;
return API;
}
Monocle.pieceLoaded('compat/env');
Monocle.CSS = function () {
var API = { constructor: Monocle.CSS }
var k = API.constants = API.constructor;
var p = API.properties = {
guineapig: document.createElement('div')
}
// Returns engine-specific properties,
//
// eg:
//
// toCSSProps('transform')
//
// ... in WebKit, this will return:
//
// ['transform', '-webkit-transform']
//
function toCSSProps(prop) {
var props = [prop];
var eng = k.engines.indexOf(Monocle.Browser.engine);
if (eng) {
var pf = k.prefixes[eng];
if (pf) {
props.push(pf+prop);
}
}
return props;
}
// Returns an engine-specific CSS string.
//
// eg:
//
// toCSSDeclaration('column-width', '300px')
//
// ... in Mozilla, this will return:
//
// "column-width: 300px; -moz-column-width: 300px;"
//
function toCSSDeclaration(prop, val) {
var props = toCSSProps(prop);
for (var i = 0, ii = props.length; i < ii; ++i) {
props[i] += ": "+val+";";
}
return props.join("");
}
// Returns an array of DOM properties specific to this engine.
//
// eg:
//
// toDOMProps('column-width')
//
// ... in Opera, this will return:
//
// [columnWidth, OColumnWidth]
//
function toDOMProps(prop) {
var parts = prop.split('-');
for (var i = parts.length; i > 0; --i) {
parts[i] = capStr(parts[i]);
}
var props = [parts.join('')];
var eng = k.engines.indexOf(Monocle.Browser.engine);
if (eng) {
var pf = k.domprefixes[eng];
if (pf) {
parts[0] = capStr(parts[0]);
props.push(pf+parts.join(''));
}
}
return props;
}
// Is this exact property (or any in this array of properties) supported
// by this engine?
//
function supportsProperty(props) {
for (var i in props) {
if (p.guineapig.style[props[i]] !== undefined) { return true; }
}
return false;
} // Thanks modernizr!
// Is this property (or a prefixed variant) supported by this engine?
//
function supportsPropertyWithAnyPrefix(prop) {
return supportsProperty(toDOMProps(prop));
}
function supportsMediaQuery(query) {
var gpid = "monocle_guineapig";
p.guineapig.id = gpid;
var st = document.createElement('style');
st.textContent = query+'{#'+gpid+'{height:3px}}';
(document.head || document.getElementsByTagName('head')[0]).appendChild(st);
document.documentElement.appendChild(p.guineapig);
var result = p.guineapig.offsetHeight === 3;
st.parentNode.removeChild(st);
p.guineapig.parentNode.removeChild(p.guineapig);
return result;
} // Thanks modernizr!
function supportsMediaQueryProperty(prop) {
return supportsMediaQuery(
'@media (' + k.prefixes.join(prop+'),(') + 'monocle__)'
);
}
function capStr(wd) {
return wd ? wd.charAt(0).toUpperCase() + wd.substr(1) : "";
}
API.toCSSProps = toCSSProps;
API.toCSSDeclaration = toCSSDeclaration;
API.toDOMProps = toDOMProps;
API.supportsProperty = supportsProperty;
API.supportsPropertyWithAnyPrefix = supportsPropertyWithAnyPrefix;
API.supportsMediaQuery = supportsMediaQuery;
API.supportsMediaQueryProperty = supportsMediaQueryProperty;
return API;
}
Monocle.CSS.engines = ["W3C", "WebKit", "Gecko", "Opera", "IE", "Konqueror"];
Monocle.CSS.prefixes = ["", "-webkit-", "-moz-", "-o-", "-ms-", "-khtml-"];
Monocle.CSS.domprefixes = ["", "Webkit", "Moz", "O", "ms", "Khtml"];
Monocle.pieceLoaded('compat/css');
// STUBS - simple debug functions and polyfills to normalise client
// execution environments.
// A little console stub if not initialized in a console-equipped browser.
//
if (typeof window.console == "undefined") {
window.console = {
messages: [],
log: function (msg) {
this.messages.push(msg);
}
}
}
// A simple version of console.dir that works on iOS.
//
window.console.compatDir = function (obj) {
var stringify = function (o) {
var parts = [];
for (x in o) {
parts.push(x + ": " + o[x]);
}
return parts.join("; ");
}
window.console.log(stringify(obj));
}
Monocle.pieceLoaded('compat/stubs');
Monocle.Browser = {}
// Detect the browser engine and set boolean flags for reference.
//
Monocle.Browser.is = {
IE: !!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1),
Opera: navigator.userAgent.indexOf('Opera') > -1,
WebKit: navigator.userAgent.indexOf('AppleWebKit') > -1,
Gecko: navigator.userAgent.indexOf('Gecko') > -1 &&
navigator.userAgent.indexOf('KHTML') === -1,
MobileSafari: !!navigator.userAgent.match(/AppleWebKit.*Mobile/)
} // ... with thanks to PrototypeJS.
if (Monocle.Browser.is.IE) {
Monocle.Browser.engine = "IE";
} else if (Monocle.Browser.is.Opera) {
Monocle.Browser.engine = "Opera";
} else if (Monocle.Browser.is.WebKit) {
Monocle.Browser.engine = "WebKit";
} else if (Monocle.Browser.is.Gecko) {
Monocle.Browser.engine = "Gecko";
} else {
Monocle.Browser.engine = "W3C";
}
// Detect the client platform (typically device/operating system).
//
Monocle.Browser.on = {
iPhone: Monocle.Browser.is.MobileSafari && screen.width == 320,
iPad: Monocle.Browser.is.MobileSafari && screen.width == 768,
UIWebView: Monocle.Browser.is.MobileSafari &&
navigator.userAgent.indexOf("Safari") < 0 &&
!navigator.standalone,
BlackBerry: navigator.userAgent.indexOf("BlackBerry") != -1,
Android: navigator.userAgent.indexOf('Android') != -1,
MacOSX: navigator.userAgent.indexOf('Mac OS X') != -1 &&
!Monocle.Browser.is.MobileSafari,
Kindle3: !!navigator.userAgent.match(/Kindle\/3/)
// TODO: Mac, Windows, etc
}
// It is only because MobileSafari is responsible for so much anguish that
// we special-case it here. Not a badge of honour.
//
if (Monocle.Browser.is.MobileSafari) {
(function () {
var ver = navigator.userAgent.match(/ OS ([\d_]+)/);
if (ver) {
Monocle.Browser.iOSVersion = ver[1].replace(/_/g, '.');
} else {
console.warn("Unknown MobileSafari user agent: "+navigator.userAgent);
}
})();
}
Monocle.Browser.iOSVersionBelow = function (strOrNum) {
return !!Monocle.Browser.iOSVersion && Monocle.Browser.iOSVersion < strOrNum;
}
// A helper class for sniffing CSS features and creating CSS rules
// appropriate to the current rendering engine.
//
Monocle.Browser.css = new Monocle.CSS();
// During Reader initialization, this method is called to create the
// "environment", which tests for the existence of various browser
// features and bugs, then invokes the callback to continue initialization.
//
// If the survey has already been conducted and the env exists, calls
// callback immediately.
//
Monocle.Browser.survey = function (callback) {
if (!Monocle.Browser.env) {
Monocle.Browser.env = new Monocle.Env();
Monocle.Browser.env.survey(callback);
} else if (typeof callback == "function") {
callback();
}
}
Monocle.pieceLoaded('compat/browser');
Monocle.Factory = function (element, label, index, reader) {
var API = { constructor: Monocle.Factory };
var k = API.constants = API.constructor;
var p = API.properties = {
element: element,
label: label,
index: index,
reader: reader,
prefix: reader.properties.classPrefix || ''
}
// If index is null, uses the first available slot. If index is not null and
// the slot is not free, throws an error.
//
function initialize() {
if (!p.label) { return; }
// Append the element to the reader's graph of DOM elements.
var node = p.reader.properties.graph;
node[p.label] = node[p.label] || [];
if (typeof p.index == 'undefined' && node[p.label][p.index]) {
throw('Element already exists in graph: '+p.label+'['+p.index+']');
} else {
p.index = p.index || node[p.label].length;
}
node[p.label][p.index] = p.element;
// Add the label as a class name.
addClass(p.label);
}
// Finds an element that has been created in the context of the current
// reader, with the given label. If oIndex is not provided, returns first.
// If oIndex is provided (eg, n), returns the nth element with the label.
//
function find(oLabel, oIndex) {
if (!p.reader.properties.graph[oLabel]) {
return null;
}
return p.reader.properties.graph[oLabel][oIndex || 0];
}
// Takes an elements and assimilates it into the reader -- essentially
// giving it a "dom" object of it's own. It will then be accessible via find.
//
// Note that (as per comments for initialize), if oIndex is provided and
// there is no free slot in the array for this label at that index, an
// error will be thrown.
//
function claim(oElement, oLabel, oIndex) {
return oElement.dom = new Monocle.Factory(
oElement,
oLabel,
oIndex,
p.reader
);
}
// Create an element with the given label.
//
// The last argument (whether third or fourth) is the options hash. Your
// options are:
//
// class - the classname for the element. Must only be one name.
// html - the innerHTML for the element.
// text - the innerText for the element (an alternative to html, simpler).
//
// Returns the created element.
//
function make(tagName, oLabel, index_or_options, or_options) {
var oIndex, options;
if (arguments.length == 1) {
oLabel = null,
oIndex = 0;
options = {};
} else if (arguments.length == 2) {
oIndex = 0;
options = {};
} else if (arguments.length == 4) {
oIndex = arguments[2];
options = arguments[3];
} else if (arguments.length == 3) {
var lastArg = arguments[arguments.length - 1];
if (typeof lastArg == "number") {
oIndex = lastArg;
options = {};
} else {
oIndex = 0;
options = lastArg;
}
}
var oElement = document.createElement(tagName);
claim(oElement, oLabel, oIndex);
if (options['class']) {
oElement.className += " "+p.prefix+options['class'];
}
if (options['html']) {
oElement.innerHTML = options['html'];
}
if (options['text']) {
oElement.appendChild(document.createTextNode(options['text']));
}
return oElement;
}
// Creates an element by passing all the given arguments to make. Then
// appends the element as a child of the current element.
//
function append(tagName, oLabel, index_or_options, or_options) {
var oElement = make.apply(this, arguments);
p.element.appendChild(oElement);
return oElement;
}
// Returns an array of [label, index, reader] for the given element.
// A simple way to introspect the arguments required for #find, for eg.
//
function address() {
return [p.label, p.index, p.reader];
}
// Apply a set of style rules (hash or string) to the current element.
// See Monocle.Styles.applyRules for more info.
//
function setStyles(rules) {
return Monocle.Styles.applyRules(p.element, rules);
}
function setBetaStyle(property, value) {
return Monocle.Styles.affix(p.element, property, value);
}
// ClassName manipulation functions - with thanks to prototype.js!
// Returns true if one of the current element's classnames matches name --
// classPrefix aware (so don't concate the prefix onto it).
//
function hasClass(name) {
name = p.prefix + name;
var klass = p.element.className;
if (!klass) { return false; }
if (klass == name) { return true; }
return new RegExp("(^|\\s)"+name+"(\\s|$)").test(klass);
}
// Adds name to the classnames of the current element (prepending the
// reader's classPrefix first).
//
function addClass(name) {
if (hasClass(name)) { return; }
var gap = p.element.className ? ' ' : '';
return p.element.className += gap+p.prefix+name;
}
// Removes (classPrefix+)name from the classnames of the current element.
//
function removeClass(name) {
var reName = new RegExp("(^|\\s+)"+p.prefix+name+"(\\s+|$)");
var reTrim = /^\s+|\s+$/g;
var klass = p.element.className;
p.element.className = klass.replace(reName, ' ').replace(reTrim, '');
return p.element.className;
}
API.find = find;
API.claim = claim;
API.make = make;
API.append = append;
API.address = address;
API.setStyles = setStyles;
API.setBetaStyle = setBetaStyle;
API.hasClass = hasClass;
API.addClass = addClass;
API.removeClass = removeClass;
initialize();
return API;
}
Monocle.pieceLoaded('core/factory');
Monocle.Events = {}
// Fire a custom event on a given target element. The attached data object will
// be available to all listeners at evt.m.
//
// Internet Explorer does not permit custom events; we'll wait for a
// version of IE that supports the W3C model.
//
Monocle.Events.dispatch = function (elem, evtType, data, cancelable) {
if (!document.createEvent) {
return true;
}
var evt = document.createEvent("Events");
evt.initEvent(evtType, false, cancelable || false);
evt.m = data;
try {
return elem.dispatchEvent(evt);
} catch(e) {
console.warn("Failed to dispatch event: "+evtType);
return false;
}
}
// Register a function to be invoked when an event fires.
//
Monocle.Events.listen = function (elem, evtType, fn, useCapture) {
if (typeof elem == "string") { elem = document.getElementById(elem); }
return elem.addEventListener(evtType, fn, useCapture || false);
}
// De-register a function from an event.
//
Monocle.Events.deafen = function (elem, evtType, fn, useCapture) {
if (elem.removeEventListener) {
return elem.removeEventListener(evtType, fn, useCapture || false);
} else if (elem.detachEvent) {
try {
return elem.detachEvent('on'+evtType, fn);
} catch(e) {}
}
}
// Register a series of functions to listen for the start, move, end
// events of a mouse or touch interaction.
//
// 'fns' argument is an object like:
//
// {
// 'start': function () { ... },
// 'move': function () { ... },
// 'end': function () { ... },
// 'cancel': function () { ... }
// }
//
// All of the functions in this object are optional.
//
// Each function is passed the event, with additional generic info about the
// cursor/touch position:
//
// event.m.offsetX (& offsetY) -- relative to top-left of document
// event.m.registrantX (& registrantY) -- relative to top-left of elem
//
// 'options' argument:
//
// {
// 'useCapture': true/false
// }
//
// Returns an object that can later be passed to Monocle.Events.deafenForContact
//
Monocle.Events.listenForContact = function (elem, fns, options) {
var listeners = {};
var cursorInfo = function (evt, ci) {
evt.m = {
pageX: ci.pageX,
pageY: ci.pageY
};
var target = evt.target || evt.srcElement;
while (target.nodeType != 1 && target.parentNode) {
target = target.parentNode;
}
// The position of contact from the top left of the element
// on which the event fired.
var offset = offsetFor(evt, target);
evt.m.offsetX = offset[0];
evt.m.offsetY = offset[1];
// The position of contact from the top left of the element
// on which the event is registered.
if (evt.currentTarget) {
offset = offsetFor(evt, evt.currentTarget);
evt.m.registrantX = offset[0];
evt.m.registrantY = offset[1];
}
return evt;
}
var offsetFor = function (evt, elem) {
var r;
if (elem.getBoundingClientRect) {
var er = elem.getBoundingClientRect();
var dr = document.documentElement.getBoundingClientRect();
r = { left: er.left - dr.left, top: er.top - dr.top };
} else {
r = { left: elem.offsetLeft, top: elem.offsetTop }
while (elem = elem.offsetParent) {
if (elem.offsetLeft || elem.offsetTop) {
r.left += elem.offsetLeft;
r.top += elem.offsetTop;
}
}
}
return [evt.m.pageX - r.left, evt.m.pageY - r.top];
}
var capture = (options && options.useCapture) || false;
if (!Monocle.Browser.env.touch) {
if (fns.start) {
listeners.mousedown = function (evt) {
if (evt.button != 0) { return; }
fns.start(cursorInfo(evt, evt));
}
Monocle.Events.listen(elem, 'mousedown', listeners.mousedown, capture);
}
if (fns.move) {
listeners.mousemove = function (evt) {
fns.move(cursorInfo(evt, evt));
}
Monocle.Events.listen(elem, 'mousemove', listeners.mousemove, capture);
}
if (fns.end) {
listeners.mouseup = function (evt) {
fns.end(cursorInfo(evt, evt));
}
Monocle.Events.listen(elem, 'mouseup', listeners.mouseup, capture);
}
if (fns.cancel) {
listeners.mouseout = function (evt) {
obj = evt.relatedTarget || evt.fromElement;
while (obj && (obj = obj.parentNode)) {
if (obj == elem) { return; }
}
fns.cancel(cursorInfo(evt, evt));
}
Monocle.Events.listen(elem, 'mouseout', listeners.mouseout, capture);
}
} else {
if (fns.start) {
listeners.start = function (evt) {
if (evt.touches.length > 1) { return; }
fns.start(cursorInfo(evt, evt.targetTouches[0]));
}
}
if (fns.move) {
listeners.move = function (evt) {
if (evt.touches.length > 1) { return; }
fns.move(cursorInfo(evt, evt.targetTouches[0]));
}
}
if (fns.end) {
listeners.end = function (evt) {
fns.end(cursorInfo(evt, evt.changedTouches[0]));
// BROWSERHACK:
// If there is something listening for contact end events, we always
// prevent the default, because TouchMonitor can't do it (since it
// fires it on a delay: ugh). Would be nice to remove this line and
// standardise things.
evt.preventDefault();
}
}
if (fns.cancel) {
listeners.cancel = function (evt) {
fns.cancel(cursorInfo(evt, evt.changedTouches[0]));
}
}
if (Monocle.Browser.env.brokenIframeTouchModel) {
Monocle.Events.tMonitor = Monocle.Events.tMonitor ||
new Monocle.Events.TouchMonitor();
Monocle.Events.tMonitor.listen(elem, listeners, options);
} else {
for (etype in listeners) {
Monocle.Events.listen(elem, 'touch'+etype, listeners[etype], capture);
}
}
}
return listeners;
}
// The 'listeners' argument is a hash of event names and the functions that
// are registered to them -- de-registers the functions from the events.
//
Monocle.Events.deafenForContact = function (elem, listeners) {
var prefix = "";
if (Monocle.Browser.env.touch) {
prefix = Monocle.Browser.env.brokenIframeTouchModel ? "contact" : "touch";
}
for (evtType in listeners) {
Monocle.Events.deafen(elem, prefix + evtType, listeners[evtType]);
}
}
// Looks for start/end events on an element without significant move events in
// between. Fires on the end event.
//
// Also sets up a dummy click event on Kindle3, so that the elem becomes a
// cursor target.
//
// If the optional activeClass string is provided, and if the element was
// created by a Monocle.Factory, then the activeClass will be applied to the
// element while it is being tapped.
//
// Returns a listeners object that you should pass to deafenForTap if you
// need to.
Monocle.Events.listenForTap = function (elem, fn, activeClass) {
var startPos;
// On Kindle, register a noop function with click to make the elem a
// cursor target.
if (Monocle.Browser.on.Kindle3) {
Monocle.Events.listen(elem, 'click', function () {});
}
var annul = function () {
startPos = null;
if (activeClass && elem.dom) { elem.dom.removeClass(activeClass); }
}
var annulIfOutOfBounds = function (evt) {
// We don't have to track this nonsense for mouse events.
if (evt.type.match(/^mouse/)) {
return;
}
// Doesn't work on iOS 3.1 for some reason, so ignore for that version.
if (Monocle.Browser.is.MobileSafari && Monocle.Browser.iOSVersion < "3.2") {
return;
}
if (
evt.m.registrantX < 0 || evt.m.registrantX > elem.offsetWidth ||
evt.m.registrantY < 0 || evt.m.registrantY > elem.offsetHeight
) {
annul();
}
}
return Monocle.Events.listenForContact(
elem,
{
start: function (evt) {
startPos = [evt.m.pageX, evt.m.pageY];
if (activeClass && elem.dom) { elem.dom.addClass(activeClass); }
},
move: annulIfOutOfBounds,
end: function (evt) {
annulIfOutOfBounds(evt);
if (startPos) {
evt.m.startOffset = startPos;
fn(evt);
}
annul();
},
cancel: annul
},
{
useCapture: false
}
);
}
Monocle.Events.deafenForTap = Monocle.Events.deafenForContact;
// Listen for the next transition-end event on the given element, call
// the function, then deafen.
//
// Returns a function that can be used to cancel the listen early.
//
Monocle.Events.afterTransition = function (elem, fn) {
var evtName = "transitionend";
if (Monocle.Browser.is.WebKit) {
evtName = 'webkitTransitionEnd';
} else if (Monocle.Browser.is.Opera) {
evtName = 'oTransitionEnd';
}
var l = null, cancel = null;
l = function () { fn(); cancel(); }
cancel = function () { Monocle.Events.deafen(elem, evtName, l); }
Monocle.Events.listen(elem, evtName, l);
return cancel;
}
// BROWSERHACK: iOS touch events on iframes are busted. The TouchMonitor,
// transposes touch events on underlying iframes onto the elements that
// sit above them. It's a massive hack.
Monocle.Events.TouchMonitor = function () {
if (Monocle.Events == this) {
return new Monocle.Events.TouchMonitor();
}
var API = { constructor: Monocle.Events.TouchMonitor }
var k = API.constants = API.constructor;
var p = API.properties = {
touching: null,
edataPrev: null,
originator: null,
brokenModel_4_1: navigator.userAgent.match(/ OS 4_1/)
}
function listenOnIframe(iframe) {
if (iframe.contentDocument) {
enableTouchProxy(iframe.contentDocument);
iframe.contentDocument.isTouchFrame = true;
}
// IN 4.1 ONLY, a touchstart/end/both fires on the *frame* itself when a
// touch completes on a part of the iframe that is not overlapped by
// anything. This should be translated to a touchend on the touching
// object.
if (p.brokenModel_4_1) {
enableTouchProxy(iframe);
}
}
function listen(element, fns, useCapture) {
for (etype in fns) {
Monocle.Events.listen(element, 'contact'+etype, fns[etype], useCapture);
}
enableTouchProxy(element, useCapture);
}
function enableTouchProxy(element, useCapture) {
if (element.monocleTouchProxy) {
return;
}
element.monocleTouchProxy = true;
var fn = function (evt) { touchProxyHandler(element, evt) }
Monocle.Events.listen(element, "touchstart", fn, useCapture);
Monocle.Events.listen(element, "touchmove", fn, useCapture);
Monocle.Events.listen(element, "touchend", fn, useCapture);
Monocle.Events.listen(element, "touchcancel", fn, useCapture);
}
function touchProxyHandler(element, evt) {
var edata = {
start: evt.type == "touchstart",
move: evt.type == "touchmove",
end: evt.type == "touchend" || evt.type == "touchcancel",
time: new Date().getTime(),
frame: element.isTouchFrame
}
if (!p.touching) {
p.originator = element;
}
var target = element;
var touch = evt.touches[0] || evt.changedTouches[0];
target = document.elementFromPoint(touch.screenX, touch.screenY);
if (target) {
translateTouchEvent(element, target, evt, edata);
}
}
function translateTouchEvent(element, target, evt, edata) {
// IN 4.1 ONLY, if we have a touch start on the layer, and it's been
// almost no time since we had a touch end on the layer, discard the start.
// (This is the most broken thing about 4.1.)
// FIXME: this seems to discard all "taps" on a naked iframe.
if (
p.brokenModel_4_1 &&
!edata.frame &&
!p.touching &&
edata.start &&
p.edataPrev &&
p.edataPrev.end &&
(edata.time - p.edataPrev.time) < 30
) {
evt.preventDefault();
return;
}
// If we don't have a touch and we see a start or a move on anything, start
// a touch.
if (!p.touching && !edata.end) {
return fireStart(evt, target, edata);
}
// If this is a move event and we already have a touch, continue the move.
if (edata.move && p.touching) {
return fireMove(evt, edata);
}
if (p.brokenModel_4_1) {
// IN 4.1 ONLY, if we have a touch in progress, and we see a start, end
// or cancel event (moves are covered in previous rule), and the event
// is not on the iframe, end the touch.
// (This is because 4.1 bizarrely sends a random event to the layer
// above the iframe, rather than an end event to the iframe itself.)
if (p.touching && !edata.frame) {
// However, a touch start will fire on the layer when moving out of
// the overlap with the frame. This would trigger the end of the touch.
// And the immediately subsequent move starts a new touch.
//
// To get around this, we only provisionally end the touch - if we get
// a touchmove momentarily, we'll cancel this touchend.
return fireProvisionalEnd(evt, edata);
}
} else {
// In older versions of MobileSafari, if the touch ends when we're
// touching something, just fire it.
if (edata.end && p.touching) {
return fireProvisionalEnd(evt, edata);
}
}
// IN 4.1 ONLY, a touch that has started outside an iframe should not be
// endable by the iframe.
if (
p.brokenModel_4_1 &&
p.originator != element &&
edata.frame &&
edata.end
) {
evt.preventDefault();
return;
}
// If we see a touch end on the frame, end the touch.
if (edata.frame && edata.end && p.touching) {
return fireProvisionalEnd(evt, edata);
}
}
function fireStart(evt, target, edata) {
p.touching = target;
p.edataPrev = edata;
return fireTouchEvent(p.touching, 'start', evt);
}
function fireMove(evt, edata) {
clearProvisionalEnd();
p.edataPrev = edata;
return fireTouchEvent(p.touching, 'move', evt);
}
function fireEnd(evt, edata) {
var result = fireTouchEvent(p.touching, 'end', evt);
p.edataPrev = edata;
p.touching = null;
return result;
}
function fireProvisionalEnd(evt, edata) {
clearProvisionalEnd();
var mimicEvt = mimicTouchEvent(p.touching, 'end', evt);
p.edataPrev = edata;
p.provisionalEnd = setTimeout(
function() {
if (p.touching) {
p.touching.dispatchEvent(mimicEvt);
p.touching = null;
}
},
30
);
}
function clearProvisionalEnd() {
if (p.provisionalEnd) {
clearTimeout(p.provisionalEnd);
p.provisionalEnd = null;
}
}
function mimicTouchEvent(target, newtype, evt) {
var cloneTouch = function (t) {
return document.createTouch(
document.defaultView,
target,
t.identifier,
t.screenX,
t.screenY,
t.screenX,
t.screenY
);
}
var findTouch = function (id) {
for (var i = 0; i < touches.all.length; ++i) {
if (touches.all[i].identifier == id) {
return touches.all[i];
}
}
}
// Mimic the event data, dispatching it on the new target.
var touches = { all: [], target: [], changed: [] };
for (var i = 0; i < evt.touches.length; ++i) {
touches.all.push(cloneTouch(evt.touches[i]));
}
for (var i = 0; i < evt.targetTouches.length; ++i) {
touches.target.push(
findTouch(evt.targetTouches[i].identifier) ||
cloneTouch(evt.targetTouches[i])
);
}
for (var i = 0; i < evt.changedTouches.length; ++i) {
touches.changed.push(
findTouch(evt.changedTouches[i].identifier) ||
cloneTouch(evt.changedTouches[i])
);
}
var mimicEvt = document.createEvent('TouchEvent');
mimicEvt.initTouchEvent(
"contact"+newtype,
true,
true,
document.defaultView,
evt.detail,
evt.screenX,
evt.screenY,
evt.screenX,
evt.screenY,
evt.ctrlKey,
evt.altKey,
evt.shiftKey,
evt.metaKey,
document.createTouchList.apply(document, touches.all),
document.createTouchList.apply(document, touches.target),
document.createTouchList.apply(document, touches.changed),
evt.scale,
evt.rotation
);
return mimicEvt;
}
function fireTouchEvent(target, newtype, evt) {
var mimicEvt = mimicTouchEvent(target, newtype, evt);
var result = target.dispatchEvent(mimicEvt);
if (!result) {
evt.preventDefault();
}
return result;
}
API.listen = listen;
API.listenOnIframe = listenOnIframe;
return API;
}
Monocle.Events.listenOnIframe = function (frame) {
if (!Monocle.Browser.env.brokenIframeTouchModel) {
return;
}
Monocle.Events.tMonitor = Monocle.Events.tMonitor ||
new Monocle.Events.TouchMonitor();
Monocle.Events.tMonitor.listenOnIframe(frame);
}
Monocle.pieceLoaded('core/events');
Monocle.Styles = {
// Takes a hash and returns a string.
rulesToString: function (rules) {
if (typeof rules != 'string') {
var parts = [];
for (var declaration in rules) {
parts.push(declaration+": "+rules[declaration]+";")
}
rules = parts.join(" ");
}
return rules;
},
// Takes a hash or string of CSS property assignments and applies them
// to the element.
//
applyRules: function (elem, rules) {
rules = Monocle.Styles.rulesToString(rules);
elem.style.cssText += ';'+rules;
return elem.style.cssText;
},
// Generates cross-browser properties for a given property.
// ie, affix(<elem>, 'transition', 'linear 100ms') would apply that value
// to webkitTransition for WebKit browsers, and to MozTransition for Gecko.
//
affix: function (elem, property, value) {
var target = elem.style ? elem.style : elem;
var props = Monocle.Browser.css.toDOMProps(property);
while (props.length) { target[props.shift()] = value; }
},
setX: function (elem, x) {
var s = elem.style;
if (typeof x == "number") { x += "px"; }
if (Monocle.Browser.env.supportsTransform3d) {
s.webkitTransform = "translate3d("+x+", 0, 0)";
} else {
s.webkitTransform = "translateX("+x+")";
}
s.MozTransform = s.OTransform = s.transform = "translateX("+x+")";
return x;
},
setY: function (elem, y) {
var s = elem.style;
if (typeof y == "number") { y += "px"; }
if (Monocle.Browser.env.supportsTransform3d) {
s.webkitTransform = "translate3d(0, "+y+", 0)";
} else {
s.webkitTransform = "translateY("+y+")";
}
s.MozTransform = s.OTransform = s.transform = "translateY("+y+")";
return y;
},
getX: function (elem) {
var currStyle = document.defaultView.getComputedStyle(elem, null);
var re = /matrix\([^,]+,[^,]+,[^,]+,[^,]+,\s*([^,]+),[^\)]+\)/;
var props = Monocle.Browser.css.toDOMProps('transform');
var matrix = null;
while (props.length && !matrix) {
matrix = currStyle[props.shift()];
}
return parseInt(matrix.match(re)[1]);
},
transitionFor: function (elem, prop, duration, timing, delay) {
var tProps = Monocle.Browser.css.toDOMProps('transition');
var pProps = Monocle.Browser.css.toCSSProps(prop);
timing = timing || "linear";
delay = (delay || 0)+"ms";
for (var i = 0, ii = tProps.length; i < ii; ++i) {
var t = "none";
if (duration) {
t = [pProps[i], duration+"ms", timing, delay].join(" ");
}
elem.style[tProps[i]] = t;
}
}
}
// These rule definitions are more or less compulsory for Monocle to behave
// as expected. Which is why they appear here and not in the stylesheet.
// Adjust them if you know what you're doing.
//
Monocle.Styles.container = {
"position": "absolute",
"top": "0",
"left": "0",
"bottom": "0",
"right": "0"
}
Monocle.Styles.page = {
"position": "absolute",
"z-index": "1",
"-webkit-user-select": "none",
"-moz-user-select": "none",
"user-select": "none",
"-webkit-transform": "translate3d(0,0,0)",
"visibility": "visible"
/*
"background": "white",
"top": "0",
"left": "0",
"bottom": "0",
"right": "0"
*/
}
Monocle.Styles.sheaf = {
"position": "absolute",
"overflow": "hidden"
/*
"top": "0",
"left": "0",
"bottom": "0",
"right": "0"
*/
}
Monocle.Styles.component = {
"width": "100%",
"height": "100%",
"border": "none",
"-webkit-user-select": "none",
"-moz-user-select": "none",
"user-select": "none"
}
Monocle.Styles.control = {
"z-index": "100",
"cursor": "pointer"
}
Monocle.Styles.overlay = {
"position": "absolute",
"display": "none",
"width": "100%",
"height": "100%",
"z-index": "1000"
}
Monocle.pieceLoaded('core/styles');
// READER
//
//
// The full DOM hierarchy created by Reader is:
//
// box
// -> container
// -> pages (the number of page elements is determined by the flipper)
// -> sheaf (basically just sets the margins)
// -> component (an iframe created by the current component)
// -> body (the document.body of the iframe)
// -> page controls
// -> standard controls
// -> overlay
// -> modal/popover controls
//
//
// Options:
//
// flipper: The class of page flipper to use.
//
// panels: The class of panels to use
//
// stylesheet: A string of CSS rules to apply to the contents of each
// component loaded into the reader.
//
// place: A book locus for the page to open to when the reader is
// initialized. (See comments at Book#pageNumberAt for more about
// the locus option).
//
// systemId: the id for root elements of components, defaults to "RS:monocle"
//
Monocle.Reader = function (node, bookData, options, onLoadCallback) {
if (Monocle == this) {
return new Monocle.Reader(node, bookData, options, onLoadCallback);
}
var API = { constructor: Monocle.Reader }
var k = API.constants = API.constructor;
var p = API.properties = {
// Initialization-completed flag.
initialized: false,
// The active book.
book: null,
// DOM graph of factory-generated objects.
graph: {},
// An array of style rules that are automatically applied to every page.
pageStylesheets: [],
// Id applied to the HTML element of each component, can be used to scope
// CSS rules.
systemId: (options ? options.systemId : null) || k.DEFAULT_SYSTEM_ID,
// Prefix for classnames for any created element.
classPrefix: k.DEFAULT_CLASS_PREFIX,
// Registered control objects (see addControl). Hashes of the form:
// {
// control: <control instance>,
// elements: <array of topmost elements created by control>,
// controlType: <standard, page, modal, popover, invisible, etc>
// }
controls: [],
// After the reader has been resized, this resettable timer must expire
// the place is restored.
resizeTimer: null
}
var dom;
// Inspects the browser environment and kicks off preparing the container.
//
function initialize() {
options = options || {}
Monocle.Browser.survey(prepareBox);
}
// Sets up the container and internal elements.
//
function prepareBox() {
var box = node;
if (typeof box == "string") { box = document.getElementById(box); }
dom = API.dom = box.dom = new Monocle.Factory(box, 'box', 0, API);
if (!Monocle.Browser.env.isCompatible()) {
if (dispatchEvent("monocle:incompatible", {}, true)) {
// TODO: Something cheerier? More informative?
box.innerHTML = "Your browser is not compatible with Monocle.";
}
return;
}
dispatchEvent("monocle:initializing");
var bk;
if (bookData) {
bk = new Monocle.Book(bookData);
} else {
bk = Monocle.Book.fromNodes([box.cloneNode(true)]);
}
box.innerHTML = "";
// Make sure the box div is absolutely or relatively positioned.
positionBox();
// Attach the page-flipping gadget.
attachFlipper(options.flipper);
// Create the essential DOM elements.
createReaderElements();
// Clamp page frames to a set of styles that reduce Monocle breakage.
clampStylesheets(options.stylesheet);
primeFrames(options.primeURL, function () {
// Make the reader elements look pretty.
applyStyles();
listen('monocle:componentmodify', persistPageStylesOnComponentChange);
p.flipper.listenForInteraction(options.panels);
setBook(bk, options.place, function () {
p.initialized = true;
if (onLoadCallback) { onLoadCallback(API); }
dispatchEvent("monocle:loaded");
});
});
}
function positionBox() {
var currPosVal;
var box = dom.find('box');
if (document.defaultView) {
var currStyle = document.defaultView.getComputedStyle(box, null);
currPosVal = currStyle.getPropertyValue('position');
} else if (box.currentStyle) {
currPosVal = box.currentStyle.position
}
if (["absolute", "relative"].indexOf(currPosVal) == -1) {
box.style.position = "relative";
}
}
function attachFlipper(flipperClass) {
if (!flipperClass) {
if (!Monocle.Browser.env.supportsColumns) {
flipperClass = Monocle.Flippers.Legacy;
} else if (Monocle.Browser.on.Kindle3) {
flipperClass = Monocle.Flippers.Instant;
}
flipperClass = flipperClass || Monocle.Flippers.Slider;
}
if (!flipperClass) { throw("Flipper not found."); }
p.flipper = new flipperClass(API, null, p.readerOptions);
}
function createReaderElements() {
var cntr = dom.append('div', 'container');
for (var i = 0; i < p.flipper.pageCount; ++i) {
var page = cntr.dom.append('div', 'page', i);
page.style.visibility = "hidden";
page.m = { reader: API, pageIndex: i, place: null }
page.m.sheafDiv = page.dom.append('div', 'sheaf', i);
page.m.activeFrame = page.m.sheafDiv.dom.append('iframe', 'component', i);
page.m.activeFrame.m = { 'pageDiv': page };
page.m.activeFrame.setAttribute('frameBorder', 0);
page.m.activeFrame.setAttribute('scrolling', 'no');
p.flipper.addPage(page);
// BROWSERHACK: hook up the iframe to the touchmonitor if it exists.
Monocle.Events.listenOnIframe(page.m.activeFrame);
}
dom.append('div', 'overlay');
dispatchEvent("monocle:loading");
}
function clampStylesheets(customStylesheet) {
var defCSS = k.DEFAULT_STYLE_RULES;
if (Monocle.Browser.env.floatsIgnoreColumns) {
defCSS.push("html#RS\\:monocle * { float: none !important;}");
}
p.defaultStyles = addPageStyles(defCSS, false);
if (customStylesheet) {
p.initialStyles = addPageStyles(customStylesheet, false);
}
}
// Opens the frame to a particular URL (usually 'about:blank').
//
function primeFrames(url, callback) {
url = url || (Monocle.Browser.on.UIWebView ? "blank.html" : "about:blank");
var pageCount = 0;
var cb = function (evt) {
var frame = evt.target || evt.srcElement;
Monocle.Events.deafen(frame, 'load', cb);
dispatchEvent(
'monocle:frameprimed',
{ frame: frame, pageIndex: pageCount }
);
if ((pageCount += 1) == p.flipper.pageCount) {
Monocle.defer(callback);
}
}
forEachPage(function (page) {
Monocle.Events.listen(page.m.activeFrame, 'load', cb);
page.m.activeFrame.src = url;
});
}
function applyStyles() {
dom.find('container').dom.setStyles(Monocle.Styles.container);
forEachPage(function (page, i) {
page.dom.setStyles(Monocle.Styles.page);
dom.find('sheaf', i).dom.setStyles(Monocle.Styles.sheaf);
var cmpt = dom.find('component', i)
cmpt.dom.setStyles(Monocle.Styles.component);
});
lockFrameWidths();
dom.find('overlay').dom.setStyles(Monocle.Styles.overlay);
dispatchEvent('monocle:styles');
}
function lockingFrameWidths() {
if (!Monocle.Browser.env.relativeIframeExpands) { return; }
for (var i = 0, cmpt; cmpt = dom.find('component', i); ++i) {
cmpt.style.display = "none";
}
}
function lockFrameWidths() {
if (!Monocle.Browser.env.relativeIframeExpands) { return; }
for (var i = 0, cmpt; cmpt = dom.find('component', i); ++i) {
cmpt.style.width = cmpt.parentNode.offsetWidth+"px";
cmpt.style.display = "block";
}
}
// Apply the book, move to a particular place or just the first page, wait
// for everything to complete, then fire the callback.
//
function setBook(bk, place, callback) {
p.book = bk;
var pageCount = 0;
if (typeof callback == 'function') {
var watchers = {
'monocle:componentchange': function (evt) {
dispatchEvent('monocle:firstcomponentchange', evt.m);
return (pageCount += 1) == p.flipper.pageCount;
},
'monocle:turn': function (evt) {
callback();
return true;
}
}
var listener = function (evt) {
if (watchers[evt.type](evt)) { deafen(evt.type, listener); }
}
for (evtType in watchers) { listen(evtType, listener) }
}
p.flipper.moveTo(place || { page: 1 });
}
function getBook() {
return p.book;
}
// Attempts to restore the place we were up to in the book before the
// reader was resized.
//
function resized() {
if (!p.initialized) {
console.warn('Attempt to resize book before initialization.');
}
lockingFrameWidths();
if (!dispatchEvent("monocle:resizing", {}, true)) {
return;
}
clearTimeout(p.resizeTimer);
p.resizeTimer = setTimeout(
function () {
lockFrameWidths();
recalculateDimensions(true);
dispatchEvent("monocle:resize");
},
k.RESIZE_DELAY
);
}
function recalculateDimensions(andRestorePlace) {
if (!p.book) { return; }
dispatchEvent("monocle:recalculating");
var place, locus;
if (andRestorePlace !== false) {
var place = getPlace();
var locus = { percent: place ? place.percentageThrough() : 0 };
}
// Better to use an event? Or chaining consecutively?
forEachPage(function (pageDiv) {
pageDiv.m.activeFrame.m.component.updateDimensions(pageDiv);
});
Monocle.defer(function () {
if (locus) { p.flipper.moveTo(locus); }
dispatchEvent("monocle:recalculated");
});
}
// Returns the current page number in the book.
//
// The pageDiv argument is optional - typically defaults to whatever the
// flipper thinks is the "active" page.
//
function pageNumber(pageDiv) {
var place = getPlace(pageDiv);
return place ? (place.pageNumber() || 1) : 1;
}
// Returns the current "place" in the book -- ie, the page number, chapter
// title, etc.
//
// The pageDiv argument is optional - typically defaults to whatever the
// flipper thinks is the "active" page.
//
function getPlace(pageDiv) {
if (!p.initialized) {
console.warn('Attempt to access place before initialization.');
}
return p.flipper.getPlace(pageDiv);
}
// Moves the current page as specified by the locus. See
// Monocle.Book#pageNumberAt for documentation on the locus argument.
//
// The callback argument is optional.
//
function moveTo(locus, callback) {
if (!p.initialized) {
console.warn('Attempt to move place before initialization.');
}
if (!p.book.isValidLocus(locus)) {
dispatchEvent(
"monocle:notfound",
{ href: locus ? locus.componentId : "anonymous" }
);
return false;
}
var fn = callback;
if (!locus.direction) {
dispatchEvent('monocle:jumping', { locus: locus });
fn = function () {
dispatchEvent('monocle:jump', { locus: locus });
if (callback) { callback(); }
}
}
p.flipper.moveTo(locus, fn);
return true;
}
// Moves to the relevant element in the relevant component.
//
function skipToChapter(src) {
var locus = p.book.locusOfChapter(src);
return moveTo(locus);
}
// Valid types:
// - standard (an overlay above the pages)
// - page (within the page)
// - modal (overlay where click-away does nothing, for a single control)
// - hud (overlay that multiple controls can share)
// - popover (overlay where click-away removes the ctrl elements)
// - invisible
//
// Options:
// - hidden -- creates and hides the ctrl elements;
// use showControl to show them
//
function addControl(ctrl, cType, options) {
alert('a')
for (var i = 0; i < p.controls.length; ++i) {
if (p.controls[i].control == ctrl) {
console.warn("Already added control: " + ctrl);
return;
}
}
options = options || {};
var ctrlData = {
control: ctrl,
elements: [],
controlType: cType
}
p.controls.push(ctrlData);
var ctrlElem;
var cntr = dom.find('container'), overlay = dom.find('overlay');
if (!cType || cType == "standard") {
ctrlElem = ctrl.createControlElements(cntr);
cntr.appendChild(ctrlElem);
ctrlData.elements.push(ctrlElem);
} else if (cType == "page") {
forEachPage(function (page, i) {
var runner = ctrl.createControlElements(page);
page.appendChild(runner);
ctrlData.elements.push(runner);
});
} else if (cType == "modal" || cType == "popover" || cType == "hud") {
ctrlElem = ctrl.createControlElements(overlay);
overlay.appendChild(ctrlElem);
ctrlData.elements.push(ctrlElem);
ctrlData.usesOverlay = true;
} else if (cType == "invisible") {
if (
typeof(ctrl.createControlElements) == "function" &&
(ctrlElem = ctrl.createControlElements(cntr))
) {
cntr.appendChild(ctrlElem);
ctrlData.elements.push(ctrlElem);
}
} else {
console.warn("Unknown control type: " + cType);
}
for (var i = 0; i < ctrlData.elements.length; ++i) {
Monocle.Styles.applyRules(ctrlData.elements[i], Monocle.Styles.control);
}
if (options.hidden) {
hideControl(ctrl);
} else {
showControl(ctrl);
}
if (typeof ctrl.assignToReader == 'function') {
ctrl.assignToReader(API);
}
return ctrl;
}
function dataForControl(ctrl) {
for (var i = 0; i < p.controls.length; ++i) {
if (p.controls[i].control == ctrl) {
return p.controls[i];
}
}
}
function hideControl(ctrl) {
var controlData = dataForControl(ctrl);
if (!controlData) {
console.warn("No data for control: " + ctrl);
return;
}
if (controlData.hidden) {
return;
}
for (var i = 0; i < controlData.elements.length; ++i) {
controlData.elements[i].style.display = "none";
}
if (controlData.usesOverlay) {
var overlay = dom.find('overlay');
overlay.style.display = "none";
Monocle.Events.deafenForContact(overlay, overlay.listeners);
}
controlData.hidden = true;
if (ctrl.properties) {
ctrl.properties.hidden = true;
}
dispatchEvent('monocle:controlhide', { control: ctrl }, false);
}
function showControl(ctrl) {
var controlData = dataForControl(ctrl);
if (!controlData) {
console.warn("No data for control: " + ctrl);
return false;
}
if (showingControl(ctrl)) {
return false;
}
var overlay = dom.find('overlay');
if (controlData.usesOverlay && controlData.controlType != "hud") {
for (var i = 0, ii = p.controls.length; i < ii; ++i) {
if (p.controls[i].usesOverlay && !p.controls[i].hidden) {
return false;
}
}
overlay.style.display = "block";
}
for (var i = 0; i < controlData.elements.length; ++i) {
controlData.elements[i].style.display = "block";
}
if (controlData.controlType == "popover") {
var onControl = function (evt) {
var obj = evt.target;
do {
if (obj == controlData.elements[0]) { return true; }
} while (obj && (obj = obj.parentNode));
return false;
}
overlay.listeners = Monocle.Events.listenForContact(
overlay,
{
start: function (evt) { if (!onControl(evt)) { hideControl(ctrl); } },
move: function (evt) { if (!onControl(evt)) { evt.preventDefault(); } }
}
);
}
controlData.hidden = false;
if (ctrl.properties) {
ctrl.properties.hidden = false;
}
dispatchEvent('monocle:controlshow', { control: ctrl }, false);
return true;
}
function showingControl(ctrl) {
var controlData = dataForControl(ctrl);
return controlData.hidden == false;
}
function dispatchEvent(evtType, data, cancelable) {
return Monocle.Events.dispatch(dom.find('box'), evtType, data, cancelable);
}
function listen(evtType, fn, useCapture) {
Monocle.Events.listen(dom.find('box'), evtType, fn, useCapture);
}
function deafen(evtType, fn) {
Monocle.Events.deafen(dom.find('box'), evtType, fn);
}
/* PAGE STYLESHEETS */
// API for adding a new stylesheet to all components. styleRules should be
// a string of CSS rules. restorePlace defaults to true.
//
// Returns a sheet index value that can be used with updatePageStyles
// and removePageStyles.
//
function addPageStyles(styleRules, restorePlace) {
return changingStylesheet(function () {
p.pageStylesheets.push(styleRules);
var sheetIndex = p.pageStylesheets.length - 1;
for (var i = 0; i < p.flipper.pageCount; ++i) {
var doc = dom.find('component', i).contentDocument;
addPageStylesheet(doc, sheetIndex);
}
return sheetIndex;
}, restorePlace);
}
// API for updating the styleRules in an existing page stylesheet across
// all components. Takes a sheet index value obtained via addPageStyles.
//
function updatePageStyles(sheetIndex, styleRules, restorePlace) {
return changingStylesheet(function () {
p.pageStylesheets[sheetIndex] = styleRules;
if (typeof styleRules.join == "function") {
styleRules = styleRules.join("\n");
}
for (var i = 0; i < p.flipper.pageCount; ++i) {
var doc = dom.find('component', i).contentDocument;
var styleTag = doc.getElementById('monStylesheet'+sheetIndex);
if (!styleTag) {
console.warn('No such stylesheet: ' + sheetIndex);
return;
}
if (styleTag.styleSheet) {
styleTag.styleSheet.cssText = styleRules;
} else {
styleTag.replaceChild(
doc.createTextNode(styleRules),
styleTag.firstChild
);
}
}
}, restorePlace);
}
// API for removing a page stylesheet from all components. Takes a sheet
// index value obtained via addPageStyles.
//
function removePageStyles(sheetIndex, restorePlace) {
return changingStylesheet(function () {
p.pageStylesheets[sheetIndex] = null;
for (var i = 0; i < p.flipper.pageCount; ++i) {
var doc = dom.find('component', i).contentDocument;
var styleTag = doc.getElementById('monStylesheet'+sheetIndex);
styleTag.parentNode.removeChild(styleTag);
}
}, restorePlace);
}
// Called when a page changes its component. Injects our current page
// stylesheets into the new component.
//
function persistPageStylesOnComponentChange(evt) {
var doc = evt.m['document'];
doc.documentElement.id = p.systemId;
for (var i = 0; i < p.pageStylesheets.length; ++i) {
if (p.pageStylesheets[i]) {
addPageStylesheet(doc, i);
}
}
}
// Wraps all API-based stylesheet changes (add, update, remove) in a
// brace of custom events (stylesheetchanging/stylesheetchange), and
// recalculates component dimensions if specified (default to true).
//
function changingStylesheet(callback, restorePlace) {
restorePlace = (restorePlace === false) ? false : true;
if (restorePlace) {
dispatchEvent("monocle:stylesheetchanging", {});
}
var result = callback();
if (restorePlace) {
recalculateDimensions(true);
Monocle.defer(
function () { dispatchEvent("monocle:stylesheetchange", {}); }
);
} else {
recalculateDimensions(false);
}
return result;
}
// Private method for adding a stylesheet to a component. Used by
// addPageStyles.
//
function addPageStylesheet(doc, sheetIndex) {
var styleRules = p.pageStylesheets[sheetIndex];
if (!styleRules) {
return;
}
var head = doc.getElementsByTagName('head')[0];
if (!head) {
head = doc.createElement('head');
doc.documentElement.appendChild(head);
}
if (typeof styleRules.join == "function") {
styleRules = styleRules.join("\n");
}
var styleTag = doc.createElement('style');
styleTag.type = 'text/css';
styleTag.id = "monStylesheet"+sheetIndex;
if (styleTag.styleSheet) {
styleTag.styleSheet.cssText = styleRules;
} else {
styleTag.appendChild(doc.createTextNode(styleRules));
}
head.appendChild(styleTag);
return styleTag;
}
function visiblePages() {
return p.flipper.visiblePages ? p.flipper.visiblePages() : [dom.find('page')];
}
function forEachPage(callback) {
for (var i = 0, ii = p.flipper.pageCount; i < ii; ++i) {
var page = dom.find('page', i);
callback(page, i);
}
}
API.getBook = getBook;
API.getPlace = getPlace;
API.moveTo = moveTo;
API.skipToChapter = skipToChapter;
API.resized = resized;
API.addControl = addControl;
API.hideControl = hideControl;
API.showControl = showControl;
API.showingControl = showingControl;
API.dispatchEvent = dispatchEvent;
API.listen = listen;
API.deafen = deafen;
API.addPageStyles = addPageStyles;
API.updatePageStyles = updatePageStyles;
API.removePageStyles = removePageStyles;
API.visiblePages = visiblePages;
initialize();
return API;
}
Monocle.Reader.RESIZE_DELAY = 100;
Monocle.Reader.DEFAULT_SYSTEM_ID = 'RS:monocle'
Monocle.Reader.DEFAULT_CLASS_PREFIX = 'monelem_'
Monocle.Reader.DEFAULT_STYLE_RULES = [
"html#RS\\:monocle * {" +
"-webkit-font-smoothing: subpixel-antialiased;" +
"text-rendering: auto !important;" +
"word-wrap: break-word !important;" +
"overflow: visible !important;" +
"}",
"html#RS\\:monocle body {" +
"margin: 0 !important;"+
"border: none !important;" +
"padding: 0 !important;" +
"width: 100% !important;" +
"position: absolute !important;" +
"-webkit-text-size-adjust: none;" +
"}",
"html#RS\\:monocle body * {" +
"max-width: 100% !important;" +
"}",
"html#RS\\:monocle img, html#RS\\:monocle video, html#RS\\:monocle object {" +
"max-height: 95% !important;" +
"height: auto !important;" +
"}"
]
Monocle.pieceLoaded('core/reader');
/* BOOK */
/* The Book handles movement through the content by the reader page elements.
*
* It's responsible for instantiating components as they are required,
* and for calculating which component and page number to move to (based on
* requests from the Reader).
*
* It should set and know the place of each page element too.
*
*/
Monocle.Book = function (dataSource) {
if (Monocle == this) { return new Monocle.Book(dataSource); }
var API = { constructor: Monocle.Book }
var k = API.constants = API.constructor;
var p = API.properties = {
dataSource: dataSource,
components: [],
chapters: {} // flat arrays of chapters per component
}
function initialize() {
p.componentIds = dataSource.getComponents();
p.contents = dataSource.getContents();
p.lastCIndex = p.componentIds.length - 1;
}
// Adjusts the given locus object to provide the page number within the
// current component.
//
// If the locus implies movement to another component, the locus
// 'componentId' property will be updated to point to this component, and
// the 'load' property will be set to true, which should be taken as a
// sign to call loadPageAt with a callback.
//
// The locus argument is an object that has one of the following properties:
//
// - page: positive integer. Counting up from the start of component.
// - pagesBack: negative integer. Counting back from the end of component.
// - percent: float
// - direction: integer relative to the current page number for this pageDiv
// - position: string, one of "start" or "end", moves to corresponding point
// in the given component
// - anchor: an element id within the component
// - xpath: the node at this XPath within the component
// - selector: the first node at this CSS selector within the component
//
// The locus object can also specify a componentId. If it is not provided
// we default to the currently active component, and if that doesn't exist,
// we default to the very first component.
//
// The locus result will be an object with the following properties:
//
// - load: boolean, true if loading component required, false otherwise
// - componentId: component to load (current componentId if load is false)
// - if load is false:
// - page
// - if load is true:
// - one of page / pagesBack / percent / direction / position / anchor
//
function pageNumberAt(pageDiv, locus) {
locus.load = false;
var currComponent = pageDiv.m.activeFrame ?
pageDiv.m.activeFrame.m.component :
null;
var component = null;
var cIndex = p.componentIds.indexOf(locus.componentId);
if (cIndex < 0 && !currComponent) {
// No specified component, no current component. Load first component.
locus.load = true;
locus.componentId = p.componentIds[0];
return locus;
} else if (
cIndex < 0 &&
locus.componentId &&
currComponent.properties.id != locus.componentId
) {
// Invalid component, say not found.
pageDiv.m.reader.dispatchEvent(
"monocle:notfound",
{ href: locus.componentId }
);
return null;
} else if (cIndex < 0) {
// No specified (or invalid) component, use current component.
component = currComponent;
locus.componentId = pageDiv.m.activeFrame.m.component.properties.id;
cIndex = p.componentIds.indexOf(locus.componentId);
} else if (!p.components[cIndex] || p.components[cIndex] != currComponent) {
// Specified component differs from current component. Load specified.
locus.load = true;
return locus;
} else {
component = currComponent;
}
// If we're here, then the locus is based on the current component.
var result = { load: false, componentId: locus.componentId, page: 1 }
// Get the current last page.
lastPageNum = component.lastPageNumber();
// Deduce the page number for the given locus.
if (typeof(locus.page) == "number") {
result.page = locus.page;
} else if (typeof(locus.pagesBack) == "number") {
result.page = lastPageNum + locus.pagesBack;
} else if (typeof(locus.percent) == "number") {
var place = new Monocle.Place();
place.setPlace(component, 1);
result.page = place.pageAtPercentageThrough(locus.percent);
} else if (typeof(locus.direction) == "number") {
if (!pageDiv.m.place) {
console.warn("Can't move in a direction if pageDiv has no place.");
}
result.page = pageDiv.m.place.pageNumber();
result.page += locus.direction;
} else if (typeof(locus.anchor) == "string") {
result.page = component.pageForChapter(locus.anchor, pageDiv);
} else if (typeof(locus.xpath) == "string") {
result.page = component.pageForXPath(locus.xpath, pageDiv);
} else if (typeof(locus.selector) == "string") {
result.page = component.pageForSelector(locus.selector, pageDiv);
} else if (typeof(locus.position) == "string") {
if (locus.position == "start") {
result.page = 1;
} else if (locus.position == "end") {
result.page = lastPageNum['new'];
}
} else {
console.warn("Unrecognised locus: " + locus);
}
if (result.page < 1) {
if (cIndex == 0) {
// On first page of book.
result.page = 1;
result.boundarystart = true;
} else {
// Moving backwards from current component.
result.load = true;
result.componentId = p.componentIds[cIndex - 1];
result.pagesBack = result.page;
result.page = null;
}
} else if (result.page > lastPageNum) {
if (cIndex == p.lastCIndex) {
// On last page of book.
result.page = lastPageNum;
result.boundaryend = true;
} else {
// Moving forwards from current component.
result.load = true;
result.componentId = p.componentIds[cIndex + 1];
result.page -= lastPageNum;
}
}
return result;
}
// Same as pageNumberAt, but if a load is not flagged, this will
// automatically update the pageDiv's place to the given pageNumber.
//
// If you call this (ie, from a flipper), you are effectively entering into
// a contract to move the frame offset to the given page returned in the
// locus if load is false.
//
function setPageAt(pageDiv, locus) {
locus = pageNumberAt(pageDiv, locus);
if (locus && !locus.load) {
var evtData = { locus: locus, page: pageDiv }
if (locus.boundarystart) {
pageDiv.m.reader.dispatchEvent('monocle:boundarystart', evtData);
} else if (locus.boundaryend) {
pageDiv.m.reader.dispatchEvent('monocle:boundaryend', evtData);
} else {
var component = p.components[p.componentIds.indexOf(locus.componentId)];
pageDiv.m.place = pageDiv.m.place || new Monocle.Place();
pageDiv.m.place.setPlace(component, locus.page);
var evtData = {
page: pageDiv,
locus: locus,
pageNumber: pageDiv.m.place.pageNumber(),
componentId: locus.componentId
}
pageDiv.m.reader.dispatchEvent("monocle:pagechange", evtData);
}
}
return locus;
}
// Will load the given component into the pageDiv's frame, then invoke the
// callback with resulting locus (provided by pageNumberAt).
//
// If the resulting page number is outside the bounds of the new component,
// (ie, pageNumberAt again requests a load), this will recurse into further
// components until non-loading locus is returned by pageNumberAt. Then the
// callback will fire with that locus.
//
// As with setPageAt, if you call this you're obliged to move the frame
// offset to the given page in the locus passed to the callback.
//
// If you pass a function as the progressCallback argument, the logic of this
// function will be in your control. The function will be invoked between:
//
// a) loading the component and
// b) applying the component to the frame and
// c) loading any further components if required
//
// with a function argument that performs the next step in the process. So
// if you need to do some special handling during the load process, you can.
//
function loadPageAt(pageDiv, locus, callback, progressCallback) {
var cIndex = p.componentIds.indexOf(locus.componentId);
if (!locus.load || cIndex < 0) {
locus = pageNumberAt(pageDiv, locus);
}
if (!locus) {
return;
}
if (!locus.load) {
callback(locus);
return;
}
var findPageNumber = function () {
locus = setPageAt(pageDiv, locus);
if (!locus) {
return;
} else if (locus.load) {
loadPageAt(pageDiv, locus, callback, progressCallback)
} else {
callback(locus);
}
}
var pgFindPageNumber = function () {
progressCallback ? progressCallback(findPageNumber) : findPageNumber();
}
var applyComponent = function (component) {
component.applyTo(pageDiv, pgFindPageNumber);
}
var pgApplyComponent = function (component) {
progressCallback ?
progressCallback(function () { applyComponent(component) }) :
applyComponent(component);
}
loadComponent(cIndex, pgApplyComponent, pageDiv);
}
// If your flipper doesn't care whether a component needs to be
// loaded before the page can be set, you can use this shortcut.
//
function setOrLoadPageAt(pageDiv, locus, callback, onProgress, onFail) {
locus = setPageAt(pageDiv, locus);
if (!locus) {
if (onFail) { onFail(); }
} else if (locus.load) {
loadPageAt(pageDiv, locus, callback, onProgress);
} else {
callback(locus);
}
}
// Fetches the component source from the dataSource.
//
// 'index' is the index of the component in the
// dataSource.getComponents array.
//
// 'callback' is invoked when the source is received.
//
// 'pageDiv' is optional, and simply allows firing events on
// the reader object that has requested this component, ONLY if
// the source has not already been received.
//
function loadComponent(index, callback, pageDiv) {
if (p.components[index]) {
return callback(p.components[index]);
}
var cmptId = p.componentIds[index];
if (pageDiv) {
var evtData = { 'page': pageDiv, 'component': cmptId, 'index': index };
pageDiv.m.reader.dispatchEvent('monocle:componentloading', evtData);
}
var failedToLoadComponent = function () {
console.warn("Failed to load component: "+cmptId);
pageDiv.m.reader.dispatchEvent('monocle:componentfailed', evtData);
try {
var currCmpt = pageDiv.m.activeFrame.m.component;
evtData.cmptId = currCmpt.properties.id;
callback(currCmpt);
} catch (e) {
console.warn("Failed to fall back to previous component.");
}
}
var fn = function (cmptSource) {
if (cmptSource === false) { return failedToLoadComponent(); }
if (pageDiv) {
evtData['source'] = cmptSource;
pageDiv.m.reader.dispatchEvent('monocle:componentloaded', evtData);
html = evtData['html'];
}
p.components[index] = new Monocle.Component(
API,
cmptId,
index,
chaptersForComponent(cmptId),
cmptSource
);
callback(p.components[index]);
}
var cmptSource = p.dataSource.getComponent(cmptId, fn);
if (cmptSource && !p.components[index]) {
fn(cmptSource);
} else if (cmptSource === false) {
return failedToLoadComponent();
}
}
// Returns an array of chapter objects that are found in the given component.
//
// A chapter object has this format:
//
// {
// title: "Chapter 1",
// fragment: null
// }
//
// The fragment property of a chapter object is either null (the chapter
// starts at the head of the component) or the fragment part of the URL
// (eg, "foo" in "index.html#foo").
//
function chaptersForComponent(cmptId) {
if (p.chapters[cmptId]) {
return p.chapters[cmptId];
}
p.chapters[cmptId] = [];
var matcher = new RegExp('^'+cmptId+"(\#(.+)|$)");
var matches;
var recurser = function (chp) {
if (matches = chp.src.match(matcher)) {
p.chapters[cmptId].push({
title: chp.title,
fragment: matches[2] || null
});
}
if (chp.children) {
for (var i = 0; i < chp.children.length; ++i) {
recurser(chp.children[i]);
}
}
}
for (var i = 0; i < p.contents.length; ++i) {
recurser(p.contents[i]);
}
return p.chapters[cmptId];
}
// Returns a locus for the chapter that has the URL given in the
// 'src' argument.
//
// See the comments at pageNumberAt for an explanation of locus objects.
//
function locusOfChapter(src) {
var matcher = new RegExp('^(.+?)(#(.*))?$');
var matches = src.match(matcher);
if (!matches) { return null; }
var cmptId = componentIdMatching(matches[1]);
if (!cmptId) { return null; }
var locus = { componentId: cmptId }
matches[3] ? locus.anchor = matches[3] : locus.position = "start";
return locus;
}
function isValidLocus(locus) {
if (!locus) { return false; }
if (locus.componentId && !componentIdMatching(locus.componentId)) {
return false;
}
return true;
}
function componentIdMatching(str) {
return p.componentIds.indexOf(str) >= 0 ? str : null;
}
API.getMetaData = dataSource.getMetaData;
API.pageNumberAt = pageNumberAt;
API.setPageAt = setPageAt;
API.loadPageAt = loadPageAt;
API.setOrLoadPageAt = setOrLoadPageAt;
API.chaptersForComponent = chaptersForComponent;
API.locusOfChapter = locusOfChapter;
API.isValidLocus = isValidLocus;
initialize();
return API;
}
// A shortcut for creating a book from an array of nodes.
//
// You could use this as follows, for eg:
//
// Monocle.Book.fromNodes([document.getElementById('content')]);
//
Monocle.Book.fromNodes = function (nodes) {
var bookData = {
getComponents: function () {
return ['anonymous'];
},
getContents: function () {
return [];
},
getComponent: function (n) {
return { 'nodes': nodes };
},
getMetaData: function (key) {
}
}
return new Monocle.Book(bookData);
}
Monocle.pieceLoaded('core/book');
// PLACE
Monocle.Place = function () {
var API = { constructor: Monocle.Place }
var k = API.constants = API.constructor;
var p = API.properties = {
component: null,
percent: null
}
function setPlace(cmpt, pageN) {
p.component = cmpt;
p.percent = pageN / cmpt.lastPageNumber();
p.chapter = null;
}
function setPercentageThrough(cmpt, percent) {
p.component = cmpt;
p.percent = percent;
p.chapter = null;
}
function componentId() {
return p.component.properties.id;
}
// How far we are through the component at the "top of the page".
//
// 0 - start of book. 1.0 - end of book.
//
function percentAtTopOfPage() {
return p.percent - 1.0 / p.component.lastPageNumber();
}
// How far we are through the component at the "bottom of the page".
//
// NB: API aliases this to percentageThrough().
//
function percentAtBottomOfPage() {
return p.percent;
}
// The page number at a given point (0: start, 1: end) within the component.
//
function pageAtPercentageThrough(percent) {
return Math.max(Math.round(p.component.lastPageNumber() * percent), 1);
}
// The page number of this point within the component.
//
function pageNumber() {
return pageAtPercentageThrough(p.percent);
}
function chapterInfo() {
if (p.chapter) {
return p.chapter;
}
return p.chapter = p.component.chapterForPage(pageNumber());
}
function chapterTitle() {
var chp = chapterInfo();
return chp ? chp.title : null;
}
function chapterSrc() {
var src = componentId();
var cinfo = chapterInfo();
if (cinfo && cinfo.fragment) {
src += "#" + cinfo.fragment;
}
return src;
}
function getLocus(options) {
options = options || {};
var locus = {
page: pageNumber(),
componentId: componentId()
}
if (options.direction) {
locus.page += options.direction;
} else {
locus.percent = percentAtBottomOfPage();
}
return locus;
}
// Returns how far this place is in the entire book (0 - start, 1.0 - end).
//
function percentageOfBook() {
componentIds = p.component.properties.book.properties.componentIds;
componentSize = 1.0 / componentIds.length;
var pc = componentIds.indexOf(componentId()) * componentSize;
pc += componentSize * p.percent;
return pc;
}
function onFirstPageOfBook() {
return p.component.properties.index == 0 && pageNumber() == 1;
}
function onLastPageOfBook() {
return (
p.component.properties.index ==
p.component.properties.book.properties.lastCIndex &&
pageNumber() == p.component.lastPageNumber()
);
}
API.setPlace = setPlace;
API.setPercentageThrough = setPercentageThrough;
API.componentId = componentId;
API.percentAtTopOfPage = percentAtTopOfPage;
API.percentAtBottomOfPage = percentAtBottomOfPage;
API.percentageThrough = percentAtBottomOfPage;
API.pageAtPercentageThrough = pageAtPercentageThrough;
API.pageNumber = pageNumber;
API.chapterInfo = chapterInfo;
API.chapterTitle = chapterTitle;
API.chapterSrc = chapterSrc;
API.getLocus = getLocus;
API.percentageOfBook = percentageOfBook;
API.onFirstPageOfBook = onFirstPageOfBook;
API.onLastPageOfBook = onLastPageOfBook;
return API;
}
Monocle.Place.FromPageNumber = function (component, pageNumber) {
var place = new Monocle.Place();
place.setPlace(component, pageNumber);
return place;
}
Monocle.Place.FromPercentageThrough = function (component, percent) {
var place = new Monocle.Place();
place.setPercentageThrough(component, percent);
return place;
}
// We can't create a place from a percentage of the book, because the
// component may not have been loaded yet. But we can get a locus.
//
Monocle.Place.percentOfBookToLocus = function (reader, percent) {
var componentIds = reader.getBook().properties.componentIds;
var componentSize = 1.0 / componentIds.length;
return {
componentId: componentIds[Math.floor(percent / componentSize)],
percent: (percent % componentSize) / componentSize
}
}
Monocle.pieceLoaded('core/place');
/* COMPONENT */
// See the properties declaration for details of constructor arguments.
//
Monocle.Component = function (book, id, index, chapters, source) {
var API = { constructor: Monocle.Component }
var k = API.constants = API.constructor;
var p = API.properties = {
// a back-reference to the public API of the book that owns this component
book: book,
// the string that represents this component in the book's component array
id: id,
// the position in the book's components array of this component
index: index,
// The chapters argument is an array of objects that list the chapters that
// can be found in this component. A chapter object is defined as:
//
// {
// title: str,
// fragment: str, // optional anchor id
// percent: n // how far into the component the chapter begins
// }
//
// NOTE: the percent property is calculated by the component - you only need
// to pass in the title and the optional id string.
//
chapters: chapters,
// the frame provided by dataSource.getComponent() for this component
source: source
}
// Makes this component the active component for the pageDiv. There are
// several strategies for this (see loadFrame).
//
// When the component has been loaded into the pageDiv's frame, the callback
// will be invoked with the pageDiv and this component as arguments.
//
function applyTo(pageDiv, callback) {
var evtData = { 'page': pageDiv, 'source': p.source };
pageDiv.m.reader.dispatchEvent('monocle:componentchanging', evtData);
var onLoaded = function () {
setupFrame(
pageDiv,
pageDiv.m.activeFrame,
function () { callback(pageDiv, API) }
);
}
Monocle.defer(function () { loadFrame(pageDiv, onLoaded); });
}
// Loads this component into the given frame, using one of the following
// strategies:
//
// * HTML - a HTML string
// * URL - a URL string
// * Nodes - an array of DOM body nodes (NB: no way to populate head)
// * Document - a DOM DocumentElement object
//
function loadFrame(pageDiv, callback) {
var frame = pageDiv.m.activeFrame;
// We own this frame now.
frame.m.component = API;
// Hide the frame while we're changing it.
frame.style.visibility = "hidden";
// Prevent about:blank overriding imported nodes in Firefox.
// Disabled again because it seems to result in blank pages in Saf.
//frame.contentWindow.stop();
if (p.source.html || (typeof p.source == "string")) { // HTML
return loadFrameFromHTML(p.source.html || p.source, frame, callback);
} else if (p.source.javascript) { // JAVASCRIPT
//console.log("Loading as javascript: "+p.source.javascript);
return loadFrameFromJavaScript(p.source.javascript, frame, callback);
} else if (p.source.url) { // URL
return loadFrameFromURL(p.source.url, frame, callback);
} else if (p.source.nodes) { // NODES
return loadFrameFromNodes(p.source.nodes, frame, callback);
} else if (p.source.doc) { // DOCUMENT
return loadFrameFromDocument(p.source.doc, frame, callback);
}
}
// LOAD STRATEGY: HTML
// Loads a HTML string into the given frame, invokes the callback once loaded.
//
// Cleans the string so it can be used in a JavaScript statement. This is
// slow, so if the string is already clean, skip this and use
// loadFrameFromJavaScript directly.
//
function loadFrameFromHTML(src, frame, callback) {
// Compress whitespace.
src = src.replace(/\n/g, '\\n').replace(/\r/, '\\r');
// Escape single-quotes.
src = src.replace(/\'/g, '\\\'');
// Remove scripts. (DISABLED -- Monocle should leave this to implementers.)
//var scriptFragment = "<script[^>]*>([\\S\\s]*?)<\/script>";
//src = src.replace(new RegExp(scriptFragment, 'img'), '');
// BROWSERHACK: Gecko chokes on the DOCTYPE declaration.
if (Monocle.Browser.is.Gecko) {
var doctypeFragment = "<!DOCTYPE[^>]*>";
src = src.replace(new RegExp(doctypeFragment, 'm'), '');
}
loadFrameFromJavaScript(src, frame, callback);
}
// LOAD STRATEGY: JAVASCRIPT
// Like the HTML strategy, but assumes that the src string is already clean.
//
function loadFrameFromJavaScript(src, frame, callback) {
src = "javascript:'"+src+"';";
frame.onload = function () {
frame.onload = null;
Monocle.defer(callback);
}
frame.src = src;
}
// LOAD STRATEGY: URL
// Loads the URL into the given frame, invokes callback once loaded.
//
function loadFrameFromURL(url, frame, callback) {
// If it's a relative path, we need to make it absolute, using the
// reader's location (not the active component's location).
if (!url.match(/^\//)) {
var link = document.createElement('a');
link.setAttribute('href', url);
url = link.href;
delete(link);
}
frame.onload = function () {
frame.onload = null;
Monocle.defer(callback);
}
frame.contentWindow.location.replace(url);
}
// LOAD STRATEGY: NODES
// Loads the array of DOM nodes into the body of the frame (replacing all
// existing nodes), then invokes the callback.
//
function loadFrameFromNodes(nodes, frame, callback) {
var destDoc = frame.contentDocument;
destDoc.documentElement.innerHTML = "";
var destHd = destDoc.createElement("head");
var destBdy = destDoc.createElement("body");
for (var i = 0; i < nodes.length; ++i) {
var node = destDoc.importNode(nodes[i], true);
destBdy.appendChild(node);
}
var oldHead = destDoc.getElementsByTagName('head')[0];
if (oldHead) {
destDoc.documentElement.replaceChild(destHd, oldHead);
} else {
destDoc.documentElement.appendChild(destHd);
}
if (destDoc.body) {
destDoc.documentElement.replaceChild(destBdy, destDoc.body);
} else {
destDoc.documentElement.appendChild(destBdy);
}
if (callback) { callback(); }
}
// LOAD STRATEGY: DOCUMENT
// Replaces the DocumentElement of the given frame with the given srcDoc.
// Invokes the callback when loaded.
//
function loadFrameFromDocument(srcDoc, frame, callback) {
var destDoc = frame.contentDocument;
var srcBases = srcDoc.getElementsByTagName('base');
if (srcBases[0]) {
var head = destDoc.getElementsByTagName('head')[0];
if (!head) {
try {
head = destDoc.createElement('head');
if (destDoc.body) {
destDoc.insertBefore(head, destDoc.body);
} else {
destDoc.appendChild(head);
}
} catch (e) {
head = destDoc.body;
}
}
var bases = destDoc.getElementsByTagName('base');
var base = bases[0] ? bases[0] : destDoc.createElement('base');
base.setAttribute('href', srcBases[0].getAttribute('href'));
head.appendChild(base);
}
destDoc.replaceChild(
destDoc.importNode(srcDoc.documentElement, true),
destDoc.documentElement
);
// DISABLED: immediate readiness - webkit has some difficulty with this.
// if (callback) { callback(); }
Monocle.defer(callback);
}
// Once a frame is loaded with this component, call this method to style
// and measure its contents.
//
function setupFrame(pageDiv, frame, callback) {
// iOS touch events on iframes are busted. See comments in
// events.js for an explanation of this hack.
//
Monocle.Events.listenOnIframe(frame);
var doc = frame.contentDocument;
var evtData = { 'page': pageDiv, 'document': doc, 'component': API };
// Announce that the component is loaded.
pageDiv.m.reader.dispatchEvent('monocle:componentmodify', evtData);
updateDimensions(pageDiv, function () {
frame.style.visibility = "visible";
// Find the place of any chapters in the component.
locateChapters(pageDiv);
// Announce that the component has changed.
pageDiv.m.reader.dispatchEvent('monocle:componentchange', evtData);
callback();
});
}
// Checks whether the pageDiv dimensions have changed. If they have,
// remeasures dimensions and returns true. Otherwise returns false.
//
function updateDimensions(pageDiv, callback) {
pageDiv.m.dimensions.update(function (pageLength) {
p.pageLength = pageLength;
if (typeof callback == "function") { callback() };
});
}
// Iterates over all the chapters that are within this component
// (according to the array we were provided on initialization) and finds
// their location (in percentage terms) within the text.
//
// Stores this percentage with the chapter object in the chapters array.
//
function locateChapters(pageDiv) {
if (p.chapters[0] && typeof p.chapters[0].percent == "number") {
return;
}
var doc = pageDiv.m.activeFrame.contentDocument;
for (var i = 0; i < p.chapters.length; ++i) {
var chp = p.chapters[i];
chp.percent = 0;
if (chp.fragment) {
var node = doc.getElementById(chp.fragment);
chp.percent = pageDiv.m.dimensions.percentageThroughOfNode(node);
}
}
return p.chapters;
}
// For a given page number within the component, return the chapter that
// starts on or most-recently-before this page.
//
// Useful, for example, in displaying the current chapter title as a
// running head on the page.
//
function chapterForPage(pageN) {
var cand = null;
var percent = (pageN - 1) / p.pageLength;
for (var i = 0; i < p.chapters.length; ++i) {
if (percent >= p.chapters[i].percent) {
cand = p.chapters[i];
} else {
return cand;
}
}
return cand;
}
// For a given chapter fragment (the bit after the hash
// in eg, "index.html#foo"), return the page number on which
// the chapter starts. If the fragment is null or blank, will
// return the first page of the component.
//
function pageForChapter(fragment, pageDiv) {
if (!fragment) {
return 1;
}
for (var i = 0; i < p.chapters.length; ++i) {
if (p.chapters[i].fragment == fragment) {
return percentToPageNumber(p.chapters[i].percent);
}
}
var doc = pageDiv.m.activeFrame.contentDocument;
var node = doc.getElementById(fragment);
var percent = pageDiv.m.dimensions.percentageThroughOfNode(node);
return percentToPageNumber(percent);
}
function pageForXPath(xpath, pageDiv) {
var doc = pageDiv.m.activeFrame.contentDocument;
var percent = 0;
if (Monocle.Browser.env.supportsXPath) {
var node = doc.evaluate(xpath, doc, null, 9, null).singleNodeValue;
if (node) {
percent = pageDiv.m.dimensions.percentageThroughOfNode(node);
}
} else {
console.warn("XPath not supported in this client.");
}
return percentToPageNumber(percent);
}
function pageForSelector(selector, pageDiv) {
var doc = pageDiv.m.activeFrame.contentDocument;
var percent = 0;
if (Monocle.Browser.env.supportsQuerySelector) {
var node = doc.querySelector(selector);
if (node) {
percent = pageDiv.m.dimensions.percentageThroughOfNode(node);
}
} else {
console.warn("querySelector not supported in this client.");
}
return percentToPageNumber(percent);
}
function percentToPageNumber(pc) {
return Math.floor(pc * p.pageLength) + 1;
}
// A public getter for p.pageLength.
//
function lastPageNumber() {
return p.pageLength;
}
API.applyTo = applyTo;
API.updateDimensions = updateDimensions;
API.chapterForPage = chapterForPage;
API.pageForChapter = pageForChapter;
API.pageForXPath = pageForXPath;
API.pageForSelector = pageForSelector;
API.lastPageNumber = lastPageNumber;
return API;
}
Monocle.pieceLoaded('core/component');
// A panel is an invisible column of interactivity. When contact occurs
// (mousedown, touchstart), the panel expands to the full width of its
// container, to catch all interaction events and prevent them from hitting
// other things.
//
// Panels are used primarily to provide hit zones for page flipping
// interactions, but you can do whatever you like with them.
//
// After instantiating a panel and adding it to the reader as a control,
// you can call listenTo() with a hash of methods for any of 'start', 'move'
// 'end' and 'cancel'.
//
Monocle.Controls.Panel = function () {
var API = { constructor: Monocle.Controls.Panel }
var k = API.constants = API.constructor;
var p = API.properties = {
evtCallbacks: {}
}
function createControlElements(cntr) {
p.div = cntr.dom.make('div', k.CLS.panel);
p.div.dom.setStyles(k.DEFAULT_STYLES);
Monocle.Events.listenForContact(
p.div,
{
'start': start,
'move': move,
'end': end,
'cancel': cancel
},
{ useCapture: false }
);
return p.div;
}
function listenTo(evtCallbacks) {
p.evtCallbacks = evtCallbacks;
}
function deafen() {
p.evtCallbacks = {}
}
function start(evt) {
p.contact = true;
evt.m.offsetX += p.div.offsetLeft;
evt.m.offsetY += p.div.offsetTop;
expand();
invoke('start', evt);
}
function move(evt) {
if (!p.contact) {
return;
}
invoke('move', evt);
}
function end(evt) {
if (!p.contact) {
return;
}
Monocle.Events.deafenForContact(p.div, p.listeners);
contract();
p.contact = false;
invoke('end', evt);
}
function cancel(evt) {
if (!p.contact) {
return;
}
Monocle.Events.deafenForContact(p.div, p.listeners);
contract();
p.contact = false;
invoke('cancel', evt);
}
function invoke(evtType, evt) {
if (p.evtCallbacks[evtType]) {
p.evtCallbacks[evtType](API, evt.m.offsetX, evt.m.offsetY);
}
evt.preventDefault();
}
function expand() {
if (p.expanded) {
return;
}
p.div.dom.addClass(k.CLS.expanded);
p.expanded = true;
}
function contract(evt) {
if (!p.expanded) {
return;
}
p.div.dom.removeClass(k.CLS.expanded);
p.expanded = false;
}
API.createControlElements = createControlElements;
API.listenTo = listenTo;
API.deafen = deafen;
API.expand = expand;
API.contract = contract;
return API;
}
Monocle.Controls.Panel.CLS = {
panel: 'panel',
expanded: 'controls_panel_expanded'
}
Monocle.Controls.Panel.DEFAULT_STYLES = {
position: 'absolute',
height: '100%'
}
Monocle.pieceLoaded('controls/panel');
// The simplest page-flipping interaction system: contact to the left half of
// the reader turns back one page, contact to the right half turns forward
// one page.
//
Monocle.Panels.TwoPane = function (flipper, evtCallbacks) {
var API = { constructor: Monocle.Panels.TwoPane }
var k = API.constants = API.constructor;
var p = API.properties = {}
function initialize() {
p.panels = {
forwards: new Monocle.Controls.Panel(),
backwards: new Monocle.Controls.Panel()
}
for (dir in p.panels) {
flipper.properties.reader.addControl(p.panels[dir]);
p.panels[dir].listenTo(evtCallbacks);
p.panels[dir].properties.direction = flipper.constants[dir.toUpperCase()];
var style = { "width": k.WIDTH };
style[(dir == "forwards" ? "right" : "left")] = 0;
p.panels[dir].properties.div.dom.setStyles(style);
}
}
initialize();
return API;
}
Monocle.Panels.IMode.WIDTH = "33%";
Monocle.pieceLoaded('panels/imode');
// A three-pane system of page interaction. The left 33% turns backwards, the
// right 33% turns forwards, and contact on the middle third causes the
// system to go into "interactive mode". In this mode, the page-flipping panels
// are only active in the margins, and all of the actual text content of the
// book is selectable. The user can exit "interactive mode" by hitting the little
// IMode icon in the lower right corner of the reader.
//
Monocle.Panels.IMode = function (flipper, evtCallbacks) {
var API = { constructor: Monocle.Panels.IMode }
var k = API.constants = API.constructor;
var p = API.properties = {}
function initialize() {
p.flipper = flipper;
p.reader = flipper.properties.reader;
p.panels = {
forwards: new Monocle.Controls.Panel(),
backwards: new Monocle.Controls.Panel()
}
p.divs = {}
for (dir in p.panels) {
p.reader.addControl(p.panels[dir]);
p.divs[dir] = p.panels[dir].properties.div;
p.panels[dir].listenTo(evtCallbacks);
p.panels[dir].properties.direction = flipper.constants[dir.toUpperCase()];
p.divs[dir].style.width = "33%";
p.divs[dir].style[dir == "forwards" ? "right" : "left"] = 0;
}
p.panels.central = new Monocle.Controls.Panel();
p.reader.addControl(p.panels.central);
p.divs.central = p.panels.central.properties.div;
p.divs.central.dom.setStyles({ left: "33%", width: "34%" });
menuCallbacks({ end: modeOn });
for (dir in p.panels) {
p.divs[dir].dom.addClass('panels_imode_panel');
p.divs[dir].dom.addClass('panels_imode_'+dir+'Panel');
}
p.toggleIcon = {
createControlElements: function (cntr) {
var div = cntr.dom.make('div', 'panels_imode_toggleIcon');
Monocle.Events.listenForTap(div, modeOff);
return div;
}
}
p.reader.addControl(p.toggleIcon, null, { hidden: true });
}
function menuCallbacks(callbacks) {
p.menuCallbacks = callbacks;
p.panels.central.listenTo(p.menuCallbacks);
}
function toggle() {
p.interactive ? modeOff() : modeOn();
}
function modeOn() {
if (p.interactive) {
return;
}
p.panels.central.contract();
var page = p.reader.visiblePages()[0];
var sheaf = page.m.sheafDiv;
var bw = sheaf.offsetLeft;
var fw = page.offsetWidth - (sheaf.offsetLeft + sheaf.offsetWidth);
bw = Math.floor(((bw - 2) / page.offsetWidth) * 10000 / 100 ) + "%";
fw = Math.floor(((fw - 2) / page.offsetWidth) * 10000 / 100 ) + "%";
startCameo(function () {
p.divs.forwards.style.width = fw;
p.divs.backwards.style.width = bw;
Monocle.Styles.affix(p.divs.central, 'transform', 'translateY(-100%)');
});
p.reader.showControl(p.toggleIcon);
p.interactive = true;
if (flipper.interactiveMode) {
flipper.interactiveMode(true);
}
}
function modeOff() {
if (!p.interactive) {
return;
}
p.panels.central.contract();
deselect();
startCameo(function () {
p.divs.forwards.style.width = "33%";
p.divs.backwards.style.width = "33%";
Monocle.Styles.affix(p.divs.central, 'transform', 'translateY(0)');
});
p.reader.hideControl(p.toggleIcon);
p.interactive = false;
if (flipper.interactiveMode) {
flipper.interactiveMode(false);
}
}
function startCameo(fn) {
// Set transitions on the panels.
var trn = Monocle.Panels.IMode.CAMEO_DURATION+"ms ease-in";
Monocle.Styles.affix(p.divs.forwards, 'transition', "width "+trn);
Monocle.Styles.affix(p.divs.backwards, 'transition', "width "+trn);
Monocle.Styles.affix(p.divs.central, 'transition', "-webkit-transform "+trn);
// Temporarily disable listeners.
for (var pan in p.panels) {
p.panels[pan].deafen();
}
// Set the panels to opaque.
for (var div in p.divs) {
p.divs[div].style.opacity = 1;
}
if (typeof WebkitTransitionEvent != "undefined") {
p.cameoListener = Monocle.Events.listen(
p.divs.central,
'webkitTransitionEnd',
endCameo
);
} else {
setTimeout(endCameo, k.CAMEO_DURATION);
}
fn();
}
function endCameo() {
setTimeout(function () {
// Remove panel transitions.
var trn = "opacity linear " + Monocle.Panels.IMode.LINGER_DURATION + "ms";
Monocle.Styles.affix(p.divs.forwards, 'transition', trn);
Monocle.Styles.affix(p.divs.backwards, 'transition', trn);
Monocle.Styles.affix(p.divs.central, 'transition', trn);
// Set the panels to transparent.
for (var div in p.divs) {
p.divs[div].style.opacity = 0;
}
// Re-enable listeners.
p.panels.forwards.listenTo(evtCallbacks);
p.panels.backwards.listenTo(evtCallbacks);
p.panels.central.listenTo(p.menuCallbacks);
}, Monocle.Panels.IMode.LINGER_DURATION);
if (p.cameoListener) {
Monocle.Events.deafen(p.divs.central, 'webkitTransitionEnd', endCameo);
}
}
function deselect() {
for (var i = 0, cmpt; cmpt = p.reader.dom.find('component', i); ++i) {
var sel = cmpt.contentWindow.getSelection() || cmpt.contentDocument.selection;
//if (sel.collapse) { sel.collapse(true); }
if (sel.removeAllRanges) { sel.removeAllRanges(); }
if (sel.empty) { sel.empty(); }
cmpt.contentDocument.body.scrollLeft = 0;
cmpt.contentDocument.body.scrollTop = 0;
}
}
API.toggle = toggle;
API.modeOn = modeOn;
API.modeOff = modeOff;
API.menuCallbacks = menuCallbacks;
initialize();
return API;
}
Monocle.Panels.IMode.CAMEO_DURATION = 250;
Monocle.Panels.IMode.LINGER_DURATION = 250;
Monocle.pieceLoaded('panels/imode');
Monocle.Panels.eInk = function (flipper, evtCallbacks) {
var API = { constructor: Monocle.Panels.eInk }
var k = API.constants = API.constructor;
var p = API.properties = {
flipper: flipper
}
function initialize() {
p.panel = new Monocle.Controls.Panel();
p.reader = p.flipper.properties.reader;
p.reader.addControl(p.panel);
p.panel.listenTo({ end: function (panel, x) {
if (x < p.panel.properties.div.offsetWidth / 2) {
p.panel.properties.direction = flipper.constants.BACKWARDS;
} else {
p.panel.properties.direction = flipper.constants.FORWARDS;
}
evtCallbacks.end(panel, x);
} });
var s = p.panel.properties.div.style;
p.reader.listen("monocle:componentchanging", function () {
s.opacity = 1;
Monocle.defer(function () { s.opacity = 0 }, 40);
});
s.width = "100%";
s.background = "#000";
s.opacity = 0;
if (k.LISTEN_FOR_KEYS) {
Monocle.Events.listen(window.top.document, 'keyup', handleKeyEvent);
}
}
function handleKeyEvent(evt) {
var eventCharCode = evt.charCode || evt.keyCode;
var dir = null;
if (eventCharCode == k.KEYS["PAGEUP"]) {
dir = flipper.constants.BACKWARDS;
} else if (eventCharCode == k.KEYS["PAGEDOWN"]) {
dir = flipper.constants.FORWARDS;
}
if (dir) {
flipper.moveTo({ direction: dir });
evt.preventDefault();
}
}
initialize();
return API;
}
Monocle.Panels.eInk.LISTEN_FOR_KEYS = true;
Monocle.Panels.eInk.KEYS = { "PAGEUP": 33, "PAGEDOWN": 34 };
// Provides page-flipping panels only in the margins of the book. This is not
// entirely suited to small screens with razor-thin margins, but is an
// appropriate panel class for larger screens (like, say, an iPad).
//
// Since the flipper hit zones are only in the margins, the actual text content
// of the book is always selectable.
//
Monocle.Panels.Marginal = function (flipper, evtCallbacks) {
var API = { constructor: Monocle.Panels.Marginal }
var k = API.constants = API.constructor;
var p = API.properties = {}
function initialize() {
p.panels = {
forwards: new Monocle.Controls.Panel(),
backwards: new Monocle.Controls.Panel()
}
for (dir in p.panels) {
flipper.properties.reader.addControl(p.panels[dir]);
p.panels[dir].listenTo(evtCallbacks);
p.panels[dir].properties.direction = flipper.constants[dir.toUpperCase()];
with (p.panels[dir].properties.div.style) {
dir == "forwards" ? right = 0 : left = 0;
}
}
setWidths();
if (flipper.interactiveMode) {
flipper.interactiveMode(true);
}
}
function setWidths() {
var page = flipper.properties.reader.dom.find('page');
var sheaf = page.m.sheafDiv;
var bw = sheaf.offsetLeft;
var fw = page.offsetWidth - (sheaf.offsetLeft + sheaf.offsetWidth);
bw = Math.floor(((bw - 2) / page.offsetWidth) * 10000 / 100 ) + "%";
fw = Math.floor(((fw - 2) / page.offsetWidth) * 10000 / 100 ) + "%";
p.panels.forwards.properties.div.style.width = fw;
p.panels.backwards.properties.div.style.width = bw;
}
API.setWidths = setWidths;
initialize();
return API;
}
Monocle.pieceLoaded('panels/marginal');
Monocle.Dimensions.Vert = function (pageDiv) {
var API = { constructor: Monocle.Dimensions.Vert }
var k = API.constants = API.constructor;
var p = API.properties = {
page: pageDiv,
reader: pageDiv.m.reader
}
function initialize() {
p.reader.listen('monocle:componentchange', componentChanged);
}
function update(callback) {
p.bodyHeight = getBodyHeight();
p.pageHeight = getPageHeight();
p.length = Math.ceil(p.bodyHeight / p.pageHeight);
callback(p.length);
}
function getBodyHeight() {
return p.page.m.activeFrame.contentDocument.body.scrollHeight;
}
function getPageHeight() {
return p.page.m.activeFrame.offsetHeight - k.GUTTER;
}
function percentageThroughOfNode(target) {
if (!target) {
return 0;
}
var doc = p.page.m.activeFrame.contentDocument;
var offset = 0;
if (target.getBoundingClientRect) {
offset = target.getBoundingClientRect().top;
offset -= doc.body.getBoundingClientRect().top;
} else {
var oldScrollTop = doc.body.scrollTop;
target.scrollIntoView();
offset = doc.body.scrollTop;
doc.body.scrollLeft = 0;
doc.body.scrollTop = oldScrollTop;
}
//console.log(id + ": " + offset + " of " + p.bodyHeight);
var percent = offset / p.bodyHeight;
return percent;
}
function componentChanged(evt) {
if (evt.m['page'] != p.page) { return; }
var sheaf = p.page.m.sheafDiv;
var cmpt = p.page.m.activeFrame;
sheaf.dom.setStyles(k.SHEAF_STYLES);
cmpt.dom.setStyles(k.COMPONENT_STYLES);
var doc = evt.m['document'];
doc.documentElement.style.overflow = 'hidden';
doc.body.style.marginRight = '10px !important';
cmpt.contentWindow.scrollTo(0,0);
}
function locusToOffset(locus) {
return p.pageHeight * (locus.page - 1);
}
API.update = update;
API.percentageThroughOfNode = percentageThroughOfNode;
API.locusToOffset = locusToOffset;
initialize();
return API;
}
Monocle.Dimensions.Vert.GUTTER = 10;
Monocle.pieceLoaded("dimensions/vert");
Monocle.Flippers.Legacy = function (reader) {
var API = { constructor: Monocle.Flippers.Legacy }
var k = API.constants = API.constructor;
var p = API.properties = {
pageCount: 1,
divs: {}
}
function initialize() {
p.reader = reader;
}
function addPage(pageDiv) {
pageDiv.m.dimensions = new Monocle.Dimensions.Vert(pageDiv);
}
function getPlace() {
return page().m.place;
}
function moveTo(locus, callback) {
var fn = frameToLocus;
if (typeof callback == "function") {
fn = function (locus) { frameToLocus(locus); callback(locus); }
}
p.reader.getBook().setOrLoadPageAt(page(), locus, fn);
}
function listenForInteraction(panelClass) {
if (typeof panelClass != "function") {
panelClass = k.DEFAULT_PANELS_CLASS;
if (!panelClass) {
console.warn("Invalid panel class.")
}
}
p.panels = new panelClass(API, { 'end': turn });
}
function page() {
return p.reader.dom.find('page');
}
function turn(panel) {
var dir = panel.properties.direction;
var place = getPlace();
if (
(dir < 0 && place.onFirstPageOfBook()) ||
(dir > 0 && place.onLastPageOfBook())
) { return; }
moveTo({ page: getPlace().pageNumber() + dir });
}
function frameToLocus(locus) {
var cmpt = p.reader.dom.find('component');
var win = cmpt.contentWindow;
var srcY = scrollPos(win);
var dims = page().m.dimensions;
var pageHeight = dims.properties.pageHeight;
var destY = dims.locusToOffset(locus);
//console.log(srcY + " => " + destY);
if (Math.abs(destY - srcY) > pageHeight) {
return win.scrollTo(0, destY);
}
showIndicator(win, srcY < destY ? srcY + pageHeight : srcY);
Monocle.defer(
function () { smoothScroll(win, srcY, destY, 300, scrollingFinished); },
150
);
}
function scrollPos(win) {
// Firefox, Chrome, Opera, Safari
if (win.pageYOffset) {
return win.pageYOffset;
}
// Internet Explorer 6 - standards mode
if (win.document.documentElement && win.document.documentElement.scrollTop) {
return win.document.documentElement.scrollTop;
}
// Internet Explorer 6, 7 and 8
if (win.document.body.scrollTop) {
return win.document.body.scrollTop;
}
return 0;
}
function smoothScroll(win, currY, finalY, duration, callback) {
clearTimeout(win.smoothScrollInterval);
var stamp = (new Date()).getTime();
var frameRate = 40;
var step = (finalY - currY) * (frameRate / duration);
var stepFn = function () {
var destY = currY + step;
if (
(new Date()).getTime() - stamp > duration ||
Math.abs(currY - finalY) < Math.abs((currY + step) - finalY)
) {
clearTimeout(win.smoothScrollInterval);
win.scrollTo(0, finalY);
if (callback) { callback(); }
} else {
win.scrollTo(0, destY);
currY = destY;
}
}
win.smoothScrollInterval = setInterval(stepFn, frameRate);
}
function scrollingFinished() {
hideIndicator(page().m.activeFrame.contentWindow);
p.reader.dispatchEvent('monocle:turn');
}
function showIndicator(win, pos) {
if (p.hideTO) { clearTimeout(p.hideTO); }
var doc = win.document;
if (!doc.body.indicator) {
doc.body.indicator = createIndicator(doc);
doc.body.appendChild(doc.body.indicator);
}
doc.body.indicator.line.style.display = "block";
doc.body.indicator.style.opacity = 1;
positionIndicator(pos);
}
function hideIndicator(win) {
var doc = win.document;
p.hideTO = Monocle.defer(
function () {
if (!doc.body.indicator) {
doc.body.indicator = createIndicator(doc);
doc.body.appendChild(doc.body.indicator);
}
var dims = page().m.dimensions;
positionIndicator(
dims.locusToOffset(getPlace().getLocus()) + dims.properties.pageHeight
)
doc.body.indicator.line.style.display = "none";
doc.body.indicator.style.opacity = 0.5;
},
600
);
}
function createIndicator(doc) {
var iBox = doc.createElement('div');
doc.body.appendChild(iBox);
Monocle.Styles.applyRules(iBox, k.STYLES.iBox);
iBox.arrow = doc.createElement('div');
iBox.appendChild(iBox.arrow);
Monocle.Styles.applyRules(iBox.arrow, k.STYLES.arrow);
iBox.line = doc.createElement('div');
iBox.appendChild(iBox.line);
Monocle.Styles.applyRules(iBox.line, k.STYLES.line);
return iBox;
}
function positionIndicator(y) {
var p = page();
var doc = p.m.activeFrame.contentDocument;
var maxHeight = p.m.dimensions.properties.bodyHeight;
maxHeight -= doc.body.indicator.offsetHeight;
if (y > maxHeight) {
y = maxHeight;
}
doc.body.indicator.style.top = y + "px";
}
// THIS IS THE CORE API THAT ALL FLIPPERS MUST PROVIDE.
API.pageCount = p.pageCount;
API.addPage = addPage;
API.getPlace = getPlace;
API.moveTo = moveTo;
API.listenForInteraction = listenForInteraction;
initialize();
return API;
}
Monocle.Flippers.Legacy.FORWARDS = 1;
Monocle.Flippers.Legacy.BACKWARDS = -1;
Monocle.Flippers.Legacy.DEFAULT_PANELS_CLASS = Monocle.Panels.IMode;
Monocle.Flippers.Legacy.STYLES = {
iBox: {
'position': 'absolute',
'right': 0,
'left': 0,
'height': '10px'
},
arrow: {
'position': 'absolute',
'right': 0,
'height': '10px',
'width': '10px',
'background': '#333',
'border-radius': '6px'
},
line: {
'width': '100%',
'border-top': '2px dotted #333',
'margin-top': '5px'
}
}
Monocle.pieceLoaded('flippers/legacy');
Monocle.Dimensions.Columns = function (pageDiv) {
var API = { constructor: Monocle.Dimensions.Columns }
var k = API.constants = API.constructor;
var p = API.properties = {
page: pageDiv,
reader: pageDiv.m.reader,
length: 0,
width: 0
}
// Logically, forceColumn browsers can't have a gap, because that would
// make the minWidth > 200%. But how much greater? Not worth the effort.
k.GAP = Monocle.Browser.env.forceColumns ? 0 : 20;
function update(callback) {
setColumnWidth();
Monocle.defer(function () {
p.length = columnCount();
if (Monocle.DEBUG) {
console.log(
'page['+p.page.m.pageIndex+'] -> '+p.length+
' ('+p.page.m.activeFrame.m.component.properties.id+')'
);
}
callback(p.length);
});
}
function setColumnWidth() {
var pdims = pageDimensions();
var ce = columnedElement();
p.width = pdims.width;
var rules = Monocle.Styles.rulesToString(k.STYLE["columned"]);
rules += Monocle.Browser.css.toCSSDeclaration('column-width', pdims.col+'px');
rules += Monocle.Browser.css.toCSSDeclaration('column-gap', k.GAP+'px');
rules += Monocle.Browser.css.toCSSDeclaration('column-fill', 'auto');
rules += Monocle.Browser.css.toCSSDeclaration('transform', 'translateX(0)');
if (Monocle.Browser.env.forceColumns && ce.scrollHeight > pdims.height) {
rules += Monocle.Styles.rulesToString(k.STYLE['column-force']);
if (Monocle.DEBUG) {
console.warn("Force columns ("+ce.scrollHeight+" > "+pdims.height+")");
}
}
if (ce.style.cssText != rules) {
// Update offset because we're translating to zero.
p.page.m.offset = 0;
// Apply body style changes.
ce.style.cssText = rules;
if (Monocle.Browser.env.scrollToApplyStyle) {
ce.scrollLeft = 0;
}
}
}
// Returns the element to which columns CSS should be applied.
//
function columnedElement() {
return p.page.m.activeFrame.contentDocument.body;
}
// Returns the width of the offsettable area of the columned element. By
// definition, the number of pages is always this divided by the
// width of a single page (eg, the client area of the columned element).
//
function columnedWidth() {
var bd = columnedElement();
var de = p.page.m.activeFrame.contentDocument.documentElement;
var w = Math.max(bd.scrollWidth, de.scrollWidth);
// Add one because the final column doesn't have right gutter.
w += k.GAP;
if (!Monocle.Browser.env.widthsIgnoreTranslate && p.page.m.offset) {
w += p.page.m.offset;
}
return w;
}
function pageDimensions() {
var elem = p.page.m.sheafDiv;
return {
col: elem.clientWidth,
width: elem.clientWidth + k.GAP,
height: elem.clientHeight
}
}
function columnCount() {
return Math.ceil(columnedWidth() / pageDimensions().width)
}
function locusToOffset(locus) {
return pageDimensions().width * (locus.page - 1);
}
// Moves the columned element to the offset implied by the locus.
//
// The 'transition' argument is optional, allowing the translation to be
// animated. If not given, no change is made to the columned element's
// transition property.
//
function translateToLocus(locus, transition) {
var offset = locusToOffset(locus);
p.page.m.offset = offset;
translateToOffset(offset, transition);
return offset;
}
function translateToOffset(offset, transition) {
var ce = columnedElement();
if (transition) {
Monocle.Styles.affix(ce, "transition", transition);
}
Monocle.Styles.affix(ce, "transform", "translateX(-"+offset+"px)");
}
function percentageThroughOfNode(target) {
if (!target) { return 0; }
var doc = p.page.m.activeFrame.contentDocument;
var offset = 0;
if (Monocle.Browser.env.findNodesByScrolling) {
// First, remove translation...
translateToOffset(0);
// Store scroll offsets for all windows.
var win = s = p.page.m.activeFrame.contentWindow;
var scrollers = [
[win, win.scrollX, win.scrollY],
[window, window.scrollX, window.scrollY]
];
//while (s != s.parent) { scrollers.push([s, s.scrollX]); s = s.parent; }
if (Monocle.Browser.env.sheafIsScroller) {
var scroller = p.page.m.sheafDiv;
var x = scroller.scrollLeft;
target.scrollIntoView();
offset = scroller.scrollLeft;
} else {
var scroller = win;
var x = scroller.scrollX;
target.scrollIntoView();
offset = scroller.scrollX;
}
// Restore scroll offsets for all windows.
while (s = scrollers.shift()) {
s[0].scrollTo(s[1], s[2]);
}
// ... finally, replace translation.
translateToOffset(p.page.m.offset);
} else {
offset = target.getBoundingClientRect().left;
offset -= doc.body.getBoundingClientRect().left;
}
// We know at least 1px will be visible, and offset should not be 0.
offset += 1;
// Percent is the offset divided by the total width of the component.
var percent = offset / (p.length * p.width);
// Page number would be offset divided by the width of a single page.
// var pageNum = Math.ceil(offset / pageDimensions().width);
return percent;
}
API.update = update;
API.percentageThroughOfNode = percentageThroughOfNode;
API.locusToOffset = locusToOffset;
API.translateToLocus = translateToLocus;
return API;
}
Monocle.Dimensions.Columns.STYLE = {
// Most of these are already applied to body, but they're repeated here
// in case columnedElement() is ever anything other than body.
"columned": {
"margin": "0",
"padding": "0",
"height": "100%",
"width": "100%",
"position": "absolute"
},
"column-force": {
"min-width": "200%",
"overflow": "hidden"
}
}
Monocle.pieceLoaded("dimensions/columns");
Monocle.Flippers.Slider = function (reader) {
if (Monocle.Flippers == this) {
return new Monocle.Flippers.Slider(reader);
}
var API = { constructor: Monocle.Flippers.Slider }
var k = API.constants = API.constructor;
var p = API.properties = {
pageCount: 2,
activeIndex: 1,
turnData: {}
}
function initialize() {
p.reader = reader;
p.reader.listen("monocle:componentchanging", showWaitControl);
}
function addPage(pageDiv) {
pageDiv.m.dimensions = new Monocle.Dimensions.Columns(pageDiv);
// BROWSERHACK: Firefox 4 is prone to beachballing on the first page turn
// unless a zeroed translateX has been applied to the page div.
Monocle.Styles.setX(pageDiv, 0);
}
function visiblePages() {
return [upperPage()];
}
function listenForInteraction(panelClass) {
// BROWSERHACK: Firstly, prime interactiveMode for buggy iOS WebKit.
interactiveMode(true);
interactiveMode(false);
if (typeof panelClass != "function") {
panelClass = k.DEFAULT_PANELS_CLASS;
if (!panelClass) {
console.warn("Invalid panel class.")
}
}
var q = function (action, panel, x) {
var dir = panel.properties.direction;
if (action == "lift") {
lift(dir, x);
} else if (action == "release") {
release(dir, x);
}
}
p.panels = new panelClass(
API,
{
'start': function (panel, x) { q('lift', panel, x); },
'move': function (panel, x) { turning(panel.properties.direction, x); },
'end': function (panel, x) { q('release', panel, x); },
'cancel': function (panel, x) { q('release', panel, x); }
}
);
}
// A panel can call this with true/false to indicate that the user needs
// to be able to select or otherwise interact with text.
function interactiveMode(bState) {
p.reader.dispatchEvent('monocle:interactive:'+(bState ? 'on' : 'off'));
if (!Monocle.Browser.env.selectIgnoresZOrder) { return; }
if (p.interactive = bState) {
if (p.activeIndex != 0) {
var place = getPlace();
if (place) {
setPage(
p.reader.dom.find('page', 0),
place.getLocus(),
function () {
flipPages();
prepareNextPage();
}
);
} else {
flipPages();
}
}
}
}
function getPlace(pageDiv) {
pageDiv = pageDiv || upperPage();
return pageDiv.m ? pageDiv.m.place : null;
}
function moveTo(locus, callback) {
var fn = function () {
prepareNextPage(function () {
if (typeof callback == "function") { callback(); }
announceTurn();
});
}
setPage(upperPage(), locus, fn);
}
function setPage(pageDiv, locus, callback) {
p.reader.getBook().setOrLoadPageAt(
pageDiv,
locus,
function (locus) {
pageDiv.m.dimensions.translateToLocus(locus);
Monocle.defer(callback);
}
);
}
function upperPage() {
return p.reader.dom.find('page', p.activeIndex);
}
function lowerPage() {
return p.reader.dom.find('page', (p.activeIndex + 1) % 2);
}
function flipPages() {
upperPage().style.zIndex = 1;
lowerPage().style.zIndex = 2;
return p.activeIndex = (p.activeIndex + 1) % 2;
}
function lift(dir, boxPointX) {
if (p.turnData.lifting || p.turnData.releasing) { return; }
p.turnData.points = {
start: boxPointX,
min: boxPointX,
max: boxPointX
}
p.turnData.lifting = true;
var place = getPlace();
if (dir == k.FORWARDS) {
if (place.onLastPageOfBook()) {
p.reader.dispatchEvent(
'monocle:boundaryend',
{
locus: getPlace().getLocus({ direction : dir }),
page: upperPage()
}
);
resetTurnData();
return;
}
onGoingForward(boxPointX);
} else if (dir == k.BACKWARDS) {
if (place.onFirstPageOfBook()) {
p.reader.dispatchEvent(
'monocle:boundarystart',
{
locus: getPlace().getLocus({ direction : dir }),
page: upperPage()
}
);
resetTurnData();
return;
}
onGoingBackward(boxPointX);
} else {
console.warn("Invalid direction: " + dir);
}
}
function turning(dir, boxPointX) {
if (!p.turnData.points) { return; }
if (p.turnData.lifting || p.turnData.releasing) { return; }
checkPoint(boxPointX);
slideToCursor(boxPointX, null, "0");
}
function release(dir, boxPointX) {
if (!p.turnData.points) {
return;
}
if (p.turnData.lifting) {
p.turnData.releaseArgs = [dir, boxPointX];
return;
}
if (p.turnData.releasing) {
return;
}
checkPoint(boxPointX);
p.turnData.releasing = true;
if (dir == k.FORWARDS) {
if (
p.turnData.points.tap ||
p.turnData.points.start - boxPointX > 60 ||
p.turnData.points.min >= boxPointX
) {
// Completing forward turn
slideOut(afterGoingForward);
} else {
// Cancelling forward turn
slideIn(afterCancellingForward);
}
} else if (dir == k.BACKWARDS) {
if (
p.turnData.points.tap ||
boxPointX - p.turnData.points.start > 60 ||
p.turnData.points.max <= boxPointX
) {
// Completing backward turn
slideIn(afterGoingBackward);
} else {
// Cancelling backward turn
slideOut(afterCancellingBackward);
}
} else {
console.warn("Invalid direction: " + dir);
}
}
function checkPoint(boxPointX) {
p.turnData.points.min = Math.min(p.turnData.points.min, boxPointX);
p.turnData.points.max = Math.max(p.turnData.points.max, boxPointX);
p.turnData.points.tap = p.turnData.points.max - p.turnData.points.min < 10;
}
function onGoingForward(x) {
lifted(x);
}
function onGoingBackward(x) {
var lp = lowerPage(), up = upperPage();
// set lower to "the page before upper"
setPage(
lp,
getPlace(up).getLocus({ direction: k.BACKWARDS }),
function () {
// flip lower to upper, ready to slide in from left
flipPages();
// move lower off the screen to the left
jumpOut(lp, function () {
lifted(x);
});
}
);
}
function afterGoingForward() {
var up = upperPage(), lp = lowerPage();
if (p.interactive) {
// set upper (off screen) to current
setPage(
up,
getPlace().getLocus({ direction: k.FORWARDS }),
function () {
// move upper back onto screen, then set lower to next and reset turn
jumpIn(up, function () { prepareNextPage(announceTurn); });
}
);
} else {
flipPages();
jumpIn(up, function () { prepareNextPage(announceTurn); });
}
}
function afterGoingBackward() {
if (p.interactive) {
// set lower page to current
setPage(
lowerPage(),
getPlace().getLocus(),
function () {
// flip lower to upper
flipPages();
// set lower to next and reset turn
prepareNextPage(announceTurn);
}
);
} else {
announceTurn();
}
}
function afterCancellingForward() {
resetTurnData();
}
function afterCancellingBackward() {
flipPages(); // flip upper to lower
jumpIn(lowerPage(), function () { prepareNextPage(resetTurnData); });
}
function prepareNextPage(callback) {
setPage(
lowerPage(),
getPlace().getLocus({ direction: k.FORWARDS }),
callback
);
}
function lifted(x) {
p.turnData.lifting = false;
var releaseArgs = p.turnData.releaseArgs;
if (releaseArgs) {
p.turnData.releaseArgs = null;
release(releaseArgs[0], releaseArgs[1]);
} else if (x) {
slideToCursor(x);
}
}
function announceTurn() {
p.reader.dispatchEvent('monocle:turn');
resetTurnData();
}
function resetTurnData() {
hideWaitControl();
p.turnData = {};
}
function setX(elem, x, options, callback) {
var duration, transition;
if (!options.duration) {
duration = 0;
} else {
duration = parseInt(options.duration);
}
if (Monocle.Browser.env.supportsTransition) {
Monocle.Styles.transitionFor(
elem,
'transform',
duration,
options.timing,
options.delay
);
if (Monocle.Browser.env.supportsTransform3d) {
Monocle.Styles.affix(elem, 'transform', 'translate3d('+x+'px,0,0)');
} else {
Monocle.Styles.affix(elem, 'transform', 'translateX('+x+'px)');
}
if (typeof callback == "function") {
if (duration && Monocle.Styles.getX(elem) != x) {
Monocle.Events.afterTransition(elem, callback);
} else {
Monocle.defer(callback);
}
}
} else {
// Old-school JS animation.
elem.currX = elem.currX || 0;
var completeTransition = function () {
elem.currX = x;
Monocle.Styles.setX(elem, x);
if (typeof callback == "function") { callback(); }
}
if (!duration) {
completeTransition();
} else {
var stamp = (new Date()).getTime();
var frameRate = 40;
var step = (x - elem.currX) * (frameRate / duration);
var stepFn = function () {
var destX = elem.currX + step;
var timeElapsed = ((new Date()).getTime() - stamp) >= duration;
var pastDest = (destX > x && elem.currX < x) ||
(destX < x && elem.currX > x);
if (timeElapsed || pastDest) {
completeTransition();
} else {
Monocle.Styles.setX(elem, destX);
elem.currX = destX;
setTimeout(stepFn, frameRate);
}
}
stepFn();
}
}
}
function jumpIn(pageDiv, callback) {
opts = { duration: (Monocle.Browser.env.stickySlideOut ? 1 : 0) }
setX(pageDiv, 0, opts, callback);
}
function jumpOut(pageDiv, callback) {
setX(pageDiv, 0 - pageDiv.offsetWidth, { duration: 0 }, callback);
}
// NB: Slides are always done by the visible upper page.
function slideIn(callback) {
setX(upperPage(), 0, slideOpts(), callback);
}
function slideOut(callback) {
setX(upperPage(), 0 - upperPage().offsetWidth, slideOpts(), callback);
}
function slideToCursor(cursorX, callback, duration) {
setX(
upperPage(),
Math.min(0, cursorX - upperPage().offsetWidth),
{ duration: duration || k.FOLLOW_DURATION },
callback
);
}
function slideOpts() {
var opts = { timing: 'ease-in', duration: 320 }
var now = (new Date()).getTime();
if (p.lastSlide && now - p.lastSlide < 1500) { opts.duration *= 0.5; }
p.lastSlide = now;
return opts;
}
function ensureWaitControl() {
if (p.waitControl) { return; }
p.waitControl = {
createControlElements: function (holder) {
return holder.dom.make('div', 'flippers_slider_wait');
}
}
p.reader.addControl(p.waitControl, 'page');
}
function showWaitControl() {
ensureWaitControl();
p.reader.dom.find('flippers_slider_wait', 0).style.opacity = 1;
p.reader.dom.find('flippers_slider_wait', 1).style.opacity = 1;
}
function hideWaitControl() {
ensureWaitControl();
p.reader.dom.find('flippers_slider_wait', 0).style.opacity = 0;
p.reader.dom.find('flippers_slider_wait', 1).style.opacity = 0;
}
// THIS IS THE CORE API THAT ALL FLIPPERS MUST PROVIDE.
API.pageCount = p.pageCount;
API.addPage = addPage;
API.getPlace = getPlace;
API.moveTo = moveTo;
API.listenForInteraction = listenForInteraction;
// OPTIONAL API - WILL BE INVOKED (WHERE RELEVANT) IF PROVIDED.
API.visiblePages = visiblePages;
API.interactiveMode = interactiveMode;
initialize();
return API;
}
// Constants
Monocle.Flippers.Slider.DEFAULT_PANELS_CLASS = Monocle.Panels.IMode;
Monocle.Flippers.Slider.FORWARDS = 1;
Monocle.Flippers.Slider.BACKWARDS = -1;
Monocle.Flippers.Slider.FOLLOW_DURATION = 100;
Monocle.pieceLoaded('flippers/slider');
Monocle.Flippers.Scroller = function (reader, setPageFn) {
var API = { constructor: Monocle.Flippers.Scroller }
var k = API.constants = API.constructor;
var p = API.properties = {
pageCount: 1,
duration: 300
}
function initialize() {
p.reader = reader;
p.setPageFn = setPageFn;
}
function addPage(pageDiv) {
pageDiv.m.dimensions = new Monocle.Dimensions.Columns(pageDiv);
}
function page() {
return p.reader.dom.find('page');
}
function listenForInteraction(panelClass) {
if (typeof panelClass != "function") {
panelClass = k.DEFAULT_PANELS_CLASS;
}
p.panels = new panelClass(
API,
{
'end': function (panel) { turn(panel.properties.direction); }
}
);
}
function turn(dir) {
if (p.turning) { return; }
moveTo({ page: getPlace().pageNumber() + dir});
}
function getPlace() {
return page().m.place;
}
function moveTo(locus, callback) {
var fn = frameToLocus;
if (typeof callback == "function") {
fn = function (locus) { frameToLocus(locus); callback(locus); }
}
p.reader.getBook().setOrLoadPageAt(page(), locus, fn);
}
function frameToLocus(locus) {
if (locus.boundarystart || locus.boundaryend) { return; }
p.turning = true;
var dims = page().m.dimensions;
var fr = page().m.activeFrame;
var bdy = fr.contentDocument.body;
var anim = true;
if (p.activeComponent != fr.m.component) {
// No animation.
p.activeComponent = fr.m.component;
dims.translateToLocus(locus, "none");
Monocle.defer(turned);
} else if (Monocle.Browser.env.supportsTransition) {
// Native animation.
dims.translateToLocus(locus, p.duration+"ms ease-in 0ms");
Monocle.Events.afterTransition(bdy, turned);
} else {
// Old-school JS animation.
var x = dims.locusToOffset(locus);
var finalX = 0 - x;
var stamp = (new Date()).getTime();
var frameRate = 40;
var currX = p.currX || 0;
var step = (finalX - currX) * (frameRate / p.duration);
var stepFn = function () {
var destX = currX + step;
if (
(new Date()).getTime() - stamp > p.duration ||
Math.abs(currX - finalX) <= Math.abs((currX + step) - finalX)
) {
Monocle.Styles.setX(bdy, finalX);
turned();
} else {
Monocle.Styles.setX(bdy, destX);
currX = destX;
setTimeout(stepFn, frameRate);
}
p.currX = destX;
}
stepFn();
}
}
function turned() {
p.turning = false;
p.reader.dispatchEvent('monocle:turn');
}
// THIS IS THE CORE API THAT ALL FLIPPERS MUST PROVIDE.
API.pageCount = p.pageCount;
API.addPage = addPage;
API.getPlace = getPlace;
API.moveTo = moveTo;
API.listenForInteraction = listenForInteraction;
initialize();
return API;
}
Monocle.Flippers.Scroller.speed = 200; // How long the animation takes
Monocle.Flippers.Scroller.rate = 20; // frame-rate of the animation
Monocle.Flippers.Scroller.FORWARDS = 1;
Monocle.Flippers.Scroller.BACKWARDS = -1;
Monocle.Flippers.Scroller.DEFAULT_PANELS_CLASS = Monocle.Panels.IMode;
Monocle.pieceLoaded('flippers/scroller');
Monocle.Flippers.Instant = function (reader) {
var API = { constructor: Monocle.Flippers.Instant }
var k = API.constants = API.constructor;
var p = API.properties = {
pageCount: 1
}
function initialize() {
p.reader = reader;
}
function addPage(pageDiv) {
pageDiv.m.dimensions = new Monocle.Dimensions.Columns(pageDiv);
}
function getPlace() {
return page().m.place;
}
function moveTo(locus, callback) {
var fn = frameToLocus;
if (typeof callback == "function") {
fn = function (locus) { frameToLocus(locus); callback(locus); }
}
p.reader.getBook().setOrLoadPageAt(page(), locus, fn);
}
function listenForInteraction(panelClass) {
if (typeof panelClass != "function") {
if (Monocle.Browser.on.Kindle3) {
panelClass = Monocle.Panels.eInk;
}
panelClass = panelClass || k.DEFAULT_PANELS_CLASS;
}
if (!panelClass) { throw("Panels not found."); }
p.panels = new panelClass(API, { 'end': turn });
}
function page() {
return p.reader.dom.find('page');
}
function turn(panel) {
var dir = panel.properties.direction;
moveTo({ page: getPlace().pageNumber() + dir});
}
function frameToLocus(locus) {
page().m.dimensions.translateToLocus(locus);
Monocle.defer(function () { p.reader.dispatchEvent('monocle:turn'); });
}
// THIS IS THE CORE API THAT ALL FLIPPERS MUST PROVIDE.
API.pageCount = p.pageCount;
API.addPage = addPage;
API.getPlace = getPlace;
API.moveTo = moveTo;
API.listenForInteraction = listenForInteraction;
initialize();
return API;
}
Monocle.Flippers.Instant.FORWARDS = 1;
Monocle.Flippers.Instant.BACKWARDS = -1;
Monocle.Flippers.Instant.DEFAULT_PANELS_CLASS = Monocle.Panels.IMode;
Monocle.pieceLoaded('flippers/instant');
Monocle.pieceLoaded('monocore');
|
var assert = require('assert'),
Model = require('../lib/model'),
Definition = require('../lib/definition'),
Types = require('../lib/types'),
util = require('../lib/util'),
_ = require('lodash');
describe('Model', function() {
var User;
beforeEach(function() {
User = Model.define('User', function() {
this.string('firstName');
this.number('age');
this.string('gender', { default: 'Male' });
this.string('socialSecurity');
});
});
describe('#define', function() {
it('inherits Model', function(done) {
var MyModel = Model.define('foo', function() {});
assert.ok(MyModel.__super__ === Model.prototype);
assert.ok(new MyModel() instanceof Model);
done();
});
it('has definition', function(done) {
assert.ok(Model.define('foo', function() {}).definition instanceof Definition);
done();
});
it('sets modelName', function(done) {
assert.equal(User.modelName, 'User');
done();
});
});
describe('constructor', function() {
it('sets properties & defaults', function(done) {
var user = new User({ firstName: 'John', 'age': 30 });
assert.equal(user.firstName, 'John');
assert.equal(user.age, 30);
assert.equal(user.gender, 'Male');
assert.equal(user.socialSecurity, undefined);
done();
});
});
describe('#hydrate', function() {
var MyModel;
beforeEach(function() {
MyModel = Model.define('foo', function() {
this.string('someString');
this.number('someNumber');
});
});
it('hydrates Model', function(done) {
var data = {
someString: 'abcd123',
someNumber: 1337
},
expected = new MyModel(data);
assert.deepEqual(MyModel.hydrate(data), expected);
done();
});
it('throws error when invalid types are given', function(done) {
var error;
try {
MyModel.hydrate({ someString: 1 });
} catch (e) {
error = e;
}
assert.ok(error instanceof Error);
assert.equal(error.message, 'Error transforming field "someString" with type "number" from the database.');
done();
});
});
describe('validation', function() {
it('validates', function(done) {
var validatorCalled = false;
var alwaysInvalidType = new Types.Type('alwaysInvalid');
alwaysInvalidType.use(function(value) {
validatorCalled = true;
});
var MyModel = Model.define('MyModel', function() {
this.type(alwaysInvalidType);
});
var model = new MyModel();
MyModel.validate(model, function(err, validatedModel) {
assert.equal(err, null);
assert.equal(validatedModel, model);
assert.ok(validatorCalled === true);
done();
});
});
it('throws error on invalid callback', function(done) {
var error, user = new User();
try {
User.validate(user);
} catch (e) {
error = e;
}
assert.ok(error instanceof Error);
assert.equal(error.message, 'Expected valid callback for Model.validate().');
done();
});
it('calls validations and returns errors when invalidation occurs', function(done) {
var validatorCalled = false;
var alwaysInvalidType = new Types.Type('alwaysInvalid');
alwaysInvalidType.use(function(value) {
validatorCalled = true;
this.invalidate('invalid!');
});
var MyModel = Model.define('MyModel', function() {
this.type(alwaysInvalidType);
});
var model = new MyModel();
MyModel.validate(model, function(err, validatedModel) {
assert.equal(validatedModel, undefined);
assert.ok(validatorCalled === true);
assert.deepEqual(err, [{ name: 'ValidationError', property: 'alwaysInvalid', errors: ['invalid!']}]);
done();
});
});
});
});
|
module.exports = importGTFS
const async = require('async')
const path = require('path')
const load = require('require-all')({
dirname: __dirname,
filter: /import.(.+)\.js$/,
excludeDirs: /^\.(git|svn)$/
})
const importOrder = [
'agency',
'calendar_dates',
'calendar',
'stops',
'routes',
'trips',
'shapes',
'stop_times'
]
function importGTFS (source, callback) {
const transit = this
const status = {
imported: {}
}
async.eachSeries(importOrder, function (what, cb) {
const importer = load[what]
importer(path.join(source, what + '.txt'), transit, function (err) {
if (err && err.code === 'ENOENT') {
if (err && importer.optional === true) {
// file is optional, so omit 'file not found' error
err = null
}
if (err &&
typeof importer.optional === 'function' &&
importer.optional(transit, status)) {
// file is optional, so omit 'file not found' error
err = null
}
}
status.imported[what] = true
cb(err)
})
}, callback)
}
|
const RedisPubSub = require("../services/RedisPubSub");
const {events, channels} = require("../constants/redis");
class AuthController {
join(req, res) {
let {authToken, meetingId, userId} = req.query;
console.log(`Controllers >> Auth controller --> join: authToken: ${authToken}
meetingId: ${meetingId} userId: ${userId}`);
let removeListener = RedisPubSub.on(events.VALIDATE_AUTH_TOKEN_REPLY, ({payload}) => {
let {meeting_id, auth_token, userid, valid} = payload;
console.log(JSON.stringify(payload));
if(meeting_id === meetingId && auth_token === authToken && userid === userId) {
clearTimeout(waitTimeout);
res.json({valid: valid === "true"});
removeListener();
}
});
let payload = {
auth_token: authToken,
userid: userId,
meeting_id: meetingId,
};
const header = {
reply_to: `${meetingId}/${userId}`,
};
RedisPubSub.publish(channels.MEETING, events.VALIDATE_AUTH_TOKEN, payload, header);
let waitTimeout = setTimeout(()=>{
res.json({valid: false});
}, 5000);
}
}
module.exports = new AuthController();
|
var path = require('path')
, fs = require('fs')
, utile = require('utile');
var application, controllersBefore;
var Dispatch = module.exports = function (app, pwd) {
application = app;
app.routes = {};
app.c = {};
app.r = {};
controllersBefore = {};
var dir = path.join(pwd, 'app/controllers');
var files = fs.readdirSync(dir);
files.forEach(function (file) {
if (path.extname(file) == '.js') {
file = file.replace('.js', '');
app.c[file] = require(path.join(dir, file));
}
});
for (var i in app.c) {
var actions = {};
controllersBefore[i] = {};
for (var j in app.c[i]) {
if (j[0] != '_') {
actions[j] = true;
controllersBefore[i][j] = [];
}
}
if (app.c[i]._before) {
app.c[i]._before.forEach(function (before) {
if (before.only) {
before.only.forEach(function (action) {
controllersBefore[i][action].push(before.exec);
});
} else {
if (before.except) {
before.except.forEach(function (action) {
actions[action] = false;
});
}
for (var j in actions) {
if (actions[j]) {
controllersBefore[i][j].push(before.exec);
} else {
actions[j] = true;
}
}
}
});
}
}
require(path.join(pwd, 'app/routes')).call(new Dispatch.builder(app.routes));
};
Dispatch.builder = function (scope, path) {
var self = this
, app = application
, _m = Dispatch._methods
, _a = Dispatch._action
, _c = Dispatch._checkAction
, _p = Dispatch._pathFunction;
this._path = path || [''];
this._scope = scope;
this.root = function (action, options) {
options = options || {};
action = action.split('/');
if (_c(action)) {
this._scope['/'] = _m(this.scope['/'] || {}, _a(action), options.via);
}
};
this.match = function (url, action, options) {
options = options || {};
action = action.split('/');
if (_c(action)) {
this._scope['/' + url] = _m(this._scope['/' + url] || {}, _a(action), options.via);
if (options.as) {
app.r[options.as + '_path'] = (url === '' ? _p(this._path) : _p(this._path.concat(url)));
}
}
};
this.api = function (model) {
this.scope(model, function () {
this.match('', model + '/index', {via: ['get'], as: model});
this.match('', model + '/create', {via: ['post']});
this.match(':id', model + '/show', {via: ['get'], as: utile.inflect.singularize(model)});
this.match(':id', model + '/update', {via: ['post']});
this.match(':id', model + '/destroy', {via: ['delete']});
});
};
this.resource = function (model) {
this.scope(model, function () {
this.match('new', model + '/new', {via: ['get'], as: 'new_' + utile.inflect.singularize(model)});
this.match(':id/edit', model + '/edit', {via: ['get'], as: 'edit_' + utile.inflect.singularize(model)});
});
this.api(model);
};
this.scope = function (name, func) {
name = '/' + name;
this._scope[name] = this._scope[name] || {};
func.call(new Dispatch.builder(this._scope[name], this._path.concat(name.slice(1))));
};
['get', 'post', 'put', 'delete'].forEach(function (method) {
self[method] = function (url, action) {
action = action.split('/');
if (_c(action)) {
var name = '/' + url;
self._scope[name] = self._scope[name] || {};
self._scope[name][method] = _a(action);
}
};
});
};
Dispatch._pathFunction = function (path) {
var ret = '', c = 0;
path.join('/').split('/').forEach(function (p) {
if (p[0] == ':') {
ret+='"+arguments[' + c + ']+"';
c++;
} else {
ret+=p;
}
ret+='/';
});
ret = ret.slice(0,-1);
if (c === 0) {
return ret;
} else {
eval('var func=function(){return "' + ret + '";};');
return func;
}
};
Dispatch._action = function (action) {
var func = function () {
var self = this
, app = application;
this.arguments = arguments;
utile.async.forEachSeries(
controllersBefore[action[0]][action[1]], function (exec, callback) {
if (exec.indexOf('/') > 0) {
exec = exec.split('/');
} else {
exec = [action[0], exec];
}
if (app.c[exec[0]][exec[1]]) {
app.c[exec[0]][exec[1]].apply(self, [callback].concat(self.arguments));
} else {
callback();
}
}, function (err) {
app.c[action[0]][action[1]].apply(self, self.arguments);
}
);
};
return func;
};
Dispatch._checkAction = function (action) {
var app = application;
if (action.length == 2) {
if (app.c[action[0]]) {
if (app.c[action[0]][action[1]]) {
if (action[1][0] == '_') {
console.log('Action name can not start with _ in ' + action.join('/'));
} else {
return true;
}
} else {
console.log('No action named ' + action[1] + ' in controller ' + action[0]);
}
} else {
console.log('No controller named ' + action[0]);
}
} else {
console.log('Wrong action format ' + action.join('/'));
}
return false;
};
Dispatch._methods = function (ret, func, via) {
via = via || ['get', 'post', 'put', 'delete'];
via.forEach(function (method) {
ret[method] = func;
});
return ret;
};
|
import { Meteor } from 'meteor/meteor';
import {formatDateISO8601Time} from '../../imports/helpers/date';
import {ConfirmationDialogFactory} from './confirmationDialogFactory';
export function isEditedHandling(element, unset, setIsEdited, evt, confirmationDialogTemplate) {
if ((element.isEditedBy != undefined && element.isEditedDate != undefined)) {
let user = Meteor.users.findOne({_id: element.isEditedBy});
let tmplData = {
isEditedBy: user.username,
isEditedDate: formatDateISO8601Time(element.isEditedDate)
};
ConfirmationDialogFactory.makeWarningDialogWithTemplate(
unset,
'Edit despite existing editing',
confirmationDialogTemplate,
tmplData,
'Edit anyway'
).show();
evt.preventDefault();
}
else {
setIsEdited();
}
}
|
const should = require('should');
const supertest = require('supertest');
const testUtils = require('../../../utils');
const localUtils = require('./utils');
const config = require('../../../../server/config');
const ghost = testUtils.startGhost;
let request;
describe('Webhooks API', function () {
var ghostServer;
before(function () {
return ghost()
.then(function (_ghostServer) {
ghostServer = _ghostServer;
request = supertest.agent(config.get('url'));
})
.then(function () {
return localUtils.doAuth(request);
});
});
it('Can creates a webhook', function (done) {
let webhookData = {
event: 'test.create',
target_url: 'http://example.com/webhooks/test/extra/1',
name: 'test',
secret: 'thisissecret',
api_version: 'v2'
};
request.post(localUtils.API.getApiQuery('webhooks/'))
.set('Origin', config.get('url'))
.send({webhooks: [webhookData]})
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(201)
.end(function (err, res) {
if (err) {
return done(err);
}
var jsonResponse = res.body;
should.exist(jsonResponse.webhooks);
localUtils.API.checkResponse(jsonResponse.webhooks[0], 'webhook');
jsonResponse.webhooks[0].event.should.equal(webhookData.event);
jsonResponse.webhooks[0].target_url.should.equal(webhookData.target_url);
jsonResponse.webhooks[0].secret.should.equal(webhookData.secret);
jsonResponse.webhooks[0].name.should.equal(webhookData.name);
jsonResponse.webhooks[0].api_version.should.equal(webhookData.api_version);
done();
});
});
it('Can edit a webhook', function (done) {
request.post(localUtils.API.getApiQuery('integrations/'))
.set('Origin', config.get('url'))
.send({
integrations: [{
name: 'Rubbish Integration Name'
}]
})
.expect(201)
.end(function (err, {body}) {
if (err) {
return done(err);
}
const [createdIntegration] = body.integrations;
request.post(localUtils.API.getApiQuery('webhooks/'))
.set('Origin', config.get('url'))
.send({
webhooks: [{
name: 'Testing',
event: 'site.changed',
target_url: 'https://example.com/rebuild',
integration_id: createdIntegration.id
}]
})
.expect(201)
.end(function (err, {body}) {
if (err) {
return done(err);
}
const [createdWebhook] = body.webhooks;
request.put(localUtils.API.getApiQuery(`webhooks/${createdWebhook.id}/`))
.set('Origin', config.get('url'))
.send({
webhooks: [{
name: 'Edit Test',
event: 'subscriber.added',
target_url: 'https://example.com/new-subscriber'
}]
})
.expect(200)
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.then(({body}) => {
const [updatedWebhook] = body.webhooks;
should.equal(updatedWebhook.id, createdWebhook.id);
should.equal(updatedWebhook.name, 'Edit Test');
should.equal(updatedWebhook.event, 'subscriber.added');
should.equal(updatedWebhook.target_url, 'https://example.com/new-subscriber');
should.equal(updatedWebhook.integration_id, createdIntegration.id);
done();
});
});
});
});
it('Can delete a webhook', function (done) {
var newWebhook = {
event: 'test.create',
// a different target_url from above is needed to avoid an "already exists" error
target_url: 'http://example.com/webhooks/test/2'
};
// create the webhook that is to be deleted
request.post(localUtils.API.getApiQuery('webhooks/'))
.set('Origin', config.get('url'))
.send({webhooks: [newWebhook]})
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(201)
.end(function (err, res) {
if (err) {
return done(err);
}
var location = res.headers.location;
var jsonResponse = res.body;
should.exist(jsonResponse.webhooks);
localUtils.API.checkResponse(jsonResponse.webhooks[0], 'webhook');
jsonResponse.webhooks[0].event.should.equal(newWebhook.event);
jsonResponse.webhooks[0].target_url.should.equal(newWebhook.target_url);
// begin delete test
request.del(localUtils.API.getApiQuery('webhooks/' + jsonResponse.webhooks[0].id + '/'))
.set('Origin', config.get('url'))
.expect(204)
.end(function (err, res) {
if (err) {
return done(err);
}
res.body.should.be.empty();
done();
});
});
});
});
|
'use strict'
module.exports = function getInfo() {
const info = this.server.info
this.log('Retrieving server info:', info)
return info
}
|
module.exports = function (x,y) {
var array = [];
if (!y) {
for (var i = 0; i < x; i++) {
array.push(i);
}
} else {
for (var i=x; i < y; i++) {
array.push(i);
}
}
return array;
};
|
/* @flow */
import type { PredefinedGeneratorOptions } from '../../types';
const path = require('path');
const { convertToPascalCase } = require('../../utils');
const createTemplate = module.parent.createTemplate;
const classComponentTemplate = createTemplate`
/* @flow */
import React, { Component } from "react";
export default class ${args => args.name} extends Component {
render () {
return (
<div>
${args => args.name}
</div>
);
}
}
`;
const functionalComponentTemplate = createTemplate`
/* @flow */
import React from "react";
export default function ${args => args.name} () {
return (
<div>
${args => args.name}
</div>
);
}
`;
const testTemplate = createTemplate`
import React from "react";
import { shallow } from "enzyme";
import ${args => args.name} from "${args => args.path}";
describe("${args => args.path}", () => {
it("renders without an issue", () => {
const subject = <${args => args.name} />;
const wrapper = shallow(subject);
expect(wrapper).toBeDefined();
});
});
`;
module.exports = (options: PredefinedGeneratorOptions) => {
const rewrittenName = convertToPascalCase(options.name);
const directoryPrefix =
options.dir && options.dir !== '.' ? `${options.dir}/` : '';
return {
args: {
name: rewrittenName,
},
entries: [
{
path: path.join(
'src',
options.entryPoint,
'components',
directoryPrefix,
),
filename: rewrittenName,
template: options.functional
? functionalComponentTemplate
: classComponentTemplate,
},
{
path: path.join(
'src',
options.entryPoint,
'components',
directoryPrefix,
'__tests__',
),
filename: `${rewrittenName}.test.js`,
template: testTemplate,
args: {
path: path.join(
options.entryPoint,
'components',
directoryPrefix,
rewrittenName,
),
},
},
],
};
};
|
/**
* Angular Wizard directive
* Copyright (c) 2014 Genadijus Paleckis (genadijus.paleckis@gmail.com)
* License: MIT
* GIT: https://github.com/sickelap/angular-wizard
*
* Example usage:
*
* In your template add tag:
* <div wizard="wizardConfig"></div>
*
* Then in your controller create wizard configuration:
*
* $scope.wizardConfig = {
* steps: [
* {
* title: 'Step #1',
* titleNext: 'Next: Step #2',
* templateUrl: 'wizard_step1.html',
* callback: function(){ return true; }
* },
* {
* title: 'Step #2',
* titlePrev: 'Back: Step #1'
* titleNext: 'Next: Step #3',
* templateUrl: 'wizard_step1.html',
* callback: function(){ return true; }
* },
* {
* title: 'Step #3',
* titlePrev: 'Back: Step #2',
* titleNext: 'Finish',
* templateUrl: 'wizard_step1.html',
* callback: function(){ return true; }
* }
* ]
* }
*
*/
angular.module('wizard', ['wizardStep'])
.directive('wizard', function () {
var template = '' +
'<div class="wizard">' +
' <ol class="wizard-breadcrumbs">' +
' <li ng-repeat="s in config.steps" class="{{ s.position }}">' +
' <a href="#" ng-click="gotoStep($index)" ng-if="s.position===\'past\'">{{ s.title }}</a>' +
' <span ng-if="s.position!==\'past\'">{{ s.title }}</span>' +
' </li>' +
' </ol>' +
' <ul class="wizard-steps">' +
' <li ng-repeat="s in config.steps" ng-show="isCurrent($index)">' +
' <div data-wizard-step="s"></div>' +
' </li>' +
' </ul>' +
'</div>';
var linkFn = function (scope) {
scope.currentStep = 0;
/**
* set correct position for all the steps in the wizard
*/
angular.forEach(scope.config.steps, function (step, index) {
step.position = (index === 0) ? 'current' : 'future';
});
scope.isCurrent = function (index) {
return (scope.config.steps[index].position === 'current');
};
scope.gotoStep = function (transitionTo) {
if (transitionTo > scope.currentStep) {
var step = scope.config.steps[scope.currentStep];
if (typeof step.callback === 'function') {
if (true !== step.callback()) {
return;
}
}
}
if (transitionTo >= scope.config.steps.length) {
return; // last step
}
if (transitionTo < 0) {
return; // first step
}
scope.currentStep = transitionTo;
angular.forEach(scope.config.steps, function (step, index) {
if (index < scope.currentStep) {
step.position = 'past';
}
if (index === scope.currentStep) {
step.position = 'current';
}
if (index > scope.currentStep) {
step.position = 'future';
}
});
};
};
var controllerFn = ['$scope', function ($scope) {
return {
goBack: function () {
$scope.gotoStep($scope.currentStep - 1);
},
goNext: function () {
$scope.gotoStep($scope.currentStep + 1);
}
};
}];
return {
replace: true,
scope: {
config: '=wizard'
},
template: template,
link: linkFn,
controller: controllerFn
};
})
;
angular.module('wizardStep', [])
.directive('wizardStep', ['$templateCache', '$compile', function ($templateCache, $compile) {
var template = '' +
'<div class="wizard-step">' +
' <div class="wizard-step-nav">' +
' <a href="#" class="wizard-step-nav-prev" ng-click="goBack()" ng-if="config.titlePrev">{{ config.titlePrev }}</a>' +
' <a href="#" class="wizard-step-nav-next" ng-click="goNext()" ng-if="config.titleNext">{{ config.titleNext }}</a>' +
' </div>' +
'</div>';
var linkFn = function (scope, element, attr, wizard) {
/**
* interpolate template into the step's DOM
*/
element.prepend($templateCache.get(scope.config.templateUrl));
$compile(element.contents())(scope);
/**
* Expose step configuration items directly to the scope.
* This way we can access step's consiguration properties directly,
* for instance {{title}} instead of {{config.title}}.
*/
angular.forEach(scope.config, function (value, key) {
scope[key] = value;
});
scope.goBack = function () {
wizard.goBack();
};
scope.goNext = function () {
// find a form in the scope
var formElm = element.find('form');
var form = scope[formElm.prop('name')];
/**
* By default step will be valid even if form element does not exist
* @type {boolean}
*/
var formValid = true;
if (form) { // Do we have a form with controller?
form.$setDirty();
formValid = form.$valid;
}
if (formValid) {
wizard.goNext();
}
};
};
return {
restrict: 'A',
require: '^wizard',
scope: {
config: '=wizardStep'
},
template: template,
link: linkFn
};
}])
;
|
'use strict';
var path = require('path');
var loadGulpPlugins = require('gulp-load-plugins');
var assign = require('object-assign');
var pkg = require('../package.json');
var requirePeer = require('./helpers/require-peer');
var parentPkgPath = path.join(process.cwd(), 'package.json');
var parentPkg = require(parentPkgPath);
var dummyScope = Math.random().toString(36).substring(-5);
parentPkg[dummyScope] = assign(
{},
pkg.neededPeerDependencies,
pkg.optionalPeerDependencies
);
module.exports = loadGulpPlugins({
config: parentPkg,
scope: [
'dependencies',
'devDependencies',
'peerDependencies'
].concat(dummyScope),
requireFn: requirePeer
});
|
'use strict';
module.exports = function(arr, arrays) {
for (var i = 1; i < arguments.length; i++) {
diff(arr, arguments[i]);
}
return arr;
};
function diff(one, two) {
if (!Array.isArray(two)) return;
var len = two.length;
var idx = -1;
while (++idx < len) {
remove(one, two[idx]);
}
}
function remove(arr, ele) {
var idx = arr.indexOf(ele);
if (idx === -1) return;
var item = arr.pop();
if (item !== ele) {
arr[idx] = item;
}
return remove(arr, ele);
}
|
/**
* Copyright 2017-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable max-len */
/**
* Displays the password mismatch error message and status icons.
*
* @returns {undefined}
*/
const showPasswordError = () => {
const errorSection = document.getElementById('error');
const inputStatus = document.querySelector('div.inputStatus');
if (errorSection) {
errorSection.innerHTML = '<p id="passwordError">Oops. Passwords don’t match.</p>';
}
if (inputStatus) {
inputStatus.innerHTML = '<img src="/images/warning.svg" class="statusIcon warning">';
}
};
/**
* Removes the password mismatch error message and status icons.
*
* @returns {undefined}
*/
const clearPasswordError = () => {
const errorSection = document.getElementById('error');
const passwordError = document.getElementById('passwordError');
if (errorSection && passwordError) {
errorSection.removeChild(passwordError);
}
const inputStatus = document.querySelector('div.inputStatus');
const warning = document.querySelector('#password2Field > div.inputStatus > img.warning');
if (inputStatus && warning) {
inputStatus.removeChild(warning);
}
};
/**
* Checks if passwords match, if not displays errors.
*
* @returns {Boolean} true if passwords match
*/
const passwordsMatch = () => {
const password = document.getElementById('password');
const passwordVerification = document.getElementById('passwordVerification');
if (!password || !passwordVerification) {
return true;
}
if (password.value&& passwordVerification.value&& password.value !== passwordVerification.value){
showPasswordError();
} else {
clearPasswordError();
}
return password.value === passwordVerification.value;
};
/**
* Applies a check icon next to a fieldset
*
* @param {Object} field Fieldset item to apply check icon to
* @returns {undefined}
*/
const applyCheckToField = (field) => {
const inputStatus = document.querySelector("div.inputStatus");
console.log("field.value",field.value);
const checkExists = document.querySelector('img[src$="check.svg"]');
if(checkExists!=null)
console.log("checkExists,mvcvmc",checkExists.src)
console.log("checkExists*******",checkExists);
if (inputStatus && !checkExists) {
inputStatus.innerHTML = '<img src="/images/check.svg" class="statusIcon warning">';
}
};
/**
* Removes icon next to a fieldset
*
* @param {Object} field Fieldset item to remove icon from
* @returns {undefined}
*/
const removeStatusFromField = (field) => {
const inputStatus = document.querySelector(".inputStatus");
const ptag = document.getElementById('errorinput');
//~ console.log("ptag",ptag);
//~ console.log("inputStatus---",inputStatus);
if (inputStatus) {
inputStatus.innerHTML = '';
if(ptag!=null)
ptag.innerHTML='';
}
};
/**
* Apply check icon to all filled out fieldsets marked required
*
* @returns {undefined}
*/
const applyCheckToFilledFields = () => {
const requiredFields = Array.apply(
null,
document.getElementsByClassName('required')
);
requiredFields.forEach((field) => {
if (field.value) {
console.log("field value is",field)
//applyCheckToField(field);
} else {
console.log("the field am calling is",field);
removeStatusFromField(field);
}
});
passwordsMatch();
};
/**
* Apply check icon to all filled out fieldsets marked required
*
* @returns {Boolean} true if all required fields have been filled
*/
const requiredFieldsFilled = () => {
const requiredFields = Array.apply(
null,
document.getElementsByClassName('required')
);
const unfilledFields = requiredFields.filter((field) => field.value === '');
return unfilledFields.length === 0;
};
/**
* Enables the submit button if required fields filled and passwords match
*
* @returns {undefined}
*/
const enableSubmit = () => {
const submitButton = document.getElementById('submit');
if (submitButton) {
submitButton.disabled = !requiredFieldsFilled() || !passwordsMatch();
}
};
/**
* Show the loading spinner on the submit button.
*
* @returns {undefined}
*/
const showSpinner = () => {
const submitButton = document.getElementById('submitText');
const spinner = document.getElementById('spinner');
if (submitButton) {
submitButton.style.opacity = '0.6';
}
if (spinner) {
spinner.style.display = 'inline';
}
};
/**
* Subscribe functions to form events on domready
*
* @returns {undefined}
*/
const subscribeToChange = () => {
const form = document.getElementsByTagName('form')[0];
if (form) {
form.addEventListener('change', enableSubmit);
form.addEventListener('paste', enableSubmit);
form.addEventListener('keyup', enableSubmit);
form.addEventListener('keyup', applyCheckToFilledFields);
form.addEventListener('submit', showSpinner, true);
}
};
document.addEventListener('DOMContentLoaded', enableSubmit);
document.addEventListener('DOMContentLoaded', subscribeToChange);
|
// reference:
// https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/custom-offline-page/service-worker.js
self.addEventListener('install', event => {
event.waitUntil(
caches.open('offline')
.then(cache => cache.addAll([
'/offline.html'
]))
.then(self.skipWaiting())
);
});
self.addEventListener('fetch', event => {
// We only want to call event.respondWith() if this is a navigation request for an HTML page.
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' &&
event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request).catch(() => {
// The catch is only triggered if fetch() throws an exception, which will most likely
// happen due to the server being unreachable.
return caches.match('/offline.html');
})
);
}
});
|
/**
* Created by Rodrigo on 25/01/2017.
*/
const data = {};
const subscribers = {};
const EVENTS = {
SET: 'set',
SUBSCRIBE : 'subscribe',
UNSUBSCRIBE: 'unsubscribe'
};
/**
* Notify to all the subscriber the new value.
* A subscriber must implement a _onEvent method.
* @param event
* @param detail
* @param path
* @private
*/
const _notify = (event, detail, path = '') => {
// This method will notify to elements subscribed to the path,
// as well as the element who are subscribed to every single action, as the global-data element.
const pathSubscribers = subscribers[path] || [];
const wildCardSubscribers = subscribers['*'] || [];
[...pathSubscribers, ...wildCardSubscribers].forEach(subscriber => {
subscriber._onEvent(event, detail);
});
};
const _addSubscriber = (path, subscriber) => {
subscribers[path] = subscribers[path] || [];
subscribers[path].push(subscriber);
};
const _deleteSubscriber = (path, subscriber) => {
const index = subscribers[path].indexOf(subscriber);
if (index >= 0) subscribers[path].splice(index, 1);
if (subscribers[path].length === 0) delete subscribers[path];
};
const get = path => data[path];
const set = (path, value) => {
if (data[path] === value) {
return
}
const { SET } = EVENTS;
data[path] = value;
_notify(SET, {
path,
value
}, path);
};
const subscribe = (path, subscriber) => {
const { SUBSCRIBE } = EVENTS;
_addSubscriber(path, subscriber)
_notify(SUBSCRIBE, {
path,
element: subscriber
})
};
const unsubscribe = (path, subscriber) => {
if (!subscribers[path]) {
return
}
const { UNSUBSCRIBE } = EVENTS;
_deleteSubscriber(path, subscriber);
_notify(UNSUBSCRIBE, {
path,
element: subscriber
});
};
/**
* If the element is subscribed, will return the path of the subscription. If not, will return `false`
* @param subscriber
* @returns {String | false}
*/
const isSubcribed = subscriber =>
Object
.entries(subscribers)
.reduce((acc, [path, subs]) =>
subs.contains(subscriber) ? path : acc
, false)
export default {
EVENTS,
get,
set,
subscribe,
unsubscribe,
isSubcribed
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.