code
stringlengths 2
1.05M
|
---|
/*!
* froala_editor v3.0.5 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2019 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* French
*/
FE.LANGUAGE['fr'] = {
translation: {
// Place holder
'Type something': 'Tapez quelque chose',
// Basic formatting
'Bold': 'Gras',
'Italic': 'Italique',
'Underline': "Soulign\xE9",
'Strikethrough': "Barr\xE9",
// Main buttons
'Insert': "Ins\xE9rer",
'Delete': 'Supprimer',
'Cancel': 'Annuler',
'OK': 'Ok',
'Back': 'Retour',
'Remove': 'Supprimer',
'More': 'Plus',
'Update': 'Actualiser',
'Style': 'Style',
// Font
'Font Family': "Polices de caract\xE8res",
'Font Size': 'Taille de police',
// Colors
'Colors': 'Couleurs',
'Background': "Arri\xE8re-plan",
'Text': 'Texte',
'HEX Color': "Couleur hexad\xE9cimale",
// Paragraphs
'Paragraph Format': 'Format de paragraphe',
'Normal': 'Normal',
'Code': 'Code',
'Heading 1': 'Titre 1',
'Heading 2': 'Titre 2',
'Heading 3': 'Titre 3',
'Heading 4': 'Titre 4',
// Style
'Paragraph Style': 'Style de paragraphe',
'Inline Style': 'Style en ligne',
// Alignment
'Align': 'Aligner',
'Align Left': "Aligner \xE0 gauche",
'Align Center': 'Aligner au centre',
'Align Right': "Aligner \xE0 droite",
'Align Justify': 'Justifier',
'None': 'Aucun',
// Lists
'Ordered List': "Liste ordonn\xE9e",
'Unordered List': "Liste non ordonn\xE9e",
// Indent
'Decrease Indent': 'Diminuer le retrait',
'Increase Indent': 'Augmenter le retrait',
// Links
'Insert Link': "Ins\xE9rer un lien",
'Open in new tab': 'Ouvrir dans un nouvel onglet',
'Open Link': 'Ouvrir le lien',
'Edit Link': 'Modifier le lien',
'Unlink': 'Enlever le lien',
'Choose Link': 'Choisir le lien',
// Images
'Insert Image': "Ins\xE9rer une image",
'Upload Image': "T\xE9l\xE9verser une image",
'By URL': 'Par URL',
'Browse': 'Parcourir',
'Drop image': "D\xE9poser une image",
'or click': 'ou cliquer',
'Manage Images': "G\xE9rer les images",
'Loading': 'Chargement',
'Deleting': 'Suppression',
'Tags': "\xC9tiquettes",
'Are you sure? Image will be deleted.': "Etes-vous certain? L'image sera supprim\xE9e.",
'Replace': 'Remplacer',
'Uploading': "En t\xE9l\xE9versement d'images",
'Loading image': 'En chargement d\'images',
'Display': 'Afficher',
'Inline': 'En ligne',
'Break Text': 'Rompre le texte',
'Alternative Text': 'Texte alternatif',
'Change Size': 'Changer la dimension',
'Width': 'Largeur',
'Height': 'Hauteur',
'Something went wrong. Please try again.': "Quelque chose a mal tourn\xE9. Veuillez r\xE9essayer.",
'Image Caption': "L\xE9gende de l'image",
'Advanced Edit': "\xC9dition avanc\xE9e",
// Video
'Insert Video': "Ins\xE9rer une vid\xE9o",
'Embedded Code': "Code int\xE9gr\xE9",
'Paste in a video URL': "Coller l'URL d'une vid\xE9o",
'Drop video': "D\xE9poser une vid\xE9o",
'Your browser does not support HTML5 video.': "Votre navigateur ne supporte pas les vid\xE9os en format HTML5.",
'Upload Video': "T\xE9l\xE9verser une vid\xE9o",
// Tables
'Insert Table': "Ins\xE9rer un tableau",
'Table Header': "Ent\xEAte de tableau",
'Remove Table': 'Supprimer le tableau',
'Table Style': 'Style de tableau',
'Horizontal Align': 'Alignement horizontal',
'Row': 'Ligne',
'Insert row above': "Ins\xE9rer une ligne au-dessus",
'Insert row below': "Ins\xE9rer une ligne en-dessous",
'Delete row': 'Supprimer la ligne',
'Column': 'Colonne',
'Insert column before': "Ins\xE9rer une colonne avant",
'Insert column after': "Ins\xE9rer une colonne apr\xE8s",
'Delete column': 'Supprimer la colonne',
'Cell': 'Cellule',
'Merge cells': 'Fusionner les cellules',
'Horizontal split': 'Diviser horizontalement',
'Vertical split': 'Diviser verticalement',
'Cell Background': "Arri\xE8re-plan de la cellule",
'Vertical Align': 'Alignement vertical',
'Top': 'En haut',
'Middle': 'Au centre',
'Bottom': 'En bas',
'Align Top': 'Aligner en haut',
'Align Middle': 'Aligner au centre',
'Align Bottom': 'Aligner en bas',
'Cell Style': 'Style de cellule',
// Files
'Upload File': "T\xE9l\xE9verser un fichier",
'Drop file': "D\xE9poser un fichier",
// Emoticons
'Emoticons': "\xC9motic\xF4nes",
'Grinning face': 'Souriant visage',
'Grinning face with smiling eyes': 'Souriant visage aux yeux souriants',
'Face with tears of joy': "Visage \xE0 des larmes de joie",
'Smiling face with open mouth': 'Visage souriant avec la bouche ouverte',
'Smiling face with open mouth and smiling eyes': 'Visage souriant avec la bouche ouverte et les yeux en souriant',
'Smiling face with open mouth and cold sweat': 'Visage souriant avec la bouche ouverte et la sueur froide',
'Smiling face with open mouth and tightly-closed eyes': "Visage souriant avec la bouche ouverte et les yeux herm\xE9tiquement clos",
'Smiling face with halo': 'Sourire visage avec halo',
'Smiling face with horns': 'Visage souriant avec des cornes',
'Winking face': 'Clin d\'oeil visage',
'Smiling face with smiling eyes': 'Sourire visage aux yeux souriants',
'Face savoring delicious food': "Visage savourant de d\xE9licieux plats",
'Relieved face': "Soulag\xE9 visage",
'Smiling face with heart-shaped eyes': 'Visage souriant avec des yeux en forme de coeur',
'Smiling face with sunglasses': 'Sourire visage avec des lunettes de soleil',
'Smirking face': 'Souriant visage',
'Neutral face': 'Visage neutre',
'Expressionless face': 'Visage sans expression',
'Unamused face': "Visage pas amus\xE9",
'Face with cold sweat': "Face \xE0 la sueur froide",
'Pensive face': 'pensif visage',
'Confused face': 'Visage confus',
'Confounded face': 'visage maudit',
'Kissing face': 'Embrasser le visage',
'Face throwing a kiss': 'Visage jetant un baiser',
'Kissing face with smiling eyes': 'Embrasser le visage avec les yeux souriants',
'Kissing face with closed eyes': "Embrasser le visage avec les yeux ferm\xE9s",
'Face with stuck out tongue': 'Visage avec sortait de la langue',
'Face with stuck out tongue and winking eye': 'Visage avec sortait de la langue et des yeux clignotante',
'Face with stuck out tongue and tightly-closed eyes': "Visage avec sortait de la langue et les yeux ferm\xE9s herm\xE9tiquement",
'Disappointed face': "Visage d\xE9\xE7u",
'Worried face': 'Visage inquiet',
'Angry face': "Visage en col\xE9re",
'Pouting face': 'Faire la moue face',
'Crying face': 'Pleurer visage',
'Persevering face': "Pers\xE9v\xE9rer face",
'Face with look of triumph': 'Visage avec le regard de triomphe',
'Disappointed but relieved face': "D\xE9\xE7u, mais le visage soulag\xE9",
'Frowning face with open mouth': "Les sourcils fronc\xE9s visage avec la bouche ouverte",
'Anguished face': "Visage angoiss\xE9",
'Fearful face': 'Craignant visage',
'Weary face': 'Visage las',
'Sleepy face': 'Visage endormi',
'Tired face': "Visage fatigu\xE9",
'Grimacing face': "Visage grima\xE7ante",
'Loudly crying face': 'Pleurer bruyamment visage',
'Face with open mouth': "Visage \xE0 la bouche ouverte",
'Hushed face': "Visage feutr\xE9e",
'Face with open mouth and cold sweat': "Visage \xE0 la bouche ouverte et la sueur froide",
'Face screaming in fear': 'Visage hurlant de peur',
'Astonished face': "Visage \xE9tonn\xE9",
'Flushed face': "Visage congestionn\xE9",
'Sleeping face': 'Visage au bois dormant',
'Dizzy face': 'Visage vertige',
'Face without mouth': 'Visage sans bouche',
'Face with medical mask': "Visage avec un masque m\xE9dical",
// Line breaker
'Break': 'Rompre',
// Math
'Subscript': 'Indice',
'Superscript': 'Exposant',
// Full screen
'Fullscreen': "Plein \xE9cran",
// Horizontal line
'Insert Horizontal Line': "Ins\xE9rer une ligne horizontale",
// Clear formatting
'Clear Formatting': 'Effacer le formatage',
// Save
'Save': 'sauvegarder',
// Undo, redo
'Undo': 'Annuler',
'Redo': "R\xE9tablir",
// Select all
'Select All': "Tout s\xE9lectionner",
// Code view
'Code View': 'Mode HTML',
// Quote
'Quote': 'Citation',
'Increase': 'Augmenter',
'Decrease': 'Diminuer',
// Quick Insert
'Quick Insert': 'Insertion rapide',
// Spcial Characters
'Special Characters': "Caract\xE8res sp\xE9ciaux",
'Latin': 'Latin',
'Greek': 'Grec',
'Cyrillic': 'Cyrillique',
'Punctuation': 'Ponctuation',
'Currency': 'Devise',
'Arrows': "Fl\xE8ches",
'Math': 'Math',
'Misc': 'Divers',
// Print.
'Print': 'Imprimer',
// Spell Checker.
'Spell Checker': 'Correcteur orthographique',
// Help
'Help': 'Aide',
'Shortcuts': 'Raccourcis',
'Inline Editor': "\xC9diteur en ligne",
'Show the editor': "Montrer l'\xE9diteur",
'Common actions': 'Actions communes',
'Copy': 'Copier',
'Cut': 'Couper',
'Paste': 'Coller',
'Basic Formatting': 'Formatage de base',
'Increase quote level': 'Augmenter le niveau de citation',
'Decrease quote level': 'Diminuer le niveau de citation',
'Image / Video': "Image / vid\xE9o",
'Resize larger': 'Redimensionner plus grand',
'Resize smaller': 'Redimensionner plus petit',
'Table': 'Table',
'Select table cell': "S\xE9lectionner la cellule du tableau",
'Extend selection one cell': "\xC9tendre la s\xE9lection d'une cellule",
'Extend selection one row': "\xC9tendre la s\xE9lection d'une ligne",
'Navigation': 'Navigation',
'Focus popup / toolbar': 'Focus popup / toolbar',
'Return focus to previous position': "Retourner l'accent sur le poste pr\xE9c\xE9dent",
// Embed.ly
'Embed URL': "URL int\xE9gr\xE9e",
'Paste in a URL to embed': "Coller une URL int\xE9gr\xE9e",
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': "Le contenu coll\xE9 provient d'un document Microsoft Word. Voulez-vous conserver le format ou le nettoyer?",
'Keep': 'Conserver',
'Clean': 'Nettoyer',
'Word Paste Detected': "Copiage de mots d\xE9tect\xE9",
// Character Counter
'Characters': 'Personnages',
// More Buttons
'More Text': 'Plus de texte',
'More Paragraph': 'Plus paragraphe',
'More Rich': 'Plus riche',
'More Misc': 'Plus divers'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=fr.js.map
|
version https://git-lfs.github.com/spec/v1
oid sha256:9d14e3992ae30f9f4c2fdaa4abea078af225c1925240fc738ff83d2d88028407
size 2781
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import ListContext from './ListContext';
export var styles = {
/* Styles applied to the root element. */
root: {
listStyle: 'none',
margin: 0,
padding: 0,
position: 'relative'
},
/* Styles applied to the root element if `disablePadding={false}`. */
padding: {
paddingTop: 8,
paddingBottom: 8
},
/* Styles applied to the root element if dense. */
dense: {},
/* Styles applied to the root element if a `subheader` is provided. */
subheader: {
paddingTop: 0
}
};
var List = React.forwardRef(function List(props, ref) {
var children = props.children,
classes = props.classes,
className = props.className,
_props$component = props.component,
Component = _props$component === void 0 ? 'ul' : _props$component,
_props$dense = props.dense,
dense = _props$dense === void 0 ? false : _props$dense,
_props$disablePadding = props.disablePadding,
disablePadding = _props$disablePadding === void 0 ? false : _props$disablePadding,
subheader = props.subheader,
other = _objectWithoutProperties(props, ["children", "classes", "className", "component", "dense", "disablePadding", "subheader"]);
var context = React.useMemo(function () {
return {
dense: dense
};
}, [dense]);
return React.createElement(ListContext.Provider, {
value: context
}, React.createElement(Component, _extends({
className: clsx(classes.root, className, dense && classes.dense, !disablePadding && classes.padding, subheader && classes.subheader),
ref: ref
}, other), subheader, children));
});
process.env.NODE_ENV !== "production" ? List.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component: PropTypes.elementType,
/**
* If `true`, compact vertical padding designed for keyboard and mouse input will be used for
* the list and list items.
* The prop is available to descendant components as the `dense` context.
*/
dense: PropTypes.bool,
/**
* If `true`, vertical padding will be removed from the list.
*/
disablePadding: PropTypes.bool,
/**
* The content of the subheader, normally `ListSubheader`.
*/
subheader: PropTypes.node
} : void 0;
export default withStyles(styles, {
name: 'MuiList'
})(List);
|
#!/usr/bin/env node
var profiler = require("v8-profiler");
var Bitcoin = require('../lib/bitcoin');
// Settings
// -----------------------------------------------------------------------------
var settings = new Bitcoin.Settings();
// Connect to live Bitcoin network
settings.setLivenetDefaults();
// Add peers to connect to
settings.network.initialPeers.push('localhost');
// MongoDB URI
settings.storage.uri ='mongodb://localhost/bitcoin';
node = new Bitcoin.Node(settings);
node.addPeer('localhost');
// Profile each state in the startup routine
node.addListener('stateChange', function (e) {
// Start profiling for the state that just started
if (e.newState) {
profiler.startProfiling(e.newState);
}
// Stop profiling for the state that just ended
if (e.oldState) {
profiler.stopProfiling(e.newState);
}
});
node.start();
|
/**
* Boundary geometry node type
*
* @author xeolabs / http://xeolabs.com
*
* <p>Usage example:</p>
*
* <pre>
* someNode.addNode({
* type: "geometry/boundary",
* min: [-9, -3, -2],
* max: [2,3,12],
* wire: false // Default
* });
* </pre>
*/
(function () {
SceneJS.Types.addType("geometry/boundary", {
construct:function (params) {
this.addNode(build.call(this, params));
}
});
function build(params) {
var min = params.min || [0, 0, 0];
var max = params.max || [0, 0, 0];
var xmin = min[0];
var ymin = min[1];
var zmin = min[2];
var xmax = max[0];
var ymax = max[1];
var zmax = max[2];
var coreId = "geometry/boundary_" + xmin + "_" + ymin + "_" + zmin + "_"
+ xmax + "_" + ymax + "_" + zmax + (params.wire ? "wire" : "_solid");
// If a node core already exists for a prim with the given properties,
// then for efficiency we'll share that core rather than create another geometry
if (this.getScene().hasCore("geometry", coreId)) {
return {
type:"geometry",
coreId:coreId
};
}
// Otherwise, create a new geometry
return {
type:"geometry",
primitive:params.wire ? "lines" : "triangles",
coreId:coreId,
positions:[
xmax, ymax, zmax,
xmax, ymin, zmax,
xmin, ymin, zmax,
xmin, ymax, zmax,
xmax, ymax, zmin,
xmax, ymin, zmin,
xmin, ymin, zmin,
xmin, ymax, zmin
],
indices:[
0, 1, 1,
2, 2, 3,
3, 0, 4,
5, 5, 6,
6, 7, 7,
4, 0, 4,
1, 5, 2,
6, 3, 7
]
}
}
})();
|
/* eslint no-var: 0, no-console: 0, import/no-extraneous-dependencies: 0 */
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import webpackConfig from './webpack.client.rails.hot.config';
const hotRailsPort = process.env.HOT_RAILS_PORT || 3500;
const compiler = webpack(webpackConfig);
const devServer = new WebpackDevServer(compiler, {
contentBase: `http://lvh.me:${hotRailsPort}`,
publicPath: webpackConfig.output.publicPath,
hot: true,
inline: true,
historyApiFallback: true,
quiet: false,
noInfo: false,
lazy: false,
stats: {
colors: true,
hash: false,
version: false,
chunks: false,
children: false,
},
});
devServer.listen(hotRailsPort, 'localhost', (err) => {
if (err) console.error(err);
console.log(
`=> 🔥 Webpack development server is running on port ${hotRailsPort}`,
);
});
|
/**
* # ItemCheckbox-test.js
*
* This class tests that the ItemCheckbox renders correctly under
* numerous conditions
*
* *Note:* if you want to understand the structures here, add a
* ```console.log``` and then ```npm test```.
*
*/
'use strict';
jest.autoMockOff();
/**
* ## Imports
*
* React is mocked in src/__mocks__/react-native.js
*
* *Note*: put a ```console.log``` on the outputs to see the structures
*/
import React, { View } from 'react-native';
import utils from 'react-addons-test-utils';
/**
* ## Under test
* class under test
*/
jest.dontMock('../ItemCheckbox');
var ItemCheckbox = require('../ItemCheckbox');
/**
* ## Test
*/
describe('ItemCheckbox', () => {
let iconName = {
'true': 'check-square',
'false': 'square-o'
};
/**
* ### renderItemCheckbox
* render the component under test and return
* @returns {Object} object with props, output and the renderer
*
*/
function renderItemCheckbox(props) {
const renderer = utils.createRenderer();
renderer.render(<ItemCheckbox {...props}/>);
const output = renderer.getRenderOutput();
return {
props,
output,
renderer
};
}
/**
* ### findTouchable
* @returns {Object} props the
*/
function findTouchable(output) {
return output.props.children.props;
}
/**
* ### findIcon
* @returns {Object} that contains icon object
*/
function findIcon(output) {
return output.children.props.children[0];
}
/**
* ### findText
* @returns {Object} that contains the text object
*/
function findText(output) {
return output.children.props.children[1];
}
/**
* ### testItemCheckbox
*
* @param {Object} props The object with fields:
*
* * checked
* * text
* * disabled
*
* Validate that the renderend componets displays correctly
*/
function testItemCheckbox(props) {
const {output} = renderItemCheckbox(props);
expect(output.type).toEqual(View);
const touchableWithoutFeedback = findTouchable(output);
if (props.disabled) {
expect(typeof touchableWithoutFeedback.onPress).toEqual('undefined');
} else {
expect(typeof touchableWithoutFeedback.onPress).toEqual('function');
}
const icon = findIcon(touchableWithoutFeedback);
expect(icon.props.name).toEqual(iconName[props.checked]);
const text = findText(touchableWithoutFeedback);
expect(text.props.children[1]).toEqual(props.text);
}
/**
* ### if not disabled and checked, it should display check-square and text
* change the props and call ```testItemCheckbox``` to validate
*/
it('if not disabled and checked, it should display check-square and text', () => {
const props = {
checked: true,
text: 'TextShouldDisplay',
disabled: false
};
testItemCheckbox(props);
});
/**
* ### if not disabled and not checked, it should display square-o and text
* change the props and call ```testItemCheckbox``` to validate
*/
it('if not disabled and not checked, it should display square-o and text', () => {
const props = {
checked: false,
text: 'TextShouldDisplay',
disabled: false
};
testItemCheckbox(props);
});
/**
* ### if disabled and checked, it should display check-square and text
* change the props and call ```testItemCheckbox``` to validate
*/
it('if disabled and checked, it should display check-square and text', () => {
const props = {
checked: true,
text: 'TextShouldDisplay',
disabled: true
};
testItemCheckbox(props);
});
/**
* ### if disabled and not checked, it should display square-o and text
* change the props and call ```testItemCheckbox``` to validate
*/
it('if disabled and not checked, it should display square-o and text', () => {
const props = {
checked: false,
text: 'TextShouldDisplay',
disabled: true
};
testItemCheckbox(props);
});
});//describe ItemCheckbox
|
module.exports={A:{A:{"2":"K C G E A B CB"},B:{"1":"M H","2":"D u Y I"},C:{"1":"0 2 3 4 5 6 7 y z v","2":"1 VB F J K C G E A B D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m n o p q r s t TB SB"},D:{"1":"3 5 6 7 v HB g DB XB EB FB","2":"F J K C G E A B D u Y I M H N O P Q R S T U V W X w Z a b c d e f L h i j k l m","16":"n o p","388":"0 2 4 q r s t y z"},E:{"2":"F J K C G E A B GB AB IB JB KB LB MB NB"},F:{"1":"l m n o p q r s t","2":"8 9 E B D I M H N O P Q R S T U V W X w Z a b c d e f L h i j k OB PB QB RB UB x"},G:{"2":"G AB WB BB YB ZB aB bB cB dB eB fB gB"},H:{"2":"hB"},I:{"1":"g","2":"iB jB kB","16":"1 F lB BB mB nB"},J:{"1":"A","2":"C"},K:{"1":"x","16":"8 9 A B D","129":"L"},L:{"1":"g"},M:{"2":"v"},N:{"2":"A B"},O:{"1":"oB"},P:{"1":"J pB","129":"F"},Q:{"2":"qB"},R:{"1":"rB"}},B:6,C:"FLAC audio format"};
|
/** (July 2012, Erik Weitnauer)
The html-plugin will load and display an arbitrary number of html pages. To proceed to the next, the
user might either press a button on the page or a specific key. Afterwards, the page get hidden and
the plugin will wait of a specified time before it proceeds.
documentation: docs.jspsych.org
*/
(function($) {
jsPsych.html = (function() {
var plugin = {};
plugin.create = function(params) {
params = jsPsych.pluginAPI.enforceArray(params, ['pages']);
var trials = [];
for (var i = 0; i < params.pages.length; i++) {
trials.push({
url: params.pages[i].url,
cont_key: params.pages[i].cont_key || params.cont_key,
cont_btn: params.pages[i].cont_btn || params.cont_btn,
check_fn: params.pages[i].check_fn || function(){ return true; },
force_refresh: (typeof params.force_refresh === 'undefined') ? false : params.force_refresh
});
}
return trials;
};
plugin.trial = function(display_element, trial) {
// if any trial variables are functions
// this evaluates the function and replaces
// it with the output of the function
trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial, ["check_fn"]);
var url = trial.url;
if (trial.force_refresh) {
url = trial.url + "?time=" + (new Date().getTime());
}
display_element.load(trial.url, function() {
var t0 = (new Date()).getTime();
var finish = function() {
if (trial.check_fn && !trial.check_fn(display_element)) return;
if (trial.cont_key) $(document).unbind('keydown', key_listener);
jsPsych.data.write({
rt: (new Date()).getTime() - t0,
url: trial.url
});
display_element.empty();
jsPsych.finishTrial();
};
if (trial.cont_btn) $('#' + trial.cont_btn).click(finish);
if (trial.cont_key) {
var key_listener = function(e) {
if (e.which == trial.cont_key) finish();
};
$(document).keydown(key_listener);
}
});
};
return plugin;
})();
})(jQuery);
|
version https://git-lfs.github.com/spec/v1
oid sha256:591441a267a599c2fdad0dc121564d5bb9d572af5098ee5272d4cdbe45a045c9
size 11246
|
/**
The missing SVG.toDataURL library for your SVG elements
SVG.toDataURL( [type], [keepNonSafe=false], [keepOutsideViewport=false] )
type MIME type of the exported data.
Default: image/svg+xml.
Must support: image/png.
[the rest of the parameters only apply when exportin image/png (or other non-svg)]
keepNonSafe
Export non-safe (image and foreignObject) elements.
This will set the Canvas origin-clean property to false, if this data is transferred to Canvas.
Default: false (to keep origin-clean true).
keepOutsideViewport
Export all drawn content, even if not visible.
Default: false, export only visible viewport, similar to Canvas toDataURL().
IMPLEMENTATION NOTES
keepNonSafe and keepOutsideViewport are not supported at all and will be ignored.
if you don't have canvg, a client-side hack¹ is attempted,
but this will fail on all current browsers (as of 2010-08)
¹ http://svgopen.org/2010/papers/62-From_SVG_to_Canvas_and_Back/#svg_to_canvas
*/
SVGElement.prototype.toDataURL = function(type, keepNonSafe, keepOutsideViewport) {
var _svg = this;
function debug(s) {
console.log("SVG.toDataURL: " + s);
}
function exportSVG() {
var svg_xml = XMLSerialize(_svg);
var svg_dataurl = base64dataURLencode(svg_xml);
return svg_dataurl;
}
function XMLSerialize(svg) {
// quick-n-serialize an SVG dom, needed for IE9 where there's no XMLSerializer nor SVG.xml
// s: SVG dom, which is the <svg> elemennt
function XMLSerializerForIE(s) {
var out = "";
out += "<" + s.nodeName;
for (var n = 0; n < s.attributes.length; n++) {
out += " " + s.attributes[n].name + "=" + "'" + s.attributes[n].value + "'";
}
if (s.hasChildNodes()) {
out += ">\n";
for (var n = 0; n < s.childNodes.length; n++) {
out += XMLSerializerForIE(s.childNodes[n]);
}
out += "</" + s.nodeName + ">" + "\n";
} else out += " />\n";
return out;
}
if (window.XMLSerializer) {
debug("using standard XMLSerializer.serializeToString")
return (new XMLSerializer()).serializeToString(svg);
} else {
debug("using custom XMLSerializerForIE")
return XMLSerializerForIE(svg);
}
}
var Base64 = {
// private property
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
function base64dataURLencode(s) {
var b64 = "data:image/svg+xml;base64,";
if (window.btoa) {
debug("using btoa for base64 encoding");
b64 += btoa(s);
} else {
debug("using custom base64 encoding");
b64 += Base64.encode(s);
}
return b64;
}
// WON'T WORK; canvas' origin-clean is dirty
function exportPNG() {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
var img = new Image();
var svg_xml = XMLSerialize(_svg);
img.src = base64dataURLencode(svg_xml);
img.onload = function() {
ctx.drawImage(img, 0, 0);
// SECURITY_ERR WILL HAPPEN NOW
var png_dataurl = canvas.toDataURL();
callback(png_dataurl);
}
img.onerror = function() {
console.log(
"Can't export! Maybe your browser doesn't support " +
"SVG in img element or SVG input for Canvas drawImage?\n" +
"http://en.wikipedia.org/wiki/SVG#Native_support"
);
}
// TODO: will not return anything
}
function exportPNGcanvg() {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
// TODO: canvg issue don't require parentNode
canvas.setAttribute("style", "display: none;");
document.body.appendChild(canvas);
var svg_xml = XMLSerialize(_svg);
canvg(canvas, svg_xml, { ignoreMouse: true, ignoreAnimation: true });
var png_dataurl = canvas.toDataURL();
document.body.removeChild(canvas);
return png_dataurl;
}
// BEGIN MAIN
if (!type) type = "image/svg+xml";
if (keepOutsideViewport) debug("keepOutsideViewport NOT supported and will be ignored!");
if (keepNonSafe) debug("keepNonSafe is NOT supported and will be ignored!");
switch (type) {
case "image/svg+xml":
return exportSVG(this);
break;
case "image/png":
if (window.canvg) {
debug("Using canvg for png exporting")
return exportPNGcanvg(this);
} else {
debug("Sorry! You don't have canvg. Using native hack for png exporting, THIS WILL FAIL!")
return exportPNG(this);
}
break;
default:
debug("Sorry! Exporting as \"" + type + "\" is not supported!")
}
}
|
//
// Copyright (c) 2016 Cisco Systems
// Licensed under the MIT License
//
/*
* a Cisco Spark Bot that listens to specific Webhooks events, leverages node-sparkbot webhook.onEvent() function.
*/
var SparkBot = require("node-sparkbot");
// Leverage a simple webhook framework
var bot = new SparkBot();
bot.onEvent("all", "all", function(trigger) {
//
// YOUR CODE HERE
//
console.log("EVENT: " + trigger.resource + "/" + trigger.event + ", with data id: " + trigger.data.id + ", triggered by person id:" + trigger.actorId);
});
|
/*global define*/
define(['underscore', 'models/graphite-model'], function(_, GraphiteModel) {
'use strict';
// Request the Pool ids for a given cluster FSID.
var GraphitePoolIopsModel = GraphiteModel.extend({
url: function() {
var name = this.clusterName || 'ceph';
return this.graphiteHost + '/metrics/find?query=ceph.cluster.' + name + '.pool.*';
},
keys: function() {
var keys = _.map(this.attributes, function(v, k) {
return k;
});
if (this.filter) {
return this.filter(keys);
}
return keys;
}
});
return GraphitePoolIopsModel;
});
|
(function ($) {
$.extend(true, window, {
Slick: {
CompositeEditor: CompositeEditor
}
});
/***
* A composite SlickGrid editor factory.
* Generates an editor that is composed of multiple editors for given columns.
* Individual editors are provided given containers instead of the original cell.
* Validation will be performed on all editors individually and the results will be aggregated into one
* validation result.
*
*
* The returned editor will have its prototype set to CompositeEditor, so you can use the "instanceof" check.
*
* NOTE: This doesn't work for detached editors since they will be created and positioned relative to the
* active cell and not the provided container.
*
* @namespace Slick
* @class CompositeEditor
* @constructor
* @param columns {Array} Column definitions from which editors will be pulled.
* @param containers {Array} Container HTMLElements in which editors will be placed.
* @param options {Object} Options hash:
* validationFailedMsg - A generic failed validation message set on the aggregated validation resuls.
* hide - A function to be called when the grid asks the editor to hide itself.
* show - A function to be called when the grid asks the editor to show itself.
* position - A function to be called when the grid asks the editor to reposition itself.
* destroy - A function to be called when the editor is destroyed.
*/
function CompositeEditor(columns, containers, options) {
var defaultOptions = {
validationFailedMsg: "Some of the fields have failed validation",
show: null,
hide: null,
position: null,
destroy: null
};
var noop = function () {
};
var firstInvalidEditor;
options = $.extend({}, defaultOptions, options);
function getContainerBox(i) {
var c = containers[i];
var offset = $(c).offset();
var w = $(c).width();
var h = $(c).height();
return {
top: offset.top,
left: offset.left,
bottom: offset.top + h,
right: offset.left + w,
width: w,
height: h,
visible: true
};
}
function editor(args) {
var editors = [];
function init() {
var newArgs = {};
var idx = columns.length;
while (idx--) {
if (columns[idx].editor) {
newArgs = $.extend({}, args);
newArgs.container = containers[idx];
newArgs.column = columns[idx];
newArgs.position = getContainerBox(idx);
newArgs.commitChanges = noop;
newArgs.cancelChanges = noop;
editors[idx] = new (columns[idx].editor)(newArgs);
}
}
}
this.destroy = function () {
var idx = editors.length;
while (idx--) {
editors[idx].destroy();
}
if (options.destroy) options.destroy();
};
this.focus = function () {
// if validation has failed, set the focus to the first invalid editor
(firstInvalidEditor || editors[0]).focus();
};
this.isValueChanged = function () {
var idx = editors.length;
while (idx--) {
if (editors[idx].isValueChanged()) {
return true;
}
}
return false;
};
this.serializeValue = function () {
var serializedValue = [];
var idx = editors.length;
while (idx--) {
serializedValue[idx] = editors[idx].serializeValue();
}
return serializedValue;
};
this.applyValue = function (item, state) {
var idx = editors.length;
while (idx--) {
editors[idx].applyValue(item, state[idx]);
}
};
this.loadValue = function (item) {
var idx = editors.length;
while (idx--) {
editors[idx].loadValue(item);
}
};
this.validate = function () {
var validationResults;
var errors = [];
firstInvalidEditor = null;
var idx = editors.length;
while (idx--) {
validationResults = editors[idx].validate();
if (!validationResults.valid) {
firstInvalidEditor = editors[idx];
errors.push({
index: idx,
editor: editors[idx],
container: containers[idx],
msg: validationResults.msg
});
}
}
if (errors.length) {
return {
valid: false,
msg: options.validationFailedMsg,
errors: errors
};
} else {
return {
valid: true,
msg: ""
};
}
};
function showOrHide(action) {
var idx = editors.length;
while (idx--) {
if (editors[idx][action]) editors[idx][action]();
}
if (options[action]) options[action]();
}
this.hide = function () {
showOrHide('hide');
};
this.show = function () {
showOrHide('show')
};
this.position = function (box) {
if(options.position) options.position(box);
};
init();
}
// so we can do "editor instanceof Slick.CompositeEditor
editor.prototype = this;
return editor;
}
})(jQuery);
|
'use strict';
const common = require('../common');
const assert = require('assert');
const cp = require('child_process');
const fs = require('fs');
const { isMainThread } = require('worker_threads');
if (isMainThread) {
const CODE = 'const { Worker } = require(\'worker_threads\'); ' +
`new Worker('${__filename.replace(/\\/g, '/')}')`;
const FILE_NAME = 'node_trace.1.log';
const tmpdir = require('../common/tmpdir');
tmpdir.refresh();
process.chdir(tmpdir.path);
const proc = cp.spawn(process.execPath,
[ '--trace-event-categories', 'node',
'-e', CODE ]);
proc.once('exit', common.mustCall(() => {
assert(fs.existsSync(FILE_NAME));
fs.readFile(FILE_NAME, common.mustCall((err, data) => {
const traces = JSON.parse(data.toString()).traceEvents;
assert(traces.length > 0);
assert(traces.some((trace) =>
trace.cat === '__metadata' && trace.name === 'thread_name' &&
trace.args.name === 'WorkerThread 1'));
}));
}));
} else {
// Do nothing here.
}
|
import { test } from '../qunit';
import isNumber from '../../lib/utils/is-number.js';
test('isNumber recognizes numbers', function (assert) {
assert.ok(isNumber(1), 'simple integer');
assert.ok(isNumber(0), 'simple number');
assert.ok(isNumber(-0), 'silly number');
assert.ok(isNumber(1010010293029), 'large number');
assert.ok(isNumber(Infinity), 'largest number');
assert.ok(isNumber(-Infinity), 'smallest number');
assert.ok(isNumber(NaN), 'not number');
assert.ok(isNumber(1.10039383), 'decimal numbers');
assert.ok(isNumber(Math.LN2), 'natural log of two');
assert.ok(isNumber(Math.PI), 'delicious number');
assert.ok(isNumber(5e10), 'scientifically notated number');
assert.ok(isNumber(new Number(1)), 'number primitive wrapped in an object');
});
test('isNumber rejects non-numbers', function (assert) {
assert.ok(!isNumber(), 'nothing');
assert.ok(!isNumber(undefined), 'undefined');
assert.ok(!isNumber(null), 'null');
assert.ok(!isNumber([1]), 'array');
assert.ok(!isNumber('[1,2,3]'), 'string');
assert.ok(!isNumber(new Date()), 'date');
assert.ok(!isNumber({ a: 1, b: 2 }), 'object');
});
|
/* http://j2s.sf.net/ */$_L(null,"java.lang.AbstractStringBuilder",["java.io.InvalidObjectException","java.lang.ArrayIndexOutOfBoundsException","$.IndexOutOfBoundsException","$.NegativeArraySizeException","$.NullPointerException","$.StringIndexOutOfBoundsException"],function(){
c$=$_C(function(){
this.value=null;
this.count=0;
this.shared=false;
$_Z(this,arguments);
},java.lang,"AbstractStringBuilder");
$_M(c$,"getValue",
function(){
return this.value;
});
$_M(c$,"shareValue",
function(){
this.shared=true;
return this.value;
});
$_M(c$,"set",
function(val,len){
if(val==null)val=$_A(0,'\0');
if(val.length<len)throw new java.io.InvalidObjectException(("K0199"));
this.shared=false;
this.value=val;
this.count=len;
},"~A,~N");
$_K(c$,
function(){
this.value=$_A(16,'\0');
});
$_K(c$,
function(capacity){
if(capacity<0)throw new NegativeArraySizeException();
this.value=$_A(capacity,'\0');
},"~N");
$_K(c$,
function(string){
this.count=string.length;
this.shared=false;
this.value=$_A(this.count+16,'\0');
string.getChars(0,this.count,this.value,0);
},"~S");
$_M(c$,"enlargeBuffer",
($fz=function(min){
var twice=(this.value.length<<1)+2;
var newData=$_A(min>twice?min:twice,'\0');
System.arraycopy(this.value,0,newData,0,this.count);
this.value=newData;
this.shared=false;
},$fz.isPrivate=true,$fz),"~N");
$_M(c$,"appendNull",
function(){
var newSize=this.count+4;
if(newSize>this.value.length){
this.enlargeBuffer(newSize);
}else if(this.shared){
this.value=this.value.clone();
this.shared=false;
}this.value[this.count++]='n';
this.value[this.count++]='u';
this.value[this.count++]='l';
this.value[this.count++]='l';
});
$_M(c$,"append0",
function(chars){
var newSize=this.count+chars.length;
if(newSize>this.value.length){
this.enlargeBuffer(newSize);
}else if(this.shared){
this.value=this.value.clone();
this.shared=false;
}System.arraycopy(chars,0,this.value,this.count,chars.length);
this.count=newSize;
},"~A");
$_M(c$,"append0",
function(chars,start,length){
if(chars==null){
throw new NullPointerException();
}if(start>=0&&0<=length&&length<=chars.length-start){
var newSize=this.count+length;
if(newSize>this.value.length){
this.enlargeBuffer(newSize);
}else if(this.shared){
this.value=this.value.clone();
this.shared=false;
}System.arraycopy(chars,start,this.value,this.count,length);
this.count=newSize;
}else{
throw new ArrayIndexOutOfBoundsException();
}},"~A,~N,~N");
$_M(c$,"append0",
function(ch){
if(this.count==this.value.length){
this.enlargeBuffer(this.count+1);
}if(this.shared){
this.value=this.value.clone();
this.shared=false;
}this.value[this.count++]=ch;
},"~N");
$_M(c$,"append0",
function(string){
if(string==null){
this.appendNull();
return;
}var adding=string.length;
var newSize=this.count+adding;
if(newSize>this.value.length){
this.enlargeBuffer(newSize);
}else if(this.shared){
this.value=this.value.clone();
this.shared=false;
}string.getChars(0,adding,this.value,this.count);
this.count=newSize;
},"~S");
$_M(c$,"append0",
function(s,start,end){
if(s==null)s="null";
if(start<0||end<0||start>end||end>s.length())throw new IndexOutOfBoundsException();
this.append0(s.subSequence(start,end).toString());
},"CharSequence,~N,~N");
$_M(c$,"capacity",
function(){
return this.value.length;
});
$_M(c$,"charAt",
function(index){
if(index<0||index>=this.count)throw new StringIndexOutOfBoundsException(index);
return this.value[index];
},"~N");
$_M(c$,"delete0",
function(start,end){
if(start>=0){
if(end>this.count){
end=this.count;
}if(end==start){
return;
}if(end>start){
var length=this.count-end;
if(length>0){
if(!this.shared){
System.arraycopy(this.value,end,this.value,start,length);
}else{
var newData=$_A(this.value.length,'\0');
System.arraycopy(this.value,0,newData,0,start);
System.arraycopy(this.value,end,newData,start,length);
this.value=newData;
this.shared=false;
}}this.count-=end-start;
return;
}}throw new StringIndexOutOfBoundsException();
},"~N,~N");
$_M(c$,"deleteCharAt0",
function(location){
if(0>location||location>=this.count)throw new StringIndexOutOfBoundsException(location);
var length=this.count-location-1;
if(length>0){
if(!this.shared){
System.arraycopy(this.value,location+1,this.value,location,length);
}else{
var newData=$_A(this.value.length,'\0');
System.arraycopy(this.value,0,newData,0,location);
System.arraycopy(this.value,location+1,newData,location,length);
this.value=newData;
this.shared=false;
}}this.count--;
},"~N");
$_M(c$,"ensureCapacity",
function(min){
if(min>this.value.length){
this.enlargeBuffer(min);
}},"~N");
$_M(c$,"getChars",
function(start,end,dest,destStart){
if(start>this.count||end>this.count||start>end){
throw new StringIndexOutOfBoundsException();
}System.arraycopy(this.value,start,dest,destStart,end-start);
},"~N,~N,~A,~N");
$_M(c$,"insert0",
function(index,chars){
if(0>index||index>this.count){
throw new StringIndexOutOfBoundsException(index);
}if(chars.length!=0){
this.move(chars.length,index);
System.arraycopy(chars,0,this.value,index,chars.length);
this.count+=chars.length;
}},"~N,~A");
$_M(c$,"insert0",
function(index,chars,start,length){
if(0<=index&&index<=this.count){
if(start>=0&&0<=length&&length<=chars.length-start){
if(length!=0){
this.move(length,index);
System.arraycopy(chars,start,this.value,index,length);
this.count+=length;
}return;
}throw new StringIndexOutOfBoundsException("offset "+start+", len "+length+", array.length "+chars.length);
}throw new StringIndexOutOfBoundsException(index);
},"~N,~A,~N,~N");
$_M(c$,"insert0",
function(index,ch){
if(0>index||index>this.count){
throw new ArrayIndexOutOfBoundsException(index);
}this.move(1,index);
this.value[index]=ch;
this.count++;
},"~N,~N");
$_M(c$,"insert0",
function(index,string){
if(0<=index&&index<=this.count){
if(string==null)string="null";
var min=string.length;
if(min!=0){
this.move(min,index);
string.getChars(0,min,this.value,index);
this.count+=min;
}}else{
throw new StringIndexOutOfBoundsException(index);
}},"~N,~S");
$_M(c$,"insert0",
function(index,s,start,end){
if(s==null)s="null";
if(index<0||index>this.count||start<0||end<0||start>end||end>s.length())throw new IndexOutOfBoundsException();
this.insert0(index,s.subSequence(start,end).toString());
},"~N,CharSequence,~N,~N");
$_M(c$,"length",
function(){
return this.count;
});
$_M(c$,"move",
($fz=function(size,index){
var newSize;
if(this.value.length-this.count>=size){
if(!this.shared){
System.arraycopy(this.value,index,this.value,index+size,this.count-index);
return;
}newSize=this.value.length;
}else{
var a=this.count+size;
var b=(this.value.length<<1)+2;
newSize=a>b?a:b;
}var newData=$_A(newSize,'\0');
System.arraycopy(this.value,0,newData,0,index);
System.arraycopy(this.value,index,newData,index+size,this.count-index);
this.value=newData;
this.shared=false;
},$fz.isPrivate=true,$fz),"~N,~N");
$_M(c$,"replace0",
function(start,end,string){
if(start>=0){
if(end>this.count)end=this.count;
if(end>start){
var stringLength=string.length;
var diff=end-start-stringLength;
if(diff>0){
if(!this.shared){
System.arraycopy(this.value,end,this.value,start+stringLength,this.count-end);
}else{
var newData=$_A(this.value.length,'\0');
System.arraycopy(this.value,0,newData,0,start);
System.arraycopy(this.value,end,newData,start+stringLength,this.count-end);
this.value=newData;
this.shared=false;
}}else if(diff<0){
this.move(-diff,end);
}else if(this.shared){
this.value=this.value.clone();
this.shared=false;
}string.getChars(0,stringLength,this.value,start);
this.count-=diff;
return;
}if(start==end){
if(string==null)throw new NullPointerException();
this.insert0(start,string);
return;
}}throw new StringIndexOutOfBoundsException();
},"~N,~N,~S");
$_M(c$,"reverse0",
function(){
if(this.count<2){
return;
}if(!this.shared){
for(var i=0,end=this.count,mid=Math.floor(this.count/2);i<mid;i++){
var temp=this.value[--end];
this.value[end]=this.value[i];
this.value[i]=temp;
}
}else{
var newData=$_A(this.value.length,'\0');
for(var i=0,end=this.count;i<this.count;i++){
newData[--end]=this.value[i];
}
this.value=newData;
this.shared=false;
}});
$_M(c$,"setCharAt",
function(index,ch){
if(0>index||index>=this.count){
throw new StringIndexOutOfBoundsException(index);
}if(this.shared){
this.value=this.value.clone();
this.shared=false;
}this.value[index]=ch;
},"~N,~N");
$_M(c$,"setLength",
function(length){
if(length<0)throw new StringIndexOutOfBoundsException(length);
if(this.count<length){
if(length>this.value.length){
this.enlargeBuffer(length);
}else{
if(this.shared){
var newData=$_A(this.value.length,'\0');
System.arraycopy(this.value,0,newData,0,this.count);
this.value=newData;
this.shared=false;
}else{
for(var i=this.count;i<length;i++){
this.value[i]=String.fromCharCode(0);
}
}}}this.count=length;
},"~N");
$_M(c$,"substring",
function(start){
if(0<=start&&start<=this.count){
if(start==this.count)return"";
this.shared=true;
return String.instantialize(start,this.count-start,this.value);
}throw new StringIndexOutOfBoundsException(start);
},"~N");
$_M(c$,"substring",
function(start,end){
if(0<=start&&start<=end&&end<=this.count){
if(start==end)return"";
this.shared=true;
return String.instantialize(this.value,start,end-start);
}throw new StringIndexOutOfBoundsException();
},"~N,~N");
$_V(c$,"toString",
function(){
if(this.count==0)return"";
if(this.count>=256&&this.count<=(this.value.length>>1))return String.instantialize(this.value,0,this.count);
this.shared=true;
return String.instantialize(0,this.count,this.value);
});
$_M(c$,"subSequence",
function(start,end){
return this.substring(start,end);
},"~N,~N");
$_M(c$,"indexOf",
function(string){
return this.indexOf(string,0);
},"~S");
$_M(c$,"indexOf",
function(subString,start){
if(start<0)start=0;
var subCount=subString.length;
if(subCount>0){
if(subCount+start>this.count)return-1;
var firstChar=subString.charAt(0);
while(true){
var i=start;
var found=false;
for(;i<this.count;i++)if((this.value[i]).charCodeAt(0)==(firstChar).charCodeAt(0)){
found=true;
break;
}
if(!found||subCount+i>this.count)return-1;
var o1=i;
var o2=0;
while(++o2<subCount&&(this.value[++o1]).charCodeAt(0)==(subString.charAt(o2)).charCodeAt(0)){
}
if(o2==subCount)return i;
start=i+1;
}
}return(start<this.count||start==0)?start:this.count;
},"~S,~N");
$_M(c$,"lastIndexOf",
function(string){
return this.lastIndexOf(string,this.count);
},"~S");
$_M(c$,"lastIndexOf",
function(subString,start){
var subCount=subString.length;
if(subCount<=this.count&&start>=0){
if(subCount>0){
if(start>this.count-subCount)start=this.count-subCount;
var firstChar=subString.charAt(0);
while(true){
var i=start;
var found=false;
for(;i>=0;--i)if((this.value[i]).charCodeAt(0)==(firstChar).charCodeAt(0)){
found=true;
break;
}
if(!found)return-1;
var o1=i;
var o2=0;
while(++o2<subCount&&(this.value[++o1]).charCodeAt(0)==(subString.charAt(o2)).charCodeAt(0)){
}
if(o2==subCount)return i;
start=i-1;
}
}return start<this.count?start:this.count;
}return-1;
},"~S,~N");
$_M(c$,"trimToSize",
function(){
if(this.count<this.value.length){
var newValue=$_A(this.count,'\0');
System.arraycopy(this.value,0,newValue,0,this.count);
this.value=newValue;
this.shared=false;
}});
$_S(c$,
"INITIAL_CAPACITY",16);
});
$_L(["java.lang.AbstractStringBuilder","$.Appendable"],"java.lang.StringBuilder",["java.lang.Double","$.Float","$.Long"],function(){
c$=$_T(java.lang,"StringBuilder",AbstractStringBuilder,[Appendable,CharSequence,java.io.Serializable]);
$_K(c$,
function(seq){
$_R(this,StringBuilder,[seq.toString()]);
},"CharSequence");
$_M(c$,"append",
function(b){
this.append0(b?"true":"false");
return this;
},"~B");
$_M(c$,"append",
function(c){
this.append0(c);
return this;
},"~N");
$_M(c$,"append",
function(i){
this.append0(Integer.toString(i));
return this;
},"~N");
$_M(c$,"append",
function(lng){
this.append0(Long.toString(lng));
return this;
},"~N");
$_M(c$,"append",
function(f){
this.append0(Float.toString(f));
return this;
},"~N");
$_M(c$,"append",
function(d){
this.append0(Double.toString(d));
return this;
},"~N");
$_M(c$,"append",
function(obj){
if(obj==null){
this.appendNull();
}else{
this.append0(obj.toString());
}return this;
},"~O");
$_M(c$,"append",
function(str){
this.append0(str);
return this;
},"~S");
$_M(c$,"append",
function(sb){
if(sb==null){
this.appendNull();
}else{
this.append0(sb.getValue(),0,sb.length());
}return this;
},"StringBuffer");
$_M(c$,"append",
function(ch){
this.append0(ch);
return this;
},"~A");
$_M(c$,"append",
function(str,offset,len){
this.append0(str,offset,len);
return this;
},"~A,~N,~N");
$_M(c$,"append",
function(csq){
if(csq==null){
this.appendNull();
}else{
this.append0(csq.toString());
}return this;
},"CharSequence");
$_M(c$,"append",
function(csq,start,end){
this.append0(csq,start,end);
return this;
},"CharSequence,~N,~N");
$_M(c$,"$delete",
function(start,end){
this.delete0(start,end);
return this;
},"~N,~N");
$_M(c$,"deleteCharAt",
function(index){
this.deleteCharAt0(index);
return this;
},"~N");
$_M(c$,"insert",
function(offset,b){
this.insert0(offset,b?"true":"false");
return this;
},"~N,~B");
$_M(c$,"insert",
function(offset,c){
this.insert0(offset,c);
return this;
},"~N,~N");
$_M(c$,"insert",
function(offset,i){
this.insert0(offset,Integer.toString(i));
return this;
},"~N,~N");
$_M(c$,"insert",
function(offset,l){
this.insert0(offset,Long.toString(l));
return this;
},"~N,~N");
$_M(c$,"insert",
function(offset,f){
this.insert0(offset,Float.toString(f));
return this;
},"~N,~N");
$_M(c$,"insert",
function(offset,d){
this.insert0(offset,Double.toString(d));
return this;
},"~N,~N");
$_M(c$,"insert",
function(offset,obj){
this.insert0(offset,obj==null?"null":obj.toString());
return this;
},"~N,~O");
$_M(c$,"insert",
function(offset,str){
this.insert0(offset,str);
return this;
},"~N,~S");
$_M(c$,"insert",
function(offset,ch){
this.insert0(offset,ch);
return this;
},"~N,~A");
$_M(c$,"insert",
function(offset,str,strOffset,strLen){
this.insert0(offset,str,strOffset,strLen);
return this;
},"~N,~A,~N,~N");
$_M(c$,"insert",
function(offset,s){
this.insert0(offset,s==null?"null":s.toString());
return this;
},"~N,CharSequence");
$_M(c$,"insert",
function(offset,s,start,end){
this.insert0(offset,s,start,end);
return this;
},"~N,CharSequence,~N,~N");
$_M(c$,"replace",
function(start,end,str){
this.replace0(start,end,str);
return this;
},"~N,~N,~S");
$_M(c$,"reverse",
function(){
this.reverse0();
return this;
});
});
|
$(function() {
// Toggle forms
$('.show-form').on('click', function(e) {
e.preventDefault();
$('.well-section[id$=form]').each(function() {
$(this).hide();
});
$($(this).data('target')).show();
});
});
|
module.exports = {
rules: {
'no-unused-vars': 'off'
}
}
|
const common = require('../../../../lib/common');
const uuid = require('uuid');
module.exports = {
config: {
transaction: true
},
async up(options) {
const conn = options.connection || options.transacting;
const membersWithoutUUID = await conn.select('id').from('members').whereNull('uuid');
common.logging.info(`Adding uuid field value to ${membersWithoutUUID.length} members.`);
for (const member of membersWithoutUUID) {
await conn('members').update('uuid', uuid.v4()).where('id', member.id);
}
},
async down() {
// noop
}
};
|
function SwapTexture(config, count) {
count = count || 1;
config = config || {};
var me = this;
gl.supports_OES_texture_float = !!gl.getExtension('OES_texture_float');
config = Utils.merge({
width: 512,
height: 512,
bindToTexture: {
pixelStore: [],
parameters: [
{
name: gl.TEXTURE_MAG_FILTER,
value: gl.supports_OES_texture_float ? gl.LINEAR : gl.NEAREST
},
{
name: gl.TEXTURE_MIN_FILTER,
value: gl.supports_OES_texture_float ? gl.LINEAR : gl.NEAREST,
generateMipmap: true
},
{
name: gl.TEXTURE_WRAP_S,
value: gl.CLAMP_TO_EDGE
},
{
name: gl.TEXTURE_WRAP_T,
value: gl.CLAMP_TO_EDGE
}
],
data: {
type: gl.supports_OES_texture_float ? gl.FLOAT : gl.UNSIGNED_BYTE
}
},
bindToRenderBuffer: false
}, config);
if (config.bindToTexture.data) {
var data = config.bindToTexture.data;
data.height = data.height || config.height;
data.width = data.width || config.width;
}
me.width = config.width;
me.height = config.height;
me.from = [];
me.to = [];
for (var i = 0; i < count; i++) {
me.from[i] = 'fb-' + Utils.uid();
me.to[i] = 'fb-' + Utils.uid();
app.setFrameBuffer(me.from[i], config);
app.setFrameBuffer(me.to[i], config);
}
}
SwapTexture.prototype = {
process: function(config, idx, noSwap) {
var me = this;
var fromTexture = [], i = 0, ln = this.from.length;
for (i = 0; i < ln; i++) {
fromTexture.push(this.from[i] + '-texture');
}
PhiloGL.Media.Image.postProcess(
Utils.merge({
width: me.width,
height: me.height,
fromTexture: fromTexture,
toFrameBuffer: this.to[idx || 0]
}, config)
);
if (!noSwap) {
me.swap();
}
},
swap: function() {
var me = this,
temp = me.from;
me.from = me.to;
me.to = temp;
}
};
|
'use strict';
exports['default'] = {
isMac: function isMac() {
return typeof window !== 'undefined' && window.navigator && /Mac/.test(window.navigator.platform);
},
isWin: function isWin() {
return typeof window !== 'undefined' && window.navigator && /Win/.test(window.navigator.platform);
}
};
|
/* global HTMLCollection: true */
module.exports = function(els, fn, context) {
if (
els instanceof HTMLCollection ||
els instanceof NodeList ||
els instanceof Array
) {
return Array.prototype.forEach.call(els, fn, context);
}
// assume simple DOM element
return fn.call(context, els);
};
|
module.exports = require('../bar/abc').default + '.2';
|
/**
@Fileoverview A facet for a customized Exhibit month
@fileoverview
This is where the monthly layout is defined. The layout is designed to
resemble the equivalent Google Calendar view.
@author Quanquan Liu <quanquan@mit.edu>
@author Mason Tang
*/
Exhibit.MonthFacet = function(containerElmt, uiContext, configElmt, timegridFacet) {
var self = this;
this._dom = null;
this._containerElmts = containerElmt;
this._uiContext = uiContext;
this._configElmt = configElmt;
this._timegridFacet = timegridFacet;
// Specifications for a month layout
this._xSize = 7;
this._ySize = 0; // This is re-calculated later based on n
this._n = 1;
this._color = "#fefebf"; // color for selected boxes
// Can flip through different months
this._iterable = true;
// Can take recurring events using these symbols
this._dayMap = { 'M' : 1, 'T' : 2, 'W' : 3, 'R' : 4, 'F' : 5, 'S': 6, 'Sn': 0, 'm': 1, 't': 2, 'w': 3, 'r': 4,
'f': 5, 's': 6, 'sn': 0 };
this._valueSet = new Exhibit.Set();
// We put title here because it depends on this.n
this._title = this._n + "-Month";
var self = this;
this._defaultFacet = this;
this._scrollwidth = 0;
this._xLabelHeight = 24;
this._yLabelWidth = 0;
this._selectedEvents = [];
this._selectedIndividualEvents = new Exhibit.Set();
// Configure our mappers to map the time of occurrence to the grid
this._xMapper = function(obj) {
return self.timezoneMapper(obj.time).getDay();
};
this._yMapper = function(obj) {
var time = self.timezoneMapper(obj.time);
var start = self.timezoneMapper(self._startTime);
// Simply divide by the number of milliseconds in a week
return Math.floor((time - start) / (1000 * 60 * 60 * 24 * 7.0));
};
};
Exhibit.MonthFacet.prototype.initializeUI = function(dom, settings, containerElmt, uiContext) {
// Using layouts and other concurrent week/month abilities
var $=Exhibit.jQuery;
this._layoutClass = this._layoutClass || new Exhibit.TimegridFacet.Layout(containerElmt, uiContext);
this._eventSource = this._eventSource || new Exhibit.TimegridFacet.EventSource();
Exhibit.jQuery.extend(this, this._layoutClass, this._eventSource);
this._settings = settings;
this._uiContext = uiContext;
this._database = this._uiContext.getDatabase();
var returnNums = function(v) {
var numberPattern = /\d+/g;
return v.match(numberPattern)[0];
}
this._dom = dom;
if ($(this._containerElmt).css("height")) {
this._gridHeight = parseInt(returnNums($(this._containerElmt).css("height")));
}
if ($(this._containerElmt).css("width")) {
this._gridWidth = parseInt(returnNums($(this._containerElmt).css("width")));
}
// Adjust gridHeight and gridWidth based on passed in parameters
this._gridHeight = this._settings.gridHeight;
this._gridWidth = this._settings.gridWidth;
this._title = this._settings.title || this._title;
if (this._settings.xCellWidth) {
this._xCellWidth = this._settings.xCellWidth;
}
if (this._settings.yCellWidth) {
this._yCellWidth = this._settings.yCellWidth;
}
this.initializeGrid();
this.computeCellSizes();
};
Exhibit.MonthFacet.prototype.initializeGrid = function() {
// Start the calendar at the specified start/end date or current date if not specified
if (this._settings.displayEndDate) {
this._endTime = this._endTime || Date.parseString(this._settings.displayEndDate);
this._endTime.setHours(0);
this._startTime = this._computeStartTime(this._endTime);
}
if (this._settings.displayStartDate) {
this._startTime = this._startTime || Date.parseString(this._settings.displayStartDate);
this._startTime.setHours(0);
this._endTime = this._computeEndTime(this._startTime);
}
this._startTime = this._startTime || this._computeStartTime(null);
this._startTime.setHours(0);
this._endTime = this._endTime || this._computeEndTime(this._startTime);
// date to start displaying feed data
this._dataStartTime = this._dataStartTime || this._startTime || this._computeStartTime(null);
if (this._curMonth != 0) {
this._curMonth = this._curMonth || this._startTime.getMonth();
}
this._updateGrid();
};
Exhibit.MonthFacet.prototype._updateGrid = function() {
this._computeDimensions();
var now = new Date();
if (now.isBetween(this._startTime, this._endTime)) { this._now = now; }
if (this._startTime) {
var iterator = this.getEventIterator(this._startTime, this._endTime);
while (iterator.hasNext()) {
var endpoints = this._getEndpoints(iterator.next());
this._addAllEndpoints(endpoints);
}
}
};
Exhibit.MonthFacet.prototype._addAllEndpoints = function(endpoints) {
// Add all events to the calendar
for (i in endpoints) {
var x = this._xMapper(endpoints[i]);
var y = this._yMapper(endpoints[i]);
this._eventGrid[x][y].push(endpoints[i]);
}
};
Exhibit.MonthFacet.prototype._computeDimensions = function() {
this._startTime = this._computeStartTime(this._startTime);
// Use a method to compute cell and y-labels (non-trivial). This method
// will also compute ySize based on n, an unfortunate grouping.
this._computeYSize(this._startTime);
this._computeLabels(this._startTime);
this._endTime = this._computeEndTime(this._startTime);
this._eventGrid = new Array(this._xSize);
for (var i = 0; i < this._xSize; i++) {
this._eventGrid[i] = new Array(this._ySize);
for (var j = 0; j < this._ySize; j++) {
// Create eventGrid for containing all events
this._eventGrid[i][j] = [];
}
}
// Compute the cell sizes for the grid
this.computeCellSizes();
};
Exhibit.MonthFacet.prototype.renderEvents = function(doc) {
var eventContainer = doc.createElement("div");
var labelContainer = doc.createElement("div");
var $=Exhibit.jQuery;
// Events
$(eventContainer).addClass("timegrid-events");
// Dates in the month
$(labelContainer).addClass("timegrid-month-labels");
var i = 0;
var dates = this._cellLabels;
for (y = 0; y < this._ySize; y++) {
for (x = 0; x < this._xSize; x++) {
var endpoints = this._eventGrid[x][y];
var events = $.map(endpoints, function(e) {
return e.type == "start" ? e.event : null;
});
var n = dates[i];
var m = this._months[i];
eventContainer.appendChild(this._renderEventList(events, x, y, n, m));
i++;
}
}
$(labelContainer).append($(this._renderMonthLabels()));
return $([eventContainer, labelContainer]);
};
// Render the list of events from the feed per day
Exhibit.MonthFacet.prototype._renderEventList = function(evts, x, y, n, m) {
var $=Exhibit.jQuery;
var jediv = $("<div></div>").addClass("timegrid-month-cell");
$(jediv).attr("classid", y*7 + x);
var map = Array.prototype.map;
var eList = $("<div></div>").addClass("timegrid-event-list");
var labels = [];
for (e in evts) {
labels.push([evts[e].getText(), 1]);
}
if (labels.length > 0) {
if (!this._timeMap[y*7 + x]) {
this._timeMap[y*7 + x] = labels;
} else {
for (i in this._timeMap[y*7 + x]) {
if (this._timeMap[y*7 + x][i][0] != labels[0][0]) {
this._timeMap[y*7 + x] = this._timeMap[y*7 + x].concat(labels);
}
}
}
}
var self = this;
var onSelect = function(evt) {
var label = evt.target.innerHTML.split("<div>").join("").split("</div>").join("");
if (!self._selectedIndividualEvents.contains(label)) {
self._selectedIndividualEvents.add(label);
self._valueSet.add(label);
$($(evt.target).parent()[0]).css("background-color", "#F5FFFA");
} else if (self._valueSet.contains(label) && self._selectedIndividualEvents.contains(label)) {
self._valueSet.remove(label);
self._selectedIndividualEvents.remove(label);
}
self._filter();
self._notifyCollection();
};
var countOccurrences = function(item, arr) {
var num = 0;
for (i in arr) {
if (arr[i] == item) {
num++;
}
}
return num;
};
var removeOccurrence = function(item, arr) {
for (i in arr) {
if (arr[i] == item) {
delete arr[i];
return;
}
}
}
if (this._now) {
var nowX = this._xMapper({ time: this._now });
var nowY = this._yMapper({ time: this._now });
if (x == nowX && y == nowY) {
jediv.addClass("timegrid-month-cell-now");
}
}
// Differentiate between current/past/future months
jediv.addClass("timegrid-month-cell-" + (m === this._curMonth ? "current" : "not-current"));
for (var i = 0; i < evts.length; i++) {
var eventLabel = $('<div>' + evts[i].getText() + '</div>').css("margin", "10px");
Exhibit.jQuery(eventLabel).bind("click", onSelect);
if (this._selectedIndividualEvents.contains(evts[i].getText())) {
eventLabel.css("background-color", "#C6E2FF");
}
eList.append(eventLabel);
}
jediv.append(eList);
// Label for the specific date
jediv.append('<span class="timegrid-month-date-label">' + n + '</span>');
jediv.css("height", this._yCellWidth).css("width", this._xCellWidth + "px");
// Automatically size the cell or determine cell size manually from settings
jediv.css("top", this._yCellWidth * y);
jediv.css("left", this._xCellWidth * x + 'px');
return jediv.get()[0]; // Return the actual DOM element
};
Exhibit.MonthFacet.prototype._renderMonthLabels = function() {
var $=Exhibit.jQuery;
var self = this;
// Place the month label on the calendar and centered
var monthString = this._monthStarts[0].date.getMonthName();
var mDiv = $('<div><span>' + monthString + '</span></div>');
mDiv.addClass('timegrid-month-label');
mDiv.css('margin-top', this._yCellWidth * this._monthStarts[0].i + "px");
var height = this._monthStarts[0].height * this._yCellWidth;
var fontSize = this._gridWidth / 1000;
mDiv.css("font-size", fontSize + "em");
mDiv.height(height + "px");
mDiv.children().css('line-height', height + "px");
return mDiv.get(0);
};
// Get labels for days
Exhibit.MonthFacet.prototype.getXLabels = function() {
return Date.l10n.dayNames;
};
// Dummy method for getting y labels--month calendar doesn't have labels
Exhibit.MonthFacet.prototype.getYLabels = function() {
return [];
};
// Reset the width and height of cells
Exhibit.MonthFacet.prototype._resetCells = function() {
this._yCellWidth = null;
this._xCellWidth = null;
}
// Going backwards on the calendar
Exhibit.MonthFacet.prototype._goPrevious = function() {
this._dataStartTime.add('M', 0 - this._n);
this._startTime = new Date(this._dataStartTime);
this._curMonth = this._startTime.getMonth();
this._resetCells();
this._updateGrid();
};
// Going forwards on the calendar
Exhibit.MonthFacet.prototype._goNext = function() {
this._dataStartTime.add('M', this._n);
this._startTime = new Date(this._dataStartTime);
this._curMonth = this._startTime.getMonth();
this._resetCells();
this._updateGrid();
};
// Get the times for the iterator
Exhibit.MonthFacet.prototype._getCurrent = function() {
var start = this._startTime;
var end = new Date(this._startTime).add('d', 34);
return Exhibit.MonthFacet.l10n.makeRange(start, end);
};
// Compute the starting time of the month facet
Exhibit.MonthFacet.prototype._computeStartTime = function(date) {
if (date) {
var startTime = new Date(date);
} else {
var startTime = new Date(new Date().clearTime().setDay(0) ||
new Date());
}
// Roll back to the first day on the grid
while (this._xMapper({ time: startTime }) > 0) {
startTime.setHours(-24);
}
return startTime;
};
// Computes the ending time of the month facet
Exhibit.MonthFacet.prototype._computeEndTime = function(date) {
if (date) {
var endTime = new Date(date);
endTime.add('d', this._ySize * 7);
return endTime;
}
return false;
};
// Computes the number of rows in the calendar
Exhibit.MonthFacet.prototype._computeYSize = function(date) {
var gridStart = { time: new Date(date) };
var month = this._dataStartTime.getMonth();
this._ySize = 0;
this._monthStarts = [{ i: this._ySize, date: new Date(this._dataStartTime) }];
while (this._xMapper(gridStart) > 0 && this._yMapper(gridStart) >= 0) {
gridStart.time.setHours(-24);
}
gridStart.time.add('d', 7);
for (; this._monthStarts.length <= this._n; gridStart.time.add('d', 7)) {
if (gridStart.time.getMonth() != month) {
month = gridStart.time.getMonth();
var year = gridStart.time.getFullYear();
this._monthStarts.push({i: this._ySize, date: new Date(gridStart.time)});
var old = this._monthStarts[this._monthStarts.length - 2];
old.height = this._ySize - old.i + 1;
}
this._ySize++;
}
this._monthStarts.pop();
};
// Date labels
Exhibit.MonthFacet.prototype._computeLabels = function(date) {
var gridStart = { time: new Date(date) };
this._cellLabels = [];
this._months = [];
// Iterate through and collect the tasty data
while (this._xMapper(gridStart) < this._xSize &&
this._yMapper(gridStart) < this._ySize) {
var d = gridStart.time;
this._cellLabels.push(d.getDate());
this._months.push(d.getMonth());
d.setHours(24);
}
};
Exhibit.MonthFacet.prototype._dispose = function() {
this._cache.dispose();
this._cache = null;
this._dom = null;
this._valueSet = new Exhibit.Set();
};
/*
Clears all restrictions set on the item
*/
Exhibit.MonthFacet.prototype.clearAllRestrictions = function() {
Exhibit.jQuery(this.getContainer()).trigger("onBeforeFacetReset.exhibit");
this._valueSet = new Exhibit.Set();
this._notifyCollection();
};
/*
Check if there are restrictions on items
*/
Exhibit.MonthFacet.prototype.hasRestrictions = function () {
var keys = this._valueSet.toArray();
for (var i = 0; i < keys.length; i++) {
if (this._timeMap[keys[i]]) {
return true;
}
}
return this._valueSet.size() > 0;
};
Exhibit.MonthFacet.prototype.applyRestrictions = function(restrictions) {
this._valueSet = new Exhibit.Set();
for (var i = 0; i < restrictions.selections.length; i++) {
this._valueSet.add(restrictions.selections[i]);
}
this._notifyCollection();
};
/*
* Renders the go back and go forward buttons
*/
Exhibit.MonthFacet.prototype.renderIterator = function() {
var $=Exhibit.jQuery;
this._div = $('<div></div>').addClass('timegrid-iterator');
$(this._div).css("margin-top", this._tabHeight || 18 + "px");
var self = this;
var makePrevCallback = function() {
self._goPrevious();
self._notifyCollection();
};
var makeNextCallback = function() {
self._goNext();
self._notifyCollection();
};
$prevLink = $('<span />', {alt: "Previous", "class": "timegrid-previous"});
$nextLink = $('<span />', {alt: "Next", "class": "timegrid-next"});
$nextLink.bind("click", function (){
makeNextCallback();
});
$prevLink.bind("click", function (){
makePrevCallback();
});
this._div.append($prevLink);
this._div.append($nextLink);
this._div.append($('<span></span>', { text: this._getCurrent() }));
if ($(this._containerElmt).find(".timegrid-iterator").length > 0) {
$($(this._containerElmt).find(".timegrid-iterator")[0]).remove();
}
$(this._containerElmt).append(this._div);
};
/*
@param {Exhibit.Set} items
@returns {Exhibit.Set}
*/
Exhibit.MonthFacet.prototype.restrict = function(items) {
var i, key, itemsArr, keys, vals, j, val;
if (this._valueSet.size() === 0) {
return items;
}
keys = Object.keys(this._valueSet);
for (i = 0; i < keys.length; i++) {
vals = this._timeMap[keys[i]];
if (vals) {
for (j = 0; j < vals.length; j++) {
val = vals[j];
item = vals[0];
if (items.contains(item)) {
this._valueSet.add(item);
}
}
}
}
// add timeMap later for restrictions
return this._valueSet;
};
Exhibit.MonthFacet.prototype._notifyCollection = function () {
this._uiContext.getCollection().onFacetUpdated(this);
};
Exhibit.MonthFacet.prototype.update = function (items) {
// method gone, replace: this._computeFacet
this._constructBody(this._computeFacet(items));
};
/*
Responsible for parsing through database items and filtering them
for insertion into calendar
@param items collection items
*/
Exhibit.MonthFacet.prototype._computeFacet = function(items) {
var entries, i, item, label, event, allItemsList, days, j, label,
day, obj, accessors, database, setIf;
entries = [];
this._timeMap = {};
accessors = this._timegridFacet._accessors;
database = this._database;
setIf = function(accessor, field) {
if ((typeof(accessor) !== "undefined") && accessor !== null) {
(accessor)(item, database, function (v) {
if (v!=null) {
event[field]=v;
}
})
}
};
this._possibleDays = {};
allItemsList = items.toArray();
for (i in allItemsList) {
item = allItemsList[i];
if (typeof(accessors.getStartTime) !== "undefined") {
accessors.getStartTime(item, database, function(v) {
if (v !== null) {
obj=v;
}
});
}
if (!this._timeMap[item] && obj) {
event = {};
setIf(accessors.getLabel, "label");
setIf(accessors.getRecurring, "days");
setIf(accessors.getStartDate, "startDate");
setIf(accessors.getEndDate, "endDate");
setIf(accessors.getStartTime, "startTime");
setIf(accessors.getEndTime, "endTime");
setIf(accessors.getColor, "color");
setIf(accessors.getDisplay, "display");
event.startDate = event.startDate || new Date().toDateString();
if (! event.endDate) {
event.endDate = new Date();
event.endDate.setFullYear(new Date().getFullYear+1);
event.endDate=event.endDate.toString();
}
event.color = event.color || "#104E8B";
if (event.startDate.indexOf("T") > -1) {
startTime = event.startDate.split("T");
event.startDate = startTime[0];
startTime = startTime[1].split(":");
} else {
startTime = event.startTime.split(":");
}
if (event.endDate.indexOf("T") > -1) {
endTime = event.endDate.split("T");
event.endDate = endTime[0];
endTime = endTime[1].split(":");
} else {
endTime = event.endTime.split(":");
}
if (startTime[1].indexOf("PM") > -1 && startTime[0] != "12") {
startTime[0] = parseInt(startTime[0]) + 12;
startTime[1] = parseInt(startTime[1].split("PM")[0]);
} else {
startTime[0] = parseInt(startTime[0]);
startTime[1] = parseInt(startTime[1].split("AM")[0]);
}
event.startTime = startTime.join(":");
startTime = startTime[0] + startTime[1].toFixed(2)/60;
if (endTime[1].indexOf("PM") > -1 && endTime[0] != "12") {
endTime[0] = parseInt(endTime[0]) + 12;
endTime[1] = parseInt(endTime[1].split("PM")[0]);
} else {
endTime[0] = parseInt(endTime[0]);
endTime[1] = parseInt(endTime[1].split("AM")[0]);
}
event.endTime = endTime.join(":");
endTime = endTime[0] + endTime[0].toFixed(2)/60;
days = event.days;
eventDays = [];
if (days.indexOf("Sn") > -1) {
days = days.split("Sn").join("");
eventDays.push("Sn");
}
days = days.split("");
for (i in days) {
if (days[i] in this._dayMap) {
eventDays.push(days[i]);
}
}
event.days = eventDays;
if (this._database.getObject(item, "display")) {
entries.push(event);
}
}
}
return entries;
};
/*
Allows switching between week and month views
on calendar
*/
Exhibit.MonthFacet.prototype.renderSwitchTab = function(container) {
var $=Exhibit.jQuery;
if ($(container).find(".timegrid-switch-tab").length == 0) {
var self = this;
var tabDiv = $('<div></div>').addClass('timegrid-switch-tab');
$(container).prepend(tabDiv);
this._switchTitle = "Week";
var newLink = $("<a />", {
href : "javascript:void",
text : "See " + this._switchTitle
});
var tab = $('<div></div>', { height : this._tabHeight + "px" })
.addClass("timegrid-tab")
.addClass("timegrid-rounded")
.css({
"width": 100 + "px",
"margin-left": this._gridWidth + this._yLabelWidth - 100 + "px",
"float": "left",
"position": "relative"
})
.append(newLink);
tabDiv.prepend(tab);
Exhibit.jQuery(tab).bind("click", function () {
self.switchToWeek();
});
var ie = (function(){
var undef, v = 3, div = document.createElement('div');
while (
div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
div.getElementsByTagName('i')[0]
);
return v> 4 ? v : undef;
}());
if (ie) { $('.timegrid-tab').corner("30px top"); }
}
};
/*
Responsible for switching from week to month
and vice versa.
*/
Exhibit.MonthFacet.prototype.switchToWeek = function(view, container) {
var $=Exhibit.jQuery;
this._valueSet = new Exhibit.Set();
this._notifyCollection();
this._settings.defaultFacet = "week";
this._uiContext.getCollection().removeFacet(this._timegridFacet);
$(this._configElmt).empty();
$(this._configElmt).attr("data-ex-default-facet", this._settings.defaultFacet);
Exhibit.TimegridFacet.createFromDOM(this._configElmt, this._containerElmt, this._uiContext);
};
/**
* @param {Array} entries
*/
Exhibit.MonthFacet.prototype._constructBody = function(entries) {
var $=Exhibit.jQuery;
var containerDiv, entry, i, labels, days, starts, ends, colors, j, k, day, dayArray, formats;
this._events = [];
containerDiv = this._dom.valuesContainer;
Exhibit.jQuery(containerDiv).empty();
$(containerDiv).addClass('month-default');
this.render(containerDiv);
for (i = 0; i < entries.length; i++) {
labels = entries[i].label;
days = entries[i].days;
starts = entries[i].startTime;
ends = entries[i].endTime;
startDates = entries[i].startDate;
endDates = entries[i].endDate;
if (entries[i].dateFormat) {
formats = entries[i].dateFormat;
}
colors = [];
if (entries[i].color) {
colors = entries[i].color.split(",;");
}
if (days.length > 0) {
for (k = 0; k < days.length; k++) {
this._events.push(
new Exhibit.TimegridFacet.EventSource.EventPrototype(
[ this._dayMap[days[k]] ],
starts,
ends,
startDates,
endDates,
labels,
"",
"",
"",
"",
colors,
"white",
formats ? formats : null
)
);
}
} else {
this._events.push(
new Exhibit.TimegridFacet.EventSource.EventPrototype(
"",
starts,
ends,
startDates,
endDates,
labels,
"",
"",
"",
"",
colors,
"white",
formats ? formats : null
)
);
}
}
this.setEventPrototypes(this._events);
this._updateGrid();
this.renderSwitchTab($(this._containerElmt).find("div")[0]);
};
/*
Clears the selection of times you want to view events
*/
Exhibit.MonthFacet.prototype._clearSelections = function () {
Exhibit.History.pushComponentState(
this,
Exhibit.Facet.getRegistryKey(),
this.exportEmptyState(),
Exhibit._("%facets.facetClearSelectionsActionTitle", this._getLabel()),
true
);
Exhibit.History.eraseState();
};
/*
@param {Object} state
@param {Array} state.selections
*/
Exhibit.MonthFacet.prototype.importState = function(state) {
if (this.stateDiffers(state)) {
this.applyRestrictions(state);
}
};
/*
@param {Object} state
@param {Array} state.selection
*/
Exhibit.MonthFacet.prototype.stateDiffers = function(state) {
var selectionStartCount, stateStartCount, stateSet;
stateStartCount = state.selections.length;
selectionsStartCount = this._valueSet.length;
if (stateStartCount !== selectionStartCount) {
return true;
} else {
stateSet = new Exhibit.Set(state.selections);
stateSet.addSet(this._valueSet);
if (stateSet.size() !== stateStartCount) {
return true;
}
}
return false;
};
Exhibit.MonthFacet.prototype.exportState = function() {
return this._exportState(false);
};
Exhibit.MonthFacet.prototype.exportEmptyState = function() {
return this._exportState(true);
};
Exhibit.MonthFacet.prototype._exportState = function(empty) {
var s = [];
if (!empty) {
s = this._valueSet.toArray();
}
return {
"selections": s
};
};
Exhibit.MonthFacet.prototype._getEndpoints = function(evt) {
return [ { type: "start",
time: evt.getStart(),
event: evt },
{ type: "end",
time: evt.getEnd(),
event: evt } ];
};
// Dummy variable for creating the "W23" label
Exhibit.MonthFacet.l10n = {};
/** Function to create a title string from an n-value */
Exhibit.MonthFacet.l10n.makeTitle = function(n) { return n + "-Day"; }
/** Function to combine two dates into a string describing the grid's range */
Exhibit.MonthFacet.l10n.makeRange = function(d1, d2) {
return d1.format(Exhibit.MonthFacet.l10n.startFormat) + " - " +
d2.format(Exhibit.MonthFacet.l10n.endFormat);
};
/** Format for horizontal "Mon 5/24" style labels */
Exhibit.MonthFacet.l10n.xLabelFormat = "E M/d";
Exhibit.MonthFacet.l10n.miniXLabelFormat = "e";
/** Format for displaying the grid's starting date, e.g. "6/12/2007" */
Exhibit.MonthFacet.l10n.startFormat = "M/d/yyyy";
/** Format for displaying the grid's ending date, e.g. "6/15/2007" */
Exhibit.MonthFacet.l10n.endFormat = "M/d/yyyy";
|
var _ = require('underscore');
var sourcemap = require('source-map');
var buildmessage = require('../buildmessage.js');
var isopackets = require('../isopackets.js');
var watch = require('../watch.js');
var Profile = require('../profile.js').Profile;
import LRU from 'lru-cache';
import {sourceMapLength} from '../utils.js';
import {findAssignedGlobals} from './js-analyze.js';
// A rather small cache size, assuming only one module is being linked
// most of the time.
const CACHE_SIZE = process.env.METEOR_APP_PRELINK_CACHE_SIZE || 1024*1024*20;
// Cache individual files prelinked
const APP_PRELINK_CACHE = new LRU({
max: CACHE_SIZE,
length: function (prelinked) {
return prelinked.source.length + sourceMapLength(prelinked.sourceMap);
}
});
var packageDot = function (name) {
if (/^[a-zA-Z][a-zA-Z0-9]*$/.exec(name))
return "Package." + name;
else
return "Package['" + name + "']";
};
///////////////////////////////////////////////////////////////////////////////
// Module
///////////////////////////////////////////////////////////////////////////////
// options include name, imports, exports, useGlobalNamespace,
// combinedServePath, all of which have the same meaning as they do when passed
// to import().
var Module = function (options) {
var self = this;
// module name or null
self.name = options.name || null;
// files in the module. array of File
self.files = [];
// options
self.useGlobalNamespace = options.useGlobalNamespace;
self.combinedServePath = options.combinedServePath;
self.noLineNumbers = options.noLineNumbers;
};
_.extend(Module.prototype, {
// source: the source code
// servePath: the path where it would prefer to be served if possible
addFile: function (inputFile) {
var self = this;
self.files.push(new File(inputFile, self));
},
maxLineLength: function (ignoreOver) {
var self = this;
var maxInFile = [];
_.each(self.files, function (file) {
var m = 0;
_.each(file.source.split('\n'), function (line) {
if (line.length <= ignoreOver && line.length > m)
m = line.length;
});
maxInFile.push(m);
});
return _.max(maxInFile);
},
// Figure out which vars need to be specifically put in the module
// scope.
computeAssignedVariables: Profile("linker Module#computeAssignedVariables", function () {
var self = this;
// The assigned variables in the app aren't actually used for anything:
// we're using the global namespace, so there's no header where we declare
// all of the assigned variables as vars. So there's no use wasting time
// running static analysis on app code.
if (self.useGlobalNamespace) {
return [];
}
// Find all global references in any files
var assignedVariables = [];
_.each(self.files, function (file) {
assignedVariables = assignedVariables.concat(
file.computeAssignedVariables());
});
assignedVariables = _.uniq(assignedVariables);
return assignedVariables;
}),
// Output is a list of objects with keys 'source', 'servePath', 'sourceMap',
// 'sourcePath'
getPrelinkedFiles: Profile("linker Module#getPrelinkedFiles", function () {
var self = this;
// If we don't want to create a separate scope for this module,
// then our job is much simpler. And we can get away with
// preserving the line numbers.
if (self.useGlobalNamespace) {
return _.map(self.files, function (file) {
const cacheKey = JSON.stringify([
file.sourceHash, file.bare, file.servePath]);
if (APP_PRELINK_CACHE.has(cacheKey)) {
return APP_PRELINK_CACHE.get(cacheKey);
}
const node = file.getPrelinkedOutput({ preserveLineNumbers: true });
const results = Profile.time(
"getPrelinkedFiles toStringWithSourceMap (app)", () => {
return node.toStringWithSourceMap({
file: file.servePath
}); // results has 'code' and 'map' attributes
}
);
const sourceMap = results.map.toJSON();
const prelinked = {
source: results.code,
servePath: file.servePath,
sourceMap: sourceMap
};
APP_PRELINK_CACHE.set(cacheKey, prelinked);
return prelinked;
});
}
// Otherwise..
// Find the maximum line length.
var sourceWidth = _.max([68, self.maxLineLength(120 - 2)]);
// Prologue
var chunks = [];
// Emit each file
_.each(self.files, function (file) {
if (!_.isEmpty(chunks))
chunks.push("\n\n\n\n\n\n");
chunks.push(file.getPrelinkedOutput({
sourceWidth: sourceWidth,
noLineNumbers: self.noLineNumbers
}));
});
var node = new sourcemap.SourceNode(null, null, null, chunks);
var results = Profile.time(
'getPrelinkedFiles toStringWithSourceMap (packages)',
function () {
return node.toStringWithSourceMap({
file: self.combinedServePath
}); // results has 'code' and 'map' attributes
}
);
return [{
source: results.code,
servePath: self.combinedServePath,
sourceMap: results.map.toJSON()
}];
})
});
// Given 'symbolMap' like {Foo: 's1', 'Bar.Baz': 's2', 'Bar.Quux.A': 's3', 'Bar.Quux.B': 's4'}
// return something like
// {Foo: 's1', Bar: {Baz: 's2', Quux: {A: 's3', B: 's4'}}}
//
// If the value of a symbol in symbolMap is set null, then we just
// ensure that its parents exist. For example, {'A.B.C': null} means
// to make sure that symbol tree contains at least {A: {B: {}}}.
var buildSymbolTree = function (symbolMap) {
var ret = {};
_.each(symbolMap, function (value, symbol) {
var parts = symbol.split('.');
var lastPart = parts.pop();
var walk = ret;
_.each(parts, function (part) {
if (! (part in walk))
walk[part] = {};
walk = walk[part];
});
if (value)
walk[lastPart] = value;
});
return ret;
};
// Given something like {Foo: 's1', Bar: {Baz: 's2', Quux: {A: 's3', B: 's4'}}}
// construct a string like {Foo: s1, Bar: {Baz: s2, Quux: {A: s3, B: s4}}}
// except with pretty indentation.
var writeSymbolTree = function (symbolTree, indent) {
var put = function (node, indent) {
if (typeof node === "string") {
return node;
}
if (_.keys(node).length === 0) {
return '{}';
}
var spacing = new Array(indent + 1).join(' ');
// XXX prettyprint!
return "{\n" +
_.map(node, function (value, key) {
return spacing + " " + key + ": " + put(value, indent + 2);
}).join(',\n') + "\n" + spacing + "}";
};
return put(symbolTree, indent || 0);
};
///////////////////////////////////////////////////////////////////////////////
// File
///////////////////////////////////////////////////////////////////////////////
var File = function (inputFile, module) {
var self = this;
// source code for this file (a string)
self.source = inputFile.data.toString('utf8');
// hash of source (precalculated for *.js files, calculated here for files
// produced by plugins)
self.sourceHash = inputFile.hash || watch.sha1(self.source);
// the path where this file would prefer to be served if possible
self.servePath = inputFile.servePath;
// If true, don't wrap this individual file in a closure.
self.bare = !!inputFile.bare;
// A source map (generated by something like CoffeeScript) for the input file.
// Is an Object, not a string.
self.sourceMap = inputFile.sourceMap;
// The Module containing this file.
self.module = module;
};
// findAssignedGlobals is somewhat slow, and we often compute assigned variables
// on the same file multiple times in one process (notably, a single file is
// often processed for two or three different unibuilds, and is processed again
// when rebuilding a package when another file has changed). We cache the
// calculated variables under the source file's hash (calculating the source
// file's hash is faster than running findAssignedGlobals, and in the case of
// *.js files we have the hash already anyway).
var ASSIGNED_GLOBALS_CACHE = {};
_.extend(File.prototype, {
// Return the globals in this file as an array of symbol names. For
// example: if the code references 'Foo.bar.baz' and 'Quux', and
// neither are declared in a scope enclosing the point where they're
// referenced, then globalReferences would include ["Foo", "Quux"].
computeAssignedVariables: Profile("linker File#computeAssignedVariables", function () {
var self = this;
if (_.has(ASSIGNED_GLOBALS_CACHE, self.sourceHash)) {
return ASSIGNED_GLOBALS_CACHE[self.sourceHash];
}
try {
return (ASSIGNED_GLOBALS_CACHE[self.sourceHash] =
_.keys(findAssignedGlobals(self.source)));
} catch (e) {
if (!e.$ParseError)
throw e;
var errorOptions = {
file: self.servePath,
line: e.lineNumber,
column: e.column
};
if (self.sourceMap) {
var parsed = new sourcemap.SourceMapConsumer(self.sourceMap);
var original = parsed.originalPositionFor(
{line: e.lineNumber, column: e.column - 1});
if (original.source) {
errorOptions.file = original.source;
errorOptions.line = original.line;
errorOptions.column = original.column + 1;
}
}
buildmessage.error(e.message, errorOptions);
// Recover by pretending that this file is empty (which
// includes replacing its source code with '' in the output)
self.source = "";
self.sourceHash = watch.sha1(self.source);
self.sourceMap = null;
return [];
}
}),
// Options:
// - preserveLineNumbers: if true, decorate minimally so that line
// numbers don't change between input and output. In this case,
// sourceWidth is ignored.
// - noLineNumbers: We still include the banners and such, but
// no line number suffix.
// - sourceWidth: width in columns to use for the source code
//
// Returns a SourceNode.
getPrelinkedOutput: Profile("linker File#getPrelinkedOutput", function (options) {
var self = this;
var width = options.sourceWidth || 70;
var bannerWidth = width + 3;
var result;
var lines;
var noLineNumbers = options.noLineNumbers;
var preserveLineNumbers = options.preserveLineNumbers;
if (self.sourceMap) {
// If we have a source map, it is also important to annotate line
// numbers using that source map, since not all browsers support
// source maps.
noLineNumbers = false;
// Honoring options.preserveLineNumbers is likely impossible if we
// have a source map, since self.source has probably already been
// transformed in a way that does not preserve line numbers. That's
// ok, though, because we have a source map, and we also annotate
// line numbers using comments (see above), just in case source maps
// are not supported.
preserveLineNumbers = false;
} else if (preserveLineNumbers) {
// If we don't have a source map, and we're supposed to be preserving line
// numbers (ie, we are not linking multiple files into one file, because
// we're the app), then we can get away without annotating line numbers
// (or making a source map), because they won't add any helpful
// information.
noLineNumbers = true;
}
if (self.sourceMap) {
result = {
code: self.source,
map: self.sourceMap
};
} else if (noLineNumbers && preserveLineNumbers) {
// No need to generate a source map if we don't want line numbers.
result = {
code: self.source,
map: null
};
} else {
// If we're planning to annotate the source with line number
// comments (e.g. because we're combining this file with others in a
// package), and we don't already have a source map, then we need to
// generate one, so that we don't have to write two different
// versions of the code for annotating line numbers, and also so
// that browsers that support source maps can display a prettier
// version of this file without the line number comments.
var smg = new sourcemap.SourceMapGenerator({
file: self.servePath
});
lines = self.source.split("\n");
_.each(lines, function (line, i) {
var start = { line: i + 1, column: 0 };
smg.addMapping({
original: start,
generated: start,
source: self.servePath
});
});
smg.setSourceContent(self.servePath, self.source);
result = {
code: self.source,
map: smg.toJSON()
};
}
var smc = result.map &&
new sourcemap.SourceMapConsumer(result.map);
if (smc && ! noLineNumbers) {
var padding = bannerPadding(bannerWidth);
// We might have already done this split above.
lines = lines || result.code.split("\n");
// Use the SourceMapConsumer object to compute the original line
// number for each line of result.code.
_.each(lines, function (line, i) {
var len = line.length;
if (len < width &&
line[len - 1] !== "\\") {
var pos = smc.originalPositionFor({
line: i + 1,
column: 0
});
if (pos) {
lines[i] += padding.slice(len, width) + " //";
// Not all source maps define a mapping for every line in the
// output. This is perfectly normal.
if (typeof pos.line === "number") {
lines[i] += " " + pos.line;
}
}
}
});
result.code = lines.join("\n");
}
var chunks = [];
var pathNoSlash = self.servePath.replace(/^\//, "");
if (! self.bare) {
var closureHeader = "(function(){";
chunks.push(
closureHeader,
preserveLineNumbers ? "" : "\n\n"
);
if (! smc) {
// No sourcemap? Generate a new one that takes into account the fact
// that we added a closure
var map = new sourcemap.SourceMapGenerator({ file: self.servePath });
_.each(result.code.split('\n'), function (line, i) {
map.addMapping({
source: self.servePath,
original: { line: i + 1, column: 0 },
generated: { line: i + 1, column: i === 0 ? closureHeader.length + 1 : 0 }
});
});
map.setSourceContent(self.servePath, result.code);
smc = new sourcemap.SourceMapConsumer(map.toJSON());
}
}
if (! preserveLineNumbers) {
// Banner
var bannerLines = [pathNoSlash];
if (self.bare) {
bannerLines.push(
"This file is in bare mode and is not in its own closure.");
}
chunks.push(banner(bannerLines, bannerWidth));
var blankLine = new Array(width + 1).join(' ') + " //\n";
chunks.push(blankLine);
}
if (result.code) {
chunks.push(
// If we have a source map for result.code, push a SourceNode onto
// the chunks array that encapsulates that source map. If we don't
// have a source map, just push result.code.
smc ? sourcemap.SourceNode.fromStringWithSourceMap(result.code, smc)
: result.code
);
// It's important for the code to end with a newline, so that a
// trailing // comment can't snarf code appended after it.
if (result.code[result.code - 1] !== "\n") {
chunks.push("\n");
}
}
// Footer
if (! self.bare) {
if (preserveLineNumbers) {
chunks.push("}).call(this);\n");
} else {
chunks.push(
dividerLine(bannerWidth),
"\n}).call(this);\n"
);
}
}
return new sourcemap.SourceNode(null, null, null, chunks);
})
});
// Given a list of lines (not newline-terminated), returns a string placing them
// in a pretty banner of width bannerWidth. All lines must have length at most
// (bannerWidth - 6); if bannerWidth is not provided, the smallest width that
// fits is used.
var banner = function (lines, bannerWidth) {
if (!bannerWidth)
bannerWidth = 6 + _.max(lines, function (x) { return x.length; }).length;
var divider = dividerLine(bannerWidth);
var spacer = "// " + new Array(bannerWidth - 6 + 1).join(' ') + " //\n";
var padding = bannerPadding(bannerWidth);
var buf = divider + spacer;
_.each(lines, function (line) {
buf += "// " + (line + padding).slice(0, bannerWidth - 6) + " //\n";
});
buf += spacer + divider;
return buf;
};
var dividerLine = function (bannerWidth) {
return new Array(bannerWidth + 1).join('/') + "\n";
};
var bannerPadding = function (bannerWidth) {
return new Array(bannerWidth + 1).join(' ');
};
///////////////////////////////////////////////////////////////////////////////
// Top-level entry points
///////////////////////////////////////////////////////////////////////////////
// Prior to the "batch-plugins" project, linker.prelink was the first phase of
// linking. It got performed at package compile time, to be followed up with a
// function that used to exist called linker.link at app bundle time. We now do
// far less processing at package compile time and simply run linker.fullLink at
// app bundle time, which is effectively the old prelink+link combined. However,
// we keep linker.prelink around now in order to allow new published packages
// that don't use the new build plugin APIs to be used by older Isobuilds.
// It only gets called on packages, not on apps.
//
// This does about half of the of the linking process. It does not require
// knowledge of your imports. It returns the module's exports, plus a set of
// partially linked files which you must pass to link() along with your import
// list to get your final linked files.
//
// options include:
//
// name: the name of this module (for stashing exports to be later
// read by the imports of other modules); null if the module has no
// name (in that case exports will not work properly)
//
// inputFiles: an array of objects representing input files.
// - source: the source code
// - servePath: the path where it would prefer to be served if
// possible. still allowed on non-browser targets, where it
// represent as hint as to what the file should be named on disk in
// the bundle (this will only be seen by someone looking at the
// bundle, not in error messages, but it's still nice to make it
// look good)
// - sourceMap: an optional source map (as string) for the input file
//
// combinedServePath: if we end up combining all of the files into
// one, use this as the servePath.
//
// Output is an object with keys:
// - files: is an array of output files in the same format as inputFiles
// - EXCEPT THAT, for now, sourcePath is omitted and is replaced with
// sourceMap (a string) (XXX)
// - assignedPackageVariables: an array of variables assigned to without
// being declared
var prelink = Profile("linker.prelink", function (options) {
var module = new Module({
name: options.name,
combinedServePath: options.combinedServePath,
noLineNumbers: options.noLineNumbers
});
_.each(options.inputFiles, function (inputFile) {
module.addFile(inputFile);
});
// Do static analysis to compute module-scoped variables. Error recovery from
// the static analysis mutates the sources, so this has to be done before
// concatenation.
var assignedVariables = module.computeAssignedVariables();
var files = module.getPrelinkedFiles();
return {
files: files,
assignedVariables: assignedVariables
};
});
var SOURCE_MAP_INSTRUCTIONS_COMMENT = banner([
"This is a generated file. You can view the original",
"source in your browser if your browser supports source maps.",
"Source maps are supported by all recent versions of Chrome, Safari, ",
"and Firefox, and by Internet Explorer 11."
]);
var getHeader = function (options) {
var chunks = [];
chunks.push("(function () {\n\n" );
chunks.push(getImportCode(options.imports, "/* Imports */\n", false));
if (!_.isEmpty(options.packageVariables)) {
chunks.push("/* Package-scope variables */\n");
chunks.push("var " + options.packageVariables.join(', ') +
";\n\n");
}
return chunks.join('');
};
var getImportCode = function (imports, header, omitvar) {
var self = this;
if (_.isEmpty(imports))
return "";
// Imports
var scratch = {};
_.each(imports, function (name, symbol) {
scratch[symbol] = packageDot(name) + "." + symbol;
});
var tree = buildSymbolTree(scratch);
// Generate output
var buf = header;
_.each(tree, function (node, key) {
buf += (omitvar ? "" : "var " ) +
key + " = " + writeSymbolTree(node) + ";\n";
});
buf += "\n";
return buf;
};
var getFooter = function (options) {
var chunks = [];
if (options.name && options.exported) {
chunks.push("\n\n/* Exports */\n");
chunks.push("if (typeof Package === 'undefined') Package = {};\n");
chunks.push(packageDot(options.name), " = ");
// Even if there are no exports, we need to define Package.foo, because the
// existence of Package.foo is how another package (eg, one that weakly
// depends on foo) can tell if foo is loaded.
if (_.isEmpty(options.exported)) {
chunks.push("{};\n");
} else {
// A slightly overkill way to print out a properly indented version of
// {Foo: Foo, Bar: Bar, Quux: Quux}. (This was less overkill back when
// you could export dotted symbols.)
var scratch = {};
_.each(options.exported, function (symbol) {
scratch[symbol] = symbol;
});
var exportTree = buildSymbolTree(scratch);
chunks.push(writeSymbolTree(exportTree));
chunks.push(";\n");
}
}
chunks.push("\n})();\n");
return chunks.join('');
};
// This is the real entry point that's still used to produce Meteor apps. It
// takes in information about the files in the package including imports and
// exports, and returns an array of linked source files.
//
// inputFiles: an array of objects representing input files.
// - source: the source code
// - hash: the hash of the source code (optional, will be calculated
// if not given)
// - servePath: the path where it would prefer to be served if
// possible. still allowed on non-browser targets, where it
// represent as hint as to what the file should be named on disk in
// the bundle (this will only be seen by someone looking at the
// bundle, not in error messages, but it's still nice to make it
// look good)
// - bare: if true, don't wrap this file in a closure
// - sourceMap: an optional source map (as object) for the input file
//
// useGlobalNamespace: make the top level namespace be the same as the global
// namespace, so that symbols are accessible from the console, and don't
// actually combine files into a single file. used when linking apps (as opposed
// to packages).
//
// combinedServePath: if we end up combining all of the files into
// one, use this as the servePath.
//
// name: the name of this module (for stashing exports to be later
// read by the imports of other modules); null if the module has no
// name (in that case exports will not work properly)
//
// declaredExports: an array of symbols that the module exports. Symbols are
// {name,testOnly} pairs.
//
// imports: a map from imported symbol to the name of the package that it is
// imported from
//
// importStubServePath: if useGlobalNamespace is set, this is the name of the
// file to create with imports into the global namespace
//
// includeSourceMapInstructions: true if JS files with source maps should
// have a comment explaining how to use them in a browser.
//
// Output is an array of output files: objects with keys source, servePath,
// sourceMap.
var fullLink = Profile("linker.fullLink", function (inputFiles, {
useGlobalNamespace, combinedServePath, name, declaredExports, imports,
importStubServePath, includeSourceMapInstructions
}) {
buildmessage.assertInJob();
var module = new Module({
name, useGlobalNamespace, combinedServePath,
noLineNumbers: false
});
_.each(inputFiles, function (inputFile) {
module.addFile(inputFile);
});
var prelinkedFiles = module.getPrelinkedFiles();
// If we're in the app, then we just add the import code as its own file in
// the front.
if (useGlobalNamespace) {
if (!_.isEmpty(imports)) {
prelinkedFiles.unshift({
source: getImportCode(imports,
"/* Imports for global scope */\n\n", true),
servePath: importStubServePath
});
}
return prelinkedFiles;
}
// Do static analysis to compute module-scoped variables. Error recovery from
// the static analysis mutates the sources, so this has to be done before
// concatenation.
let assignedVariables;
const failed = buildmessage.enterJob('computing assigned variables', () => {
assignedVariables = module.computeAssignedVariables();
return buildmessage.jobHasMessages();
});
if (failed)
return []; // recover by pretending there are no files
// Otherwise we're making a package and we have to actually combine the files
// into a single scope.
var header = getHeader({
imports,
packageVariables: _.union(assignedVariables, declaredExports)
});
var footer = getFooter({
exported: declaredExports,
name
});
return _.map(prelinkedFiles, function (file) {
if (file.sourceMap) {
if (includeSourceMapInstructions)
header = SOURCE_MAP_INSTRUCTIONS_COMMENT + "\n\n" + header;
// Bias the source map by the length of the header without
// (fully) parsing and re-serializing it. (We used to do this
// with the source-map library, but it was incredibly slow,
// accounting for over half of bundling time.) It would be nice
// if we could use "index maps" for this (the 'sections' key),
// as that would let us avoid even JSON-parsing the source map,
// but that doesn't seem to be supported by Firefox yet.
if (header.charAt(header.length - 1) !== "\n")
header += "\n"; // make sure it's a whole number of lines
var headerLines = header.split('\n').length - 1;
var sourceMap = file.sourceMap;
sourceMap.mappings = (new Array(headerLines + 1).join(';')) +
sourceMap.mappings;
return {
source: header + file.source + footer,
servePath: file.servePath,
sourceMap: sourceMap
};
} else {
return {
source: header + file.source + footer,
servePath: file.servePath
};
}
});
});
var linker = module.exports = {
prelink: prelink,
fullLink: fullLink
};
|
/*!
* global/window.min.js
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2018 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 4.0.0-beta.64
*/
"function"==typeof define&&define.amd?define(function(){return window}):"object"==typeof exports&&(module.exports=window);
|
define(
//begin v1.x content
{
"field-quarter-short-relative+0": "dette kv.",
"field-quarter-short-relative+1": "neste kv.",
"field-tue-relative+-1": "tirsdag sist uke",
"field-year": "år",
"field-wed-relative+0": "onsdag denne uken",
"field-wed-relative+1": "onsdag neste uke",
"field-minute": "minutt",
"field-month-narrow-relative+-1": "forrige md.",
"field-tue-narrow-relative+0": "denne ti.",
"field-tue-narrow-relative+1": "neste ti.",
"field-thu-short-relative+0": "denne tor.",
"field-day-short-relative+-1": "i går",
"dateTimeFormat-short": "{1} {0}",
"field-thu-short-relative+1": "neste tor.",
"field-day-relative+0": "i dag",
"field-day-short-relative+-2": "i forgårs",
"field-day-relative+1": "i morgen",
"field-week-narrow-relative+0": "denne uken",
"field-day-relative+2": "i overmorgen",
"field-week-narrow-relative+1": "neste uke",
"field-wed-narrow-relative+-1": "sist on.",
"field-year-narrow": "år",
"field-tue-relative+0": "tirsdag denne uken",
"field-tue-relative+1": "tirsdag neste uke",
"field-second-short": "sek",
"dateFormatItem-MMMd": "d. MMM",
"field-week-relative+0": "denne uken",
"field-month-relative+0": "denne måneden",
"field-week-relative+1": "neste uke",
"field-month-relative+1": "neste måned",
"field-sun-narrow-relative+0": "denne sø.",
"field-mon-short-relative+0": "denne man.",
"field-sun-narrow-relative+1": "neste sø.",
"field-mon-short-relative+1": "neste man.",
"field-second-relative+0": "nå",
"dateFormatItem-yyyyQQQ": "QQQ r(U)",
"months-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"field-month-short": "mnd.",
"dateFormatItem-GyMMMEd": "E d. MMM r(U)",
"dateFormatItem-yyyyMd": "dd.MM.r",
"field-day": "dag",
"field-year-relative+-1": "i fjor",
"field-sat-short-relative+-1": "sist lør.",
"field-hour-relative+0": "denne timen",
"dateFormatItem-yyyyMEd": "E dd.MM.r",
"field-wed-relative+-1": "onsdag sist uke",
"dateTimeFormat-medium": "{1} {0}",
"field-sat-narrow-relative+-1": "sist lø.",
"field-second": "sekund",
"dateFormat-long": "d. MMMM r(U)",
"dateFormatItem-GyMMMd": "d. MMM r",
"field-quarter": "kvartal",
"field-week-short": "uke",
"field-tue-short-relative+0": "denne tir.",
"field-tue-short-relative+1": "neste tir.",
"field-month-short-relative+-1": "forrige md.",
"field-mon-relative+-1": "mandag sist uke",
"dateFormatItem-GyMMM": "MMM r(U)",
"field-month": "måned",
"field-day-narrow": "d.",
"dateFormatItem-MMM": "LLL",
"field-minute-short": "min",
"field-dayperiod": "a.m./p.m.",
"field-sat-short-relative+0": "denne lør.",
"field-sat-short-relative+1": "neste lør.",
"dateFormat-medium": "d. MMM r",
"dateFormatItem-yyyyMMMM": "MMMM r(U)",
"dateFormatItem-UMMM": "MMM U",
"dateFormatItem-yyyyM": "MM.r",
"field-second-narrow": "s",
"field-mon-relative+0": "mandag denne uken",
"field-mon-relative+1": "mandag neste uke",
"field-year-short": "år",
"field-quarter-relative+-1": "forrige kvartal",
"dateFormatItem-yyyyMMMd": "d. MMM r",
"field-week-narrow-relative+-1": "forrige uke",
"field-sat-relative+-1": "lørdag sist uke",
"dateTimeFormat-long": "{1} {0}",
"dateFormatItem-Md": "dd.MM",
"field-hour": "time",
"months-format-wide": [
"M01",
"M02",
"M03",
"M04",
"M05",
"M06",
"M07",
"M08",
"M09",
"M10",
"M11",
"M12"
],
"dateFormat-full": "EEEE d. MMMM r(U)",
"dateFormatItem-UMd": "d.MM. U",
"field-month-relative+-1": "forrige måned",
"field-quarter-short": "kv.",
"field-sat-narrow-relative+0": "denne lø.",
"field-fri-relative+0": "fredag denne uken",
"field-sat-narrow-relative+1": "neste lø.",
"field-fri-relative+1": "fredag neste uke",
"field-month-narrow-relative+0": "denne md.",
"field-month-narrow-relative+1": "neste md.",
"field-sun-short-relative+0": "denne søn.",
"field-sun-short-relative+1": "neste søn.",
"field-week-relative+-1": "forrige uke",
"field-quarter-short-relative+-1": "forrige kv.",
"field-quarter-relative+0": "dette kvartalet",
"field-minute-relative+0": "dette minuttet",
"field-quarter-relative+1": "neste kvartal",
"field-wed-short-relative+-1": "sist ons.",
"dateFormat-short": "d.M.r",
"field-thu-short-relative+-1": "sist tor.",
"dateFormatItem-yyyyMMMEd": "E d. MMM r(U)",
"field-mon-narrow-relative+-1": "sist ma.",
"dateFormatItem-MMMMd": "d. MMMM",
"field-thu-narrow-relative+-1": "sist to.",
"dateFormatItem-E": "ccc",
"field-tue-narrow-relative+-1": "sist ti.",
"dateFormatItem-yyyy": "r(U)",
"field-wed-short-relative+0": "denne ons.",
"dateFormatItem-M": "L.",
"field-wed-short-relative+1": "neste ons.",
"field-sun-relative+-1": "søndag sist uke",
"dateTimeFormat-full": "{1} {0}",
"dateFormatItem-d": "d.",
"field-weekday": "ukedag",
"field-day-short-relative+0": "i dag",
"field-quarter-narrow-relative+0": "dette kv.",
"field-day-short-relative+1": "i morgen",
"field-sat-relative+0": "lørdag denne uken",
"field-quarter-narrow-relative+1": "neste kv.",
"field-day-short-relative+2": "i overmorgen",
"field-sat-relative+1": "lørdag neste uke",
"field-week-short-relative+0": "denne uken",
"field-week-short-relative+1": "neste uke",
"field-month-short-relative+0": "denne md.",
"field-month-short-relative+1": "neste md.",
"dateFormatItem-MEd": "E dd.MM.",
"dateFormatItem-y": "r(U)",
"field-thu-narrow-relative+0": "denne to.",
"field-thu-narrow-relative+1": "neste to.",
"field-sun-narrow-relative+-1": "sist sø.",
"field-mon-short-relative+-1": "sist man.",
"field-thu-relative+0": "torsdag denne uken",
"field-thu-relative+1": "torsdag neste uke",
"field-fri-short-relative+-1": "sist fre.",
"field-thu-relative+-1": "torsdag sist uke",
"dateFormatItem-yMd": "dd.MM.r",
"field-week": "uke",
"dateFormatItem-Ed": "E d.",
"field-wed-narrow-relative+0": "denne on.",
"field-wed-narrow-relative+1": "neste on.",
"field-quarter-narrow-relative+-1": "forrige kv.",
"dateFormatItem-yyyyMMM": "MMM r(U)",
"field-fri-short-relative+0": "denne fre.",
"field-fri-short-relative+1": "neste fre.",
"field-week-short-relative+-1": "forrige uke",
"dateFormatItem-yyyyQQQQ": "QQQQ r(U)",
"dateFormatItem-UMMMd": "d. MMM U",
"field-hour-short": "t",
"field-month-narrow": "md.",
"field-hour-narrow": "t",
"field-fri-narrow-relative+-1": "sist fr.",
"field-year-relative+0": "i år",
"field-year-relative+1": "neste år",
"field-fri-relative+-1": "fredag sist uke",
"field-tue-short-relative+-1": "sist tir.",
"field-minute-narrow": "m",
"field-mon-narrow-relative+0": "denne ma.",
"field-mon-narrow-relative+1": "neste ma.",
"field-zone": "tidssone",
"dateFormatItem-MMMEd": "E d. MMM",
"field-quarter-narrow": "kv.",
"field-sun-short-relative+-1": "sist søn.",
"field-day-relative+-1": "i går",
"field-day-relative+-2": "i forgårs",
"field-sun-relative+0": "søndag denne uken",
"field-sun-relative+1": "søndag neste uke",
"dateFormatItem-Gy": "r(U)",
"field-day-short": "dag",
"field-week-narrow": "u.",
"field-era": "tidsalder",
"field-fri-narrow-relative+0": "denne fr.",
"dateFormatItem-UM": "MM. U",
"field-fri-narrow-relative+1": "neste fr."
}
//end v1.x content
);
|
#!/usr/bin/env node
var dirName = "js/tquery.core.create.js";
var cmdline = "make buildBundle"
// Run the first time
//require('child_process').exec(cmdline)
var onChange = function (curr, prev){
console.log("trigger", curr.mtime, prev.mtime)
if( curr.mtime - prev.mtime === 0 ) return;
//console.dir(curr.mtime)
//console.dir(prev.mtime)
console.log("change on "+dirName+".", new Date()," Running '"+ cmdline+"'")
//require('child_process').exec(cmdline)
}
console.log("Start monitoring", dirName)
require('fs').watchFile(dirName, function (curr, prev){
console.log("trigger", curr.mtime, prev.mtime)
if( curr.mtime - prev.mtime === 0 ) return;
//console.dir(curr.mtime)
//console.dir(prev.mtime)
console.log("change on "+dirName+".", new Date()," Running '"+ cmdline+"'")
//require('child_process').exec(cmdline)
});
|
/*! jQuery UI - v1.10.4 - 2014-05-25
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(t){t.datepicker.regional["nl-BE"]={closeText:"Sluiten",prevText:"←",nextText:"→",currentText:"Vandaag",monthNames:["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"],monthNamesShort:["jan","feb","mrt","apr","mei","jun","jul","aug","sep","okt","nov","dec"],dayNames:["zondag","maandag","dinsdag","woensdag","donderdag","vrijdag","zaterdag"],dayNamesShort:["zon","maa","din","woe","don","vri","zat"],dayNamesMin:["zo","ma","di","wo","do","vr","za"],weekHeader:"Wk",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional["nl-BE"])});
|
if (typeof print !== 'function') { print = console.log; }
function test() {
var b = (Uint8Array.allocPlain || Duktape.Buffer)(4096);
var i;
print(typeof b);
for (i = 0; i < 1e7; i++) {
b[100] = 123;
b[100] = 123;
b[100] = 123;
b[100] = 123;
b[100] = 123;
b[100] = 123;
b[100] = 123;
b[100] = 123;
b[100] = 123;
b[100] = 123;
}
}
try {
test();
} catch (e) {
print(e.stack || e);
throw e;
}
|
/* global Babel */
import _ from 'underscore';
import s from 'underscore.string';
const scopedChannels = ['all_public_channels', 'all_private_groups', 'all_direct_messages'];
const validChannelChars = ['@', '#'];
function _verifyRequiredFields(integration) {
if (!integration.event || !Match.test(integration.event, String) || integration.event.trim() === '' || !RocketChat.integrations.outgoingEvents[integration.event]) {
throw new Meteor.Error('error-invalid-event-type', 'Invalid event type', { function: 'validateOutgoing._verifyRequiredFields' });
}
if (!integration.username || !Match.test(integration.username, String) || integration.username.trim() === '') {
throw new Meteor.Error('error-invalid-username', 'Invalid username', { function: 'validateOutgoing._verifyRequiredFields' });
}
if (RocketChat.integrations.outgoingEvents[integration.event].use.targetRoom && !integration.targetRoom) {
throw new Meteor.Error('error-invalid-targetRoom', 'Invalid Target Room', { function: 'validateOutgoing._verifyRequiredFields' });
}
if (!Match.test(integration.urls, [String])) {
throw new Meteor.Error('error-invalid-urls', 'Invalid URLs', { function: 'validateOutgoing._verifyRequiredFields' });
}
for (const [index, url] of integration.urls.entries()) {
if (url.trim() === '') {
delete integration.urls[index];
}
}
integration.urls = _.without(integration.urls, [undefined]);
if (integration.urls.length === 0) {
throw new Meteor.Error('error-invalid-urls', 'Invalid URLs', { function: 'validateOutgoing._verifyRequiredFields' });
}
}
function _verifyUserHasPermissionForChannels(integration, userId, channels) {
for (let channel of channels) {
if (scopedChannels.includes(channel)) {
if (channel === 'all_public_channels') {
// No special permissions needed to add integration to public channels
} else if (!RocketChat.authz.hasPermission(userId, 'manage-integrations')) {
throw new Meteor.Error('error-invalid-channel', 'Invalid Channel', { function: 'validateOutgoing._verifyUserHasPermissionForChannels' });
}
} else {
let record;
const channelType = channel[0];
channel = channel.substr(1);
switch (channelType) {
case '#':
record = RocketChat.models.Rooms.findOne({
$or: [
{_id: channel},
{name: channel}
]
});
break;
case '@':
record = RocketChat.models.Users.findOne({
$or: [
{_id: channel},
{username: channel}
]
});
break;
}
if (!record) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { function: 'validateOutgoing._verifyUserHasPermissionForChannels' });
}
if (record.usernames && !RocketChat.authz.hasPermission(userId, 'manage-integrations') && RocketChat.authz.hasPermission(userId, 'manage-own-integrations') && !record.usernames.includes(Meteor.user().username)) {
throw new Meteor.Error('error-invalid-channel', 'Invalid Channel', { function: 'validateOutgoing._verifyUserHasPermissionForChannels' });
}
}
}
}
function _verifyRetryInformation(integration) {
if (!integration.retryFailedCalls) {
return;
}
// Don't allow negative retry counts
integration.retryCount = integration.retryCount && parseInt(integration.retryCount) > 0 ? parseInt(integration.retryCount) : 4;
integration.retryDelay = !integration.retryDelay || !integration.retryDelay.trim() ? 'powers-of-ten' : integration.retryDelay.toLowerCase();
}
RocketChat.integrations.validateOutgoing = function _validateOutgoing(integration, userId) {
if (integration.channel && Match.test(integration.channel, String) && integration.channel.trim() === '') {
delete integration.channel;
}
//Moved to it's own function to statisfy the complexity rule
_verifyRequiredFields(integration);
let channels = [];
if (RocketChat.integrations.outgoingEvents[integration.event].use.channel) {
if (!Match.test(integration.channel, String)) {
throw new Meteor.Error('error-invalid-channel', 'Invalid Channel', { function: 'validateOutgoing' });
} else {
channels = _.map(integration.channel.split(','), (channel) => s.trim(channel));
for (const channel of channels) {
if (!validChannelChars.includes(channel[0]) && !scopedChannels.includes(channel.toLowerCase())) {
throw new Meteor.Error('error-invalid-channel-start-with-chars', 'Invalid channel. Start with @ or #', { function: 'validateOutgoing' });
}
}
}
} else if (!RocketChat.authz.hasPermission(userId, 'manage-integrations')) {
throw new Meteor.Error('error-invalid-permissions', 'Invalid permission for required Integration creation.', { function: 'validateOutgoing' });
}
if (RocketChat.integrations.outgoingEvents[integration.event].use.triggerWords && integration.triggerWords) {
if (!Match.test(integration.triggerWords, [String])) {
throw new Meteor.Error('error-invalid-triggerWords', 'Invalid triggerWords', { function: 'validateOutgoing' });
}
integration.triggerWords.forEach((word, index) => {
if (!word || word.trim() === '') {
delete integration.triggerWords[index];
}
});
integration.triggerWords = _.without(integration.triggerWords, [undefined]);
} else {
delete integration.triggerWords;
}
if (integration.scriptEnabled === true && integration.script && integration.script.trim() !== '') {
try {
const babelOptions = Object.assign(Babel.getDefaultOptions({ runtime: false }), { compact: true, minified: true, comments: false });
integration.scriptCompiled = Babel.compile(integration.script, babelOptions).code;
integration.scriptError = undefined;
} catch (e) {
integration.scriptCompiled = undefined;
integration.scriptError = _.pick(e, 'name', 'message', 'stack');
}
}
if (typeof integration.runOnEdits !== 'undefined') {
// Verify this value is only true/false
integration.runOnEdits = integration.runOnEdits === true;
}
_verifyUserHasPermissionForChannels(integration, userId, channels);
_verifyRetryInformation(integration);
const user = RocketChat.models.Users.findOne({ username: integration.username });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user (did you delete the `rocket.cat` user?)', { function: 'validateOutgoing' });
}
integration.type = 'webhook-outgoing';
integration.userId = user._id;
integration.channel = channels;
return integration;
};
|
function range(start, end) {
var array = [];
for (var i = start; i <= end; i++) {
array.push(i);
}
return array;
}
function sum(numbersArray) {
var sum = 0;
numbersArray.forEach(function (element) {
sum += element;
});
return sum;
}
console.log(sum(range(1, 10)));
|
'use strict';
angular.module('ngQuantum.services.parseOptions', [])
.provider('$parseOptions', function () {
var defaults = this.defaults = { regexp: /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/ };
this.$get = [
'$parse',
'$q',
function ($parse, $q) {
function ParseOptionsFactory(attr, $element) {
var $parseOptions = {};
var options = angular.extend({}, defaults);
$parseOptions.$values = [];
var match, displayFn, valueName, keyName, groupByFn, valueFn, valuesFn;
$parseOptions.init = function () {
$parseOptions.$match = match = attr.match(options.regexp);
displayFn = $parse(match[2] || match[1]), valueName = match[4] || match[6], keyName = match[5], groupByFn = $parse(match[3] || ''), valueFn = $parse(match[2] ? match[1] : valueName), valuesFn = $parse(match[7]);
};
$parseOptions.valuesFn = function (scope, controller) {
return $q.when(valuesFn(scope, controller)).then(function (values) {
$parseOptions.$values = values ? parseValues(values) : {};
return $parseOptions.$values;
});
};
$parseOptions.parseInit = function () {
$parseOptions.$values = parseElement($element)
}
$parseOptions.valuesParse = function (elem) {
return $q.when(elem).then(function (el) {
$parseOptions.$values = parseElement(el) || [];
return $parseOptions.$values;
});
};
function parseValues(values) {
return values.map(function (match, index) {
var locals = {}, label, value, group;
locals[valueName] = match;
label = displayFn(locals);
value = valueFn(locals) || label;
group = groupByFn(locals);
return {
label: label,
value: value,
group: group ? { label: group } : undefined,
disabled: match.disabled
};
});
}
function parseElement(element) {
var array = [];
angular.forEach(element.children(), function (value, key) {
if (angular.element(value).is("option")) {
array.push(optionToData(angular.element(value)))
}
else if (angular.element(value).is("optgroup")) {
var group = optionGroupToData(angular.element(value));
angular.forEach(angular.element(value).children(), function (gval, gkey) {
array.push(optionToData(angular.element(gval), group))
})
}
})
return array;
}
function optionToData(element, group) {
return {
value: element.prop("value"),
label: element.text(),
group: group,
disabled: element.prop("disabled") || group && group.disabled
};
}
function optionGroupToData(element) {
return {
label: element.attr("label"),
disabled: element.prop("disabled")
};
}
if ($element)
$parseOptions.parseInit();
else
$parseOptions.init();
return $parseOptions;
}
return ParseOptionsFactory;
}
];
});
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("./foundation.core"), require("./foundation.util.keyboard"), require("./foundation.util.mediaQuery"), require("./foundation.util.motion"), require("jquery"));
else if(typeof define === 'function' && define.amd)
define(["./foundation.core", "./foundation.util.keyboard", "./foundation.util.mediaQuery", "./foundation.util.motion", "jquery"], factory);
else if(typeof exports === 'object')
exports["foundation.offcanvas"] = factory(require("./foundation.core"), require("./foundation.util.keyboard"), require("./foundation.util.mediaQuery"), require("./foundation.util.motion"), require("jquery"));
else
root["__FOUNDATION_EXTERNAL__"] = root["__FOUNDATION_EXTERNAL__"] || {}, root["__FOUNDATION_EXTERNAL__"]["foundation.offcanvas"] = factory(root["__FOUNDATION_EXTERNAL__"]["foundation.core"], root["__FOUNDATION_EXTERNAL__"]["foundation.util.keyboard"], root["__FOUNDATION_EXTERNAL__"]["foundation.util.mediaQuery"], root["__FOUNDATION_EXTERNAL__"]["foundation.util.motion"], root["jQuery"]);
})(window, function(__WEBPACK_EXTERNAL_MODULE__foundation_core__, __WEBPACK_EXTERNAL_MODULE__foundation_util_keyboard__, __WEBPACK_EXTERNAL_MODULE__foundation_util_mediaQuery__, __WEBPACK_EXTERNAL_MODULE__foundation_util_motion__, __WEBPACK_EXTERNAL_MODULE_jquery__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 9);
/******/ })
/************************************************************************/
/******/ ({
/***/ "./foundation.core":
/*!****************************************************************************************************************************************************************!*\
!*** external {"root":["__FOUNDATION_EXTERNAL__","foundation.core"],"amd":"./foundation.core","commonjs":"./foundation.core","commonjs2":"./foundation.core"} ***!
\****************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE__foundation_core__;
/***/ }),
/***/ "./foundation.util.keyboard":
/*!****************************************************************************************************************************************************************************************************!*\
!*** external {"root":["__FOUNDATION_EXTERNAL__","foundation.util.keyboard"],"amd":"./foundation.util.keyboard","commonjs":"./foundation.util.keyboard","commonjs2":"./foundation.util.keyboard"} ***!
\****************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE__foundation_util_keyboard__;
/***/ }),
/***/ "./foundation.util.mediaQuery":
/*!************************************************************************************************************************************************************************************************************!*\
!*** external {"root":["__FOUNDATION_EXTERNAL__","foundation.util.mediaQuery"],"amd":"./foundation.util.mediaQuery","commonjs":"./foundation.util.mediaQuery","commonjs2":"./foundation.util.mediaQuery"} ***!
\************************************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE__foundation_util_mediaQuery__;
/***/ }),
/***/ "./foundation.util.motion":
/*!********************************************************************************************************************************************************************************************!*\
!*** external {"root":["__FOUNDATION_EXTERNAL__","foundation.util.motion"],"amd":"./foundation.util.motion","commonjs":"./foundation.util.motion","commonjs2":"./foundation.util.motion"} ***!
\********************************************************************************************************************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE__foundation_util_motion__;
/***/ }),
/***/ "./js/entries/plugins/foundation.offcanvas.js":
/*!****************************************************!*\
!*** ./js/entries/plugins/foundation.offcanvas.js ***!
\****************************************************/
/*! exports provided: Foundation, OffCanvas */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _foundation_core__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./foundation.core */ "./foundation.core");
/* harmony import */ var _foundation_core__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_foundation_core__WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Foundation", function() { return _foundation_core__WEBPACK_IMPORTED_MODULE_0__["Foundation"]; });
/* harmony import */ var _foundation_offcanvas__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../foundation.offcanvas */ "./js/foundation.offcanvas.js");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OffCanvas", function() { return _foundation_offcanvas__WEBPACK_IMPORTED_MODULE_1__["OffCanvas"]; });
_foundation_core__WEBPACK_IMPORTED_MODULE_0__["Foundation"].plugin(_foundation_offcanvas__WEBPACK_IMPORTED_MODULE_1__["OffCanvas"], 'OffCanvas');
/***/ }),
/***/ "./js/foundation.offcanvas.js":
/*!************************************!*\
!*** ./js/foundation.offcanvas.js ***!
\************************************/
/*! exports provided: OffCanvas */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OffCanvas", function() { return OffCanvas; });
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "jquery");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./foundation.core.plugin */ "./foundation.core");
/* harmony import */ var _foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _foundation_util_keyboard__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./foundation.util.keyboard */ "./foundation.util.keyboard");
/* harmony import */ var _foundation_util_keyboard__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_foundation_util_keyboard__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _foundation_util_mediaQuery__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./foundation.util.mediaQuery */ "./foundation.util.mediaQuery");
/* harmony import */ var _foundation_util_mediaQuery__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_foundation_util_mediaQuery__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _foundation_util_triggers__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./foundation.util.triggers */ "./js/foundation.util.triggers.js");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
/**
* OffCanvas module.
* @module foundation.offCanvas
* @requires foundation.util.keyboard
* @requires foundation.util.mediaQuery
* @requires foundation.util.triggers
*/
var OffCanvas =
/*#__PURE__*/
function (_Plugin) {
_inherits(OffCanvas, _Plugin);
function OffCanvas() {
_classCallCheck(this, OffCanvas);
return _possibleConstructorReturn(this, _getPrototypeOf(OffCanvas).apply(this, arguments));
}
_createClass(OffCanvas, [{
key: "_setup",
/**
* Creates a new instance of an off-canvas wrapper.
* @class
* @name OffCanvas
* @fires OffCanvas#init
* @param {Object} element - jQuery object to initialize.
* @param {Object} options - Overrides to the default plugin settings.
*/
value: function _setup(element, options) {
var _this2 = this;
this.className = 'OffCanvas'; // ie9 back compat
this.$element = element;
this.options = jquery__WEBPACK_IMPORTED_MODULE_0___default.a.extend({}, OffCanvas.defaults, this.$element.data(), options);
this.contentClasses = {
base: [],
reveal: []
};
this.$lastTrigger = jquery__WEBPACK_IMPORTED_MODULE_0___default()();
this.$triggers = jquery__WEBPACK_IMPORTED_MODULE_0___default()();
this.position = 'left';
this.$content = jquery__WEBPACK_IMPORTED_MODULE_0___default()();
this.nested = !!this.options.nested;
this.$sticky = jquery__WEBPACK_IMPORTED_MODULE_0___default()();
this.isInCanvas = false; // Defines the CSS transition/position classes of the off-canvas content container.
jquery__WEBPACK_IMPORTED_MODULE_0___default()(['push', 'overlap']).each(function (index, val) {
_this2.contentClasses.base.push('has-transition-' + val);
});
jquery__WEBPACK_IMPORTED_MODULE_0___default()(['left', 'right', 'top', 'bottom']).each(function (index, val) {
_this2.contentClasses.base.push('has-position-' + val);
_this2.contentClasses.reveal.push('has-reveal-' + val);
}); // Triggers init is idempotent, just need to make sure it is initialized
_foundation_util_triggers__WEBPACK_IMPORTED_MODULE_4__["Triggers"].init(jquery__WEBPACK_IMPORTED_MODULE_0___default.a);
_foundation_util_mediaQuery__WEBPACK_IMPORTED_MODULE_3__["MediaQuery"]._init();
this._init();
this._events();
_foundation_util_keyboard__WEBPACK_IMPORTED_MODULE_2__["Keyboard"].register('OffCanvas', {
'ESCAPE': 'close'
});
}
/**
* Initializes the off-canvas wrapper by adding the exit overlay (if needed).
* @function
* @private
*/
}, {
key: "_init",
value: function _init() {
var id = this.$element.attr('id');
this.$element.attr('aria-hidden', 'true'); // Find off-canvas content, either by ID (if specified), by siblings or by closest selector (fallback)
if (this.options.contentId) {
this.$content = jquery__WEBPACK_IMPORTED_MODULE_0___default()('#' + this.options.contentId);
} else if (this.$element.siblings('[data-off-canvas-content]').length) {
this.$content = this.$element.siblings('[data-off-canvas-content]').first();
} else {
this.$content = this.$element.closest('[data-off-canvas-content]').first();
}
if (!this.options.contentId) {
// Assume that the off-canvas element is nested if it isn't a sibling of the content
this.nested = this.$element.siblings('[data-off-canvas-content]').length === 0;
} else if (this.options.contentId && this.options.nested === null) {
// Warning if using content ID without setting the nested option
// Once the element is nested it is required to work properly in this case
console.warn('Remember to use the nested option if using the content ID option!');
}
if (this.nested === true) {
// Force transition overlap if nested
this.options.transition = 'overlap'; // Remove appropriate classes if already assigned in markup
this.$element.removeClass('is-transition-push');
}
this.$element.addClass("is-transition-".concat(this.options.transition, " is-closed")); // Find triggers that affect this element and add aria-expanded to them
this.$triggers = jquery__WEBPACK_IMPORTED_MODULE_0___default()(document).find('[data-open="' + id + '"], [data-close="' + id + '"], [data-toggle="' + id + '"]').attr('aria-expanded', 'false').attr('aria-controls', id); // Get position by checking for related CSS class
this.position = this.$element.is('.position-left, .position-top, .position-right, .position-bottom') ? this.$element.attr('class').match(/position\-(left|top|right|bottom)/)[1] : this.position; // Add an overlay over the content if necessary
if (this.options.contentOverlay === true) {
var overlay = document.createElement('div');
var overlayPosition = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this.$element).css("position") === 'fixed' ? 'is-overlay-fixed' : 'is-overlay-absolute';
overlay.setAttribute('class', 'js-off-canvas-overlay ' + overlayPosition);
this.$overlay = jquery__WEBPACK_IMPORTED_MODULE_0___default()(overlay);
if (overlayPosition === 'is-overlay-fixed') {
jquery__WEBPACK_IMPORTED_MODULE_0___default()(this.$overlay).insertAfter(this.$element);
} else {
this.$content.append(this.$overlay);
}
} // Get the revealOn option from the class.
var revealOnRegExp = new RegExp(Object(_foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1__["RegExpEscape"])(this.options.revealClass) + '([^\\s]+)', 'g');
var revealOnClass = revealOnRegExp.exec(this.$element[0].className);
if (revealOnClass) {
this.options.isRevealed = true;
this.options.revealOn = this.options.revealOn || revealOnClass[1];
} // Ensure the `reveal-on-*` class is set.
if (this.options.isRevealed === true && this.options.revealOn) {
this.$element.first().addClass("".concat(this.options.revealClass).concat(this.options.revealOn));
this._setMQChecker();
}
if (this.options.transitionTime) {
this.$element.css('transition-duration', this.options.transitionTime);
} // Find fixed elements that should stay fixed while off-canvas is opened
this.$sticky = this.$content.find('[data-off-canvas-sticky]');
if (this.$sticky.length > 0 && this.options.transition === 'push') {
// If there's at least one match force contentScroll:false because the absolute top value doesn't get recalculated on scroll
// Limit to push transition since there's no transform scope for overlap
this.options.contentScroll = false;
}
var inCanvasFor = this.$element.attr('class').match(/\bin-canvas-for-(\w+)/);
if (inCanvasFor && inCanvasFor.length === 2) {
// Set `inCanvasOn` option if found in-canvas-for-[BREAKPONT] CSS class
this.options.inCanvasOn = inCanvasFor[1];
} else if (this.options.inCanvasOn) {
// Ensure the CSS class is set
this.$element.addClass("in-canvas-for-".concat(this.options.inCanvasOn));
}
if (this.options.inCanvasOn) {
this._checkInCanvas();
} // Initally remove all transition/position CSS classes from off-canvas content container.
this._removeContentClasses();
}
/**
* Adds event handlers to the off-canvas wrapper and the exit overlay.
* @function
* @private
*/
}, {
key: "_events",
value: function _events() {
var _this3 = this;
this.$element.off('.zf.trigger .zf.offCanvas').on({
'open.zf.trigger': this.open.bind(this),
'close.zf.trigger': this.close.bind(this),
'toggle.zf.trigger': this.toggle.bind(this),
'keydown.zf.offCanvas': this._handleKeyboard.bind(this)
});
if (this.options.closeOnClick === true) {
var $target = this.options.contentOverlay ? this.$overlay : this.$content;
$target.on({
'click.zf.offCanvas': this.close.bind(this)
});
}
if (this.options.inCanvasOn) {
jquery__WEBPACK_IMPORTED_MODULE_0___default()(window).on('changed.zf.mediaquery', function () {
_this3._checkInCanvas();
});
}
}
/**
* Applies event listener for elements that will reveal at certain breakpoints.
* @private
*/
}, {
key: "_setMQChecker",
value: function _setMQChecker() {
var _this = this;
this.onLoadListener = Object(_foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1__["onLoad"])(jquery__WEBPACK_IMPORTED_MODULE_0___default()(window), function () {
if (_foundation_util_mediaQuery__WEBPACK_IMPORTED_MODULE_3__["MediaQuery"].atLeast(_this.options.revealOn)) {
_this.reveal(true);
}
});
jquery__WEBPACK_IMPORTED_MODULE_0___default()(window).on('changed.zf.mediaquery', function () {
if (_foundation_util_mediaQuery__WEBPACK_IMPORTED_MODULE_3__["MediaQuery"].atLeast(_this.options.revealOn)) {
_this.reveal(true);
} else {
_this.reveal(false);
}
});
}
/**
* Checks if InCanvas on current breakpoint and adjust off-canvas accordingly
* @private
*/
}, {
key: "_checkInCanvas",
value: function _checkInCanvas() {
this.isInCanvas = _foundation_util_mediaQuery__WEBPACK_IMPORTED_MODULE_3__["MediaQuery"].atLeast(this.options.inCanvasOn);
if (this.isInCanvas === true) {
this.close();
}
}
/**
* Removes the CSS transition/position classes of the off-canvas content container.
* Removing the classes is important when another off-canvas gets opened that uses the same content container.
* @param {Boolean} hasReveal - true if related off-canvas element is revealed.
* @private
*/
}, {
key: "_removeContentClasses",
value: function _removeContentClasses(hasReveal) {
if (typeof hasReveal !== 'boolean') {
this.$content.removeClass(this.contentClasses.base.join(' '));
} else if (hasReveal === false) {
this.$content.removeClass("has-reveal-".concat(this.position));
}
}
/**
* Adds the CSS transition/position classes of the off-canvas content container, based on the opening off-canvas element.
* Beforehand any transition/position class gets removed.
* @param {Boolean} hasReveal - true if related off-canvas element is revealed.
* @private
*/
}, {
key: "_addContentClasses",
value: function _addContentClasses(hasReveal) {
this._removeContentClasses(hasReveal);
if (typeof hasReveal !== 'boolean') {
this.$content.addClass("has-transition-".concat(this.options.transition, " has-position-").concat(this.position));
} else if (hasReveal === true) {
this.$content.addClass("has-reveal-".concat(this.position));
}
}
/**
* Preserves the fixed behavior of sticky elements on opening an off-canvas with push transition.
* Since the off-canvas container has got a transform scope in such a case, it is done by calculating position absolute values.
* @private
*/
}, {
key: "_fixStickyElements",
value: function _fixStickyElements() {
this.$sticky.each(function (_, el) {
var $el = jquery__WEBPACK_IMPORTED_MODULE_0___default()(el); // If sticky element is currently fixed, adjust its top value to match absolute position due to transform scope
// Limit to push transition because postion:fixed works without problems for overlap (no transform scope)
if ($el.css('position') === 'fixed') {
// Save current inline styling to restore it if undoing the absolute fixing
var topVal = parseInt($el.css('top'), 10);
$el.data('offCanvasSticky', {
top: topVal
});
var absoluteTopVal = jquery__WEBPACK_IMPORTED_MODULE_0___default()(document).scrollTop() + topVal;
$el.css({
top: "".concat(absoluteTopVal, "px"),
width: '100%',
transition: 'none'
});
}
});
}
/**
* Restores the original fixed styling of sticky elements after having closed an off-canvas that got pseudo fixed beforehand.
* This reverts the changes of _fixStickyElements()
* @private
*/
}, {
key: "_unfixStickyElements",
value: function _unfixStickyElements() {
this.$sticky.each(function (_, el) {
var $el = jquery__WEBPACK_IMPORTED_MODULE_0___default()(el);
var stickyData = $el.data('offCanvasSticky'); // If sticky element has got data object with prior values (meaning it was originally fixed) restore these values once off-canvas is closed
if (_typeof(stickyData) === 'object') {
$el.css({
top: "".concat(stickyData.top, "px"),
width: '',
transition: ''
});
$el.data('offCanvasSticky', '');
}
});
}
/**
* Handles the revealing/hiding the off-canvas at breakpoints, not the same as open.
* @param {Boolean} isRevealed - true if element should be revealed.
* @function
*/
}, {
key: "reveal",
value: function reveal(isRevealed) {
if (isRevealed) {
this.close();
this.isRevealed = true;
this.$element.attr('aria-hidden', 'false');
this.$element.off('open.zf.trigger toggle.zf.trigger');
this.$element.removeClass('is-closed');
} else {
this.isRevealed = false;
this.$element.attr('aria-hidden', 'true');
this.$element.off('open.zf.trigger toggle.zf.trigger').on({
'open.zf.trigger': this.open.bind(this),
'toggle.zf.trigger': this.toggle.bind(this)
});
this.$element.addClass('is-closed');
}
this._addContentClasses(isRevealed);
}
/**
* Stops scrolling of the body when OffCanvas is open on mobile Safari and other troublesome browsers.
* @function
* @private
*/
}, {
key: "_stopScrolling",
value: function _stopScrolling(event) {
return false;
}
/**
* Tag the element given as context whether it can be scrolled up and down.
* Used to allow or prevent it to scroll. See `_stopScrollPropagation`.
*
* Taken and adapted from http://stackoverflow.com/questions/16889447/prevent-full-page-scrolling-ios
* Only really works for y, not sure how to extend to x or if we need to.
*
* @function
* @private
*/
}, {
key: "_recordScrollable",
value: function _recordScrollable(event) {
var elem = this; // called from event handler context with this as elem
// If the element is scrollable (content overflows), then...
if (elem.scrollHeight !== elem.clientHeight) {
// If we're at the top, scroll down one pixel to allow scrolling up
if (elem.scrollTop === 0) {
elem.scrollTop = 1;
} // If we're at the bottom, scroll up one pixel to allow scrolling down
if (elem.scrollTop === elem.scrollHeight - elem.clientHeight) {
elem.scrollTop = elem.scrollHeight - elem.clientHeight - 1;
}
}
elem.allowUp = elem.scrollTop > 0;
elem.allowDown = elem.scrollTop < elem.scrollHeight - elem.clientHeight;
elem.lastY = event.originalEvent.pageY;
}
/**
* Prevent the given event propagation if the element given as context can scroll.
* Used to preserve the element scrolling on mobile (`touchmove`) when the document
* scrolling is prevented. See https://git.io/zf-9707.
* @function
* @private
*/
}, {
key: "_stopScrollPropagation",
value: function _stopScrollPropagation(event) {
var elem = this; // called from event handler context with this as elem
var parent; // off-canvas elem if called from inner scrollbox
var up = event.pageY < elem.lastY;
var down = !up;
elem.lastY = event.pageY;
if (up && elem.allowUp || down && elem.allowDown) {
// It is not recommended to stop event propagation (the user cannot watch it),
// but in this case this is the only solution we have.
event.stopPropagation(); // If elem is inner scrollbox we are scrolling the outer off-canvas down/up once the box end has been reached
// This lets the user continue to touch move the off-canvas without the need to place the finger outside the scrollbox
if (elem.hasAttribute('data-off-canvas-scrollbox')) {
parent = elem.closest('[data-off-canvas], [data-off-canvas-scrollbox-outer]');
if (elem.scrollTop <= 1 && parent.scrollTop > 0) {
parent.scrollTop--;
} else if (elem.scrollTop >= elem.scrollHeight - elem.clientHeight - 1 && parent.scrollTop < parent.scrollHeight - parent.clientHeight) {
parent.scrollTop++;
}
}
} else {
event.preventDefault();
}
}
/**
* Opens the off-canvas menu.
* @function
* @param {Object} event - Event object passed from listener.
* @param {jQuery} trigger - element that triggered the off-canvas to open.
* @fires OffCanvas#opened
* @todo also trigger 'open' event?
*/
}, {
key: "open",
value: function open(event, trigger) {
var _this4 = this;
if (this.$element.hasClass('is-open') || this.isRevealed || this.isInCanvas) {
return;
}
var _this = this;
if (trigger) {
this.$lastTrigger = trigger;
}
if (this.options.forceTo === 'top') {
window.scrollTo(0, 0);
} else if (this.options.forceTo === 'bottom') {
window.scrollTo(0, document.body.scrollHeight);
}
if (this.options.transitionTime && this.options.transition !== 'overlap') {
this.$element.siblings('[data-off-canvas-content]').css('transition-duration', this.options.transitionTime);
} else {
this.$element.siblings('[data-off-canvas-content]').css('transition-duration', '');
}
this.$element.addClass('is-open').removeClass('is-closed');
this.$triggers.attr('aria-expanded', 'true');
this.$element.attr('aria-hidden', 'false');
this.$content.addClass('is-open-' + this.position); // If `contentScroll` is set to false, add class and disable scrolling on touch devices.
if (this.options.contentScroll === false) {
jquery__WEBPACK_IMPORTED_MODULE_0___default()('body').addClass('is-off-canvas-open').on('touchmove', this._stopScrolling);
this.$element.on('touchstart', this._recordScrollable);
this.$element.on('touchmove', this._stopScrollPropagation);
this.$element.on('touchstart', '[data-off-canvas-scrollbox]', this._recordScrollable);
this.$element.on('touchmove', '[data-off-canvas-scrollbox]', this._stopScrollPropagation);
}
if (this.options.contentOverlay === true) {
this.$overlay.addClass('is-visible');
}
if (this.options.closeOnClick === true && this.options.contentOverlay === true) {
this.$overlay.addClass('is-closable');
}
if (this.options.autoFocus === true) {
this.$element.one(Object(_foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1__["transitionend"])(this.$element), function () {
if (!_this.$element.hasClass('is-open')) {
return; // exit if prematurely closed
}
var canvasFocus = _this.$element.find('[data-autofocus]');
if (canvasFocus.length) {
canvasFocus.eq(0).focus();
} else {
_this.$element.find('a, button').eq(0).focus();
}
});
}
if (this.options.trapFocus === true) {
this.$content.attr('tabindex', '-1');
_foundation_util_keyboard__WEBPACK_IMPORTED_MODULE_2__["Keyboard"].trapFocus(this.$element);
}
if (this.options.transition === 'push') {
this._fixStickyElements();
}
this._addContentClasses();
/**
* Fires when the off-canvas menu opens.
* @event OffCanvas#opened
*/
this.$element.trigger('opened.zf.offCanvas');
/**
* Fires when the off-canvas menu open transition is done.
* @event OffCanvas#openedEnd
*/
this.$element.one(Object(_foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1__["transitionend"])(this.$element), function () {
_this4.$element.trigger('openedEnd.zf.offCanvas');
});
}
/**
* Closes the off-canvas menu.
* @function
* @param {Function} cb - optional cb to fire after closure.
* @fires OffCanvas#close
* @fires OffCanvas#closed
*/
}, {
key: "close",
value: function close(cb) {
var _this5 = this;
if (!this.$element.hasClass('is-open') || this.isRevealed) {
return;
}
/**
* Fires when the off-canvas menu closes.
* @event OffCanvas#close
*/
this.$element.trigger('close.zf.offCanvas');
var _this = this;
this.$element.removeClass('is-open');
this.$element.attr('aria-hidden', 'true');
this.$content.removeClass('is-open-left is-open-top is-open-right is-open-bottom');
if (this.options.contentOverlay === true) {
this.$overlay.removeClass('is-visible');
}
if (this.options.closeOnClick === true && this.options.contentOverlay === true) {
this.$overlay.removeClass('is-closable');
}
this.$triggers.attr('aria-expanded', 'false'); // Listen to transitionEnd: add class, re-enable scrolling and release focus when done.
this.$element.one(Object(_foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1__["transitionend"])(this.$element), function (e) {
_this5.$element.addClass('is-closed');
_this5._removeContentClasses();
if (_this5.options.transition === 'push') {
_this5._unfixStickyElements();
} // If `contentScroll` is set to false, remove class and re-enable scrolling on touch devices.
if (_this5.options.contentScroll === false) {
jquery__WEBPACK_IMPORTED_MODULE_0___default()('body').removeClass('is-off-canvas-open').off('touchmove', _this5._stopScrolling);
_this5.$element.off('touchstart', _this5._recordScrollable);
_this5.$element.off('touchmove', _this5._stopScrollPropagation);
_this5.$element.off('touchstart', '[data-off-canvas-scrollbox]', _this5._recordScrollable);
_this5.$element.off('touchmove', '[data-off-canvas-scrollbox]', _this5._stopScrollPropagation);
}
if (_this5.options.trapFocus === true) {
_this5.$content.removeAttr('tabindex');
_foundation_util_keyboard__WEBPACK_IMPORTED_MODULE_2__["Keyboard"].releaseFocus(_this5.$element);
}
/**
* Fires when the off-canvas menu close transition is done.
* @event OffCanvas#closed
*/
_this5.$element.trigger('closed.zf.offCanvas');
});
}
/**
* Toggles the off-canvas menu open or closed.
* @function
* @param {Object} event - Event object passed from listener.
* @param {jQuery} trigger - element that triggered the off-canvas to open.
*/
}, {
key: "toggle",
value: function toggle(event, trigger) {
if (this.$element.hasClass('is-open')) {
this.close(event, trigger);
} else {
this.open(event, trigger);
}
}
/**
* Handles keyboard input when detected. When the escape key is pressed, the off-canvas menu closes, and focus is restored to the element that opened the menu.
* @function
* @private
*/
}, {
key: "_handleKeyboard",
value: function _handleKeyboard(e) {
var _this6 = this;
_foundation_util_keyboard__WEBPACK_IMPORTED_MODULE_2__["Keyboard"].handleKey(e, 'OffCanvas', {
close: function close() {
_this6.close();
_this6.$lastTrigger.focus();
return true;
},
handled: function handled() {
e.preventDefault();
}
});
}
/**
* Destroys the OffCanvas plugin.
* @function
*/
}, {
key: "_destroy",
value: function _destroy() {
this.close();
this.$element.off('.zf.trigger .zf.offCanvas');
this.$overlay.off('.zf.offCanvas');
if (this.onLoadListener) jquery__WEBPACK_IMPORTED_MODULE_0___default()(window).off(this.onLoadListener);
}
}]);
return OffCanvas;
}(_foundation_core_plugin__WEBPACK_IMPORTED_MODULE_1__["Plugin"]);
OffCanvas.defaults = {
/**
* Allow the user to click outside of the menu to close it.
* @option
* @type {boolean}
* @default true
*/
closeOnClick: true,
/**
* Adds an overlay on top of `[data-off-canvas-content]`.
* @option
* @type {boolean}
* @default true
*/
contentOverlay: true,
/**
* Target an off-canvas content container by ID that may be placed anywhere. If null the closest content container will be taken.
* @option
* @type {?string}
* @default null
*/
contentId: null,
/**
* Define the off-canvas element is nested in an off-canvas content. This is required when using the contentId option for a nested element.
* @option
* @type {boolean}
* @default null
*/
nested: null,
/**
* Enable/disable scrolling of the main content when an off canvas panel is open.
* @option
* @type {boolean}
* @default true
*/
contentScroll: true,
/**
* Amount of time the open and close transition requires, including the appropriate milliseconds (`ms`) or seconds (`s`) unit (e.g. `500ms`, `.75s`) If none selected, pulls from body style.
* @option
* @type {string}
* @default null
*/
transitionTime: null,
/**
* Type of transition for the OffCanvas menu. Options are 'push', 'detached' or 'slide'.
* @option
* @type {string}
* @default push
*/
transition: 'push',
/**
* Force the page to scroll to top or bottom on open.
* @option
* @type {?string}
* @default null
*/
forceTo: null,
/**
* Allow the OffCanvas to remain open for certain breakpoints.
* @option
* @type {boolean}
* @default false
*/
isRevealed: false,
/**
* Breakpoint at which to reveal. JS will use a RegExp to target standard classes, if changing classnames, pass your class with the `revealClass` option.
* @option
* @type {?string}
* @default null
*/
revealOn: null,
/**
* Breakpoint at which the off-canvas gets moved into canvas content and acts as regular page element.
* @option
* @type {?string}
* @default null
*/
inCanvasOn: null,
/**
* Force focus to the offcanvas on open. If true, will focus the opening trigger on close.
* @option
* @type {boolean}
* @default true
*/
autoFocus: true,
/**
* Class used to force an OffCanvas to remain open. Foundation defaults for this are `reveal-for-large` & `reveal-for-medium`.
* @option
* @type {string}
* @default reveal-for-
* @todo improve the regex testing for this.
*/
revealClass: 'reveal-for-',
/**
* Triggers optional focus trapping when opening an OffCanvas. Sets tabindex of [data-off-canvas-content] to -1 for accessibility purposes.
* @option
* @type {boolean}
* @default false
*/
trapFocus: false
};
/***/ }),
/***/ "./js/foundation.util.triggers.js":
/*!****************************************!*\
!*** ./js/foundation.util.triggers.js ***!
\****************************************/
/*! exports provided: Triggers */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Triggers", function() { return Triggers; });
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! jquery */ "jquery");
/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _foundation_core_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./foundation.core.utils */ "./foundation.core");
/* harmony import */ var _foundation_core_utils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_foundation_core_utils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _foundation_util_motion__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./foundation.util.motion */ "./foundation.util.motion");
/* harmony import */ var _foundation_util_motion__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_foundation_util_motion__WEBPACK_IMPORTED_MODULE_2__);
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var MutationObserver = function () {
var prefixes = ['WebKit', 'Moz', 'O', 'Ms', ''];
for (var i = 0; i < prefixes.length; i++) {
if ("".concat(prefixes[i], "MutationObserver") in window) {
return window["".concat(prefixes[i], "MutationObserver")];
}
}
return false;
}();
var triggers = function triggers(el, type) {
el.data(type).split(' ').forEach(function (id) {
jquery__WEBPACK_IMPORTED_MODULE_0___default()("#".concat(id))[type === 'close' ? 'trigger' : 'triggerHandler']("".concat(type, ".zf.trigger"), [el]);
});
};
var Triggers = {
Listeners: {
Basic: {},
Global: {}
},
Initializers: {}
};
Triggers.Listeners.Basic = {
openListener: function openListener() {
triggers(jquery__WEBPACK_IMPORTED_MODULE_0___default()(this), 'open');
},
closeListener: function closeListener() {
var id = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).data('close');
if (id) {
triggers(jquery__WEBPACK_IMPORTED_MODULE_0___default()(this), 'close');
} else {
jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).trigger('close.zf.trigger');
}
},
toggleListener: function toggleListener() {
var id = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).data('toggle');
if (id) {
triggers(jquery__WEBPACK_IMPORTED_MODULE_0___default()(this), 'toggle');
} else {
jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).trigger('toggle.zf.trigger');
}
},
closeableListener: function closeableListener(e) {
var animation = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).data('closable'); // Only close the first closable element. See https://git.io/zf-7833
e.stopPropagation();
if (animation !== '') {
_foundation_util_motion__WEBPACK_IMPORTED_MODULE_2__["Motion"].animateOut(jquery__WEBPACK_IMPORTED_MODULE_0___default()(this), animation, function () {
jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).trigger('closed.zf');
});
} else {
jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).fadeOut().trigger('closed.zf');
}
},
toggleFocusListener: function toggleFocusListener() {
var id = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).data('toggle-focus');
jquery__WEBPACK_IMPORTED_MODULE_0___default()("#".concat(id)).triggerHandler('toggle.zf.trigger', [jquery__WEBPACK_IMPORTED_MODULE_0___default()(this)]);
}
}; // Elements with [data-open] will reveal a plugin that supports it when clicked.
Triggers.Initializers.addOpenListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.openListener);
$elem.on('click.zf.trigger', '[data-open]', Triggers.Listeners.Basic.openListener);
}; // Elements with [data-close] will close a plugin that supports it when clicked.
// If used without a value on [data-close], the event will bubble, allowing it to close a parent component.
Triggers.Initializers.addCloseListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.closeListener);
$elem.on('click.zf.trigger', '[data-close]', Triggers.Listeners.Basic.closeListener);
}; // Elements with [data-toggle] will toggle a plugin that supports it when clicked.
Triggers.Initializers.addToggleListener = function ($elem) {
$elem.off('click.zf.trigger', Triggers.Listeners.Basic.toggleListener);
$elem.on('click.zf.trigger', '[data-toggle]', Triggers.Listeners.Basic.toggleListener);
}; // Elements with [data-closable] will respond to close.zf.trigger events.
Triggers.Initializers.addCloseableListener = function ($elem) {
$elem.off('close.zf.trigger', Triggers.Listeners.Basic.closeableListener);
$elem.on('close.zf.trigger', '[data-closeable], [data-closable]', Triggers.Listeners.Basic.closeableListener);
}; // Elements with [data-toggle-focus] will respond to coming in and out of focus
Triggers.Initializers.addToggleFocusListener = function ($elem) {
$elem.off('focus.zf.trigger blur.zf.trigger', Triggers.Listeners.Basic.toggleFocusListener);
$elem.on('focus.zf.trigger blur.zf.trigger', '[data-toggle-focus]', Triggers.Listeners.Basic.toggleFocusListener);
}; // More Global/complex listeners and triggers
Triggers.Listeners.Global = {
resizeListener: function resizeListener($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).triggerHandler('resizeme.zf.trigger');
});
} //trigger all listening elements and signal a resize event
$nodes.attr('data-events', "resize");
},
scrollListener: function scrollListener($nodes) {
if (!MutationObserver) {
//fallback for IE 9
$nodes.each(function () {
jquery__WEBPACK_IMPORTED_MODULE_0___default()(this).triggerHandler('scrollme.zf.trigger');
});
} //trigger all listening elements and signal a scroll event
$nodes.attr('data-events', "scroll");
},
closeMeListener: function closeMeListener(e, pluginId) {
var plugin = e.namespace.split('.')[0];
var plugins = jquery__WEBPACK_IMPORTED_MODULE_0___default()("[data-".concat(plugin, "]")).not("[data-yeti-box=\"".concat(pluginId, "\"]"));
plugins.each(function () {
var _this = jquery__WEBPACK_IMPORTED_MODULE_0___default()(this);
_this.triggerHandler('close.zf.trigger', [_this]);
});
} // Global, parses whole document.
};
Triggers.Initializers.addClosemeListener = function (pluginName) {
var yetiBoxes = jquery__WEBPACK_IMPORTED_MODULE_0___default()('[data-yeti-box]'),
plugNames = ['dropdown', 'tooltip', 'reveal'];
if (pluginName) {
if (typeof pluginName === 'string') {
plugNames.push(pluginName);
} else if (_typeof(pluginName) === 'object' && typeof pluginName[0] === 'string') {
plugNames = plugNames.concat(pluginName);
} else {
console.error('Plugin names must be strings');
}
}
if (yetiBoxes.length) {
var listeners = plugNames.map(function (name) {
return "closeme.zf.".concat(name);
}).join(' ');
jquery__WEBPACK_IMPORTED_MODULE_0___default()(window).off(listeners).on(listeners, Triggers.Listeners.Global.closeMeListener);
}
};
function debounceGlobalListener(debounce, trigger, listener) {
var timer,
args = Array.prototype.slice.call(arguments, 3);
jquery__WEBPACK_IMPORTED_MODULE_0___default()(window).off(trigger).on(trigger, function (e) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
listener.apply(null, args);
}, debounce || 10); //default time to emit scroll event
});
}
Triggers.Initializers.addResizeListener = function (debounce) {
var $nodes = jquery__WEBPACK_IMPORTED_MODULE_0___default()('[data-resize]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'resize.zf.trigger', Triggers.Listeners.Global.resizeListener, $nodes);
}
};
Triggers.Initializers.addScrollListener = function (debounce) {
var $nodes = jquery__WEBPACK_IMPORTED_MODULE_0___default()('[data-scroll]');
if ($nodes.length) {
debounceGlobalListener(debounce, 'scroll.zf.trigger', Triggers.Listeners.Global.scrollListener, $nodes);
}
};
Triggers.Initializers.addMutationEventsListener = function ($elem) {
if (!MutationObserver) {
return false;
}
var $nodes = $elem.find('[data-resize], [data-scroll], [data-mutate]'); //element callback
var listeningElementsMutation = function listeningElementsMutation(mutationRecordsList) {
var $target = jquery__WEBPACK_IMPORTED_MODULE_0___default()(mutationRecordsList[0].target); //trigger the event handler for the element depending on type
switch (mutationRecordsList[0].type) {
case "attributes":
if ($target.attr("data-events") === "scroll" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('scrollme.zf.trigger', [$target, window.pageYOffset]);
}
if ($target.attr("data-events") === "resize" && mutationRecordsList[0].attributeName === "data-events") {
$target.triggerHandler('resizeme.zf.trigger', [$target]);
}
if (mutationRecordsList[0].attributeName === "style") {
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
}
break;
case "childList":
$target.closest("[data-mutate]").attr("data-events", "mutate");
$target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]);
break;
default:
return false;
//nothing
}
};
if ($nodes.length) {
//for each element that needs to listen for resizing, scrolling, or mutation add a single observer
for (var i = 0; i <= $nodes.length - 1; i++) {
var elementObserver = new MutationObserver(listeningElementsMutation);
elementObserver.observe($nodes[i], {
attributes: true,
childList: true,
characterData: false,
subtree: true,
attributeFilter: ["data-events", "style"]
});
}
}
};
Triggers.Initializers.addSimpleListeners = function () {
var $document = jquery__WEBPACK_IMPORTED_MODULE_0___default()(document);
Triggers.Initializers.addOpenListener($document);
Triggers.Initializers.addCloseListener($document);
Triggers.Initializers.addToggleListener($document);
Triggers.Initializers.addCloseableListener($document);
Triggers.Initializers.addToggleFocusListener($document);
};
Triggers.Initializers.addGlobalListeners = function () {
var $document = jquery__WEBPACK_IMPORTED_MODULE_0___default()(document);
Triggers.Initializers.addMutationEventsListener($document);
Triggers.Initializers.addResizeListener();
Triggers.Initializers.addScrollListener();
Triggers.Initializers.addClosemeListener();
};
Triggers.init = function ($, Foundation) {
Object(_foundation_core_utils__WEBPACK_IMPORTED_MODULE_1__["onLoad"])($(window), function () {
if ($.triggersInitialized !== true) {
Triggers.Initializers.addSimpleListeners();
Triggers.Initializers.addGlobalListeners();
$.triggersInitialized = true;
}
});
if (Foundation) {
Foundation.Triggers = Triggers; // Legacy included to be backwards compatible for now.
Foundation.IHearYou = Triggers.Initializers.addGlobalListeners;
}
};
/***/ }),
/***/ 9:
/*!**********************************************************!*\
!*** multi ./js/entries/plugins/foundation.offcanvas.js ***!
\**********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! /Users/joeworkman/Development/foundation-sites/js/entries/plugins/foundation.offcanvas.js */"./js/entries/plugins/foundation.offcanvas.js");
/***/ }),
/***/ "jquery":
/*!********************************************************************************************!*\
!*** external {"root":["jQuery"],"amd":"jquery","commonjs":"jquery","commonjs2":"jquery"} ***!
\********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_jquery__;
/***/ })
/******/ });
});
//# sourceMappingURL=foundation.offcanvas.js.map
|
'use strict';
var async = require('async');
var validator = require('validator');
var user = require('../user');
var topics = require('../topics');
var pagination = require('../pagination');
var helpers = require('./helpers');
var tagsController = {};
tagsController.getTag = function (req, res, next) {
var tag = validator.escape(String(req.params.tag));
var page = parseInt(req.query.page, 10) || 1;
var templateData = {
topics: [],
tag: tag,
breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[tags:tags]]', url: '/tags' }, { text: tag }]),
title: '[[pages:tag, ' + tag + ']]',
};
var settings;
var topicCount = 0;
async.waterfall([
function (next) {
user.getSettings(req.uid, next);
},
function (_settings, next) {
settings = _settings;
var start = Math.max(0, (page - 1) * settings.topicsPerPage);
var stop = start + settings.topicsPerPage - 1;
templateData.nextStart = stop + 1;
async.parallel({
topicCount: function (next) {
topics.getTagTopicCount(tag, next);
},
tids: function (next) {
topics.getTagTids(req.params.tag, start, stop, next);
},
}, next);
},
function (results, next) {
if (Array.isArray(results.tids) && !results.tids.length) {
return res.render('tag', templateData);
}
topicCount = results.topicCount;
topics.getTopics(results.tids, req.uid, next);
},
], function (err, topics) {
if (err) {
return next(err);
}
res.locals.metaTags = [
{
name: 'title',
content: tag,
},
{
property: 'og:title',
content: tag,
},
];
templateData.topics = topics;
var pageCount = Math.max(1, Math.ceil(topicCount / settings.topicsPerPage));
templateData.pagination = pagination.create(page, pageCount);
res.render('tag', templateData);
});
};
tagsController.getTags = function (req, res, next) {
topics.getTags(0, 99, function (err, tags) {
if (err) {
return next(err);
}
tags = tags.filter(Boolean);
var data = {
tags: tags,
nextStart: 100,
breadcrumbs: helpers.buildBreadcrumbs([{ text: '[[tags:tags]]' }]),
title: '[[pages:tags]]',
};
res.render('tags', data);
});
};
module.exports = tagsController;
|
'use strict';
const isObj = require('is-obj');
const disallowedKeys = [
'__proto__',
'prototype',
'constructor'
];
const isValidPath = pathSegments => !pathSegments.some(segment => disallowedKeys.includes(segment));
function getPathSegments(path) {
const pathArray = path.split('.');
const parts = [];
for (let i = 0; i < pathArray.length; i++) {
let p = pathArray[i];
while (p[p.length - 1] === '\\' && pathArray[i + 1] !== undefined) {
p = p.slice(0, -1) + '.';
p += pathArray[++i];
}
parts.push(p);
}
if (!isValidPath(parts)) {
return [];
}
return parts;
}
module.exports = {
get(object, path, value) {
if (!isObj(object) || typeof path !== 'string') {
return value === undefined ? object : value;
}
const pathArray = getPathSegments(path);
if (pathArray.length === 0) {
return;
}
for (let i = 0; i < pathArray.length; i++) {
if (!Object.prototype.propertyIsEnumerable.call(object, pathArray[i])) {
return value;
}
object = object[pathArray[i]];
if (object === undefined || object === null) {
// `object` is either `undefined` or `null` so we want to stop the loop, and
// if this is not the last bit of the path, and
// if it did't return `undefined`
// it would return `null` if `object` is `null`
// but we want `get({foo: null}, 'foo.bar')` to equal `undefined`, or the supplied value, not `null`
if (i !== pathArray.length - 1) {
return value;
}
break;
}
}
return object;
},
set(object, path, value) {
if (!isObj(object) || typeof path !== 'string') {
return object;
}
const root = object;
const pathArray = getPathSegments(path);
for (let i = 0; i < pathArray.length; i++) {
const p = pathArray[i];
if (!isObj(object[p])) {
object[p] = {};
}
if (i === pathArray.length - 1) {
object[p] = value;
}
object = object[p];
}
return root;
},
delete(object, path) {
if (!isObj(object) || typeof path !== 'string') {
return false;
}
const pathArray = getPathSegments(path);
for (let i = 0; i < pathArray.length; i++) {
const p = pathArray[i];
if (i === pathArray.length - 1) {
delete object[p];
return true;
}
object = object[p];
if (!isObj(object)) {
return false;
}
}
},
has(object, path) {
if (!isObj(object) || typeof path !== 'string') {
return false;
}
const pathArray = getPathSegments(path);
if (pathArray.length === 0) {
return false;
}
// eslint-disable-next-line unicorn/no-for-loop
for (let i = 0; i < pathArray.length; i++) {
if (isObj(object)) {
if (!(pathArray[i] in object)) {
return false;
}
object = object[pathArray[i]];
} else {
return false;
}
}
return true;
}
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = rewriteLiveReferences;
function _assert() {
const data = _interopRequireDefault(require("assert"));
_assert = function () {
return data;
};
return data;
}
function t() {
const data = _interopRequireWildcard(require("@babel/types"));
t = function () {
return data;
};
return data;
}
function _template() {
const data = _interopRequireDefault(require("@babel/template"));
_template = function () {
return data;
};
return data;
}
function _helperSimpleAccess() {
const data = _interopRequireDefault(require("@babel/helper-simple-access"));
_helperSimpleAccess = function () {
return data;
};
return data;
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function rewriteLiveReferences(programPath, metadata) {
const imported = new Map();
const exported = new Map();
const requeueInParent = path => {
programPath.requeue(path);
};
for (const [source, data] of metadata.source) {
for (const [localName, importName] of data.imports) {
imported.set(localName, [source, importName, null]);
}
for (const localName of data.importsNamespace) {
imported.set(localName, [source, null, localName]);
}
}
for (const [local, data] of metadata.local) {
let exportMeta = exported.get(local);
if (!exportMeta) {
exportMeta = [];
exported.set(local, exportMeta);
}
exportMeta.push(...data.names);
}
programPath.traverse(rewriteBindingInitVisitor, {
metadata,
requeueInParent,
scope: programPath.scope,
exported
});
(0, _helperSimpleAccess().default)(programPath, new Set([...Array.from(imported.keys()), ...Array.from(exported.keys())]));
programPath.traverse(rewriteReferencesVisitor, {
seen: new WeakSet(),
metadata,
requeueInParent,
scope: programPath.scope,
imported,
exported,
buildImportReference: ([source, importName, localName], identNode) => {
const meta = metadata.source.get(source);
if (localName) {
if (meta.lazy) identNode = t().callExpression(identNode, []);
return identNode;
}
let namespace = t().identifier(meta.name);
if (meta.lazy) namespace = t().callExpression(namespace, []);
return t().memberExpression(namespace, t().identifier(importName));
}
});
}
const rewriteBindingInitVisitor = {
ClassProperty(path) {
path.skip();
},
Function(path) {
path.skip();
},
ClassDeclaration(path) {
const {
requeueInParent,
exported,
metadata
} = this;
const {
id
} = path.node;
if (!id) throw new Error("Expected class to have a name");
const localName = id.name;
const exportNames = exported.get(localName) || [];
if (exportNames.length > 0) {
const statement = t().expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t().identifier(localName)));
statement._blockHoist = path.node._blockHoist;
requeueInParent(path.insertAfter(statement)[0]);
}
},
VariableDeclaration(path) {
const {
requeueInParent,
exported,
metadata
} = this;
Object.keys(path.getOuterBindingIdentifiers()).forEach(localName => {
const exportNames = exported.get(localName) || [];
if (exportNames.length > 0) {
const statement = t().expressionStatement(buildBindingExportAssignmentExpression(metadata, exportNames, t().identifier(localName)));
statement._blockHoist = path.node._blockHoist;
requeueInParent(path.insertAfter(statement)[0]);
}
});
}
};
const buildBindingExportAssignmentExpression = (metadata, exportNames, localExpr) => {
return (exportNames || []).reduce((expr, exportName) => {
return t().assignmentExpression("=", t().memberExpression(t().identifier(metadata.exportName), t().identifier(exportName)), expr);
}, localExpr);
};
const buildImportThrow = localName => {
return _template().default.expression.ast`
(function() {
throw new Error('"' + '${localName}' + '" is read-only.');
})()
`;
};
const rewriteReferencesVisitor = {
ReferencedIdentifier(path) {
const {
seen,
buildImportReference,
scope,
imported,
requeueInParent
} = this;
if (seen.has(path.node)) return;
seen.add(path.node);
const localName = path.node.name;
const localBinding = path.scope.getBinding(localName);
const rootBinding = scope.getBinding(localName);
if (rootBinding !== localBinding) return;
const importData = imported.get(localName);
if (importData) {
const ref = buildImportReference(importData, path.node);
ref.loc = path.node.loc;
if (path.parentPath.isCallExpression({
callee: path.node
}) && t().isMemberExpression(ref)) {
path.replaceWith(t().sequenceExpression([t().numericLiteral(0), ref]));
} else if (path.isJSXIdentifier() && t().isMemberExpression(ref)) {
const {
object,
property
} = ref;
path.replaceWith(t().JSXMemberExpression(t().JSXIdentifier(object.name), t().JSXIdentifier(property.name)));
} else {
path.replaceWith(ref);
}
requeueInParent(path);
path.skip();
}
},
AssignmentExpression: {
exit(path) {
const {
scope,
seen,
imported,
exported,
requeueInParent,
buildImportReference
} = this;
if (seen.has(path.node)) return;
seen.add(path.node);
const left = path.get("left");
if (left.isIdentifier()) {
const localName = left.node.name;
if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
return;
}
const exportedNames = exported.get(localName) || [];
const importData = imported.get(localName);
if (exportedNames.length > 0 || importData) {
(0, _assert().default)(path.node.operator === "=", "Path was not simplified");
const assignment = path.node;
if (importData) {
assignment.left = buildImportReference(importData, assignment.left);
assignment.right = t().sequenceExpression([assignment.right, buildImportThrow(localName)]);
}
path.replaceWith(buildBindingExportAssignmentExpression(this.metadata, exportedNames, assignment));
requeueInParent(path);
}
} else if (left.isMemberExpression()) {} else {
const ids = left.getOuterBindingIdentifiers();
const id = Object.keys(ids).filter(localName => imported.has(localName)).pop();
if (id) {
path.node.right = t().sequenceExpression([path.node.right, buildImportThrow(id)]);
}
const items = [];
Object.keys(ids).forEach(localName => {
if (scope.getBinding(localName) !== path.scope.getBinding(localName)) {
return;
}
const exportedNames = exported.get(localName) || [];
if (exportedNames.length > 0) {
items.push(buildBindingExportAssignmentExpression(this.metadata, exportedNames, t().identifier(localName)));
}
});
if (items.length > 0) {
let node = t().sequenceExpression(items);
if (path.parentPath.isExpressionStatement()) {
node = t().expressionStatement(node);
node._blockHoist = path.parentPath.node._blockHoist;
}
const statement = path.insertAfter(node)[0];
requeueInParent(statement);
}
}
}
}
};
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("specialchar","tr",{euro:"Euro işareti",lsquo:"Sol tek tırnak işareti",rsquo:"Sağ tek tırnak işareti",ldquo:"Sol çift tırnak işareti",rdquo:"Sağ çift tırnak işareti",ndash:"En tire",mdash:"Em tire",iexcl:"Ters ünlem işareti",cent:"Cent işareti",pound:"Pound işareti",curren:"Para birimi işareti",yen:"Yen işareti",brvbar:"Kırık bar",sect:"Bölüm işareti",uml:"İki sesli harfin ayrılması",copy:"Telif hakkı işareti",ordf:"Dişil sıralı gösterge",laquo:"Sol-işaret çift açı tırnak işareti",
not:"Not işareti",reg:"Kayıtlı işareti",macr:"Makron",deg:"Derece işareti",sup2:"İkili üstsimge",sup3:"Üçlü üstsimge",acute:"Aksan işareti",micro:"Mikro işareti",para:"Pilcrow işareti",middot:"Orta nokta",cedil:"Kedilla",sup1:"Üstsimge",ordm:"Eril sıralı gösterge",raquo:"Sağ işaret çift açı tırnak işareti",frac14:"Bayağı kesrin dörtte biri",frac12:"Bayağı kesrin bir yarım",frac34:"Bayağı kesrin dörtte üç",iquest:"Ters soru işareti",Agrave:"Aksanlı latin harfi",Aacute:"Aşırı aksanıyla Latin harfi",
Acirc:"Çarpık Latin harfi",Atilde:"Tilde latin harfi",Auml:"Sesli harf ayrılımlıı latin harfi",Aring:"Halkalı latin büyük A harfi",AElig:"Latin büyük Æ harfi",Ccedil:"Latin büyük C harfi ile kedilla",Egrave:"Aksanlı latin büyük E harfi",Eacute:"Aşırı vurgulu latin büyük E harfi",Ecirc:"Çarpık latin büyük E harfi",Euml:"Sesli harf ayrılımlıı latin büyük E harfi",Igrave:"Aksanlı latin büyük I harfi",Iacute:"Aşırı aksanlı latin büyük I harfi",Icirc:"Çarpık latin büyük I harfi",Iuml:"Sesli harf ayrılımlıı latin büyük I harfi",
ETH:"Latin büyük Eth harfi",Ntilde:"Tildeli latin büyük N harfi",Ograve:"Aksanlı latin büyük O harfi",Oacute:"Aşırı aksanlı latin büyük O harfi",Ocirc:"Çarpık latin büyük O harfi",Otilde:"Tildeli latin büyük O harfi",Ouml:"Sesli harf ayrılımlı latin büyük O harfi",times:"Çarpma işareti",Oslash:"Vurgulu latin büyük O harfi",Ugrave:"Aksanlı latin büyük U harfi",Uacute:"Aşırı aksanlı latin büyük U harfi",Ucirc:"Çarpık latin büyük U harfi",Uuml:"Sesli harf ayrılımlı latin büyük U harfi",Yacute:"Aşırı aksanlı latin büyük Y harfi",
THORN:"Latin büyük Thorn harfi",szlig:"Latin küçük keskin s harfi",agrave:"Aksanlı latin küçük a harfi",aacute:"Aşırı aksanlı latin küçük a harfi",acirc:"Çarpık latin küçük a harfi",atilde:"Tildeli latin küçük a harfi",auml:"Sesli harf ayrılımlı latin küçük a harfi",aring:"Halkalı latin küçük a harfi",aelig:"Latin büyük æ harfi",ccedil:"Kedillalı latin küçük c harfi",egrave:"Aksanlı latin küçük e harfi",eacute:"Aşırı aksanlı latin küçük e harfi",ecirc:"Çarpık latin küçük e harfi",euml:"Sesli harf ayrılımlı latin küçük e harfi",
igrave:"Aksanlı latin küçük i harfi",iacute:"Aşırı aksanlı latin küçük i harfi",icirc:"Çarpık latin küçük i harfi",iuml:"Sesli harf ayrılımlı latin küçük i harfi",eth:"Latin küçük eth harfi",ntilde:"Tildeli latin küçük n harfi",ograve:"Aksanlı latin küçük o harfi",oacute:"Aşırı aksanlı latin küçük o harfi",ocirc:"Çarpık latin küçük o harfi",otilde:"Tildeli latin küçük o harfi",ouml:"Sesli harf ayrılımlı latin küçük o harfi",divide:"Bölme işareti",oslash:"Vurgulu latin küçük o harfi",ugrave:"Aksanlı latin küçük u harfi",
uacute:"Aşırı aksanlı latin küçük u harfi",ucirc:"Çarpık latin küçük u harfi",uuml:"Sesli harf ayrılımlı latin küçük u harfi",yacute:"Aşırı aksanlı latin küçük y harfi",thorn:"Latin küçük thorn harfi",yuml:"Sesli harf ayrılımlı latin küçük y harfi",OElig:"Latin büyük bağlı OE harfi",oelig:"Latin küçük bağlı oe harfi",372:"Çarpık latin büyük W harfi",374:"Çarpık latin büyük Y harfi",373:"Çarpık latin küçük w harfi",375:"Çarpık latin küçük y harfi",sbquo:"Tek düşük-9 tırnak işareti",8219:"Tek yüksek-ters-9 tırnak işareti",
bdquo:"Çift düşük-9 tırnak işareti",hellip:"Yatay elips",trade:"Marka tescili işareti",9658:"Siyah sağ işaret işaretçisi",bull:"Koyu nokta",rarr:"Sağa doğru ok",rArr:"Sağa doğru çift ok",hArr:"Sol, sağ çift ok",diams:"Siyah elmas takımı",asymp:"Hemen hemen eşit"});
|
/*
RequireJS text 1.0.7 Copyright (c) 2010-2011, The Dojo Foundation All Rights Reserved.
Available via the MIT or new BSD license.
see: http://github.com/jrburke/requirejs for details
*/
(function(){var k=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],n=/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,o=/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,i=typeof location!=="undefined"&&location.href,p=i&&location.protocol&&location.protocol.replace(/\:/,""),q=i&&location.hostname,r=i&&(location.port||void 0),j=[];define(function(){var g,h,l;typeof window!=="undefined"&&window.navigator&&window.document?h=function(a,c){var b=g.createXhr();b.open("GET",a,!0);b.onreadystatechange=
function(){b.readyState===4&&c(b.responseText)};b.send(null)}:typeof process!=="undefined"&&process.versions&&process.versions.node?(l=require.nodeRequire("fs"),h=function(a,c){var b=l.readFileSync(a,"utf8");b.indexOf("\ufeff")===0&&(b=b.substring(1));c(b)}):typeof Packages!=="undefined"&&(h=function(a,c){var b=new java.io.File(a),e=java.lang.System.getProperty("line.separator"),b=new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(b),"utf-8")),d,f,g="";try{d=new java.lang.StringBuffer;
(f=b.readLine())&&f.length()&&f.charAt(0)===65279&&(f=f.substring(1));for(d.append(f);(f=b.readLine())!==null;)d.append(e),d.append(f);g=String(d.toString())}finally{b.close()}c(g)});return g={version:"1.0.7",strip:function(a){if(a){var a=a.replace(n,""),c=a.match(o);c&&(a=c[1])}else a="";return a},jsEscape:function(a){return a.replace(/(['\\])/g,"\\$1").replace(/[\f]/g,"\\f").replace(/[\b]/g,"\\b").replace(/[\n]/g,"\\n").replace(/[\t]/g,"\\t").replace(/[\r]/g,"\\r")},createXhr:function(){var a,c,
b;if(typeof XMLHttpRequest!=="undefined")return new XMLHttpRequest;else for(c=0;c<3;c++){b=k[c];try{a=new ActiveXObject(b)}catch(e){}if(a){k=[b];break}}if(!a)throw Error("createXhr(): XMLHttpRequest not available");return a},get:h,parseName:function(a){var c=!1,b=a.indexOf("."),e=a.substring(0,b),a=a.substring(b+1,a.length),b=a.indexOf("!");b!==-1&&(c=a.substring(b+1,a.length),c=c==="strip",a=a.substring(0,b));return{moduleName:e,ext:a,strip:c}},xdRegExp:/^((\w+)\:)?\/\/([^\/\\]+)/,useXhr:function(a,
c,b,e){var d=g.xdRegExp.exec(a),f;if(!d)return!0;a=d[2];d=d[3];d=d.split(":");f=d[1];d=d[0];return(!a||a===c)&&(!d||d===b)&&(!f&&!d||f===e)},finishLoad:function(a,c,b,e,d){b=c?g.strip(b):b;d.isBuild&&(j[a]=b);e(b)},load:function(a,c,b,e){if(e.isBuild&&!e.inlineText)b();else{var d=g.parseName(a),f=d.moduleName+"."+d.ext,m=c.toUrl(f),h=e&&e.text&&e.text.useXhr||g.useXhr;!i||h(m,p,q,r)?g.get(m,function(c){g.finishLoad(a,d.strip,c,b,e)}):c([f],function(a){g.finishLoad(d.moduleName+"."+d.ext,d.strip,a,
b,e)})}},write:function(a,c,b){if(c in j){var e=g.jsEscape(j[c]);b.asModule(a+"!"+c,"define(function () { return '"+e+"';});\n")}},writeFile:function(a,c,b,e,d){var c=g.parseName(c),f=c.moduleName+"."+c.ext,h=b.toUrl(c.moduleName+"."+c.ext)+".js";g.load(f,b,function(){var b=function(a){return e(h,a)};b.asModule=function(a,b){return e.asModule(a,h,b)};g.write(a,f,b,d)},d)}}})})();
|
/** @jsx React.DOM */
var React = require('react');
var Router = require('react-router');
var Routes = Router.Routes;
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var ActiveState = Router.ActiveState;
var data = require('./data');
var CategoryNav = React.createClass({
getInitialState: function() {
return { isOpen: this.props.defaultIsOpen};
},
getDefaultProps: function() {
return { isOpen: false };
},
componentWillReceiveProps: function(newProps) {
if (!this.state.isOpen)
this.setState({isOpen: newProps.defaultIsOpen});
},
toggle: function() {
this.setState({isOpen: !this.state.isOpen});
},
buildToggleClassName: function() {
var toggleClassName = 'CategoryNav__Toggle';
if (this.state.isOpen)
toggleClassName += ' CategoryNav__Toggle--is-open';
return toggleClassName;
},
renderItems: function() {
var category = this.props.category;
return this.state.isOpen ? category.items.map(function(item) {
var params = { name: item.name, category: category.name };
return (
<li key={item.name}>
<Link to="item" params={params}>{item.name}</Link>
</li>
);
}) : null;
},
render: function() {
var category = this.props.category;
return (
<div className="CategoryNav">
<h3
className={this.buildToggleClassName()}
onClick={this.toggle}
>{category.name}</h3>
<ul>{this.renderItems()}</ul>
</div>
);
}
});
var Sidebar = React.createClass({
renderCategory: function(category) {
return <CategoryNav
key={category.name}
defaultIsOpen={category.name === this.props.activeCategory}
category={category}
/>;
},
render: function() {
return (
<div className="Sidebar">
{this.props.categories.map(this.renderCategory)}
</div>
);
}
});
var App = React.createClass({
mixins: [ActiveState],
render: function() {
var activeCategory = this.getActiveParams().category;
return (
<div>
<Sidebar activeCategory={activeCategory} categories={data.getAll()}/>
<div className="Content">
<this.props.activeRouteHandler />
</div>
</div>
);
}
});
var Item = React.createClass({
render: function() {
var params = this.props.params;
var category = data.lookupCategory(params.category);
var item = data.lookupItem(params.category, params.name);
return (
<div>
<h2>{category.name} / {item.name}</h2>
<p>Price: ${item.price}</p>
</div>
);
}
});
var Index = React.createClass({
render: function() {
return (
<div>
<p>Sidebar features:</p>
<ul style={{maxWidth: '400px'}}>
<li>User can open/close categories</li>
<li>
Visiting an item on first page load will automatically open
the correct category. (Click an item, then reload the
browser.)
</li>
<li>
Navigating with forward/back buttons will open an active
category if it is not already open. (Navigate to several
items, close all the categories, then use back/forward
buttons.)
</li>
<li>
Only the user can close a category. (Navigating from an
active category will not close it.)
</li>
</ul>
</div>
);
}
});
var routes = (
<Routes>
<Route handler={App}>
<DefaultRoute handler={Index}/>
<Route name="item" path=":category/:name" handler={Item} />
</Route>
</Routes>
);
React.renderComponent(routes, document.getElementById('example'));
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.10.2.11_A1_T7;
* @section: 15.10.2.11, 15.10.2.9;
* @assertion: DecimalEscape :: DecimalIntegerLiteral [lookahead not in DecimalDigit];
* @description: DecimalIntegerLiteral is not 0;
*/
var arr = /\1(A)(B)\2/.exec("ABB");
//CHECK#1
if ((arr === null) || (arr[0] !== "ABB")) {
$ERROR('#1: var arr = /\\1(A)(B)\\2/.exec("ABB"); arr[0] === "ABB". Actual. ' + (arr && arr[0]));
}
//CHECK#2
if ((arr === null) || (arr[1] !== "A")) {
$ERROR('#2: var arr = /\\1(A)(B)\\2/.exec("ABB"); arr[1] === "A". Actual. ' + (arr && arr[1]));
}
//CHECK#3
if ((arr === null) || (arr[2] !== "B")) {
$ERROR('#3: var arr = /\\1(A)(B)\\2/.exec("ABB"); arr[2] === "B". Actual. ' + (arr && arr[2]));
}
|
/*!
* Pikaday
*
* Copyright © 2014 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday
*/
(function (root, factory) {
'use strict';
var moment;
if (typeof exports === 'object') {
// CommonJS module
// Load moment.js as an optional dependency
try { moment = require('moment'); } catch (e) { }
module.exports = factory(moment);
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(function (req) {
// Load moment.js as an optional dependency
var id = 'moment';
moment = req.defined && req.defined(id) ? req(id) : undefined;
return factory(moment);
});
} else {
root.Pikaday = factory(root.moment);
}
}(this, function (moment) {
'use strict';
/**
* feature detection and helper functions
*/
var hasMoment = typeof moment === 'function',
hasEventListeners = !!window.addEventListener,
document = window.document,
sto = window.setTimeout,
addEvent = function (el, e, callback, capture) {
if (hasEventListeners) {
el.addEventListener(e, callback, !!capture);
} else {
el.attachEvent('on' + e, callback);
}
},
removeEvent = function (el, e, callback, capture) {
if (hasEventListeners) {
el.removeEventListener(e, callback, !!capture);
} else {
el.detachEvent('on' + e, callback);
}
},
fireEvent = function (el, eventName, data) {
var ev;
if (document.createEvent) {
ev = document.createEvent('HTMLEvents');
ev.initEvent(eventName, true, false);
ev = extend(ev, data);
el.dispatchEvent(ev);
} else if (document.createEventObject) {
ev = document.createEventObject();
ev = extend(ev, data);
el.fireEvent('on' + eventName, ev);
}
},
trim = function (str) {
return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, '');
},
hasClass = function (el, cn) {
return (' ' + el.className + ' ').indexOf(' ' + cn + ' ') !== -1;
},
addClass = function (el, cn) {
if (!hasClass(el, cn)) {
el.className = (el.className === '') ? cn : el.className + ' ' + cn;
}
},
removeClass = function (el, cn) {
el.className = trim((' ' + el.className + ' ').replace(' ' + cn + ' ', ' '));
},
isArray = function (obj) {
return (/Array/).test(Object.prototype.toString.call(obj));
},
isDate = function (obj) {
return (/Date/).test(Object.prototype.toString.call(obj)) && !isNaN(obj.getTime());
},
isLeapYear = function (year) {
// solution by Matti Virkkunen: http://stackoverflow.com/a/4881951
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
},
getDaysInMonth = function (year, month) {
return [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
setToStartOfDay = function (date) {
if (isDate(date)) date.setHours(0, 0, 0, 0);
},
compareDates = function (a, b) {
// weak date comparison (use setToStartOfDay(date) to ensure correct result)
return a.getTime() === b.getTime();
},
extend = function (to, from, overwrite) {
var prop, hasProp;
for (prop in from) {
hasProp = to[prop] !== undefined;
if (hasProp && typeof from[prop] === 'object' && from[prop].nodeName === undefined) {
if (isDate(from[prop])) {
if (overwrite) {
to[prop] = new Date(from[prop].getTime());
}
}
else if (isArray(from[prop])) {
if (overwrite) {
to[prop] = from[prop].slice(0);
}
} else {
to[prop] = extend({}, from[prop], overwrite);
}
} else if (overwrite || !hasProp) {
to[prop] = from[prop];
}
}
return to;
},
adjustCalendar = function (calendar) {
if (calendar.month < 0) {
calendar.year -= Math.ceil(Math.abs(calendar.month) / 12);
calendar.month += 12;
}
if (calendar.month > 11) {
calendar.year += Math.floor(Math.abs(calendar.month) / 12);
calendar.month -= 12;
}
return calendar;
},
/**
* defaults and localisation
*/
defaults = {
// bind the picker to a form field
field: null,
// automatically show/hide the picker on `field` focus (default `true` if `field` is set)
bound: undefined,
// position of the datepicker, relative to the field (default to bottom & left)
// ('bottom' & 'left' keywords are not used, 'top' & 'right' are modifier on the bottom/left position)
position: 'bottom left',
// the default output format for `.toString()` and `field` value
format: 'YYYY-MM-DD',
// the initial date to view when first opened
defaultDate: null,
// make the `defaultDate` the initial selected value
setDefaultDate: false,
// first day of week (0: Sunday, 1: Monday etc)
firstDay: 0,
// the minimum/earliest date that can be selected
minDate: null,
// the maximum/latest date that can be selected
maxDate: null,
// number of years either side, or array of upper/lower range
yearRange: 10,
// show week numbers at head of row
showWeekNumber: false,
// used internally (don't config outside)
minYear: 0,
maxYear: 9999,
minMonth: undefined,
maxMonth: undefined,
isRTL: false,
// Additional text to append to the year in the calendar title
yearSuffix: '',
// Render the month after year in the calendar title
showMonthAfterYear: false,
// how many months are visible
numberOfMonths: 1,
// when numberOfMonths is used, this will help you to choose where the main calendar will be (default `left`, can be set to `right`)
// only used for the first display or when a selected date is not visible
mainCalendar: 'left',
// Specify a DOM element to render the calendar in
container: undefined,
// internationalization
i18n: {
previousMonth: 'Previous Month',
nextMonth: 'Next Month',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
},
// callback function
onSelect: null,
onOpen: null,
onClose: null,
onDraw: null
},
/**
* templating functions to abstract HTML rendering
*/
renderDayName = function (opts, day, abbr) {
day += opts.firstDay;
while (day >= 7) {
day -= 7;
}
return abbr ? opts.i18n.weekdaysShort[day] : opts.i18n.weekdays[day];
},
renderDay = function (d, m, y, isSelected, isToday, isDisabled, isEmpty) {
if (isEmpty) {
return '<td class="is-empty"></td>';
}
var arr = [];
if (isDisabled) {
arr.push('is-disabled');
}
if (isToday) {
arr.push('is-today');
}
if (isSelected) {
arr.push('is-selected');
}
return '<td data-day="' + d + '" class="' + arr.join(' ') + '">' +
'<button class="pika-button pika-day" type="button" ' +
'data-pika-year="' + y + '" data-pika-month="' + m + '" data-pika-day="' + d + '">' +
d +
'</button>' +
'</td>';
},
renderWeek = function (d, m, y) {
// Lifted from http://javascript.about.com/library/blweekyear.htm, lightly modified.
var onejan = new Date(y, 0, 1),
weekNum = Math.ceil((((new Date(y, m, d) - onejan) / 86400000) + onejan.getDay() + 1) / 7);
return '<td class="pika-week">' + weekNum + '</td>';
},
renderRow = function (days, isRTL) {
return '<tr>' + (isRTL ? days.reverse() : days).join('') + '</tr>';
},
renderBody = function (rows) {
return '<tbody>' + rows.join('') + '</tbody>';
},
renderHead = function (opts) {
var i, arr = [];
if (opts.showWeekNumber) {
arr.push('<th></th>');
}
for (i = 0; i < 7; i++) {
arr.push('<th scope="col"><abbr title="' + renderDayName(opts, i) + '">' + renderDayName(opts, i, true) + '</abbr></th>');
}
return '<thead>' + (opts.isRTL ? arr.reverse() : arr).join('') + '</thead>';
},
renderTitle = function (instance, c, year, month, refYear) {
var i, j, arr,
opts = instance._o,
isMinYear = year === opts.minYear,
isMaxYear = year === opts.maxYear,
html = '<div class="pika-title">',
monthHtml,
yearHtml,
prev = true,
next = true;
for (arr = [], i = 0; i < 12; i++) {
arr.push('<option value="' + (year === refYear ? i - c : 12 + i - c) + '"' +
(i === month ? ' selected' : '') +
((isMinYear && i < opts.minMonth) || (isMaxYear && i > opts.maxMonth) ? 'disabled' : '') + '>' +
opts.i18n.months[i] + '</option>');
}
monthHtml = '<div class="pika-label">' + opts.i18n.months[month] + '<select class="pika-select pika-select-month">' + arr.join('') + '</select></div>';
if (isArray(opts.yearRange)) {
i = opts.yearRange[0];
j = opts.yearRange[1] + 1;
} else {
i = year - opts.yearRange;
j = 1 + year + opts.yearRange;
}
for (arr = []; i < j && i <= opts.maxYear; i++) {
if (i >= opts.minYear) {
arr.push('<option value="' + i + '"' + (i === year ? ' selected' : '') + '>' + (i) + '</option>');
}
}
yearHtml = '<div class="pika-label">' + year + opts.yearSuffix + '<select class="pika-select pika-select-year">' + arr.join('') + '</select></div>';
if (opts.showMonthAfterYear) {
html += yearHtml + monthHtml;
} else {
html += monthHtml + yearHtml;
}
if (isMinYear && (month === 0 || opts.minMonth >= month)) {
prev = false;
}
if (isMaxYear && (month === 11 || opts.maxMonth <= month)) {
next = false;
}
if (c === 0) {
html += '<button class="pika-prev' + (prev ? '' : ' is-disabled') + '" type="button">' + opts.i18n.previousMonth + '</button>';
}
if (c === (instance._o.numberOfMonths - 1)) {
html += '<button class="pika-next' + (next ? '' : ' is-disabled') + '" type="button">' + opts.i18n.nextMonth + '</button>';
}
return html += '</div>';
},
renderTable = function (opts, data) {
return '<table cellpadding="0" cellspacing="0" class="pika-table">' + renderHead(opts) + renderBody(data) + '</table>';
},
/**
* Pikaday constructor
*/
Pikaday = function (options) {
var self = this,
opts = self.config(options);
self._onMouseDown = function (e) {
if (!self._v) {
return;
}
e = e || window.event;
var target = e.target || e.srcElement;
if (!target) {
return;
}
if (!hasClass(target, 'is-disabled')) {
if (hasClass(target, 'pika-button') && !hasClass(target, 'is-empty')) {
self.setDate(new Date(target.getAttribute('data-pika-year'), target.getAttribute('data-pika-month'), target.getAttribute('data-pika-day')));
if (opts.bound) {
sto(function () {
self.hide();
if (opts.field) {
opts.field.blur();
}
}, 100);
}
return;
}
else if (hasClass(target, 'pika-prev')) {
self.prevMonth();
}
else if (hasClass(target, 'pika-next')) {
self.nextMonth();
}
}
if (!hasClass(target, 'pika-select')) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
return false;
}
} else {
self._c = true;
}
};
self._onChange = function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
if (!target) {
return;
}
if (hasClass(target, 'pika-select-month')) {
self.gotoMonth(target.value);
}
else if (hasClass(target, 'pika-select-year')) {
self.gotoYear(target.value);
}
};
self._onInputChange = function (e) {
var date;
if (e.firedBy === self) {
return;
}
if (hasMoment) {
date = moment(opts.field.value, opts.format);
date = (date && date.isValid()) ? date.toDate() : null;
}
else {
date = new Date(Date.parse(opts.field.value));
}
self.setDate(isDate(date) ? date : null);
if (!self._v) {
self.show();
}
};
self._onInputFocus = function () {
self.show();
};
self._onInputClick = function () {
self.show();
};
self._onInputBlur = function () {
if (!self._c) {
self._b = sto(function () {
self.hide();
}, 50);
}
self._c = false;
};
self._onClick = function (e) {
e = e || window.event;
var target = e.target || e.srcElement,
pEl = target;
if (!target) {
return;
}
if (!hasEventListeners && hasClass(target, 'pika-select')) {
if (!target.onchange) {
target.setAttribute('onchange', 'return;');
addEvent(target, 'change', self._onChange);
}
}
do {
if (hasClass(pEl, 'pika-single')) {
return;
}
}
while ((pEl = pEl.parentNode));
if (self._v && target !== opts.trigger) {
self.hide();
}
};
self.el = document.createElement('div');
self.el.className = 'pika-single' + (opts.isRTL ? ' is-rtl' : '');
addEvent(self.el, 'mousedown', self._onMouseDown, true);
addEvent(self.el, 'change', self._onChange);
if (opts.field) {
if (opts.container) {
opts.container.appendChild(self.el);
} else if (opts.bound) {
document.body.appendChild(self.el);
} else {
opts.field.parentNode.insertBefore(self.el, opts.field.nextSibling);
}
addEvent(opts.field, 'change', self._onInputChange);
if (!opts.defaultDate) {
if (hasMoment && opts.field.value) {
opts.defaultDate = moment(opts.field.value, opts.format).toDate();
} else {
opts.defaultDate = new Date(Date.parse(opts.field.value));
}
opts.setDefaultDate = true;
}
}
var defDate = opts.defaultDate;
if (isDate(defDate)) {
if (opts.setDefaultDate) {
self.setDate(defDate, true);
} else {
self.gotoDate(defDate);
}
} else {
self.gotoDate(new Date());
}
if (opts.bound) {
this.hide();
self.el.className += ' is-bound';
addEvent(opts.trigger, 'click', self._onInputClick);
addEvent(opts.trigger, 'focus', self._onInputFocus);
addEvent(opts.trigger, 'blur', self._onInputBlur);
} else {
this.show();
}
};
/**
* public Pikaday API
*/
Pikaday.prototype = {
/**
* configure functionality
*/
config: function (options) {
if (!this._o) {
this._o = extend({}, defaults, true);
}
var opts = extend(this._o, options, true);
opts.isRTL = !!opts.isRTL;
opts.field = (opts.field && opts.field.nodeName) ? opts.field : null;
opts.bound = !!(opts.bound !== undefined ? opts.field && opts.bound : opts.field);
opts.trigger = (opts.trigger && opts.trigger.nodeName) ? opts.trigger : opts.field;
var nom = parseInt(opts.numberOfMonths, 10) || 1;
opts.numberOfMonths = nom > 4 ? 4 : nom;
if (!isDate(opts.minDate)) {
opts.minDate = false;
}
if (!isDate(opts.maxDate)) {
opts.maxDate = false;
}
if ((opts.minDate && opts.maxDate) && opts.maxDate < opts.minDate) {
opts.maxDate = opts.minDate = false;
}
if (opts.minDate) {
setToStartOfDay(opts.minDate);
opts.minYear = opts.minDate.getFullYear();
opts.minMonth = opts.minDate.getMonth();
}
if (opts.maxDate) {
setToStartOfDay(opts.maxDate);
opts.maxYear = opts.maxDate.getFullYear();
opts.maxMonth = opts.maxDate.getMonth();
}
if (isArray(opts.yearRange)) {
var fallback = new Date().getFullYear() - 10;
opts.yearRange[0] = parseInt(opts.yearRange[0], 10) || fallback;
opts.yearRange[1] = parseInt(opts.yearRange[1], 10) || fallback;
} else {
opts.yearRange = Math.abs(parseInt(opts.yearRange, 10)) || defaults.yearRange;
if (opts.yearRange > 100) {
opts.yearRange = 100;
}
}
return opts;
},
/**
* return a formatted string of the current selection (using Moment.js if available)
*/
toString: function (format) {
return !isDate(this._d) ? '' : hasMoment ? moment(this._d).format(format || this._o.format) : this._d.toDateString();
},
/**
* return a Moment.js object of the current selection (if available)
*/
getMoment: function () {
return hasMoment ? moment(this._d) : null;
},
/**
* set the current selection from a Moment.js object (if available)
*/
setMoment: function (date, preventOnSelect) {
if (hasMoment && moment.isMoment(date)) {
this.setDate(date.toDate(), preventOnSelect);
}
},
/**
* return a Date object of the current selection
*/
getDate: function () {
return isDate(this._d) ? new Date(this._d.getTime()) : null;
},
/**
* set the current selection
*/
setDate: function (date, preventOnSelect) {
if (!date) {
this._d = null;
return this.draw();
}
if (typeof date === 'string') {
date = new Date(Date.parse(date));
}
if (!isDate(date)) {
return;
}
var min = this._o.minDate,
max = this._o.maxDate;
if (isDate(min) && date < min) {
date = min;
} else if (isDate(max) && date > max) {
date = max;
}
this._d = new Date(date.getTime());
setToStartOfDay(this._d);
this.gotoDate(this._d);
if (this._o.field) {
this._o.field.value = this.toString();
fireEvent(this._o.field, 'change', { firedBy: this });
}
if (!preventOnSelect && typeof this._o.onSelect === 'function') {
this._o.onSelect.call(this, this.getDate());
}
},
/**
* change view to a specific date
*/
gotoDate: function (date) {
var newCalendar = true;
if (!isDate(date)) {
return;
}
if (this.calendars) {
var firstVisibleDate = new Date(this.calendars[0].year, this.calendars[0].month, 1),
lastVisibleDate = new Date(this.calendars[this.calendars.length - 1].year, this.calendars[this.calendars.length - 1].month, 1),
visibleDate = date.getTime();
// get the end of the month
lastVisibleDate.setMonth(lastVisibleDate.getMonth() + 1);
lastVisibleDate.setDate(lastVisibleDate.getDate() - 1);
newCalendar = (visibleDate < firstVisibleDate.getTime() || lastVisibleDate.getTime() < visibleDate);
}
if (newCalendar) {
this.calendars = [{
month: date.getMonth(),
year: date.getFullYear()
}];
if (this._o.mainCalendar === 'right') {
this.calendars[0].month += 1 - this._o.numberOfMonths;
}
}
this.adjustCalendars();
},
adjustCalendars: function () {
this.calendars[0] = adjustCalendar(this.calendars[0]);
for (var c = 1; c < this._o.numberOfMonths; c++) {
this.calendars[c] = adjustCalendar({
month: this.calendars[0].month + c,
year: this.calendars[0].year
});
}
this.draw();
},
gotoToday: function () {
this.gotoDate(new Date());
},
/**
* change view to a specific month (zero-index, e.g. 0: January)
*/
gotoMonth: function (month) {
if (!isNaN(month)) {
this.calendars[0].month = parseInt(month, 10);
this.adjustCalendars();
}
},
nextMonth: function () {
this.calendars[0].month++;
this.adjustCalendars();
},
prevMonth: function () {
this.calendars[0].month--;
this.adjustCalendars();
},
/**
* change view to a specific full year (e.g. "2012")
*/
gotoYear: function (year) {
if (!isNaN(year)) {
this.calendars[0].year = parseInt(year, 10);
this.adjustCalendars();
}
},
/**
* change the minDate
*/
setMinDate: function (value) {
this._o.minDate = value;
},
/**
* change the maxDate
*/
setMaxDate: function (value) {
this._o.maxDate = value;
},
/**
* refresh the HTML
*/
draw: function (force) {
if (!this._v && !force) {
return;
}
var opts = this._o,
minYear = opts.minYear,
maxYear = opts.maxYear,
minMonth = opts.minMonth,
maxMonth = opts.maxMonth,
html = '';
if (this._y <= minYear) {
this._y = minYear;
if (!isNaN(minMonth) && this._m < minMonth) {
this._m = minMonth;
}
}
if (this._y >= maxYear) {
this._y = maxYear;
if (!isNaN(maxMonth) && this._m > maxMonth) {
this._m = maxMonth;
}
}
for (var c = 0; c < opts.numberOfMonths; c++) {
html += '<div class="pika-lendar">' + renderTitle(this, c, this.calendars[c].year, this.calendars[c].month, this.calendars[0].year) + this.render(this.calendars[c].year, this.calendars[c].month) + '</div>';
}
this.el.innerHTML = html;
if (opts.bound) {
if (opts.field.type !== 'hidden') {
sto(function () {
opts.trigger.focus();
}, 1);
}
}
if (typeof this._o.onDraw === 'function') {
var self = this;
sto(function () {
self._o.onDraw.call(self);
}, 0);
}
},
adjustPosition: function () {
if (this._o.container) return;
var field = this._o.trigger, pEl = field,
width = this.el.offsetWidth, height = this.el.offsetHeight,
viewportWidth = window.innerWidth || document.documentElement.clientWidth,
viewportHeight = window.innerHeight || document.documentElement.clientHeight,
scrollTop = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop,
left, top, clientRect;
if (typeof field.getBoundingClientRect === 'function') {
clientRect = field.getBoundingClientRect();
left = clientRect.left + window.pageXOffset;
top = clientRect.bottom + window.pageYOffset;
} else {
left = pEl.offsetLeft;
top = pEl.offsetTop + pEl.offsetHeight;
while ((pEl = pEl.offsetParent)) {
left += pEl.offsetLeft;
top += pEl.offsetTop;
}
}
// default position is bottom & left
if (left + width > viewportWidth ||
(
this._o.position.indexOf('right') > -1 &&
left - width + field.offsetWidth > 0
)
) {
left = left - width + field.offsetWidth;
}
if (top + height > viewportHeight + scrollTop ||
(
this._o.position.indexOf('top') > -1 &&
top - height - field.offsetHeight > 0
)
) {
top = top - height - field.offsetHeight;
}
this.el.style.cssText = [
'position: absolute',
'left: ' + left + 'px',
'top: ' + top + 'px'
].join(';');
},
/**
* render HTML for a particular month
*/
render: function (year, month) {
var opts = this._o,
now = new Date(),
days = getDaysInMonth(year, month),
before = new Date(year, month, 1).getDay(),
data = [],
row = [];
setToStartOfDay(now);
if (opts.firstDay > 0) {
before -= opts.firstDay;
if (before < 0) {
before += 7;
}
}
var cells = days + before,
after = cells;
while (after > 7) {
after -= 7;
}
cells += 7 - after;
for (var i = 0, r = 0; i < cells; i++) {
var day = new Date(year, month, 1 + (i - before)),
isDisabled = (opts.minDate && day < opts.minDate) || (opts.maxDate && day > opts.maxDate),
isSelected = isDate(this._d) ? compareDates(day, this._d) : false,
isToday = compareDates(day, now),
isEmpty = i < before || i >= (days + before);
row.push(renderDay(1 + (i - before), month, year, isSelected, isToday, isDisabled, isEmpty));
if (++r === 7) {
if (opts.showWeekNumber) {
row.unshift(renderWeek(i - before, month, year));
}
data.push(renderRow(row, opts.isRTL));
row = [];
r = 0;
}
}
return renderTable(opts, data);
},
isVisible: function () {
return this._v;
},
show: function () {
if (!this._v) {
removeClass(this.el, 'is-hidden');
this._v = true;
this.draw();
if (this._o.bound) {
addEvent(document, 'click', this._onClick);
this.adjustPosition();
}
if (typeof this._o.onOpen === 'function') {
this._o.onOpen.call(this);
}
}
},
hide: function () {
var v = this._v;
if (v !== false) {
if (this._o.bound) {
removeEvent(document, 'click', this._onClick);
}
this.el.style.cssText = '';
addClass(this.el, 'is-hidden');
this._v = false;
if (v !== undefined && typeof this._o.onClose === 'function') {
this._o.onClose.call(this);
}
}
},
/**
* GAME OVER
*/
destroy: function () {
this.hide();
removeEvent(this.el, 'mousedown', this._onMouseDown, true);
removeEvent(this.el, 'change', this._onChange);
if (this._o.field) {
removeEvent(this._o.field, 'change', this._onInputChange);
if (this._o.bound) {
removeEvent(this._o.trigger, 'click', this._onInputClick);
removeEvent(this._o.trigger, 'focus', this._onInputFocus);
removeEvent(this._o.trigger, 'blur', this._onInputBlur);
}
}
if (this.el.parentNode) {
this.el.parentNode.removeChild(this.el);
}
}
};
return Pikaday;
}));
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import { refType } from '@material-ui/utils';
import styled from '../styles/styled';
import useThemeProps from '../styles/useThemeProps';
import Input from '../Input';
import FilledInput from '../FilledInput';
import OutlinedInput from '../OutlinedInput';
import InputLabel from '../InputLabel';
import FormControl from '../FormControl';
import FormHelperText from '../FormHelperText';
import Select from '../Select';
import { getTextFieldUtilityClass } from './textFieldClasses';
import { jsxs as _jsxs } from "react/jsx-runtime";
import { jsx as _jsx } from "react/jsx-runtime";
var variantComponent = {
standard: Input,
filled: FilledInput,
outlined: OutlinedInput
};
var useUtilityClasses = function useUtilityClasses(styleProps) {
var classes = styleProps.classes;
var slots = {
root: ['root']
};
return composeClasses(slots, getTextFieldUtilityClass, classes);
};
var TextFieldRoot = styled(FormControl, {
name: 'MuiTextField',
slot: 'Root',
overridesResolver: function overridesResolver(props, styles) {
return styles.root;
}
})({});
/**
* The `TextField` is a convenience wrapper for the most common cases (80%).
* It cannot be all things to all people, otherwise the API would grow out of control.
*
* ## Advanced Configuration
*
* It's important to understand that the text field is a simple abstraction
* on top of the following components:
*
* - [FormControl](/api/form-control/)
* - [InputLabel](/api/input-label/)
* - [FilledInput](/api/filled-input/)
* - [OutlinedInput](/api/outlined-input/)
* - [Input](/api/input/)
* - [FormHelperText](/api/form-helper-text/)
*
* If you wish to alter the props applied to the `input` element, you can do so as follows:
*
* ```jsx
* const inputProps = {
* step: 300,
* };
*
* return <TextField id="time" type="time" inputProps={inputProps} />;
* ```
*
* For advanced cases, please look at the source of TextField by clicking on the
* "Edit this page" button above. Consider either:
*
* - using the upper case props for passing values directly to the components
* - using the underlying components directly as shown in the demos
*/
var TextField = /*#__PURE__*/React.forwardRef(function TextField(inProps, ref) {
var props = useThemeProps({
props: inProps,
name: 'MuiTextField'
});
var autoComplete = props.autoComplete,
_props$autoFocus = props.autoFocus,
autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,
children = props.children,
className = props.className,
_props$color = props.color,
color = _props$color === void 0 ? 'primary' : _props$color,
defaultValue = props.defaultValue,
_props$disabled = props.disabled,
disabled = _props$disabled === void 0 ? false : _props$disabled,
_props$error = props.error,
error = _props$error === void 0 ? false : _props$error,
FormHelperTextProps = props.FormHelperTextProps,
_props$fullWidth = props.fullWidth,
fullWidth = _props$fullWidth === void 0 ? false : _props$fullWidth,
helperText = props.helperText,
id = props.id,
InputLabelProps = props.InputLabelProps,
inputProps = props.inputProps,
InputProps = props.InputProps,
inputRef = props.inputRef,
label = props.label,
maxRows = props.maxRows,
minRows = props.minRows,
_props$multiline = props.multiline,
multiline = _props$multiline === void 0 ? false : _props$multiline,
name = props.name,
onBlur = props.onBlur,
onChange = props.onChange,
onFocus = props.onFocus,
placeholder = props.placeholder,
_props$required = props.required,
required = _props$required === void 0 ? false : _props$required,
rows = props.rows,
_props$select = props.select,
select = _props$select === void 0 ? false : _props$select,
SelectProps = props.SelectProps,
type = props.type,
value = props.value,
_props$variant = props.variant,
variant = _props$variant === void 0 ? 'outlined' : _props$variant,
other = _objectWithoutProperties(props, ["autoComplete", "autoFocus", "children", "className", "color", "defaultValue", "disabled", "error", "FormHelperTextProps", "fullWidth", "helperText", "id", "InputLabelProps", "inputProps", "InputProps", "inputRef", "label", "maxRows", "minRows", "multiline", "name", "onBlur", "onChange", "onFocus", "placeholder", "required", "rows", "select", "SelectProps", "type", "value", "variant"]);
var styleProps = _extends({}, props, {
autoFocus: autoFocus,
color: color,
disabled: disabled,
error: error,
fullWidth: fullWidth,
multiline: multiline,
required: required,
select: select,
variant: variant
});
var classes = useUtilityClasses(styleProps);
if (process.env.NODE_ENV !== 'production') {
if (select && !children) {
console.error('Material-UI: `children` must be passed when using the `TextField` component with `select`.');
}
}
var InputMore = {};
if (variant === 'outlined') {
if (InputLabelProps && typeof InputLabelProps.shrink !== 'undefined') {
InputMore.notched = InputLabelProps.shrink;
}
if (label) {
var _InputLabelProps$requ;
var displayRequired = (_InputLabelProps$requ = InputLabelProps == null ? void 0 : InputLabelProps.required) != null ? _InputLabelProps$requ : required;
InputMore.label = /*#__PURE__*/_jsxs(React.Fragment, {
children: [label, displayRequired && "\xA0*"]
});
}
}
if (select) {
// unset defaults from textbox inputs
if (!SelectProps || !SelectProps.native) {
InputMore.id = undefined;
}
InputMore['aria-describedby'] = undefined;
}
var helperTextId = helperText && id ? "".concat(id, "-helper-text") : undefined;
var inputLabelId = label && id ? "".concat(id, "-label") : undefined;
var InputComponent = variantComponent[variant];
var InputElement = /*#__PURE__*/_jsx(InputComponent, _extends({
"aria-describedby": helperTextId,
autoComplete: autoComplete,
autoFocus: autoFocus,
defaultValue: defaultValue,
fullWidth: fullWidth,
multiline: multiline,
name: name,
rows: rows,
maxRows: maxRows,
minRows: minRows,
type: type,
value: value,
id: id,
inputRef: inputRef,
onBlur: onBlur,
onChange: onChange,
onFocus: onFocus,
placeholder: placeholder,
inputProps: inputProps
}, InputMore, InputProps));
return /*#__PURE__*/_jsxs(TextFieldRoot, _extends({
className: clsx(classes.root, className),
disabled: disabled,
error: error,
fullWidth: fullWidth,
ref: ref,
required: required,
color: color,
variant: variant,
styleProps: styleProps
}, other, {
children: [label && /*#__PURE__*/_jsx(InputLabel, _extends({
htmlFor: id,
id: inputLabelId
}, InputLabelProps, {
children: label
})), select ? /*#__PURE__*/_jsx(Select, _extends({
"aria-describedby": helperTextId,
id: id,
labelId: inputLabelId,
value: value,
input: InputElement
}, SelectProps, {
children: children
})) : InputElement, helperText && /*#__PURE__*/_jsx(FormHelperText, _extends({
id: helperTextId
}, FormHelperTextProps, {
children: helperText
}))]
}));
});
process.env.NODE_ENV !== "production" ? TextField.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* This prop helps users to fill forms faster, especially on mobile devices.
* The name can be confusing, as it's more like an autofill.
* You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).
*/
autoComplete: PropTypes.string,
/**
* If `true`, the `input` element is focused during the first mount.
* @default false
*/
autoFocus: PropTypes.bool,
/**
* @ignore
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
* @default 'primary'
*/
color: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),
/**
* The default value. Use when the component is not controlled.
*/
defaultValue: PropTypes.any,
/**
* If `true`, the component is disabled.
* @default false
*/
disabled: PropTypes.bool,
/**
* If `true`, the label is displayed in an error state.
* @default false
*/
error: PropTypes.bool,
/**
* Props applied to the [`FormHelperText`](/api/form-helper-text/) element.
*/
FormHelperTextProps: PropTypes.object,
/**
* If `true`, the input will take up the full width of its container.
* @default false
*/
fullWidth: PropTypes.bool,
/**
* The helper text content.
*/
helperText: PropTypes.node,
/**
* The id of the `input` element.
* Use this prop to make `label` and `helperText` accessible for screen readers.
*/
id: PropTypes.string,
/**
* Props applied to the [`InputLabel`](/api/input-label/) element.
*/
InputLabelProps: PropTypes.object,
/**
* [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.
*/
inputProps: PropTypes.object,
/**
* Props applied to the Input element.
* It will be a [`FilledInput`](/api/filled-input/),
* [`OutlinedInput`](/api/outlined-input/) or [`Input`](/api/input/)
* component depending on the `variant` prop value.
*/
InputProps: PropTypes.object,
/**
* Pass a ref to the `input` element.
*/
inputRef: refType,
/**
* The label content.
*/
label: PropTypes.node,
/**
* If `dense` or `normal`, will adjust vertical spacing of this and contained components.
* @default 'none'
*/
margin: PropTypes.oneOf(['dense', 'none', 'normal']),
/**
* Maximum number of rows to display when multiline option is set to true.
*/
maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Minimum number of rows to display when multiline option is set to true.
*/
minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* If `true`, a `textarea` element is rendered instead of an input.
* @default false
*/
multiline: PropTypes.bool,
/**
* Name attribute of the `input` element.
*/
name: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* Callback fired when the value is changed.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* @ignore
*/
onFocus: PropTypes.func,
/**
* The short hint displayed in the `input` before the user enters a value.
*/
placeholder: PropTypes.string,
/**
* If `true`, the label is displayed as required and the `input` element is required.
* @default false
*/
required: PropTypes.bool,
/**
* Number of rows to display when multiline option is set to true.
*/
rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Render a [`Select`](/api/select/) element while passing the Input element to `Select` as `input` parameter.
* If this option is set you must pass the options of the select as children.
* @default false
*/
select: PropTypes.bool,
/**
* Props applied to the [`Select`](/api/select/) element.
*/
SelectProps: PropTypes.object,
/**
* The size of the component.
*/
size: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object,
/**
* Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).
*/
type: PropTypes.string,
/**
* The value of the `input` element, required for a controlled component.
*/
value: PropTypes.any,
/**
* The variant to use.
* @default 'outlined'
*/
variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])
} : void 0;
export default TextField;
|
describe('iD.Graph', function() {
describe("constructor", function () {
it("accepts an entities Array", function () {
var entity = iD.Entity(),
graph = iD.Graph([entity]);
expect(graph.entity(entity.id)).to.equal(entity);
});
it("accepts a Graph", function () {
var entity = iD.Entity(),
graph = iD.Graph(iD.Graph([entity]));
expect(graph.entity(entity.id)).to.equal(entity);
});
it("copies other's entities", function () {
var entity = iD.Entity(),
base = iD.Graph([entity]),
graph = iD.Graph(base);
expect(graph.entities).not.to.equal(base.entities);
});
it("rebases on other's base", function () {
var base = iD.Graph(),
graph = iD.Graph(base);
expect(graph.base().entities).to.equal(base.base().entities);
});
it("freezes by default", function () {
expect(iD.Graph().frozen).to.be.true;
});
it("remains mutable if passed true as second argument", function () {
expect(iD.Graph([], true).frozen).to.be.false;
});
});
describe("#hasEntity", function () {
it("returns the entity when present", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
expect(graph.hasEntity(node.id)).to.equal(node);
});
it("returns undefined when the entity is not present", function () {
expect(iD.Graph().hasEntity('1')).to.be.undefined;
});
});
describe("#entity", function () {
it("returns the entity when present", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
expect(graph.entity(node.id)).to.equal(node);
});
it("throws when the entity is not present", function () {
expect(function() { iD.Graph().entity('1'); }).to.throw;
});
});
describe("#rebase", function () {
it("preserves existing entities", function () {
var node = iD.Node({id: 'n'}),
graph = iD.Graph([node]);
graph.rebase([], [graph]);
expect(graph.entity('n')).to.equal(node);
});
it("includes new entities", function () {
var node = iD.Node({id: 'n'}),
graph = iD.Graph();
graph.rebase([node], [graph]);
expect(graph.entity('n')).to.equal(node);
});
it("doesn't rebase deleted entities", function () {
var node = iD.Node({id: 'n', visible: false}),
graph = iD.Graph();
graph.rebase([node], [graph]);
expect(graph.hasEntity('n')).to.be.not.ok;
});
it("gives precedence to existing entities", function () {
var a = iD.Node({id: 'n'}),
b = iD.Node({id: 'n'}),
graph = iD.Graph([a]);
graph.rebase([b], [graph]);
expect(graph.entity('n')).to.equal(a);
});
it("gives precedence to new entities when force = true", function () {
var a = iD.Node({id: 'n'}),
b = iD.Node({id: 'n'}),
graph = iD.Graph([a]);
graph.rebase([b], [graph], true);
expect(graph.entity('n')).to.equal(b);
});
it("inherits entities from base prototypally", function () {
var graph = iD.Graph();
graph.rebase([iD.Node({id: 'n'})], [graph]);
expect(graph.entities).not.to.have.ownProperty('n');
});
it("updates parentWays", function () {
var n = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w1', nodes: ['n']}),
w2 = iD.Way({id: 'w2', nodes: ['n']}),
graph = iD.Graph([n, w1]);
graph.rebase([w2], [graph]);
expect(graph.parentWays(n)).to.eql([w1, w2]);
expect(graph._parentWays.hasOwnProperty('n')).to.be.false;
});
it("avoids adding duplicate parentWays", function () {
var n = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w1', nodes: ['n']}),
graph = iD.Graph([n, w1]);
graph.rebase([w1], [graph]);
expect(graph.parentWays(n)).to.eql([w1]);
});
it("updates parentWays for nodes with modified parentWays", function () {
var n = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w1', nodes: ['n']}),
w2 = iD.Way({id: 'w2', nodes: ['n']}),
w3 = iD.Way({id: 'w3', nodes: ['n']}),
graph = iD.Graph([n, w1]),
graph2 = graph.replace(w2);
graph.rebase([w3], [graph, graph2]);
expect(graph2.parentWays(n)).to.eql([w1, w2, w3]);
});
it("avoids re-adding a modified way as a parent way", function() {
var n1 = iD.Node({id: 'n1'}),
n2 = iD.Node({id: 'n2'}),
w1 = iD.Way({id: 'w1', nodes: ['n1', 'n2']}),
w2 = w1.removeNode('n2'),
graph = iD.Graph([n1, n2, w1]),
graph2 = graph.replace(w2);
graph.rebase([w1], [graph, graph2]);
expect(graph2.parentWays(n2)).to.eql([]);
});
it("avoids re-adding a deleted way as a parent way", function() {
var n = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w1', nodes: ['n']}),
graph = iD.Graph([n, w1]),
graph2 = graph.remove(w1);
graph.rebase([w1], [graph, graph2]);
expect(graph2.parentWays(n)).to.eql([]);
});
it("re-adds a deleted node that is discovered to have another parent", function() {
var n = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w1', nodes: ['n']}),
w2 = iD.Way({id: 'w2', nodes: ['n']}),
graph = iD.Graph([n, w1]),
graph2 = graph.remove(n);
graph.rebase([n, w2], [graph, graph2]);
expect(graph2.entity('n')).to.eql(n);
});
it("updates parentRelations", function () {
var n = iD.Node({id: 'n'}),
r1 = iD.Relation({id: 'r1', members: [{id: 'n'}]}),
r2 = iD.Relation({id: 'r2', members: [{id: 'n'}]}),
graph = iD.Graph([n, r1]);
graph.rebase([r2], [graph]);
expect(graph.parentRelations(n)).to.eql([r1, r2]);
expect(graph._parentRels.hasOwnProperty('n')).to.be.false;
});
it("avoids re-adding a modified relation as a parent relation", function() {
var n = iD.Node({id: 'n'}),
r1 = iD.Relation({id: 'r1', members: [{id: 'n'}]}),
r2 = r1.removeMembersWithID('n'),
graph = iD.Graph([n, r1]),
graph2 = graph.replace(r2);
graph.rebase([r1], [graph, graph2]);
expect(graph2.parentRelations(n)).to.eql([]);
});
it("avoids re-adding a deleted relation as a parent relation", function() {
var n = iD.Node({id: 'n'}),
r1 = iD.Relation({id: 'r1', members: [{id: 'n'}]}),
graph = iD.Graph([n, r1]),
graph2 = graph.remove(r1);
graph.rebase([r1], [graph, graph2]);
expect(graph2.parentRelations(n)).to.eql([]);
});
it("updates parentRels for nodes with modified parentWays", function () {
var n = iD.Node({id: 'n'}),
r1 = iD.Relation({id: 'r1', members: [{id: 'n'}]}),
r2 = iD.Relation({id: 'r2', members: [{id: 'n'}]}),
r3 = iD.Relation({id: 'r3', members: [{id: 'n'}]}),
graph = iD.Graph([n, r1]),
graph2 = graph.replace(r2);
graph.rebase([r3], [graph, graph2]);
expect(graph2.parentRelations(n)).to.eql([r1, r2, r3]);
});
it("invalidates transients", function() {
var n = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w1', nodes: ['n']}),
w2 = iD.Way({id: 'w2', nodes: ['n']}),
graph = iD.Graph([n, w1]);
function numParents(entity) {
return graph.transient(entity, 'numParents', function() {
return graph.parentWays(entity).length;
});
}
expect(numParents(n)).to.equal(1);
graph.rebase([w2], [graph]);
expect(numParents(n)).to.equal(2);
});
});
describe("#remove", function () {
it("returns a new graph", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
expect(graph.remove(node)).not.to.equal(graph);
});
it("doesn't modify the receiver", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
graph.remove(node);
expect(graph.entity(node.id)).to.equal(node);
});
it("removes the entity from the result", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
expect(graph.remove(node).hasEntity(node.id)).to.be.undefined;
});
it("removes the entity as a parentWay", function () {
var node = iD.Node({id: 'n' }),
w1 = iD.Way({id: 'w', nodes: ['n']}),
graph = iD.Graph([node, w1]);
expect(graph.remove(w1).parentWays(node)).to.eql([]);
});
it("removes the entity as a parentRelation", function () {
var node = iD.Node({id: 'n' }),
r1 = iD.Relation({id: 'w', members: [{id: 'n' }]}),
graph = iD.Graph([node, r1]);
expect(graph.remove(r1).parentRelations(node)).to.eql([]);
});
});
describe("#replace", function () {
it("is a no-op if the replacement is identical to the existing entity", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
expect(graph.replace(node)).to.equal(graph);
});
it("returns a new graph", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
expect(graph.replace(node.update())).not.to.equal(graph);
});
it("doesn't modify the receiver", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
graph.replace(node);
expect(graph.entity(node.id)).to.equal(node);
});
it("replaces the entity in the result", function () {
var node1 = iD.Node(),
node2 = node1.update({}),
graph = iD.Graph([node1]);
expect(graph.replace(node2).entity(node2.id)).to.equal(node2);
});
it("adds parentWays", function () {
var node = iD.Node({id: 'n' }),
w1 = iD.Way({id: 'w', nodes: ['n']}),
graph = iD.Graph([node]);
expect(graph.replace(w1).parentWays(node)).to.eql([w1]);
});
it("removes parentWays", function () {
var node = iD.Node({id: 'n' }),
w1 = iD.Way({id: 'w', nodes: ['n']}),
graph = iD.Graph([node, w1]);
expect(graph.remove(w1).parentWays(node)).to.eql([]);
});
it("doesn't add duplicate parentWays", function () {
var node = iD.Node({id: 'n' }),
w1 = iD.Way({id: 'w', nodes: ['n']}),
graph = iD.Graph([node, w1]);
expect(graph.replace(w1).parentWays(node)).to.eql([w1]);
});
it("adds parentRelations", function () {
var node = iD.Node({id: 'n' }),
r1 = iD.Relation({id: 'r', members: [{id: 'n'}]}),
graph = iD.Graph([node]);
expect(graph.replace(r1).parentRelations(node)).to.eql([r1]);
});
it("removes parentRelations", function () {
var node = iD.Node({id: 'n' }),
r1 = iD.Relation({id: 'r', members: [{id: 'n'}]}),
graph = iD.Graph([node, r1]);
expect(graph.remove(r1).parentRelations(node)).to.eql([]);
});
it("doesn't add duplicate parentRelations", function () {
var node = iD.Node({id: 'n' }),
r1 = iD.Relation({id: 'r', members: [{id: 'n'}]}),
graph = iD.Graph([node, r1]);
expect(graph.replace(r1).parentRelations(node)).to.eql([r1]);
});
});
describe("#revert", function () {
it("is a no-op if the head entity is identical to the base entity", function () {
var n1 = iD.Node({id: 'n'}),
graph = iD.Graph([n1]);
expect(graph.revert('n')).to.equal(graph);
});
it("returns a new graph", function () {
var n1 = iD.Node({id: 'n'}),
n2 = n1.update({}),
graph = iD.Graph([n1]).replace(n2);
expect(graph.revert('n')).not.to.equal(graph);
});
it("doesn't modify the receiver", function () {
var n1 = iD.Node({id: 'n'}),
n2 = n1.update({}),
graph = iD.Graph([n1]).replace(n2);
graph.revert('n');
expect(graph.hasEntity('n')).to.equal(n2);
});
it("removes a new entity", function () {
var n1 = iD.Node({id: 'n'}),
graph = iD.Graph().replace(n1);
graph = graph.revert('n');
expect(graph.hasEntity('n')).to.be.undefined;
});
it("reverts an updated entity to the base version", function () {
var n1 = iD.Node({id: 'n'}),
n2 = n1.update({}),
graph = iD.Graph([n1]).replace(n2);
graph = graph.revert('n');
expect(graph.hasEntity('n')).to.equal(n1);
});
it("restores a deleted entity", function () {
var n1 = iD.Node({id: 'n'}),
graph = iD.Graph([n1]).remove(n1);
graph = graph.revert('n');
expect(graph.hasEntity('n')).to.equal(n1);
});
it("removes new parentWays", function () {
var n1 = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w', nodes: ['n']}),
graph = iD.Graph().replace(n1).replace(w1);
graph = graph.revert('w');
expect(graph.hasEntity('n')).to.equal(n1);
expect(graph.parentWays(n1)).to.eql([]);
});
it("removes new parentRelations", function () {
var n1 = iD.Node({id: 'n'}),
r1 = iD.Relation({id: 'r', members: [{id: 'n'}]}),
graph = iD.Graph().replace(n1).replace(r1);
graph = graph.revert('r');
expect(graph.hasEntity('n')).to.equal(n1);
expect(graph.parentRelations(n1)).to.eql([]);
});
it("reverts updated parentWays", function () {
var n1 = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w', nodes: ['n']}),
w2 = w1.removeNode('n'),
graph = iD.Graph([n1, w1]).replace(w2);
graph = graph.revert('w');
expect(graph.hasEntity('n')).to.equal(n1);
expect(graph.parentWays(n1)).to.eql([w1]);
});
it("reverts updated parentRelations", function () {
var n1 = iD.Node({id: 'n'}),
r1 = iD.Relation({id: 'r', members: [{id: 'n'}]}),
r2 = r1.removeMembersWithID('n'),
graph = iD.Graph([n1, r1]).replace(r2);
graph = graph.revert('r');
expect(graph.hasEntity('n')).to.equal(n1);
expect(graph.parentRelations(n1)).to.eql([r1]);
});
it("restores deleted parentWays", function () {
var n1 = iD.Node({id: 'n'}),
w1 = iD.Way({id: 'w', nodes: ['n']}),
graph = iD.Graph([n1, w1]).remove(w1);
graph = graph.revert('w');
expect(graph.hasEntity('n')).to.equal(n1);
expect(graph.parentWays(n1)).to.eql([w1]);
});
it("restores deleted parentRelations", function () {
var n1 = iD.Node({id: 'n'}),
r1 = iD.Relation({id: 'r', members: [{id: 'n'}]}),
graph = iD.Graph([n1, r1]).remove(r1);
graph = graph.revert('r');
expect(graph.hasEntity('n')).to.equal(n1);
expect(graph.parentRelations(n1)).to.eql([r1]);
});
});
describe("#update", function () {
it("returns a new graph if self is frozen", function () {
var graph = iD.Graph();
expect(graph.update()).not.to.equal(graph);
});
it("returns self if self is not frozen", function () {
var graph = iD.Graph([], true);
expect(graph.update()).to.equal(graph);
});
it("doesn't modify self is self is frozen", function () {
var node = iD.Node(),
graph = iD.Graph([node]);
graph.update(function (graph) { graph.remove(node); });
expect(graph.entity(node.id)).to.equal(node);
});
it("modifies self is self is not frozen", function () {
var node = iD.Node(),
graph = iD.Graph([node], true);
graph.update(function (graph) { graph.remove(node); });
expect(graph.hasEntity(node.id)).to.be.undefined;
});
it("executes all of the given functions", function () {
var a = iD.Node(),
b = iD.Node(),
graph = iD.Graph([a]);
graph = graph.update(
function (graph) { graph.remove(a); },
function (graph) { graph.replace(b); }
);
expect(graph.hasEntity(a.id)).to.be.undefined;
expect(graph.entity(b.id)).to.equal(b);
});
});
describe("#parentWays", function() {
it("returns an array of ways that contain the given node id", function () {
var node = iD.Node({id: "n1"}),
way = iD.Way({id: "w1", nodes: ["n1"]}),
graph = iD.Graph([node, way]);
expect(graph.parentWays(node)).to.eql([way]);
expect(graph.parentWays(way)).to.eql([]);
});
});
describe("#parentRelations", function() {
it("returns an array of relations that contain the given entity id", function () {
var node = iD.Node({id: "n1"}),
nonnode = iD.Node({id: "n2"}),
relation = iD.Relation({id: "r1", members: [{ id: "n1", role: 'from' }]}),
graph = iD.Graph([node, relation]);
expect(graph.parentRelations(node)).to.eql([relation]);
expect(graph.parentRelations(nonnode)).to.eql([]);
});
});
describe("#childNodes", function () {
it("returns an array of child nodes", function () {
var node = iD.Node({id: "n1"}),
way = iD.Way({id: "w1", nodes: ["n1"]}),
graph = iD.Graph([node, way]);
expect(graph.childNodes(way)).to.eql([node]);
});
});
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.9.5_A4.1_T1;
* @section: 11.9.5, 11.9.6;
* @assertion: If x or y is NaN, return true;
* @description: x is NaN;
*/
//CHECK#1
if (!(Number.NaN !== true)) {
$ERROR('#1: NaN !== true');
}
//CHECK#2
if (!(Number.NaN !== 1)) {
$ERROR('#2: NaN !== 1');
}
//CHECK#3
if (!(Number.NaN !== Number.NaN)) {
$ERROR('#3: NaN !== NaN');
}
//CHECK#4
if (!(Number.NaN !== Number.POSITIVE_INFINITY)) {
$ERROR('#4: NaN !== +Infinity');
}
//CHECK#5
if (!(Number.NaN !== Number.NEGATIVE_INFINITY)) {
$ERROR('#5: NaN !== -Infinity');
}
//CHECK#6
if (!(Number.NaN !== Number.MAX_VALUE)) {
$ERROR('#6: NaN !== Number.MAX_VALUE');
}
//CHECK#7
if (!(Number.NaN !== Number.MIN_VALUE)) {
$ERROR('#7: NaN !== Number.MIN_VALUE');
}
//CHECK#8
if (!(Number.NaN !== "string")) {
$ERROR('#8: NaN !== "string"');
}
//CHECK#9
if (!(Number.NaN !== new Object())) {
$ERROR('#9: NaN !== new Object()');
}
|
// silly custom pseudo just for tests
Q.pseudos.humanoid = function(e, v) { return Q.is(e, 'li:contains(human)') || Q.is(e, 'ol:contains(human)') }
var hasQSA = !!document.querySelectorAll
, sinkSuite = function (label, suite) {
sink(label + (hasQSA ? ' [qSA]' : ''), function () {
hasQSA && Q.configure({ useNativeQSA: true })
suite.apply(null, arguments)
})
hasQSA && sink(label + ' [non-QSA]', function () {
Q.configure({ useNativeQSA: false })
suite.apply(null, arguments)
})
}
sinkSuite('Contexts', function (test, ok) {
test('should be able to pass optional context', 2, function () {
ok(Q('.a').length === 3, 'no context found 3 elements (.a)');
ok(Q('.a', Q('#boosh')).length === 2, 'context found 2 elements (#boosh .a)');
});
test('should be able to pass string as context', 5, function() {
ok(Q('.a', '#boosh').length == 2, 'context found 2 elements(.a, #boosh)');
ok(Q('.a', '.a').length == 0, 'context found 0 elements(.a, .a)');
ok(Q('.a', '.b').length == 1, 'context found 1 elements(.a, .b)');
ok(Q('.a', '#boosh .b').length == 1, 'context found 1 elements(.a, #boosh .b)');
ok(Q('.b', '#boosh .b').length == 0, 'context found 0 elements(.b, #boosh .b)');
});
test('should be able to pass qwery result as context', 5, function() {
ok(Q('.a', Q('#boosh')).length == 2, 'context found 2 elements(.a, #boosh)');
ok(Q('.a', Q('.a')).length == 0, 'context found 0 elements(.a, .a)');
ok(Q('.a', Q('.b')).length == 1, 'context found 1 elements(.a, .b)');
ok(Q('.a', Q('#boosh .b')).length == 1, 'context found 1 elements(.a, #boosh .b)');
ok(Q('.b', Q('#boosh .b')).length == 0, 'context found 0 elements(.b, #boosh .b)');
});
test('should not return duplicates from combinators', 2, function () {
ok(Q('#boosh,#boosh').length == 1, 'two booshes dont make a thing go right');
ok(Q('#boosh,.apples,#boosh').length == 1, 'two booshes and an apple dont make a thing go right');
});
test('byId sub-queries within context', 6, function() {
ok(Q('#booshTest', Q('#boosh')).length == 1, 'found "#id #id"')
ok(Q('.a.b #booshTest', Q('#boosh')).length == 1, 'found ".class.class #id"')
ok(Q('.a>#booshTest', Q('#boosh')).length == 1, 'found ".class>#id"')
ok(Q('>.a>#booshTest', Q('#boosh')).length == 1, 'found ">.class>#id"')
ok(!Q('#boosh', Q('#booshTest')).length, 'shouldn\'t find #boosh (ancestor) within #booshTest (descendent)')
ok(!Q('#boosh', Q('#lonelyBoosh')).length, 'shouldn\'t find #boosh within #lonelyBoosh (unrelated)')
})
})
sinkSuite('CSS 1', function (test, ok) {
test('get element by id', 2, function () {
var result = Q('#boosh');
ok(!!result[0], 'found element with id=boosh');
ok(!!Q('h1')[0], 'found 1 h1');
});
test('byId sub-queries', 4, function() {
ok(Q('#boosh #booshTest').length == 1, 'found "#id #id"')
ok(Q('.a.b #booshTest').length == 1, 'found ".class.class #id"')
ok(Q('#boosh>.a>#booshTest').length == 1, 'found "#id>.class>#id"')
ok(Q('.a>#booshTest').length == 1, 'found ".class>#id"')
})
test('get elements by class', 6, function () {
ok(Q('#boosh .a').length == 2, 'found two elements');
ok(!!Q('#boosh div.a')[0], 'found one element');
ok(Q('#boosh div').length == 2, 'found two {div} elements');
ok(!!Q('#boosh span')[0], 'found one {span} element');
ok(!!Q('#boosh div div')[0], 'found a single div');
ok(Q('a.odd').length == 1, 'found single a');
});
test('combos', 1, function () {
ok(Q('#boosh div,#boosh span').length == 3, 'found 2 divs and 1 span');
});
test('class with dashes', 1, function() {
ok(Q('.class-with-dashes').length == 1, 'found something');
});
test('should ignore comment nodes', 1, function() {
ok(Q('#boosh *').length === 4, 'found only 4 elements under #boosh')
});
test('deep messy relationships', 6, function() {
// these are mostly characterised by a combination of tight relationships and loose relationships
// on the right side of the query it's easy to find matches but they tighten up quickly as you
// go to the left
// they are useful for making sure the dom crawler doesn't stop short or over-extend as it works
// up the tree the crawl needs to be comprehensive
ok(Q('div#fixtures > div a').length == 5, 'found four results for "div#fixtures > div a"')
ok(Q('.direct-descend > .direct-descend .lvl2').length == 1, 'found one result for ".direct-descend > .direct-descend .lvl2"')
ok(Q('.direct-descend > .direct-descend div').length == 1, 'found one result for ".direct-descend > .direct-descend div"')
ok(Q('.direct-descend > .direct-descend div').length == 1, 'found one result for ".direct-descend > .direct-descend div"')
ok(Q('div#fixtures div ~ a div').length == 0, 'found no results for odd query')
ok(Q('.direct-descend > .direct-descend > .direct-descend ~ .lvl2').length == 0, 'found no results for another odd query')
});
});
sinkSuite('CSS 2', function (test, ok) {
test('get elements by attribute', 4, function () {
var wanted = Q('#boosh div[test]')[0];
var expected = document.getElementById('booshTest');
ok(wanted == expected, 'found attribute');
ok(Q('#boosh div[test=fg]')[0] == expected, 'found attribute with value');
ok(Q('em[rel~="copyright"]').length == 1, 'found em[rel~="copyright"]');
ok(Q('em[nopass~="copyright"]').length == 0, 'found em[nopass~="copyright"]');
});
test('should not throw error by attribute selector', 1, function () {
ok(Q('[foo^="bar"]').length === 1, 'found 1 element');
});
test('crazy town', 1, function () {
var el = document.getElementById('attr-test3');
ok(Q('div#attr-test3.found.you[title="whatup duders"]')[0] == el, 'found the right element');
});
});
sinkSuite('attribute selectors', function (test, ok, b, a, assert) {
/* CSS 2 SPEC */
test('[attr]', 1, function () {
var expected = document.getElementById('attr-test-1');
ok(Q('#attributes div[unique-test]')[0] == expected, 'found attribute with [attr]');
});
test('[attr=val]', 3, function () {
var expected = document.getElementById('attr-test-2');
ok(Q('#attributes div[test="two-foo"]')[0] == expected, 'found attribute with =');
ok(Q("#attributes div[test='two-foo']")[0] == expected, 'found attribute with =');
ok(Q('#attributes div[test=two-foo]')[0] == expected, 'found attribute with =');
});
test('[attr~=val]', 1, function () {
var expected = document.getElementById('attr-test-3');
ok(Q('#attributes div[test~=three]')[0] == expected, 'found attribute with ~=');
});
test('[attr|=val]', 2, function () {
var expected = document.getElementById('attr-test-2');
ok(Q('#attributes div[test|="two-foo"]')[0] == expected, 'found attribute with |=');
ok(Q('#attributes div[test|=two]')[0] == expected, 'found attribute with |=');
});
test('[href=#x] special case', 1, function () {
var expected = document.getElementById('attr-test-4');
ok(Q('#attributes a[href="#aname"]')[0] == expected, 'found attribute with href=#x');
});
/* CSS 3 SPEC */
test('[attr^=val]', 1, function () {
var expected = document.getElementById('attr-test-2');
ok(Q('#attributes div[test^=two]')[0] == expected, 'found attribute with ^=');
});
test('[attr$=val]', 1, function () {
var expected = document.getElementById('attr-test-2');
ok(Q('#attributes div[test$=foo]')[0] == expected, 'found attribute with $=');
});
test('[attr*=val]', 1, function () {
var expected = document.getElementById('attr-test-3');
ok(Q('#attributes div[test*=hree]')[0] == expected, 'found attribute with *=');
});
test('direct descendants', 2, function () {
ok(Q('#direct-descend > .direct-descend').length == 2, 'found two direct descendents');
ok(Q('#direct-descend > .direct-descend > .lvl2').length == 3, 'found three second-level direct descendents');
});
test('sibling elements', 17, function () {
assert(Q('#sibling-selector ~ .sibling-selector').length, 2, 'found two siblings')
assert(Q('#sibling-selector ~ div.sibling-selector').length, 2, 'found two siblings')
assert(Q('#sibling-selector + div.sibling-selector').length, 1, 'found one sibling')
assert(Q('#sibling-selector + .sibling-selector').length, 1, 'found one sibling')
assert(Q('.parent .oldest ~ .sibling').length, 4, 'found four younger siblings')
assert(Q('.parent .middle ~ .sibling').length, 2, 'found two younger siblings')
assert(Q('.parent .middle ~ h4').length, 1, 'found next sibling by tag')
assert(Q('.parent .middle ~ h4.younger').length, 1, 'found next sibling by tag and class')
assert(Q('.parent .middle ~ h3').length, 0, 'an element can\'t be its own sibling')
assert(Q('.parent .middle ~ h2').length, 0, 'didn\'t find an older sibling')
assert(Q('.parent .youngest ~ .sibling').length, 0, 'found no younger siblings')
assert(Q('.parent .oldest + .sibling').length, 1, 'found next sibling')
assert(Q('.parent .middle + .sibling').length, 1, 'found next sibling')
assert(Q('.parent .middle + h4').length, 1, 'found next sibling by tag')
assert(Q('.parent .middle + h3').length, 0, 'an element can\'t be its own sibling')
assert(Q('.parent .middle + h2').length, 0, 'didn\'t find an older sibling')
assert(Q('.parent .youngest + .sibling').length, 0, 'found no younger siblings')
});
});
sinkSuite('Uniq', function (test, ok) {
test('duplicates arent found in arrays', 2, function () {
ok(Q.uniq(['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']).length == 5, 'result should be a, b, c, d, e')
ok(Q.uniq(['a', 'b', 'c', 'c', 'c']).length == 3, 'result should be a, b, c')
})
})
sinkSuite('element-context queries', function(test, ok) {
test('relationship-first queries', 5, function() {
var pass = false
try { pass = Q('> .direct-descend', Q('#direct-descend')).length == 2 } catch (e) { }
ok(pass, 'found two direct descendents using > first');
pass = false
try { pass = Q('~ .sibling-selector', Q('#sibling-selector')).length == 2 } catch (e) { }
ok(pass, 'found two siblings with ~ first')
pass = false
try { pass = Q('+ .sibling-selector', Q('#sibling-selector')).length == 1 } catch (e) { }
ok(pass, 'found one sibling with + first')
pass = false
var ctx = Q('.idless')[0]
try { pass = Q('> .tokens a', ctx).length == 1 } catch (e) { }
ok(pass, 'found one sibling from a root with no id')
ok(!ctx.getAttribute('id'), 'root element used for selection still has no id')
})
// should be able to query on an element that hasn't been inserted into the dom
var frag = document.createElement('div')
frag.innerHTML = '<div class="d i v"><p id="oooo"><em></em><em id="emem"></em></p></div><p id="sep"><div class="a"><span></span></div></p>'
test('detached fragments', 2, function() {
ok(Q('.a span', frag).length == 1, 'should find child elements of fragment')
ok(Q('> div p em', frag).length == 2, 'should find child elements of fragment, relationship first')
})
test('byId sub-queries within detached fragment', 6, function () {
ok(Q('#emem', frag).length == 1, 'found "#id" in fragment')
ok(Q('.d.i #emem', frag).length == 1, 'found ".class.class #id" in fragment')
ok(Q('.d #oooo #emem', frag).length == 1, 'found ".class #id #id" in fragment')
ok(Q('> div #oooo', frag).length == 1, 'found "> .class #id" in fragment')
ok(!Q('#oooo', Q('#emem', frag)).length, 'shouldn\'t find #oooo (ancestor) within #emem (descendent)')
ok(!Q('#sep', Q('#emem', frag)).length, 'shouldn\'t find #sep within #emem (unrelated)')
})
test('exclude self in match', 1, function() {
ok(Q('.order-matters', Q('#order-matters')).length == 4, 'should not include self in element-context queries')
});
// because form's have .length
test('forms can be used as contexts', 1, function() {
ok(Q('*', Q('form')[0]).length === 3, 'found 3 elements under <form>')
})
})
sinkSuite('tokenizer', function (test, ok) {
test('should not get weird tokens', 5, function () {
ok(Q('div .tokens[title="one"]')[0] == document.getElementById('token-one'), 'found div .tokens[title="one"]');
ok(Q('div .tokens[title="one two"]')[0] == document.getElementById('token-two'), 'found div .tokens[title="one two"]');
ok(Q('div .tokens[title="one two three #%"]')[0] == document.getElementById('token-three'), 'found div .tokens[title="one two three #%"]');
ok(Q("div .tokens[title='one two three #%'] a")[0] == document.getElementById('token-four'), 'found div .tokens[title=\'one two three #%\'] a');
ok(Q('div .tokens[title="one two three #%"] a[href$=foo] div')[0] == document.getElementById('token-five'), 'found div .tokens[title="one two three #%"] a[href=foo] div');
});
});
sinkSuite('interesting syntaxes', function (test, ok) {
test('should parse bad selectors', 1, function () {
ok(Q('#spaced-tokens p em a').length, 'found element with funny tokens')
});
});
sinkSuite('order matters', function (test, ok) {
function tag(el) {
return el.tagName.toLowerCase();
}
// <div id="order-matters">
// <p class="order-matters"></p>
// <a class="order-matters">
// <em class="order-matters"></em><b class="order-matters"></b>
// </a>
// </div>
test('the order of elements return matters', 4, function () {
var els = Q('#order-matters .order-matters');
ok(tag(els[0]) == 'p', 'first element matched is a {p} tag');
ok(tag(els[1]) == 'a', 'first element matched is a {a} tag');
ok(tag(els[2]) == 'em', 'first element matched is a {em} tag');
ok(tag(els[3]) == 'b', 'first element matched is a {b} tag');
});
});
sinkSuite('pseudo-selectors', function (test, ok) {
test(':contains', 4, function() {
ok(Q('li:contains(humans)').length == 1, 'found by "element:contains(text)"')
ok(Q(':contains(humans)').length == 5, 'found by ":contains(text)", including all ancestors')
// * is an important case, can cause weird errors
ok(Q('*:contains(humans)').length == 5, 'found by "*:contains(text)", including all ancestors')
ok(Q('ol:contains(humans)').length == 1, 'found by "ancestor:contains(text)"')
})
test(':not', 1, function() {
ok(Q('.odd:not(div)').length == 1, 'found one .odd :not an <a>')
})
test(':first-child', 2, function () {
ok(Q('#pseudos div:first-child')[0] == document.getElementById('pseudos').getElementsByTagName('*')[0], 'found first child')
ok(Q('#pseudos div:first-child').length == 1, 'found only 1')
});
test(':last-child', 2, function () {
var all = document.getElementById('pseudos').getElementsByTagName('div');
ok(Q('#pseudos div:last-child')[0] == all[all.length - 1], 'found last child')
ok(Q('#pseudos div:last-child').length == 1, 'found only 1')
});
test('ol > li[attr="boosh"]:last-child', 2, function () {
var expected = document.getElementById('attr-child-boosh');
ok(Q('ol > li[attr="boosh"]:last-child').length == 1, 'only 1 element found');
ok(Q('ol > li[attr="boosh"]:last-child')[0] == expected, 'found correct element');
});
test(':nth-child(odd|even|x)', 4, function () {
var second = document.getElementById('pseudos').getElementsByTagName('div')[1];
ok(Q('#pseudos :nth-child(odd)').length == 4, 'found 4 odd elements');
ok(Q('#pseudos div:nth-child(odd)').length == 3, 'found 3 odd elements with div tag');
ok(Q('#pseudos div:nth-child(even)').length == 3, 'found 3 even elements with div tag');
ok(Q('#pseudos div:nth-child(2)')[0] == second, 'found 2nd nth-child of pseudos');
});
test(':nth-child(expr)', 6, function () {
var fifth = document.getElementById('pseudos').getElementsByTagName('a')[0];
var sixth = document.getElementById('pseudos').getElementsByTagName('div')[4];
ok(Q('#pseudos :nth-child(3n+1)').length == 3, 'found 3 elements');
ok(Q('#pseudos :nth-child(3n-2)').length == 3, 'found 3 elements'); // was +3n-2 but older safari no likey +
ok(Q('#pseudos :nth-child(-n+6)').length == 6, 'found 6 elements');
ok(Q('#pseudos :nth-child(-n+5)').length == 5, 'found 5 elements');
ok(Q('#pseudos :nth-child(3n+2)')[1] == fifth, 'second :nth-child(3n+2) is the fifth child');
ok(Q('#pseudos :nth-child(3n)')[1] == sixth, 'second :nth-child(3n) is the sixth child');
});
test(':nth-last-child(odd|even|x)', 4, function () {
var second = document.getElementById('pseudos').getElementsByTagName('div')[1];
ok(Q('#pseudos :nth-last-child(odd)').length == 4, 'found 4 odd elements');
ok(Q('#pseudos div:nth-last-child(odd)').length == 3, 'found 3 odd elements with div tag');
ok(Q('#pseudos div:nth-last-child(even)').length == 3, 'found 3 even elements with div tag');
ok(Q('#pseudos div:nth-last-child(6)')[0] == second, '6th nth-last-child should be 2nd of 7 elements');
});
test(':nth-last-child(expr)', 5, function () {
var third = document.getElementById('pseudos').getElementsByTagName('div')[2];
ok(Q('#pseudos :nth-last-child(3n+1)').length == 3, 'found 3 elements');
ok(Q('#pseudos :nth-last-child(3n-2)').length == 3, 'found 3 elements');
ok(Q('#pseudos :nth-last-child(-n+6)').length == 6, 'found 6 elements');
ok(Q('#pseudos :nth-last-child(-n+5)').length == 5, 'found 5 elements');
ok(Q('#pseudos :nth-last-child(3n+2)')[0] == third, 'first :nth-last-child(3n+2) is the third child');
});
test(':nth-of-type(expr)', 6, function () {
var a = document.getElementById('pseudos').getElementsByTagName('a')[0];
ok(Q('#pseudos div:nth-of-type(3n+1)').length == 2, 'found 2 div elements');
ok(Q('#pseudos a:nth-of-type(3n+1)').length == 1, 'found 1 a element');
ok(Q('#pseudos a:nth-of-type(3n+1)')[0] == a, 'found the right a element');
ok(Q('#pseudos a:nth-of-type(3n)').length == 0, 'no matches for every third a');
ok(Q('#pseudos a:nth-of-type(odd)').length == 1, 'found the odd a');
ok(Q('#pseudos a:nth-of-type(1)').length == 1, 'found the first a');
});
test(':nth-last-of-type(expr)', 3, function () {
var second = document.getElementById('pseudos').getElementsByTagName('div')[1];
ok(Q('#pseudos div:nth-last-of-type(3n+1)').length == 2, 'found 2 div elements');
ok(Q('#pseudos a:nth-last-of-type(3n+1)').length == 1, 'found 1 a element');
ok(Q('#pseudos div:nth-last-of-type(5)')[0] == second, '5th nth-last-of-type should be 2nd of 7 elements');
});
test(':first-of-type', 2, function () {
ok(Q('#pseudos a:first-of-type')[0] == document.getElementById('pseudos').getElementsByTagName('a')[0], 'found first a element')
ok(Q('#pseudos a:first-of-type').length == 1, 'found only 1')
});
test(':last-of-type', 2, function () {
var all = document.getElementById('pseudos').getElementsByTagName('div');
ok(Q('#pseudos div:last-of-type')[0] == all[all.length - 1], 'found last div element')
ok(Q('#pseudos div:last-of-type').length == 1, 'found only 1')
});
test(':only-of-type', 2, function () {
ok(Q('#pseudos a:only-of-type')[0] == document.getElementById('pseudos').getElementsByTagName('a')[0], 'found the only a element')
ok(Q('#pseudos a:first-of-type').length == 1, 'found only 1')
});
test(':target', 2, function () {
location.hash = '';
ok(Q('#pseudos:target').length == 0, '#pseudos is not the target');
location.hash = '#pseudos';
ok(Q('#pseudos:target').length == 1, 'now #pseudos is the target');
location.hash = '';
});
test('custom pseudos', 1, function() {
// :humanoid implemented just for testing purposes
ok(Q(':humanoid').length == 2, 'selected using custom pseudo')
});
});
sinkSuite('argument types', function (test, ok) {
test('should be able to pass in nodes as arguments', 5, function () {
var el = document.getElementById('boosh');
ok(Q(el)[0] == el, 'Q(el)[0] == el');
ok(Q(el, 'body')[0] == el, "Q(el, 'body')[0] == el");
ok(Q(el, document)[0] == el, "Q(el, document)[0] == el");
ok(Q(window)[0] == window, 'Q(window)[0] == window');
ok(Q(document)[0] == document, 'Q(document)[0] == document');
});
test('should be able to pass in an array of results as arguments', 5, function () {
var el = document.getElementById('boosh');
var result = Q([Q('#boosh'), Q(document), Q(window)]);
ok(result.length == 3, '3 elements in the combined set');
ok(result[0] == el, "result[0] == el");
ok(result[1] == document, "result[0] == document");
ok(result[2] == window, 'result[0] == window');
ok(Q([Q('#pseudos div.odd'), Q('#pseudos div.even')]).length == 6, 'found all the odd and even divs');
});
});
sinkSuite('is()', function (test, ok) {
var el = document.getElementById('attr-child-boosh');
test('simple selectors', 9, function () {
ok(Q.is(el, 'li'), 'tag');
ok(Q.is(el, '*'), 'wildcard');
ok(Q.is(el, '#attr-child-boosh'), '#id');
ok(Q.is(el, '[attr]'), '[attr]');
ok(Q.is(el, '[attr=boosh]'), '[attr=val]');
ok(!Q.is(el, 'div'), 'wrong tag');
ok(!Q.is(el, '#foo'), 'wrong #id');
ok(!Q.is(el, '[foo]'), 'wrong [attr]');
ok(!Q.is(el, '[attr=foo]'), 'wrong [attr=val]');
});
test('selector sequences', 2, function () {
ok(Q.is(el, 'li#attr-child-boosh[attr=boosh]'), 'tag#id[attr=val]');
ok(!Q.is(el, 'div#attr-child-boosh[attr=boosh]'), 'wrong tag#id[attr=val]');
});
test('selector sequences combinators', 7, function () {
ok(Q.is(el, 'ol li'), 'tag tag');
ok(Q.is(el, 'ol>li'), 'tag>tag');
ok(Q.is(el, 'ol>li+li'), 'tab>tag+tag');
ok(Q.is(el, 'ol#list li#attr-child-boosh[attr=boosh]'), 'tag#id tag#id[attr=val]');
ok(!Q.is(el, 'ol#list>li#attr-child-boosh[attr=boosh]'), 'wrong tag#id>tag#id[attr=val]');
ok(Q.is(el, 'ol ol li#attr-child-boosh[attr=boosh]'), 'tag tag tag#id[attr=val]');
ok(Q.is(Q('#token-four')[0], 'div#fixtures>div a'), 'tag#id>tag tag where ambiguous middle tag requires backtracking');
});
test('pseudos', 4, function() {
//TODO: more tests!
ok(Q.is(el, 'li:contains(hello)'), 'matching :contains(text)')
ok(!Q.is(el, 'li:contains(human)'), 'non-matching :contains(text)')
ok(Q.is(Q('#list>li')[2], ':humanoid'), 'matching custom pseudo')
ok(!Q.is(Q('#list>li')[1], ':humanoid'), 'non-matching custom pseudo')
})
test('context', 2, function () {
ok(Q.is(el, 'li#attr-child-boosh[attr=boosh]', Q('#list')[0]), 'context');
ok(!Q.is(el, 'ol#list li#attr-child-boosh[attr=boosh]', Q('#boosh')[0]), 'wrong context');
});
});
sinkSuite('selecting elements in other documents', function (test, ok) {
var doc = document.getElementById('frame').contentWindow.document
doc.body.innerHTML =
'<div id="hsoob">' +
'<div class="a b">' +
'<div class="d e sib" test="fg" id="booshTest"><p><span id="spanny"></span></p></div>' +
'<em nopass="copyrighters" rel="copyright booshrs" test="f g" class="sib"></em>' +
'<span class="h i a sib"></span>' +
'</div>' +
'<p class="odd"></p>' +
'</div>' +
'<div id="lonelyHsoob"></div>'
test('get element by id', 1, function () {
var result = Q('#hsoob', doc);
ok(!!result[0], 'found element with id=hsoob');
});
test('get elements by class', 6, function () {
ok(Q('#hsoob .a', doc).length == 2, 'found two elements');
ok(!!Q('#hsoob div.a', doc)[0], 'found one element');
ok(Q('#hsoob div', doc).length == 2, 'found two {div} elements');
ok(!!Q('#hsoob span', doc)[0], 'found one {span} element');
ok(!!Q('#hsoob div div', doc)[0], 'found a single div');
ok(Q('p.odd', doc).length == 1, 'found single br');
});
test('complex selectors', 4, function () {
ok(Q('.d ~ .sib', doc).length === 2, 'found one ~ sibling')
ok(Q('.a .d + .sib', doc).length === 1, 'found 2 + siblings')
ok(Q('#hsoob > div > .h', doc).length === 1, 'found span using child selectors')
ok(Q('.a .d ~ .sib[test="f g"]', doc).length === 1, 'found 1 ~ sibling with test attribute')
});
test('byId sub-queries', 3, function () {
ok(Q('#hsoob #spanny', doc).length == 1, 'found "#id #id" in frame')
ok(Q('.a #spanny', doc).length == 1, 'found ".class #id" in frame')
ok(Q('.a #booshTest #spanny', doc).length == 1, 'found ".class #id #id" in frame')
//ok(Q('> #hsoob', doc).length == 1, 'found "> #id" in frame') --> would be good to support this, needs some tweaking though
})
test('byId sub-queries within sub-context', 6, function () {
ok(Q('#spanny', Q('#hsoob', doc)).length == 1, 'found "#id -> #id" in frame')
ok(Q('.a #spanny', Q('#hsoob', doc)).length == 1, 'found ".class #id" in frame')
ok(Q('.a #booshTest #spanny', Q('#hsoob', doc)).length == 1, 'found ".class #id #id" in frame')
ok(Q('.a > #booshTest', Q('#hsoob', doc)).length == 1, 'found "> .class #id" in frame')
ok(!Q('#booshTest', Q('#spanny', doc)).length, 'shouldn\'t find #booshTest (ancestor) within #spanny (descendent)')
ok(!Q('#booshTest', Q('#lonelyHsoob', doc)).length, 'shouldn\'t find #booshTest within #lonelyHsoob (unrelated)')
})
});
start();
|
import Ember from 'ember';
import ValidationEngine from 'ghost/mixins/validation-engine';
import {request as ajax} from 'ic-ajax';
export default Ember.Controller.extend(ValidationEngine, {
submitting: false,
loggingIn: false,
ghostPaths: Ember.inject.service('ghost-paths'),
notifications: Ember.inject.service(),
flowErrors: '',
// ValidationEngine settings
validationType: 'signin',
actions: {
authenticate: function () {
var self = this,
model = this.get('model'),
authStrategy = 'simple-auth-authenticator:oauth2-password-grant',
data = model.getProperties('identification', 'password');
this.get('session').authenticate(authStrategy, data).then(function () {
self.toggleProperty('loggingIn');
}).catch(function (err) {
self.toggleProperty('loggingIn');
if (err.errors) {
self.set('flowErrors', err.errors[0].message.string);
if (err.errors[0].message.string.match(/no user with that email/)) {
self.get('model.errors').add('identification', '');
}
if (err.errors[0].message.string.match(/password is incorrect/)) {
self.get('model.errors').add('password', '');
}
}
// if authentication fails a rejected promise will be returned.
// it needs to be caught so it doesn't generate an exception in the console,
// but it's actually "handled" by the sessionAuthenticationFailed action handler.
});
},
validateAndAuthenticate: function () {
var self = this;
this.set('flowErrors', '');
// Manually trigger events for input fields, ensuring legacy compatibility with
// browsers and password managers that don't send proper events on autofill
$('#login').find('input').trigger('change');
this.validate({property: 'signin'}).then(function () {
self.toggleProperty('loggingIn');
self.send('authenticate');
}).catch(function (error) {
if (error) {
self.get('notifications').showAPIError(error);
} else {
self.set('flowErrors', 'Please fill out the form to sign in.');
}
});
},
forgotten: function () {
var email = this.get('model.identification'),
notifications = this.get('notifications'),
self = this;
this.set('flowErrors', '');
this.validate({property: 'forgotPassword'}).then(function () {
self.toggleProperty('submitting');
ajax({
url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
type: 'POST',
data: {
passwordreset: [{
email: email
}]
}
}).then(function () {
self.toggleProperty('submitting');
notifications.showAlert('Please check your email for instructions.', {type: 'info'});
}).catch(function (resp) {
self.toggleProperty('submitting');
if (resp && resp.jqXHR && resp.jqXHR.responseJSON && resp.jqXHR.responseJSON.errors) {
var message = resp.jqXHR.responseJSON.errors[0].message;
self.set('flowErrors', message);
if (message.match(/no user with that email/)) {
self.get('model.errors').add('identification', '');
}
} else {
notifications.showAPIError(resp, {defaultErrorText: 'There was a problem with the reset, please try again.'});
}
});
}).catch(function () {
self.set('flowErrors', 'Please enter an email address then click "Forgot?".');
});
}
}
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.10.2_A2.4_T1;
* @section: 11.10.2;
* @assertion: First expression is evaluated first, and then second expression;
* @description: Checking with "=";
*/
//CHECK#1
var x = 1;
if (((x = 0) ^ x) !== 0) {
$ERROR('#1: var x = 0; ((x = 1) ^ x) === 0. Actual: ' + (((x = 1) ^ x)));
}
//CHECK#2
var x = 0;
if ((x ^ (x = 1)) !== 1) {
$ERROR('#2: var x = 0; (x ^ (x = 1)) === 1. Actual: ' + ((x ^ (x = 1))));
}
|
/*! jQuery UI - v1.11.0 - 2014-08-11
* http://jqueryui.com
* Includes: core.js, widget.js, position.js, autocomplete.js, menu.js
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function (e) {
"function" == typeof define && define.amd ? define(["jquery"], e) : e(jQuery)
})(function (e) {
function t(t, s) {
var n, a, o, r = t.nodeName.toLowerCase();
return "area" === r ? (n = t.parentNode, a = n.name, t.href && a && "map" === n.nodeName.toLowerCase() ? (o = e("img[usemap=#" + a + "]")[0], !!o && i(o)) : !1) : (/input|select|textarea|button|object/.test(r) ? !t.disabled : "a" === r ? t.href || s : s) && i(t)
}
function i(t) {
return e.expr.filters.visible(t) && !e(t).parents().addBack().filter(function () {
return "hidden" === e.css(this, "visibility")
}).length
}
e.ui = e.ui || {}, e.extend(e.ui, {
version: "1.11.0",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
}), e.fn.extend({
scrollParent: function () {
var t = this.css("position"),
i = "absolute" === t,
s = this.parents().filter(function () {
var t = e(this);
return i && "static" === t.css("position") ? !1 : /(auto|scroll)/.test(t.css("overflow") + t.css("overflow-y") + t.css("overflow-x"))
}).eq(0);
return "fixed" !== t && s.length ? s : e(this[0].ownerDocument || document)
},
uniqueId: function () {
var e = 0;
return function () {
return this.each(function () {
this.id || (this.id = "ui-id-" + ++e)
})
}
}(),
removeUniqueId: function () {
return this.each(function () {
/^ui-id-\d+$/.test(this.id) && e(this).removeAttr("id")
})
}
}), e.extend(e.expr[":"], {
data: e.expr.createPseudo ? e.expr.createPseudo(function (t) {
return function (i) {
return !!e.data(i, t)
}
}) : function (t, i, s) {
return !!e.data(t, s[3])
},
focusable: function (i) {
return t(i, !isNaN(e.attr(i, "tabindex")))
},
tabbable: function (i) {
var s = e.attr(i, "tabindex"),
n = isNaN(s);
return (n || s >= 0) && t(i, !n)
}
}), e("<a>").outerWidth(1).jquery || e.each(["Width", "Height"], function (t, i) {
function s(t, i, s, a) {
return e.each(n, function () {
i -= parseFloat(e.css(t, "padding" + this)) || 0, s && (i -= parseFloat(e.css(t, "border" + this + "Width")) || 0), a && (i -= parseFloat(e.css(t, "margin" + this)) || 0)
}), i
}
var n = "Width" === i ? ["Left", "Right"] : ["Top", "Bottom"],
a = i.toLowerCase(),
o = {
innerWidth: e.fn.innerWidth,
innerHeight: e.fn.innerHeight,
outerWidth: e.fn.outerWidth,
outerHeight: e.fn.outerHeight
};
e.fn["inner" + i] = function (t) {
return void 0 === t ? o["inner" + i].call(this) : this.each(function () {
e(this).css(a, s(this, t) + "px")
})
}, e.fn["outer" + i] = function (t, n) {
return "number" != typeof t ? o["outer" + i].call(this, t) : this.each(function () {
e(this).css(a, s(this, t, !0, n) + "px")
})
}
}), e.fn.addBack || (e.fn.addBack = function (e) {
return this.add(null == e ? this.prevObject : this.prevObject.filter(e))
}), e("<a>").data("a-b", "a").removeData("a-b").data("a-b") && (e.fn.removeData = function (t) {
return function (i) {
return arguments.length ? t.call(this, e.camelCase(i)) : t.call(this)
}
}(e.fn.removeData)), e.ui.ie = !!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()), e.fn.extend({
focus: function (t) {
return function (i, s) {
return "number" == typeof i ? this.each(function () {
var t = this;
setTimeout(function () {
e(t).focus(), s && s.call(t)
}, i)
}) : t.apply(this, arguments)
}
}(e.fn.focus),
disableSelection: function () {
var e = "onselectstart" in document.createElement("div") ? "selectstart" : "mousedown";
return function () {
return this.bind(e + ".ui-disableSelection", function (e) {
e.preventDefault()
})
}
}(),
enableSelection: function () {
return this.unbind(".ui-disableSelection")
},
zIndex: function (t) {
if (void 0 !== t) return this.css("zIndex", t);
if (this.length)
for (var i, s, n = e(this[0]); n.length && n[0] !== document;) {
if (i = n.css("position"), ("absolute" === i || "relative" === i || "fixed" === i) && (s = parseInt(n.css("zIndex"), 10), !isNaN(s) && 0 !== s)) return s;
n = n.parent()
}
return 0
}
}), e.ui.plugin = {
add: function (t, i, s) {
var n, a = e.ui[t].prototype;
for (n in s) a.plugins[n] = a.plugins[n] || [], a.plugins[n].push([i, s[n]])
},
call: function (e, t, i, s) {
var n, a = e.plugins[t];
if (a && (s || e.element[0].parentNode && 11 !== e.element[0].parentNode.nodeType))
for (n = 0; a.length > n; n++) e.options[a[n][0]] && a[n][1].apply(e.element, i)
}
};
var s = 0,
n = Array.prototype.slice;
e.cleanData = function (t) {
return function (i) {
for (var s, n = 0; null != (s = i[n]); n++) try {
e(s).triggerHandler("remove")
} catch (a) {}
t(i)
}
}(e.cleanData), e.widget = function (t, i, s) {
var n, a, o, r, h = {},
l = t.split(".")[0];
return t = t.split(".")[1], n = l + "-" + t, s || (s = i, i = e.Widget), e.expr[":"][n.toLowerCase()] = function (t) {
return !!e.data(t, n)
}, e[l] = e[l] || {}, a = e[l][t], o = e[l][t] = function (e, t) {
return this._createWidget ? (arguments.length && this._createWidget(e, t), void 0) : new o(e, t)
}, e.extend(o, a, {
version: s.version,
_proto: e.extend({}, s),
_childConstructors: []
}), r = new i, r.options = e.widget.extend({}, r.options), e.each(s, function (t, s) {
return e.isFunction(s) ? (h[t] = function () {
var e = function () {
return i.prototype[t].apply(this, arguments)
},
n = function (e) {
return i.prototype[t].apply(this, e)
};
return function () {
var t, i = this._super,
a = this._superApply;
return this._super = e, this._superApply = n, t = s.apply(this, arguments), this._super = i, this._superApply = a, t
}
}(), void 0) : (h[t] = s, void 0)
}), o.prototype = e.widget.extend(r, {
widgetEventPrefix: a ? r.widgetEventPrefix || t : t
}, h, {
constructor: o,
namespace: l,
widgetName: t,
widgetFullName: n
}), a ? (e.each(a._childConstructors, function (t, i) {
var s = i.prototype;
e.widget(s.namespace + "." + s.widgetName, o, i._proto)
}), delete a._childConstructors) : i._childConstructors.push(o), e.widget.bridge(t, o), o
}, e.widget.extend = function (t) {
for (var i, s, a = n.call(arguments, 1), o = 0, r = a.length; r > o; o++)
for (i in a[o]) s = a[o][i], a[o].hasOwnProperty(i) && void 0 !== s && (t[i] = e.isPlainObject(s) ? e.isPlainObject(t[i]) ? e.widget.extend({}, t[i], s) : e.widget.extend({}, s) : s);
return t
}, e.widget.bridge = function (t, i) {
var s = i.prototype.widgetFullName || t;
e.fn[t] = function (a) {
var o = "string" == typeof a,
r = n.call(arguments, 1),
h = this;
return a = !o && r.length ? e.widget.extend.apply(null, [a].concat(r)) : a, o ? this.each(function () {
var i, n = e.data(this, s);
return "instance" === a ? (h = n, !1) : n ? e.isFunction(n[a]) && "_" !== a.charAt(0) ? (i = n[a].apply(n, r), i !== n && void 0 !== i ? (h = i && i.jquery ? h.pushStack(i.get()) : i, !1) : void 0) : e.error("no such method '" + a + "' for " + t + " widget instance") : e.error("cannot call methods on " + t + " prior to initialization; " + "attempted to call method '" + a + "'")
}) : this.each(function () {
var t = e.data(this, s);
t ? (t.option(a || {}), t._init && t._init()) : e.data(this, s, new i(a, this))
}), h
}
}, e.Widget = function () {}, e.Widget._childConstructors = [], e.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: !1,
create: null
},
_createWidget: function (t, i) {
i = e(i || this.defaultElement || this)[0], this.element = e(i), this.uuid = s++, this.eventNamespace = "." + this.widgetName + this.uuid, this.options = e.widget.extend({}, this.options, this._getCreateOptions(), t), this.bindings = e(), this.hoverable = e(), this.focusable = e(), i !== this && (e.data(i, this.widgetFullName, this), this._on(!0, this.element, {
remove: function (e) {
e.target === i && this.destroy()
}
}), this.document = e(i.style ? i.ownerDocument : i.document || i), this.window = e(this.document[0].defaultView || this.document[0].parentWindow)), this._create(), this._trigger("create", null, this._getCreateEventData()), this._init()
},
_getCreateOptions: e.noop,
_getCreateEventData: e.noop,
_create: e.noop,
_init: e.noop,
destroy: function () {
this._destroy(), this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)), this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName + "-disabled " + "ui-state-disabled"), this.bindings.unbind(this.eventNamespace), this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus")
},
_destroy: e.noop,
widget: function () {
return this.element
},
option: function (t, i) {
var s, n, a, o = t;
if (0 === arguments.length) return e.widget.extend({}, this.options);
if ("string" == typeof t)
if (o = {}, s = t.split("."), t = s.shift(), s.length) {
for (n = o[t] = e.widget.extend({}, this.options[t]), a = 0; s.length - 1 > a; a++) n[s[a]] = n[s[a]] || {}, n = n[s[a]];
if (t = s.pop(), 1 === arguments.length) return void 0 === n[t] ? null : n[t];
n[t] = i
} else {
if (1 === arguments.length) return void 0 === this.options[t] ? null : this.options[t];
o[t] = i
}
return this._setOptions(o), this
},
_setOptions: function (e) {
var t;
for (t in e) this._setOption(t, e[t]);
return this
},
_setOption: function (e, t) {
return this.options[e] = t, "disabled" === e && (this.widget().toggleClass(this.widgetFullName + "-disabled", !!t), t && (this.hoverable.removeClass("ui-state-hover"), this.focusable.removeClass("ui-state-focus"))), this
},
enable: function () {
return this._setOptions({
disabled: !1
})
},
disable: function () {
return this._setOptions({
disabled: !0
})
},
_on: function (t, i, s) {
var n, a = this;
"boolean" != typeof t && (s = i, i = t, t = !1), s ? (i = n = e(i), this.bindings = this.bindings.add(i)) : (s = i, i = this.element, n = this.widget()), e.each(s, function (s, o) {
function r() {
return t || a.options.disabled !== !0 && !e(this).hasClass("ui-state-disabled") ? ("string" == typeof o ? a[o] : o).apply(a, arguments) : void 0
}
"string" != typeof o && (r.guid = o.guid = o.guid || r.guid || e.guid++);
var h = s.match(/^([\w:-]*)\s*(.*)$/),
l = h[1] + a.eventNamespace,
u = h[2];
u ? n.delegate(u, l, r) : i.bind(l, r)
})
},
_off: function (e, t) {
t = (t || "").split(" ").join(this.eventNamespace + " ") + this.eventNamespace, e.unbind(t).undelegate(t)
},
_delay: function (e, t) {
function i() {
return ("string" == typeof e ? s[e] : e).apply(s, arguments)
}
var s = this;
return setTimeout(i, t || 0)
},
_hoverable: function (t) {
this.hoverable = this.hoverable.add(t), this._on(t, {
mouseenter: function (t) {
e(t.currentTarget).addClass("ui-state-hover")
},
mouseleave: function (t) {
e(t.currentTarget).removeClass("ui-state-hover")
}
})
},
_focusable: function (t) {
this.focusable = this.focusable.add(t), this._on(t, {
focusin: function (t) {
e(t.currentTarget).addClass("ui-state-focus")
},
focusout: function (t) {
e(t.currentTarget).removeClass("ui-state-focus")
}
})
},
_trigger: function (t, i, s) {
var n, a, o = this.options[t];
if (s = s || {}, i = e.Event(i), i.type = (t === this.widgetEventPrefix ? t : this.widgetEventPrefix + t).toLowerCase(), i.target = this.element[0], a = i.originalEvent)
for (n in a) n in i || (i[n] = a[n]);
return this.element.trigger(i, s), !(e.isFunction(o) && o.apply(this.element[0], [i].concat(s)) === !1 || i.isDefaultPrevented())
}
}, e.each({
show: "fadeIn",
hide: "fadeOut"
}, function (t, i) {
e.Widget.prototype["_" + t] = function (s, n, a) {
"string" == typeof n && (n = {
effect: n
});
var o, r = n ? n === !0 || "number" == typeof n ? i : n.effect || i : t;
n = n || {}, "number" == typeof n && (n = {
duration: n
}), o = !e.isEmptyObject(n), n.complete = a, n.delay && s.delay(n.delay), o && e.effects && e.effects.effect[r] ? s[t](n) : r !== t && s[r] ? s[r](n.duration, n.easing, a) : s.queue(function (i) {
e(this)[t](), a && a.call(s[0]), i()
})
}
}), e.widget,
function () {
function t(e, t, i) {
return [parseFloat(e[0]) * (p.test(e[0]) ? t / 100 : 1), parseFloat(e[1]) * (p.test(e[1]) ? i / 100 : 1)]
}
function i(t, i) {
return parseInt(e.css(t, i), 10) || 0
}
function s(t) {
var i = t[0];
return 9 === i.nodeType ? {
width: t.width(),
height: t.height(),
offset: {
top: 0,
left: 0
}
} : e.isWindow(i) ? {
width: t.width(),
height: t.height(),
offset: {
top: t.scrollTop(),
left: t.scrollLeft()
}
} : i.preventDefault ? {
width: 0,
height: 0,
offset: {
top: i.pageY,
left: i.pageX
}
} : {
width: t.outerWidth(),
height: t.outerHeight(),
offset: t.offset()
}
}
e.ui = e.ui || {};
var n, a, o = Math.max,
r = Math.abs,
h = Math.round,
l = /left|center|right/,
u = /top|center|bottom/,
d = /[\+\-]\d+(\.[\d]+)?%?/,
c = /^\w+/,
p = /%$/,
f = e.fn.position;
e.position = {
scrollbarWidth: function () {
if (void 0 !== n) return n;
var t, i, s = e("<div style='display:block;position:absolute;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),
a = s.children()[0];
return e("body").append(s), t = a.offsetWidth, s.css("overflow", "scroll"), i = a.offsetWidth, t === i && (i = s[0].clientWidth), s.remove(), n = t - i
},
getScrollInfo: function (t) {
var i = t.isWindow || t.isDocument ? "" : t.element.css("overflow-x"),
s = t.isWindow || t.isDocument ? "" : t.element.css("overflow-y"),
n = "scroll" === i || "auto" === i && t.width < t.element[0].scrollWidth,
a = "scroll" === s || "auto" === s && t.height < t.element[0].scrollHeight;
return {
width: a ? e.position.scrollbarWidth() : 0,
height: n ? e.position.scrollbarWidth() : 0
}
},
getWithinInfo: function (t) {
var i = e(t || window),
s = e.isWindow(i[0]),
n = !!i[0] && 9 === i[0].nodeType;
return {
element: i,
isWindow: s,
isDocument: n,
offset: i.offset() || {
left: 0,
top: 0
},
scrollLeft: i.scrollLeft(),
scrollTop: i.scrollTop(),
width: s ? i.width() : i.outerWidth(),
height: s ? i.height() : i.outerHeight()
}
}
}, e.fn.position = function (n) {
if (!n || !n.of) return f.apply(this, arguments);
n = e.extend({}, n);
var p, m, g, v, y, b, _ = e(n.of),
x = e.position.getWithinInfo(n.within),
w = e.position.getScrollInfo(x),
k = (n.collision || "flip").split(" "),
T = {};
return b = s(_), _[0].preventDefault && (n.at = "left top"), m = b.width, g = b.height, v = b.offset, y = e.extend({}, v), e.each(["my", "at"], function () {
var e, t, i = (n[this] || "").split(" ");
1 === i.length && (i = l.test(i[0]) ? i.concat(["center"]) : u.test(i[0]) ? ["center"].concat(i) : ["center", "center"]), i[0] = l.test(i[0]) ? i[0] : "center", i[1] = u.test(i[1]) ? i[1] : "center", e = d.exec(i[0]), t = d.exec(i[1]), T[this] = [e ? e[0] : 0, t ? t[0] : 0], n[this] = [c.exec(i[0])[0], c.exec(i[1])[0]]
}), 1 === k.length && (k[1] = k[0]), "right" === n.at[0] ? y.left += m : "center" === n.at[0] && (y.left += m / 2), "bottom" === n.at[1] ? y.top += g : "center" === n.at[1] && (y.top += g / 2), p = t(T.at, m, g), y.left += p[0], y.top += p[1], this.each(function () {
var s, l, u = e(this),
d = u.outerWidth(),
c = u.outerHeight(),
f = i(this, "marginLeft"),
b = i(this, "marginTop"),
D = d + f + i(this, "marginRight") + w.width,
S = c + b + i(this, "marginBottom") + w.height,
N = e.extend({}, y),
M = t(T.my, u.outerWidth(), u.outerHeight());
"right" === n.my[0] ? N.left -= d : "center" === n.my[0] && (N.left -= d / 2), "bottom" === n.my[1] ? N.top -= c : "center" === n.my[1] && (N.top -= c / 2), N.left += M[0], N.top += M[1], a || (N.left = h(N.left), N.top = h(N.top)), s = {
marginLeft: f,
marginTop: b
}, e.each(["left", "top"], function (t, i) {
e.ui.position[k[t]] && e.ui.position[k[t]][i](N, {
targetWidth: m,
targetHeight: g,
elemWidth: d,
elemHeight: c,
collisionPosition: s,
collisionWidth: D,
collisionHeight: S,
offset: [p[0] + M[0], p[1] + M[1]],
my: n.my,
at: n.at,
within: x,
elem: u
})
}), n.using && (l = function (e) {
var t = v.left - N.left,
i = t + m - d,
s = v.top - N.top,
a = s + g - c,
h = {
target: {
element: _,
left: v.left,
top: v.top,
width: m,
height: g
},
element: {
element: u,
left: N.left,
top: N.top,
width: d,
height: c
},
horizontal: 0 > i ? "left" : t > 0 ? "right" : "center",
vertical: 0 > a ? "top" : s > 0 ? "bottom" : "middle"
};
d > m && m > r(t + i) && (h.horizontal = "center"), c > g && g > r(s + a) && (h.vertical = "middle"), h.important = o(r(t), r(i)) > o(r(s), r(a)) ? "horizontal" : "vertical", n.using.call(this, e, h)
}), u.offset(e.extend(N, {
using: l
}))
})
}, e.ui.position = {
fit: {
left: function (e, t) {
var i, s = t.within,
n = s.isWindow ? s.scrollLeft : s.offset.left,
a = s.width,
r = e.left - t.collisionPosition.marginLeft,
h = n - r,
l = r + t.collisionWidth - a - n;
t.collisionWidth > a ? h > 0 && 0 >= l ? (i = e.left + h + t.collisionWidth - a - n, e.left += h - i) : e.left = l > 0 && 0 >= h ? n : h > l ? n + a - t.collisionWidth : n : h > 0 ? e.left += h : l > 0 ? e.left -= l : e.left = o(e.left - r, e.left)
},
top: function (e, t) {
var i, s = t.within,
n = s.isWindow ? s.scrollTop : s.offset.top,
a = t.within.height,
r = e.top - t.collisionPosition.marginTop,
h = n - r,
l = r + t.collisionHeight - a - n;
t.collisionHeight > a ? h > 0 && 0 >= l ? (i = e.top + h + t.collisionHeight - a - n, e.top += h - i) : e.top = l > 0 && 0 >= h ? n : h > l ? n + a - t.collisionHeight : n : h > 0 ? e.top += h : l > 0 ? e.top -= l : e.top = o(e.top - r, e.top)
}
},
flip: {
left: function (e, t) {
var i, s, n = t.within,
a = n.offset.left + n.scrollLeft,
o = n.width,
h = n.isWindow ? n.scrollLeft : n.offset.left,
l = e.left - t.collisionPosition.marginLeft,
u = l - h,
d = l + t.collisionWidth - o - h,
c = "left" === t.my[0] ? -t.elemWidth : "right" === t.my[0] ? t.elemWidth : 0,
p = "left" === t.at[0] ? t.targetWidth : "right" === t.at[0] ? -t.targetWidth : 0,
f = -2 * t.offset[0];
0 > u ? (i = e.left + c + p + f + t.collisionWidth - o - a, (0 > i || r(u) > i) && (e.left += c + p + f)) : d > 0 && (s = e.left - t.collisionPosition.marginLeft + c + p + f - h, (s > 0 || d > r(s)) && (e.left += c + p + f))
},
top: function (e, t) {
var i, s, n = t.within,
a = n.offset.top + n.scrollTop,
o = n.height,
h = n.isWindow ? n.scrollTop : n.offset.top,
l = e.top - t.collisionPosition.marginTop,
u = l - h,
d = l + t.collisionHeight - o - h,
c = "top" === t.my[1],
p = c ? -t.elemHeight : "bottom" === t.my[1] ? t.elemHeight : 0,
f = "top" === t.at[1] ? t.targetHeight : "bottom" === t.at[1] ? -t.targetHeight : 0,
m = -2 * t.offset[1];
0 > u ? (s = e.top + p + f + m + t.collisionHeight - o - a, e.top + p + f + m > u && (0 > s || r(u) > s) && (e.top += p + f + m)) : d > 0 && (i = e.top - t.collisionPosition.marginTop + p + f + m - h, e.top + p + f + m > d && (i > 0 || d > r(i)) && (e.top += p + f + m))
}
},
flipfit: {
left: function () {
e.ui.position.flip.left.apply(this, arguments), e.ui.position.fit.left.apply(this, arguments)
},
top: function () {
e.ui.position.flip.top.apply(this, arguments), e.ui.position.fit.top.apply(this, arguments)
}
}
},
function () {
var t, i, s, n, o, r = document.getElementsByTagName("body")[0],
h = document.createElement("div");
t = document.createElement(r ? "div" : "body"), s = {
visibility: "hidden",
width: 0,
height: 0,
border: 0,
margin: 0,
background: "none"
}, r && e.extend(s, {
position: "absolute",
left: "-1000px",
top: "-1000px"
});
for (o in s) t.style[o] = s[o];
t.appendChild(h), i = r || document.documentElement, i.insertBefore(t, i.firstChild), h.style.cssText = "position: absolute; left: 10.7432222px;", n = e(h).offset().left, a = n > 10 && 11 > n, t.innerHTML = "", i.removeChild(t)
}()
}(), e.ui.position, e.widget("ui.menu", {
version: "1.11.0",
defaultElement: "<ul>",
delay: 300,
options: {
icons: {
submenu: "ui-icon-carat-1-e"
},
items: "> *",
menus: "ul",
position: {
my: "left-1 top",
at: "right top"
},
role: "menu",
blur: null,
focus: null,
select: null
},
_create: function () {
this.activeMenu = this.element, this.mouseHandled = !1, this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content").toggleClass("ui-menu-icons", !!this.element.find(".ui-icon").length).attr({
role: this.options.role,
tabIndex: 0
}), this.options.disabled && this.element.addClass("ui-state-disabled").attr("aria-disabled", "true"), this._on({
"mousedown .ui-menu-item": function (e) {
e.preventDefault()
},
"click .ui-menu-item": function (t) {
var i = e(t.target);
!this.mouseHandled && i.not(".ui-state-disabled").length && (this.select(t), t.isPropagationStopped() || (this.mouseHandled = !0), i.has(".ui-menu").length ? this.expand(t) : !this.element.is(":focus") && e(this.document[0].activeElement).closest(".ui-menu").length && (this.element.trigger("focus", [!0]), this.active && 1 === this.active.parents(".ui-menu").length && clearTimeout(this.timer)))
},
"mouseenter .ui-menu-item": function (t) {
var i = e(t.currentTarget);
i.siblings(".ui-state-active").removeClass("ui-state-active"), this.focus(t, i)
},
mouseleave: "collapseAll",
"mouseleave .ui-menu": "collapseAll",
focus: function (e, t) {
var i = this.active || this.element.find(this.options.items).eq(0);
t || this.focus(e, i)
},
blur: function (t) {
this._delay(function () {
e.contains(this.element[0], this.document[0].activeElement) || this.collapseAll(t)
})
},
keydown: "_keydown"
}), this.refresh(), this._on(this.document, {
click: function (e) {
this._closeOnDocumentClick(e) && this.collapseAll(e), this.mouseHandled = !1
}
})
},
_destroy: function () {
this.element.removeAttr("aria-activedescendant").find(".ui-menu").addBack().removeClass("ui-menu ui-widget ui-widget-content ui-menu-icons ui-front").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(), this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").removeUniqueId().removeClass("ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function () {
var t = e(this);
t.data("ui-menu-submenu-carat") && t.remove()
}), this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")
},
_keydown: function (t) {
function i(e) {
return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
}
var s, n, a, o, r, h = !0;
switch (t.keyCode) {
case e.ui.keyCode.PAGE_UP:
this.previousPage(t);
break;
case e.ui.keyCode.PAGE_DOWN:
this.nextPage(t);
break;
case e.ui.keyCode.HOME:
this._move("first", "first", t);
break;
case e.ui.keyCode.END:
this._move("last", "last", t);
break;
case e.ui.keyCode.UP:
this.previous(t);
break;
case e.ui.keyCode.DOWN:
this.next(t);
break;
case e.ui.keyCode.LEFT:
this.collapse(t);
break;
case e.ui.keyCode.RIGHT:
this.active && !this.active.is(".ui-state-disabled") && this.expand(t);
break;
case e.ui.keyCode.ENTER:
case e.ui.keyCode.SPACE:
this._activate(t);
break;
case e.ui.keyCode.ESCAPE:
this.collapse(t);
break;
default:
h = !1, n = this.previousFilter || "", a = String.fromCharCode(t.keyCode), o = !1, clearTimeout(this.filterTimer), a === n ? o = !0 : a = n + a, r = RegExp("^" + i(a), "i"), s = this.activeMenu.find(this.options.items).filter(function () {
return r.test(e(this).text())
}), s = o && -1 !== s.index(this.active.next()) ? this.active.nextAll(".ui-menu-item") : s, s.length || (a = String.fromCharCode(t.keyCode), r = RegExp("^" + i(a), "i"), s = this.activeMenu.find(this.options.items).filter(function () {
return r.test(e(this).text())
})), s.length ? (this.focus(t, s), s.length > 1 ? (this.previousFilter = a, this.filterTimer = this._delay(function () {
delete this.previousFilter
}, 1e3)) : delete this.previousFilter) : delete this.previousFilter
}
h && t.preventDefault()
},
_activate: function (e) {
this.active.is(".ui-state-disabled") || (this.active.is("[aria-haspopup='true']") ? this.expand(e) : this.select(e))
},
refresh: function () {
var t, i, s = this,
n = this.options.icons.submenu,
a = this.element.find(this.options.menus);
this.element.toggleClass("ui-menu-icons", !!this.element.find(".ui-icon").length), a.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-front").hide().attr({
role: this.options.role,
"aria-hidden": "true",
"aria-expanded": "false"
}).each(function () {
var t = e(this),
i = t.parent(),
s = e("<span>").addClass("ui-menu-icon ui-icon " + n).data("ui-menu-submenu-carat", !0);
i.attr("aria-haspopup", "true").prepend(s), t.attr("aria-labelledby", i.attr("id"))
}), t = a.add(this.element), i = t.find(this.options.items), i.not(".ui-menu-item").each(function () {
var t = e(this);
s._isDivider(t) && t.addClass("ui-widget-content ui-menu-divider")
}), i.not(".ui-menu-item, .ui-menu-divider").addClass("ui-menu-item").uniqueId().attr({
tabIndex: -1,
role: this._itemRole()
}), i.filter(".ui-state-disabled").attr("aria-disabled", "true"), this.active && !e.contains(this.element[0], this.active[0]) && this.blur()
},
_itemRole: function () {
return {
menu: "menuitem",
listbox: "option"
}[this.options.role]
},
_setOption: function (e, t) {
"icons" === e && this.element.find(".ui-menu-icon").removeClass(this.options.icons.submenu).addClass(t.submenu), "disabled" === e && this.element.toggleClass("ui-state-disabled", !!t).attr("aria-disabled", t), this._super(e, t)
},
focus: function (e, t) {
var i, s;
this.blur(e, e && "focus" === e.type), this._scrollIntoView(t), this.active = t.first(), s = this.active.addClass("ui-state-focus").removeClass("ui-state-active"), this.options.role && this.element.attr("aria-activedescendant", s.attr("id")), this.active.parent().closest(".ui-menu-item").addClass("ui-state-active"), e && "keydown" === e.type ? this._close() : this.timer = this._delay(function () {
this._close()
}, this.delay), i = t.children(".ui-menu"), i.length && e && /^mouse/.test(e.type) && this._startOpening(i), this.activeMenu = t.parent(), this._trigger("focus", e, {
item: t
})
},
_scrollIntoView: function (t) {
var i, s, n, a, o, r;
this._hasScroll() && (i = parseFloat(e.css(this.activeMenu[0], "borderTopWidth")) || 0, s = parseFloat(e.css(this.activeMenu[0], "paddingTop")) || 0, n = t.offset().top - this.activeMenu.offset().top - i - s, a = this.activeMenu.scrollTop(), o = this.activeMenu.height(), r = t.outerHeight(), 0 > n ? this.activeMenu.scrollTop(a + n) : n + r > o && this.activeMenu.scrollTop(a + n - o + r))
},
blur: function (e, t) {
t || clearTimeout(this.timer), this.active && (this.active.removeClass("ui-state-focus"), this.active = null, this._trigger("blur", e, {
item: this.active
}))
},
_startOpening: function (e) {
clearTimeout(this.timer), "true" === e.attr("aria-hidden") && (this.timer = this._delay(function () {
this._close(), this._open(e)
}, this.delay))
},
_open: function (t) {
var i = e.extend({
of: this.active
}, this.options.position);
clearTimeout(this.timer), this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden", "true"), t.show().removeAttr("aria-hidden").attr("aria-expanded", "true").position(i)
},
collapseAll: function (t, i) {
clearTimeout(this.timer), this.timer = this._delay(function () {
var s = i ? this.element : e(t && t.target).closest(this.element.find(".ui-menu"));
s.length || (s = this.element), this._close(s), this.blur(t), this.activeMenu = s
}, this.delay)
},
_close: function (e) {
e || (e = this.active ? this.active.parent() : this.element), e.find(".ui-menu").hide().attr("aria-hidden", "true").attr("aria-expanded", "false").end().find(".ui-state-active").not(".ui-state-focus").removeClass("ui-state-active")
},
_closeOnDocumentClick: function (t) {
return !e(t.target).closest(".ui-menu").length
},
_isDivider: function (e) {
return !/[^\-\u2014\u2013\s]/.test(e.text())
},
collapse: function (e) {
var t = this.active && this.active.parent().closest(".ui-menu-item", this.element);
t && t.length && (this._close(), this.focus(e, t))
},
expand: function (e) {
var t = this.active && this.active.children(".ui-menu ").find(this.options.items).first();
t && t.length && (this._open(t.parent()), this._delay(function () {
this.focus(e, t)
}))
},
next: function (e) {
this._move("next", "first", e)
},
previous: function (e) {
this._move("prev", "last", e)
},
isFirstItem: function () {
return this.active && !this.active.prevAll(".ui-menu-item").length
},
isLastItem: function () {
return this.active && !this.active.nextAll(".ui-menu-item").length
},
_move: function (e, t, i) {
var s;
this.active && (s = "first" === e || "last" === e ? this.active["first" === e ? "prevAll" : "nextAll"](".ui-menu-item").eq(-1) : this.active[e + "All"](".ui-menu-item").eq(0)), s && s.length && this.active || (s = this.activeMenu.find(this.options.items)[t]()), this.focus(i, s)
},
nextPage: function (t) {
var i, s, n;
return this.active ? (this.isLastItem() || (this._hasScroll() ? (s = this.active.offset().top, n = this.element.height(), this.active.nextAll(".ui-menu-item").each(function () {
return i = e(this), 0 > i.offset().top - s - n
}), this.focus(t, i)) : this.focus(t, this.activeMenu.find(this.options.items)[this.active ? "last" : "first"]())), void 0) : (this.next(t), void 0)
},
previousPage: function (t) {
var i, s, n;
return this.active ? (this.isFirstItem() || (this._hasScroll() ? (s = this.active.offset().top, n = this.element.height(), this.active.prevAll(".ui-menu-item").each(function () {
return i = e(this), i.offset().top - s + n > 0
}), this.focus(t, i)) : this.focus(t, this.activeMenu.find(this.options.items).first())), void 0) : (this.next(t), void 0)
},
_hasScroll: function () {
return this.element.outerHeight() < this.element.prop("scrollHeight")
},
select: function (t) {
this.active = this.active || e(t.target).closest(".ui-menu-item");
var i = {
item: this.active
};
this.active.has(".ui-menu").length || this.collapseAll(t, !0), this._trigger("select", t, i)
}
}), e.widget("ui.autocomplete", {
version: "1.11.0",
defaultElement: "<input>",
options: {
appendTo: null,
autoFocus: !1,
delay: 300,
minLength: 1,
position: {
my: "left top",
at: "left bottom",
collision: "none"
},
source: null,
change: null,
close: null,
focus: null,
open: null,
response: null,
search: null,
select: null
},
requestIndex: 0,
pending: 0,
_create: function () {
var t, i, s, n = this.element[0].nodeName.toLowerCase(),
a = "textarea" === n,
o = "input" === n;
this.isMultiLine = a ? !0 : o ? !1 : this.element.prop("isContentEditable"), this.valueMethod = this.element[a || o ? "val" : "text"], this.isNewMenu = !0, this.element.addClass("ui-autocomplete-input").attr("autocomplete", "off"), this._on(this.element, {
keydown: function (n) {
if (this.element.prop("readOnly")) return t = !0, s = !0, i = !0, void 0;
t = !1, s = !1, i = !1;
var a = e.ui.keyCode;
switch (n.keyCode) {
case a.PAGE_UP:
t = !0, this._move("previousPage", n);
break;
case a.PAGE_DOWN:
t = !0, this._move("nextPage", n);
break;
case a.UP:
t = !0, this._keyEvent("previous", n);
break;
case a.DOWN:
t = !0, this._keyEvent("next", n);
break;
case a.ENTER:
this.menu.active && (t = !0, n.preventDefault(), this.menu.select(n));
break;
case a.TAB:
this.menu.active && this.menu.select(n);
break;
case a.ESCAPE:
this.menu.element.is(":visible") && (this._value(this.term), this.close(n), n.preventDefault());
break;
default:
i = !0, this._searchTimeout(n)
}
},
keypress: function (s) {
if (t) return t = !1, (!this.isMultiLine || this.menu.element.is(":visible")) && s.preventDefault(), void 0;
if (!i) {
var n = e.ui.keyCode;
switch (s.keyCode) {
case n.PAGE_UP:
this._move("previousPage", s);
break;
case n.PAGE_DOWN:
this._move("nextPage", s);
break;
case n.UP:
this._keyEvent("previous", s);
break;
case n.DOWN:
this._keyEvent("next", s)
}
}
},
input: function (e) {
return s ? (s = !1, e.preventDefault(), void 0) : (this._searchTimeout(e), void 0)
},
focus: function () {
this.selectedItem = null, this.previous = this._value()
},
blur: function (e) {
return this.cancelBlur ? (delete this.cancelBlur, void 0) : (clearTimeout(this.searching), this.close(e), this._change(e), void 0)
}
}), this._initSource(), this.menu = e("<ul>").addClass("ui-autocomplete ui-front").appendTo(this._appendTo()).menu({
role: null
}).hide().menu("instance"), this._on(this.menu.element, {
mousedown: function (t) {
t.preventDefault(), this.cancelBlur = !0, this._delay(function () {
delete this.cancelBlur
});
var i = this.menu.element[0];
e(t.target).closest(".ui-menu-item").length || this._delay(function () {
var t = this;
this.document.one("mousedown", function (s) {
s.target === t.element[0] || s.target === i || e.contains(i, s.target) || t.close()
})
})
},
menufocus: function (t, i) {
var s, n;
return this.isNewMenu && (this.isNewMenu = !1, t.originalEvent && /^mouse/.test(t.originalEvent.type)) ? (this.menu.blur(), this.document.one("mousemove", function () {
e(t.target).trigger(t.originalEvent)
}), void 0) : (n = i.item.data("ui-autocomplete-item"), !1 !== this._trigger("focus", t, {
item: n
}) && t.originalEvent && /^key/.test(t.originalEvent.type) && this._value(n.value), s = i.item.attr("aria-label") || n.value, s && jQuery.trim(s).length && (this.liveRegion.children().hide(), e("<div>").text(s).appendTo(this.liveRegion)), void 0)
},
menuselect: function (e, t) {
var i = t.item.data("ui-autocomplete-item"),
s = this.previous;
this.element[0] !== this.document[0].activeElement && (this.element.focus(), this.previous = s, this._delay(function () {
this.previous = s, this.selectedItem = i
})), !1 !== this._trigger("select", e, {
item: i
}) && this._value(i.value), this.term = this._value(), this.close(e), this.selectedItem = i
}
}), this.liveRegion = e("<span>", {
role: "status",
"aria-live": "assertive",
"aria-relevant": "additions"
}).addClass("ui-helper-hidden-accessible").appendTo(this.document[0].body), this._on(this.window, {
beforeunload: function () {
this.element.removeAttr("autocomplete")
}
})
},
_destroy: function () {
clearTimeout(this.searching), this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"), this.menu.element.remove(), this.liveRegion.remove()
},
_setOption: function (e, t) {
this._super(e, t), "source" === e && this._initSource(), "appendTo" === e && this.menu.element.appendTo(this._appendTo()), "disabled" === e && t && this.xhr && this.xhr.abort()
},
_appendTo: function () {
var t = this.options.appendTo;
return t && (t = t.jquery || t.nodeType ? e(t) : this.document.find(t).eq(0)), t && t[0] || (t = this.element.closest(".ui-front")), t.length || (t = this.document[0].body), t
},
_initSource: function () {
var t, i, s = this;
e.isArray(this.options.source) ? (t = this.options.source, this.source = function (i, s) {
s(e.ui.autocomplete.filter(t, i.term))
}) : "string" == typeof this.options.source ? (i = this.options.source, this.source = function (t, n) {
s.xhr && s.xhr.abort(), s.xhr = e.ajax({
url: i,
data: t,
dataType: "json",
success: function (e) {
n(e)
},
error: function () {
n([])
}
})
}) : this.source = this.options.source
},
_searchTimeout: function (e) {
clearTimeout(this.searching), this.searching = this._delay(function () {
var t = this.term === this._value(),
i = this.menu.element.is(":visible"),
s = e.altKey || e.ctrlKey || e.metaKey || e.shiftKey;
(!t || t && !i && !s) && (this.selectedItem = null, this.search(null, e))
}, this.options.delay)
},
search: function (e, t) {
return e = null != e ? e : this._value(), this.term = this._value(), e.length < this.options.minLength ? this.close(t) : this._trigger("search", t) !== !1 ? this._search(e) : void 0
},
_search: function (e) {
this.pending++, this.element.addClass("ui-autocomplete-loading"), this.cancelSearch = !1, this.source({
term: e
}, this._response())
},
_response: function () {
var t = ++this.requestIndex;
return e.proxy(function (e) {
t === this.requestIndex && this.__response(e), this.pending--, this.pending || this.element.removeClass("ui-autocomplete-loading")
}, this)
},
__response: function (e) {
e && (e = this._normalize(e)), this._trigger("response", null, {
content: e
}), !this.options.disabled && e && e.length && !this.cancelSearch ? (this._suggest(e), this._trigger("open")) : this._close()
},
close: function (e) {
this.cancelSearch = !0, this._close(e)
},
_close: function (e) {
this.menu.element.is(":visible") && (this.menu.element.hide(), this.menu.blur(), this.isNewMenu = !0, this._trigger("close", e))
},
_change: function (e) {
this.previous !== this._value() && this._trigger("change", e, {
item: this.selectedItem
})
},
_normalize: function (t) {
return t.length && t[0].label && t[0].value ? t : e.map(t, function (t) {
return "string" == typeof t ? {
label: t,
value: t
} : e.extend({}, t, {
label: t.label || t.value,
value: t.value || t.label
})
})
},
_suggest: function (t) {
var i = this.menu.element.empty();
this._renderMenu(i, t), this.isNewMenu = !0, this.menu.refresh(), i.show(), this._resizeMenu(), i.position(e.extend({
of: this.element
}, this.options.position)), this.options.autoFocus && this.menu.next()
},
_resizeMenu: function () {
var e = this.menu.element;
e.outerWidth(Math.max(e.width("").outerWidth() + 1, this.element.outerWidth()))
},
_renderMenu: function (t, i) {
var s = this;
e.each(i, function (e, i) {
s._renderItemData(t, i)
})
},
_renderItemData: function (e, t) {
return this._renderItem(e, t).data("ui-autocomplete-item", t)
},
_renderItem: function (t, i) {
return e("<li>").text(i.label).appendTo(t)
},
_move: function (e, t) {
return this.menu.element.is(":visible") ? this.menu.isFirstItem() && /^previous/.test(e) || this.menu.isLastItem() && /^next/.test(e) ? (this.isMultiLine || this._value(this.term), this.menu.blur(), void 0) : (this.menu[e](t), void 0) : (this.search(null, t), void 0)
},
widget: function () {
return this.menu.element
},
_value: function () {
return this.valueMethod.apply(this.element, arguments)
},
_keyEvent: function (e, t) {
(!this.isMultiLine || this.menu.element.is(":visible")) && (this._move(e, t), t.preventDefault())
}
}), e.extend(e.ui.autocomplete, {
escapeRegex: function (e) {
return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
},
filter: function (t, i) {
var s = RegExp(e.ui.autocomplete.escapeRegex(i), "i");
return e.grep(t, function (e) {
return s.test(e.label || e.value || e)
})
}
}), e.widget("ui.autocomplete", e.ui.autocomplete, {
options: {
messages: {
noResults: "No search results.",
results: function (e) {
return e + (e > 1 ? " results are" : " result is") + " available, use up and down arrow keys to navigate."
}
}
},
__response: function (t) {
var i;
this._superApply(arguments), this.options.disabled || this.cancelSearch || (i = t && t.length ? this.options.messages.results(t.length) : this.options.messages.noResults, this.liveRegion.children().hide(), e("<div>").text(i).appendTo(this.liveRegion))
}
}), e.ui.autocomplete
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.6.3_A12_T1;
* @section: 12.6.3;
* @assertion: If (Evaluate Statement).type is "break" and (Evaluate Statement).target is in the current label set, (normal, (Evaluate Statement), empty) is returned while evaluating a loop;
* @description: Breaking a loop with "break";
*/
__str=""
for(index=0; index<10; index+=1) {
if (index>5)break;
__str+=index;
}
if (__str!=="012345") {
$ERROR('#1:__str === "012345". Actual: __str ==='+__str );
}
|
'use strict'
var crypto = require('crypto')
function encode(bytes, keyBytes) {
for (var i = 0; i < bytes.length; i++) {
// This is really dense but happens commonly so I'm in-lining some of what
// could be tossed into variables. It takes the current byte of bytes, then
// XORs it with the current byte of the key (which uses modulo to make sure
// to not overrun the end.)
bytes.writeUInt8(bytes.readUInt8(i) ^ keyBytes.readUInt8(i % keyBytes.length), i)
}
return bytes
}
function obfuscateNameUsingKey(name, key) {
var encodedBytes = new Buffer(name, 'utf-8')
var keyBytes = new Buffer(key)
return encode(encodedBytes, keyBytes).toString('base64')
}
function deobfuscateNameUsingKey(name, key) {
var bytes = new Buffer(name, 'base64')
var keyBytes = new Buffer(key)
return encode(bytes, keyBytes).toString("utf-8")
}
function calculatePathHash(appName, pathName, referingPathHash) {
if (typeof referingPathHash === 'string') {
referingPathHash = parseInt(referingPathHash, 16)
}
var rotated = ((referingPathHash << 1) | (referingPathHash >>> 31)) >>> 0
var hash = getHash(appName, pathName)
var result = (rotated ^ hash) >>> 0
// This is a trick to pad it out to 8 chars regardless of length.
var retval = ('00000000' + result.toString(16)).substr(-8)
return retval
}
function getHash(appName, txName) {
var md5sum = crypto.createHash('md5')
md5sum.update(new Buffer(appName + ';' + txName), 'utf8')
var buf = new Buffer(md5sum.digest('base64'), 'base64')
// pull the low 4 bytes in network byte order
return buf.slice(buf.length - 4, buf.length).readUInt32BE(0)
}
exports.obfuscateNameUsingKey = obfuscateNameUsingKey
exports.deobfuscateNameUsingKey = deobfuscateNameUsingKey
exports.calculatePathHash = calculatePathHash
exports.getHash = getHash
|
describe('Native template engine', function() {
beforeEach(function() {
function ensureNodeExistsAndIsEmpty(id, tagName, type) {
var existingNode = document.getElementById(id);
if (existingNode != null)
existingNode.parentNode.removeChild(existingNode);
var resultNode = document.createElement(tagName || "div");
resultNode.id = id;
if (type)
resultNode.setAttribute("type", type);
document.body.appendChild(resultNode);
return resultNode;
}
window.testDivTemplate = ensureNodeExistsAndIsEmpty("testDivTemplate");
window.testScriptTemplate = ensureNodeExistsAndIsEmpty("testScriptTemplate", "script", "text/html");
window.testTextAreaTemplate = ensureNodeExistsAndIsEmpty("testTextAreaTemplate", "textarea");
window.templateOutput = ensureNodeExistsAndIsEmpty("templateOutput");
});
describe('Named templates', function () {
it('can display static content from regular DOM element', function () {
window.testDivTemplate.innerHTML = "this is some static content";
ko.renderTemplate("testDivTemplate", null, null, window.templateOutput);
expect(window.templateOutput).toContainHtml("this is some static content");
});
it('can fetch template from regular DOM element and data-bind on results', function () {
window.testDivTemplate.innerHTML = "name: <div data-bind='text: name'></div>";
ko.renderTemplate("testDivTemplate", { name: 'bert' }, null, window.templateOutput);
expect(window.templateOutput).toContainHtml("name: <div data-bind=\"text: name\">bert</div>");
});
it('can fetch template from <script> elements and data-bind on results', function () {
window.testScriptTemplate.text = "name: <div data-bind='text: name'></div>";
ko.renderTemplate("testScriptTemplate", { name: 'bert' }, null, window.templateOutput);
expect(window.templateOutput).toContainHtml("name: <div data-bind=\"text: name\">bert</div>");
});
it('can fetch template from <textarea> elements and data-bind on results', function () {
var prop = (typeof window.testTextAreaTemplate.innerText !== "undefined") ? "innerText" : "textContent";
window.testTextAreaTemplate[prop] = "name: <div data-bind='text: name'></div>";
ko.renderTemplate("testTextAreaTemplate", { name: 'bert' }, null, window.templateOutput);
expect(window.templateOutput).toContainHtml("name: <div data-bind=\"text: name\">bert</div>");
});
});
describe('Anonymous templates', function () {
it('can display static content', function () {
new ko.templateSources.anonymousTemplate(window.templateOutput).text("this is some static content");
window.templateOutput.innerHTML = "irrelevant initial content";
ko.renderTemplate(window.templateOutput, null, null, window.templateOutput);
expect(window.templateOutput).toContainHtml("this is some static content");
});
it('can data-bind on results', function () {
new ko.templateSources.anonymousTemplate(window.templateOutput).text("name: <div data-bind='text: name'></div>");
window.templateOutput.innerHTML = "irrelevant initial content";
ko.renderTemplate(window.templateOutput, { name: 'bert' }, null, window.templateOutput);
expect(window.templateOutput).toContainHtml("name: <div data-bind=\"text: name\">bert</div>");
});
it('can be supplied by not giving a template name', function() {
window.testDivTemplate.innerHTML = "<div data-bind='template: { data: someItem }'>Value: <span data-bind='text: val'></span></div>"
var viewModel = {
someItem: { val: 'abc' }
};
ko.applyBindings(viewModel, window.testDivTemplate);
expect(window.testDivTemplate.childNodes[0]).toContainText("Value: abc");
});
it('work in conjunction with foreach', function() {
window.testDivTemplate.innerHTML = "<div data-bind='template: { foreach: myItems }'><b>Item: <span data-bind='text: itemProp'></span></b></div>";
var myItems = ko.observableArray([{ itemProp: 'Alpha' }, { itemProp: 'Beta' }, { itemProp: 'Gamma' }]);
ko.applyBindings({ myItems: myItems }, window.testDivTemplate);
expect(window.testDivTemplate.childNodes[0].childNodes[0]).toContainText("Item: Alpha");
expect(window.testDivTemplate.childNodes[0].childNodes[1]).toContainText("Item: Beta");
expect(window.testDivTemplate.childNodes[0].childNodes[2]).toContainText("Item: Gamma");
// Can cause re-rendering
myItems.push({ itemProp: 'Pushed' });
expect(window.testDivTemplate.childNodes[0].childNodes[0]).toContainText("Item: Alpha");
expect(window.testDivTemplate.childNodes[0].childNodes[1]).toContainText("Item: Beta");
expect(window.testDivTemplate.childNodes[0].childNodes[2]).toContainText("Item: Gamma");
expect(window.testDivTemplate.childNodes[0].childNodes[3]).toContainText("Item: Pushed");
myItems.splice(1, 1);
expect(window.testDivTemplate.childNodes[0].childNodes[0]).toContainText("Item: Alpha");
expect(window.testDivTemplate.childNodes[0].childNodes[1]).toContainText("Item: Gamma");
expect(window.testDivTemplate.childNodes[0].childNodes[2]).toContainText("Item: Pushed");
});
it('may be nested', function() {
window.testDivTemplate.innerHTML = "<div data-bind='template: { foreach: items }'>"
+ "<div data-bind='template: { foreach: children }'>"
+ "(Val: <span data-bind='text: $data'></span>, Invocations: <span data-bind='text: $root.invocationCount()'></span>, Parents: <span data-bind='text: $parents.length'></span>)"
+ "</div>"
+ "</div>";
var viewModel = {
invocations: 0, // Verifying # invocations to be sure we're not rendering anything multiple times and discarding the results
items: ko.observableArray([
{ children: ko.observableArray(['A1', 'A2', 'A3']) },
{ children: ko.observableArray(['B1', 'B2']) }
])
};
viewModel.invocationCount = function() { return ++this.invocations }.bind(viewModel);
ko.applyBindings(viewModel, window.testDivTemplate);
expect(window.testDivTemplate.childNodes[0].childNodes[0]).toContainText("(Val: A1, Invocations: 1, Parents: 2)(Val: A2, Invocations: 2, Parents: 2)(Val: A3, Invocations: 3, Parents: 2)");
expect(window.testDivTemplate.childNodes[0].childNodes[1]).toContainText("(Val: B1, Invocations: 4, Parents: 2)(Val: B2, Invocations: 5, Parents: 2)");
// Check we can insert without causing anything else to rerender
viewModel.items()[1].children.unshift('ANew');
expect(window.testDivTemplate.childNodes[0].childNodes[0]).toContainText("(Val: A1, Invocations: 1, Parents: 2)(Val: A2, Invocations: 2, Parents: 2)(Val: A3, Invocations: 3, Parents: 2)");
expect(window.testDivTemplate.childNodes[0].childNodes[1]).toContainText("(Val: ANew, Invocations: 6, Parents: 2)(Val: B1, Invocations: 4, Parents: 2)(Val: B2, Invocations: 5, Parents: 2)");
});
});
describe('Data-bind syntax', function () {
it('should expose parent binding context as $parent if binding with an explicit \"data\" value', function() {
window.testDivTemplate.innerHTML = "<div data-bind='template: { data: someItem }'>"
+ "ValueBound: <span data-bind='text: $parent.parentProp'></span>"
+ "</div>";
ko.applyBindings({ someItem: {}, parentProp: 'Hello' }, window.testDivTemplate);
expect(window.testDivTemplate.childNodes[0]).toContainText("ValueBound: Hello");
});
it('should expose all ancestor binding contexts as $parents, with top frame also given as $root', function() {
window.testDivTemplate.innerHTML = "<div data-bind='template: { data: outerItem }'>"
+ "<div data-bind='template: { data: middleItem }'>"
+ "<div data-bind='template: { data: innerItem }'>("
+ "data: <span data-bind='text: $data.val'></span>, "
+ "parent: <span data-bind='text: $parent.val'></span>, "
+ "parents[0]: <span data-bind='text: $parents[0].val'></span>, "
+ "parents[1]: <span data-bind='text: $parents[1].val'></span>, "
+ "parents.length: <span data-bind='text: $parents.length'></span>, "
+ "root: <span data-bind='text: $root.val'></span>"
+ ")</div>"
+ "</div>"
+ "</div>";
ko.applyBindings({
val: "ROOT",
outerItem: {
val: "OUTER",
middleItem: {
val: "MIDDLE",
innerItem: { val: "INNER" }
}
}
}, window.testDivTemplate);
expect(window.testDivTemplate.childNodes[0].childNodes[0].childNodes[0]).toContainText("(data: INNER, parent: MIDDLE, parents[0]: MIDDLE, parents[1]: OUTER, parents.length: 3, root: ROOT)");
});
});
});
|
'use strict';
require('./')();
|
'use strict';
var matrix = require( 'dstructs-matrix' ),
pdf = require( './../lib' );
var data,
mat,
out,
tmp,
i;
// ----
// Plain arrays...
data = new Array( 10 );
for ( i = 0; i < data.length; i++ ) {
data[ i ] = i * 0.5;
}
out = pdf( data );
console.log( 'Arrays: %s\n', out );
// ----
// Object arrays (accessors)...
function getValue( d ) {
return d.x;
}
for ( i = 0; i < data.length; i++ ) {
data[ i ] = {
'x': data[ i ]
};
}
out = pdf( data, {
'accessor': getValue
});
console.log( 'Accessors: %s\n', out );
// ----
// Deep set arrays...
for ( i = 0; i < data.length; i++ ) {
data[ i ] = {
'x': [ i, data[ i ].x ]
};
}
out = pdf( data, {
'path': 'x/1',
'sep': '/'
});
console.log( 'Deepset:');
console.dir( out );
console.log( '\n' );
// ----
// Typed arrays...
data = new Float32Array( 10 );
for ( i = 0; i < data.length; i++ ) {
data[ i ] = i * 0.5;
}
tmp = pdf( data );
out = '';
for ( i = 0; i < data.length; i++ ) {
out += tmp[ i ];
if ( i < data.length-1 ) {
out += ',';
}
}
console.log( 'Typed arrays: %s\n', out );
// ----
// Matrices...
mat = matrix( data, [5,2], 'float32' );
out = pdf( mat );
console.log( 'Matrix: %s\n', out.toString() );
// ----
// Matrices (custom output data type)...
out = pdf( mat, {
'dtype': 'uint8'
});
console.log( 'Matrix (%s): %s\n', out.dtype, out.toString() );
|
/*!
* Bootstrap-select v1.13.0 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2018 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
!function(a,b){"function"==typeof define&&define.amd?define(["jquery"],function(a){return b(a)}):"object"==typeof module&&module.exports?module.exports=b(require("jquery")):b(a.jQuery)}(this,function(a){!function(a){a.fn.selectpicker.defaults={noneSelectedText:"没有选中任何项",noneResultsText:"没有找到匹配项",countSelectedText:"选中{1}中的{0}项",maxOptionsText:["超出限制 (最多选择{n}项)","组选择超出限制(最多选择{n}组)"],multipleSeparator:", ",selectAllText:"全选",deselectAllText:"取消全选"}}(a)});
|
/*!
* JavaScript Cookie v2.2.0
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader;
if (typeof define === 'function' && define.amd) {
define(factory);
registeredInModuleLoader = true;
}
if (typeof exports === 'object') {
module.exports = factory();
registeredInModuleLoader = true;
}
if (!registeredInModuleLoader) {
var OldCookies = window.Cookies;
var api = window.Cookies = factory();
api.noConflict = function () {
window.Cookies = OldCookies;
return api;
};
}
}(function () {
function extend () {
var i = 0;
var result = {};
for (; i < arguments.length; i++) {
var attributes = arguments[ i ];
for (var key in attributes) {
result[key] = attributes[key];
}
}
return result;
}
function init (converter) {
function api (key, value, attributes) {
if (typeof document === 'undefined') {
return;
}
// Write
if (arguments.length > 1) {
attributes = extend({
path: '/'
}, api.defaults, attributes);
if (typeof attributes.expires === 'number') {
attributes.expires = new Date(new Date() * 1 + attributes.expires * 864e+5);
}
// We're using "expires" because "max-age" is not supported by IE
attributes.expires = attributes.expires ? attributes.expires.toUTCString() : '';
try {
var result = JSON.stringify(value);
if (/^[\{\[]/.test(result)) {
value = result;
}
} catch (e) {}
value = converter.write ?
converter.write(value, key) :
encodeURIComponent(String(value))
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent);
key = encodeURIComponent(String(key))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[\(\)]/g, escape);
var stringifiedAttributes = '';
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += '; ' + attributeName;
if (attributes[attributeName] === true) {
continue;
}
// Considers RFC 6265 section 5.2:
// ...
// 3. If the remaining unparsed-attributes contains a %x3B (";")
// character:
// Consume the characters of the unparsed-attributes up to,
// not including, the first %x3B (";") character.
// ...
stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
}
return (document.cookie = key + '=' + value + stringifiedAttributes);
}
// Read
var jar = {};
var decode = function (s) {
return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent);
};
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all.
var cookies = document.cookie ? document.cookie.split('; ') : [];
var i = 0;
for (; i < cookies.length; i++) {
var parts = cookies[i].split('=');
var cookie = parts.slice(1).join('=');
if (!this.json && cookie.charAt(0) === '"') {
cookie = cookie.slice(1, -1);
}
try {
var name = decode(parts[0]);
cookie = (converter.read || converter)(cookie, name) ||
decode(cookie);
if (this.json) {
try {
cookie = JSON.parse(cookie);
} catch (e) {}
}
jar[name] = cookie;
if (key === name) {
break;
}
} catch (e) {}
}
return key ? jar[key] : jar;
}
api.set = api;
api.get = function (key) {
return api.call(api, key);
};
api.getJSON = function (key) {
return api.call({
json: true
}, key);
};
api.remove = function (key, attributes) {
api(key, '', extend(attributes, {
expires: -1
}));
};
api.defaults = {};
api.withConverter = init;
return api;
}
return init(function () {});
}));
|
/*
YUI 3.5.0 (build 5089)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('dom-base', function(Y) {
/**
* @for DOM
* @module dom
*/
var documentElement = Y.config.doc.documentElement,
Y_DOM = Y.DOM,
TAG_NAME = 'tagName',
OWNER_DOCUMENT = 'ownerDocument',
EMPTY_STRING = '',
addFeature = Y.Features.add,
testFeature = Y.Features.test;
Y.mix(Y_DOM, {
/**
* Returns the text content of the HTMLElement.
* @method getText
* @param {HTMLElement} element The html element.
* @return {String} The text content of the element (includes text of any descending elements).
*/
getText: (documentElement.textContent !== undefined) ?
function(element) {
var ret = '';
if (element) {
ret = element.textContent;
}
return ret || '';
} : function(element) {
var ret = '';
if (element) {
ret = element.innerText || element.nodeValue; // might be a textNode
}
return ret || '';
},
/**
* Sets the text content of the HTMLElement.
* @method setText
* @param {HTMLElement} element The html element.
* @param {String} content The content to add.
*/
setText: (documentElement.textContent !== undefined) ?
function(element, content) {
if (element) {
element.textContent = content;
}
} : function(element, content) {
if ('innerText' in element) {
element.innerText = content;
} else if ('nodeValue' in element) {
element.nodeValue = content;
}
},
CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8
'for': 'htmlFor',
'class': 'className'
} : { // w3c
'htmlFor': 'for',
'className': 'class'
},
/**
* Provides a normalized attribute interface.
* @method setAttribute
* @param {HTMLElement} el The target element for the attribute.
* @param {String} attr The attribute to set.
* @param {String} val The value of the attribute.
*/
setAttribute: function(el, attr, val, ieAttr) {
if (el && attr && el.setAttribute) {
attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
el.setAttribute(attr, val, ieAttr);
}
else { Y.log('bad input to setAttribute', 'warn', 'dom'); }
},
/**
* Provides a normalized attribute interface.
* @method getAttribute
* @param {HTMLElement} el The target element for the attribute.
* @param {String} attr The attribute to get.
* @return {String} The current value of the attribute.
*/
getAttribute: function(el, attr, ieAttr) {
ieAttr = (ieAttr !== undefined) ? ieAttr : 2;
var ret = '';
if (el && attr && el.getAttribute) {
attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr;
ret = el.getAttribute(attr, ieAttr);
if (ret === null) {
ret = ''; // per DOM spec
}
}
else { Y.log('bad input to getAttribute', 'warn', 'dom'); }
return ret;
},
VALUE_SETTERS: {},
VALUE_GETTERS: {},
getValue: function(node) {
var ret = '', // TODO: return null?
getter;
if (node && node[TAG_NAME]) {
getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()];
if (getter) {
ret = getter(node);
} else {
ret = node.value;
}
}
// workaround for IE8 JSON stringify bug
// which converts empty string values to null
if (ret === EMPTY_STRING) {
ret = EMPTY_STRING; // for real
}
return (typeof ret === 'string') ? ret : '';
},
setValue: function(node, val) {
var setter;
if (node && node[TAG_NAME]) {
setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()];
if (setter) {
setter(node, val);
} else {
node.value = val;
}
}
},
creators: {}
});
addFeature('value-set', 'select', {
test: function() {
var node = Y.config.doc.createElement('select');
node.innerHTML = '<option>1</option><option>2</option>';
node.value = '2';
return (node.value && node.value === '2');
}
});
if (!testFeature('value-set', 'select')) {
Y_DOM.VALUE_SETTERS.select = function(node, val) {
for (var i = 0, options = node.getElementsByTagName('option'), option;
option = options[i++];) {
if (Y_DOM.getValue(option) === val) {
option.selected = true;
//Y_DOM.setAttribute(option, 'selected', 'selected');
break;
}
}
}
}
Y.mix(Y_DOM.VALUE_GETTERS, {
button: function(node) {
return (node.attributes && node.attributes.value) ? node.attributes.value.value : '';
}
});
Y.mix(Y_DOM.VALUE_SETTERS, {
// IE: node.value changes the button text, which should be handled via innerHTML
button: function(node, val) {
var attr = node.attributes.value;
if (!attr) {
attr = node[OWNER_DOCUMENT].createAttribute('value');
node.setAttributeNode(attr);
}
attr.value = val;
}
});
Y.mix(Y_DOM.VALUE_GETTERS, {
option: function(node) {
var attrs = node.attributes;
return (attrs.value && attrs.value.specified) ? node.value : node.text;
},
select: function(node) {
var val = node.value,
options = node.options;
if (options && options.length) {
// TODO: implement multipe select
if (node.multiple) {
Y.log('multiple select normalization not implemented', 'warn', 'DOM');
} else if (node.selectedIndex > -1) {
val = Y_DOM.getValue(options[node.selectedIndex]);
}
}
return val;
}
});
var addClass, hasClass, removeClass;
Y.mix(Y.DOM, {
/**
* Determines whether a DOM element has the given className.
* @method hasClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to search for
* @return {Boolean} Whether or not the element has the given class.
*/
hasClass: function(node, className) {
var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)');
return re.test(node.className);
},
/**
* Adds a class name to a given DOM element.
* @method addClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to add to the class attribute
*/
addClass: function(node, className) {
if (!Y.DOM.hasClass(node, className)) { // skip if already present
node.className = Y.Lang.trim([node.className, className].join(' '));
}
},
/**
* Removes a class name from a given element.
* @method removeClass
* @for DOM
* @param {HTMLElement} element The DOM element.
* @param {String} className the class name to remove from the class attribute
*/
removeClass: function(node, className) {
if (className && hasClass(node, className)) {
node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' +
className + '(?:\\s+|$)'), ' '));
if ( hasClass(node, className) ) { // in case of multiple adjacent
removeClass(node, className);
}
}
},
/**
* Replace a class with another class for a given element.
* If no oldClassName is present, the newClassName is simply added.
* @method replaceClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} oldClassName the class name to be replaced
* @param {String} newClassName the class name that will be replacing the old class name
*/
replaceClass: function(node, oldC, newC) {
//Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node');
removeClass(node, oldC); // remove first in case oldC === newC
addClass(node, newC);
},
/**
* If the className exists on the node it is removed, if it doesn't exist it is added.
* @method toggleClass
* @for DOM
* @param {HTMLElement} element The DOM element
* @param {String} className the class name to be toggled
* @param {Boolean} addClass optional boolean to indicate whether class
* should be added or removed regardless of current state
*/
toggleClass: function(node, className, force) {
var add = (force !== undefined) ? force :
!(hasClass(node, className));
if (add) {
addClass(node, className);
} else {
removeClass(node, className);
}
}
});
hasClass = Y.DOM.hasClass;
removeClass = Y.DOM.removeClass;
addClass = Y.DOM.addClass;
var re_tag = /<([a-z]+)/i,
Y_DOM = Y.DOM,
addFeature = Y.Features.add,
testFeature = Y.Features.test,
creators = {},
createFromDIV = function(html, tag) {
var div = Y.config.doc.createElement('div'),
ret = true;
div.innerHTML = html;
if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) {
ret = false;
}
return ret;
},
re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/,
TABLE_OPEN = '<table>',
TABLE_CLOSE = '</table>';
Y.mix(Y.DOM, {
_fragClones: {},
_create: function(html, doc, tag) {
tag = tag || 'div';
var frag = Y_DOM._fragClones[tag];
if (frag) {
frag = frag.cloneNode(false);
} else {
frag = Y_DOM._fragClones[tag] = doc.createElement(tag);
}
frag.innerHTML = html;
return frag;
},
_children: function(node, tag) {
var i = 0,
children = node.children,
childNodes,
hasComments,
child;
if (children && children.tags) { // use tags filter when possible
if (tag) {
children = node.children.tags(tag);
} else { // IE leaks comments into children
hasComments = children.tags('!').length;
}
}
if (!children || (!children.tags && tag) || hasComments) {
childNodes = children || node.childNodes;
children = [];
while ((child = childNodes[i++])) {
if (child.nodeType === 1) {
if (!tag || tag === child.tagName) {
children.push(child);
}
}
}
}
return children || [];
},
/**
* Creates a new dom node using the provided markup string.
* @method create
* @param {String} html The markup used to create the element
* @param {HTMLDocument} doc An optional document context
* @return {HTMLElement|DocumentFragment} returns a single HTMLElement
* when creating one node, and a documentFragment when creating
* multiple nodes.
*/
create: function(html, doc) {
if (typeof html === 'string') {
html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML
}
doc = doc || Y.config.doc;
var m = re_tag.exec(html),
create = Y_DOM._create,
custom = creators,
ret = null,
creator,
tag, nodes;
if (html != undefined) { // not undefined or null
if (m && m[1]) {
creator = custom[m[1].toLowerCase()];
if (typeof creator === 'function') {
create = creator;
} else {
tag = creator;
}
}
nodes = create(html, doc, tag).childNodes;
if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment"
ret = nodes[0].parentNode.removeChild(nodes[0]);
} else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected)
if (nodes.length === 2) {
ret = nodes[0].nextSibling;
} else {
nodes[0].parentNode.removeChild(nodes[0]);
ret = Y_DOM._nl2frag(nodes, doc);
}
} else { // return multiple nodes as a fragment
ret = Y_DOM._nl2frag(nodes, doc);
}
}
return ret;
},
_nl2frag: function(nodes, doc) {
var ret = null,
i, len;
if (nodes && (nodes.push || nodes.item) && nodes[0]) {
doc = doc || nodes[0].ownerDocument;
ret = doc.createDocumentFragment();
if (nodes.item) { // convert live list to static array
nodes = Y.Array(nodes, 0, true);
}
for (i = 0, len = nodes.length; i < len; i++) {
ret.appendChild(nodes[i]);
}
} // else inline with log for minification
return ret;
},
/**
* Inserts content in a node at the given location
* @method addHTML
* @param {HTMLElement} node The node to insert into
* @param {HTMLElement | Array | HTMLCollection} content The content to be inserted
* @param {HTMLElement} where Where to insert the content
* If no "where" is given, content is appended to the node
* Possible values for "where"
* <dl>
* <dt>HTMLElement</dt>
* <dd>The element to insert before</dd>
* <dt>"replace"</dt>
* <dd>Replaces the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts before the existing HTML</dd>
* <dt>"before"</dt>
* <dd>Inserts content before the node</dd>
* <dt>"after"</dt>
* <dd>Inserts content after the node</dd>
* </dl>
*/
addHTML: function(node, content, where) {
var nodeParent = node.parentNode,
i = 0,
item,
ret = content,
newNode;
if (content != undefined) { // not null or undefined (maybe 0)
if (content.nodeType) { // DOM node, just add it
newNode = content;
} else if (typeof content == 'string' || typeof content == 'number') {
ret = newNode = Y_DOM.create(content);
} else if (content[0] && content[0].nodeType) { // array or collection
newNode = Y.config.doc.createDocumentFragment();
while ((item = content[i++])) {
newNode.appendChild(item); // append to fragment for insertion
}
}
}
if (where) {
if (newNode && where.parentNode) { // insert regardless of relationship to node
where.parentNode.insertBefore(newNode, where);
} else {
switch (where) {
case 'replace':
while (node.firstChild) {
node.removeChild(node.firstChild);
}
if (newNode) { // allow empty content to clear node
node.appendChild(newNode);
}
break;
case 'before':
if (newNode) {
nodeParent.insertBefore(newNode, node);
}
break;
case 'after':
if (newNode) {
if (node.nextSibling) { // IE errors if refNode is null
nodeParent.insertBefore(newNode, node.nextSibling);
} else {
nodeParent.appendChild(newNode);
}
}
break;
default:
if (newNode) {
node.appendChild(newNode);
}
}
}
} else if (newNode) {
node.appendChild(newNode);
}
return ret;
},
wrap: function(node, html) {
var parent = (html && html.nodeType) ? html : Y.DOM.create(html),
nodes = parent.getElementsByTagName('*');
if (nodes.length) {
parent = nodes[nodes.length - 1];
}
if (node.parentNode) {
node.parentNode.replaceChild(parent, node);
}
parent.appendChild(node);
},
unwrap: function(node) {
var parent = node.parentNode,
lastChild = parent.lastChild,
next = node,
grandparent;
if (parent) {
grandparent = parent.parentNode;
if (grandparent) {
node = parent.firstChild;
while (node !== lastChild) {
next = node.nextSibling;
grandparent.insertBefore(node, parent);
node = next;
}
grandparent.replaceChild(lastChild, parent);
} else {
parent.removeChild(node);
}
}
}
});
addFeature('innerhtml', 'table', {
test: function() {
var node = Y.config.doc.createElement('table');
try {
node.innerHTML = '<tbody></tbody>';
} catch(e) {
return false;
}
return (node.firstChild && node.firstChild.nodeName === 'TBODY');
}
});
addFeature('innerhtml-div', 'tr', {
test: function() {
return createFromDIV('<tr></tr>', 'tr');
}
});
addFeature('innerhtml-div', 'script', {
test: function() {
return createFromDIV('<script></script>', 'script');
}
});
if (!testFeature('innerhtml', 'table')) {
// TODO: thead/tfoot with nested tbody
// IE adds TBODY when creating TABLE elements (which may share this impl)
creators.tbody = function(html, doc) {
var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc),
tb = Y.DOM._children(frag, 'tbody')[0];
if (frag.children.length > 1 && tb && !re_tbody.test(html)) {
tb.parentNode.removeChild(tb); // strip extraneous tbody
}
return frag;
};
}
if (!testFeature('innerhtml-div', 'script')) {
creators.script = function(html, doc) {
var frag = doc.createElement('div');
frag.innerHTML = '-' + html;
frag.removeChild(frag.firstChild);
return frag;
}
creators.link = creators.style = creators.script;
}
if (!testFeature('innerhtml-div', 'tr')) {
Y.mix(creators, {
option: function(html, doc) {
return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc);
},
tr: function(html, doc) {
return Y_DOM.create('<tbody>' + html + '</tbody>', doc);
},
td: function(html, doc) {
return Y_DOM.create('<tr>' + html + '</tr>', doc);
},
col: function(html, doc) {
return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc);
},
tbody: 'table'
});
Y.mix(creators, {
legend: 'fieldset',
th: creators.td,
thead: creators.tbody,
tfoot: creators.tbody,
caption: creators.tbody,
colgroup: creators.tbody,
optgroup: creators.option
});
}
Y_DOM.creators = creators;
Y.mix(Y.DOM, {
/**
* Sets the width of the element to the given size, regardless
* of box model, border, padding, etc.
* @method setWidth
* @param {HTMLElement} element The DOM element.
* @param {String|Number} size The pixel height to size to
*/
setWidth: function(node, size) {
Y.DOM._setSize(node, 'width', size);
},
/**
* Sets the height of the element to the given size, regardless
* of box model, border, padding, etc.
* @method setHeight
* @param {HTMLElement} element The DOM element.
* @param {String|Number} size The pixel height to size to
*/
setHeight: function(node, size) {
Y.DOM._setSize(node, 'height', size);
},
_setSize: function(node, prop, val) {
val = (val > 0) ? val : 0;
var size = 0;
node.style[prop] = val + 'px';
size = (prop === 'height') ? node.offsetHeight : node.offsetWidth;
if (size > val) {
val = val - (size - val);
if (val < 0) {
val = 0;
}
node.style[prop] = val + 'px';
}
}
});
}, '3.5.0' ,{requires:['dom-core']});
|
/*
* Copyright (c) 2009 WiQuery team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/** Hebrew translation */
jQuery(function($) {
$.ui.dialog.wiquery.regional['iw'] = {
okButton: 'אישור',
cancelButton: 'ביטול',
questionTitle: 'שאלה',
waitTitle: 'אנא המתן',
errorTitle: 'שגיאה',
warningTitle: 'אזהרה'
};
});
|
module.exports = {
"plugins": [
"react",
"spellcheck"
],
"env": {
"browser": true,
"commonjs": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"settings": {
"react": {
"version": "16"
}
},
"parserOptions": {
"ecmaFeatures": {
"jsx": true,
"arrowFunctions": true,
"blockBindings": true,
"classes": true,
"defaultParams": true,
"destructuring": true,
"forOf": true,
"generators": true,
"modules": true,
"objectLiteralComputedProperties": true,
"regexUFlag": true,
"regexYFlag": true,
"spread": true,
"superInFunctions": false,
"templateStrings": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
"globals": {
"__": false,
"Promise": false,
"VERSION": false
},
"rules": {
"semi": "error",
"no-var": "error",
"quotes": ["warn", "double" ],
"indent": ["warn", 4, {"SwitchCase": 1}],
"no-unused-vars": "warn",
"no-console": "warn",
"keyword-spacing": "warn",
"eqeqeq": "warn",
"space-before-function-paren": ["warn", { "anonymous": "always", "named": "never" }],
"space-before-blocks": "warn",
"no-multiple-empty-lines": "warn",
"react/jsx-equals-spacing": ["warn", "never"],
"id-match": ["error", "^([A-Za-z0-9_])+$", {"properties": true}]
}
};
|
var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;
var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;
var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;
module.exports.translate = function (load) {
if (load.source.indexOf('moduleId') != -1) return load;
var url = document.createElement('a');
url.href = load.address;
var basePathParts = url.pathname.split('/');
basePathParts.pop();
var basePath = basePathParts.join('/');
var baseHref = document.createElement('a');
baseHref.href = this.baseURL;
baseHref = baseHref.pathname;
if (!baseHref.startsWith('/base/')) { // it is not karma
basePath = basePath.replace(baseHref, '');
}
load.source = load.source
.replace(templateUrlRegex, function (match, quote, url) {
let resolvedUrl = url;
if (url.startsWith('.')) {
resolvedUrl = basePath + url.substr(1);
}
return 'templateUrl: "' + resolvedUrl + '"';
})
.replace(stylesRegex, function (match, relativeUrls) {
var urls = [];
while ((match = stringRegex.exec(relativeUrls)) !== null) {
if (match[2].startsWith('.')) {
urls.push('"' + basePath + match[2].substr(1) + '"');
} else {
urls.push('"' + match[2] + '"');
}
}
return "styleUrls: [" + urls.join(', ') + "]";
});
return load;
};
|
/*
* Ensure gap/indent handling deals with NUL codepoints correctly.
*/
/*===
{
--<NUL>-->"foo": 1,
--<NUL>-->"bar": 2,
--<NUL>-->"quux": 3,
--<NUL>-->"baz": [
--<NUL>-->--<NUL>-->1,
--<NUL>-->--<NUL>-->2,
--<NUL>-->--<NUL>-->3
--<NUL>-->]
}
===*/
function nulInGapTest() {
var obj = { foo: 1, bar: 2, quux: 3, baz: [ 1, 2, 3 ] };
var res;
// NUL in the middle of gap should not be an issue.
res = JSON.stringify(obj, null, '--\u0000-->');
print(res.replace(/\u0000/g, '<NUL>'));
}
try {
nulInGapTest();
} catch (e) {
print(e.stack || e);
}
|
'use strict';
var es = require('event-stream');
var Writer = require('./Writer');
var EMPTY_COMPONENT = '$$';
function writeLog(commits, options, done) {
var log = '';
var stream = es.through(function(data) {
log += data;
}, function() {
done(null, log);
});
var writer = new Writer(stream, options);
var sections = {
fix: {},
feat: {},
breaks: {}
};
commits.forEach(function(commit) {
var section = sections[commit.type];
var component = commit.component || EMPTY_COMPONENT;
if (section) {
section[component] = section[component] || [];
section[component].push(commit);
}
commit.breaks.forEach(function(breakMsg) {
sections.breaks[EMPTY_COMPONENT] = sections.breaks[EMPTY_COMPONENT] || [];
sections.breaks[EMPTY_COMPONENT].push({
subject: breakMsg,
hash: commit.hash,
closes: []
});
});
});
if (!writer.header()) {
return done('No version specified');
}
writer.section('Bug Fixes', sections.fix);
writer.section('Features', sections.feat);
writer.section('Breaking Changes', sections.breaks);
writer.end();
}
module.exports = writeLog;
|
'use strict';
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
/**
* --------------------------------------------------------------------------
* Bootstrap (v4.0.0-alpha.2): modal.js
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* --------------------------------------------------------------------------
*/
var Modal = (function ($) {
/**
* ------------------------------------------------------------------------
* Constants
* ------------------------------------------------------------------------
*/
var NAME = 'modal';
var VERSION = '4.0.0-alpha.2';
var DATA_KEY = 'bs.modal';
var EVENT_KEY = '.' + DATA_KEY;
var DATA_API_KEY = '.data-api';
var JQUERY_NO_CONFLICT = $.fn[NAME];
var TRANSITION_DURATION = 300;
var BACKDROP_TRANSITION_DURATION = 150;
var Default = {
backdrop: true,
keyboard: true,
focus: true,
show: true
};
var DefaultType = {
backdrop: '(boolean|string)',
keyboard: 'boolean',
focus: 'boolean',
show: 'boolean'
};
var Event = {
HIDE: 'hide' + EVENT_KEY,
HIDDEN: 'hidden' + EVENT_KEY,
SHOW: 'show' + EVENT_KEY,
SHOWN: 'shown' + EVENT_KEY,
FOCUSIN: 'focusin' + EVENT_KEY,
RESIZE: 'resize' + EVENT_KEY,
CLICK_DISMISS: 'click.dismiss' + EVENT_KEY,
KEYDOWN_DISMISS: 'keydown.dismiss' + EVENT_KEY,
MOUSEUP_DISMISS: 'mouseup.dismiss' + EVENT_KEY,
MOUSEDOWN_DISMISS: 'mousedown.dismiss' + EVENT_KEY,
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
};
var ClassName = {
SCROLLBAR_MEASURER: 'modal-scrollbar-measure',
BACKDROP: 'modal-backdrop',
OPEN: 'modal-open',
FADE: 'fade',
IN: 'in'
};
var Selector = {
DIALOG: '.modal-dialog',
DATA_TOGGLE: '[data-toggle="modal"]',
DATA_DISMISS: '[data-dismiss="modal"]',
FIXED_CONTENT: '.navbar-fixed-top, .navbar-fixed-bottom, .is-fixed'
};
/**
* ------------------------------------------------------------------------
* Class Definition
* ------------------------------------------------------------------------
*/
var Modal = (function () {
function Modal(element, config) {
_classCallCheck(this, Modal);
this._config = this._getConfig(config);
this._element = element;
this._dialog = $(element).find(Selector.DIALOG)[0];
this._backdrop = null;
this._isShown = false;
this._isBodyOverflowing = false;
this._ignoreBackdropClick = false;
this._originalBodyPadding = 0;
this._scrollbarWidth = 0;
}
/**
* ------------------------------------------------------------------------
* Data Api implementation
* ------------------------------------------------------------------------
*/
// getters
_createClass(Modal, [{
key: 'toggle',
// public
value: function toggle(relatedTarget) {
return this._isShown ? this.hide() : this.show(relatedTarget);
}
}, {
key: 'show',
value: function show(relatedTarget) {
var _this = this;
var showEvent = $.Event(Event.SHOW, {
relatedTarget: relatedTarget
});
$(this._element).trigger(showEvent);
if (this._isShown || showEvent.isDefaultPrevented()) {
return;
}
this._isShown = true;
this._checkScrollbar();
this._setScrollbar();
$(document.body).addClass(ClassName.OPEN);
this._setEscapeEvent();
this._setResizeEvent();
$(this._element).on(Event.CLICK_DISMISS, Selector.DATA_DISMISS, $.proxy(this.hide, this));
$(this._dialog).on(Event.MOUSEDOWN_DISMISS, function () {
$(_this._element).one(Event.MOUSEUP_DISMISS, function (event) {
if ($(event.target).is(_this._element)) {
_this._ignoreBackdropClick = true;
}
});
});
this._showBackdrop($.proxy(this._showElement, this, relatedTarget));
}
}, {
key: 'hide',
value: function hide(event) {
if (event) {
event.preventDefault();
}
var hideEvent = $.Event(Event.HIDE);
$(this._element).trigger(hideEvent);
if (!this._isShown || hideEvent.isDefaultPrevented()) {
return;
}
this._isShown = false;
this._setEscapeEvent();
this._setResizeEvent();
$(document).off(Event.FOCUSIN);
$(this._element).removeClass(ClassName.IN);
$(this._element).off(Event.CLICK_DISMISS);
$(this._dialog).off(Event.MOUSEDOWN_DISMISS);
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
$(this._element).one(Util.TRANSITION_END, $.proxy(this._hideModal, this)).emulateTransitionEnd(TRANSITION_DURATION);
} else {
this._hideModal();
}
}
}, {
key: 'dispose',
value: function dispose() {
$.removeData(this._element, DATA_KEY);
$(window).off(EVENT_KEY);
$(document).off(EVENT_KEY);
$(this._element).off(EVENT_KEY);
$(this._backdrop).off(EVENT_KEY);
this._config = null;
this._element = null;
this._dialog = null;
this._backdrop = null;
this._isShown = null;
this._isBodyOverflowing = null;
this._ignoreBackdropClick = null;
this._originalBodyPadding = null;
this._scrollbarWidth = null;
}
// private
}, {
key: '_getConfig',
value: function _getConfig(config) {
config = $.extend({}, Default, config);
Util.typeCheckConfig(NAME, config, DefaultType);
return config;
}
}, {
key: '_showElement',
value: function _showElement(relatedTarget) {
var _this2 = this;
var transition = Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE);
if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) {
// don't move modals dom position
document.body.appendChild(this._element);
}
this._element.style.display = 'block';
this._element.scrollTop = 0;
if (transition) {
Util.reflow(this._element);
}
$(this._element).addClass(ClassName.IN);
if (this._config.focus) {
this._enforceFocus();
}
var shownEvent = $.Event(Event.SHOWN, {
relatedTarget: relatedTarget
});
var transitionComplete = function transitionComplete() {
if (_this2._config.focus) {
_this2._element.focus();
}
$(_this2._element).trigger(shownEvent);
};
if (transition) {
$(this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(TRANSITION_DURATION);
} else {
transitionComplete();
}
}
}, {
key: '_enforceFocus',
value: function _enforceFocus() {
var _this3 = this;
$(document).off(Event.FOCUSIN) // guard against infinite focus loop
.on(Event.FOCUSIN, function (event) {
if (document !== event.target && _this3._element !== event.target && !$(_this3._element).has(event.target).length) {
_this3._element.focus();
}
});
}
}, {
key: '_setEscapeEvent',
value: function _setEscapeEvent() {
var _this4 = this;
if (this._isShown && this._config.keyboard) {
$(this._element).on(Event.KEYDOWN_DISMISS, function (event) {
if (event.which === 27) {
_this4.hide();
}
});
} else if (!this._isShown) {
$(this._element).off(Event.KEYDOWN_DISMISS);
}
}
}, {
key: '_setResizeEvent',
value: function _setResizeEvent() {
if (this._isShown) {
$(window).on(Event.RESIZE, $.proxy(this._handleUpdate, this));
} else {
$(window).off(Event.RESIZE);
}
}
}, {
key: '_hideModal',
value: function _hideModal() {
var _this5 = this;
this._element.style.display = 'none';
this._showBackdrop(function () {
$(document.body).removeClass(ClassName.OPEN);
_this5._resetAdjustments();
_this5._resetScrollbar();
$(_this5._element).trigger(Event.HIDDEN);
});
}
}, {
key: '_removeBackdrop',
value: function _removeBackdrop() {
if (this._backdrop) {
$(this._backdrop).remove();
this._backdrop = null;
}
}
}, {
key: '_showBackdrop',
value: function _showBackdrop(callback) {
var _this6 = this;
var animate = $(this._element).hasClass(ClassName.FADE) ? ClassName.FADE : '';
if (this._isShown && this._config.backdrop) {
var doAnimate = Util.supportsTransitionEnd() && animate;
this._backdrop = document.createElement('div');
this._backdrop.className = ClassName.BACKDROP;
if (animate) {
$(this._backdrop).addClass(animate);
}
$(this._backdrop).appendTo(document.body);
$(this._element).on(Event.CLICK_DISMISS, function (event) {
if (_this6._ignoreBackdropClick) {
_this6._ignoreBackdropClick = false;
return;
}
if (event.target !== event.currentTarget) {
return;
}
if (_this6._config.backdrop === 'static') {
_this6._element.focus();
} else {
_this6.hide();
}
});
if (doAnimate) {
Util.reflow(this._backdrop);
}
$(this._backdrop).addClass(ClassName.IN);
if (!callback) {
return;
}
if (!doAnimate) {
callback();
return;
}
$(this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else if (!this._isShown && this._backdrop) {
$(this._backdrop).removeClass(ClassName.IN);
var callbackRemove = function callbackRemove() {
_this6._removeBackdrop();
if (callback) {
callback();
}
};
if (Util.supportsTransitionEnd() && $(this._element).hasClass(ClassName.FADE)) {
$(this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(BACKDROP_TRANSITION_DURATION);
} else {
callbackRemove();
}
} else if (callback) {
callback();
}
}
// ----------------------------------------------------------------------
// the following methods are used to handle overflowing modals
// todo (fat): these should probably be refactored out of modal.js
// ----------------------------------------------------------------------
}, {
key: '_handleUpdate',
value: function _handleUpdate() {
this._adjustDialog();
}
}, {
key: '_adjustDialog',
value: function _adjustDialog() {
var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight;
if (!this._isBodyOverflowing && isModalOverflowing) {
this._element.style.paddingLeft = this._scrollbarWidth + 'px';
}
if (this._isBodyOverflowing && !isModalOverflowing) {
this._element.style.paddingRight = this._scrollbarWidth + 'px~';
}
}
}, {
key: '_resetAdjustments',
value: function _resetAdjustments() {
this._element.style.paddingLeft = '';
this._element.style.paddingRight = '';
}
}, {
key: '_checkScrollbar',
value: function _checkScrollbar() {
var fullWindowWidth = window.innerWidth;
if (!fullWindowWidth) {
// workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect();
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left);
}
this._isBodyOverflowing = document.body.clientWidth < fullWindowWidth;
this._scrollbarWidth = this._getScrollbarWidth();
}
}, {
key: '_setScrollbar',
value: function _setScrollbar() {
var bodyPadding = parseInt($(Selector.FIXED_CONTENT).css('padding-right') || 0, 10);
this._originalBodyPadding = document.body.style.paddingRight || '';
if (this._isBodyOverflowing) {
document.body.style.paddingRight = bodyPadding + this._scrollbarWidth + 'px';
}
}
}, {
key: '_resetScrollbar',
value: function _resetScrollbar() {
document.body.style.paddingRight = this._originalBodyPadding;
}
}, {
key: '_getScrollbarWidth',
value: function _getScrollbarWidth() {
// thx d.walsh
var scrollDiv = document.createElement('div');
scrollDiv.className = ClassName.SCROLLBAR_MEASURER;
document.body.appendChild(scrollDiv);
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
}
// static
}], [{
key: '_jQueryInterface',
value: function _jQueryInterface(config, relatedTarget) {
return this.each(function () {
var data = $(this).data(DATA_KEY);
var _config = $.extend({}, Modal.Default, $(this).data(), typeof config === 'object' && config);
if (!data) {
data = new Modal(this, _config);
$(this).data(DATA_KEY, data);
}
if (typeof config === 'string') {
if (data[config] === undefined) {
throw new Error('No method named "' + config + '"');
}
data[config](relatedTarget);
} else if (_config.show) {
data.show(relatedTarget);
}
});
}
}, {
key: 'VERSION',
get: function get() {
return VERSION;
}
}, {
key: 'Default',
get: function get() {
return Default;
}
}]);
return Modal;
})();
$(document).on(Event.CLICK_DATA_API, Selector.DATA_TOGGLE, function (event) {
var _this7 = this;
var target = undefined;
var selector = Util.getSelectorFromElement(this);
if (selector) {
target = $(selector)[0];
}
var config = $(target).data(DATA_KEY) ? 'toggle' : $.extend({}, $(target).data(), $(this).data());
if (this.tagName === 'A') {
event.preventDefault();
}
var $target = $(target).one(Event.SHOW, function (showEvent) {
if (showEvent.isDefaultPrevented()) {
// only register focus restorer if modal will actually get shown
return;
}
$target.one(Event.HIDDEN, function () {
if ($(_this7).is(':visible')) {
_this7.focus();
}
});
});
Modal._jQueryInterface.call($(target), config, this);
});
/**
* ------------------------------------------------------------------------
* jQuery
* ------------------------------------------------------------------------
*/
$.fn[NAME] = Modal._jQueryInterface;
$.fn[NAME].Constructor = Modal;
$.fn[NAME].noConflict = function () {
$.fn[NAME] = JQUERY_NO_CONFLICT;
return Modal._jQueryInterface;
};
return Modal;
})(jQuery);
//# sourceMappingURL=modal.js.map
|
version https://git-lfs.github.com/spec/v1
oid sha256:a5547ad40d959d0925dead85818b7e457ac214b497b446f03e9497ffbe7ec60e
size 2245
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'liststyle', 'sl', {
armenian: 'Armenian numbering',
bulletedTitle: 'Bulleted List Properties',
circle: 'Circle',
decimal: 'Decimal (1, 2, 3, etc.)',
decimalLeadingZero: 'Decimal leading zero (01, 02, 03, etc.)',
disc: 'Disc',
georgian: 'Georgian numbering (an, ban, gan, etc.)',
lowerAlpha: 'Lower Alpha (a, b, c, d, e, etc.)',
lowerGreek: 'Lower Greek (alpha, beta, gamma, etc.)',
lowerRoman: 'Lower Roman (i, ii, iii, iv, v, etc.)',
none: 'None',
notset: '<not set>',
numberedTitle: 'Numbered List Properties',
square: 'Square',
start: 'Start',
type: 'Type',
upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)',
upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)',
validateStartNumber: 'List start number must be a whole number.'
} );
|
/****************************************************************************
http://www.cocos2d-html5.org
http://www.cocos2d-iphone.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var unitTestSceneIdx = -1;
//------------------------------------------------------------------
//
// UnitTestBase
//
//------------------------------------------------------------------
var UnitTestBase = BaseTestLayer.extend({
_title:"",
_subtitle:"",
onRestartCallback:function (sender) {
var s = new UnitTestScene();
s.addChild(restartUnitTest());
director.replaceScene(s);
},
onNextCallback:function (sender) {
var s = new UnitTestScene();
s.addChild(nextUnitTest());
director.replaceScene(s);
},
onBackCallback:function (sender) {
var s = new UnitTestScene();
s.addChild(previousUnitTest());
director.replaceScene(s);
},
// automation
numberOfPendingTests:function() {
return ( (arrayOfUnitTest.length-1) - unitTestSceneIdx );
},
getTestNumber:function() {
return unitTestSceneIdx;
}
});
//------------------------------------------------------------------
//
// RectUnitTest
//
//------------------------------------------------------------------
var RectUnitTest = UnitTestBase.extend({
_title:"Rect Unit Test",
_subtitle:"See console for possible errors",
onEnter:function () {
this._super();
this.runTest();
},
runTest:function () {
var ret = [];
var rectA;
var rectB;
var rectC;
var point;
var r;
this.log("Test 1: rectIntersectsRect 1");
rectA = cc.rect(0,0,5,10);
rectB = cc.rect(4,9,5,10);
r = cc.rectIntersectsRect(rectA, rectB);
if(!r)
throw "Fail rectIntersectsRect 1";
ret.push(r);
this.log("Test 2: rectIntersectsRect 2");
rectA = cc.rect(0,0,5,10);
rectB = cc.rect(40,90,5,10);
r = cc.rectIntersectsRect(rectA, rectB);
if(r)
throw "Fail rectIntersectsRect 2";
ret.push(r);
this.log("Test 3: rectIntersection");
rectA = cc.rect(0,0,5,10);
rectB = cc.rect(4,9,5,10);
rectC = cc.rectIntersection(rectA, rectB);
r = cc.rectEqualToRect(rectC, cc.rect(4,9,1,1) );
if(!r)
throw "Fail rectIntersection";
ret.push(r);
this.log("Test 4: rectUnion");
rectA = cc.rect(0,0,5,10);
rectB = cc.rect(4,9,5,10);
rectC = cc.rectUnion(rectA, rectB);
r = cc.rectEqualToRect(rectC, cc.rect(0,0,9,19) );
if(!r)
throw "Fail rectUnion";
ret.push(r);
this.log("Test 5: rectContainsPoint 1");
rectA = cc.rect(0,0,5,10);
point = cc.p(1,1);
r = cc.rectContainsPoint(rectA, point);
if(!r)
throw "Fail rectContainsPoint 1";
ret.push(r);
this.log("Test 6: rectContainsPoint 2");
rectA = cc.rect(0,0,5,10);
point = cc.p(1,-1);
r = cc.rectContainsPoint(rectA, point);
if(r)
throw "Fail rectContainsPoint 2";
ret.push(r);
this.log("Test 7: rect property x");
rectA = cc.rect(1,2,3,4);
if( rectA.x != 1)
throw "Fail rect property x";
ret.push(rectA.x);
this.log("Test 8: rect property y");
rectA = cc.rect(1,2,3,4);
if( rectA.y != 2)
throw "Fail rect property y";
ret.push(rectA.y);
this.log("Test 9: rect property width");
rectA = cc.rect(1,2,3,4);
if( rectA.width != 3)
throw "Fail rect property width";
ret.push(rectA.width);
this.log("Test 10: rect property height");
rectA = cc.rect(1,2,3,4);
if( rectA.height != 4)
throw "Fail rect property height";
ret.push(rectA.height);
this.log("Test 11: getBoundingBox()");
var node = cc.Node.create();
node.setContentSize( cc.size(99,101) );
var bb = node.getBoundingBox();
if( bb.height != 101 || bb.width != 99)
throw "Fail getBoundingBox()";
ret.push( bb.height );
ret.push( bb.width );
return ret;
},
//
// Automation
//
testDuration:0.1,
getExpectedResult:function() {
var ret = [true,false,true,true,true,false,1,2,3,4,101,99];
return JSON.stringify(ret);
},
getCurrentResult:function() {
var ret = this.runTest();
return JSON.stringify(ret);
}
});
//------------------------------------------------------------------
//
// DictionaryToFromTest
//
//------------------------------------------------------------------
var DictionaryToFromTest = UnitTestBase.extend({
_title:"Dictionary To/From Test",
_subtitle:"Sends and receives a dictionary to JSB",
ctor:function() {
this._super();
this.runTest();
},
runTest:function() {
var frameCache = cc.SpriteFrameCache.getInstance();
frameCache.addSpriteFrames(s_grossiniPlist);
// Purge previously loaded animation
var animCache = cc.AnimationCache.getInstance();
animCache.addAnimations(s_animations2Plist);
var normal = animCache.getAnimation("dance_1");
var frame = normal.getFrames()[0];
var dict = frame.getUserInfo();
this.log( JSON.stringify(dict) );
frame.setUserInfo( {
"array":[1,2,3,"hello world"],
"bool0":0, // false XXX
"bool1":1, // true XXX
"dict":{"key1":"value1", "key2":2},
"number":42,
"string":"hello!"
});
dict = frame.getUserInfo();
this.log(JSON.stringify(dict));
return dict;
},
//
// Automation
//
testDuration:0.1,
getExpectedResult:function() {
var ret = this.sortObject( {"array":[1,2,3,"hello world"],"bool0":0,"bool1":1,"dict":{"key1":"value1","key2":2},"number":42,"string":"hello!"} );
return JSON.stringify(ret);
},
getCurrentResult:function() {
var ret = this.sortObject( this.runTest() );
return JSON.stringify(ret);
}
});
var UnitTestScene = TestScene.extend({
runThisTest:function () {
unitTestSceneIdx = -1;
var layer = nextUnitTest();
this.addChild(layer);
director.replaceScene(this);
}
});
//
// Flow control
//
var arrayOfUnitTest = [
RectUnitTest,
DictionaryToFromTest
];
var nextUnitTest = function () {
unitTestSceneIdx++;
unitTestSceneIdx = unitTestSceneIdx % arrayOfUnitTest.length;
return new arrayOfUnitTest[unitTestSceneIdx]();
};
var previousUnitTest = function () {
unitTestSceneIdx--;
if (unitTestSceneIdx < 0)
unitTestSceneIdx += arrayOfUnitTest.length;
return new arrayOfUnitTest[unitTestSceneIdx]();
};
var restartUnitTest = function () {
return new arrayOfUnitTest[unitTestSceneIdx]();
};
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'indent', 'lt', {
indent: 'Padidinti įtrauką',
outdent: 'Sumažinti įtrauką'
});
|
/* ========================================================================
* ZUI: boards.js
* http://zui.sexy
* ========================================================================
* Copyright (c) 2014 cnezsoft.com; Licensed MIT
* ======================================================================== */
(function($){
'use strict';
if (!$.fn.droppable) throw new Error('droppable requires for boards');
var Boards = function(element, options)
{
this.$ = $(element);
this.options = this.getOptions(options);
this.getLang();
this.init();
};
Boards.DEFAULTS = {
lang: 'zh-cn',
langs:
{
'zh-cn':
{
append2end: '移动到末尾'
},
'zh-tw':
{
append2end: '移动到末尾'
},
'en':
{
append2end: 'Move to the end.'
}
}
}; // default options
Boards.prototype.getOptions = function(options)
{
options = $.extend(
{}, Boards.DEFAULTS, this.$.data(), options);
return options;
};
Boards.prototype.getLang = function()
{
var config = window.config;
if (!this.options.lang)
{
if (typeof(config) != 'undefined' && config.clientLang)
{
this.options.lang = config.clientLang;
}
else
{
var hl = $('html').attr('lang');
this.options.lang = hl ? hl : 'en';
}
this.options.lang = this.options.lang.replace(/-/, '_').toLowerCase();
}
this.lang = this.options.langs[this.options.lang] || this.options.langs[Boards.DEFAULTS.lang];
};
Boards.prototype.init = function()
{
var idSeed = 1;
var lang = this.lang;
this.$.find('.board-item:not(".disable-drop"), .board:not(".disable-drop")').each(function()
{
var $this = $(this);
if ($this.attr('id'))
{
$this.attr('data-id', $this.attr('id'));
}
else if (!$this.attr('data-id'))
{
$this.attr('data-id', 'board' + (idSeed++));
}
if ($this.hasClass('board'))
{
$this.find('.board-list').append('<div class="board-item board-item-empty"><i class="icon-plus"></i> {append2end}</div>'.format(lang))
.append('<div class="board-item board-item-shadow"></div>'.format(lang));
}
});
this.bind();
};
Boards.prototype.bind = function(items)
{
var $boards = this.$,
setting = this.options;
if (typeof(items) == 'undefined')
{
items = $boards.find('.board-item:not(".disable-drop, .board-item-shadow")');
}
items.droppable(
{
before: setting.before,
target: '.board-item:not(".disable-drop, .board-item-shadow")',
flex: true,
start: function(e)
{
$boards.addClass('dragging').find('.board-item-shadow').height(e.element.outerHeight());
},
drag: function(e)
{
$boards.find('.board.drop-in-empty').removeClass('drop-in-empty');
if (e.isIn)
{
var board = e.target.closest('.board').addClass('drop-in');
var shadow = board.find('.board-item-shadow');
var target = e.target;
$boards.addClass('drop-in').find('.board.drop-in').not(board).removeClass('drop-in');
shadow.insertBefore(target);
board.toggleClass('drop-in-empty', target.hasClass('board-item-empty'));
}
},
drop: function(e)
{
if (e.isNew)
{
var DROP = 'drop';
var result;
if (setting.hasOwnProperty(DROP) && $.isFunction(setting[DROP]))
{
result = setting[DROP](e);
}
if (result !== false) e.element.insertBefore(e.target);
}
},
finish: function()
{
$boards.removeClass('dragging').removeClass('drop-in').find('.board.drop-in').removeClass('drop-in');
}
});
};
$.fn.boards = function(option)
{
return this.each(function()
{
var $this = $(this);
var data = $this.data('zui.boards');
var options = typeof option == 'object' && option;
if (!data) $this.data('zui.boards', (data = new Boards(this, options)));
if (typeof option == 'string') data[option]();
});
};
$.fn.boards.Constructor = Boards;
$(function()
{
$('[data-toggle="boards"]').boards();
});
}(jQuery));
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'contextmenu', 'mk', {
options: 'Контекст-мени опции'
} );
|
import format from './format';
import defaultLang from './lang/zh-CN';
let _lang = defaultLang
function use(lang) {
_lang = lang;
}
function t(path, options) {
const array = path.split('.');
let current = _lang;
for (var i = 0, j = array.length; i < j; i++) {
var property = array[i];
var value = current[property];
if (i === j - 1) return format(value, options);
if (!value) return '';
current = value;
}
return '';
}
export default {
use,
t
}
|
/*! asmCrypto v0.14.0, (c) 2018 Artem S Vybornov, opensource.org/licenses/MIT */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.asmCrypto = {})));
}(this, (function (exports) { 'use strict';
var FloatArray = typeof Float64Array !== "undefined" ? Float64Array : Float32Array; // make PhantomJS happy
function string_to_bytes ( str, utf8 ) {
utf8 = !!utf8;
var len = str.length,
bytes = new Uint8Array( utf8 ? 4*len : len );
for ( var i = 0, j = 0; i < len; i++ ) {
var c = str.charCodeAt(i);
if ( utf8 && 0xd800 <= c && c <= 0xdbff ) {
if ( ++i >= len ) throw new Error( "Malformed string, low surrogate expected at position " + i );
c = ( (c ^ 0xd800) << 10 ) | 0x10000 | ( str.charCodeAt(i) ^ 0xdc00 );
}
else if ( !utf8 && c >>> 8 ) {
throw new Error("Wide characters are not allowed.");
}
if ( !utf8 || c <= 0x7f ) {
bytes[j++] = c;
}
else if ( c <= 0x7ff ) {
bytes[j++] = 0xc0 | (c >> 6);
bytes[j++] = 0x80 | (c & 0x3f);
}
else if ( c <= 0xffff ) {
bytes[j++] = 0xe0 | (c >> 12);
bytes[j++] = 0x80 | (c >> 6 & 0x3f);
bytes[j++] = 0x80 | (c & 0x3f);
}
else {
bytes[j++] = 0xf0 | (c >> 18);
bytes[j++] = 0x80 | (c >> 12 & 0x3f);
bytes[j++] = 0x80 | (c >> 6 & 0x3f);
bytes[j++] = 0x80 | (c & 0x3f);
}
}
return bytes.subarray(0, j);
}
function hex_to_bytes ( str ) {
var len = str.length;
if ( len & 1 ) {
str = '0'+str;
len++;
}
var bytes = new Uint8Array(len>>1);
for ( var i = 0; i < len; i += 2 ) {
bytes[i>>1] = parseInt( str.substr( i, 2), 16 );
}
return bytes;
}
function base64_to_bytes ( str ) {
return string_to_bytes( atob( str ) );
}
function bytes_to_string ( bytes, utf8 ) {
utf8 = !!utf8;
var len = bytes.length,
chars = new Array(len);
for ( var i = 0, j = 0; i < len; i++ ) {
var b = bytes[i];
if ( !utf8 || b < 128 ) {
chars[j++] = b;
}
else if ( b >= 192 && b < 224 && i+1 < len ) {
chars[j++] = ( (b & 0x1f) << 6 ) | (bytes[++i] & 0x3f);
}
else if ( b >= 224 && b < 240 && i+2 < len ) {
chars[j++] = ( (b & 0xf) << 12 ) | ( (bytes[++i] & 0x3f) << 6 ) | (bytes[++i] & 0x3f);
}
else if ( b >= 240 && b < 248 && i+3 < len ) {
var c = ( (b & 7) << 18 ) | ( (bytes[++i] & 0x3f) << 12 ) | ( (bytes[++i] & 0x3f) << 6 ) | (bytes[++i] & 0x3f);
if ( c <= 0xffff ) {
chars[j++] = c;
}
else {
c ^= 0x10000;
chars[j++] = 0xd800 | (c >> 10);
chars[j++] = 0xdc00 | (c & 0x3ff);
}
}
else {
throw new Error("Malformed UTF8 character at byte offset " + i);
}
}
var str = '',
bs = 16384;
for ( var i = 0; i < j; i += bs ) {
str += String.fromCharCode.apply( String, chars.slice( i, i+bs <= j ? i+bs : j ) );
}
return str;
}
function bytes_to_hex ( arr ) {
var str = '';
for ( var i = 0; i < arr.length; i++ ) {
var h = ( arr[i] & 0xff ).toString(16);
if ( h.length < 2 ) str += '0';
str += h;
}
return str;
}
function bytes_to_base64 ( arr ) {
return btoa( bytes_to_string(arr) );
}
function pow2_ceil ( a ) {
a -= 1;
a |= a >>> 1;
a |= a >>> 2;
a |= a >>> 4;
a |= a >>> 8;
a |= a >>> 16;
a += 1;
return a;
}
function is_number ( a ) {
return ( typeof a === 'number' );
}
function is_string ( a ) {
return ( typeof a === 'string' );
}
function is_buffer ( a ) {
return ( a instanceof ArrayBuffer );
}
function is_bytes ( a ) {
return ( a instanceof Uint8Array );
}
function is_typed_array ( a ) {
return ( a instanceof Int8Array ) || ( a instanceof Uint8Array )
|| ( a instanceof Int16Array ) || ( a instanceof Uint16Array )
|| ( a instanceof Int32Array ) || ( a instanceof Uint32Array )
|| ( a instanceof Float32Array )
|| ( a instanceof Float64Array );
}
function _heap_init ( constructor, options ) {
var heap = options.heap,
size = heap ? heap.byteLength : options.heapSize || 65536;
if ( size & 0xfff || size <= 0 )
throw new Error("heap size must be a positive integer and a multiple of 4096");
heap = heap || new constructor( new ArrayBuffer(size) );
return heap;
}
function _heap_write ( heap, hpos, data, dpos, dlen ) {
var hlen = heap.length - hpos,
wlen = ( hlen < dlen ) ? hlen : dlen;
heap.set( data.subarray( dpos, dpos+wlen ), hpos );
return wlen;
}
/**
* Util exports
*/
function IllegalStateError () { var err = Error.apply( this, arguments ); this.message = err.message, this.stack = err.stack; }
IllegalStateError.prototype = Object.create( Error.prototype, { name: { value: 'IllegalStateError' } } );
function IllegalArgumentError () { var err = Error.apply( this, arguments ); this.message = err.message, this.stack = err.stack; }
IllegalArgumentError.prototype = Object.create( Error.prototype, { name: { value: 'IllegalArgumentError' } } );
function SecurityError () { var err = Error.apply( this, arguments ); this.message = err.message, this.stack = err.stack; }
SecurityError.prototype = Object.create( Error.prototype, { name: { value: 'SecurityError' } } );
/**
* @file {@link http://asmjs.org Asm.js} implementation of the {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard Advanced Encryption Standard}.
* @author Artem S Vybornov <vybornov@gmail.com>
* @license MIT
*/
var AES_asm = function () {
var ginit_done = false;
/**
* Galois Field exponentiation and logarithm tables for 3 (the generator)
*/
var gexp3, glog3;
/**
* Init Galois Field tables
*/
function ginit () {
gexp3 = [], glog3 = [];
var a = 1, c, d;
for ( c = 0; c < 255; c++ ) {
gexp3[c] = a;
// Multiply by three
d = a & 0x80, a <<= 1, a &= 255;
if ( d === 0x80 ) a ^= 0x1b;
a ^= gexp3[c];
// Set the log table value
glog3[gexp3[c]] = c;
}
gexp3[255] = gexp3[0];
glog3[0] = 0;
ginit_done = true;
}
/**
* Galois Field multiplication
* @param {int} a
* @param {int} b
* @return {int}
*/
function gmul ( a, b ) {
var c = gexp3[ ( glog3[a] + glog3[b] ) % 255 ];
if ( a === 0 || b === 0 ) c = 0;
return c;
}
/**
* Galois Field reciprocal
* @param {int} a
* @return {int}
*/
function ginv ( a ) {
var i = gexp3[ 255 - glog3[a] ];
if ( a === 0 ) i = 0;
return i;
}
/**
* AES stuff init flag
*/
var aes_init_done = false;
/**
* Encryption, Decryption, S-Box and KeyTransform tables
*/
var aes_sbox, aes_sinv, aes_enc, aes_dec;
/**
* Init AES tables
*/
function aes_init () {
if ( !ginit_done ) ginit();
// Calculates AES S-Box value
function _s ( a ) {
var c, s, x;
s = x = ginv(a);
for ( c = 0; c < 4; c++ ) {
s = ( (s << 1) | (s >>> 7) ) & 255;
x ^= s;
}
x ^= 99;
return x;
}
// Tables
aes_sbox = [], aes_sinv = [], aes_enc = [ [], [], [], [] ], aes_dec = [ [], [], [], [] ];
for ( var i = 0; i < 256; i++ ) {
var s = _s(i);
// S-Box and its inverse
aes_sbox[i] = s;
aes_sinv[s] = i;
// Ecryption and Decryption tables
aes_enc[0][i] = ( gmul( 2, s ) << 24 ) | ( s << 16 ) | ( s << 8 ) | gmul( 3, s );
aes_dec[0][s] = ( gmul( 14, i ) << 24 ) | ( gmul( 9, i ) << 16 ) | ( gmul( 13, i ) << 8 ) | gmul( 11, i );
// Rotate tables
for ( var t = 1; t < 4; t++ ) {
aes_enc[t][i] = ( aes_enc[t-1][i] >>> 8 ) | ( aes_enc[t-1][i] << 24 );
aes_dec[t][s] = ( aes_dec[t-1][s] >>> 8 ) | ( aes_dec[t-1][s] << 24 );
}
}
}
/**
* Asm.js module constructor.
*
* <p>
* Heap buffer layout by offset:
* <pre>
* 0x0000 encryption key schedule
* 0x0400 decryption key schedule
* 0x0800 sbox
* 0x0c00 inv sbox
* 0x1000 encryption tables
* 0x2000 decryption tables
* 0x3000 reserved (future GCM multiplication lookup table)
* 0x4000 data
* </pre>
* Don't touch anything before <code>0x400</code>.
* </p>
*
* @alias AES_asm
* @class
* @param {Object} foreign - <i>ignored</i>
* @param {ArrayBuffer} buffer - heap buffer to link with
*/
var wrapper = function ( foreign, buffer ) {
// Init AES stuff for the first time
if ( !aes_init_done ) aes_init();
// Fill up AES tables
var heap = new Uint32Array(buffer);
heap.set( aes_sbox, 0x0800>>2 );
heap.set( aes_sinv, 0x0c00>>2 );
for ( var i = 0; i < 4; i++ ) {
heap.set( aes_enc[i], ( 0x1000 + 0x400 * i )>>2 );
heap.set( aes_dec[i], ( 0x2000 + 0x400 * i )>>2 );
}
/**
* Calculate AES key schedules.
* @instance
* @memberof AES_asm
* @param {int} ks - key size, 4/6/8 (for 128/192/256-bit key correspondingly)
* @param {int} k0..k7 - key vector components
*/
function set_key ( ks, k0, k1, k2, k3, k4, k5, k6, k7 ) {
var ekeys = heap.subarray( 0x000, 60 ),
dkeys = heap.subarray( 0x100, 0x100+60 );
// Encryption key schedule
ekeys.set( [ k0, k1, k2, k3, k4, k5, k6, k7 ] );
for ( var i = ks, rcon = 1; i < 4*ks+28; i++ ) {
var k = ekeys[i-1];
if ( ( i % ks === 0 ) || ( ks === 8 && i % ks === 4 ) ) {
k = aes_sbox[k>>>24]<<24 ^ aes_sbox[k>>>16&255]<<16 ^ aes_sbox[k>>>8&255]<<8 ^ aes_sbox[k&255];
}
if ( i % ks === 0 ) {
k = (k << 8) ^ (k >>> 24) ^ (rcon << 24);
rcon = (rcon << 1) ^ ( (rcon & 0x80) ? 0x1b : 0 );
}
ekeys[i] = ekeys[i-ks] ^ k;
}
// Decryption key schedule
for ( var j = 0; j < i; j += 4 ) {
for ( var jj = 0; jj < 4; jj++ ) {
var k = ekeys[i-(4+j)+(4-jj)%4];
if ( j < 4 || j >= i-4 ) {
dkeys[j+jj] = k;
} else {
dkeys[j+jj] = aes_dec[0][aes_sbox[k>>>24]]
^ aes_dec[1][aes_sbox[k>>>16&255]]
^ aes_dec[2][aes_sbox[k>>>8&255]]
^ aes_dec[3][aes_sbox[k&255]];
}
}
}
// Set rounds number
asm.set_rounds( ks + 5 );
}
// create library object with necessary properties
var stdlib = { Uint8Array: Uint8Array, Uint32Array: Uint32Array };
var asm = function ( stdlib, foreign, buffer ) {
var S0 = 0, S1 = 0, S2 = 0, S3 = 0,
I0 = 0, I1 = 0, I2 = 0, I3 = 0,
N0 = 0, N1 = 0, N2 = 0, N3 = 0,
M0 = 0, M1 = 0, M2 = 0, M3 = 0,
H0 = 0, H1 = 0, H2 = 0, H3 = 0,
R = 0;
var HEAP = new stdlib.Uint32Array(buffer),
DATA = new stdlib.Uint8Array(buffer);
/**
* AES core
* @param {int} k - precomputed key schedule offset
* @param {int} s - precomputed sbox table offset
* @param {int} t - precomputed round table offset
* @param {int} r - number of inner rounds to perform
* @param {int} x0..x3 - 128-bit input block vector
*/
function _core ( k, s, t, r, x0, x1, x2, x3 ) {
k = k|0;
s = s|0;
t = t|0;
r = r|0;
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
var t1 = 0, t2 = 0, t3 = 0,
y0 = 0, y1 = 0, y2 = 0, y3 = 0,
i = 0;
t1 = t|0x400, t2 = t|0x800, t3 = t|0xc00;
// round 0
x0 = x0 ^ HEAP[(k|0)>>2], x1 = x1 ^ HEAP[(k|4)>>2], x2 = x2 ^ HEAP[(k|8)>>2], x3 = x3 ^ HEAP[(k|12)>>2];
// round 1..r
for ( i = 16; (i|0) <= (r<<4); i = (i+16)|0 ) {
y0 = HEAP[(t|x0>>22&1020)>>2] ^ HEAP[(t1|x1>>14&1020)>>2] ^ HEAP[(t2|x2>>6&1020)>>2] ^ HEAP[(t3|x3<<2&1020)>>2] ^ HEAP[(k|i|0)>>2], y1 = HEAP[(t|x1>>22&1020)>>2] ^ HEAP[(t1|x2>>14&1020)>>2] ^ HEAP[(t2|x3>>6&1020)>>2] ^ HEAP[(t3|x0<<2&1020)>>2] ^ HEAP[(k|i|4)>>2], y2 = HEAP[(t|x2>>22&1020)>>2] ^ HEAP[(t1|x3>>14&1020)>>2] ^ HEAP[(t2|x0>>6&1020)>>2] ^ HEAP[(t3|x1<<2&1020)>>2] ^ HEAP[(k|i|8)>>2], y3 = HEAP[(t|x3>>22&1020)>>2] ^ HEAP[(t1|x0>>14&1020)>>2] ^ HEAP[(t2|x1>>6&1020)>>2] ^ HEAP[(t3|x2<<2&1020)>>2] ^ HEAP[(k|i|12)>>2];
x0 = y0, x1 = y1, x2 = y2, x3 = y3;
}
// final round
S0 = HEAP[(s|x0>>22&1020)>>2]<<24 ^ HEAP[(s|x1>>14&1020)>>2]<<16 ^ HEAP[(s|x2>>6&1020)>>2]<<8 ^ HEAP[(s|x3<<2&1020)>>2] ^ HEAP[(k|i|0)>>2], S1 = HEAP[(s|x1>>22&1020)>>2]<<24 ^ HEAP[(s|x2>>14&1020)>>2]<<16 ^ HEAP[(s|x3>>6&1020)>>2]<<8 ^ HEAP[(s|x0<<2&1020)>>2] ^ HEAP[(k|i|4)>>2], S2 = HEAP[(s|x2>>22&1020)>>2]<<24 ^ HEAP[(s|x3>>14&1020)>>2]<<16 ^ HEAP[(s|x0>>6&1020)>>2]<<8 ^ HEAP[(s|x1<<2&1020)>>2] ^ HEAP[(k|i|8)>>2], S3 = HEAP[(s|x3>>22&1020)>>2]<<24 ^ HEAP[(s|x0>>14&1020)>>2]<<16 ^ HEAP[(s|x1>>6&1020)>>2]<<8 ^ HEAP[(s|x2<<2&1020)>>2] ^ HEAP[(k|i|12)>>2];
}
/**
* ECB mode encryption
* @param {int} x0..x3 - 128-bit input block vector
*/
function _ecb_enc ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
_core(
0x0000, 0x0800, 0x1000,
R,
x0,
x1,
x2,
x3
);
}
/**
* ECB mode decryption
* @param {int} x0..x3 - 128-bit input block vector
*/
function _ecb_dec ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
var t = 0;
_core(
0x0400, 0x0c00, 0x2000,
R,
x0,
x3,
x2,
x1
);
t = S1, S1 = S3, S3 = t;
}
/**
* CBC mode encryption
* @param {int} x0..x3 - 128-bit input block vector
*/
function _cbc_enc ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
_core(
0x0000, 0x0800, 0x1000,
R,
I0 ^ x0,
I1 ^ x1,
I2 ^ x2,
I3 ^ x3
);
I0 = S0, I1 = S1, I2 = S2, I3 = S3;
}
/**
* CBC mode decryption
* @param {int} x0..x3 - 128-bit input block vector
*/
function _cbc_dec ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
var t = 0;
_core(
0x0400, 0x0c00, 0x2000,
R,
x0,
x3,
x2,
x1
);
t = S1, S1 = S3, S3 = t;
S0 = S0 ^ I0, S1 = S1 ^ I1, S2 = S2 ^ I2, S3 = S3 ^ I3;
I0 = x0, I1 = x1, I2 = x2, I3 = x3;
}
/**
* CFB mode encryption
* @param {int} x0..x3 - 128-bit input block vector
*/
function _cfb_enc ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
_core(
0x0000, 0x0800, 0x1000,
R,
I0,
I1,
I2,
I3
);
I0 = S0 = S0 ^ x0, I1 = S1 = S1 ^ x1, I2 = S2 = S2 ^ x2, I3 = S3 = S3 ^ x3;
}
/**
* CFB mode decryption
* @param {int} x0..x3 - 128-bit input block vector
*/
function _cfb_dec ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
_core(
0x0000, 0x0800, 0x1000,
R,
I0,
I1,
I2,
I3
);
S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3;
I0 = x0, I1 = x1, I2 = x2, I3 = x3;
}
/**
* OFB mode encryption / decryption
* @param {int} x0..x3 - 128-bit input block vector
*/
function _ofb ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
_core(
0x0000, 0x0800, 0x1000,
R,
I0,
I1,
I2,
I3
);
I0 = S0, I1 = S1, I2 = S2, I3 = S3;
S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3;
}
/**
* CTR mode encryption / decryption
* @param {int} x0..x3 - 128-bit input block vector
*/
function _ctr ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
_core(
0x0000, 0x0800, 0x1000,
R,
N0,
N1,
N2,
N3
);
N3 = ( ~M3 & N3 ) | M3 & ( N3 + 1 ), N2 = ( ~M2 & N2 ) | M2 & ( N2 + ( (N3|0) == 0 ) ), N1 = ( ~M1 & N1 ) | M1 & ( N1 + ( (N2|0) == 0 ) ), N0 = ( ~M0 & N0 ) | M0 & ( N0 + ( (N1|0) == 0 ) );
S0 = S0 ^ x0, S1 = S1 ^ x1, S2 = S2 ^ x2, S3 = S3 ^ x3;
}
/**
* GCM mode MAC calculation
* @param {int} x0..x3 - 128-bit input block vector
*/
function _gcm_mac ( x0, x1, x2, x3 ) {
x0 = x0|0;
x1 = x1|0;
x2 = x2|0;
x3 = x3|0;
var y0 = 0, y1 = 0, y2 = 0, y3 = 0,
z0 = 0, z1 = 0, z2 = 0, z3 = 0,
i = 0, c = 0;
x0 = x0 ^ I0, x1 = x1 ^ I1, x2 = x2 ^ I2, x3 = x3 ^ I3;
y0 = H0|0, y1 = H1|0, y2 = H2|0, y3 = H3|0;
for ( ; (i|0) < 128; i = (i + 1)|0 ) {
if ( y0 >>> 31 ) {
z0 = z0 ^ x0, z1 = z1 ^ x1, z2 = z2 ^ x2, z3 = z3 ^ x3;
}
y0 = (y0 << 1) | (y1 >>> 31), y1 = (y1 << 1) | (y2 >>> 31), y2 = (y2 << 1) | (y3 >>> 31), y3 = (y3 << 1);
c = x3 & 1;
x3 = (x3 >>> 1) | (x2 << 31), x2 = (x2 >>> 1) | (x1 << 31), x1 = (x1 >>> 1) | (x0 << 31), x0 = (x0 >>> 1);
if ( c ) x0 = x0 ^ 0xe1000000;
}
I0 = z0, I1 = z1, I2 = z2, I3 = z3;
}
/**
* Set the internal rounds number.
* @instance
* @memberof AES_asm
* @param {int} r - number if inner AES rounds
*/
function set_rounds ( r ) {
r = r|0;
R = r;
}
/**
* Populate the internal state of the module.
* @instance
* @memberof AES_asm
* @param {int} s0...s3 - state vector
*/
function set_state ( s0, s1, s2, s3 ) {
s0 = s0|0;
s1 = s1|0;
s2 = s2|0;
s3 = s3|0;
S0 = s0, S1 = s1, S2 = s2, S3 = s3;
}
/**
* Populate the internal iv of the module.
* @instance
* @memberof AES_asm
* @param {int} i0...i3 - iv vector
*/
function set_iv ( i0, i1, i2, i3 ) {
i0 = i0|0;
i1 = i1|0;
i2 = i2|0;
i3 = i3|0;
I0 = i0, I1 = i1, I2 = i2, I3 = i3;
}
/**
* Set nonce for CTR-family modes.
* @instance
* @memberof AES_asm
* @param {int} n0..n3 - nonce vector
*/
function set_nonce ( n0, n1, n2, n3 ) {
n0 = n0|0;
n1 = n1|0;
n2 = n2|0;
n3 = n3|0;
N0 = n0, N1 = n1, N2 = n2, N3 = n3;
}
/**
* Set counter mask for CTR-family modes.
* @instance
* @memberof AES_asm
* @param {int} m0...m3 - counter mask vector
*/
function set_mask ( m0, m1, m2, m3 ) {
m0 = m0|0;
m1 = m1|0;
m2 = m2|0;
m3 = m3|0;
M0 = m0, M1 = m1, M2 = m2, M3 = m3;
}
/**
* Set counter for CTR-family modes.
* @instance
* @memberof AES_asm
* @param {int} c0...c3 - counter vector
*/
function set_counter ( c0, c1, c2, c3 ) {
c0 = c0|0;
c1 = c1|0;
c2 = c2|0;
c3 = c3|0;
N3 = ( ~M3 & N3 ) | M3 & c3, N2 = ( ~M2 & N2 ) | M2 & c2, N1 = ( ~M1 & N1 ) | M1 & c1, N0 = ( ~M0 & N0 ) | M0 & c0;
}
/**
* Store the internal state vector into the heap.
* @instance
* @memberof AES_asm
* @param {int} pos - offset where to put the data
* @return {int} The number of bytes have been written into the heap, always 16.
*/
function get_state ( pos ) {
pos = pos|0;
if ( pos & 15 ) return -1;
DATA[pos|0] = S0>>>24, DATA[pos|1] = S0>>>16&255, DATA[pos|2] = S0>>>8&255, DATA[pos|3] = S0&255, DATA[pos|4] = S1>>>24, DATA[pos|5] = S1>>>16&255, DATA[pos|6] = S1>>>8&255, DATA[pos|7] = S1&255, DATA[pos|8] = S2>>>24, DATA[pos|9] = S2>>>16&255, DATA[pos|10] = S2>>>8&255, DATA[pos|11] = S2&255, DATA[pos|12] = S3>>>24, DATA[pos|13] = S3>>>16&255, DATA[pos|14] = S3>>>8&255, DATA[pos|15] = S3&255;
return 16;
}
/**
* Store the internal iv vector into the heap.
* @instance
* @memberof AES_asm
* @param {int} pos - offset where to put the data
* @return {int} The number of bytes have been written into the heap, always 16.
*/
function get_iv ( pos ) {
pos = pos|0;
if ( pos & 15 ) return -1;
DATA[pos|0] = I0>>>24, DATA[pos|1] = I0>>>16&255, DATA[pos|2] = I0>>>8&255, DATA[pos|3] = I0&255, DATA[pos|4] = I1>>>24, DATA[pos|5] = I1>>>16&255, DATA[pos|6] = I1>>>8&255, DATA[pos|7] = I1&255, DATA[pos|8] = I2>>>24, DATA[pos|9] = I2>>>16&255, DATA[pos|10] = I2>>>8&255, DATA[pos|11] = I2&255, DATA[pos|12] = I3>>>24, DATA[pos|13] = I3>>>16&255, DATA[pos|14] = I3>>>8&255, DATA[pos|15] = I3&255;
return 16;
}
/**
* GCM initialization.
* @instance
* @memberof AES_asm
*/
function gcm_init ( ) {
_ecb_enc( 0, 0, 0, 0 );
H0 = S0, H1 = S1, H2 = S2, H3 = S3;
}
/**
* Perform ciphering operation on the supplied data.
* @instance
* @memberof AES_asm
* @param {int} mode - block cipher mode (see {@link AES_asm} mode constants)
* @param {int} pos - offset of the data being processed
* @param {int} len - length of the data being processed
* @return {int} Actual amount of data have been processed.
*/
function cipher ( mode, pos, len ) {
mode = mode|0;
pos = pos|0;
len = len|0;
var ret = 0;
if ( pos & 15 ) return -1;
while ( (len|0) >= 16 ) {
_cipher_modes[mode&7](
DATA[pos|0]<<24 | DATA[pos|1]<<16 | DATA[pos|2]<<8 | DATA[pos|3],
DATA[pos|4]<<24 | DATA[pos|5]<<16 | DATA[pos|6]<<8 | DATA[pos|7],
DATA[pos|8]<<24 | DATA[pos|9]<<16 | DATA[pos|10]<<8 | DATA[pos|11],
DATA[pos|12]<<24 | DATA[pos|13]<<16 | DATA[pos|14]<<8 | DATA[pos|15]
);
DATA[pos|0] = S0>>>24, DATA[pos|1] = S0>>>16&255, DATA[pos|2] = S0>>>8&255, DATA[pos|3] = S0&255, DATA[pos|4] = S1>>>24, DATA[pos|5] = S1>>>16&255, DATA[pos|6] = S1>>>8&255, DATA[pos|7] = S1&255, DATA[pos|8] = S2>>>24, DATA[pos|9] = S2>>>16&255, DATA[pos|10] = S2>>>8&255, DATA[pos|11] = S2&255, DATA[pos|12] = S3>>>24, DATA[pos|13] = S3>>>16&255, DATA[pos|14] = S3>>>8&255, DATA[pos|15] = S3&255;
ret = (ret + 16)|0, pos = (pos + 16)|0, len = (len - 16)|0;
}
return ret|0;
}
/**
* Calculates MAC of the supplied data.
* @instance
* @memberof AES_asm
* @param {int} mode - block cipher mode (see {@link AES_asm} mode constants)
* @param {int} pos - offset of the data being processed
* @param {int} len - length of the data being processed
* @return {int} Actual amount of data have been processed.
*/
function mac ( mode, pos, len ) {
mode = mode|0;
pos = pos|0;
len = len|0;
var ret = 0;
if ( pos & 15 ) return -1;
while ( (len|0) >= 16 ) {
_mac_modes[mode&1](
DATA[pos|0]<<24 | DATA[pos|1]<<16 | DATA[pos|2]<<8 | DATA[pos|3],
DATA[pos|4]<<24 | DATA[pos|5]<<16 | DATA[pos|6]<<8 | DATA[pos|7],
DATA[pos|8]<<24 | DATA[pos|9]<<16 | DATA[pos|10]<<8 | DATA[pos|11],
DATA[pos|12]<<24 | DATA[pos|13]<<16 | DATA[pos|14]<<8 | DATA[pos|15]
);
ret = (ret + 16)|0, pos = (pos + 16)|0, len = (len - 16)|0;
}
return ret|0;
}
/**
* AES cipher modes table (virual methods)
*/
var _cipher_modes = [ _ecb_enc, _ecb_dec, _cbc_enc, _cbc_dec, _cfb_enc, _cfb_dec, _ofb, _ctr ];
/**
* AES MAC modes table (virual methods)
*/
var _mac_modes = [ _cbc_enc, _gcm_mac ];
/**
* Asm.js module exports
*/
return {
set_rounds: set_rounds,
set_state: set_state,
set_iv: set_iv,
set_nonce: set_nonce,
set_mask: set_mask,
set_counter:set_counter,
get_state: get_state,
get_iv: get_iv,
gcm_init: gcm_init,
cipher: cipher,
mac: mac
};
}( stdlib, foreign, buffer );
asm.set_key = set_key;
return asm;
};
/**
* AES enciphering mode constants
* @enum {int}
* @const
*/
wrapper.ENC = {
ECB: 0,
CBC: 2,
CFB: 4,
OFB: 6,
CTR: 7
}, wrapper.DEC = {
ECB: 1,
CBC: 3,
CFB: 5,
OFB: 6,
CTR: 7
}, wrapper.MAC = {
CBC: 0,
GCM: 1
};
/**
* Heap data offset
* @type {int}
* @const
*/
wrapper.HEAP_DATA = 0x4000;
return wrapper;
}();
function AES ( options ) {
options = options || {};
this.heap = _heap_init( Uint8Array, options ).subarray( AES_asm.HEAP_DATA );
this.asm = options.asm || AES_asm( null, this.heap.buffer );
this.mode = null;
this.key = null;
this.reset( options );
}
function AES_set_key ( key ) {
if ( key !== undefined ) {
if ( is_buffer(key) || is_bytes(key) ) {
key = new Uint8Array(key);
}
else if ( is_string(key) ) {
key = string_to_bytes(key);
}
else {
throw new TypeError("unexpected key type");
}
var keylen = key.length;
if ( keylen !== 16 && keylen !== 24 && keylen !== 32 )
throw new IllegalArgumentError("illegal key size");
var keyview = new DataView( key.buffer, key.byteOffset, key.byteLength );
this.asm.set_key(
keylen >> 2,
keyview.getUint32(0),
keyview.getUint32(4),
keyview.getUint32(8),
keyview.getUint32(12),
keylen > 16 ? keyview.getUint32(16) : 0,
keylen > 16 ? keyview.getUint32(20) : 0,
keylen > 24 ? keyview.getUint32(24) : 0,
keylen > 24 ? keyview.getUint32(28) : 0
);
this.key = key;
}
else if ( !this.key ) {
throw new Error("key is required");
}
}
function AES_set_iv ( iv ) {
if ( iv !== undefined ) {
if ( is_buffer(iv) || is_bytes(iv) ) {
iv = new Uint8Array(iv);
}
else if ( is_string(iv) ) {
iv = string_to_bytes(iv);
}
else {
throw new TypeError("unexpected iv type");
}
if ( iv.length !== 16 )
throw new IllegalArgumentError("illegal iv size");
var ivview = new DataView( iv.buffer, iv.byteOffset, iv.byteLength );
this.iv = iv;
this.asm.set_iv( ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12) );
}
else {
this.iv = null;
this.asm.set_iv( 0, 0, 0, 0 );
}
}
function AES_set_padding ( padding ) {
if ( padding !== undefined ) {
this.padding = !!padding;
}
else {
this.padding = true;
}
}
function AES_reset ( options ) {
options = options || {};
this.result = null;
this.pos = 0;
this.len = 0;
AES_set_key.call( this, options.key );
if ( this.hasOwnProperty('iv') ) AES_set_iv.call( this, options.iv );
if ( this.hasOwnProperty('padding') ) AES_set_padding.call( this, options.padding );
return this;
}
function AES_Encrypt_process ( data ) {
if ( is_string(data) )
data = string_to_bytes(data);
if ( is_buffer(data) )
data = new Uint8Array(data);
if ( !is_bytes(data) )
throw new TypeError("data isn't of expected type");
var asm = this.asm,
heap = this.heap,
amode = AES_asm.ENC[this.mode],
hpos = AES_asm.HEAP_DATA,
pos = this.pos,
len = this.len,
dpos = 0,
dlen = data.length || 0,
rpos = 0,
rlen = (len + dlen) & -16,
wlen = 0;
var result = new Uint8Array(rlen);
while ( dlen > 0 ) {
wlen = _heap_write( heap, pos+len, data, dpos, dlen );
len += wlen;
dpos += wlen;
dlen -= wlen;
wlen = asm.cipher( amode, hpos + pos, len );
if ( wlen ) result.set( heap.subarray( pos, pos + wlen ), rpos );
rpos += wlen;
if ( wlen < len ) {
pos += wlen;
len -= wlen;
} else {
pos = 0;
len = 0;
}
}
this.result = result;
this.pos = pos;
this.len = len;
return this;
}
function AES_Encrypt_finish ( data ) {
var presult = null,
prlen = 0;
if ( data !== undefined ) {
presult = AES_Encrypt_process.call( this, data ).result;
prlen = presult.length;
}
var asm = this.asm,
heap = this.heap,
amode = AES_asm.ENC[this.mode],
hpos = AES_asm.HEAP_DATA,
pos = this.pos,
len = this.len,
plen = 16 - len % 16,
rlen = len;
if ( this.hasOwnProperty('padding') ) {
if ( this.padding ) {
for ( var p = 0; p < plen; ++p ) heap[ pos + len + p ] = plen;
len += plen;
rlen = len;
}
else if ( len % 16 ) {
throw new IllegalArgumentError("data length must be a multiple of the block size");
}
}
else {
len += plen;
}
var result = new Uint8Array( prlen + rlen );
if ( prlen ) result.set( presult );
if ( len ) asm.cipher( amode, hpos + pos, len );
if ( rlen ) result.set( heap.subarray( pos, pos + rlen ), prlen );
this.result = result;
this.pos = 0;
this.len = 0;
return this;
}
function AES_Decrypt_process ( data ) {
if ( is_string(data) )
data = string_to_bytes(data);
if ( is_buffer(data) )
data = new Uint8Array(data);
if ( !is_bytes(data) )
throw new TypeError("data isn't of expected type");
var asm = this.asm,
heap = this.heap,
amode = AES_asm.DEC[this.mode],
hpos = AES_asm.HEAP_DATA,
pos = this.pos,
len = this.len,
dpos = 0,
dlen = data.length || 0,
rpos = 0,
rlen = (len + dlen) & -16,
plen = 0,
wlen = 0;
if ( this.hasOwnProperty('padding') && this.padding ) {
plen = len + dlen - rlen || 16;
rlen -= plen;
}
var result = new Uint8Array(rlen);
while ( dlen > 0 ) {
wlen = _heap_write( heap, pos+len, data, dpos, dlen );
len += wlen;
dpos += wlen;
dlen -= wlen;
wlen = asm.cipher( amode, hpos + pos, len - ( !dlen ? plen : 0 ) );
if ( wlen ) result.set( heap.subarray( pos, pos + wlen ), rpos );
rpos += wlen;
if ( wlen < len ) {
pos += wlen;
len -= wlen;
} else {
pos = 0;
len = 0;
}
}
this.result = result;
this.pos = pos;
this.len = len;
return this;
}
function AES_Decrypt_finish ( data ) {
var presult = null,
prlen = 0;
if ( data !== undefined ) {
presult = AES_Decrypt_process.call( this, data ).result;
prlen = presult.length;
}
var asm = this.asm,
heap = this.heap,
amode = AES_asm.DEC[this.mode],
hpos = AES_asm.HEAP_DATA,
pos = this.pos,
len = this.len,
rlen = len;
if ( len > 0 ) {
if ( len % 16 ) {
if ( this.hasOwnProperty('padding') ) {
throw new IllegalArgumentError("data length must be a multiple of the block size");
} else {
len += 16 - len % 16;
}
}
asm.cipher( amode, hpos + pos, len );
if ( this.hasOwnProperty('padding') && this.padding ) {
var pad = heap[ pos + rlen - 1 ];
if ( pad < 1 || pad > 16 || pad > rlen )
throw new SecurityError("bad padding");
var pcheck = 0;
for ( var i = pad; i > 1; i-- ) pcheck |= pad ^ heap[ pos + rlen - i ];
if ( pcheck )
throw new SecurityError("bad padding");
rlen -= pad;
}
}
var result = new Uint8Array( prlen + rlen );
if ( prlen > 0 ) {
result.set( presult );
}
if ( rlen > 0 ) {
result.set( heap.subarray( pos, pos + rlen ), prlen );
}
this.result = result;
this.pos = 0;
this.len = 0;
return this;
}
/**
* Cipher Block Chaining Mode (CBC)
*/
function AES_CBC_constructor (options ) {
this.padding = true;
this.iv = null;
AES.call( this, options );
this.mode = 'CBC';
}
var AES_CBC_prototype = AES_CBC_constructor.prototype;
AES_CBC_prototype.BLOCK_SIZE = 16;
AES_CBC_prototype.reset = AES_reset;
AES_CBC_prototype.encrypt = AES_Encrypt_finish;
AES_CBC_prototype.decrypt = AES_Decrypt_finish;
function AES_CBC_Encrypt ( options ) {
AES_CBC_constructor.call( this, options );
}
var AES_CBC_Encrypt_prototype = AES_CBC_Encrypt.prototype;
AES_CBC_Encrypt_prototype.BLOCK_SIZE = 16;
AES_CBC_Encrypt_prototype.reset = AES_reset;
AES_CBC_Encrypt_prototype.process = AES_Encrypt_process;
AES_CBC_Encrypt_prototype.finish = AES_Encrypt_finish;
function AES_CBC_Decrypt ( options ) {
AES_CBC_constructor.call( this, options );
}
var AES_CBC_Decrypt_prototype = AES_CBC_Decrypt.prototype;
AES_CBC_Decrypt_prototype.BLOCK_SIZE = 16;
AES_CBC_Decrypt_prototype.reset = AES_reset;
AES_CBC_Decrypt_prototype.process = AES_Decrypt_process;
AES_CBC_Decrypt_prototype.finish = AES_Decrypt_finish;
// shared asm.js module and heap
var _AES_heap_instance = new Uint8Array(0x100000);
var _AES_asm_instance = AES_asm( null, _AES_heap_instance.buffer );
/**
* AES-CBC exports
*/
function AES_CBC_encrypt_bytes (data, key, padding, iv ) {
if ( data === undefined ) throw new SyntaxError("data required");
if ( key === undefined ) throw new SyntaxError("key required");
return new AES_CBC_constructor( { heap: _AES_heap_instance, asm: _AES_asm_instance, key: key, padding: padding, iv: iv } ).encrypt(data).result;
}
function AES_CBC_decrypt_bytes ( data, key, padding, iv ) {
if ( data === undefined ) throw new SyntaxError("data required");
if ( key === undefined ) throw new SyntaxError("key required");
return new AES_CBC_constructor( { heap: _AES_heap_instance, asm: _AES_asm_instance, key: key, padding: padding, iv: iv } ).decrypt(data).result;
}
var AES_CBC = AES_CBC_constructor;
AES_CBC.encrypt = AES_CBC_encrypt_bytes;
AES_CBC.decrypt = AES_CBC_decrypt_bytes;
AES_CBC.Encrypt = AES_CBC_Encrypt;
AES_CBC.Decrypt = AES_CBC_Decrypt;
/**
* Galois/Counter mode
*/
var _AES_GCM_data_maxLength = 68719476704; // 2^36 - 2^5
function _gcm_mac_process ( data ) {
var heap = this.heap,
asm = this.asm,
dpos = 0,
dlen = data.length || 0,
wlen = 0;
while ( dlen > 0 ) {
wlen = _heap_write( heap, 0, data, dpos, dlen );
dpos += wlen;
dlen -= wlen;
while ( wlen & 15 ) heap[ wlen++ ] = 0;
asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA, wlen );
}
}
function AES_GCM_constructor (options ) {
this.nonce = null;
this.adata = null;
this.iv = null;
this.counter = 1;
this.tagSize = 16;
AES.call( this, options );
this.mode = 'GCM';
}
function AES_GCM_Encrypt ( options ) {
AES_GCM_constructor.call( this, options );
}
function AES_GCM_Decrypt ( options ) {
AES_GCM_constructor.call( this, options );
}
function AES_GCM_reset ( options ) {
options = options || {};
AES_reset.call( this, options );
var asm = this.asm,
heap = this.heap;
asm.gcm_init();
var tagSize = options.tagSize;
if ( tagSize !== undefined ) {
if ( !is_number(tagSize) )
throw new TypeError("tagSize must be a number");
if ( tagSize < 4 || tagSize > 16 )
throw new IllegalArgumentError("illegal tagSize value");
this.tagSize = tagSize;
}
else {
this.tagSize = 16;
}
var nonce = options.nonce;
if ( nonce !== undefined ) {
if ( is_bytes(nonce) || is_buffer(nonce) ) {
nonce = new Uint8Array(nonce);
}
else if ( is_string(nonce) ) {
nonce = string_to_bytes(nonce);
}
else {
throw new TypeError("unexpected nonce type");
}
this.nonce = nonce;
var noncelen = nonce.length || 0,
noncebuf = new Uint8Array(16);
if ( noncelen !== 12 ) {
_gcm_mac_process.call( this, nonce );
heap[0] = heap[1] = heap[2] = heap[3] = heap[4] = heap[5] = heap[6] = heap[7] = heap[8] = heap[9] = heap[10] = 0, heap[11] = noncelen>>>29, heap[12] = noncelen>>>21&255, heap[13] = noncelen>>>13&255, heap[14] = noncelen>>>5&255, heap[15] = noncelen<<3&255;
asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16 );
asm.get_iv( AES_asm.HEAP_DATA );
asm.set_iv();
noncebuf.set( heap.subarray( 0, 16 ) );
}
else {
noncebuf.set(nonce);
noncebuf[15] = 1;
}
var nonceview = new DataView( noncebuf.buffer );
this.gamma0 = nonceview.getUint32(12);
asm.set_nonce( nonceview.getUint32(0), nonceview.getUint32(4), nonceview.getUint32(8), 0 );
asm.set_mask( 0, 0, 0, 0xffffffff );
}
else {
throw new Error("nonce is required");
}
var adata = options.adata;
if ( adata !== undefined && adata !== null ) {
if ( is_bytes(adata) || is_buffer(adata) ) {
adata = new Uint8Array(adata);
}
else if ( is_string(adata) ) {
adata = string_to_bytes(adata);
}
else {
throw new TypeError("unexpected adata type");
}
if ( adata.length > _AES_GCM_data_maxLength )
throw new IllegalArgumentError("illegal adata length");
if ( adata.length ) {
this.adata = adata;
_gcm_mac_process.call( this, adata );
}
else {
this.adata = null;
}
}
else {
this.adata = null;
}
var counter = options.counter;
if ( counter !== undefined ) {
if ( !is_number(counter) )
throw new TypeError("counter must be a number");
if ( counter < 1 || counter > 0xffffffff )
throw new RangeError("counter must be a positive 32-bit integer");
this.counter = counter;
asm.set_counter( 0, 0, 0, this.gamma0+counter|0 );
}
else {
this.counter = 1;
asm.set_counter( 0, 0, 0, this.gamma0+1|0 );
}
var iv = options.iv;
if ( iv !== undefined ) {
if ( !is_number(counter) )
throw new TypeError("counter must be a number");
this.iv = iv;
AES_set_iv.call( this, iv );
}
return this;
}
function AES_GCM_Encrypt_process ( data ) {
if ( is_string(data) )
data = string_to_bytes(data);
if ( is_buffer(data) )
data = new Uint8Array(data);
if ( !is_bytes(data) )
throw new TypeError("data isn't of expected type");
var dpos = 0,
dlen = data.length || 0,
asm = this.asm,
heap = this.heap,
counter = this.counter,
pos = this.pos,
len = this.len,
rpos = 0,
rlen = ( len + dlen ) & -16,
wlen = 0;
if ( ((counter-1)<<4) + len + dlen > _AES_GCM_data_maxLength )
throw new RangeError("counter overflow");
var result = new Uint8Array(rlen);
while ( dlen > 0 ) {
wlen = _heap_write( heap, pos+len, data, dpos, dlen );
len += wlen;
dpos += wlen;
dlen -= wlen;
wlen = asm.cipher( AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, len );
wlen = asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen );
if ( wlen ) result.set( heap.subarray( pos, pos + wlen ), rpos );
counter += (wlen>>>4);
rpos += wlen;
if ( wlen < len ) {
pos += wlen;
len -= wlen;
} else {
pos = 0;
len = 0;
}
}
this.result = result;
this.counter = counter;
this.pos = pos;
this.len = len;
return this;
}
function AES_GCM_Encrypt_finish () {
var asm = this.asm,
heap = this.heap,
counter = this.counter,
tagSize = this.tagSize,
adata = this.adata,
pos = this.pos,
len = this.len;
var result = new Uint8Array( len + tagSize );
asm.cipher( AES_asm.ENC.CTR, AES_asm.HEAP_DATA + pos, (len + 15) & -16 );
if ( len ) result.set( heap.subarray( pos, pos + len ) );
for ( var i = len; i & 15; i++ ) heap[ pos + i ] = 0;
asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i );
var alen = ( adata !== null ) ? adata.length : 0,
clen = ( (counter-1) << 4) + len;
heap[0] = heap[1] = heap[2] = 0, heap[3] = alen>>>29, heap[4] = alen>>>21, heap[5] = alen>>>13&255, heap[6] = alen>>>5&255, heap[7] = alen<<3&255, heap[8] = heap[9] = heap[10] = 0, heap[11] = clen>>>29, heap[12] = clen>>>21&255, heap[13] = clen>>>13&255, heap[14] = clen>>>5&255, heap[15] = clen<<3&255;
asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16 );
asm.get_iv( AES_asm.HEAP_DATA );
asm.set_counter( 0, 0, 0, this.gamma0 );
asm.cipher( AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16 );
result.set( heap.subarray( 0, tagSize ), len );
this.result = result;
this.counter = 1;
this.pos = 0;
this.len = 0;
return this;
}
function AES_GCM_encrypt ( data ) {
var result1 = AES_GCM_Encrypt_process.call( this, data ).result,
result2 = AES_GCM_Encrypt_finish.call(this).result;
var result = new Uint8Array( result1.length + result2.length );
if ( result1.length ) result.set( result1 );
if ( result2.length ) result.set( result2, result1.length );
this.result = result;
return this;
}
function AES_GCM_Decrypt_process ( data ) {
if ( is_string(data) )
data = string_to_bytes(data);
if ( is_buffer(data) )
data = new Uint8Array(data);
if ( !is_bytes(data) )
throw new TypeError("data isn't of expected type");
var dpos = 0,
dlen = data.length || 0,
asm = this.asm,
heap = this.heap,
counter = this.counter,
tagSize = this.tagSize,
pos = this.pos,
len = this.len,
rpos = 0,
rlen = len + dlen > tagSize ? ( len + dlen - tagSize ) & -16 : 0,
tlen = len + dlen - rlen,
wlen = 0;
if ( ((counter-1)<<4) + len + dlen > _AES_GCM_data_maxLength )
throw new RangeError("counter overflow");
var result = new Uint8Array(rlen);
while ( dlen > tlen ) {
wlen = _heap_write( heap, pos+len, data, dpos, dlen-tlen );
len += wlen;
dpos += wlen;
dlen -= wlen;
wlen = asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, wlen );
wlen = asm.cipher( AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, wlen );
if ( wlen ) result.set( heap.subarray( pos, pos+wlen ), rpos );
counter += (wlen>>>4);
rpos += wlen;
pos = 0;
len = 0;
}
if ( dlen > 0 ) {
len += _heap_write( heap, 0, data, dpos, dlen );
}
this.result = result;
this.counter = counter;
this.pos = pos;
this.len = len;
return this;
}
function AES_GCM_Decrypt_finish () {
var asm = this.asm,
heap = this.heap,
tagSize = this.tagSize,
adata = this.adata,
counter = this.counter,
pos = this.pos,
len = this.len,
rlen = len - tagSize,
wlen = 0;
if ( len < tagSize )
throw new IllegalStateError("authentication tag not found");
var result = new Uint8Array(rlen),
atag = new Uint8Array( heap.subarray( pos+rlen, pos+len ) );
for ( var i = rlen; i & 15; i++ ) heap[ pos + i ] = 0;
wlen = asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA + pos, i );
wlen = asm.cipher( AES_asm.DEC.CTR, AES_asm.HEAP_DATA + pos, i );
if ( rlen ) result.set( heap.subarray( pos, pos+rlen ) );
var alen = ( adata !== null ) ? adata.length : 0,
clen = ( (counter-1) << 4) + len - tagSize;
heap[0] = heap[1] = heap[2] = 0, heap[3] = alen>>>29, heap[4] = alen>>>21, heap[5] = alen>>>13&255, heap[6] = alen>>>5&255, heap[7] = alen<<3&255, heap[8] = heap[9] = heap[10] = 0, heap[11] = clen>>>29, heap[12] = clen>>>21&255, heap[13] = clen>>>13&255, heap[14] = clen>>>5&255, heap[15] = clen<<3&255;
asm.mac( AES_asm.MAC.GCM, AES_asm.HEAP_DATA, 16 );
asm.get_iv( AES_asm.HEAP_DATA );
asm.set_counter( 0, 0, 0, this.gamma0 );
asm.cipher( AES_asm.ENC.CTR, AES_asm.HEAP_DATA, 16 );
var acheck = 0;
for ( var i = 0; i < tagSize; ++i ) acheck |= atag[i] ^ heap[i];
if ( acheck )
throw new SecurityError("data integrity check failed");
this.result = result;
this.counter = 1;
this.pos = 0;
this.len = 0;
return this;
}
function AES_GCM_decrypt ( data ) {
var result1 = AES_GCM_Decrypt_process.call( this, data ).result,
result2 = AES_GCM_Decrypt_finish.call( this ).result;
var result = new Uint8Array( result1.length + result2.length );
if ( result1.length ) result.set( result1 );
if ( result2.length ) result.set( result2, result1.length );
this.result = result;
return this;
}
var AES_GCM_prototype = AES_GCM_constructor.prototype;
AES_GCM_prototype.BLOCK_SIZE = 16;
AES_GCM_prototype.reset = AES_GCM_reset;
AES_GCM_prototype.encrypt = AES_GCM_encrypt;
AES_GCM_prototype.decrypt = AES_GCM_decrypt;
var AES_GCM_Encrypt_prototype = AES_GCM_Encrypt.prototype;
AES_GCM_Encrypt_prototype.BLOCK_SIZE = 16;
AES_GCM_Encrypt_prototype.reset = AES_GCM_reset;
AES_GCM_Encrypt_prototype.process = AES_GCM_Encrypt_process;
AES_GCM_Encrypt_prototype.finish = AES_GCM_Encrypt_finish;
var AES_GCM_Decrypt_prototype = AES_GCM_Decrypt.prototype;
AES_GCM_Decrypt_prototype.BLOCK_SIZE = 16;
AES_GCM_Decrypt_prototype.reset = AES_GCM_reset;
AES_GCM_Decrypt_prototype.process = AES_GCM_Decrypt_process;
AES_GCM_Decrypt_prototype.finish = AES_GCM_Decrypt_finish;
/**
* AES-GCM exports
*/
function AES_GCM_encrypt_bytes ( data, key, nonce, adata, tagSize ) {
if ( data === undefined ) throw new SyntaxError("data required");
if ( key === undefined ) throw new SyntaxError("key required");
if ( nonce === undefined ) throw new SyntaxError("nonce required");
return new AES_GCM_constructor( { heap: _AES_heap_instance, asm: _AES_asm_instance, key: key, nonce: nonce, adata: adata, tagSize: tagSize } ).encrypt(data).result;
}
function AES_GCM_decrypt_bytes ( data, key, nonce, adata, tagSize ) {
if ( data === undefined ) throw new SyntaxError("data required");
if ( key === undefined ) throw new SyntaxError("key required");
if ( nonce === undefined ) throw new SyntaxError("nonce required");
return new AES_GCM_constructor( { heap: _AES_heap_instance, asm: _AES_asm_instance, key: key, nonce: nonce, adata: adata, tagSize: tagSize } ).decrypt(data).result;
}
var AES_GCM = AES_GCM_constructor;
AES_GCM.encrypt = AES_GCM_encrypt_bytes;
AES_GCM.decrypt = AES_GCM_decrypt_bytes;
AES_GCM.Encrypt = AES_GCM_Encrypt;
AES_GCM.Decrypt = AES_GCM_Decrypt;
function sha1_asm ( stdlib, foreign, buffer ) {
var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0,
TOTAL0 = 0, TOTAL1 = 0;
// HMAC state
var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0,
O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0;
// I/O buffer
var HEAP = new stdlib.Uint8Array(buffer);
function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
w0 = w0|0;
w1 = w1|0;
w2 = w2|0;
w3 = w3|0;
w4 = w4|0;
w5 = w5|0;
w6 = w6|0;
w7 = w7|0;
w8 = w8|0;
w9 = w9|0;
w10 = w10|0;
w11 = w11|0;
w12 = w12|0;
w13 = w13|0;
w14 = w14|0;
w15 = w15|0;
var a = 0, b = 0, c = 0, d = 0, e = 0, n = 0, t = 0,
w16 = 0, w17 = 0, w18 = 0, w19 = 0,
w20 = 0, w21 = 0, w22 = 0, w23 = 0, w24 = 0, w25 = 0, w26 = 0, w27 = 0, w28 = 0, w29 = 0,
w30 = 0, w31 = 0, w32 = 0, w33 = 0, w34 = 0, w35 = 0, w36 = 0, w37 = 0, w38 = 0, w39 = 0,
w40 = 0, w41 = 0, w42 = 0, w43 = 0, w44 = 0, w45 = 0, w46 = 0, w47 = 0, w48 = 0, w49 = 0,
w50 = 0, w51 = 0, w52 = 0, w53 = 0, w54 = 0, w55 = 0, w56 = 0, w57 = 0, w58 = 0, w59 = 0,
w60 = 0, w61 = 0, w62 = 0, w63 = 0, w64 = 0, w65 = 0, w66 = 0, w67 = 0, w68 = 0, w69 = 0,
w70 = 0, w71 = 0, w72 = 0, w73 = 0, w74 = 0, w75 = 0, w76 = 0, w77 = 0, w78 = 0, w79 = 0;
a = H0;
b = H1;
c = H2;
d = H3;
e = H4;
// 0
t = ( w0 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 1
t = ( w1 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 2
t = ( w2 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 3
t = ( w3 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 4
t = ( w4 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 5
t = ( w5 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 6
t = ( w6 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 7
t = ( w7 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 8
t = ( w8 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 9
t = ( w9 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 10
t = ( w10 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 11
t = ( w11 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 12
t = ( w12 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 13
t = ( w13 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 14
t = ( w14 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 15
t = ( w15 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 16
n = w13 ^ w8 ^ w2 ^ w0;
w16 = (n << 1) | (n >>> 31);
t = (w16 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 17
n = w14 ^ w9 ^ w3 ^ w1;
w17 = (n << 1) | (n >>> 31);
t = (w17 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 18
n = w15 ^ w10 ^ w4 ^ w2;
w18 = (n << 1) | (n >>> 31);
t = (w18 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 19
n = w16 ^ w11 ^ w5 ^ w3;
w19 = (n << 1) | (n >>> 31);
t = (w19 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (~b & d)) + 0x5a827999 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 20
n = w17 ^ w12 ^ w6 ^ w4;
w20 = (n << 1) | (n >>> 31);
t = (w20 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 21
n = w18 ^ w13 ^ w7 ^ w5;
w21 = (n << 1) | (n >>> 31);
t = (w21 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 22
n = w19 ^ w14 ^ w8 ^ w6;
w22 = (n << 1) | (n >>> 31);
t = (w22 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 23
n = w20 ^ w15 ^ w9 ^ w7;
w23 = (n << 1) | (n >>> 31);
t = (w23 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 24
n = w21 ^ w16 ^ w10 ^ w8;
w24 = (n << 1) | (n >>> 31);
t = (w24 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 25
n = w22 ^ w17 ^ w11 ^ w9;
w25 = (n << 1) | (n >>> 31);
t = (w25 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 26
n = w23 ^ w18 ^ w12 ^ w10;
w26 = (n << 1) | (n >>> 31);
t = (w26 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 27
n = w24 ^ w19 ^ w13 ^ w11;
w27 = (n << 1) | (n >>> 31);
t = (w27 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 28
n = w25 ^ w20 ^ w14 ^ w12;
w28 = (n << 1) | (n >>> 31);
t = (w28 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 29
n = w26 ^ w21 ^ w15 ^ w13;
w29 = (n << 1) | (n >>> 31);
t = (w29 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 30
n = w27 ^ w22 ^ w16 ^ w14;
w30 = (n << 1) | (n >>> 31);
t = (w30 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 31
n = w28 ^ w23 ^ w17 ^ w15;
w31 = (n << 1) | (n >>> 31);
t = (w31 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 32
n = w29 ^ w24 ^ w18 ^ w16;
w32 = (n << 1) | (n >>> 31);
t = (w32 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 33
n = w30 ^ w25 ^ w19 ^ w17;
w33 = (n << 1) | (n >>> 31);
t = (w33 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 34
n = w31 ^ w26 ^ w20 ^ w18;
w34 = (n << 1) | (n >>> 31);
t = (w34 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 35
n = w32 ^ w27 ^ w21 ^ w19;
w35 = (n << 1) | (n >>> 31);
t = (w35 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 36
n = w33 ^ w28 ^ w22 ^ w20;
w36 = (n << 1) | (n >>> 31);
t = (w36 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 37
n = w34 ^ w29 ^ w23 ^ w21;
w37 = (n << 1) | (n >>> 31);
t = (w37 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 38
n = w35 ^ w30 ^ w24 ^ w22;
w38 = (n << 1) | (n >>> 31);
t = (w38 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 39
n = w36 ^ w31 ^ w25 ^ w23;
w39 = (n << 1) | (n >>> 31);
t = (w39 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) + 0x6ed9eba1 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 40
n = w37 ^ w32 ^ w26 ^ w24;
w40 = (n << 1) | (n >>> 31);
t = (w40 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 41
n = w38 ^ w33 ^ w27 ^ w25;
w41 = (n << 1) | (n >>> 31);
t = (w41 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 42
n = w39 ^ w34 ^ w28 ^ w26;
w42 = (n << 1) | (n >>> 31);
t = (w42 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 43
n = w40 ^ w35 ^ w29 ^ w27;
w43 = (n << 1) | (n >>> 31);
t = (w43 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 44
n = w41 ^ w36 ^ w30 ^ w28;
w44 = (n << 1) | (n >>> 31);
t = (w44 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 45
n = w42 ^ w37 ^ w31 ^ w29;
w45 = (n << 1) | (n >>> 31);
t = (w45 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 46
n = w43 ^ w38 ^ w32 ^ w30;
w46 = (n << 1) | (n >>> 31);
t = (w46 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 47
n = w44 ^ w39 ^ w33 ^ w31;
w47 = (n << 1) | (n >>> 31);
t = (w47 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 48
n = w45 ^ w40 ^ w34 ^ w32;
w48 = (n << 1) | (n >>> 31);
t = (w48 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 49
n = w46 ^ w41 ^ w35 ^ w33;
w49 = (n << 1) | (n >>> 31);
t = (w49 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 50
n = w47 ^ w42 ^ w36 ^ w34;
w50 = (n << 1) | (n >>> 31);
t = (w50 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 51
n = w48 ^ w43 ^ w37 ^ w35;
w51 = (n << 1) | (n >>> 31);
t = (w51 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 52
n = w49 ^ w44 ^ w38 ^ w36;
w52 = (n << 1) | (n >>> 31);
t = (w52 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 53
n = w50 ^ w45 ^ w39 ^ w37;
w53 = (n << 1) | (n >>> 31);
t = (w53 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 54
n = w51 ^ w46 ^ w40 ^ w38;
w54 = (n << 1) | (n >>> 31);
t = (w54 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 55
n = w52 ^ w47 ^ w41 ^ w39;
w55 = (n << 1) | (n >>> 31);
t = (w55 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 56
n = w53 ^ w48 ^ w42 ^ w40;
w56 = (n << 1) | (n >>> 31);
t = (w56 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 57
n = w54 ^ w49 ^ w43 ^ w41;
w57 = (n << 1) | (n >>> 31);
t = (w57 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 58
n = w55 ^ w50 ^ w44 ^ w42;
w58 = (n << 1) | (n >>> 31);
t = (w58 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 59
n = w56 ^ w51 ^ w45 ^ w43;
w59 = (n << 1) | (n >>> 31);
t = (w59 + ((a << 5) | (a >>> 27)) + e + ((b & c) | (b & d) | (c & d)) - 0x70e44324 )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 60
n = w57 ^ w52 ^ w46 ^ w44;
w60 = (n << 1) | (n >>> 31);
t = (w60 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 61
n = w58 ^ w53 ^ w47 ^ w45;
w61 = (n << 1) | (n >>> 31);
t = (w61 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 62
n = w59 ^ w54 ^ w48 ^ w46;
w62 = (n << 1) | (n >>> 31);
t = (w62 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 63
n = w60 ^ w55 ^ w49 ^ w47;
w63 = (n << 1) | (n >>> 31);
t = (w63 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 64
n = w61 ^ w56 ^ w50 ^ w48;
w64 = (n << 1) | (n >>> 31);
t = (w64 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 65
n = w62 ^ w57 ^ w51 ^ w49;
w65 = (n << 1) | (n >>> 31);
t = (w65 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 66
n = w63 ^ w58 ^ w52 ^ w50;
w66 = (n << 1) | (n >>> 31);
t = (w66 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 67
n = w64 ^ w59 ^ w53 ^ w51;
w67 = (n << 1) | (n >>> 31);
t = (w67 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 68
n = w65 ^ w60 ^ w54 ^ w52;
w68 = (n << 1) | (n >>> 31);
t = (w68 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 69
n = w66 ^ w61 ^ w55 ^ w53;
w69 = (n << 1) | (n >>> 31);
t = (w69 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 70
n = w67 ^ w62 ^ w56 ^ w54;
w70 = (n << 1) | (n >>> 31);
t = (w70 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 71
n = w68 ^ w63 ^ w57 ^ w55;
w71 = (n << 1) | (n >>> 31);
t = (w71 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 72
n = w69 ^ w64 ^ w58 ^ w56;
w72 = (n << 1) | (n >>> 31);
t = (w72 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 73
n = w70 ^ w65 ^ w59 ^ w57;
w73 = (n << 1) | (n >>> 31);
t = (w73 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 74
n = w71 ^ w66 ^ w60 ^ w58;
w74 = (n << 1) | (n >>> 31);
t = (w74 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 75
n = w72 ^ w67 ^ w61 ^ w59;
w75 = (n << 1) | (n >>> 31);
t = (w75 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 76
n = w73 ^ w68 ^ w62 ^ w60;
w76 = (n << 1) | (n >>> 31);
t = (w76 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 77
n = w74 ^ w69 ^ w63 ^ w61;
w77 = (n << 1) | (n >>> 31);
t = (w77 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 78
n = w75 ^ w70 ^ w64 ^ w62;
w78 = (n << 1) | (n >>> 31);
t = (w78 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
// 79
n = w76 ^ w71 ^ w65 ^ w63;
w79 = (n << 1) | (n >>> 31);
t = (w79 + ((a << 5) | (a >>> 27)) + e + (b ^ c ^ d) - 0x359d3e2a )|0;
e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t;
H0 = ( H0 + a )|0;
H1 = ( H1 + b )|0;
H2 = ( H2 + c )|0;
H3 = ( H3 + d )|0;
H4 = ( H4 + e )|0;
}
function _core_heap ( offset ) {
offset = offset|0;
_core(
HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
);
}
// offset — multiple of 32
function _state_to_heap ( output ) {
output = output|0;
HEAP[output|0] = H0>>>24;
HEAP[output|1] = H0>>>16&255;
HEAP[output|2] = H0>>>8&255;
HEAP[output|3] = H0&255;
HEAP[output|4] = H1>>>24;
HEAP[output|5] = H1>>>16&255;
HEAP[output|6] = H1>>>8&255;
HEAP[output|7] = H1&255;
HEAP[output|8] = H2>>>24;
HEAP[output|9] = H2>>>16&255;
HEAP[output|10] = H2>>>8&255;
HEAP[output|11] = H2&255;
HEAP[output|12] = H3>>>24;
HEAP[output|13] = H3>>>16&255;
HEAP[output|14] = H3>>>8&255;
HEAP[output|15] = H3&255;
HEAP[output|16] = H4>>>24;
HEAP[output|17] = H4>>>16&255;
HEAP[output|18] = H4>>>8&255;
HEAP[output|19] = H4&255;
}
function reset () {
H0 = 0x67452301;
H1 = 0xefcdab89;
H2 = 0x98badcfe;
H3 = 0x10325476;
H4 = 0xc3d2e1f0;
TOTAL0 = TOTAL1 = 0;
}
function init ( h0, h1, h2, h3, h4, total0, total1 ) {
h0 = h0|0;
h1 = h1|0;
h2 = h2|0;
h3 = h3|0;
h4 = h4|0;
total0 = total0|0;
total1 = total1|0;
H0 = h0;
H1 = h1;
H2 = h2;
H3 = h3;
H4 = h4;
TOTAL0 = total0;
TOTAL1 = total1;
}
// offset — multiple of 64
function process ( offset, length ) {
offset = offset|0;
length = length|0;
var hashed = 0;
if ( offset & 63 )
return -1;
while ( (length|0) >= 64 ) {
_core_heap(offset);
offset = ( offset + 64 )|0;
length = ( length - 64 )|0;
hashed = ( hashed + 64 )|0;
}
TOTAL0 = ( TOTAL0 + hashed )|0;
if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
return hashed|0;
}
// offset — multiple of 64
// output — multiple of 32
function finish ( offset, length, output ) {
offset = offset|0;
length = length|0;
output = output|0;
var hashed = 0,
i = 0;
if ( offset & 63 )
return -1;
if ( ~output )
if ( output & 31 )
return -1;
if ( (length|0) >= 64 ) {
hashed = process( offset, length )|0;
if ( (hashed|0) == -1 )
return -1;
offset = ( offset + hashed )|0;
length = ( length - hashed )|0;
}
hashed = ( hashed + length )|0;
TOTAL0 = ( TOTAL0 + length )|0;
if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = (TOTAL1 + 1)|0;
HEAP[offset|length] = 0x80;
if ( (length|0) >= 56 ) {
for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
HEAP[offset|i] = 0x00;
_core_heap(offset);
length = 0;
HEAP[offset|0] = 0;
}
for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
HEAP[offset|i] = 0;
HEAP[offset|56] = TOTAL1>>>21&255;
HEAP[offset|57] = TOTAL1>>>13&255;
HEAP[offset|58] = TOTAL1>>>5&255;
HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
HEAP[offset|60] = TOTAL0>>>21&255;
HEAP[offset|61] = TOTAL0>>>13&255;
HEAP[offset|62] = TOTAL0>>>5&255;
HEAP[offset|63] = TOTAL0<<3&255;
_core_heap(offset);
if ( ~output )
_state_to_heap(output);
return hashed|0;
}
function hmac_reset () {
H0 = I0;
H1 = I1;
H2 = I2;
H3 = I3;
H4 = I4;
TOTAL0 = 64;
TOTAL1 = 0;
}
function _hmac_opad () {
H0 = O0;
H1 = O1;
H2 = O2;
H3 = O3;
H4 = O4;
TOTAL0 = 64;
TOTAL1 = 0;
}
function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
p0 = p0|0;
p1 = p1|0;
p2 = p2|0;
p3 = p3|0;
p4 = p4|0;
p5 = p5|0;
p6 = p6|0;
p7 = p7|0;
p8 = p8|0;
p9 = p9|0;
p10 = p10|0;
p11 = p11|0;
p12 = p12|0;
p13 = p13|0;
p14 = p14|0;
p15 = p15|0;
// opad
reset();
_core(
p0 ^ 0x5c5c5c5c,
p1 ^ 0x5c5c5c5c,
p2 ^ 0x5c5c5c5c,
p3 ^ 0x5c5c5c5c,
p4 ^ 0x5c5c5c5c,
p5 ^ 0x5c5c5c5c,
p6 ^ 0x5c5c5c5c,
p7 ^ 0x5c5c5c5c,
p8 ^ 0x5c5c5c5c,
p9 ^ 0x5c5c5c5c,
p10 ^ 0x5c5c5c5c,
p11 ^ 0x5c5c5c5c,
p12 ^ 0x5c5c5c5c,
p13 ^ 0x5c5c5c5c,
p14 ^ 0x5c5c5c5c,
p15 ^ 0x5c5c5c5c
);
O0 = H0;
O1 = H1;
O2 = H2;
O3 = H3;
O4 = H4;
// ipad
reset();
_core(
p0 ^ 0x36363636,
p1 ^ 0x36363636,
p2 ^ 0x36363636,
p3 ^ 0x36363636,
p4 ^ 0x36363636,
p5 ^ 0x36363636,
p6 ^ 0x36363636,
p7 ^ 0x36363636,
p8 ^ 0x36363636,
p9 ^ 0x36363636,
p10 ^ 0x36363636,
p11 ^ 0x36363636,
p12 ^ 0x36363636,
p13 ^ 0x36363636,
p14 ^ 0x36363636,
p15 ^ 0x36363636
);
I0 = H0;
I1 = H1;
I2 = H2;
I3 = H3;
I4 = H4;
TOTAL0 = 64;
TOTAL1 = 0;
}
// offset — multiple of 64
// output — multiple of 32
function hmac_finish ( offset, length, output ) {
offset = offset|0;
length = length|0;
output = output|0;
var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, hashed = 0;
if ( offset & 63 )
return -1;
if ( ~output )
if ( output & 31 )
return -1;
hashed = finish( offset, length, -1 )|0;
t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
_hmac_opad();
_core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
if ( ~output )
_state_to_heap(output);
return hashed|0;
}
// salt is assumed to be already processed
// offset — multiple of 64
// output — multiple of 32
function pbkdf2_generate_block ( offset, length, block, count, output ) {
offset = offset|0;
length = length|0;
block = block|0;
count = count|0;
output = output|0;
var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0,
t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
if ( offset & 63 )
return -1;
if ( ~output )
if ( output & 31 )
return -1;
// pad block number into heap
// FIXME probable OOB write
HEAP[(offset+length)|0] = block>>>24;
HEAP[(offset+length+1)|0] = block>>>16&255;
HEAP[(offset+length+2)|0] = block>>>8&255;
HEAP[(offset+length+3)|0] = block&255;
// finish first iteration
hmac_finish( offset, (length+4)|0, -1 )|0;
h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4;
count = (count-1)|0;
// perform the rest iterations
while ( (count|0) > 0 ) {
hmac_reset();
_core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
_hmac_opad();
_core( t0, t1, t2, t3, t4, 0x80000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 672 );
t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4;
h0 = h0 ^ H0;
h1 = h1 ^ H1;
h2 = h2 ^ H2;
h3 = h3 ^ H3;
h4 = h4 ^ H4;
count = (count-1)|0;
}
H0 = h0;
H1 = h1;
H2 = h2;
H3 = h3;
H4 = h4;
if ( ~output )
_state_to_heap(output);
return 0;
}
return {
// SHA1
reset: reset,
init: init,
process: process,
finish: finish,
// HMAC-SHA1
hmac_reset: hmac_reset,
hmac_init: hmac_init,
hmac_finish: hmac_finish,
// PBKDF2-HMAC-SHA1
pbkdf2_generate_block: pbkdf2_generate_block
}
}
function hash_reset () {
this.result = null;
this.pos = 0;
this.len = 0;
this.asm.reset();
return this;
}
function hash_process ( data ) {
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
if ( is_string(data) )
data = string_to_bytes(data);
if ( is_buffer(data) )
data = new Uint8Array(data);
if ( !is_bytes(data) )
throw new TypeError("data isn't of expected type");
var asm = this.asm,
heap = this.heap,
hpos = this.pos,
hlen = this.len,
dpos = 0,
dlen = data.length,
wlen = 0;
while ( dlen > 0 ) {
wlen = _heap_write( heap, hpos+hlen, data, dpos, dlen );
hlen += wlen;
dpos += wlen;
dlen -= wlen;
wlen = asm.process( hpos, hlen );
hpos += wlen;
hlen -= wlen;
if ( !hlen ) hpos = 0;
}
this.pos = hpos;
this.len = hlen;
return this;
}
function hash_finish () {
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
this.asm.finish( this.pos, this.len, 0 );
this.result = new Uint8Array(this.HASH_SIZE);
this.result.set( this.heap.subarray( 0, this.HASH_SIZE ) );
this.pos = 0;
this.len = 0;
return this;
}
var _sha1_block_size = 64;
var _sha1_hash_size = 20;
function sha1_constructor ( options ) {
options = options || {};
this.heap = _heap_init( Uint8Array, options );
this.asm = options.asm || sha1_asm( { Uint8Array: Uint8Array }, null, this.heap.buffer );
this.BLOCK_SIZE = _sha1_block_size;
this.HASH_SIZE = _sha1_hash_size;
this.reset();
}
sha1_constructor.BLOCK_SIZE = _sha1_block_size;
sha1_constructor.NAME = "sha1";
sha1_constructor.HASH_SIZE = _sha1_hash_size;
var sha1_prototype = sha1_constructor.prototype;
sha1_prototype.reset = hash_reset;
sha1_prototype.process = hash_process;
sha1_prototype.finish = hash_finish;
var sha1_instance = null;
function get_sha1_instance () {
if ( sha1_instance === null ) sha1_instance = new sha1_constructor( { heapSize: 0x100000 } );
return sha1_instance;
}
/**
* SHA1 exports
*/
function sha1_bytes (data ) {
if ( data === undefined ) throw new SyntaxError("data required");
return get_sha1_instance().reset().process(data).finish().result;
}
function sha1_hex ( data ) {
var result = sha1_bytes(data);
return bytes_to_hex(result);
}
function sha1_base64 ( data ) {
var result = sha1_bytes(data);
return bytes_to_base64(result);
}
var SHA1 = sha1_constructor;
SHA1.bytes = sha1_bytes;
SHA1.hex = sha1_hex;
SHA1.base64 = sha1_base64;
function sha256_asm ( stdlib, foreign, buffer ) {
var H0 = 0, H1 = 0, H2 = 0, H3 = 0, H4 = 0, H5 = 0, H6 = 0, H7 = 0,
TOTAL0 = 0, TOTAL1 = 0;
// HMAC state
var I0 = 0, I1 = 0, I2 = 0, I3 = 0, I4 = 0, I5 = 0, I6 = 0, I7 = 0,
O0 = 0, O1 = 0, O2 = 0, O3 = 0, O4 = 0, O5 = 0, O6 = 0, O7 = 0;
// I/O buffer
var HEAP = new stdlib.Uint8Array(buffer);
function _core ( w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15 ) {
w0 = w0|0;
w1 = w1|0;
w2 = w2|0;
w3 = w3|0;
w4 = w4|0;
w5 = w5|0;
w6 = w6|0;
w7 = w7|0;
w8 = w8|0;
w9 = w9|0;
w10 = w10|0;
w11 = w11|0;
w12 = w12|0;
w13 = w13|0;
w14 = w14|0;
w15 = w15|0;
var a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0;
a = H0;
b = H1;
c = H2;
d = H3;
e = H4;
f = H5;
g = H6;
h = H7;
// 0
h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x428a2f98 )|0;
d = ( d + h )|0;
h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
// 1
g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x71374491 )|0;
c = ( c + g )|0;
g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
// 2
f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb5c0fbcf )|0;
b = ( b + f )|0;
f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
// 3
e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xe9b5dba5 )|0;
a = ( a + e )|0;
e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
// 4
d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x3956c25b )|0;
h = ( h + d )|0;
d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
// 5
c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x59f111f1 )|0;
g = ( g + c )|0;
c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
// 6
b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x923f82a4 )|0;
f = ( f + b )|0;
b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
// 7
a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xab1c5ed5 )|0;
e = ( e + a )|0;
a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
// 8
h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xd807aa98 )|0;
d = ( d + h )|0;
h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
// 9
g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x12835b01 )|0;
c = ( c + g )|0;
g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
// 10
f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x243185be )|0;
b = ( b + f )|0;
f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
// 11
e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x550c7dc3 )|0;
a = ( a + e )|0;
e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
// 12
d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x72be5d74 )|0;
h = ( h + d )|0;
d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
// 13
c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x80deb1fe )|0;
g = ( g + c )|0;
c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
// 14
b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x9bdc06a7 )|0;
f = ( f + b )|0;
b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
// 15
a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc19bf174 )|0;
e = ( e + a )|0;
a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
// 16
w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xe49b69c1 )|0;
d = ( d + h )|0;
h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
// 17
w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xefbe4786 )|0;
c = ( c + g )|0;
g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
// 18
w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x0fc19dc6 )|0;
b = ( b + f )|0;
f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
// 19
w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x240ca1cc )|0;
a = ( a + e )|0;
e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
// 20
w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x2de92c6f )|0;
h = ( h + d )|0;
d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
// 21
w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4a7484aa )|0;
g = ( g + c )|0;
c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
// 22
w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5cb0a9dc )|0;
f = ( f + b )|0;
b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
// 23
w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x76f988da )|0;
e = ( e + a )|0;
a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
// 24
w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x983e5152 )|0;
d = ( d + h )|0;
h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
// 25
w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa831c66d )|0;
c = ( c + g )|0;
g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
// 26
w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xb00327c8 )|0;
b = ( b + f )|0;
f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
// 27
w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xbf597fc7 )|0;
a = ( a + e )|0;
e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
// 28
w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xc6e00bf3 )|0;
h = ( h + d )|0;
d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
// 29
w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd5a79147 )|0;
g = ( g + c )|0;
c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
// 30
w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x06ca6351 )|0;
f = ( f + b )|0;
b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
// 31
w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x14292967 )|0;
e = ( e + a )|0;
a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
// 32
w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x27b70a85 )|0;
d = ( d + h )|0;
h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
// 33
w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x2e1b2138 )|0;
c = ( c + g )|0;
g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
// 34
w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x4d2c6dfc )|0;
b = ( b + f )|0;
f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
// 35
w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x53380d13 )|0;
a = ( a + e )|0;
e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
// 36
w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x650a7354 )|0;
h = ( h + d )|0;
d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
// 37
w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x766a0abb )|0;
g = ( g + c )|0;
c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
// 38
w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x81c2c92e )|0;
f = ( f + b )|0;
b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
// 39
w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x92722c85 )|0;
e = ( e + a )|0;
a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
// 40
w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0xa2bfe8a1 )|0;
d = ( d + h )|0;
h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
// 41
w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0xa81a664b )|0;
c = ( c + g )|0;
g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
// 42
w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0xc24b8b70 )|0;
b = ( b + f )|0;
f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
// 43
w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0xc76c51a3 )|0;
a = ( a + e )|0;
e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
// 44
w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0xd192e819 )|0;
h = ( h + d )|0;
d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
// 45
w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xd6990624 )|0;
g = ( g + c )|0;
c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
// 46
w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xf40e3585 )|0;
f = ( f + b )|0;
b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
// 47
w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x106aa070 )|0;
e = ( e + a )|0;
a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
// 48
w0 = ( ( w1>>>7 ^ w1>>>18 ^ w1>>>3 ^ w1<<25 ^ w1<<14 ) + ( w14>>>17 ^ w14>>>19 ^ w14>>>10 ^ w14<<15 ^ w14<<13 ) + w0 + w9 )|0;
h = ( w0 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x19a4c116 )|0;
d = ( d + h )|0;
h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
// 49
w1 = ( ( w2>>>7 ^ w2>>>18 ^ w2>>>3 ^ w2<<25 ^ w2<<14 ) + ( w15>>>17 ^ w15>>>19 ^ w15>>>10 ^ w15<<15 ^ w15<<13 ) + w1 + w10 )|0;
g = ( w1 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x1e376c08 )|0;
c = ( c + g )|0;
g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
// 50
w2 = ( ( w3>>>7 ^ w3>>>18 ^ w3>>>3 ^ w3<<25 ^ w3<<14 ) + ( w0>>>17 ^ w0>>>19 ^ w0>>>10 ^ w0<<15 ^ w0<<13 ) + w2 + w11 )|0;
f = ( w2 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x2748774c )|0;
b = ( b + f )|0;
f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
// 51
w3 = ( ( w4>>>7 ^ w4>>>18 ^ w4>>>3 ^ w4<<25 ^ w4<<14 ) + ( w1>>>17 ^ w1>>>19 ^ w1>>>10 ^ w1<<15 ^ w1<<13 ) + w3 + w12 )|0;
e = ( w3 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x34b0bcb5 )|0;
a = ( a + e )|0;
e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
// 52
w4 = ( ( w5>>>7 ^ w5>>>18 ^ w5>>>3 ^ w5<<25 ^ w5<<14 ) + ( w2>>>17 ^ w2>>>19 ^ w2>>>10 ^ w2<<15 ^ w2<<13 ) + w4 + w13 )|0;
d = ( w4 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x391c0cb3 )|0;
h = ( h + d )|0;
d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
// 53
w5 = ( ( w6>>>7 ^ w6>>>18 ^ w6>>>3 ^ w6<<25 ^ w6<<14 ) + ( w3>>>17 ^ w3>>>19 ^ w3>>>10 ^ w3<<15 ^ w3<<13 ) + w5 + w14 )|0;
c = ( w5 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0x4ed8aa4a )|0;
g = ( g + c )|0;
c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
// 54
w6 = ( ( w7>>>7 ^ w7>>>18 ^ w7>>>3 ^ w7<<25 ^ w7<<14 ) + ( w4>>>17 ^ w4>>>19 ^ w4>>>10 ^ w4<<15 ^ w4<<13 ) + w6 + w15 )|0;
b = ( w6 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0x5b9cca4f )|0;
f = ( f + b )|0;
b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
// 55
w7 = ( ( w8>>>7 ^ w8>>>18 ^ w8>>>3 ^ w8<<25 ^ w8<<14 ) + ( w5>>>17 ^ w5>>>19 ^ w5>>>10 ^ w5<<15 ^ w5<<13 ) + w7 + w0 )|0;
a = ( w7 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0x682e6ff3 )|0;
e = ( e + a )|0;
a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
// 56
w8 = ( ( w9>>>7 ^ w9>>>18 ^ w9>>>3 ^ w9<<25 ^ w9<<14 ) + ( w6>>>17 ^ w6>>>19 ^ w6>>>10 ^ w6<<15 ^ w6<<13 ) + w8 + w1 )|0;
h = ( w8 + h + ( e>>>6 ^ e>>>11 ^ e>>>25 ^ e<<26 ^ e<<21 ^ e<<7 ) + ( g ^ e & (f^g) ) + 0x748f82ee )|0;
d = ( d + h )|0;
h = ( h + ( (a & b) ^ ( c & (a ^ b) ) ) + ( a>>>2 ^ a>>>13 ^ a>>>22 ^ a<<30 ^ a<<19 ^ a<<10 ) )|0;
// 57
w9 = ( ( w10>>>7 ^ w10>>>18 ^ w10>>>3 ^ w10<<25 ^ w10<<14 ) + ( w7>>>17 ^ w7>>>19 ^ w7>>>10 ^ w7<<15 ^ w7<<13 ) + w9 + w2 )|0;
g = ( w9 + g + ( d>>>6 ^ d>>>11 ^ d>>>25 ^ d<<26 ^ d<<21 ^ d<<7 ) + ( f ^ d & (e^f) ) + 0x78a5636f )|0;
c = ( c + g )|0;
g = ( g + ( (h & a) ^ ( b & (h ^ a) ) ) + ( h>>>2 ^ h>>>13 ^ h>>>22 ^ h<<30 ^ h<<19 ^ h<<10 ) )|0;
// 58
w10 = ( ( w11>>>7 ^ w11>>>18 ^ w11>>>3 ^ w11<<25 ^ w11<<14 ) + ( w8>>>17 ^ w8>>>19 ^ w8>>>10 ^ w8<<15 ^ w8<<13 ) + w10 + w3 )|0;
f = ( w10 + f + ( c>>>6 ^ c>>>11 ^ c>>>25 ^ c<<26 ^ c<<21 ^ c<<7 ) + ( e ^ c & (d^e) ) + 0x84c87814 )|0;
b = ( b + f )|0;
f = ( f + ( (g & h) ^ ( a & (g ^ h) ) ) + ( g>>>2 ^ g>>>13 ^ g>>>22 ^ g<<30 ^ g<<19 ^ g<<10 ) )|0;
// 59
w11 = ( ( w12>>>7 ^ w12>>>18 ^ w12>>>3 ^ w12<<25 ^ w12<<14 ) + ( w9>>>17 ^ w9>>>19 ^ w9>>>10 ^ w9<<15 ^ w9<<13 ) + w11 + w4 )|0;
e = ( w11 + e + ( b>>>6 ^ b>>>11 ^ b>>>25 ^ b<<26 ^ b<<21 ^ b<<7 ) + ( d ^ b & (c^d) ) + 0x8cc70208 )|0;
a = ( a + e )|0;
e = ( e + ( (f & g) ^ ( h & (f ^ g) ) ) + ( f>>>2 ^ f>>>13 ^ f>>>22 ^ f<<30 ^ f<<19 ^ f<<10 ) )|0;
// 60
w12 = ( ( w13>>>7 ^ w13>>>18 ^ w13>>>3 ^ w13<<25 ^ w13<<14 ) + ( w10>>>17 ^ w10>>>19 ^ w10>>>10 ^ w10<<15 ^ w10<<13 ) + w12 + w5 )|0;
d = ( w12 + d + ( a>>>6 ^ a>>>11 ^ a>>>25 ^ a<<26 ^ a<<21 ^ a<<7 ) + ( c ^ a & (b^c) ) + 0x90befffa )|0;
h = ( h + d )|0;
d = ( d + ( (e & f) ^ ( g & (e ^ f) ) ) + ( e>>>2 ^ e>>>13 ^ e>>>22 ^ e<<30 ^ e<<19 ^ e<<10 ) )|0;
// 61
w13 = ( ( w14>>>7 ^ w14>>>18 ^ w14>>>3 ^ w14<<25 ^ w14<<14 ) + ( w11>>>17 ^ w11>>>19 ^ w11>>>10 ^ w11<<15 ^ w11<<13 ) + w13 + w6 )|0;
c = ( w13 + c + ( h>>>6 ^ h>>>11 ^ h>>>25 ^ h<<26 ^ h<<21 ^ h<<7 ) + ( b ^ h & (a^b) ) + 0xa4506ceb )|0;
g = ( g + c )|0;
c = ( c + ( (d & e) ^ ( f & (d ^ e) ) ) + ( d>>>2 ^ d>>>13 ^ d>>>22 ^ d<<30 ^ d<<19 ^ d<<10 ) )|0;
// 62
w14 = ( ( w15>>>7 ^ w15>>>18 ^ w15>>>3 ^ w15<<25 ^ w15<<14 ) + ( w12>>>17 ^ w12>>>19 ^ w12>>>10 ^ w12<<15 ^ w12<<13 ) + w14 + w7 )|0;
b = ( w14 + b + ( g>>>6 ^ g>>>11 ^ g>>>25 ^ g<<26 ^ g<<21 ^ g<<7 ) + ( a ^ g & (h^a) ) + 0xbef9a3f7 )|0;
f = ( f + b )|0;
b = ( b + ( (c & d) ^ ( e & (c ^ d) ) ) + ( c>>>2 ^ c>>>13 ^ c>>>22 ^ c<<30 ^ c<<19 ^ c<<10 ) )|0;
// 63
w15 = ( ( w0>>>7 ^ w0>>>18 ^ w0>>>3 ^ w0<<25 ^ w0<<14 ) + ( w13>>>17 ^ w13>>>19 ^ w13>>>10 ^ w13<<15 ^ w13<<13 ) + w15 + w8 )|0;
a = ( w15 + a + ( f>>>6 ^ f>>>11 ^ f>>>25 ^ f<<26 ^ f<<21 ^ f<<7 ) + ( h ^ f & (g^h) ) + 0xc67178f2 )|0;
e = ( e + a )|0;
a = ( a + ( (b & c) ^ ( d & (b ^ c) ) ) + ( b>>>2 ^ b>>>13 ^ b>>>22 ^ b<<30 ^ b<<19 ^ b<<10 ) )|0;
H0 = ( H0 + a )|0;
H1 = ( H1 + b )|0;
H2 = ( H2 + c )|0;
H3 = ( H3 + d )|0;
H4 = ( H4 + e )|0;
H5 = ( H5 + f )|0;
H6 = ( H6 + g )|0;
H7 = ( H7 + h )|0;
}
function _core_heap ( offset ) {
offset = offset|0;
_core(
HEAP[offset|0]<<24 | HEAP[offset|1]<<16 | HEAP[offset|2]<<8 | HEAP[offset|3],
HEAP[offset|4]<<24 | HEAP[offset|5]<<16 | HEAP[offset|6]<<8 | HEAP[offset|7],
HEAP[offset|8]<<24 | HEAP[offset|9]<<16 | HEAP[offset|10]<<8 | HEAP[offset|11],
HEAP[offset|12]<<24 | HEAP[offset|13]<<16 | HEAP[offset|14]<<8 | HEAP[offset|15],
HEAP[offset|16]<<24 | HEAP[offset|17]<<16 | HEAP[offset|18]<<8 | HEAP[offset|19],
HEAP[offset|20]<<24 | HEAP[offset|21]<<16 | HEAP[offset|22]<<8 | HEAP[offset|23],
HEAP[offset|24]<<24 | HEAP[offset|25]<<16 | HEAP[offset|26]<<8 | HEAP[offset|27],
HEAP[offset|28]<<24 | HEAP[offset|29]<<16 | HEAP[offset|30]<<8 | HEAP[offset|31],
HEAP[offset|32]<<24 | HEAP[offset|33]<<16 | HEAP[offset|34]<<8 | HEAP[offset|35],
HEAP[offset|36]<<24 | HEAP[offset|37]<<16 | HEAP[offset|38]<<8 | HEAP[offset|39],
HEAP[offset|40]<<24 | HEAP[offset|41]<<16 | HEAP[offset|42]<<8 | HEAP[offset|43],
HEAP[offset|44]<<24 | HEAP[offset|45]<<16 | HEAP[offset|46]<<8 | HEAP[offset|47],
HEAP[offset|48]<<24 | HEAP[offset|49]<<16 | HEAP[offset|50]<<8 | HEAP[offset|51],
HEAP[offset|52]<<24 | HEAP[offset|53]<<16 | HEAP[offset|54]<<8 | HEAP[offset|55],
HEAP[offset|56]<<24 | HEAP[offset|57]<<16 | HEAP[offset|58]<<8 | HEAP[offset|59],
HEAP[offset|60]<<24 | HEAP[offset|61]<<16 | HEAP[offset|62]<<8 | HEAP[offset|63]
);
}
// offset — multiple of 32
function _state_to_heap ( output ) {
output = output|0;
HEAP[output|0] = H0>>>24;
HEAP[output|1] = H0>>>16&255;
HEAP[output|2] = H0>>>8&255;
HEAP[output|3] = H0&255;
HEAP[output|4] = H1>>>24;
HEAP[output|5] = H1>>>16&255;
HEAP[output|6] = H1>>>8&255;
HEAP[output|7] = H1&255;
HEAP[output|8] = H2>>>24;
HEAP[output|9] = H2>>>16&255;
HEAP[output|10] = H2>>>8&255;
HEAP[output|11] = H2&255;
HEAP[output|12] = H3>>>24;
HEAP[output|13] = H3>>>16&255;
HEAP[output|14] = H3>>>8&255;
HEAP[output|15] = H3&255;
HEAP[output|16] = H4>>>24;
HEAP[output|17] = H4>>>16&255;
HEAP[output|18] = H4>>>8&255;
HEAP[output|19] = H4&255;
HEAP[output|20] = H5>>>24;
HEAP[output|21] = H5>>>16&255;
HEAP[output|22] = H5>>>8&255;
HEAP[output|23] = H5&255;
HEAP[output|24] = H6>>>24;
HEAP[output|25] = H6>>>16&255;
HEAP[output|26] = H6>>>8&255;
HEAP[output|27] = H6&255;
HEAP[output|28] = H7>>>24;
HEAP[output|29] = H7>>>16&255;
HEAP[output|30] = H7>>>8&255;
HEAP[output|31] = H7&255;
}
function reset () {
H0 = 0x6a09e667;
H1 = 0xbb67ae85;
H2 = 0x3c6ef372;
H3 = 0xa54ff53a;
H4 = 0x510e527f;
H5 = 0x9b05688c;
H6 = 0x1f83d9ab;
H7 = 0x5be0cd19;
TOTAL0 = TOTAL1 = 0;
}
function init ( h0, h1, h2, h3, h4, h5, h6, h7, total0, total1 ) {
h0 = h0|0;
h1 = h1|0;
h2 = h2|0;
h3 = h3|0;
h4 = h4|0;
h5 = h5|0;
h6 = h6|0;
h7 = h7|0;
total0 = total0|0;
total1 = total1|0;
H0 = h0;
H1 = h1;
H2 = h2;
H3 = h3;
H4 = h4;
H5 = h5;
H6 = h6;
H7 = h7;
TOTAL0 = total0;
TOTAL1 = total1;
}
// offset — multiple of 64
function process ( offset, length ) {
offset = offset|0;
length = length|0;
var hashed = 0;
if ( offset & 63 )
return -1;
while ( (length|0) >= 64 ) {
_core_heap(offset);
offset = ( offset + 64 )|0;
length = ( length - 64 )|0;
hashed = ( hashed + 64 )|0;
}
TOTAL0 = ( TOTAL0 + hashed )|0;
if ( TOTAL0>>>0 < hashed>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
return hashed|0;
}
// offset — multiple of 64
// output — multiple of 32
function finish ( offset, length, output ) {
offset = offset|0;
length = length|0;
output = output|0;
var hashed = 0,
i = 0;
if ( offset & 63 )
return -1;
if ( ~output )
if ( output & 31 )
return -1;
if ( (length|0) >= 64 ) {
hashed = process( offset, length )|0;
if ( (hashed|0) == -1 )
return -1;
offset = ( offset + hashed )|0;
length = ( length - hashed )|0;
}
hashed = ( hashed + length )|0;
TOTAL0 = ( TOTAL0 + length )|0;
if ( TOTAL0>>>0 < length>>>0 ) TOTAL1 = ( TOTAL1 + 1 )|0;
HEAP[offset|length] = 0x80;
if ( (length|0) >= 56 ) {
for ( i = (length+1)|0; (i|0) < 64; i = (i+1)|0 )
HEAP[offset|i] = 0x00;
_core_heap(offset);
length = 0;
HEAP[offset|0] = 0;
}
for ( i = (length+1)|0; (i|0) < 59; i = (i+1)|0 )
HEAP[offset|i] = 0;
HEAP[offset|56] = TOTAL1>>>21&255;
HEAP[offset|57] = TOTAL1>>>13&255;
HEAP[offset|58] = TOTAL1>>>5&255;
HEAP[offset|59] = TOTAL1<<3&255 | TOTAL0>>>29;
HEAP[offset|60] = TOTAL0>>>21&255;
HEAP[offset|61] = TOTAL0>>>13&255;
HEAP[offset|62] = TOTAL0>>>5&255;
HEAP[offset|63] = TOTAL0<<3&255;
_core_heap(offset);
if ( ~output )
_state_to_heap(output);
return hashed|0;
}
function hmac_reset () {
H0 = I0;
H1 = I1;
H2 = I2;
H3 = I3;
H4 = I4;
H5 = I5;
H6 = I6;
H7 = I7;
TOTAL0 = 64;
TOTAL1 = 0;
}
function _hmac_opad () {
H0 = O0;
H1 = O1;
H2 = O2;
H3 = O3;
H4 = O4;
H5 = O5;
H6 = O6;
H7 = O7;
TOTAL0 = 64;
TOTAL1 = 0;
}
function hmac_init ( p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15 ) {
p0 = p0|0;
p1 = p1|0;
p2 = p2|0;
p3 = p3|0;
p4 = p4|0;
p5 = p5|0;
p6 = p6|0;
p7 = p7|0;
p8 = p8|0;
p9 = p9|0;
p10 = p10|0;
p11 = p11|0;
p12 = p12|0;
p13 = p13|0;
p14 = p14|0;
p15 = p15|0;
// opad
reset();
_core(
p0 ^ 0x5c5c5c5c,
p1 ^ 0x5c5c5c5c,
p2 ^ 0x5c5c5c5c,
p3 ^ 0x5c5c5c5c,
p4 ^ 0x5c5c5c5c,
p5 ^ 0x5c5c5c5c,
p6 ^ 0x5c5c5c5c,
p7 ^ 0x5c5c5c5c,
p8 ^ 0x5c5c5c5c,
p9 ^ 0x5c5c5c5c,
p10 ^ 0x5c5c5c5c,
p11 ^ 0x5c5c5c5c,
p12 ^ 0x5c5c5c5c,
p13 ^ 0x5c5c5c5c,
p14 ^ 0x5c5c5c5c,
p15 ^ 0x5c5c5c5c
);
O0 = H0;
O1 = H1;
O2 = H2;
O3 = H3;
O4 = H4;
O5 = H5;
O6 = H6;
O7 = H7;
// ipad
reset();
_core(
p0 ^ 0x36363636,
p1 ^ 0x36363636,
p2 ^ 0x36363636,
p3 ^ 0x36363636,
p4 ^ 0x36363636,
p5 ^ 0x36363636,
p6 ^ 0x36363636,
p7 ^ 0x36363636,
p8 ^ 0x36363636,
p9 ^ 0x36363636,
p10 ^ 0x36363636,
p11 ^ 0x36363636,
p12 ^ 0x36363636,
p13 ^ 0x36363636,
p14 ^ 0x36363636,
p15 ^ 0x36363636
);
I0 = H0;
I1 = H1;
I2 = H2;
I3 = H3;
I4 = H4;
I5 = H5;
I6 = H6;
I7 = H7;
TOTAL0 = 64;
TOTAL1 = 0;
}
// offset — multiple of 64
// output — multiple of 32
function hmac_finish ( offset, length, output ) {
offset = offset|0;
length = length|0;
output = output|0;
var t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
hashed = 0;
if ( offset & 63 )
return -1;
if ( ~output )
if ( output & 31 )
return -1;
hashed = finish( offset, length, -1 )|0;
t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
_hmac_opad();
_core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
if ( ~output )
_state_to_heap(output);
return hashed|0;
}
// salt is assumed to be already processed
// offset — multiple of 64
// output — multiple of 32
function pbkdf2_generate_block ( offset, length, block, count, output ) {
offset = offset|0;
length = length|0;
block = block|0;
count = count|0;
output = output|0;
var h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0, h7 = 0,
t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0;
if ( offset & 63 )
return -1;
if ( ~output )
if ( output & 31 )
return -1;
// pad block number into heap
// FIXME probable OOB write
HEAP[(offset+length)|0] = block>>>24;
HEAP[(offset+length+1)|0] = block>>>16&255;
HEAP[(offset+length+2)|0] = block>>>8&255;
HEAP[(offset+length+3)|0] = block&255;
// finish first iteration
hmac_finish( offset, (length+4)|0, -1 )|0;
h0 = t0 = H0, h1 = t1 = H1, h2 = t2 = H2, h3 = t3 = H3, h4 = t4 = H4, h5 = t5 = H5, h6 = t6 = H6, h7 = t7 = H7;
count = (count-1)|0;
// perform the rest iterations
while ( (count|0) > 0 ) {
hmac_reset();
_core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
_hmac_opad();
_core( t0, t1, t2, t3, t4, t5, t6, t7, 0x80000000, 0, 0, 0, 0, 0, 0, 768 );
t0 = H0, t1 = H1, t2 = H2, t3 = H3, t4 = H4, t5 = H5, t6 = H6, t7 = H7;
h0 = h0 ^ H0;
h1 = h1 ^ H1;
h2 = h2 ^ H2;
h3 = h3 ^ H3;
h4 = h4 ^ H4;
h5 = h5 ^ H5;
h6 = h6 ^ H6;
h7 = h7 ^ H7;
count = (count-1)|0;
}
H0 = h0;
H1 = h1;
H2 = h2;
H3 = h3;
H4 = h4;
H5 = h5;
H6 = h6;
H7 = h7;
if ( ~output )
_state_to_heap(output);
return 0;
}
return {
// SHA256
reset: reset,
init: init,
process: process,
finish: finish,
// HMAC-SHA256
hmac_reset: hmac_reset,
hmac_init: hmac_init,
hmac_finish: hmac_finish,
// PBKDF2-HMAC-SHA256
pbkdf2_generate_block: pbkdf2_generate_block
}
}
var _sha256_block_size = 64;
var _sha256_hash_size = 32;
function sha256_constructor ( options ) {
options = options || {};
this.heap = _heap_init( Uint8Array, options );
this.asm = options.asm || sha256_asm( { Uint8Array: Uint8Array }, null, this.heap.buffer );
this.BLOCK_SIZE = _sha256_block_size;
this.HASH_SIZE = _sha256_hash_size;
this.reset();
}
sha256_constructor.BLOCK_SIZE = _sha256_block_size;
sha256_constructor.HASH_SIZE = _sha256_hash_size;
sha256_constructor.NAME = "sha256";
var sha256_prototype = sha256_constructor.prototype;
sha256_prototype.reset = hash_reset;
sha256_prototype.process = hash_process;
sha256_prototype.finish = hash_finish;
var sha256_instance = null;
function get_sha256_instance () {
if ( sha256_instance === null ) sha256_instance = new sha256_constructor( { heapSize: 0x100000 } );
return sha256_instance;
}
/**
* SHA256 exports
*/
function sha256_bytes (data ) {
if ( data === undefined ) throw new SyntaxError("data required");
return get_sha256_instance().reset().process(data).finish().result;
}
function sha256_hex ( data ) {
var result = sha256_bytes(data);
return bytes_to_hex(result);
}
function sha256_base64 ( data ) {
var result = sha256_bytes(data);
return bytes_to_base64(result);
}
var SHA256 = sha256_constructor;
SHA256.bytes = sha256_bytes;
SHA256.hex = sha256_hex;
SHA256.base64 = sha256_base64;
function hmac_constructor (options ) {
options = options || {};
if ( !options.hash )
throw new SyntaxError("option 'hash' is required");
if ( !options.hash.HASH_SIZE )
throw new SyntaxError("option 'hash' supplied doesn't seem to be a valid hash function");
this.hash = options.hash;
this.BLOCK_SIZE = this.hash.BLOCK_SIZE;
this.HMAC_SIZE = this.hash.HASH_SIZE;
this.key = null;
this.verify = null;
this.result = null;
if ( options.password !== undefined || options.verify !== undefined )
this.reset(options);
return this;
}
function _hmac_key ( hash, password ) {
if ( is_buffer(password) )
password = new Uint8Array(password);
if ( is_string(password) )
password = string_to_bytes(password);
if ( !is_bytes(password) )
throw new TypeError("password isn't of expected type");
var key = new Uint8Array( hash.BLOCK_SIZE );
if ( password.length > hash.BLOCK_SIZE ) {
key.set( hash.reset().process(password).finish().result );
}
else {
key.set(password);
}
return key;
}
function _hmac_init_verify ( verify ) {
if ( is_buffer(verify) || is_bytes(verify) ) {
verify = new Uint8Array(verify);
}
else if ( is_string(verify) ) {
verify = string_to_bytes(verify);
}
else {
throw new TypeError("verify tag isn't of expected type");
}
if ( verify.length !== this.HMAC_SIZE )
throw new IllegalArgumentError("illegal verification tag size");
this.verify = verify;
}
function hmac_reset ( options ) {
options = options || {};
var password = options.password;
if ( this.key === null && !is_string(password) && !password )
throw new IllegalStateError("no key is associated with the instance");
this.result = null;
this.hash.reset();
if ( password || is_string(password) )
this.key = _hmac_key( this.hash, password );
var ipad = new Uint8Array(this.key);
for ( var i = 0; i < ipad.length; ++i )
ipad[i] ^= 0x36;
this.hash.process(ipad);
var verify = options.verify;
if ( verify !== undefined ) {
_hmac_init_verify.call( this, verify );
}
else {
this.verify = null;
}
return this;
}
function hmac_process ( data ) {
if ( this.key === null )
throw new IllegalStateError("no key is associated with the instance");
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
this.hash.process(data);
return this;
}
function hmac_finish () {
if ( this.key === null )
throw new IllegalStateError("no key is associated with the instance");
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
var inner_result = this.hash.finish().result;
var opad = new Uint8Array(this.key);
for ( var i = 0; i < opad.length; ++i )
opad[i] ^= 0x5c;
var verify = this.verify;
var result = this.hash.reset().process(opad).process(inner_result).finish().result;
if ( verify ) {
if ( verify.length === result.length ) {
var diff = 0;
for ( var i = 0; i < verify.length; i++ ) {
diff |= ( verify[i] ^ result[i] );
}
this.result = !diff;
} else {
this.result = false;
}
}
else {
this.result = result;
}
return this;
}
var hmac_prototype = hmac_constructor.prototype;
hmac_prototype.reset = hmac_reset;
hmac_prototype.process = hmac_process;
hmac_prototype.finish = hmac_finish;
function hmac_sha1_constructor (options ) {
options = options || {};
if ( !( options.hash instanceof sha1_constructor ) )
options.hash = get_sha1_instance();
hmac_constructor.call( this, options );
return this;
}
function hmac_sha1_reset ( options ) {
options = options || {};
this.result = null;
this.hash.reset();
var password = options.password;
if ( password !== undefined ) {
if ( is_string(password) )
password = string_to_bytes(password);
var key = this.key = _hmac_key( this.hash, password );
this.hash.reset().asm.hmac_init(
(key[0]<<24)|(key[1]<<16)|(key[2]<<8)|(key[3]),
(key[4]<<24)|(key[5]<<16)|(key[6]<<8)|(key[7]),
(key[8]<<24)|(key[9]<<16)|(key[10]<<8)|(key[11]),
(key[12]<<24)|(key[13]<<16)|(key[14]<<8)|(key[15]),
(key[16]<<24)|(key[17]<<16)|(key[18]<<8)|(key[19]),
(key[20]<<24)|(key[21]<<16)|(key[22]<<8)|(key[23]),
(key[24]<<24)|(key[25]<<16)|(key[26]<<8)|(key[27]),
(key[28]<<24)|(key[29]<<16)|(key[30]<<8)|(key[31]),
(key[32]<<24)|(key[33]<<16)|(key[34]<<8)|(key[35]),
(key[36]<<24)|(key[37]<<16)|(key[38]<<8)|(key[39]),
(key[40]<<24)|(key[41]<<16)|(key[42]<<8)|(key[43]),
(key[44]<<24)|(key[45]<<16)|(key[46]<<8)|(key[47]),
(key[48]<<24)|(key[49]<<16)|(key[50]<<8)|(key[51]),
(key[52]<<24)|(key[53]<<16)|(key[54]<<8)|(key[55]),
(key[56]<<24)|(key[57]<<16)|(key[58]<<8)|(key[59]),
(key[60]<<24)|(key[61]<<16)|(key[62]<<8)|(key[63])
);
}
else {
this.hash.asm.hmac_reset();
}
var verify = options.verify;
if ( verify !== undefined ) {
_hmac_init_verify.call( this, verify );
}
else {
this.verify = null;
}
return this;
}
function hmac_sha1_finish () {
if ( this.key === null )
throw new IllegalStateError("no key is associated with the instance");
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
var hash = this.hash,
asm = this.hash.asm,
heap = this.hash.heap;
asm.hmac_finish( hash.pos, hash.len, 0 );
var verify = this.verify;
var result = new Uint8Array(_sha1_hash_size);
result.set( heap.subarray( 0, _sha1_hash_size ) );
if ( verify ) {
if ( verify.length === result.length ) {
var diff = 0;
for ( var i = 0; i < verify.length; i++ ) {
diff |= ( verify[i] ^ result[i] );
}
this.result = !diff;
} else {
this.result = false;
}
}
else {
this.result = result;
}
return this;
}
hmac_sha1_constructor.BLOCK_SIZE = sha1_constructor.BLOCK_SIZE;
hmac_sha1_constructor.HMAC_SIZE = sha1_constructor.HASH_SIZE;
var hmac_sha1_prototype = hmac_sha1_constructor.prototype;
hmac_sha1_prototype.reset = hmac_sha1_reset;
hmac_sha1_prototype.process = hmac_process;
hmac_sha1_prototype.finish = hmac_sha1_finish;
var hmac_sha1_instance = null;
function get_hmac_sha1_instance () {
if ( hmac_sha1_instance === null ) hmac_sha1_instance = new hmac_sha1_constructor();
return hmac_sha1_instance;
}
/**
* HMAC-SHA1 exports
*/
function hmac_sha1_bytes (data, password ) {
if ( data === undefined ) throw new SyntaxError("data required");
if ( password === undefined ) throw new SyntaxError("password required");
return get_hmac_sha1_instance().reset( { password: password } ).process(data).finish().result;
}
function hmac_sha1_hex ( data, password ) {
var result = hmac_sha1_bytes( data, password );
return bytes_to_hex(result);
}
function hmac_sha1_base64 ( data, password ) {
var result = hmac_sha1_bytes( data, password );
return bytes_to_base64(result);
}
var HMAC_SHA1 = hmac_sha1_constructor;
HMAC_SHA1.bytes = hmac_sha1_bytes;
HMAC_SHA1.hex = hmac_sha1_hex;
HMAC_SHA1.base64 = hmac_sha1_base64;
function hmac_sha256_constructor (options ) {
options = options || {};
if ( !( options.hash instanceof sha256_constructor ) )
options.hash = get_sha256_instance();
hmac_constructor.call( this, options );
return this;
}
function hmac_sha256_reset ( options ) {
options = options || {};
this.result = null;
this.hash.reset();
var password = options.password;
if ( password !== undefined ) {
if ( is_string(password) )
password = string_to_bytes(password);
var key = this.key = _hmac_key( this.hash, password );
this.hash.reset().asm.hmac_init(
(key[0]<<24)|(key[1]<<16)|(key[2]<<8)|(key[3]),
(key[4]<<24)|(key[5]<<16)|(key[6]<<8)|(key[7]),
(key[8]<<24)|(key[9]<<16)|(key[10]<<8)|(key[11]),
(key[12]<<24)|(key[13]<<16)|(key[14]<<8)|(key[15]),
(key[16]<<24)|(key[17]<<16)|(key[18]<<8)|(key[19]),
(key[20]<<24)|(key[21]<<16)|(key[22]<<8)|(key[23]),
(key[24]<<24)|(key[25]<<16)|(key[26]<<8)|(key[27]),
(key[28]<<24)|(key[29]<<16)|(key[30]<<8)|(key[31]),
(key[32]<<24)|(key[33]<<16)|(key[34]<<8)|(key[35]),
(key[36]<<24)|(key[37]<<16)|(key[38]<<8)|(key[39]),
(key[40]<<24)|(key[41]<<16)|(key[42]<<8)|(key[43]),
(key[44]<<24)|(key[45]<<16)|(key[46]<<8)|(key[47]),
(key[48]<<24)|(key[49]<<16)|(key[50]<<8)|(key[51]),
(key[52]<<24)|(key[53]<<16)|(key[54]<<8)|(key[55]),
(key[56]<<24)|(key[57]<<16)|(key[58]<<8)|(key[59]),
(key[60]<<24)|(key[61]<<16)|(key[62]<<8)|(key[63])
);
}
else {
this.hash.asm.hmac_reset();
}
var verify = options.verify;
if ( verify !== undefined ) {
_hmac_init_verify.call( this, verify );
}
else {
this.verify = null;
}
return this;
}
function hmac_sha256_finish () {
if ( this.key === null )
throw new IllegalStateError("no key is associated with the instance");
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
var hash = this.hash,
asm = this.hash.asm,
heap = this.hash.heap;
asm.hmac_finish( hash.pos, hash.len, 0 );
var verify = this.verify;
var result = new Uint8Array(_sha256_hash_size);
result.set( heap.subarray( 0, _sha256_hash_size ) );
if ( verify ) {
if ( verify.length === result.length ) {
var diff = 0;
for ( var i = 0; i < verify.length; i++ ) {
diff |= ( verify[i] ^ result[i] );
}
this.result = !diff;
} else {
this.result = false;
}
}
else {
this.result = result;
}
return this;
}
hmac_sha256_constructor.BLOCK_SIZE = sha256_constructor.BLOCK_SIZE;
hmac_sha256_constructor.HMAC_SIZE = sha256_constructor.HASH_SIZE;
var hmac_sha256_prototype = hmac_sha256_constructor.prototype;
hmac_sha256_prototype.reset = hmac_sha256_reset;
hmac_sha256_prototype.process = hmac_process;
hmac_sha256_prototype.finish = hmac_sha256_finish;
var hmac_sha256_instance = null;
function get_hmac_sha256_instance () {
if ( hmac_sha256_instance === null ) hmac_sha256_instance = new hmac_sha256_constructor();
return hmac_sha256_instance;
}
/**
* HMAC-SHA256 exports
*/
function hmac_sha256_bytes (data, password ) {
if ( data === undefined ) throw new SyntaxError("data required");
if ( password === undefined ) throw new SyntaxError("password required");
return get_hmac_sha256_instance().reset( { password: password } ).process(data).finish().result;
}
function hmac_sha256_hex ( data, password ) {
var result = hmac_sha256_bytes( data, password );
return bytes_to_hex(result);
}
function hmac_sha256_base64 ( data, password ) {
var result = hmac_sha256_bytes( data, password );
return bytes_to_base64(result);
}
var HMAC_SHA256 = hmac_sha256_constructor;
HMAC_SHA256.bytes = hmac_sha256_bytes;
HMAC_SHA256.hex = hmac_sha256_hex;
HMAC_SHA256.base64 = hmac_sha256_base64;
function pbkdf2_constructor (options ) {
options = options || {};
if ( !options.hmac )
throw new SyntaxError("option 'hmac' is required");
if ( !options.hmac.HMAC_SIZE )
throw new SyntaxError("option 'hmac' supplied doesn't seem to be a valid HMAC function");
this.hmac = options.hmac;
this.count = options.count || 4096;
this.length = options.length || this.hmac.HMAC_SIZE;
this.result = null;
var password = options.password;
if ( password || is_string(password) )
this.reset(options);
return this;
}
function pbkdf2_reset ( options ) {
this.result = null;
this.hmac.reset(options);
return this;
}
function pbkdf2_generate ( salt, count, length ) {
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
if ( !salt && !is_string(salt) )
throw new IllegalArgumentError("bad 'salt' value");
count = count || this.count;
length = length || this.length;
this.result = new Uint8Array(length);
var blocks = Math.ceil( length / this.hmac.HMAC_SIZE );
for ( var i = 1; i <= blocks; ++i ) {
var j = ( i - 1 ) * this.hmac.HMAC_SIZE;
var l = ( i < blocks ? 0 : length % this.hmac.HMAC_SIZE ) || this.hmac.HMAC_SIZE;
var tmp = new Uint8Array( this.hmac.reset().process(salt).process( new Uint8Array([ i>>>24&0xff, i>>>16&0xff, i>>>8&0xff, i&0xff ]) ).finish().result );
this.result.set( tmp.subarray( 0, l ), j );
for ( var k = 1; k < count; ++k ) {
tmp = new Uint8Array( this.hmac.reset().process(tmp).finish().result );
for ( var r = 0; r < l; ++r ) this.result[j+r] ^= tmp[r];
}
}
return this;
}
// methods
var pbkdf2_prototype = pbkdf2_constructor.prototype;
pbkdf2_prototype.reset = pbkdf2_reset;
pbkdf2_prototype.generate = pbkdf2_generate;
function pbkdf2_hmac_sha1_constructor (options ) {
options = options || {};
if ( !( options.hmac instanceof hmac_sha1_constructor ) )
options.hmac = get_hmac_sha1_instance();
pbkdf2_constructor.call( this, options );
return this;
}
function pbkdf2_hmac_sha1_generate ( salt, count, length ) {
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
if ( !salt && !is_string(salt) )
throw new IllegalArgumentError("bad 'salt' value");
count = count || this.count;
length = length || this.length;
this.result = new Uint8Array(length);
var blocks = Math.ceil( length / this.hmac.HMAC_SIZE );
for ( var i = 1; i <= blocks; ++i ) {
var j = ( i - 1 ) * this.hmac.HMAC_SIZE;
var l = ( i < blocks ? 0 : length % this.hmac.HMAC_SIZE ) || this.hmac.HMAC_SIZE;
this.hmac.reset().process(salt);
this.hmac.hash.asm.pbkdf2_generate_block( this.hmac.hash.pos, this.hmac.hash.len, i, count, 0 );
this.result.set( this.hmac.hash.heap.subarray( 0, l ), j );
}
return this;
}
var pbkdf2_hmac_sha1_prototype = pbkdf2_hmac_sha1_constructor.prototype;
pbkdf2_hmac_sha1_prototype.reset = pbkdf2_reset;
pbkdf2_hmac_sha1_prototype.generate = pbkdf2_hmac_sha1_generate;
var pbkdf2_hmac_sha1_instance = null;
function get_pbkdf2_hmac_sha1_instance () {
if ( pbkdf2_hmac_sha1_instance === null ) pbkdf2_hmac_sha1_instance = new pbkdf2_hmac_sha1_constructor();
return pbkdf2_hmac_sha1_instance;
}
/**
* PBKDF2-HMAC-SHA1 exports
*/
function pbkdf2_hmac_sha1_bytes (password, salt, iterations, dklen ) {
if ( password === undefined ) throw new SyntaxError("password required");
if ( salt === undefined ) throw new SyntaxError("salt required");
return get_pbkdf2_hmac_sha1_instance().reset( { password: password } ).generate( salt, iterations, dklen ).result;
}
function pbkdf2_hmac_sha1_hex ( password, salt, iterations, dklen ) {
var result = pbkdf2_hmac_sha1_bytes( password, salt, iterations, dklen );
return bytes_to_hex(result);
}
function pbkdf2_hmac_sha1_base64 ( password, salt, iterations, dklen ) {
var result = pbkdf2_hmac_sha1_bytes( password, salt, iterations, dklen );
return bytes_to_base64(result);
}
var PBKDF2 = {
bytes: pbkdf2_hmac_sha1_bytes,
hex: pbkdf2_hmac_sha1_hex,
base64: pbkdf2_hmac_sha1_base64
};
var PBKDF2_HMAC_SHA1 = {
bytes: pbkdf2_hmac_sha1_bytes,
hex: pbkdf2_hmac_sha1_hex,
base64: pbkdf2_hmac_sha1_base64
};
function pbkdf2_hmac_sha256_constructor ( options ) {
options = options || {};
if ( !( options.hmac instanceof hmac_sha256_constructor ) )
options.hmac = get_hmac_sha256_instance();
pbkdf2_constructor.call( this, options );
return this;
}
function pbkdf2_hmac_sha256_generate ( salt, count, length ) {
if ( this.result !== null )
throw new IllegalStateError("state must be reset before processing new data");
if ( !salt && !is_string(salt) )
throw new IllegalArgumentError("bad 'salt' value");
count = count || this.count;
length = length || this.length;
this.result = new Uint8Array(length);
var blocks = Math.ceil( length / this.hmac.HMAC_SIZE );
for ( var i = 1; i <= blocks; ++i ) {
var j = ( i - 1 ) * this.hmac.HMAC_SIZE;
var l = ( i < blocks ? 0 : length % this.hmac.HMAC_SIZE ) || this.hmac.HMAC_SIZE;
this.hmac.reset().process(salt);
this.hmac.hash.asm.pbkdf2_generate_block( this.hmac.hash.pos, this.hmac.hash.len, i, count, 0 );
this.result.set( this.hmac.hash.heap.subarray( 0, l ), j );
}
return this;
}
var pbkdf2_hmac_sha256_prototype = pbkdf2_hmac_sha256_constructor.prototype;
pbkdf2_hmac_sha256_prototype.reset = pbkdf2_reset;
pbkdf2_hmac_sha256_prototype.generate = pbkdf2_hmac_sha256_generate;
var pbkdf2_hmac_sha256_instance = null;
function get_pbkdf2_hmac_sha256_instance () {
if ( pbkdf2_hmac_sha256_instance === null ) pbkdf2_hmac_sha256_instance = new pbkdf2_hmac_sha256_constructor();
return pbkdf2_hmac_sha256_instance;
}
/**
* PBKDF2-HMAC-SHA256 exports
*/
function pbkdf2_hmac_sha256_bytes (password, salt, iterations, dklen ) {
if ( password === undefined ) throw new SyntaxError("password required");
if ( salt === undefined ) throw new SyntaxError("salt required");
return get_pbkdf2_hmac_sha256_instance().reset( { password: password } ).generate( salt, iterations, dklen ).result;
}
function pbkdf2_hmac_sha256_hex ( password, salt, iterations, dklen ) {
var result = pbkdf2_hmac_sha256_bytes( password, salt, iterations, dklen );
return bytes_to_hex(result);
}
function pbkdf2_hmac_sha256_base64 ( password, salt, iterations, dklen ) {
var result = pbkdf2_hmac_sha256_bytes( password, salt, iterations, dklen );
return bytes_to_base64(result);
}
var PBKDF2_HMAC_SHA256 = {
bytes: pbkdf2_hmac_sha256_bytes,
hex: pbkdf2_hmac_sha256_hex,
base64: pbkdf2_hmac_sha256_base64
};
/* ----------------------------------------------------------------------
* Copyright (c) 2014 Artem S Vybornov
*
* Copyright (c) 2012 Yves-Marie K. Rinquin
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* ----------------------------------------------------------------------
*
* ISAAC is a cryptographically secure pseudo-random number generator
* (or CSPRNG for short) designed by Robert J. Jenkins Jr. in 1996 and
* based on RC4. It is designed for speed and security.
*
* ISAAC's informations & analysis:
* http://burtleburtle.net/bob/rand/isaac.html
* ISAAC's implementation details:
* http://burtleburtle.net/bob/rand/isaacafa.html
*
* ISAAC succesfully passed TestU01
*/
var ISAAC = ( function () {
var m = new Uint32Array(256), // internal memory
r = new Uint32Array(256), // result array
acc = 0, // accumulator
brs = 0, // last result
cnt = 0, // counter
gnt = 0; // generation counter
/* private: randinit function, same as ISAAC reference implementation */
function randinit() {
var a, b, c, d, e, f, g, h;
/* private mixing function */
function mix () {
a ^= b << 11; d = (d + a)|0; b = (b + c)|0;
b ^= c >>> 2; e = (e + b)|0; c = (c + d)|0;
c ^= d << 8; f = (f + c)|0; d = (d + e)|0;
d ^= e >>> 16; g = (g + d)|0; e = (e + f)|0;
e ^= f << 10; h = (h + e)|0; f = (f + g)|0;
f ^= g >>> 4; a = (a + f)|0; g = (g + h)|0;
g ^= h << 8; b = (b + g)|0; h = (h + a)|0;
h ^= a >>> 9; c = (c + h)|0; a = (a + b)|0;
}
acc = brs = cnt = 0;
// the golden ratio
a = b = c = d = e = f = g = h = 0x9e3779b9;
// scramble it
for ( var i = 0; i < 4; i++ )
mix();
// mix it and combine with the internal state
for ( var i = 0; i < 256; i += 8 ) {
a = (a + r[i|0])|0; b = (b + r[i|1])|0;
c = (c + r[i|2])|0; d = (d + r[i|3])|0;
e = (e + r[i|4])|0; f = (f + r[i|5])|0;
g = (g + r[i|6])|0; h = (h + r[i|7])|0;
mix();
m.set([a, b, c, d, e, f, g, h], i);
}
// mix it again
for ( var i = 0; i < 256; i += 8 ) {
a = (a + m[i|0])|0; b = (b + m[i|1])|0;
c = (c + m[i|2])|0; d = (d + m[i|3])|0;
e = (e + m[i|4])|0; f = (f + m[i|5])|0;
g = (g + m[i|6])|0; h = (h + m[i|7])|0;
mix();
m.set([a, b, c, d, e, f, g, h], i);
}
// fill in the first set of results
prng(1), gnt = 256;
}
/* public: seeding function */
function seed ( s ) {
var i, j, k, n, l;
if ( !is_typed_array(s) ) {
if ( is_number(s) ) {
n = new FloatArray(1), n[0] = s;
s = new Uint8Array(n.buffer);
}
else if ( is_string(s) ) {
s = string_to_bytes(s);
}
else if ( is_buffer(s) ) {
s = new Uint8Array(s);
}
else {
throw new TypeError("bad seed type");
}
}
else {
s = new Uint8Array(s.buffer);
}
// preprocess the seed
l = s.length;
for ( j = 0; j < l; j += 1024 )
{
// xor each chunk of 1024 bytes with r, for randinit() to mix in
for ( k = j, i = 0; ( i < 1024 ) && ( k < l ); k = j | (++i) ) {
r[i >> 2] ^= ( s[k] << ( (i & 3) << 3 ) );
}
randinit();
}
}
/* public: isaac generator, n = number of run */
function prng ( n ) {
n = n || 1;
var i, x, y;
while ( n-- ) {
cnt = (cnt + 1)|0;
brs = (brs + cnt)|0;
for ( i = 0; i < 256; i += 4 ) {
acc ^= acc << 13;
acc = m[(i + 128) & 0xff] + acc | 0; x = m[i|0];
m[i|0] = y = m[(x>>>2) & 0xff] + ( acc + brs | 0 ) | 0;
r[i|0] = brs = m[(y>>>10) & 0xff] + x | 0;
acc ^= acc >>> 6;
acc = m[(i + 129) & 0xff] + acc | 0; x = m[i|1];
m[i|1] = y = m[(x >>> 2) & 0xff] + ( acc + brs | 0 ) | 0;
r[i|1] = brs = m[(y >>> 10) & 0xff] + x | 0;
acc ^= acc << 2;
acc = m[(i + 130) & 0xff] + acc | 0; x = m[i|2];
m[i|2] = y = m[(x >>> 2) & 0xff] + ( acc + brs | 0 ) | 0;
r[i|2] = brs = m[(y >>> 10) & 0xff] + x | 0;
acc ^= acc >>> 16;
acc = m[(i + 131) & 0xff] + acc | 0; x = m[i|3];
m[i|3] = y = m[(x >>> 2) & 0xff] + (acc + brs | 0 ) | 0;
r[i|3] = brs = m[(y >>> 10) & 0xff] + x | 0;
}
}
}
/* public: return a random number */
function rand() {
if ( !gnt-- )
prng(1), gnt = 255;
return r[gnt];
}
/* return class object */
return {
'seed': seed,
'prng': prng,
'rand': rand
};
})();
var _global_console = typeof console !== "undefined" ? console : undefined;
var _global_date_now = Date.now;
var _global_math_random = Math.random;
var _global_performance = typeof performance !== "undefined" ? performance : undefined;
var _global_crypto = typeof crypto !== "undefined" ? crypto : (typeof msCrypto !== "undefined" ? msCrypto : undefined);
var _global_crypto_getRandomValues;
if ( _global_crypto !== undefined )
_global_crypto_getRandomValues = _global_crypto.getRandomValues;
var _isaac_rand = ISAAC.rand;
var _isaac_seed = ISAAC.seed;
var _isaac_counter = 0;
var _isaac_weak_seeded = false;
var _isaac_seeded = false;
var _random_estimated_entropy = 0;
var _random_required_entropy = 256;
var _random_warn_callstacks = {};
exports._random_skip_system_rng_warning = false;
exports._random_allow_weak = false;
var _hires_now;
if ( _global_performance !== undefined ) {
_hires_now = function () { return 1000 * _global_performance.now() | 0 };
}
else {
var _hires_epoch = 1000 * _global_date_now() | 0;
_hires_now = function () { return 1000 * _global_date_now() - _hires_epoch | 0 };
}
/**
* weak_seed
*
* Seeds RNG with native `crypto.getRandomValues` output or with high-resolution
* time and single `Math.random()` value, and various other sources.
*
* We estimate this may give at least ~50 bits of unpredictableness,
* but this has not been analysed thoroughly or precisely.
*/
function Random_weak_seed () {
if ( _global_crypto !== undefined ) {
buffer = new Uint8Array(32);
_global_crypto_getRandomValues.call( _global_crypto, buffer );
_isaac_seed(buffer);
}
else {
// Some clarification about brute-force attack cost:
// - entire bitcoin network operates at ~10^16 hash guesses per second;
// - each PBKDF2 iteration requires the same number of hashing operations as bitcoin nonce guess;
// - attacker having such a hashing power is able to break worst-case 50 bits of the randomness in ~3 hours;
// Sounds sad though attacker having such a hashing power more likely would prefer to mine bitcoins.
var buffer = new FloatArray(3),
i, t;
buffer[0] = _global_math_random();
buffer[1] = _global_date_now();
buffer[2] = _hires_now();
buffer = new Uint8Array(buffer.buffer);
var salt = '';
if ( typeof location !== "undefined" ) {
salt += location.href;
}
else if ( typeof process !== "undefined" ) {
salt += process.pid + process.title;
}
var pbkdf2 = get_pbkdf2_hmac_sha256_instance();
for ( i = 0; i < 100; i++ ) {
buffer = pbkdf2.reset( { password: buffer } ).generate( salt, 1000, 32 ).result;
t = _hires_now();
buffer[0] ^= t >>> 24, buffer[1] ^= t >>> 16, buffer[2] ^= t >>> 8, buffer[3] ^= t;
}
_isaac_seed(buffer);
}
_isaac_counter = 0;
_isaac_weak_seeded = true;
}
/**
* seed
*
* Seeds PRNG with supplied random values if these values have enough entropy.
*
* A false return value means the RNG is currently insecure; however a true
* return value does not mean it is necessarily secure (depending on how you
* collected the seed) though asmCrypto will be forced to assume this.
*
* The input buffer will be zeroed to discourage reuse. You should not copy it
* or use it anywhere else before passing it into this function.
*
* **DISCLAIMER!** Seeding with a poor values is an easiest way shoot your legs, so
* do not seed until you're know what entropy is and how to obtail high-quality random values,
* **DO NOT SEED WITH CONSTANT VALUE! YOU'LL GET NO RANDOMNESS FROM CONSTANT!**
*/
function Random_seed ( seed ) {
if ( !is_buffer(seed) && !is_typed_array(seed) )
throw new TypeError("bad seed type");
var bpos = seed.byteOffset || 0,
blen = seed.byteLength || seed.length,
buff = new Uint8Array( ( seed.buffer || seed ), bpos, blen );
_isaac_seed(buff);
_isaac_counter = 0;
// don't let the user use these bytes again
var nonzero = 0;
for ( var i = 0; i < buff.length; i++ ) {
nonzero |= buff[i];
buff[i] = 0;
}
if ( nonzero !== 0 ) {
// TODO we could make a better estimate, but half-length is a prudent
// simple measure that seems unlikely to over-estimate
_random_estimated_entropy += 4 * blen;
}
_isaac_seeded = ( _random_estimated_entropy >= _random_required_entropy );
return _isaac_seeded;
}
/**
* getValues
*
* Populates the buffer with cryptographically secure random values. These are
* calculated using `crypto.getRandomValues` if it is available, as well as our
* own ISAAC PRNG implementation.
*
* If the former is not available (older browsers such as IE10 [1]), then the
* latter *must* be seeded using `Random.seed`, unless `asmCrypto.random.allowWeak` is true.
*
* *We assume the system RNG is strong*; if you cannot afford this risk, then
* you should also seed ISAAC using `Random.seed`. This is advisable for very
* important situations, such as generation of long-term secrets. See also [2].
*
* [1] https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
* [2] https://en.wikipedia.org/wiki/Dual_EC_DRBG
*
* In all cases, we opportunistically seed using various arbitrary sources
* such as high-resolution time and one single value from the insecure
* Math.random(); however this is not reliable as a strong security measure.
*/
function Random_getValues ( buffer ) {
// opportunistically seed ISAAC with a weak seed; this hopefully makes an
// attack harder in the case where the system RNG is weak *and* we haven't
// seeded ISAAC. but don't make any guarantees to the user about this.
if ( !_isaac_weak_seeded )
Random_weak_seed();
// if we have no strong sources then the RNG is weak, handle it
if ( !_isaac_seeded && _global_crypto === undefined ) {
if ( !exports._random_allow_weak )
throw new SecurityError("No strong PRNGs available. Use asmCrypto.random.seed().");
if ( _global_console !== undefined )
_global_console.error("No strong PRNGs available; your security is greatly lowered. Use asmCrypto.random.seed().");
}
// separate warning about assuming system RNG strong
if ( !exports._random_skip_system_rng_warning && !_isaac_seeded && _global_crypto !== undefined && _global_console !== undefined ) {
// Hacky way to get call stack
var s = new Error().stack;
_random_warn_callstacks[s] |= 0;
if ( !_random_warn_callstacks[s]++ )
_global_console.warn("asmCrypto PRNG not seeded; your security relies on your system PRNG. If this is not acceptable, use asmCrypto.random.seed().");
}
// proceed to get random values
if ( !is_buffer(buffer) && !is_typed_array(buffer) )
throw new TypeError("unexpected buffer type");
var bpos = buffer.byteOffset || 0,
blen = buffer.byteLength || buffer.length,
bytes = new Uint8Array( ( buffer.buffer || buffer ), bpos, blen ),
i, r;
// apply system rng
if ( _global_crypto !== undefined )
_global_crypto_getRandomValues.call( _global_crypto, bytes );
// apply isaac rng
for ( i = 0; i < blen; i++ ) {
if ( (i & 3) === 0 ) {
if ( _isaac_counter >= 0x10000000000 ) Random_weak_seed();
r = _isaac_rand();
_isaac_counter++;
}
bytes[i] ^= r;
r >>>= 8;
}
return buffer;
}
/**
* getNumber
*
* A drop-in `Math.random` replacement.
* Intended for prevention of random material leakage out of the user's host.
*/
function Random_getNumber () {
if ( !_isaac_weak_seeded || _isaac_counter >= 0x10000000000 )
Random_weak_seed();
var n = ( 0x100000 * _isaac_rand() + ( _isaac_rand() >>> 12 ) ) / 0x10000000000000;
_isaac_counter += 2;
return n;
}
Object.defineProperty( Random_getNumber, 'allowWeak', {
get: function () { return exports._random_allow_weak; },
set: function ( a ) { exports._random_allow_weak = a; }
});
Object.defineProperty( Random_getNumber, 'skipSystemRNGWarning', {
get: function () { return exports._random_skip_system_rng_warning; },
set: function ( w ) { exports._random_skip_system_rng_warning = w; }
});
Object.defineProperty( Random_getValues, 'allowWeak', {
get: function () { return exports._random_allow_weak; },
set: function ( a ) { exports._random_allow_weak = a; }
});
Object.defineProperty( Random_getValues, 'skipSystemRNGWarning', {
get: function () { return exports._random_skip_system_rng_warning; },
set: function ( w ) { exports._random_skip_system_rng_warning = w; }
});
Random_getNumber.seed = Random_seed;
Random_getValues.seed = Random_seed;
/**
* Integers are represented as little endian array of 32-bit limbs.
* Limbs number is a power of 2 and a multiple of 8 (256 bits).
* Negative values use two's complement representation.
*/
function bigint_asm ( stdlib, foreign, buffer ) {
var SP = 0;
var HEAP32 = new stdlib.Uint32Array(buffer);
var imul = stdlib.Math.imul;
/**
* Simple stack memory allocator
*
* Methods:
* sreset
* salloc
* sfree
*/
function sreset ( p ) {
p = p|0;
SP = p = (p + 31) & -32;
return p|0;
}
function salloc ( l ) {
l = l|0;
var p = 0; p = SP;
SP = p + ((l + 31) & -32)|0;
return p|0;
}
function sfree ( l ) {
l = l|0;
SP = SP - ((l + 31) & -32)|0;
}
/**
* Utility functions:
* cp
* z
*/
function cp ( l, A, B ) {
l = l|0;
A = A|0;
B = B|0;
var i = 0;
if ( (A|0) > (B|0) ) {
for ( ; (i|0) < (l|0); i = (i+4)|0 ) {
HEAP32[(B+i)>>2] = HEAP32[(A+i)>>2];
}
}
else {
for ( i = (l-4)|0; (i|0) >= 0; i = (i-4)|0 ) {
HEAP32[(B+i)>>2] = HEAP32[(A+i)>>2];
}
}
}
function z ( l, z, A ) {
l = l|0;
z = z|0;
A = A|0;
var i = 0;
for ( ; (i|0) < (l|0); i = (i+4)|0 ) {
HEAP32[(A+i)>>2] = z;
}
}
/**
* Negate the argument
*
* Perform two's complement transformation:
*
* -A = ~A + 1
*
* @param A offset of the argment being negated, 32-byte aligned
* @param lA length of the argument, multiple of 32
*
* @param R offset where to place the result to, 32-byte aligned
* @param lR length to truncate the result to, multiple of 32
*/
function neg ( A, lA, R, lR ) {
A = A|0;
lA = lA|0;
R = R|0;
lR = lR|0;
var a = 0, c = 0, t = 0, r = 0, i = 0;
if ( (lR|0) <= 0 )
lR = lA;
if ( (lR|0) < (lA|0) )
lA = lR;
c = 1;
for ( ; (i|0) < (lA|0); i = (i+4)|0 ) {
a = ~HEAP32[(A+i)>>2];
t = (a & 0xffff) + c|0;
r = (a >>> 16) + (t >>> 16)|0;
HEAP32[(R+i)>>2] = (r << 16) | (t & 0xffff);
c = r >>> 16;
}
for ( ; (i|0) < (lR|0); i = (i+4)|0 ) {
HEAP32[(R+i)>>2] = (c-1)|0;
}
return c|0;
}
function cmp ( A, lA, B, lB ) {
A = A|0;
lA = lA|0;
B = B|0;
lB = lB|0;
var a = 0, b = 0, i = 0;
if ( (lA|0) > (lB|0) ) {
for ( i = (lA-4)|0; (i|0) >= (lB|0); i = (i-4)|0 ) {
if ( HEAP32[(A+i)>>2]|0 ) return 1;
}
}
else {
for ( i = (lB-4)|0; (i|0) >= (lA|0); i = (i-4)|0 ) {
if ( HEAP32[(B+i)>>2]|0 ) return -1;
}
}
for ( ; (i|0) >= 0; i = (i-4)|0 ) {
a = HEAP32[(A+i)>>2]|0, b = HEAP32[(B+i)>>2]|0;
if ( (a>>>0) < (b>>>0) ) return -1;
if ( (a>>>0) > (b>>>0) ) return 1;
}
return 0;
}
/**
* Test the argument
*
* Same as `cmp` with zero.
*/
function tst ( A, lA ) {
A = A|0;
lA = lA|0;
var i = 0;
for ( i = (lA-4)|0; (i|0) >= 0; i = (i-4)|0 ) {
if ( HEAP32[(A+i)>>2]|0 ) return (i+4)|0;
}
return 0;
}
/**
* Conventional addition
*
* @param A offset of the first argument, 32-byte aligned
* @param lA length of the first argument, multiple of 32
*
* @param B offset of the second argument, 32-bit aligned
* @param lB length of the second argument, multiple of 32
*
* @param R offset where to place the result to, 32-byte aligned
* @param lR length to truncate the result to, multiple of 32
*/
function add ( A, lA, B, lB, R, lR ) {
A = A|0;
lA = lA|0;
B = B|0;
lB = lB|0;
R = R|0;
lR = lR|0;
var a = 0, b = 0, c = 0, t = 0, r = 0, i = 0;
if ( (lA|0) < (lB|0) ) {
t = A, A = B, B = t;
t = lA, lA = lB, lB = t;
}
if ( (lR|0) <= 0 )
lR = lA+4|0;
if ( (lR|0) < (lB|0) )
lA = lB = lR;
for ( ; (i|0) < (lB|0); i = (i+4)|0 ) {
a = HEAP32[(A+i)>>2]|0;
b = HEAP32[(B+i)>>2]|0;
t = ( (a & 0xffff) + (b & 0xffff)|0 ) + c|0;
r = ( (a >>> 16) + (b >>> 16)|0 ) + (t >>> 16)|0;
HEAP32[(R+i)>>2] = (t & 0xffff) | (r << 16);
c = r >>> 16;
}
for ( ; (i|0) < (lA|0); i = (i+4)|0 ) {
a = HEAP32[(A+i)>>2]|0;
t = (a & 0xffff) + c|0;
r = (a >>> 16) + (t >>> 16)|0;
HEAP32[(R+i)>>2] = (t & 0xffff) | (r << 16);
c = r >>> 16;
}
for ( ; (i|0) < (lR|0); i = (i+4)|0 ) {
HEAP32[(R+i)>>2] = c|0;
c = 0;
}
return c|0;
}
/**
* Conventional subtraction
*
* @param A offset of the first argument, 32-byte aligned
* @param lA length of the first argument, multiple of 32
*
* @param B offset of the second argument, 32-bit aligned
* @param lB length of the second argument, multiple of 32
*
* @param R offset where to place the result to, 32-byte aligned
* @param lR length to truncate the result to, multiple of 32
*/
function sub ( A, lA, B, lB, R, lR ) {
A = A|0;
lA = lA|0;
B = B|0;
lB = lB|0;
R = R|0;
lR = lR|0;
var a = 0, b = 0, c = 0, t = 0, r = 0, i = 0;
if ( (lR|0) <= 0 )
lR = (lA|0) > (lB|0) ? lA+4|0 : lB+4|0;
if ( (lR|0) < (lA|0) )
lA = lR;
if ( (lR|0) < (lB|0) )
lB = lR;
if ( (lA|0) < (lB|0) ) {
for ( ; (i|0) < (lA|0); i = (i+4)|0 ) {
a = HEAP32[(A+i)>>2]|0;
b = HEAP32[(B+i)>>2]|0;
t = ( (a & 0xffff) - (b & 0xffff)|0 ) + c|0;
r = ( (a >>> 16) - (b >>> 16)|0 ) + (t >> 16)|0;
HEAP32[(R+i)>>2] = (t & 0xffff) | (r << 16);
c = r >> 16;
}
for ( ; (i|0) < (lB|0); i = (i+4)|0 ) {
b = HEAP32[(B+i)>>2]|0;
t = c - (b & 0xffff)|0;
r = (t >> 16) - (b >>> 16)|0;
HEAP32[(R+i)>>2] = (t & 0xffff) | (r << 16);
c = r >> 16;
}
}
else {
for ( ; (i|0) < (lB|0); i = (i+4)|0 ) {
a = HEAP32[(A+i)>>2]|0;
b = HEAP32[(B+i)>>2]|0;
t = ( (a & 0xffff) - (b & 0xffff)|0 ) + c|0;
r = ( (a >>> 16) - (b >>> 16)|0 ) + (t >> 16)|0;
HEAP32[(R+i)>>2] = (t & 0xffff) | (r << 16);
c = r >> 16;
}
for ( ; (i|0) < (lA|0); i = (i+4)|0 ) {
a = HEAP32[(A+i)>>2]|0;
t = (a & 0xffff) + c|0;
r = (a >>> 16) + (t >> 16)|0;
HEAP32[(R+i)>>2] = (t & 0xffff) | (r << 16);
c = r >> 16;
}
}
for ( ; (i|0) < (lR|0); i = (i+4)|0 ) {
HEAP32[(R+i)>>2] = c|0;
}
return c|0;
}
/**
* Conventional multiplication
*
* TODO implement Karatsuba algorithm for large multiplicands
*
* @param A offset of the first argument, 32-byte aligned
* @param lA length of the first argument, multiple of 32
*
* @param B offset of the second argument, 32-byte aligned
* @param lB length of the second argument, multiple of 32
*
* @param R offset where to place the result to, 32-byte aligned
* @param lR length to truncate the result to, multiple of 32
*/
function mul ( A, lA, B, lB, R, lR ) {
A = A|0;
lA = lA|0;
B = B|0;
lB = lB|0;
R = R|0;
lR = lR|0;
var al0 = 0, al1 = 0, al2 = 0, al3 = 0, al4 = 0, al5 = 0, al6 = 0, al7 = 0, ah0 = 0, ah1 = 0, ah2 = 0, ah3 = 0, ah4 = 0, ah5 = 0, ah6 = 0, ah7 = 0,
bl0 = 0, bl1 = 0, bl2 = 0, bl3 = 0, bl4 = 0, bl5 = 0, bl6 = 0, bl7 = 0, bh0 = 0, bh1 = 0, bh2 = 0, bh3 = 0, bh4 = 0, bh5 = 0, bh6 = 0, bh7 = 0,
r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0, r5 = 0, r6 = 0, r7 = 0, r8 = 0, r9 = 0, r10 = 0, r11 = 0, r12 = 0, r13 = 0, r14 = 0, r15 = 0,
u = 0, v = 0, w = 0, m = 0,
i = 0, Ai = 0, j = 0, Bj = 0, Rk = 0;
if ( (lA|0) > (lB|0) ) {
u = A, v = lA;
A = B, lA = lB;
B = u, lB = v;
}
m = (lA+lB)|0;
if ( ( (lR|0) > (m|0) ) | ( (lR|0) <= 0 ) )
lR = m;
if ( (lR|0) < (lA|0) )
lA = lR;
if ( (lR|0) < (lB|0) )
lB = lR;
for ( ; (i|0) < (lA|0); i = (i+32)|0 ) {
Ai = (A+i)|0;
ah0 = HEAP32[(Ai|0)>>2]|0, ah1 = HEAP32[(Ai|4)>>2]|0, ah2 = HEAP32[(Ai|8)>>2]|0, ah3 = HEAP32[(Ai|12)>>2]|0, ah4 = HEAP32[(Ai|16)>>2]|0, ah5 = HEAP32[(Ai|20)>>2]|0, ah6 = HEAP32[(Ai|24)>>2]|0, ah7 = HEAP32[(Ai|28)>>2]|0, al0 = ah0 & 0xffff, al1 = ah1 & 0xffff, al2 = ah2 & 0xffff, al3 = ah3 & 0xffff, al4 = ah4 & 0xffff, al5 = ah5 & 0xffff, al6 = ah6 & 0xffff, al7 = ah7 & 0xffff, ah0 = ah0 >>> 16, ah1 = ah1 >>> 16, ah2 = ah2 >>> 16, ah3 = ah3 >>> 16, ah4 = ah4 >>> 16, ah5 = ah5 >>> 16, ah6 = ah6 >>> 16, ah7 = ah7 >>> 16;
r8 = r9 = r10 = r11 = r12 = r13 = r14 = r15 = 0;
for ( j = 0; (j|0) < (lB|0); j = (j+32)|0 ) {
Bj = (B+j)|0;
Rk = (R+(i+j|0))|0;
bh0 = HEAP32[(Bj|0)>>2]|0, bh1 = HEAP32[(Bj|4)>>2]|0, bh2 = HEAP32[(Bj|8)>>2]|0, bh3 = HEAP32[(Bj|12)>>2]|0, bh4 = HEAP32[(Bj|16)>>2]|0, bh5 = HEAP32[(Bj|20)>>2]|0, bh6 = HEAP32[(Bj|24)>>2]|0, bh7 = HEAP32[(Bj|28)>>2]|0, bl0 = bh0 & 0xffff, bl1 = bh1 & 0xffff, bl2 = bh2 & 0xffff, bl3 = bh3 & 0xffff, bl4 = bh4 & 0xffff, bl5 = bh5 & 0xffff, bl6 = bh6 & 0xffff, bl7 = bh7 & 0xffff, bh0 = bh0 >>> 16, bh1 = bh1 >>> 16, bh2 = bh2 >>> 16, bh3 = bh3 >>> 16, bh4 = bh4 >>> 16, bh5 = bh5 >>> 16, bh6 = bh6 >>> 16, bh7 = bh7 >>> 16;
r0 = HEAP32[(Rk|0)>>2]|0, r1 = HEAP32[(Rk|4)>>2]|0, r2 = HEAP32[(Rk|8)>>2]|0, r3 = HEAP32[(Rk|12)>>2]|0, r4 = HEAP32[(Rk|16)>>2]|0, r5 = HEAP32[(Rk|20)>>2]|0, r6 = HEAP32[(Rk|24)>>2]|0, r7 = HEAP32[(Rk|28)>>2]|0;
u = ((imul(al0, bl0)|0) + (r8 & 0xffff)|0) + (r0 & 0xffff)|0;
v = ((imul(ah0, bl0)|0) + (r8 >>> 16)|0) + (r0 >>> 16)|0;
w = ((imul(al0, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r0 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl1)|0) + (m & 0xffff)|0) + (r1 & 0xffff)|0;
v = ((imul(ah0, bl1)|0) + (m >>> 16)|0) + (r1 >>> 16)|0;
w = ((imul(al0, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r1 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl2)|0) + (m & 0xffff)|0) + (r2 & 0xffff)|0;
v = ((imul(ah0, bl2)|0) + (m >>> 16)|0) + (r2 >>> 16)|0;
w = ((imul(al0, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl3)|0) + (m & 0xffff)|0) + (r3 & 0xffff)|0;
v = ((imul(ah0, bl3)|0) + (m >>> 16)|0) + (r3 >>> 16)|0;
w = ((imul(al0, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl4)|0) + (m & 0xffff)|0) + (r4 & 0xffff)|0;
v = ((imul(ah0, bl4)|0) + (m >>> 16)|0) + (r4 >>> 16)|0;
w = ((imul(al0, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl5)|0) + (m & 0xffff)|0) + (r5 & 0xffff)|0;
v = ((imul(ah0, bl5)|0) + (m >>> 16)|0) + (r5 >>> 16)|0;
w = ((imul(al0, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl6)|0) + (m & 0xffff)|0) + (r6 & 0xffff)|0;
v = ((imul(ah0, bl6)|0) + (m >>> 16)|0) + (r6 >>> 16)|0;
w = ((imul(al0, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl7)|0) + (m & 0xffff)|0) + (r7 & 0xffff)|0;
v = ((imul(ah0, bl7)|0) + (m >>> 16)|0) + (r7 >>> 16)|0;
w = ((imul(al0, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
r8 = m;
u = ((imul(al1, bl0)|0) + (r9 & 0xffff)|0) + (r1 & 0xffff)|0;
v = ((imul(ah1, bl0)|0) + (r9 >>> 16)|0) + (r1 >>> 16)|0;
w = ((imul(al1, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r1 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl1)|0) + (m & 0xffff)|0) + (r2 & 0xffff)|0;
v = ((imul(ah1, bl1)|0) + (m >>> 16)|0) + (r2 >>> 16)|0;
w = ((imul(al1, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl2)|0) + (m & 0xffff)|0) + (r3 & 0xffff)|0;
v = ((imul(ah1, bl2)|0) + (m >>> 16)|0) + (r3 >>> 16)|0;
w = ((imul(al1, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl3)|0) + (m & 0xffff)|0) + (r4 & 0xffff)|0;
v = ((imul(ah1, bl3)|0) + (m >>> 16)|0) + (r4 >>> 16)|0;
w = ((imul(al1, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl4)|0) + (m & 0xffff)|0) + (r5 & 0xffff)|0;
v = ((imul(ah1, bl4)|0) + (m >>> 16)|0) + (r5 >>> 16)|0;
w = ((imul(al1, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl5)|0) + (m & 0xffff)|0) + (r6 & 0xffff)|0;
v = ((imul(ah1, bl5)|0) + (m >>> 16)|0) + (r6 >>> 16)|0;
w = ((imul(al1, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl6)|0) + (m & 0xffff)|0) + (r7 & 0xffff)|0;
v = ((imul(ah1, bl6)|0) + (m >>> 16)|0) + (r7 >>> 16)|0;
w = ((imul(al1, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl7)|0) + (m & 0xffff)|0) + (r8 & 0xffff)|0;
v = ((imul(ah1, bl7)|0) + (m >>> 16)|0) + (r8 >>> 16)|0;
w = ((imul(al1, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
r9 = m;
u = ((imul(al2, bl0)|0) + (r10 & 0xffff)|0) + (r2 & 0xffff)|0;
v = ((imul(ah2, bl0)|0) + (r10 >>> 16)|0) + (r2 >>> 16)|0;
w = ((imul(al2, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl1)|0) + (m & 0xffff)|0) + (r3 & 0xffff)|0;
v = ((imul(ah2, bl1)|0) + (m >>> 16)|0) + (r3 >>> 16)|0;
w = ((imul(al2, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl2)|0) + (m & 0xffff)|0) + (r4 & 0xffff)|0;
v = ((imul(ah2, bl2)|0) + (m >>> 16)|0) + (r4 >>> 16)|0;
w = ((imul(al2, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl3)|0) + (m & 0xffff)|0) + (r5 & 0xffff)|0;
v = ((imul(ah2, bl3)|0) + (m >>> 16)|0) + (r5 >>> 16)|0;
w = ((imul(al2, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl4)|0) + (m & 0xffff)|0) + (r6 & 0xffff)|0;
v = ((imul(ah2, bl4)|0) + (m >>> 16)|0) + (r6 >>> 16)|0;
w = ((imul(al2, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl5)|0) + (m & 0xffff)|0) + (r7 & 0xffff)|0;
v = ((imul(ah2, bl5)|0) + (m >>> 16)|0) + (r7 >>> 16)|0;
w = ((imul(al2, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl6)|0) + (m & 0xffff)|0) + (r8 & 0xffff)|0;
v = ((imul(ah2, bl6)|0) + (m >>> 16)|0) + (r8 >>> 16)|0;
w = ((imul(al2, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl7)|0) + (m & 0xffff)|0) + (r9 & 0xffff)|0;
v = ((imul(ah2, bl7)|0) + (m >>> 16)|0) + (r9 >>> 16)|0;
w = ((imul(al2, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
r10 = m;
u = ((imul(al3, bl0)|0) + (r11 & 0xffff)|0) + (r3 & 0xffff)|0;
v = ((imul(ah3, bl0)|0) + (r11 >>> 16)|0) + (r3 >>> 16)|0;
w = ((imul(al3, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl1)|0) + (m & 0xffff)|0) + (r4 & 0xffff)|0;
v = ((imul(ah3, bl1)|0) + (m >>> 16)|0) + (r4 >>> 16)|0;
w = ((imul(al3, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl2)|0) + (m & 0xffff)|0) + (r5 & 0xffff)|0;
v = ((imul(ah3, bl2)|0) + (m >>> 16)|0) + (r5 >>> 16)|0;
w = ((imul(al3, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl3)|0) + (m & 0xffff)|0) + (r6 & 0xffff)|0;
v = ((imul(ah3, bl3)|0) + (m >>> 16)|0) + (r6 >>> 16)|0;
w = ((imul(al3, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl4)|0) + (m & 0xffff)|0) + (r7 & 0xffff)|0;
v = ((imul(ah3, bl4)|0) + (m >>> 16)|0) + (r7 >>> 16)|0;
w = ((imul(al3, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl5)|0) + (m & 0xffff)|0) + (r8 & 0xffff)|0;
v = ((imul(ah3, bl5)|0) + (m >>> 16)|0) + (r8 >>> 16)|0;
w = ((imul(al3, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl6)|0) + (m & 0xffff)|0) + (r9 & 0xffff)|0;
v = ((imul(ah3, bl6)|0) + (m >>> 16)|0) + (r9 >>> 16)|0;
w = ((imul(al3, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl7)|0) + (m & 0xffff)|0) + (r10 & 0xffff)|0;
v = ((imul(ah3, bl7)|0) + (m >>> 16)|0) + (r10 >>> 16)|0;
w = ((imul(al3, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
r11 = m;
u = ((imul(al4, bl0)|0) + (r12 & 0xffff)|0) + (r4 & 0xffff)|0;
v = ((imul(ah4, bl0)|0) + (r12 >>> 16)|0) + (r4 >>> 16)|0;
w = ((imul(al4, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl1)|0) + (m & 0xffff)|0) + (r5 & 0xffff)|0;
v = ((imul(ah4, bl1)|0) + (m >>> 16)|0) + (r5 >>> 16)|0;
w = ((imul(al4, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl2)|0) + (m & 0xffff)|0) + (r6 & 0xffff)|0;
v = ((imul(ah4, bl2)|0) + (m >>> 16)|0) + (r6 >>> 16)|0;
w = ((imul(al4, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl3)|0) + (m & 0xffff)|0) + (r7 & 0xffff)|0;
v = ((imul(ah4, bl3)|0) + (m >>> 16)|0) + (r7 >>> 16)|0;
w = ((imul(al4, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl4)|0) + (m & 0xffff)|0) + (r8 & 0xffff)|0;
v = ((imul(ah4, bl4)|0) + (m >>> 16)|0) + (r8 >>> 16)|0;
w = ((imul(al4, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl5)|0) + (m & 0xffff)|0) + (r9 & 0xffff)|0;
v = ((imul(ah4, bl5)|0) + (m >>> 16)|0) + (r9 >>> 16)|0;
w = ((imul(al4, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl6)|0) + (m & 0xffff)|0) + (r10 & 0xffff)|0;
v = ((imul(ah4, bl6)|0) + (m >>> 16)|0) + (r10 >>> 16)|0;
w = ((imul(al4, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl7)|0) + (m & 0xffff)|0) + (r11 & 0xffff)|0;
v = ((imul(ah4, bl7)|0) + (m >>> 16)|0) + (r11 >>> 16)|0;
w = ((imul(al4, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r11 = (w << 16) | (u & 0xffff);
r12 = m;
u = ((imul(al5, bl0)|0) + (r13 & 0xffff)|0) + (r5 & 0xffff)|0;
v = ((imul(ah5, bl0)|0) + (r13 >>> 16)|0) + (r5 >>> 16)|0;
w = ((imul(al5, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl1)|0) + (m & 0xffff)|0) + (r6 & 0xffff)|0;
v = ((imul(ah5, bl1)|0) + (m >>> 16)|0) + (r6 >>> 16)|0;
w = ((imul(al5, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl2)|0) + (m & 0xffff)|0) + (r7 & 0xffff)|0;
v = ((imul(ah5, bl2)|0) + (m >>> 16)|0) + (r7 >>> 16)|0;
w = ((imul(al5, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl3)|0) + (m & 0xffff)|0) + (r8 & 0xffff)|0;
v = ((imul(ah5, bl3)|0) + (m >>> 16)|0) + (r8 >>> 16)|0;
w = ((imul(al5, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl4)|0) + (m & 0xffff)|0) + (r9 & 0xffff)|0;
v = ((imul(ah5, bl4)|0) + (m >>> 16)|0) + (r9 >>> 16)|0;
w = ((imul(al5, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl5)|0) + (m & 0xffff)|0) + (r10 & 0xffff)|0;
v = ((imul(ah5, bl5)|0) + (m >>> 16)|0) + (r10 >>> 16)|0;
w = ((imul(al5, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl6)|0) + (m & 0xffff)|0) + (r11 & 0xffff)|0;
v = ((imul(ah5, bl6)|0) + (m >>> 16)|0) + (r11 >>> 16)|0;
w = ((imul(al5, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r11 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl7)|0) + (m & 0xffff)|0) + (r12 & 0xffff)|0;
v = ((imul(ah5, bl7)|0) + (m >>> 16)|0) + (r12 >>> 16)|0;
w = ((imul(al5, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r12 = (w << 16) | (u & 0xffff);
r13 = m;
u = ((imul(al6, bl0)|0) + (r14 & 0xffff)|0) + (r6 & 0xffff)|0;
v = ((imul(ah6, bl0)|0) + (r14 >>> 16)|0) + (r6 >>> 16)|0;
w = ((imul(al6, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl1)|0) + (m & 0xffff)|0) + (r7 & 0xffff)|0;
v = ((imul(ah6, bl1)|0) + (m >>> 16)|0) + (r7 >>> 16)|0;
w = ((imul(al6, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl2)|0) + (m & 0xffff)|0) + (r8 & 0xffff)|0;
v = ((imul(ah6, bl2)|0) + (m >>> 16)|0) + (r8 >>> 16)|0;
w = ((imul(al6, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl3)|0) + (m & 0xffff)|0) + (r9 & 0xffff)|0;
v = ((imul(ah6, bl3)|0) + (m >>> 16)|0) + (r9 >>> 16)|0;
w = ((imul(al6, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl4)|0) + (m & 0xffff)|0) + (r10 & 0xffff)|0;
v = ((imul(ah6, bl4)|0) + (m >>> 16)|0) + (r10 >>> 16)|0;
w = ((imul(al6, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl5)|0) + (m & 0xffff)|0) + (r11 & 0xffff)|0;
v = ((imul(ah6, bl5)|0) + (m >>> 16)|0) + (r11 >>> 16)|0;
w = ((imul(al6, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r11 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl6)|0) + (m & 0xffff)|0) + (r12 & 0xffff)|0;
v = ((imul(ah6, bl6)|0) + (m >>> 16)|0) + (r12 >>> 16)|0;
w = ((imul(al6, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r12 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl7)|0) + (m & 0xffff)|0) + (r13 & 0xffff)|0;
v = ((imul(ah6, bl7)|0) + (m >>> 16)|0) + (r13 >>> 16)|0;
w = ((imul(al6, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r13 = (w << 16) | (u & 0xffff);
r14 = m;
u = ((imul(al7, bl0)|0) + (r15 & 0xffff)|0) + (r7 & 0xffff)|0;
v = ((imul(ah7, bl0)|0) + (r15 >>> 16)|0) + (r7 >>> 16)|0;
w = ((imul(al7, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl1)|0) + (m & 0xffff)|0) + (r8 & 0xffff)|0;
v = ((imul(ah7, bl1)|0) + (m >>> 16)|0) + (r8 >>> 16)|0;
w = ((imul(al7, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl2)|0) + (m & 0xffff)|0) + (r9 & 0xffff)|0;
v = ((imul(ah7, bl2)|0) + (m >>> 16)|0) + (r9 >>> 16)|0;
w = ((imul(al7, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl3)|0) + (m & 0xffff)|0) + (r10 & 0xffff)|0;
v = ((imul(ah7, bl3)|0) + (m >>> 16)|0) + (r10 >>> 16)|0;
w = ((imul(al7, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl4)|0) + (m & 0xffff)|0) + (r11 & 0xffff)|0;
v = ((imul(ah7, bl4)|0) + (m >>> 16)|0) + (r11 >>> 16)|0;
w = ((imul(al7, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r11 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl5)|0) + (m & 0xffff)|0) + (r12 & 0xffff)|0;
v = ((imul(ah7, bl5)|0) + (m >>> 16)|0) + (r12 >>> 16)|0;
w = ((imul(al7, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r12 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl6)|0) + (m & 0xffff)|0) + (r13 & 0xffff)|0;
v = ((imul(ah7, bl6)|0) + (m >>> 16)|0) + (r13 >>> 16)|0;
w = ((imul(al7, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r13 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl7)|0) + (m & 0xffff)|0) + (r14 & 0xffff)|0;
v = ((imul(ah7, bl7)|0) + (m >>> 16)|0) + (r14 >>> 16)|0;
w = ((imul(al7, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r14 = (w << 16) | (u & 0xffff);
r15 = m;
HEAP32[(Rk|0)>>2] = r0, HEAP32[(Rk|4)>>2] = r1, HEAP32[(Rk|8)>>2] = r2, HEAP32[(Rk|12)>>2] = r3, HEAP32[(Rk|16)>>2] = r4, HEAP32[(Rk|20)>>2] = r5, HEAP32[(Rk|24)>>2] = r6, HEAP32[(Rk|28)>>2] = r7;
}
Rk = (R+(i+j|0))|0;
HEAP32[(Rk|0)>>2] = r8, HEAP32[(Rk|4)>>2] = r9, HEAP32[(Rk|8)>>2] = r10, HEAP32[(Rk|12)>>2] = r11, HEAP32[(Rk|16)>>2] = r12, HEAP32[(Rk|20)>>2] = r13, HEAP32[(Rk|24)>>2] = r14, HEAP32[(Rk|28)>>2] = r15;
}
/*
for ( i = lA & -32; (i|0) < (lA|0); i = (i+4)|0 ) {
Ai = (A+i)|0;
ah0 = HEAP32[Ai>>2]|0,
al0 = ah0 & 0xffff,
ah0 = ah0 >>> 16;
r1 = 0;
for ( j = 0; (j|0) < (lB|0); j = (j+4)|0 ) {
Bj = (B+j)|0;
Rk = (R+(i+j|0))|0;
bh0 = HEAP32[Bj>>2]|0,
bl0 = bh0 & 0xffff,
bh0 = bh0 >>> 16;
r0 = HEAP32[Rk>>2]|0;
u = ((imul(al0, bl0)|0) + (r1 & 0xffff)|0) + (r0 & 0xffff)|0;
v = ((imul(ah0, bl0)|0) + (r1 >>> 16)|0) + (r0 >>> 16)|0;
w = ((imul(al0, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r0 = (w << 16) | (u & 0xffff);
r1 = m;
HEAP32[Rk>>2] = r0;
}
Rk = (R+(i+j|0))|0;
HEAP32[Rk>>2] = r1;
}
*/
}
/**
* Fast squaring
*
* Exploits the fact:
*
* X² = ( X0 + X1*B )² = X0² + 2*X0*X1*B + X1²*B²,
*
* where B is a power of 2, so:
*
* 2*X0*X1*B = (X0*X1 << 1)*B
*
* @param A offset of the argument being squared, 32-byte aligned
* @param lA length of the argument, multiple of 32
*
* @param R offset where to place the result to, 32-byte aligned
*/
function sqr ( A, lA, R ) {
A = A|0;
lA = lA|0;
R = R|0;
var al0 = 0, al1 = 0, al2 = 0, al3 = 0, al4 = 0, al5 = 0, al6 = 0, al7 = 0, ah0 = 0, ah1 = 0, ah2 = 0, ah3 = 0, ah4 = 0, ah5 = 0, ah6 = 0, ah7 = 0,
bl0 = 0, bl1 = 0, bl2 = 0, bl3 = 0, bl4 = 0, bl5 = 0, bl6 = 0, bl7 = 0, bh0 = 0, bh1 = 0, bh2 = 0, bh3 = 0, bh4 = 0, bh5 = 0, bh6 = 0, bh7 = 0,
r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0, r5 = 0, r6 = 0, r7 = 0, r8 = 0, r9 = 0, r10 = 0, r11 = 0, r12 = 0, r13 = 0, r14 = 0, r15 = 0,
u = 0, v = 0, w = 0, c = 0, h = 0, m = 0, r = 0,
d = 0, dd = 0, p = 0, i = 0, j = 0, k = 0, Ai = 0, Aj = 0, Rk = 0;
// prepare for iterations
for ( ; (i|0) < (lA|0); i = (i+4)|0 ) {
Rk = R+(i<<1)|0;
ah0 = HEAP32[(A+i)>>2]|0, al0 = ah0 & 0xffff, ah0 = ah0 >>> 16;
u = imul(al0,al0)|0;
v = (imul(al0,ah0)|0) + (u >>> 17)|0;
w = (imul(ah0,ah0)|0) + (v >>> 15)|0;
HEAP32[(Rk)>>2] = (v << 17) | (u & 0x1ffff);
HEAP32[(Rk|4)>>2] = w;
}
// unrolled 1st iteration
for ( p = 0; (p|0) < (lA|0); p = (p+8)|0 ) {
Ai = A+p|0, Rk = R+(p<<1)|0;
ah0 = HEAP32[(Ai)>>2]|0, al0 = ah0 & 0xffff, ah0 = ah0 >>> 16;
bh0 = HEAP32[(Ai|4)>>2]|0, bl0 = bh0 & 0xffff, bh0 = bh0 >>> 16;
u = imul(al0,bl0)|0;
v = (imul(al0,bh0)|0) + (u >>> 16)|0;
w = (imul(ah0,bl0)|0) + (v & 0xffff)|0;
m = ((imul(ah0,bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r = HEAP32[(Rk|4)>>2]|0;
u = (r & 0xffff) + ((u & 0xffff) << 1)|0;
w = ((r >>> 16) + ((w & 0xffff) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|4)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk|8)>>2]|0;
u = ((r & 0xffff) + ((m & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((m >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|8)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
if ( c ) {
r = HEAP32[(Rk|12)>>2]|0;
u = (r & 0xffff) + c|0;
w = (r >>> 16) + (u >>> 16)|0;
HEAP32[(Rk|12)>>2] = (w << 16) | (u & 0xffff);
}
}
// unrolled 2nd iteration
for ( p = 0; (p|0) < (lA|0); p = (p+16)|0 ) {
Ai = A+p|0, Rk = R+(p<<1)|0;
ah0 = HEAP32[(Ai)>>2]|0, al0 = ah0 & 0xffff, ah0 = ah0 >>> 16, ah1 = HEAP32[(Ai|4)>>2]|0, al1 = ah1 & 0xffff, ah1 = ah1 >>> 16;
bh0 = HEAP32[(Ai|8)>>2]|0, bl0 = bh0 & 0xffff, bh0 = bh0 >>> 16, bh1 = HEAP32[(Ai|12)>>2]|0, bl1 = bh1 & 0xffff, bh1 = bh1 >>> 16;
u = imul(al0, bl0)|0;
v = imul(ah0, bl0)|0;
w = ((imul(al0, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r0 = (w << 16) | (u & 0xffff);
u = (imul(al0, bl1)|0) + (m & 0xffff)|0;
v = (imul(ah0, bl1)|0) + (m >>> 16)|0;
w = ((imul(al0, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r1 = (w << 16) | (u & 0xffff);
r2 = m;
u = (imul(al1, bl0)|0) + (r1 & 0xffff)|0;
v = (imul(ah1, bl0)|0) + (r1 >>> 16)|0;
w = ((imul(al1, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r1 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl1)|0) + (r2 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl1)|0) + (r2 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
r3 = m;
r = HEAP32[(Rk|8)>>2]|0;
u = (r & 0xffff) + ((r0 & 0xffff) << 1)|0;
w = ((r >>> 16) + ((r0 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|8)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk|12)>>2]|0;
u = ((r & 0xffff) + ((r1 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r1 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|12)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk|16)>>2]|0;
u = ((r & 0xffff) + ((r2 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r2 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|16)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk|20)>>2]|0;
u = ((r & 0xffff) + ((r3 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r3 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|20)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
for ( k = 24; !!c & ( (k|0) < 32 ); k = (k+4)|0 ) {
r = HEAP32[(Rk|k)>>2]|0;
u = (r & 0xffff) + c|0;
w = (r >>> 16) + (u >>> 16)|0;
HEAP32[(Rk|k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
}
}
// unrolled 3rd iteration
for ( p = 0; (p|0) < (lA|0); p = (p+32)|0 ) {
Ai = A+p|0, Rk = R+(p<<1)|0;
ah0 = HEAP32[(Ai)>>2]|0, al0 = ah0 & 0xffff, ah0 = ah0 >>> 16, ah1 = HEAP32[(Ai|4)>>2]|0, al1 = ah1 & 0xffff, ah1 = ah1 >>> 16, ah2 = HEAP32[(Ai|8)>>2]|0, al2 = ah2 & 0xffff, ah2 = ah2 >>> 16, ah3 = HEAP32[(Ai|12)>>2]|0, al3 = ah3 & 0xffff, ah3 = ah3 >>> 16;
bh0 = HEAP32[(Ai|16)>>2]|0, bl0 = bh0 & 0xffff, bh0 = bh0 >>> 16, bh1 = HEAP32[(Ai|20)>>2]|0, bl1 = bh1 & 0xffff, bh1 = bh1 >>> 16, bh2 = HEAP32[(Ai|24)>>2]|0, bl2 = bh2 & 0xffff, bh2 = bh2 >>> 16, bh3 = HEAP32[(Ai|28)>>2]|0, bl3 = bh3 & 0xffff, bh3 = bh3 >>> 16;
u = imul(al0, bl0)|0;
v = imul(ah0, bl0)|0;
w = ((imul(al0, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r0 = (w << 16) | (u & 0xffff);
u = (imul(al0, bl1)|0) + (m & 0xffff)|0;
v = (imul(ah0, bl1)|0) + (m >>> 16)|0;
w = ((imul(al0, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r1 = (w << 16) | (u & 0xffff);
u = (imul(al0, bl2)|0) + (m & 0xffff)|0;
v = (imul(ah0, bl2)|0) + (m >>> 16)|0;
w = ((imul(al0, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = (imul(al0, bl3)|0) + (m & 0xffff)|0;
v = (imul(ah0, bl3)|0) + (m >>> 16)|0;
w = ((imul(al0, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
r4 = m;
u = (imul(al1, bl0)|0) + (r1 & 0xffff)|0;
v = (imul(ah1, bl0)|0) + (r1 >>> 16)|0;
w = ((imul(al1, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r1 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl1)|0) + (r2 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl1)|0) + (r2 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl2)|0) + (r3 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl2)|0) + (r3 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl3)|0) + (r4 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl3)|0) + (r4 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
r5 = m;
u = (imul(al2, bl0)|0) + (r2 & 0xffff)|0;
v = (imul(ah2, bl0)|0) + (r2 >>> 16)|0;
w = ((imul(al2, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl1)|0) + (r3 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl1)|0) + (r3 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl2)|0) + (r4 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl2)|0) + (r4 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl3)|0) + (r5 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl3)|0) + (r5 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
r6 = m;
u = (imul(al3, bl0)|0) + (r3 & 0xffff)|0;
v = (imul(ah3, bl0)|0) + (r3 >>> 16)|0;
w = ((imul(al3, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl1)|0) + (r4 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl1)|0) + (r4 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl2)|0) + (r5 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl2)|0) + (r5 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl3)|0) + (r6 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl3)|0) + (r6 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
r7 = m;
r = HEAP32[(Rk|16)>>2]|0;
u = (r & 0xffff) + ((r0 & 0xffff) << 1)|0;
w = ((r >>> 16) + ((r0 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|16)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk|20)>>2]|0;
u = ((r & 0xffff) + ((r1 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r1 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|20)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk|24)>>2]|0;
u = ((r & 0xffff) + ((r2 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r2 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|24)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk|28)>>2]|0;
u = ((r & 0xffff) + ((r3 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r3 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk|28)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk+32)>>2]|0;
u = ((r & 0xffff) + ((r4 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r4 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+32)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk+36)>>2]|0;
u = ((r & 0xffff) + ((r5 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r5 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+36)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk+40)>>2]|0;
u = ((r & 0xffff) + ((r6 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r6 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+40)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
r = HEAP32[(Rk+44)>>2]|0;
u = ((r & 0xffff) + ((r7 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r7 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+44)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
for ( k = 48; !!c & ( (k|0) < 64 ); k = (k+4)|0 ) {
r = HEAP32[(Rk+k)>>2]|0;
u = (r & 0xffff) + c|0;
w = (r >>> 16) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
}
}
// perform iterations
for ( d = 32; (d|0) < (lA|0); d = d << 1 ) { // depth loop
dd = d << 1;
for ( p = 0; (p|0) < (lA|0); p = (p+dd)|0 ) { // part loop
Rk = R+(p<<1)|0;
h = 0;
for ( i = 0; (i|0) < (d|0); i = (i+32)|0 ) { // multiply-and-add loop
Ai = (A+p|0)+i|0;
ah0 = HEAP32[(Ai)>>2]|0, al0 = ah0 & 0xffff, ah0 = ah0 >>> 16, ah1 = HEAP32[(Ai|4)>>2]|0, al1 = ah1 & 0xffff, ah1 = ah1 >>> 16, ah2 = HEAP32[(Ai|8)>>2]|0, al2 = ah2 & 0xffff, ah2 = ah2 >>> 16, ah3 = HEAP32[(Ai|12)>>2]|0, al3 = ah3 & 0xffff, ah3 = ah3 >>> 16, ah4 = HEAP32[(Ai|16)>>2]|0, al4 = ah4 & 0xffff, ah4 = ah4 >>> 16, ah5 = HEAP32[(Ai|20)>>2]|0, al5 = ah5 & 0xffff, ah5 = ah5 >>> 16, ah6 = HEAP32[(Ai|24)>>2]|0, al6 = ah6 & 0xffff, ah6 = ah6 >>> 16, ah7 = HEAP32[(Ai|28)>>2]|0, al7 = ah7 & 0xffff, ah7 = ah7 >>> 16;
r8 = r9 = r10 = r11 = r12 = r13 = r14 = r15 = c = 0;
for ( j = 0; (j|0) < (d|0); j = (j+32)|0 ) {
Aj = ((A+p|0)+d|0)+j|0;
bh0 = HEAP32[(Aj)>>2]|0, bl0 = bh0 & 0xffff, bh0 = bh0 >>> 16, bh1 = HEAP32[(Aj|4)>>2]|0, bl1 = bh1 & 0xffff, bh1 = bh1 >>> 16, bh2 = HEAP32[(Aj|8)>>2]|0, bl2 = bh2 & 0xffff, bh2 = bh2 >>> 16, bh3 = HEAP32[(Aj|12)>>2]|0, bl3 = bh3 & 0xffff, bh3 = bh3 >>> 16, bh4 = HEAP32[(Aj|16)>>2]|0, bl4 = bh4 & 0xffff, bh4 = bh4 >>> 16, bh5 = HEAP32[(Aj|20)>>2]|0, bl5 = bh5 & 0xffff, bh5 = bh5 >>> 16, bh6 = HEAP32[(Aj|24)>>2]|0, bl6 = bh6 & 0xffff, bh6 = bh6 >>> 16, bh7 = HEAP32[(Aj|28)>>2]|0, bl7 = bh7 & 0xffff, bh7 = bh7 >>> 16;
r0 = r1 = r2 = r3 = r4 = r5 = r6 = r7 = 0;
u = ((imul(al0, bl0)|0) + (r0 & 0xffff)|0) + (r8 & 0xffff)|0;
v = ((imul(ah0, bl0)|0) + (r0 >>> 16)|0) + (r8 >>> 16)|0;
w = ((imul(al0, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r0 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl1)|0) + (r1 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah0, bl1)|0) + (r1 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al0, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r1 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl2)|0) + (r2 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah0, bl2)|0) + (r2 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al0, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl3)|0) + (r3 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah0, bl3)|0) + (r3 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al0, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl4)|0) + (r4 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah0, bl4)|0) + (r4 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al0, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl5)|0) + (r5 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah0, bl5)|0) + (r5 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al0, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl6)|0) + (r6 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah0, bl6)|0) + (r6 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al0, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al0, bl7)|0) + (r7 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah0, bl7)|0) + (r7 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al0, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah0, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
r8 = m;
u = ((imul(al1, bl0)|0) + (r1 & 0xffff)|0) + (r9 & 0xffff)|0;
v = ((imul(ah1, bl0)|0) + (r1 >>> 16)|0) + (r9 >>> 16)|0;
w = ((imul(al1, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r1 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl1)|0) + (r2 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl1)|0) + (r2 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl2)|0) + (r3 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl2)|0) + (r3 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl3)|0) + (r4 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl3)|0) + (r4 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl4)|0) + (r5 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl4)|0) + (r5 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl5)|0) + (r6 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl5)|0) + (r6 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl6)|0) + (r7 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl6)|0) + (r7 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al1, bl7)|0) + (r8 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah1, bl7)|0) + (r8 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al1, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah1, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
r9 = m;
u = ((imul(al2, bl0)|0) + (r2 & 0xffff)|0) + (r10 & 0xffff)|0;
v = ((imul(ah2, bl0)|0) + (r2 >>> 16)|0) + (r10 >>> 16)|0;
w = ((imul(al2, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r2 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl1)|0) + (r3 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl1)|0) + (r3 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl2)|0) + (r4 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl2)|0) + (r4 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl3)|0) + (r5 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl3)|0) + (r5 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl4)|0) + (r6 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl4)|0) + (r6 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl5)|0) + (r7 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl5)|0) + (r7 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl6)|0) + (r8 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl6)|0) + (r8 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al2, bl7)|0) + (r9 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah2, bl7)|0) + (r9 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al2, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah2, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
r10 = m;
u = ((imul(al3, bl0)|0) + (r3 & 0xffff)|0) + (r11 & 0xffff)|0;
v = ((imul(ah3, bl0)|0) + (r3 >>> 16)|0) + (r11 >>> 16)|0;
w = ((imul(al3, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r3 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl1)|0) + (r4 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl1)|0) + (r4 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl2)|0) + (r5 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl2)|0) + (r5 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl3)|0) + (r6 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl3)|0) + (r6 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl4)|0) + (r7 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl4)|0) + (r7 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl5)|0) + (r8 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl5)|0) + (r8 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl6)|0) + (r9 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl6)|0) + (r9 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al3, bl7)|0) + (r10 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah3, bl7)|0) + (r10 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al3, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah3, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
r11 = m;
u = ((imul(al4, bl0)|0) + (r4 & 0xffff)|0) + (r12 & 0xffff)|0;
v = ((imul(ah4, bl0)|0) + (r4 >>> 16)|0) + (r12 >>> 16)|0;
w = ((imul(al4, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r4 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl1)|0) + (r5 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah4, bl1)|0) + (r5 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al4, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl2)|0) + (r6 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah4, bl2)|0) + (r6 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al4, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl3)|0) + (r7 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah4, bl3)|0) + (r7 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al4, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl4)|0) + (r8 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah4, bl4)|0) + (r8 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al4, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl5)|0) + (r9 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah4, bl5)|0) + (r9 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al4, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl6)|0) + (r10 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah4, bl6)|0) + (r10 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al4, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
u = ((imul(al4, bl7)|0) + (r11 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah4, bl7)|0) + (r11 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al4, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah4, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r11 = (w << 16) | (u & 0xffff);
r12 = m;
u = ((imul(al5, bl0)|0) + (r5 & 0xffff)|0) + (r13 & 0xffff)|0;
v = ((imul(ah5, bl0)|0) + (r5 >>> 16)|0) + (r13 >>> 16)|0;
w = ((imul(al5, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r5 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl1)|0) + (r6 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah5, bl1)|0) + (r6 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al5, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl2)|0) + (r7 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah5, bl2)|0) + (r7 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al5, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl3)|0) + (r8 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah5, bl3)|0) + (r8 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al5, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl4)|0) + (r9 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah5, bl4)|0) + (r9 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al5, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl5)|0) + (r10 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah5, bl5)|0) + (r10 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al5, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl6)|0) + (r11 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah5, bl6)|0) + (r11 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al5, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r11 = (w << 16) | (u & 0xffff);
u = ((imul(al5, bl7)|0) + (r12 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah5, bl7)|0) + (r12 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al5, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah5, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r12 = (w << 16) | (u & 0xffff);
r13 = m;
u = ((imul(al6, bl0)|0) + (r6 & 0xffff)|0) + (r14 & 0xffff)|0;
v = ((imul(ah6, bl0)|0) + (r6 >>> 16)|0) + (r14 >>> 16)|0;
w = ((imul(al6, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r6 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl1)|0) + (r7 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah6, bl1)|0) + (r7 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al6, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl2)|0) + (r8 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah6, bl2)|0) + (r8 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al6, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl3)|0) + (r9 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah6, bl3)|0) + (r9 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al6, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl4)|0) + (r10 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah6, bl4)|0) + (r10 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al6, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl5)|0) + (r11 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah6, bl5)|0) + (r11 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al6, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r11 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl6)|0) + (r12 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah6, bl6)|0) + (r12 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al6, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r12 = (w << 16) | (u & 0xffff);
u = ((imul(al6, bl7)|0) + (r13 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah6, bl7)|0) + (r13 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al6, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah6, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r13 = (w << 16) | (u & 0xffff);
r14 = m;
u = ((imul(al7, bl0)|0) + (r7 & 0xffff)|0) + (r15 & 0xffff)|0;
v = ((imul(ah7, bl0)|0) + (r7 >>> 16)|0) + (r15 >>> 16)|0;
w = ((imul(al7, bh0)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh0)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r7 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl1)|0) + (r8 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah7, bl1)|0) + (r8 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al7, bh1)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh1)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r8 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl2)|0) + (r9 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah7, bl2)|0) + (r9 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al7, bh2)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh2)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r9 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl3)|0) + (r10 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah7, bl3)|0) + (r10 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al7, bh3)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh3)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r10 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl4)|0) + (r11 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah7, bl4)|0) + (r11 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al7, bh4)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh4)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r11 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl5)|0) + (r12 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah7, bl5)|0) + (r12 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al7, bh5)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh5)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r12 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl6)|0) + (r13 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah7, bl6)|0) + (r13 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al7, bh6)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh6)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r13 = (w << 16) | (u & 0xffff);
u = ((imul(al7, bl7)|0) + (r14 & 0xffff)|0) + (m & 0xffff)|0;
v = ((imul(ah7, bl7)|0) + (r14 >>> 16)|0) + (m >>> 16)|0;
w = ((imul(al7, bh7)|0) + (v & 0xffff)|0) + (u >>> 16)|0;
m = ((imul(ah7, bh7)|0) + (v >>> 16)|0) + (w >>> 16)|0;
r14 = (w << 16) | (u & 0xffff);
r15 = m;
k = d+(i+j|0)|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r0 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r0 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r1 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r1 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r2 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r2 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r3 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r3 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r4 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r4 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r5 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r5 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r6 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r6 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r7 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r7 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
}
k = d+(i+j|0)|0;
r = HEAP32[(Rk+k)>>2]|0;
u = (((r & 0xffff) + ((r8 & 0xffff) << 1)|0) + c|0) + h|0;
w = ((r >>> 16) + ((r8 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r9 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r9 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r10 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r10 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r11 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r11 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r12 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r12 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r13 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r13 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r14 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r14 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
c = w >>> 16;
k = k+4|0;
r = HEAP32[(Rk+k)>>2]|0;
u = ((r & 0xffff) + ((r15 & 0xffff) << 1)|0) + c|0;
w = ((r >>> 16) + ((r15 >>> 16) << 1)|0) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
h = w >>> 16;
}
for ( k = k+4|0; !!h & ( (k|0) < (dd<<1) ); k = (k+4)|0 ) { // carry propagation loop
r = HEAP32[(Rk+k)>>2]|0;
u = (r & 0xffff) + h|0;
w = (r >>> 16) + (u >>> 16)|0;
HEAP32[(Rk+k)>>2] = (w << 16) | (u & 0xffff);
h = w >>> 16;
}
}
}
}
/**
* Conventional division
*
* @param A offset of the numerator, 32-byte aligned
* @param lA length of the numerator, multiple of 32
*
* @param B offset of the divisor, 32-byte aligned
* @param lB length of the divisor, multiple of 32
*
* @param R offset where to place the remainder to, 32-byte aligned
*
* @param Q offser where to place the quotient to, 32-byte aligned
*/
function div ( N, lN, D, lD, Q ) {
N = N|0;
lN = lN|0;
D = D|0;
lD = lD|0;
Q = Q|0;
var n = 0, d = 0, e = 0,
u1 = 0, u0 = 0,
v0 = 0, vh = 0, vl = 0,
qh = 0, ql = 0, rh = 0, rl = 0,
t1 = 0, t2 = 0, m = 0, c = 0,
i = 0, j = 0, k = 0;
// number of significant limbs in `N` (multiplied by 4)
for ( i = (lN-1) & -4; (i|0) >= 0; i = (i-4)|0 ) {
n = HEAP32[(N+i)>>2]|0;
if ( n ) {
lN = i;
break;
}
}
// number of significant limbs in `D` (multiplied by 4)
for ( i = (lD-1) & -4; (i|0) >= 0; i = (i-4)|0 ) {
d = HEAP32[(D+i)>>2]|0;
if ( d ) {
lD = i;
break;
}
}
// `D` is zero? WTF?!
// calculate `e` — the power of 2 of the normalization factor
while ( (d & 0x80000000) == 0 ) {
d = d << 1;
e = e + 1|0;
}
// normalize `N` in place
u0 = HEAP32[(N+lN)>>2]|0;
if ( e ) {
u1 = u0>>>(32-e|0);
for ( i = (lN-4)|0; (i|0) >= 0; i = (i-4)|0 ) {
n = HEAP32[(N+i)>>2]|0;
HEAP32[(N+i+4)>>2] = (u0 << e) | ( e ? n >>> (32-e|0) : 0 );
u0 = n;
}
HEAP32[N>>2] = u0 << e;
}
// normalize `D` in place
if ( e ) {
v0 = HEAP32[(D+lD)>>2]|0;
for ( i = (lD-4)|0; (i|0) >= 0; i = (i-4)|0 ) {
d = HEAP32[(D+i)>>2]|0;
HEAP32[(D+i+4)>>2] = (v0 << e) | ( d >>> (32-e|0) );
v0 = d;
}
HEAP32[D>>2] = v0 << e;
}
// divisor parts won't change
v0 = HEAP32[(D+lD)>>2]|0;
vh = v0 >>> 16, vl = v0 & 0xffff;
// perform division
for ( i = lN; (i|0) >= (lD|0); i = (i-4)|0 ) {
j = (i-lD)|0;
// estimate high part of the quotient
u0 = HEAP32[(N+i)>>2]|0;
qh = ( (u1>>>0) / (vh>>>0) )|0, rh = ( (u1>>>0) % (vh>>>0) )|0, t1 = imul(qh, vl)|0;
while ( ( (qh|0) == 0x10000 ) | ( (t1>>>0) > (((rh << 16)|(u0 >>> 16))>>>0) ) ) {
qh = (qh-1)|0, rh = (rh+vh)|0, t1 = (t1-vl)|0;
if ( (rh|0) >= 0x10000 ) break;
}
// bulk multiply-and-subtract
// m - multiplication carry, c - subtraction carry
m = 0, c = 0;
for ( k = 0; (k|0) <= (lD|0); k = (k+4)|0 ) {
d = HEAP32[(D+k)>>2]|0;
t1 = (imul(qh, d & 0xffff)|0) + (m >>> 16)|0;
t2 = (imul(qh, d >>> 16)|0) + (t1 >>> 16)|0;
d = (m & 0xffff) | (t1 << 16);
m = t2;
n = HEAP32[(N+j+k)>>2]|0;
t1 = ((n & 0xffff) - (d & 0xffff)|0) + c|0;
t2 = ((n >>> 16) - (d >>> 16)|0) + (t1 >> 16)|0;
HEAP32[(N+j+k)>>2] = (t2 << 16) | (t1 & 0xffff);
c = t2 >> 16;
}
t1 = ((u1 & 0xffff) - (m & 0xffff)|0) + c|0;
t2 = ((u1 >>> 16) - (m >>> 16)|0) + (t1 >> 16)|0;
u1 = (t2 << 16) | (t1 & 0xffff);
c = t2 >> 16;
// add `D` back if got carry-out
if ( c ) {
qh = (qh-1)|0;
c = 0;
for ( k = 0; (k|0) <= (lD|0); k = (k+4)|0 ) {
d = HEAP32[(D+k)>>2]|0;
n = HEAP32[(N+j+k)>>2]|0;
t1 = (n & 0xffff) + c|0;
t2 = (n >>> 16) + d + (t1 >>> 16)|0;
HEAP32[(N+j+k)>>2] = (t2 << 16) | (t1 & 0xffff);
c = t2 >>> 16;
}
u1 = (u1+c)|0;
}
// estimate low part of the quotient
u0 = HEAP32[(N+i)>>2]|0;
n = (u1 << 16) | (u0 >>> 16);
ql = ( (n>>>0) / (vh>>>0) )|0, rl = ( (n>>>0) % (vh>>>0) )|0, t1 = imul(ql, vl)|0;
while ( ( (ql|0) == 0x10000 ) | ( (t1>>>0) > (((rl << 16)|(u0 & 0xffff))>>>0) ) ) {
ql = (ql-1)|0, rl = (rl+vh)|0, t1 = (t1-vl)|0;
if ( (rl|0) >= 0x10000 ) break;
}
// bulk multiply-and-subtract
// m - multiplication carry, c - subtraction carry
m = 0, c = 0;
for ( k = 0; (k|0) <= (lD|0); k = (k+4)|0 ) {
d = HEAP32[(D+k)>>2]|0;
t1 = (imul(ql, d & 0xffff)|0) + (m & 0xffff)|0;
t2 = ((imul(ql, d >>> 16)|0) + (t1 >>> 16)|0) + (m >>> 16)|0;
d = (t1 & 0xffff) | (t2 << 16);
m = t2 >>> 16;
n = HEAP32[(N+j+k)>>2]|0;
t1 = ((n & 0xffff) - (d & 0xffff)|0) + c|0;
t2 = ((n >>> 16) - (d >>> 16)|0) + (t1 >> 16)|0;
c = t2 >> 16;
HEAP32[(N+j+k)>>2] = (t2 << 16) | (t1 & 0xffff);
}
t1 = ((u1 & 0xffff) - (m & 0xffff)|0) + c|0;
t2 = ((u1 >>> 16) - (m >>> 16)|0) + (t1 >> 16)|0;
c = t2 >> 16;
// add `D` back if got carry-out
if ( c ) {
ql = (ql-1)|0;
c = 0;
for ( k = 0; (k|0) <= (lD|0); k = (k+4)|0 ) {
d = HEAP32[(D+k)>>2]|0;
n = HEAP32[(N+j+k)>>2]|0;
t1 = ((n & 0xffff) + (d & 0xffff)|0) + c|0;
t2 = ((n >>> 16) + (d >>> 16)|0) + (t1 >>> 16)|0;
c = t2 >>> 16;
HEAP32[(N+j+k)>>2] = (t1 & 0xffff) | (t2 << 16);
}
}
// got quotient limb
HEAP32[(Q+j)>>2] = (qh << 16) | ql;
u1 = HEAP32[(N+i)>>2]|0;
}
if ( e ) {
// TODO denormalize `D` in place
// denormalize `N` in place
u0 = HEAP32[N>>2]|0;
for ( i = 4; (i|0) <= (lD|0); i = (i+4)|0 ) {
n = HEAP32[(N+i)>>2]|0;
HEAP32[(N+i-4)>>2] = ( n << (32-e|0) ) | (u0 >>> e);
u0 = n;
}
HEAP32[(N+lD)>>2] = u0 >>> e;
}
}
/**
* Montgomery modular reduction
*
* Definition:
*
* MREDC(A) = A × X (mod N),
* M × X = N × Y + 1,
*
* where M = 2^(32*m) such that N < M and A < N×M
*
* Numbers `X` and `Y` can be calculated using Extended Euclidean Algorithm.
*/
function mredc ( A, lA, N, lN, y, R ) {
A = A|0;
lA = lA|0;
N = N|0;
lN = lN|0;
y = y|0;
R = R|0;
var T = 0,
c = 0, uh = 0, ul = 0, vl = 0, vh = 0, w0 = 0, w1 = 0, w2 = 0, r0 = 0, r1 = 0,
i = 0, j = 0, k = 0;
T = salloc(lN<<1)|0;
z(lN<<1, 0, T);
cp( lA, A, T );
// HAC 14.32
for ( i = 0; (i|0) < (lN|0); i = (i+4)|0 ) {
uh = HEAP32[(T+i)>>2]|0, ul = uh & 0xffff, uh = uh >>> 16;
vh = y >>> 16, vl = y & 0xffff;
w0 = imul(ul,vl)|0, w1 = ( (imul(ul,vh)|0) + (imul(uh,vl)|0) | 0 ) + (w0 >>> 16) | 0;
ul = w0 & 0xffff, uh = w1 & 0xffff;
r1 = 0;
for ( j = 0; (j|0) < (lN|0); j = (j+4)|0 ) {
k = (i+j)|0;
vh = HEAP32[(N+j)>>2]|0, vl = vh & 0xffff, vh = vh >>> 16;
r0 = HEAP32[(T+k)>>2]|0;
w0 = ((imul(ul, vl)|0) + (r1 & 0xffff)|0) + (r0 & 0xffff)|0;
w1 = ((imul(ul, vh)|0) + (r1 >>> 16)|0) + (r0 >>> 16)|0;
w2 = ((imul(uh, vl)|0) + (w1 & 0xffff)|0) + (w0 >>> 16)|0;
r1 = ((imul(uh, vh)|0) + (w2 >>> 16)|0) + (w1 >>> 16)|0;
r0 = (w2 << 16) | (w0 & 0xffff);
HEAP32[(T+k)>>2] = r0;
}
k = (i+j)|0;
r0 = HEAP32[(T+k)>>2]|0;
w0 = ((r0 & 0xffff) + (r1 & 0xffff)|0) + c|0;
w1 = ((r0 >>> 16) + (r1 >>> 16)|0) + (w0 >>> 16)|0;
HEAP32[(T+k)>>2] = (w1 << 16) | (w0 & 0xffff);
c = w1 >>> 16;
}
cp( lN, (T+lN)|0, R );
sfree(lN<<1);
if ( c | ( (cmp( N, lN, R, lN )|0) <= 0 ) ) {
sub( R, lN, N, lN, R, lN )|0;
}
}
return {
sreset: sreset,
salloc: salloc,
sfree: sfree,
z: z,
tst: tst,
neg: neg,
cmp: cmp,
add: add,
sub: sub,
mul: mul,
sqr: sqr,
div: div,
mredc: mredc
};
}
function is_big_number ( a ) {
return ( a instanceof BigNumber_constructor );
}
///////////////////////////////////////////////////////////////////////////////
var _bigint_stdlib = { Uint32Array: Uint32Array, Math: Math };
var _bigint_heap = new Uint32Array(0x100000);
var _bigint_asm;
function _half_imul ( a, b ) {
return a * b | 0;
}
if ( _bigint_stdlib.Math.imul === undefined ) {
_bigint_stdlib.Math.imul = _half_imul;
_bigint_asm = bigint_asm( _bigint_stdlib, null, _bigint_heap.buffer );
delete _bigint_stdlib.Math.imul;
}
else {
_bigint_asm = bigint_asm( _bigint_stdlib, null, _bigint_heap.buffer );
}
///////////////////////////////////////////////////////////////////////////////
var _BigNumber_ZERO_limbs = new Uint32Array(0);
function BigNumber_constructor (num ) {
var limbs = _BigNumber_ZERO_limbs,
bitlen = 0,
sign = 0;
if ( is_string(num) )
num = string_to_bytes(num);
if ( is_buffer(num) )
num = new Uint8Array(num);
if ( num === undefined ) {
// do nothing
}
else if ( is_number(num) ) {
var absnum = Math.abs(num);
if ( absnum > 0xffffffff ) {
limbs = new Uint32Array(2);
limbs[0] = absnum|0;
limbs[1] = (absnum/0x100000000)|0;
bitlen = 52;
}
else if ( absnum > 0 ) {
limbs = new Uint32Array(1);
limbs[0] = absnum;
bitlen = 32;
}
else {
limbs = _BigNumber_ZERO_limbs;
bitlen = 0;
}
sign = num < 0 ? -1 : 1;
}
else if ( is_bytes(num) ) {
for ( var i = 0; !num[i]; i++ );
bitlen = ( num.length - i ) * 8;
if ( !bitlen )
return BigNumber_ZERO;
limbs = new Uint32Array( (bitlen + 31) >> 5 );
for ( var j = num.length-4; j >= i ; j -= 4 ) {
limbs[(num.length-4-j)>>2] = (num[j] << 24) | (num[j+1] << 16) | (num[j+2] << 8) | num[j+3];
}
if ( i-j === 3 ) {
limbs[limbs.length-1] = num[i];
}
else if ( i-j === 2 ) {
limbs[limbs.length-1] = (num[i] << 8) | num[i+1];
}
else if ( i-j === 1 ) {
limbs[limbs.length-1] = (num[i] << 16) | (num[i+1] << 8) | num[i+2];
}
sign = 1;
}
else if ( typeof num === 'object' && num !== null ) {
limbs = new Uint32Array( num.limbs );
bitlen = num.bitLength;
sign = num.sign;
}
else {
throw new TypeError("number is of unexpected type");
}
this.limbs = limbs;
this.bitLength = bitlen;
this.sign = sign;
}
function BigNumber_toString ( radix ) {
radix = radix || 16;
var limbs = this.limbs,
bitlen = this.bitLength,
str = '';
if ( radix === 16 ) {
// FIXME clamp last limb to (bitlen % 32)
for ( var i = (bitlen+31>>5)-1; i >= 0; i-- ) {
var h = limbs[i].toString(16);
str += '00000000'.substr(h.length);
str += h;
}
str = str.replace( /^0+/, '' );
if ( !str.length )
str = '0';
}
else {
throw new IllegalArgumentError("bad radix");
}
if ( this.sign < 0 )
str = '-' + str;
return str;
}
function BigNumber_toBytes () {
var bitlen = this.bitLength,
limbs = this.limbs;
if ( bitlen === 0 )
return new Uint8Array(0);
var bytelen = ( bitlen + 7 ) >> 3,
bytes = new Uint8Array(bytelen);
for ( var i = 0; i < bytelen; i++ ) {
var j = bytelen - i - 1;
bytes[i] = limbs[j>>2] >> ( (j & 3) << 3 );
}
return bytes;
}
// Downgrade to Number
function BigNumber_valueOf () {
var limbs = this.limbs,
bits = this.bitLength,
sign = this.sign;
if ( !sign )
return 0;
if ( bits <= 32 )
return sign * (limbs[0]>>>0);
if ( bits <= 52 )
return sign * ( 0x100000000 * (limbs[1]>>>0) + (limbs[0]>>>0) );
// normalization
var i, l, e = 0;
for ( i = limbs.length-1; i >= 0; i-- ) {
if ( (l = limbs[i]) === 0 ) continue;
while ( ( (l << e) & 0x80000000 ) === 0 ) e++;
break;
}
if ( i === 0 )
return sign * (limbs[0]>>>0);
return sign * ( 0x100000 * (( (limbs[i] << e) | ( e ? limbs[i-1] >>> (32-e) : 0 ) )>>>0)
+ (( (limbs[i-1] << e) | ( e && i > 1 ? limbs[i-2] >>> (32-e) : 0 ) )>>>12)
) * Math.pow( 2, 32*i-e-52 );
}
function BigNumber_clamp ( b ) {
var limbs = this.limbs,
bitlen = this.bitLength;
// FIXME check b is number and in a valid range
if ( b >= bitlen )
return this;
var clamped = new BigNumber_constructor,
n = (b + 31) >> 5,
k = b % 32;
clamped.limbs = new Uint32Array( limbs.subarray(0,n) );
clamped.bitLength = b;
clamped.sign = this.sign;
if ( k ) clamped.limbs[n-1] &= (-1 >>> (32-k));
return clamped;
}
function BigNumber_slice ( f, b ) {
if ( !is_number(f) )
throw new TypeError("TODO");
if ( b !== undefined && !is_number(b) )
throw new TypeError("TODO");
var limbs = this.limbs,
bitlen = this.bitLength;
if ( f < 0 )
throw new RangeError("TODO");
if ( f >= bitlen )
return BigNumber_ZERO;
if ( b === undefined || b > bitlen - f )
b = bitlen - f;
var sliced = new BigNumber_constructor, slimbs,
n = f >> 5, m = (f + b + 31) >> 5, l = (b + 31) >> 5,
t = f % 32, k = b % 32;
slimbs = new Uint32Array(l);
if ( t ) {
for ( var i = 0; i < m-n-1; i++ ) {
slimbs[i] = (limbs[n+i]>>>t) | ( limbs[n+i+1]<<(32-t) );
}
slimbs[i] = limbs[n+i]>>>t;
}
else {
slimbs.set( limbs.subarray(n, m) );
}
if ( k ) {
slimbs[l-1] &= (-1 >>> (32-k));
}
sliced.limbs = slimbs;
sliced.bitLength = b;
sliced.sign = this.sign;
return sliced;
}
///////////////////////////////////////////////////////////////////////////////
function BigNumber_negate () {
var negative = new BigNumber_constructor;
negative.limbs = this.limbs;
negative.bitLength = this.bitLength;
negative.sign = -1 * this.sign;
return negative;
}
function BigNumber_compare ( that ) {
if ( !is_big_number(that) )
that = new BigNumber_constructor(that);
var alimbs = this.limbs, alimbcnt = alimbs.length,
blimbs = that.limbs, blimbcnt = blimbs.length,
z = 0;
if ( this.sign < that.sign )
return -1;
if ( this.sign > that.sign )
return 1;
_bigint_heap.set( alimbs, 0 );
_bigint_heap.set( blimbs, alimbcnt );
z = _bigint_asm.cmp( 0, alimbcnt<<2, alimbcnt<<2, blimbcnt<<2 );
return z * this.sign;
}
function BigNumber_add ( that ) {
if ( !is_big_number(that) )
that = new BigNumber_constructor(that);
if ( !this.sign )
return that;
if ( !that.sign )
return this;
var abitlen = this.bitLength, alimbs = this.limbs, alimbcnt = alimbs.length, asign = this.sign,
bbitlen = that.bitLength, blimbs = that.limbs, blimbcnt = blimbs.length, bsign = that.sign,
rbitlen, rlimbcnt, rsign, rof, result = new BigNumber_constructor;
rbitlen = ( abitlen > bbitlen ? abitlen : bbitlen ) + ( asign * bsign > 0 ? 1 : 0 );
rlimbcnt = ( rbitlen + 31 ) >> 5;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc( alimbcnt<<2 ),
pB = _bigint_asm.salloc( blimbcnt<<2 ),
pR = _bigint_asm.salloc( rlimbcnt<<2 );
_bigint_asm.z( pR-pA+(rlimbcnt<<2), 0, pA );
_bigint_heap.set( alimbs, pA>>2 );
_bigint_heap.set( blimbs, pB>>2 );
if ( asign * bsign > 0 ) {
_bigint_asm.add( pA, alimbcnt<<2, pB, blimbcnt<<2, pR, rlimbcnt<<2 );
rsign = asign;
}
else if ( asign > bsign ) {
rof = _bigint_asm.sub( pA, alimbcnt<<2, pB, blimbcnt<<2, pR, rlimbcnt<<2 );
rsign = rof ? bsign : asign;
}
else {
rof = _bigint_asm.sub( pB, blimbcnt<<2, pA, alimbcnt<<2, pR, rlimbcnt<<2 );
rsign = rof ? asign : bsign;
}
if ( rof )
_bigint_asm.neg( pR, rlimbcnt<<2, pR, rlimbcnt<<2 );
if ( _bigint_asm.tst( pR, rlimbcnt<<2 ) === 0 )
return BigNumber_ZERO;
result.limbs = new Uint32Array( _bigint_heap.subarray( pR>>2, (pR>>2)+rlimbcnt ) );
result.bitLength = rbitlen;
result.sign = rsign;
return result;
}
function BigNumber_subtract ( that ) {
if ( !is_big_number(that) )
that = new BigNumber_constructor(that);
return this.add( that.negate() );
}
function BigNumber_multiply ( that ) {
if ( !is_big_number(that) )
that = new BigNumber_constructor(that);
if ( !this.sign || !that.sign )
return BigNumber_ZERO;
var abitlen = this.bitLength, alimbs = this.limbs, alimbcnt = alimbs.length,
bbitlen = that.bitLength, blimbs = that.limbs, blimbcnt = blimbs.length,
rbitlen, rlimbcnt, result = new BigNumber_constructor;
rbitlen = abitlen + bbitlen;
rlimbcnt = ( rbitlen + 31 ) >> 5;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc( alimbcnt<<2 ),
pB = _bigint_asm.salloc( blimbcnt<<2 ),
pR = _bigint_asm.salloc( rlimbcnt<<2 );
_bigint_asm.z( pR-pA+(rlimbcnt<<2), 0, pA );
_bigint_heap.set( alimbs, pA>>2 );
_bigint_heap.set( blimbs, pB>>2 );
_bigint_asm.mul( pA, alimbcnt<<2, pB, blimbcnt<<2, pR, rlimbcnt<<2 );
result.limbs = new Uint32Array( _bigint_heap.subarray( pR>>2, (pR>>2)+rlimbcnt ) );
result.sign = this.sign * that.sign;
result.bitLength = rbitlen;
return result;
}
function BigNumber_square () {
if ( !this.sign )
return BigNumber_ZERO;
var abitlen = this.bitLength, alimbs = this.limbs, alimbcnt = alimbs.length,
rbitlen, rlimbcnt, result = new BigNumber_constructor;
rbitlen = abitlen << 1;
rlimbcnt = ( rbitlen + 31 ) >> 5;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc( alimbcnt<<2 ),
pR = _bigint_asm.salloc( rlimbcnt<<2 );
_bigint_asm.z( pR-pA+(rlimbcnt<<2), 0, pA );
_bigint_heap.set( alimbs, pA>>2 );
_bigint_asm.sqr( pA, alimbcnt<<2, pR );
result.limbs = new Uint32Array( _bigint_heap.subarray( pR>>2, (pR>>2)+rlimbcnt ) );
result.bitLength = rbitlen;
result.sign = 1;
return result;
}
function BigNumber_divide ( that ) {
if ( !is_big_number(that) )
that = new BigNumber_constructor(that);
var abitlen = this.bitLength, alimbs = this.limbs, alimbcnt = alimbs.length,
bbitlen = that.bitLength, blimbs = that.limbs, blimbcnt = blimbs.length,
qlimbcnt, rlimbcnt, quotient = BigNumber_ZERO, remainder = BigNumber_ZERO;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc( alimbcnt<<2 ),
pB = _bigint_asm.salloc( blimbcnt<<2 ),
pQ = _bigint_asm.salloc( alimbcnt<<2 );
_bigint_asm.z( pQ-pA+(alimbcnt<<2), 0, pA );
_bigint_heap.set( alimbs, pA>>2 );
_bigint_heap.set( blimbs, pB>>2 );
_bigint_asm.div( pA, alimbcnt<<2, pB, blimbcnt<<2, pQ );
qlimbcnt = _bigint_asm.tst( pQ, alimbcnt<<2 )>>2;
if ( qlimbcnt ) {
quotient = new BigNumber_constructor;
quotient.limbs = new Uint32Array( _bigint_heap.subarray( pQ>>2, (pQ>>2)+qlimbcnt ) );
quotient.bitLength = abitlen < (qlimbcnt<<5) ? abitlen : (qlimbcnt<<5);
quotient.sign = this.sign * that.sign;
}
rlimbcnt = _bigint_asm.tst( pA, blimbcnt<<2 )>>2;
if ( rlimbcnt ) {
remainder = new BigNumber_constructor;
remainder.limbs = new Uint32Array( _bigint_heap.subarray( pA>>2, (pA>>2)+rlimbcnt ) );
remainder.bitLength = bbitlen < (rlimbcnt<<5) ? bbitlen : (rlimbcnt<<5);
remainder.sign = this.sign;
}
return {
quotient: quotient,
remainder: remainder
};
}
///////////////////////////////////////////////////////////////////////////////
var BigNumberPrototype = BigNumber_constructor.prototype = new Number;
BigNumberPrototype.toString = BigNumber_toString;
BigNumberPrototype.toBytes = BigNumber_toBytes;
BigNumberPrototype.valueOf = BigNumber_valueOf;
BigNumberPrototype.clamp = BigNumber_clamp;
BigNumberPrototype.slice = BigNumber_slice;
///////////////////////////////////////////////////////////////////////////////
BigNumberPrototype.negate = BigNumber_negate;
BigNumberPrototype.compare = BigNumber_compare;
BigNumberPrototype.add = BigNumber_add;
BigNumberPrototype.subtract = BigNumber_subtract;
BigNumberPrototype.multiply = BigNumber_multiply;
BigNumberPrototype.square = BigNumber_square;
BigNumberPrototype.divide = BigNumber_divide;
///////////////////////////////////////////////////////////////////////////////
var BigNumber_ZERO = new BigNumber_constructor(0);
var BigNumber_ONE = new BigNumber_constructor(1);
Object.freeze(BigNumber_ZERO);
Object.freeze(BigNumber_ONE);
function Number_extGCD (a, b ) {
var sa = ( a < 0 ) ? -1 : 1,
sb = ( b < 0 ) ? -1 : 1,
xi = 1, xj = 0,
yi = 0, yj = 1,
r, q, t, a_cmp_b;
a *= sa;
b *= sb;
a_cmp_b = ( a < b );
if ( a_cmp_b ) {
t = a; a = b, b = t;
t = sa; sa = sb; sb = t;
}
q = Math.floor( a / b ), r = a - q*b;
while ( r ) {
t = xi - q*xj, xi = xj, xj = t;
t = yi - q*yj, yi = yj, yj = t;
a = b, b = r;
q = Math.floor( a / b ), r = a - q*b;
}
xj *= sa;
yj *= sb;
if ( a_cmp_b ) {
t = xj; xj = yj, yj = t;
}
return {
gcd: b,
x: xj,
y: yj
};
}
function BigNumber_extGCD ( a, b ) {
if ( !is_big_number(a) )
a = new BigNumber_constructor(a);
if ( !is_big_number(b) )
b = new BigNumber_constructor(b);
var sa = a.sign, sb = b.sign;
if ( sa < 0 )
a = a.negate();
if ( sb < 0 )
b = b.negate();
var a_cmp_b = a.compare(b);
if ( a_cmp_b < 0 ) {
var t = a; a = b, b = t;
t = sa; sa = sb; sb = t;
}
var xi = BigNumber_ONE, xj = BigNumber_ZERO, lx = b.bitLength,
yi = BigNumber_ZERO, yj = BigNumber_ONE, ly = a.bitLength,
z, r, q;
z = a.divide(b);
while ( (r = z.remainder) !== BigNumber_ZERO ) {
q = z.quotient;
z = xi.subtract( q.multiply(xj).clamp(lx) ).clamp(lx), xi = xj, xj = z;
z = yi.subtract( q.multiply(yj).clamp(ly) ).clamp(ly), yi = yj, yj = z;
a = b, b = r;
z = a.divide(b);
}
if ( sa < 0 )
xj = xj.negate();
if ( sb < 0 )
yj = yj.negate();
if ( a_cmp_b < 0 ) {
var t = xj; xj = yj, yj = t;
}
return {
gcd: b,
x: xj,
y: yj
};
}
/**
* Modulus
*/
function Modulus () {
BigNumber_constructor.apply( this, arguments );
if ( this.valueOf() < 1 )
throw new RangeError();
if ( this.bitLength <= 32 )
return;
var comodulus;
if ( this.limbs[0] & 1 ) {
var bitlen = ( (this.bitLength+31) & -32 ) + 1, limbs = new Uint32Array( (bitlen+31) >> 5 );
limbs[limbs.length-1] = 1;
comodulus = new BigNumber_constructor();
comodulus.sign = 1;
comodulus.bitLength = bitlen;
comodulus.limbs = limbs;
var k = Number_extGCD( 0x100000000, this.limbs[0] ).y;
this.coefficient = k < 0 ? -k : 0x100000000-k;
}
else {
/**
* TODO even modulus reduction
* Modulus represented as `N = 2^U * V`, where `V` is odd and thus `GCD(2^U, V) = 1`.
* Calculation `A = TR' mod V` is made as for odd modulo using Montgomery method.
* Calculation `B = TR' mod 2^U` is easy as modulus is a power of 2.
* Using Chinese Remainder Theorem and Garner's Algorithm restore `TR' mod N` from `A` and `B`.
*/
return;
}
this.comodulus = comodulus;
this.comodulusRemainder = comodulus.divide(this).remainder;
this.comodulusRemainderSquare = comodulus.square().divide(this).remainder;
}
/**
* Modular reduction
*/
function Modulus_reduce ( a ) {
if ( !is_big_number(a) )
a = new BigNumber_constructor(a);
if ( a.bitLength <= 32 && this.bitLength <= 32 )
return new BigNumber_constructor( a.valueOf() % this.valueOf() );
if ( a.compare(this) < 0 )
return a;
return a.divide(this).remainder;
}
/**
* Modular inverse
*/
function Modulus_inverse ( a ) {
a = this.reduce(a);
var r = BigNumber_extGCD( this, a );
if ( r.gcd.valueOf() !== 1 ) return null;
r = r.y;
if ( r.sign < 0 ) r = r.add(this).clamp(this.bitLength);
return r;
}
/**
* Modular exponentiation
*/
function Modulus_power ( g, e ) {
if ( !is_big_number(g) )
g = new BigNumber_constructor(g);
if ( !is_big_number(e) )
e = new BigNumber_constructor(e);
// count exponent set bits
var c = 0;
for ( var i = 0; i < e.limbs.length; i++ ) {
var t = e.limbs[i];
while ( t ) {
if ( t & 1 ) c++;
t >>>= 1;
}
}
// window size parameter
var k = 8;
if ( e.bitLength <= 4536 ) k = 7;
if ( e.bitLength <= 1736 ) k = 6;
if ( e.bitLength <= 630 ) k = 5;
if ( e.bitLength <= 210 ) k = 4;
if ( e.bitLength <= 60 ) k = 3;
if ( e.bitLength <= 12 ) k = 2;
if ( c <= (1 << (k-1)) ) k = 1;
// montgomerize base
g = _Montgomery_reduce( this.reduce(g).multiply(this.comodulusRemainderSquare), this );
// precompute odd powers
var g2 = _Montgomery_reduce( g.square(), this ),
gn = new Array( 1 << (k-1) );
gn[0] = g;
gn[1] = _Montgomery_reduce( g.multiply(g2), this );
for ( var i = 2; i < (1 << (k-1)); i++ ) {
gn[i] = _Montgomery_reduce( gn[i-1].multiply(g2), this );
}
// perform exponentiation
var u = this.comodulusRemainder,
r = u;
for ( var i = e.limbs.length-1; i >= 0; i-- ) {
var t = e.limbs[i];
for ( var j = 32; j > 0; ) {
if ( t & 0x80000000 ) {
var n = t >>> (32-k), l = k;
while ( (n & 1) === 0 ) { n >>>= 1; l--; }
var m = gn[n>>>1];
while ( n ) { n >>>= 1; if ( r !== u ) r = _Montgomery_reduce( r.square(), this ); }
r = ( r !== u ) ? _Montgomery_reduce( r.multiply(m), this ) : m;
t <<= l, j -= l;
}
else {
if ( r !== u ) r = _Montgomery_reduce( r.square(), this );
t <<= 1, j--;
}
}
}
// de-montgomerize result
r = _Montgomery_reduce( r, this );
return r;
}
function _Montgomery_reduce ( a, n ) {
var alimbs = a.limbs, alimbcnt = alimbs.length,
nlimbs = n.limbs, nlimbcnt = nlimbs.length,
y = n.coefficient;
_bigint_asm.sreset();
var pA = _bigint_asm.salloc( alimbcnt<<2 ),
pN = _bigint_asm.salloc( nlimbcnt<<2 ),
pR = _bigint_asm.salloc( nlimbcnt<<2 );
_bigint_asm.z( pR-pA+(nlimbcnt<<2), 0, pA );
_bigint_heap.set( alimbs, pA>>2 );
_bigint_heap.set( nlimbs, pN>>2 );
_bigint_asm.mredc( pA, alimbcnt<<2, pN, nlimbcnt<<2, y, pR );
var result = new BigNumber_constructor();
result.limbs = new Uint32Array( _bigint_heap.subarray( pR>>2, (pR>>2)+nlimbcnt ) );
result.bitLength = n.bitLength;
result.sign = 1;
return result;
}
var ModulusPrototype = Modulus.prototype = new BigNumber_constructor;
ModulusPrototype.reduce = Modulus_reduce;
ModulusPrototype.inverse = Modulus_inverse;
ModulusPrototype.power = Modulus_power;
// Tests if the number supplied is a Miller-Rabin strong probable prime
function _BigNumber_isMillerRabinProbablePrime (rounds ) {
var t = new BigNumber_constructor(this),
s = 0;
t.limbs[0] -= 1;
while ( t.limbs[s>>5] === 0 ) s += 32;
while ( ( ( t.limbs[s>>5] >> (s & 31) ) & 1 ) === 0 ) s++;
t = t.slice(s);
var m = new Modulus(this),
m1 = this.subtract(BigNumber_constructor.ONE),
a = new BigNumber_constructor(this),
l = this.limbs.length-1;
while ( a.limbs[l] === 0 ) l--;
while ( --rounds >= 0 ) {
Random_getValues(a.limbs);
if ( a.limbs[0] < 2 ) a.limbs[0] += 2;
while ( a.compare(m1) >= 0 ) a.limbs[l] >>>= 1;
var x = m.power( a, t );
if ( x.compare(BigNumber_constructor.ONE) === 0 ) continue;
if ( x.compare(m1) === 0 ) continue;
var c = s;
while ( --c > 0 ) {
x = x.square().divide(m).remainder;
if ( x.compare(BigNumber_constructor.ONE) === 0 ) return false;
if ( x.compare(m1) === 0 ) break;
}
if ( c === 0 ) return false;
}
return true;
}
function BigNumber_isProbablePrime ( paranoia ) {
paranoia = paranoia || 80;
var limbs = this.limbs,
i = 0;
// Oddity test
// (50% false positive probability)
if ( ( limbs[0] & 1 ) === 0 ) return false;
if ( paranoia <= 1 ) return true;
// Magic divisors (3, 5, 17) test
// (~25% false positive probability)
var s3 = 0, s5 = 0, s17 = 0;
for ( i = 0; i < limbs.length; i++ ) {
var l3 = limbs[i];
while ( l3 ) {
s3 += (l3 & 3);
l3 >>>= 2;
}
var l5 = limbs[i];
while ( l5 ) {
s5 += (l5 & 3);
l5 >>>= 2;
s5 -= (l5 & 3);
l5 >>>= 2;
}
var l17 = limbs[i];
while ( l17 ) {
s17 += (l17 & 15);
l17 >>>= 4;
s17 -= (l17 & 15);
l17 >>>= 4;
}
}
if ( !(s3 % 3) || !(s5 % 5) || !(s17 % 17) ) return false;
if ( paranoia <= 2 ) return true;
// Miller-Rabin test
// (≤ 4^(-k) false positive probability)
return _BigNumber_isMillerRabinProbablePrime.call( this, paranoia >>> 1 );
}
// Small primes for trail division
var _primes = [ 2, 3 /* and so on, computed lazily */ ];
// Returns an array populated with first n primes.
function _small_primes ( n ) {
if ( _primes.length >= n )
return _primes.slice( 0, n );
for ( var p = _primes[_primes.length-1] + 2; _primes.length < n; p += 2 ) {
for ( var i = 0, d = _primes[i]; d*d <= p; d = _primes[++i] ) {
if ( p % d == 0 ) break;
}
if ( d*d > p ) _primes.push(p);
}
return _primes;
}
// Returns strong pseudoprime of a specified bit length
function BigNumber_randomProbablePrime ( bitlen, filter ) {
var limbcnt = (bitlen + 31) >> 5,
prime = new BigNumber_constructor({ sign: 1, bitLength: bitlen, limbs: limbcnt }),
limbs = prime.limbs;
// Number of small divisors to try that minimizes the total cost of the trial division
// along with the first round of Miller-Rabin test for a certain bit length.
var k = 10000;
if ( bitlen <= 512 ) k = 2200;
if ( bitlen <= 256 ) k = 600;
var divisors = _small_primes(k),
remainders = new Uint32Array(k);
// Number of Miller-Rabin iterations for an error rate of less than 2^-80
// Damgaard, Landrock, Pomerance: Average case error estimates for the strong probable prime test.
var s = (bitlen * Math.LN2) | 0,
r = 27;
if ( bitlen >= 250 ) r = 12;
if ( bitlen >= 450 ) r = 6;
if ( bitlen >= 850 ) r = 3;
if ( bitlen >= 1300 ) r = 2;
while ( true ) {
// populate `prime` with random bits, clamp to the appropriate bit length
Random_getValues(limbs);
limbs[0] |= 1;
limbs[limbcnt-1] |= 1 << ((bitlen - 1) & 31);
if ( bitlen & 31 ) limbs[limbcnt-1] &= pow2_ceil((bitlen + 1) & 31) - 1;
// remainders from division to small primes
remainders[0] = 1;
for ( var i = 1; i < k; i++ ) {
remainders[i] = prime.divide( divisors[i] ).remainder.valueOf();
}
// try no more than `s` subsequent candidates
seek:
for ( var j = 0; j < s; j += 2, limbs[0] += 2 ) {
// check for small factors
for ( var i = 1; i < k; i++ ) {
if ( ( remainders[i] + j ) % divisors[i] === 0 ) continue seek;
}
// additional check just before the heavy lifting
if ( typeof filter === 'function' && !filter(prime) ) continue;
// proceed to Miller-Rabin test
if ( _BigNumber_isMillerRabinProbablePrime.call( prime, r ) ) return prime;
}
}
}
BigNumber_constructor.prototype.isProbablePrime = BigNumber_isProbablePrime;
BigNumber_constructor.randomProbablePrime = BigNumber_randomProbablePrime;
var BigNumber = BigNumber_constructor;
BigNumber.ZERO = BigNumber_ZERO;
BigNumber.ONE = BigNumber_ONE;
BigNumber.extGCD = BigNumber_extGCD;
function RSA_reset ( options ) {
options = options || {};
this.result = null;
var key = options.key;
if ( key !== undefined ) {
if ( key instanceof Array ) {
var l = key.length;
if ( l !== 2 && l !== 3 && l !== 8 )
throw new SyntaxError("unexpected key type");
var k = [];
k[0] = new Modulus( key[0] );
k[1] = new BigNumber_constructor( key[1] );
if ( l > 2 ) {
k[2] = new BigNumber_constructor( key[2] );
}
if ( l > 3 ) {
k[3] = new Modulus( key[3] );
k[4] = new Modulus( key[4] );
k[5] = new BigNumber_constructor( key[5] );
k[6] = new BigNumber_constructor( key[6] );
k[7] = new BigNumber_constructor( key[7] );
}
this.key = k;
}
else {
throw new TypeError("unexpected key type");
}
}
return this;
}
function RSA_encrypt ( data ) {
if ( !this.key )
throw new IllegalStateError("no key is associated with the instance");
if ( is_string(data) )
data = string_to_bytes(data);
if ( is_buffer(data) )
data = new Uint8Array(data);
var msg;
if ( is_bytes(data) ) {
msg = new BigNumber_constructor(data);
}
else if ( is_big_number(data) ) {
msg = data;
}
else {
throw new TypeError("unexpected data type");
}
if ( this.key[0].compare(msg) <= 0 )
throw new RangeError("data too large");
var m = this.key[0],
e = this.key[1];
var result = m.power( msg, e ).toBytes();
var bytelen = m.bitLength + 7 >> 3;
if ( result.length < bytelen ) {
var r = new Uint8Array(bytelen);
r.set( result, bytelen - result.length );
result = r;
}
this.result = result;
return this;
}
function RSA_decrypt ( data ) {
if ( !this.key )
throw new IllegalStateError("no key is associated with the instance");
if ( this.key.length < 3 )
throw new IllegalStateError("key isn't suitable for decription");
if ( is_string(data) )
data = string_to_bytes(data);
if ( is_buffer(data) )
data = new Uint8Array(data);
var msg;
if ( is_bytes(data) ) {
msg = new BigNumber_constructor(data);
}
else if ( is_big_number(data) ) {
msg = data;
}
else {
throw new TypeError("unexpected data type");
}
if ( this.key[0].compare(msg) <= 0 )
throw new RangeError("data too large");
var result;
if ( this.key.length > 3 ) {
var m = this.key[0],
p = this.key[3],
q = this.key[4],
dp = this.key[5],
dq = this.key[6],
u = this.key[7];
var x = p.power( msg, dp ),
y = q.power( msg, dq );
var t = x.subtract(y);
while ( t.sign < 0 ) t = t.add(p);
var h = p.reduce( u.multiply(t) );
result = h.multiply(q).add(y).clamp(m.bitLength).toBytes();
}
else {
var m = this.key[0],
d = this.key[2];
result = m.power( msg, d ).toBytes();
}
var bytelen = m.bitLength + 7 >> 3;
if ( result.length < bytelen ) {
var r = new Uint8Array(bytelen);
r.set( result, bytelen - result.length );
result = r;
}
this.result = result;
return this;
}
function RSA_OAEP ( options ) {
options = options || {};
if ( !options.hash )
throw new SyntaxError("option 'hash' is required");
if ( !options.hash.HASH_SIZE )
throw new SyntaxError("option 'hash' supplied doesn't seem to be a valid hash function");
this.hash = options.hash;
this.label = null;
this.reset(options);
}
function RSA_OAEP_reset ( options ) {
options = options || {};
var label = options.label;
if ( label !== undefined ) {
if ( is_buffer(label) || is_bytes(label) ) {
label = new Uint8Array(label);
}
else if ( is_string(label) ) {
label = string_to_bytes(label);
}
else {
throw new TypeError("unexpected label type");
}
this.label = ( label.length > 0 ) ? label : null;
}
else {
this.label = null;
}
RSA_reset.call( this, options );
}
function RSA_OAEP_encrypt ( data ) {
if ( !this.key )
throw new IllegalStateError("no key is associated with the instance");
var key_size = Math.ceil( this.key[0].bitLength / 8 ),
hash_size = this.hash.HASH_SIZE,
data_length = data.byteLength || data.length || 0,
ps_length = key_size - data_length - 2*hash_size - 2;
if ( data_length > key_size - 2*this.hash.HASH_SIZE - 2 )
throw new IllegalArgumentError("data too large");
var message = new Uint8Array(key_size),
seed = message.subarray( 1, hash_size + 1 ),
data_block = message.subarray( hash_size + 1 );
if ( is_bytes(data) ) {
data_block.set( data, hash_size + ps_length + 1 );
}
else if ( is_buffer(data) ) {
data_block.set( new Uint8Array(data), hash_size + ps_length + 1 );
}
else if ( is_string(data) ) {
data_block.set( string_to_bytes(data), hash_size + ps_length + 1 );
}
else {
throw new TypeError("unexpected data type");
}
data_block.set( this.hash.reset().process( this.label || '' ).finish().result, 0 );
data_block[ hash_size + ps_length ] = 1;
Random_getValues(seed);
var data_block_mask = RSA_MGF1_generate.call( this, seed, data_block.length );
for ( var i = 0; i < data_block.length; i++ )
data_block[i] ^= data_block_mask[i];
var seed_mask = RSA_MGF1_generate.call( this, data_block, seed.length );
for ( var i = 0; i < seed.length; i++ )
seed[i] ^= seed_mask[i];
RSA_encrypt.call( this, message );
return this;
}
function RSA_OAEP_decrypt ( data ) {
if ( !this.key )
throw new IllegalStateError("no key is associated with the instance");
var key_size = Math.ceil( this.key[0].bitLength / 8 ),
hash_size = this.hash.HASH_SIZE,
data_length = data.byteLength || data.length || 0;
if ( data_length !== key_size )
throw new IllegalArgumentError("bad data");
RSA_decrypt.call( this, data );
var z = this.result[0],
seed = this.result.subarray( 1, hash_size + 1 ),
data_block = this.result.subarray( hash_size + 1 );
if ( z !== 0 )
throw new SecurityError("decryption failed");
var seed_mask = RSA_MGF1_generate.call( this, data_block, seed.length );
for ( var i = 0; i < seed.length; i++ )
seed[i] ^= seed_mask[i];
var data_block_mask = RSA_MGF1_generate.call( this, seed, data_block.length );
for ( var i = 0; i < data_block.length; i++ )
data_block[i] ^= data_block_mask[i];
var lhash = this.hash.reset().process( this.label || '' ).finish().result;
for ( var i = 0; i < hash_size; i++ ) {
if ( lhash[i] !== data_block[i] )
throw new SecurityError("decryption failed");
}
var ps_end = hash_size;
for ( ; ps_end < data_block.length; ps_end++ ) {
var psz = data_block[ps_end];
if ( psz === 1 )
break;
if ( psz !== 0 )
throw new SecurityError("decryption failed");
}
if ( ps_end === data_block.length )
throw new SecurityError("decryption failed");
this.result = data_block.subarray( ps_end + 1 );
return this;
}
function RSA_MGF1_generate( seed, length ) {
seed = seed || '';
length = length || 0;
var hash_size = this.hash.HASH_SIZE;
// if ( length > (hash_size * 0x100000000) )
// throw new IllegalArgumentError("mask length too large");
var mask = new Uint8Array(length),
counter = new Uint8Array(4),
chunks = Math.ceil( length / hash_size );
for ( var i = 0; i < chunks; i++ ) {
counter[0] = i >>> 24, counter[1] = (i >>> 16) & 255, counter[2] = (i >>> 8) & 255, counter[3] = i & 255;
var submask = mask.subarray( i * hash_size );
var chunk = this.hash.reset().process(seed).process(counter).finish().result;
if ( chunk.length > submask.length ) chunk = chunk.subarray( 0, submask.length );
submask.set(chunk);
}
return mask;
}
function RSA_PSS ( options ) {
options = options || {};
if ( !options.hash )
throw new SyntaxError("option 'hash' is required");
if ( !options.hash.HASH_SIZE )
throw new SyntaxError("option 'hash' supplied doesn't seem to be a valid hash function");
this.hash = options.hash;
this.saltLength = 4;
this.reset(options);
}
function RSA_PSS_reset ( options ) {
options = options || {};
RSA_reset.call( this, options );
var slen = options.saltLength;
if ( slen !== undefined ) {
if ( !is_number(slen) || slen < 0 )
throw new TypeError("saltLength should be a non-negative number");
if ( this.key !== null && Math.ceil( ( this.key[0].bitLength - 1 ) / 8 ) < this.hash.HASH_SIZE + slen + 2 )
throw new SyntaxError("saltLength is too large");
this.saltLength = slen;
}
else {
this.saltLength = 4;
}
}
function RSA_PSS_sign ( data ) {
if ( !this.key )
throw new IllegalStateError("no key is associated with the instance");
var key_bits = this.key[0].bitLength,
hash_size = this.hash.HASH_SIZE,
message_length = Math.ceil( ( key_bits - 1 ) / 8 ),
salt_length = this.saltLength,
ps_length = message_length - salt_length - hash_size - 2;
var message = new Uint8Array(message_length),
h_block = message.subarray( message_length - hash_size - 1, message_length - 1 ),
d_block = message.subarray( 0, message_length - hash_size - 1 ),
d_salt = d_block.subarray( ps_length + 1 );
var m_block = new Uint8Array( 8 + hash_size + salt_length ),
m_hash = m_block.subarray( 8, 8 + hash_size ),
m_salt = m_block.subarray( 8 + hash_size );
m_hash.set( this.hash.reset().process(data).finish().result );
if ( salt_length > 0 )
Random_getValues(m_salt);
d_block[ps_length] = 1;
d_salt.set(m_salt);
h_block.set( this.hash.reset().process(m_block).finish().result );
var d_block_mask = RSA_MGF1_generate.call( this, h_block, d_block.length );
for ( var i = 0; i < d_block.length; i++ )
d_block[i] ^= d_block_mask[i];
message[message_length-1] = 0xbc;
var zbits = 8*message_length - key_bits + 1;
if ( zbits % 8 ) message[0] &= (0xff >>> zbits);
RSA_decrypt.call( this, message );
return this;
}
function RSA_PSS_verify ( signature, data ) {
if ( !this.key )
throw new IllegalStateError("no key is associated with the instance");
var key_bits = this.key[0].bitLength,
hash_size = this.hash.HASH_SIZE,
message_length = Math.ceil( ( key_bits - 1 ) / 8 ),
salt_length = this.saltLength,
ps_length = message_length - salt_length - hash_size - 2;
RSA_encrypt.call( this, signature );
var message = this.result;
if ( message[message_length-1] !== 0xbc )
throw new SecurityError("bad signature");
var h_block = message.subarray( message_length - hash_size - 1, message_length - 1 ),
d_block = message.subarray( 0, message_length - hash_size - 1 ),
d_salt = d_block.subarray( ps_length + 1 );
var zbits = 8*message_length - key_bits + 1;
if ( (zbits % 8) && (message[0] >>> (8-zbits)) )
throw new SecurityError("bad signature");
var d_block_mask = RSA_MGF1_generate.call( this, h_block, d_block.length );
for ( var i = 0; i < d_block.length; i++ )
d_block[i] ^= d_block_mask[i];
if ( zbits % 8 ) message[0] &= (0xff >>> zbits);
for ( var i = 0; i < ps_length; i++ ) {
if ( d_block[i] !== 0 )
throw new SecurityError("bad signature");
}
if ( d_block[ps_length] !== 1 )
throw new SecurityError("bad signature");
var m_block = new Uint8Array( 8 + hash_size + salt_length ),
m_hash = m_block.subarray( 8, 8 + hash_size ),
m_salt = m_block.subarray( 8 + hash_size );
m_hash.set( this.hash.reset().process(data).finish().result );
m_salt.set( d_salt );
var h_block_verify = this.hash.reset().process(m_block).finish().result;
for ( var i = 0; i < hash_size; i++ ) {
if ( h_block[i] !== h_block_verify[i] )
throw new SecurityError("bad signature");
}
return this;
}
var RSA_OAEP_prototype = RSA_OAEP.prototype;
RSA_OAEP_prototype.reset = RSA_OAEP_reset;
RSA_OAEP_prototype.encrypt = RSA_OAEP_encrypt;
RSA_OAEP_prototype.decrypt = RSA_OAEP_decrypt;
var RSA_PSS_prototype = RSA_PSS.prototype;
RSA_PSS_prototype.reset = RSA_PSS_reset;
RSA_PSS_prototype.sign = RSA_PSS_sign;
RSA_PSS_prototype.verify = RSA_PSS_verify;
var _global_console$1 = typeof console !== 'undefined' ? console : undefined;
var _secure_origin = (typeof location === "undefined") || !location.protocol.search( /https:|file:|chrome:|chrome-extension:|moz-extension:/ );
if ( !_secure_origin && _global_console$1 !== undefined ) {
_global_console$1.warn("asmCrypto seems to be load from an insecure origin; this may cause to MitM-attack vulnerability. Consider using secure transport protocol.");
}
exports.string_to_bytes = string_to_bytes;
exports.hex_to_bytes = hex_to_bytes;
exports.base64_to_bytes = base64_to_bytes;
exports.bytes_to_string = bytes_to_string;
exports.bytes_to_hex = bytes_to_hex;
exports.bytes_to_base64 = bytes_to_base64;
exports.IllegalStateError = IllegalStateError;
exports.IllegalArgumentError = IllegalArgumentError;
exports.SecurityError = SecurityError;
exports.AES_CBC = AES_CBC;
exports.AES_GCM = AES_GCM;
exports.SHA1 = SHA1;
exports.SHA256 = SHA256;
exports.HMAC_SHA1 = HMAC_SHA1;
exports.HMAC_SHA256 = HMAC_SHA256;
exports.PBKDF2 = PBKDF2;
exports.PBKDF2_HMAC_SHA1 = PBKDF2_HMAC_SHA1;
exports.PBKDF2_HMAC_SHA256 = PBKDF2_HMAC_SHA256;
exports.Random_seed = Random_seed;
exports.Random_getValues = Random_getValues;
exports.Random_getNumber = Random_getNumber;
exports.BigNumber = BigNumber;
exports.Modulus = Modulus;
exports.RSA_OAEP = RSA_OAEP;
exports.RSA_PSS = RSA_PSS;
exports.random = Random_getNumber;
exports.getRandomValues = Random_getValues;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=asmcrypto.js.map
|
/* parser generated by jison 0.4.17-144 */
/*
* Returns a Parser object of the following structure:
*
* Parser: {
* yy: {} The so-called "shared state" or rather the *source* of it;
* the real "shared state" `yy` passed around to
* the rule actions, etc. is a derivative/copy of this one,
* not a direct reference!
* }
*
* Parser.prototype: {
* yy: {},
* EOF: 1,
* TERROR: 2,
*
* trace: function(errorMessage, ...),
*
* JisonParserError: function(msg, hash),
*
* quoteName: function(name),
* Helper function which can be overridden by user code later on: put suitable
* quotes around literal IDs in a description string.
*
* originalQuoteName: function(name),
* The basic quoteName handler provided by JISON.
* `cleanupAfterParse()` will clean up and reset `quoteName()` to reference this function
* at the end of the `parse()`.
*
* describeSymbol: function(symbol),
* Return a more-or-less human-readable description of the given symbol, when
* available, or the symbol itself, serving as its own 'description' for lack
* of something better to serve up.
*
* Return NULL when the symbol is unknown to the parser.
*
* symbols_: {associative list: name ==> number},
* terminals_: {associative list: number ==> name},
* nonterminals: {associative list: rule-name ==> {associative list: number ==> rule-alt}},
* terminal_descriptions_: (if there are any) {associative list: number ==> description},
* productions_: [...],
*
* performAction: function parser__performAction(yytext, yyleng, yylineno, yyloc, yy, yystate, $0, $$, _$, yystack, yysstack, ...),
* where `...` denotes the (optional) additional arguments the user passed to
* `parser.parse(str, ...)`
*
* table: [...],
* State transition table
* ----------------------
*
* index levels are:
* - `state` --> hash table
* - `symbol` --> action (number or array)
*
* If the `action` is an array, these are the elements' meaning:
* - index [0]: 1 = shift, 2 = reduce, 3 = accept
* - index [1]: GOTO `state`
*
* If the `action` is a number, it is the GOTO `state`
*
* defaultActions: {...},
*
* parseError: function(str, hash),
* yyErrOk: function(),
* yyClearIn: function(),
*
* constructParseErrorInfo: function(error_message, exception_object, expected_token_set, is_recoverable),
* Helper function **which will be set up during the first invocation of the `parse()` method**.
* Produces a new errorInfo 'hash object' which can be passed into `parseError()`.
* See it's use in this parser kernel in many places; example usage:
*
* var infoObj = parser.constructParseErrorInfo('fail!', null,
* parser.collect_expected_token_set(state), true);
* var retVal = parser.parseError(infoObj.errStr, infoObj);
*
* originalParseError: function(str, hash),
* The basic parseError handler provided by JISON.
* `cleanupAfterParse()` will clean up and reset `parseError()` to reference this function
* at the end of the `parse()`.
*
* options: { ... parser %options ... },
*
* parse: function(input[, args...]),
* Parse the given `input` and return the parsed value (or `true` when none was provided by
* the root action, in which case the parser is acting as a *matcher*).
* You MAY use the additional `args...` parameters as per `%parse-param` spec of this grammar:
* these extra `args...` are passed verbatim to the grammar rules' action code.
*
* cleanupAfterParse: function(resultValue, invoke_post_methods),
* Helper function **which will be set up during the first invocation of the `parse()` method**.
* This helper API is invoked at the end of the `parse()` call, unless an exception was thrown
* and `%options no-try-catch` has been defined for this grammar: in that case this helper MAY
* be invoked by calling user code to ensure the `post_parse` callbacks are invoked and
* the internal parser gets properly garbage collected under these particular circumstances.
*
* lexer: {
* yy: {...}, A reference to the so-called "shared state" `yy` once
* received via a call to the `.setInput(input, yy)` lexer API.
* EOF: 1,
* ERROR: 2,
* JisonLexerError: function(msg, hash),
* parseError: function(str, hash),
* setInput: function(input, [yy]),
* input: function(),
* unput: function(str),
* more: function(),
* reject: function(),
* less: function(n),
* pastInput: function(n),
* upcomingInput: function(n),
* showPosition: function(),
* test_match: function(regex_match_array, rule_index),
* next: function(),
* lex: function(),
* begin: function(condition),
* pushState: function(condition),
* popState: function(),
* topState: function(),
* _currentRules: function(),
* stateStackSize: function(),
*
* options: { ... lexer %options ... },
*
* performAction: function(yy, yy_, $avoiding_name_collisions, YY_START),
* rules: [...],
* conditions: {associative list: name ==> set},
* }
* }
*
*
* token location info (@$, _$, etc.): {
* first_line: n,
* last_line: n,
* first_column: n,
* last_column: n,
* range: [start_number, end_number]
* (where the numbers are indexes into the input string, zero-based)
* }
*
* ---
*
* The parseError function receives a 'hash' object with these members for lexer and
* parser errors:
*
* {
* text: (matched text)
* token: (the produced terminal token, if any)
* token_id: (the produced terminal token numeric ID, if any)
* line: (yylineno)
* loc: (yylloc)
* }
*
* parser (grammar) errors will also provide these additional members:
*
* {
* expected: (array describing the set of expected tokens;
* may be UNDEFINED when we cannot easily produce such a set)
* state: (integer (or array when the table includes grammar collisions);
* represents the current internal state of the parser kernel.
* can, for example, be used to pass to the `collect_expected_token_set()`
* API to obtain the expected token set)
* action: (integer; represents the current internal action which will be executed)
* new_state: (integer; represents the next/planned internal state, once the current
* action has executed)
* recoverable: (boolean: TRUE when the parser MAY have an error recovery rule
* available for this particular error)
* state_stack: (array: the current parser LALR/LR internal state stack; this can be used,
* for instance, for advanced error analysis and reporting)
* value_stack: (array: the current parser LALR/LR internal `$$` value stack; this can be used,
* for instance, for advanced error analysis and reporting)
* location_stack: (array: the current parser LALR/LR internal location stack; this can be used,
* for instance, for advanced error analysis and reporting)
* yy: (object: the current parser internal "shared state" `yy`
* as is also available in the rule actions; this can be used,
* for instance, for advanced error analysis and reporting)
* lexer: (reference to the current lexer instance used by the parser)
* }
*
* while `this` will reference the current parser instance.
*
* When `parseError` is invoked by the lexer, `this` will still reference the related *parser*
* instance, while these additional `hash` fields will also be provided:
*
* {
* lexer: (reference to the current lexer instance which reported the error)
* }
*
* When `parseError` is invoked by the parser due to a **JavaScript exception** being fired
* from either the parser or lexer, `this` will still reference the related *parser*
* instance, while these additional `hash` fields will also be provided:
*
* {
* exception: (reference to the exception thrown)
* }
*
* Please do note that in the latter situation, the `expected` field will be omitted as
* type of failure is assumed not to be due to *parse errors* but rather due to user
* action code in either parser or lexer failing unexpectedly.
*
* ---
*
* You can specify parser options by setting / modifying the `.yy` object of your Parser instance.
* These options are available:
*
* ### options which are global for all parser instances
*
* Parser.pre_parse: function(yy [, optional parse() args])
* optional: you can specify a pre_parse() function in the chunk following
* the grammar, i.e. after the last `%%`.
* Parser.post_parse: function(yy, retval [, optional parse() args]) { return retval; }
* optional: you can specify a post_parse() function in the chunk following
* the grammar, i.e. after the last `%%`. When it does not return any value,
* the parser will return the original `retval`.
*
* ### options which can be set up per parser instance
*
* yy: {
* pre_parse: function(yy [, optional parse() args])
* optional: is invoked before the parse cycle starts (and before the first
* invocation of `lex()`) but immediately after the invocation of
* `parser.pre_parse()`).
* post_parse: function(yy, retval [, optional parse() args]) { return retval; }
* optional: is invoked when the parse terminates due to success ('accept')
* or failure (even when exceptions are thrown).
* `retval` contains the return value to be produced by `Parser.parse()`;
* this function can override the return value by returning another.
* When it does not return any value, the parser will return the original
* `retval`.
* This function is invoked immediately before `Parser.post_parse()`.
*
* parseError: function(str, hash)
* optional: overrides the default `parseError` function.
* quoteName: function(name),
* optional: overrides the default `quoteName` function.
* }
*
* parser.lexer.options: {
* pre_lex: function()
* optional: is invoked before the lexer is invoked to produce another token.
* `this` refers to the Lexer object.
* post_lex: function(token) { return token; }
* optional: is invoked when the lexer has produced a token `token`;
* this function can override the returned token value by returning another.
* When it does not return any (truthy) value, the lexer will return
* the original `token`.
* `this` refers to the Lexer object.
*
* ranges: boolean
* optional: `true` ==> token location info will include a .range[] member.
* flex: boolean
* optional: `true` ==> flex-like lexing behaviour where the rules are tested
* exhaustively to find the longest match.
* backtrack_lexer: boolean
* optional: `true` ==> lexer regexes are tested in order and for invoked;
* the lexer terminates the scan when a token is returned by the action code.
* xregexp: boolean
* optional: `true` ==> lexer rule regexes are "extended regex format" requiring the
* `XRegExp` library. When this %option has not been specified at compile time, all lexer
* rule regexes have been written as standard JavaScript RegExp expressions.
* }
*/
var ccalcParse = (function () {
// See also:
// http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript/#35881508
// but we keep the prototype.constructor and prototype.name assignment lines too for compatibility
// with userland code which might access the derived class in a 'classic' way.
function JisonParserError(msg, hash) {
Object.defineProperty(this, 'name', {
enumerable: false,
writable: false,
value: 'JisonParserError'
});
if (msg == null) msg = '???';
Object.defineProperty(this, 'message', {
enumerable: false,
writable: true,
value: msg
});
this.hash = hash;
var stacktrace;
if (hash && hash.exception instanceof Error) {
var ex2 = hash.exception;
this.message = ex2.message || msg;
stacktrace = ex2.stack;
}
if (!stacktrace) {
if (Error.hasOwnProperty('captureStackTrace')) { // V8
Error.captureStackTrace(this, this.constructor);
} else {
stacktrace = (new Error(msg)).stack;
}
}
if (stacktrace) {
Object.defineProperty(this, 'stack', {
enumerable: false,
writable: false,
value: stacktrace
});
}
}
if (typeof Object.setPrototypeOf === 'function') {
Object.setPrototypeOf(JisonParserError.prototype, Error.prototype);
} else {
JisonParserError.prototype = Object.create(Error.prototype);
}
JisonParserError.prototype.constructor = JisonParserError;
JisonParserError.prototype.name = 'JisonParserError';
// helper: reconstruct the productions[] table
function bp(s) {
var rv = [];
var p = s.pop;
var r = s.rule;
for (var i = 0, l = p.length; i < l; i++) {
rv.push([
p[i],
r[i]
]);
}
return rv;
}
// helper: reconstruct the 'goto' table
function bt(s) {
var rv = [];
var d = s.len;
var y = s.symbol;
var t = s.type;
var a = s.state;
var m = s.mode;
var g = s.goto;
for (var i = 0, l = d.length; i < l; i++) {
var n = d[i];
var q = {};
for (var j = 0; j < n; j++) {
var z = y.shift();
switch (t.shift()) {
case 2:
q[z] = [
m.shift(),
g.shift()
];
break;
case 0:
q[z] = a.shift();
break;
default:
// type === 1: accept
q[z] = [
3
];
}
}
rv.push(q);
}
return rv;
}
// helper: runlength encoding with increment step: code, length: step (default step = 0)
// `this` references an array
function s(c, l, a) {
a = a || 0;
for (var i = 0; i < l; i++) {
this.push(c);
c += a;
}
}
// helper: duplicate sequence from *relative* offset and length.
// `this` references an array
function c(i, l) {
i = this.length - i;
for (l += i; i < l; i++) {
this.push(this[i]);
}
}
// helper: unpack an array using helpers and data, all passed in an array argument 'a'.
function u(a) {
var rv = [];
for (var i = 0, l = a.length; i < l; i++) {
var e = a[i];
// Is this entry a helper function?
if (typeof e === 'function') {
i++;
e.apply(rv, a[i]);
} else {
rv.push(e);
}
}
return rv;
}
var parser = {
trace: function no_op_trace() { },
JisonParserError: JisonParserError,
yy: {},
options: {
type: "lalr",
errorRecoveryTokenDiscardCount: 3
},
symbols_: {
"$accept": 0,
"$end": 1,
"ADD": 12,
"ASSIGN": 7,
"DIV": 14,
"EOF": 1,
"IDENTIFIER": 6,
"LBRACE": 9,
"MULT": 13,
"RBRACE": 10,
"SEMICOLON": 5,
"SUB": 11,
"VALUE": 15,
"error": 2,
"expression": 8,
"program": 3,
"statement": 4
},
terminals_: {
1: "EOF",
2: "error",
5: "SEMICOLON",
6: "IDENTIFIER",
7: "ASSIGN",
9: "LBRACE",
10: "RBRACE",
11: "SUB",
12: "ADD",
13: "MULT",
14: "DIV",
15: "VALUE"
},
TERROR: 2,
EOF: 1,
// internals: defined here so the object *structure* doesn't get modified by parse() et al,
// thus helping JIT compilers like Chrome V8.
originalQuoteName: null,
originalParseError: null,
cleanupAfterParse: null,
constructParseErrorInfo: null,
__reentrant_call_depth: 0, // INTERNAL USE ONLY
// APIs which will be set up depending on user action code analysis:
//yyErrOk: 0,
//yyClearIn: 0,
// Helper APIs
// -----------
// Helper function which can be overridden by user code later on: put suitable quotes around
// literal IDs in a description string.
quoteName: function parser_quoteName(id_str) {
return '"' + id_str + '"';
},
// Return a more-or-less human-readable description of the given symbol, when available,
// or the symbol itself, serving as its own 'description' for lack of something better to serve up.
//
// Return NULL when the symbol is unknown to the parser.
describeSymbol: function parser_describeSymbol(symbol) {
if (symbol !== this.EOF && this.terminal_descriptions_ && this.terminal_descriptions_[symbol]) {
return this.terminal_descriptions_[symbol];
}
else if (symbol === this.EOF) {
return 'end of input';
}
else if (this.terminals_[symbol]) {
return this.quoteName(this.terminals_[symbol]);
}
// Otherwise... this might refer to a RULE token i.e. a non-terminal: see if we can dig that one up.
//
// An example of this may be where a rule's action code contains a call like this:
//
// parser.describeSymbol(#$)
//
// to obtain a human-readable description or name of the current grammar rule. This comes handy in
// error handling action code blocks, for example.
var s = this.symbols_;
for (var key in s) {
if (s[key] === symbol) {
return key;
}
}
return null;
},
// Produce a (more or less) human-readable list of expected tokens at the point of failure.
//
// The produced list may contain token or token set descriptions instead of the tokens
// themselves to help turning this output into something that easier to read by humans
// unless `do_not_describe` parameter is set, in which case a list of the raw, *numeric*,
// expected terminals and nonterminals is produced.
//
// The returned list (array) will not contain any duplicate entries.
collect_expected_token_set: function parser_collect_expected_token_set(state, do_not_describe) {
var TERROR = this.TERROR;
var tokenset = [];
var check = {};
// Has this (error?) state been outfitted with a custom expectations description text for human consumption?
// If so, use that one instead of the less palatable token set.
if (!do_not_describe && this.state_descriptions_ && this.state_descriptions_[state]) {
return [
this.state_descriptions_[state]
];
}
for (var p in this.table[state]) {
p = +p;
if (p !== TERROR) {
var d = do_not_describe ? p : this.describeSymbol(p);
if (d && !check[d]) {
tokenset.push(d);
check[d] = true; // Mark this token description as already mentioned to prevent outputting duplicate entries.
}
}
}
return tokenset;
},
productions_: bp({
pop: u([
s,
[3, 3],
4,
4,
s,
[8, 8]
]),
rule: u([
3,
2,
4,
3,
1,
3,
2,
s,
[3, 4],
1,
1
])
}),
performAction: function parser__PerformAction(yytext, yyloc, yy, yystate /* action[1] */, $0, $$ /* vstack */, _$ /* lstack */) {
/* this == yyval */
switch (yystate) {
case 3:
/*! Production:: program : statement error SEMICOLON program */
yy.parser.yyErrOk();
break;
case 4:
/*! Production:: statement : IDENTIFIER ASSIGN expression */
VarSetValue(var, $$[$0]);
break;
case 6:
/*! Production:: expression : LBRACE expression RBRACE */
this.$ = $$[$0 - 1];
break;
case 7:
/*! Production:: expression : SUB expression */
this.$ = - $$[$0];
break;
case 8:
/*! Production:: expression : expression ADD expression */
this.$ = ReduceAdd($$[$0 - 2], $$[$0], &_$[$0]);
if ( debug )
printf("reduce %lf + %lf => %lf\n", $$[$0 - 2], $$[$0], this.$);
break;
case 9:
/*! Production:: expression : expression SUB expression */
this.$ = ReduceSub($$[$0 - 2], $$[$0], &_$[$0]);
if ( debug )
printf("reduce %lf - %lf => %lf\n", $$[$0 - 2], $$[$0], this.$);
break;
case 10:
/*! Production:: expression : expression MULT expression */
this.$ = ReduceMult($$[$0 - 2], $$[$0], &_$[$0]);
if ( debug )
printf("reduce %lf * %lf => %lf\n", $$[$0 - 2], $$[$0], this.$);
break;
case 11:
/*! Production:: expression : expression DIV expression */
this.$ = ReduceDiv($$[$0 - 2], $$[$0], &_$[$0]);
if ( debug )
printf("reduce %lf / %lf => %lf\n", $$[$0 - 2], $$[$0], this.$);
break;
case 12:
/*! Production:: expression : VALUE */
this.$ = $$[$0];
break;
case 13:
/*! Production:: expression : IDENTIFIER */
this.$ = VarGetValue($$[$0], &_$[$0]);
if ( debug )
printf("identifier %s => %lf\n", $$[$0], this.$);
break;
}
},
table: bt({
len: u([
7,
1,
2,
7,
6,
5,
5,
7,
8,
1,
s,
[5, 6],
7,
7,
1,
7,
6,
s,
[7, 5],
1
]),
symbol: u([
3,
4,
6,
8,
9,
11,
15,
1,
2,
5,
2,
5,
7,
s,
[11, 4, 1],
2,
5,
c,
[6, 4],
c,
[21, 5],
c,
[5, 5],
2,
5,
s,
[10, 5, 1],
1,
c,
[41, 7],
5,
c,
[26, 10],
c,
[5, 15],
c,
[39, 5],
c,
[46, 7],
c,
[53, 15],
c,
[84, 6],
c,
[28, 14],
c,
[7, 21],
1
]),
type: u([
0,
0,
2,
0,
s,
[2, 3],
1,
s,
[2, 16],
c,
[21, 4],
c,
[5, 6],
c,
[17, 8],
c,
[41, 6],
c,
[26, 12],
c,
[5, 15],
s,
[2, 19],
c,
[53, 9],
s,
[2, 40]
]),
state: u([
1,
2,
4,
15,
17,
18,
2,
4,
s,
[20, 5, 1],
26,
2,
4
]),
mode: u([
s,
[1, 6],
2,
2,
c,
[3, 3],
s,
[2, 4],
s,
[1, 12],
s,
[2, 8],
s,
[1, 30],
s,
[2, 15],
c,
[78, 7],
c,
[25, 8],
c,
[7, 14],
s,
[2, 17]
]),
goto: u([
3,
5,
6,
7,
9,
8,
13,
13,
10,
s,
[13, 4],
5,
5,
12,
11,
13,
14,
16,
c,
[19, 3],
c,
[4, 4],
s,
[12, 7],
2,
c,
[35, 4],
19,
c,
[21, 8],
c,
[4, 12],
25,
c,
[46, 4],
s,
[13, 7],
s,
[7, 7],
1,
c,
[45, 4],
4,
4,
c,
[25, 4],
s,
[8, 5],
13,
14,
s,
[9, 5],
13,
14,
s,
[10, 7],
s,
[11, 7],
s,
[6, 7],
3
])
}),
defaultActions: {
18: 1,
26: 3
},
parseError: function parseError(str, hash) {
if (hash.recoverable) {
this.trace(str);
hash.destroy(); // destroy... well, *almost*!
// assert('recoverable' in hash);
} else {
throw new this.JisonParserError(str, hash);
}
},
parse: function parse(input) {
var self = this,
stack = new Array(128), // token stack: stores token which leads to state at the same index (column storage)
sstack = new Array(128), // state stack: stores states
vstack = new Array(128), // semantic value stack
lstack = new Array(128), // location stack
table = this.table,
sp = 0; // 'stack pointer': index into the stacks
var recovering = 0; // (only used when the grammar contains error recovery rules)
var TERROR = this.TERROR,
EOF = this.EOF,
ERROR_RECOVERY_TOKEN_DISCARD_COUNT = (this.options.errorRecoveryTokenDiscardCount | 0) || 3;
var NO_ACTION = [0, table.length /* ensures that anyone using this new state will fail dramatically! */];
//this.reductionCount = this.shiftCount = 0;
var lexer;
if (this.__lexer__) {
lexer = this.__lexer__;
} else {
lexer = this.__lexer__ = Object.create(this.lexer);
}
var sharedState = {
yy: {
parseError: null,
quoteName: null,
lexer: null,
parser: null,
pre_parse: null,
post_parse: null
}
};
// copy state
for (var k in this.yy) {
if (Object.prototype.hasOwnProperty.call(this.yy, k)) {
sharedState.yy[k] = this.yy[k];
}
}
sharedState.yy.lexer = lexer;
sharedState.yy.parser = this;
if (this.yyErrOk === 1) {
this.yyErrOk = function yyErrOk() {
recovering = 0;
};
}
lexer.setInput(input, sharedState.yy);
if (typeof lexer.yylloc === 'undefined') {
lexer.yylloc = {};
}
var yyloc = lexer.yylloc;
lstack[sp] = yyloc;
vstack[sp] = null;
sstack[sp] = 0;
stack[sp] = 0;
++sp;
if (typeof lexer.yytext === 'undefined') {
lexer.yytext = '';
}
var yytext = lexer.yytext;
if (typeof lexer.yylineno === 'undefined') {
lexer.yylineno = 0;
}
var ranges = lexer.options && lexer.options.ranges;
// Does the shared state override the default `parseError` that already comes with this instance?
if (typeof sharedState.yy.parseError === 'function') {
this.parseError = sharedState.yy.parseError;
} else {
this.parseError = this.originalParseError;
}
// Does the shared state override the default `quoteName` that already comes with this instance?
if (typeof sharedState.yy.quoteName === 'function') {
this.quoteName = sharedState.yy.quoteName;
} else {
this.quoteName = this.originalQuoteName;
}
// set up the cleanup function; make it an API so that external code can re-use this one in case of
// calamities or when the `%options no-try-catch` option has been specified for the grammar, in which
// case this parse() API method doesn't come with a `finally { ... }` block any more!
//
// NOTE: as this API uses parse() as a closure, it MUST be set again on every parse() invocation,
// or else your `sharedState`, etc. references will be *wrong*!
//
// The function resets itself to the previous set up one to support reentrant parsers.
this.cleanupAfterParse = function parser_cleanupAfterParse(resultValue, invoke_post_methods) {
var rv;
if (invoke_post_methods) {
if (sharedState.yy.post_parse) {
rv = sharedState.yy.post_parse.call(this, sharedState.yy, resultValue);
if (typeof rv !== 'undefined') resultValue = rv;
}
if (this.post_parse) {
rv = this.post_parse.call(this, sharedState.yy, resultValue);
if (typeof rv !== 'undefined') resultValue = rv;
}
}
if (this.__reentrant_call_depth > 1) return resultValue; // do not (yet) kill the sharedState when this is a reentrant run.
// prevent lingering circular references from causing memory leaks:
if (sharedState.yy) {
sharedState.yy.parseError = undefined;
sharedState.yy.quoteName = undefined;
sharedState.yy.lexer = undefined;
sharedState.yy.parser = undefined;
if (lexer.yy === sharedState.yy) {
lexer.yy = undefined;
}
}
sharedState.yy = undefined;
this.parseError = this.originalParseError;
this.quoteName = this.originalQuoteName;
// nuke the vstack[] array at least as that one will still reference obsoleted user values.
// To be safe, we nuke the other internal stack columns as well...
stack.length = 0; // fastest way to nuke an array without overly bothering the GC
sstack.length = 0;
lstack.length = 0;
vstack.length = 0;
stack_pointer = 0;
return resultValue;
};
// NOTE: as this API uses parse() as a closure, it MUST be set again on every parse() invocation,
// or else your `lexer`, `sharedState`, etc. references will be *wrong*!
this.constructParseErrorInfo = function parser_constructParseErrorInfo(msg, ex, expected, recoverable) {
return {
errStr: msg,
exception: ex,
text: lexer.match,
value: lexer.yytext,
token: this.describeSymbol(symbol) || symbol,
token_id: symbol,
line: lexer.yylineno,
loc: lexer.yylloc,
expected: expected,
recoverable: recoverable,
state: state,
action: action,
new_state: newState,
symbol_stack: stack,
state_stack: sstack,
value_stack: vstack,
location_stack: lstack,
stack_pointer: sp,
yy: sharedState.yy,
lexer: lexer,
// and make sure the error info doesn't stay due to potential ref cycle via userland code manipulations (memory leak opportunity!):
destroy: function destructParseErrorInfo() {
// remove cyclic references added to error info:
// info.yy = null;
// info.lexer = null;
// info.value = null;
// info.value_stack = null;
// ...
var rec = !!this.recoverable;
for (var key in this) {
if (this.hasOwnProperty(key) && typeof key !== 'function') {
this[key] = undefined;
}
}
this.recoverable = rec;
}
};
};
function lex() {
var token = lexer.lex();
// if token isn't its numeric value, convert
if (typeof token !== 'number') {
token = self.symbols_[token] || token;
}
return token || EOF;
}
var symbol = 0;
var preErrorSymbol = 0;
var state, action, r, t;
var yyval = {};
var p, len, this_production;
var lstack_begin, lstack_end;
var newState;
var retval = false;
// Return the rule stack depth where the nearest error rule can be found.
// Return -1 when no error recovery rule was found.
function locateNearestErrorRecoveryRule(state) {
var stack_probe = sp - 1;
var depth = 0;
// try to recover from error
for (;;) {
// check for error recovery rule in this state
var t = table[state][TERROR] || NO_ACTION;
if (t[0]) {
return depth;
}
if (state === 0 /* $accept rule */ || stack_probe < 1) {
return -1; // No suitable error recovery rule available.
}
--stack_probe; // popStack(1): [symbol, action]
state = sstack[stack_probe];
++depth;
}
}
try {
this.__reentrant_call_depth++;
if (this.pre_parse) {
this.pre_parse.call(this, sharedState.yy);
}
if (sharedState.yy.pre_parse) {
sharedState.yy.pre_parse.call(this, sharedState.yy);
}
newState = sstack[sp - 1];
for (;;) {
// retrieve state number from top of stack
state = newState; // sstack[sp - 1];
// use default actions if available
if (this.defaultActions[state]) {
action = 2;
newState = this.defaultActions[state];
} else {
// The single `==` condition below covers both these `===` comparisons in a single
// operation:
//
// if (symbol === null || typeof symbol === 'undefined') ...
if (!symbol) {
symbol = lex();
}
// read action for current state and first input
t = (table[state] && table[state][symbol]) || NO_ACTION;
newState = t[1];
action = t[0];
// handle parse error
if (!action) {
// first see if there's any chance at hitting an error recovery rule:
var error_rule_depth = locateNearestErrorRecoveryRule(state);
var errStr = null;
var errSymbolDescr = (this.describeSymbol(symbol) || symbol);
var expected = this.collect_expected_token_set(state);
if (!recovering) {
// Report error
if (lexer.showPosition) {
errStr = 'Parse error on line ' + (lexer.yylineno + 1) + ':\n' + lexer.showPosition(79 - 10, 10) + '\n';
} else {
errStr = 'Parse error on line ' + (lexer.yylineno + 1) + ': ';
}
if (expected.length) {
errStr += 'Expecting ' + expected.join(', ') + ', got unexpected ' + errSymbolDescr;
} else {
errStr += 'Unexpected ' + errSymbolDescr;
}
p = this.constructParseErrorInfo(errStr, null, expected, (error_rule_depth >= 0));
r = this.parseError(p.errStr, p);
if (!p.recoverable) {
retval = r;
break;
} else {
// TODO: allow parseError callback to edit symbol and or state tat the start of the error recovery process...
}
}
// just recovered from another error
if (recovering === ERROR_RECOVERY_TOKEN_DISCARD_COUNT && error_rule_depth >= 0) {
// only barf a fatal hairball when we're out of look-ahead symbols and none hit a match;
// this DOES discard look-ahead while recovering from an error when said look-ahead doesn't
// suit the error recovery rules... The error HAS been reported already so we're fine with
// throwing away a few items if that is what it takes to match the nearest recovery rule!
if (symbol === EOF || preErrorSymbol === EOF) {
p = this.constructParseErrorInfo((errStr || 'Parsing halted while starting to recover from another error.'), null, expected, false);
retval = this.parseError(p.errStr, p);
break;
}
// discard current lookahead and grab another
yytext = lexer.yytext;
yyloc = lexer.yylloc;
symbol = lex();
}
// try to recover from error
if (error_rule_depth < 0) {
p = this.constructParseErrorInfo((errStr || 'Parsing halted. No suitable error recovery rule available.'), null, expected, false);
retval = this.parseError(p.errStr, p);
break;
}
sp -= error_rule_depth;
preErrorSymbol = (symbol === TERROR ? 0 : symbol); // save the lookahead token
symbol = TERROR; // insert generic error symbol as new lookahead
// allow N (default: 3) real symbols to be shifted before reporting a new error
recovering = ERROR_RECOVERY_TOKEN_DISCARD_COUNT;
newState = sstack[sp - 1];
continue;
}
}
switch (action) {
// catch misc. parse failures:
default:
// this shouldn't happen, unless resolve defaults are off
if (action instanceof Array) {
p = this.constructParseErrorInfo(('Parse Error: multiple actions possible at state: ' + state + ', token: ' + symbol), null, null, false);
retval = this.parseError(p.errStr, p);
break;
}
// Another case of better safe than sorry: in case state transitions come out of another error recovery process
// or a buggy LUT (LookUp Table):
p = this.constructParseErrorInfo('Parsing halted. No viable error recovery approach available due to internal system failure.', null, null, false);
retval = this.parseError(p.errStr, p);
break;
// shift:
case 1:
//this.shiftCount++;
stack[sp] = symbol;
vstack[sp] = lexer.yytext;
lstack[sp] = lexer.yylloc;
sstack[sp] = newState; // push state
++sp;
symbol = 0;
if (!preErrorSymbol) { // normal execution / no error
// Pick up the lexer details for the current symbol as that one is not 'look-ahead' any more:
yytext = lexer.yytext;
yyloc = lexer.yylloc;
if (recovering > 0) {
recovering--;
}
} else {
// error just occurred, resume old lookahead f/ before error, *unless* that drops us straight back into error mode:
symbol = preErrorSymbol;
preErrorSymbol = 0;
// read action for current state and first input
t = (table[newState] && table[newState][symbol]) || NO_ACTION;
if (!t[0]) {
// forget about that symbol and move forward: this wasn't an 'forgot to insert' error type where
// (simple) stuff might have been missing before the token which caused the error we're
// recovering from now...
symbol = 0;
}
}
continue;
// reduce:
case 2:
//this.reductionCount++;
this_production = this.productions_[newState - 1]; // `this.productions_[]` is zero-based indexed while states start from 1 upwards...
len = this_production[1];
lstack_end = sp;
lstack_begin = lstack_end - (len || 1);
lstack_end--;
// Make sure subsequent `$$ = $1` default action doesn't fail
// for rules where len==0 as then there's no $1 (you're reducing an epsilon rule then!)
//
// Also do this to prevent nasty action block codes to *read* `$0` or `$$`
// and *not* get `undefined` as a result for their efforts!
vstack[sp] = undefined;
// perform semantic action
yyval.$ = vstack[sp - len]; // default to $$ = $1; result must produce `undefined` when len == 0, as then there's no $1
// default location, uses first token for firsts, last for lasts
yyval._$ = {
first_line: lstack[lstack_begin].first_line,
last_line: lstack[lstack_end].last_line,
first_column: lstack[lstack_begin].first_column,
last_column: lstack[lstack_end].last_column
};
if (ranges) {
yyval._$.range = [lstack[lstack_begin].range[0], lstack[lstack_end].range[1]];
}
r = this.performAction.call(yyval, yytext, yyloc, sharedState.yy, newState, sp - 1, vstack, lstack);
if (typeof r !== 'undefined') {
retval = r;
break;
}
// pop off stack
sp -= len;
// don't overwrite the `symbol` variable: use a local var to speed things up:
var ntsymbol = this_production[0]; // push nonterminal (reduce)
stack[sp] = ntsymbol;
vstack[sp] = yyval.$;
lstack[sp] = yyval._$;
// goto new state = table[STATE][NONTERMINAL]
newState = table[sstack[sp - 1]][ntsymbol];
sstack[sp] = newState;
++sp;
continue;
// accept:
case 3:
retval = true;
// Return the `$accept` rule's `$$` result, if available.
//
// Also note that JISON always adds this top-most `$accept` rule (with implicit,
// default, action):
//
// $accept: <startSymbol> $end
// %{ $$ = $1; @$ = @1; %}
//
// which, combined with the parse kernel's `$accept` state behaviour coded below,
// will produce the `$$` value output of the <startSymbol> rule as the parse result,
// IFF that result is *not* `undefined`. (See also the parser kernel code.)
//
// In code:
//
// %{
// @$ = @1; // if location tracking support is included
// if (typeof $1 !== 'undefined')
// return $1;
// else
// return true; // the default parse result if the rule actions don't produce anything
// %}
if (typeof yyval.$ !== 'undefined') {
retval = yyval.$;
}
break;
}
// break out of loop: we accept or fail with error
break;
}
} catch (ex) {
// report exceptions through the parseError callback too:
p = this.constructParseErrorInfo('Parsing aborted due to exception.', ex, null, false);
retval = this.parseError(p.errStr, p);
} finally {
retval = this.cleanupAfterParse(retval, true);
this.__reentrant_call_depth--;
}
return retval;
},
yyErrOk: 1
};
parser.originalParseError = parser.parseError;
parser.originalQuoteName = parser.quoteName;
/*! @file lex.l
* @brief Lexical Analysis
*********************************************************************
* a simple calculator with variables
*
* sample-files for a artikel in developerworks.ibm.com
* Author: Christian Hagen, chagen@de.ibm.com
*
* @par parse.l & parse.c
* grammar for the parser-generator bison
*
*********************************************************************
*/
// #define YYERROR_VERBOSE 1
// #define YYDEBUG 1
// int yydebug=0;
/*--------------------------------------------------------------------
*
* global variables
*
*------------------------------------------------------------------*/
static Variable *var;
/*------------------------------------------------------------------------------
*
* functions
*
*----------------------------------------------------------------------------*/
//extern
//void yyerror(char *s) {
// // simple error-message
// // printf("Error '%s'\n", s);
// // a more sophisticated error-function
// PrintError(s);
//}
/*--------------------------------------------------------------------
* parse.y
*------------------------------------------------------------------*/
/* generated by jison-lex 0.3.4-144 */
var lexer = (function () {
// See also:
// http://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript/#35881508
// but we keep the prototype.constructor and prototype.name assignment lines too for compatibility
// with userland code which might access the derived class in a 'classic' way.
function JisonLexerError(msg, hash) {
Object.defineProperty(this, 'name', {
enumerable: false,
writable: false,
value: 'JisonLexerError'
});
if (msg == null) msg = '???';
Object.defineProperty(this, 'message', {
enumerable: false,
writable: true,
value: msg
});
this.hash = hash;
var stacktrace;
if (hash && hash.exception instanceof Error) {
var ex2 = hash.exception;
this.message = ex2.message || msg;
stacktrace = ex2.stack;
}
if (!stacktrace) {
if (Error.hasOwnProperty('captureStackTrace')) { // V8
Error.captureStackTrace(this, this.constructor);
} else {
stacktrace = (new Error(msg)).stack;
}
}
if (stacktrace) {
Object.defineProperty(this, 'stack', {
enumerable: false,
writable: false,
value: stacktrace
});
}
}
if (typeof Object.setPrototypeOf === 'function') {
Object.setPrototypeOf(JisonLexerError.prototype, Error.prototype);
} else {
JisonLexerError.prototype = Object.create(Error.prototype);
}
JisonLexerError.prototype.constructor = JisonLexerError;
JisonLexerError.prototype.name = 'JisonLexerError';
var lexer = {
EOF: 1,
ERROR: 2,
// JisonLexerError: JisonLexerError, // <-- injected by the code generator
// options: {}, // <-- injected by the code generator
// yy: ..., // <-- injected by setInput()
__currentRuleSet__: null, // <-- internal rule set cache for the current lexer state
parseError: function lexer_parseError(str, hash) {
if (this.yy.parser && typeof this.yy.parser.parseError === 'function') {
return this.yy.parser.parseError(str, hash) || this.ERROR;
} else {
throw new this.JisonLexerError(str);
}
},
// clear the lexer token context; intended for internal use only
clear: function lexer_clear() {
this.yytext = '';
this.yyleng = 0;
this.match = '';
this.matches = false;
this._more = false;
this._backtrack = false;
},
// resets the lexer, sets new input
setInput: function lexer_setInput(input, yy) {
this.yy = yy || this.yy || {};
this._input = input;
this.clear();
this._signaled_error_token = this.done = false;
this.yylineno = 0;
this.matched = '';
this.conditionStack = ['INITIAL'];
this.__currentRuleSet__ = null;
this.yylloc = {
first_line: 1,
first_column: 0,
last_line: 1,
last_column: 0
};
if (this.options.ranges) {
this.yylloc.range = [0, 0];
}
this.offset = 0;
return this;
},
// consumes and returns one char from the input
input: function lexer_input() {
if (!this._input) {
this.done = true;
return null;
}
var ch = this._input[0];
this.yytext += ch;
this.yyleng++;
this.offset++;
this.match += ch;
this.matched += ch;
// Count the linenumber up when we hit the LF (or a stand-alone CR).
// On CRLF, the linenumber is incremented when you fetch the CR or the CRLF combo
// and we advance immediately past the LF as well, returning both together as if
// it was all a single 'character' only.
var slice_len = 1;
var lines = false;
if (ch === '\n') {
lines = true;
} else if (ch === '\r') {
lines = true;
var ch2 = this._input[1];
if (ch2 === '\n') {
slice_len++;
ch += ch2;
this.yytext += ch2;
this.yyleng++;
this.offset++;
this.match += ch2;
this.matched += ch2;
if (this.options.ranges) {
this.yylloc.range[1]++;
}
}
}
if (lines) {
this.yylineno++;
this.yylloc.last_line++;
} else {
this.yylloc.last_column++;
}
if (this.options.ranges) {
this.yylloc.range[1]++;
}
this._input = this._input.slice(slice_len);
return ch;
},
// unshifts one char (or a string) into the input
unput: function lexer_unput(ch) {
var len = ch.length;
var lines = ch.split(/(?:\r\n?|\n)/g);
this._input = ch + this._input;
this.yytext = this.yytext.substr(0, this.yytext.length - len);
//this.yyleng -= len;
this.offset -= len;
var oldLines = this.match.split(/(?:\r\n?|\n)/g);
this.match = this.match.substr(0, this.match.length - len);
this.matched = this.matched.substr(0, this.matched.length - len);
if (lines.length - 1) {
this.yylineno -= lines.length - 1;
}
this.yylloc.last_line = this.yylineno + 1;
this.yylloc.last_column = (lines ?
(lines.length === oldLines.length ? this.yylloc.first_column : 0)
+ oldLines[oldLines.length - lines.length].length - lines[0].length :
this.yylloc.first_column - len);
if (this.options.ranges) {
this.yylloc.range[1] = this.yylloc.range[0] + this.yyleng - len;
}
this.yyleng = this.yytext.length;
this.done = false;
return this;
},
// When called from action, caches matched text and appends it on next action
more: function lexer_more() {
this._more = true;
return this;
},
// When called from action, signals the lexer that this rule fails to match the input, so the next matching rule (regex) should be tested instead.
reject: function lexer_reject() {
if (this.options.backtrack_lexer) {
this._backtrack = true;
} else {
// when the parseError() call returns, we MUST ensure that the error is registered.
// We accomplish this by signaling an 'error' token to be produced for the current
// .lex() run.
this._signaled_error_token = (this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true).\n' + this.showPosition(), {
text: this.match,
token: null,
line: this.yylineno,
loc: this.yylloc,
lexer: this
}) || this.ERROR);
}
return this;
},
// retain first n characters of the match
less: function lexer_less(n) {
return this.unput(this.match.slice(n));
},
// return (part of the) already matched input, i.e. for error messages.
// Limit the returned string length to `maxSize` (default: 20).
// Limit the returned string to the `maxLines` number of lines of input (default: 1).
// Negative limit values equal *unlimited*.
pastInput: function lexer_pastInput(maxSize, maxLines) {
var past = this.matched.substring(0, this.matched.length - this.match.length);
if (maxSize < 0)
maxSize = past.length;
else if (!maxSize)
maxSize = 20;
if (maxLines < 0)
maxLines = past.length; // can't ever have more input lines than this!
else if (!maxLines)
maxLines = 1;
// `substr` anticipation: treat \r\n as a single character and take a little
// more than necessary so that we can still properly check against maxSize
// after we've transformed and limited the newLines in here:
past = past.substr(-maxSize * 2 - 2);
// now that we have a significantly reduced string to process, transform the newlines
// and chop them, then limit them:
var a = past.replace(/\r\n|\r/g, '\n').split('\n');
a = a.slice(-maxLines);
past = a.join('\n');
// When, after limiting to maxLines, we still have to much to return,
// do add an ellipsis prefix...
if (past.length > maxSize) {
past = '...' + past.substr(-maxSize);
}
return past;
},
// return (part of the) upcoming input, i.e. for error messages.
// Limit the returned string length to `maxSize` (default: 20).
// Limit the returned string to the `maxLines` number of lines of input (default: 1).
// Negative limit values equal *unlimited*.
upcomingInput: function lexer_upcomingInput(maxSize, maxLines) {
var next = this.match;
if (maxSize < 0)
maxSize = next.length + this._input.length;
else if (!maxSize)
maxSize = 20;
if (maxLines < 0)
maxLines = maxSize; // can't ever have more input lines than this!
else if (!maxLines)
maxLines = 1;
// `substring` anticipation: treat \r\n as a single character and take a little
// more than necessary so that we can still properly check against maxSize
// after we've transformed and limited the newLines in here:
if (next.length < maxSize * 2 + 2) {
next += this._input.substring(0, maxSize * 2 + 2); // substring is faster on Chrome/V8
}
// now that we have a significantly reduced string to process, transform the newlines
// and chop them, then limit them:
var a = next.replace(/\r\n|\r/g, '\n').split('\n');
a = a.slice(0, maxLines);
next = a.join('\n');
// When, after limiting to maxLines, we still have to much to return,
// do add an ellipsis postfix...
if (next.length > maxSize) {
next = next.substring(0, maxSize) + '...';
}
return next;
},
// return a string which displays the character position where the lexing error occurred, i.e. for error messages
showPosition: function lexer_showPosition(maxPrefix, maxPostfix) {
var pre = this.pastInput(maxPrefix).replace(/\s/g, ' ');
var c = new Array(pre.length + 1).join('-');
return pre + this.upcomingInput(maxPostfix).replace(/\s/g, ' ') + '\n' + c + '^';
},
// helper function, used to produce a human readable description as a string, given
// the input `yylloc` location object.
// Set `display_range_too` to TRUE to include the string character inex position(s)
// in the description if the `yylloc.range` is available.
describeYYLLOC: function lexer_describe_yylloc(yylloc, display_range_too) {
var l1 = yylloc.first_line;
var l2 = yylloc.last_line;
var o1 = yylloc.first_column;
var o2 = yylloc.last_column - 1;
var dl = l2 - l1;
var d_o = (dl === 0 ? o2 - o1 : 1000);
var rv;
if (dl === 0) {
rv = 'line ' + l1 + ', ';
if (d_o === 0) {
rv += 'column ' + o1;
} else {
rv += 'columns ' + o1 + ' .. ' + o2;
}
} else {
rv = 'lines ' + l1 + '(column ' + o1 + ') .. ' + l2 + '(column ' + o2 + ')';
}
if (yylloc.range && display_range_too) {
var r1 = yylloc.range[0];
var r2 = yylloc.range[1] - 1;
if (r2 === r1) {
rv += ' {String Offset: ' + r1 + '}';
} else {
rv += ' {String Offset range: ' + r1 + ' .. ' + r2 + '}';
}
}
return rv;
// return JSON.stringify(yylloc);
},
// test the lexed token: return FALSE when not a match, otherwise return token.
//
// `match` is supposed to be an array coming out of a regex match, i.e. `match[0]`
// contains the actually matched text string.
//
// Also move the input cursor forward and update the match collectors:
// - yytext
// - yyleng
// - match
// - matches
// - yylloc
// - offset
test_match: function lexer_test_match(match, indexed_rule) {
var token,
lines,
backup,
match_str;
if (this.options.backtrack_lexer) {
// save context
backup = {
yylineno: this.yylineno,
yylloc: {
first_line: this.yylloc.first_line,
last_line: this.last_line,
first_column: this.yylloc.first_column,
last_column: this.yylloc.last_column
},
yytext: this.yytext,
match: this.match,
matches: this.matches,
matched: this.matched,
yyleng: this.yyleng,
offset: this.offset,
_more: this._more,
_input: this._input,
yy: this.yy,
conditionStack: this.conditionStack.slice(0),
done: this.done
};
if (this.options.ranges) {
backup.yylloc.range = this.yylloc.range.slice(0);
}
}
match_str = match[0];
lines = match_str.match(/(?:\r\n?|\n).*/g);
if (lines) {
this.yylineno += lines.length;
}
this.yylloc = {
first_line: this.yylloc.last_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.last_column,
last_column: lines ?
lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length :
this.yylloc.last_column + match_str.length
};
this.yytext += match_str;
this.match += match_str;
this.matches = match;
this.yyleng = this.yytext.length;
if (this.options.ranges) {
this.yylloc.range = [this.offset, this.offset + this.yyleng];
}
// previous lex rules MAY have invoked the `more()` API rather than producing a token:
// those rules will already have moved this `offset` forward matching their match lengths,
// hence we must only add our own match length now:
this.offset += match_str.length;
this._more = false;
this._backtrack = false;
this._input = this._input.slice(match_str.length);
this.matched += match_str;
token = this.performAction.call(this, this.yy, this, indexed_rule, this.conditionStack[this.conditionStack.length - 1]);
if (this.done && this._input) {
this.done = false;
}
if (token) {
return token;
} else if (this._backtrack) {
// recover context
for (var k in backup) {
this[k] = backup[k];
}
this.__currentRuleSet__ = null;
return false; // rule action called reject() implying the next rule should be tested instead.
} else if (this._signaled_error_token) {
// produce one 'error' token as .parseError() in reject() did not guarantee a failure signal by throwing an exception!
token = this._signaled_error_token;
this._signaled_error_token = false;
return token;
}
return false;
},
// return next match in input
next: function lexer_next() {
if (this.done) {
this.clear();
return this.EOF;
}
if (!this._input) {
this.done = true;
}
var token,
match,
tempMatch,
index;
if (!this._more) {
this.clear();
}
var rules = this.__currentRuleSet__;
if (!rules) {
// Update the ruleset cache as we apparently encountered a state change or just started lexing.
// The cache is set up for fast lookup -- we assume a lexer will switch states much less often than it will
// invoke the `lex()` token-producing API and related APIs, hence caching the set for direct access helps
// speed up those activities a tiny bit.
rules = this.__currentRuleSet__ = this._currentRules();
}
for (var i = 0, len = rules.length; i < len; i++) {
tempMatch = this._input.match(this.rules[rules[i]]);
if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
match = tempMatch;
index = i;
if (this.options.backtrack_lexer) {
token = this.test_match(tempMatch, rules[i]);
if (token !== false) {
return token;
} else if (this._backtrack) {
match = undefined;
continue; // rule action called reject() implying a rule MISmatch.
} else {
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return false;
}
} else if (!this.options.flex) {
break;
}
}
}
if (match) {
token = this.test_match(match, rules[index]);
if (token !== false) {
return token;
}
// else: this is a lexer rule which consumes input without producing a token (e.g. whitespace)
return false;
}
if (this._input === '') {
this.clear();
this.done = true;
return this.EOF;
} else {
token = this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), {
text: this.match + this._input,
token: null,
line: this.yylineno,
loc: this.yylloc,
lexer: this
}) || this.ERROR;
if (token === this.ERROR) {
// we can try to recover from a lexer error that parseError() did not 'recover' for us, by moving forward at least one character at a time:
if (!this.match.length) {
this.input();
}
}
return token;
}
},
// return next match that has a token
lex: function lexer_lex() {
var r;
// allow the PRE/POST handlers set/modify the return token for maximum flexibility of the generated lexer:
if (typeof this.options.pre_lex === 'function') {
r = this.options.pre_lex.call(this);
}
while (!r) {
r = this.next();
}
if (typeof this.options.post_lex === 'function') {
// (also account for a userdef function which does not return any value: keep the token as is)
r = this.options.post_lex.call(this, r) || r;
}
return r;
},
// backwards compatible alias for `pushState()`;
// the latter is symmetrical with `popState()` and we advise to use
// those APIs in any modern lexer code, rather than `begin()`.
begin: function lexer_begin(condition) {
return this.pushState(condition);
},
// activates a new lexer condition state (pushes the new lexer condition state onto the condition stack)
pushState: function lexer_pushState(condition) {
this.conditionStack.push(condition);
this.__currentRuleSet__ = null;
return this;
},
// pop the previously active lexer condition state off the condition stack
popState: function lexer_popState() {
var n = this.conditionStack.length - 1;
if (n > 0) {
this.__currentRuleSet__ = null;
return this.conditionStack.pop();
} else {
return this.conditionStack[0];
}
},
// return the currently active lexer condition state; when an index argument is provided it produces the N-th previous condition state, if available
topState: function lexer_topState(n) {
n = this.conditionStack.length - 1 - Math.abs(n || 0);
if (n >= 0) {
return this.conditionStack[n];
} else {
return 'INITIAL';
}
},
// (internal) determine the lexer rule set which is active for the currently active lexer condition state
_currentRules: function lexer__currentRules() {
if (this.conditionStack.length && this.conditionStack[this.conditionStack.length - 1]) {
return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
} else {
return this.conditions['INITIAL'].rules;
}
},
// return the number of states currently on the stack
stateStackSize: function lexer_stateStackSize() {
return this.conditionStack.length;
},
options: {},
JisonLexerError: JisonLexerError,
performAction: function lexer__performAction(yy, yy_, $avoiding_name_collisions, YY_START) {
var YYSTATE = YY_START;
switch($avoiding_name_collisions) {
case 0 :
/*! Conditions:: INITIAL */
/*! Rule:: [ \t\r\n]+ */
/* eat up whitespace */
BeginToken(yy_.yytext);
break;
case 1 :
/*! Conditions:: INITIAL */
/*! Rule:: {DIGIT}+ */
BeginToken(yy_.yytext);
yylval.value = atof(yy_.yytext);
return VALUE;
break;
case 2 :
/*! Conditions:: INITIAL */
/*! Rule:: {DIGIT}+\.{DIGIT}* */
BeginToken(yy_.yytext);
yylval.value = atof(yy_.yytext);
return VALUE;
break;
case 3 :
/*! Conditions:: INITIAL */
/*! Rule:: {DIGIT}+[eE]["+""-"]?{DIGIT}* */
BeginToken(yy_.yytext);
yylval.value = atof(yy_.yytext);
return VALUE;
break;
case 4 :
/*! Conditions:: INITIAL */
/*! Rule:: {DIGIT}+\.{DIGIT}*[eE]["+""-"]?{DIGIT}* */
BeginToken(yy_.yytext);
yylval.value = atof(yy_.yytext);
return VALUE;
break;
case 5 :
/*! Conditions:: INITIAL */
/*! Rule:: {ID} */
BeginToken(yy_.yytext);
yylval.string = malloc(strlen(yy_.yytext)+1);
strcpy(yylval.string, yy_.yytext);
return IDENTIFIER;
break;
case 6 :
/*! Conditions:: INITIAL */
/*! Rule:: \+ */
BeginToken(yy_.yytext); return ADD;
break;
case 7 :
/*! Conditions:: INITIAL */
/*! Rule:: - */
BeginToken(yy_.yytext); return SUB;
break;
case 8 :
/*! Conditions:: INITIAL */
/*! Rule:: \* */
BeginToken(yy_.yytext); return MULT;
break;
case 9 :
/*! Conditions:: INITIAL */
/*! Rule:: \/ */
BeginToken(yy_.yytext); return DIV;
break;
case 10 :
/*! Conditions:: INITIAL */
/*! Rule:: \( */
BeginToken(yy_.yytext); return LBRACE;
break;
case 11 :
/*! Conditions:: INITIAL */
/*! Rule:: \) */
BeginToken(yy_.yytext); return RBRACE;
break;
case 12 :
/*! Conditions:: INITIAL */
/*! Rule:: ; */
BeginToken(yy_.yytext); return SEMICOLON;
break;
case 13 :
/*! Conditions:: INITIAL */
/*! Rule:: = */
BeginToken(yy_.yytext); return ASSIGN;
break;
case 14 :
/*! Conditions:: INITIAL */
/*! Rule:: . */
BeginToken(yy_.yytext);
return yy_.yytext[0];
break;
default:
return this.simpleCaseActionClusters[$avoiding_name_collisions];
}
},
simpleCaseActionClusters: {
},
rules: [
/^(?:[ \t\r\n]+)/,
/^(?:([0-9])+)/,
/^(?:([0-9])+\.([0-9])*)/,
/^(?:([0-9])+[Ee]["+]?([0-9])*)/,
/^(?:([0-9])+\.([0-9])*[Ee]["+]?([0-9])*)/,
/^(?:([A-Z_a-z][0-9A-Z_a-z]*))/,
/^(?:\+)/,
/^(?:-)/,
/^(?:\*)/,
/^(?:\/)/,
/^(?:\()/,
/^(?:\))/,
/^(?:;)/,
/^(?:=)/,
/^(?:.)/
],
conditions: {
"INITIAL": {
rules: [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14
],
inclusive: true
}
}
};
/*--------------------------------------------------------------------
* lex.l
*------------------------------------------------------------------*/;
return lexer;
})();
parser.lexer = lexer;
function Parser() {
this.yy = {};
}
Parser.prototype = parser;
parser.Parser = Parser;
return new Parser();
})();
if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
exports.parser = ccalcParse;
exports.Parser = ccalcParse.Parser;
exports.parse = function () {
return ccalcParse.parse.apply(ccalcParse, arguments);
};
}
|
/**
* A stream is an abstract interface implemented by various objects in
* Node.
*/
var stream = {};
/**
* A Readable Stream has the following methods, members, and events.
* @constructor
*/
stream.ReadableStream = function() {}
stream.ReadableStream.prototype = new events.EventEmitter();
/**
* Issues an advisory signal to the underlying communication layer,
* requesting that no further data be sent until resume() is called.
*/
stream.ReadableStream.prototype.pause = function() {}
/**
* Makes the 'data' event emit a string instead of a Buffer. encoding can
* be 'utf8', 'utf16le' ('ucs2'), 'ascii', or 'hex'. Defaults to 'utf8'.
* @param encoding
*/
stream.ReadableStream.prototype.setEncoding = function(encoding) {}
/**
* Resumes the incoming 'data' events after a pause().
*/
stream.ReadableStream.prototype.resume = function() {}
/**
* A boolean that is true by default, but turns false after an 'error'
* occurred, the stream came to an 'end', or destroy() was called.
* @type {Boolean}
*/
stream.ReadableStream.prototype.readable = 0;
/**
* This is a Stream.prototype method available on all Streams.
* @param destination
* @param options
*/
stream.ReadableStream.prototype.pipe = function(destination, options) {}
/**
* Closes the underlying file descriptor. Stream will not emit any more
* events.
*/
stream.ReadableStream.prototype.destroy = function() {}
/** @__local__ */ stream.ReadableStream.__events__ = {};
/**
* The 'data' event emits either a Buffer (by default) or a string if
* setEncoding() was used. Note that the data will be lost if there is no
* listener when a Readable Stream emits a 'data' event.
* @param data {buffer.Buffer}
*/
stream.ReadableStream.__events__.data = function(data) {};
/**
* Emitted when the stream has received an EOF (FIN in TCP terminology).
* Indicates that no more 'data' events will happen. If the stream is also
* writable, it may be possible to continue writing.
*/
stream.ReadableStream.__events__.end = function() {};
/**
* Emitted if there was an error receiving data.
* @param exception {Error}
*/
stream.ReadableStream.__events__.error = function(exception) {};
/**
* Emitted when the underlying resource (for example, the backing file
* descriptor) has been closed. Not all streams will emit this.
*/
stream.ReadableStream.__events__.close = function() {};
/**
* A Writable Stream has the following methods, members, and events.
* @constructor
*/
stream.WritableStream = function() {}
stream.WritableStream.prototype = new events.EventEmitter();
/**
* A boolean that is true by default, but turns false after an 'error'
* occurred or end() / destroy() was called.
* @type {Boolean}
*/
stream.WritableStream.prototype.writable = 0;
/**
* Writes string with the given encoding to the stream. Returns true if the
* string has been flushed to the kernel buffer. Returns false to indicate
* that the kernel buffer is full, and the data will be sent out in the
* future. The 'drain' event will indicate when the kernel buffer is empty
* again. The encoding defaults to 'utf8'.
* @param string
* @param encoding='utf8' {String}
* @param fd
* @returns true if the string has been flushed to the kernel buffer
*/
stream.WritableStream.prototype.write = function(string, encoding, fd) {}
/**
* Same as the above except with a raw buffer.
* @param buffer
*/
stream.WritableStream.prototype.write = function(buffer) {}
/**
* Terminates the stream with EOF or FIN.
*/
stream.WritableStream.prototype.end = function() {}
/**
* Sends string with the given encoding and terminates the stream with EOF
* or FIN. This is useful to reduce the number of packets sent.
* @param string
* @param encoding
*/
stream.WritableStream.prototype.end = function(string, encoding) {}
/**
* Same as above but with a buffer.
* @param buffer
*/
stream.WritableStream.prototype.end = function(buffer) {}
/**
* After the write queue is drained, close the file descriptor.
* destroySoon() can still destroy straight away, as long as there is no
* data left in the queue for writes.
*/
stream.WritableStream.prototype.destroySoon = function() {}
/**
* Closes the underlying file descriptor. Stream will not emit any more
* events.
*/
stream.WritableStream.prototype.destroy = function() {}
/** @__local__ */ stream.WritableStream.__events__ = {};
/**
* After a write() method returned false, this event is emitted to indicate
* that it is safe to write again.
*/
stream.WritableStream.__events__.drain = function() {};
/**
* Emitted on error with the exception exception.
* @param exception {Error}
*/
stream.WritableStream.__events__.error = function(exception) {};
/**
* Emitted when the underlying file descriptor has been closed.
*/
stream.WritableStream.__events__.close = function() {};
/**
* Emitted when the stream is passed to a readable stream's pipe method.
* @param src {stream.ReadableStream}
*/
stream.WritableStream.__events__.pipe = function(src) {};
var events = require('events');
exports = stream;
|
'use strict';
// Load modules
const Punycode = require('punycode');
// Declare internals
const internals = {
hasOwn: Object.prototype.hasOwnProperty,
indexOf: Array.prototype.indexOf,
defaultThreshold: 16,
maxIPv6Groups: 8,
categories: {
valid: 1,
dnsWarn: 7,
rfc5321: 15,
cfws: 31,
deprecated: 63,
rfc5322: 127,
error: 255
},
diagnoses: {
// Address is valid
valid: 0,
// Address is valid for SMTP but has unusual elements
rfc5321TLD: 9,
rfc5321TLDNumeric: 10,
rfc5321QuotedString: 11,
rfc5321AddressLiteral: 12,
// Address is valid for message, but must be modified for envelope
cfwsComment: 17,
cfwsFWS: 18,
// Address contains deprecated elements, but may still be valid in some contexts
deprecatedLocalPart: 33,
deprecatedFWS: 34,
deprecatedQTEXT: 35,
deprecatedQP: 36,
deprecatedComment: 37,
deprecatedCTEXT: 38,
deprecatedIPv6: 39,
deprecatedCFWSNearAt: 49,
// Address is only valid according to broad definition in RFC 5322, but is otherwise invalid
rfc5322Domain: 65,
rfc5322TooLong: 66,
rfc5322LocalTooLong: 67,
rfc5322DomainTooLong: 68,
rfc5322LabelTooLong: 69,
rfc5322DomainLiteral: 70,
rfc5322DomainLiteralOBSDText: 71,
rfc5322IPv6GroupCount: 72,
rfc5322IPv62x2xColon: 73,
rfc5322IPv6BadCharacter: 74,
rfc5322IPv6MaxGroups: 75,
rfc5322IPv6ColonStart: 76,
rfc5322IPv6ColonEnd: 77,
// Address is invalid for any purpose
errExpectingDTEXT: 129,
errNoLocalPart: 130,
errNoDomain: 131,
errConsecutiveDots: 132,
errATEXTAfterCFWS: 133,
errATEXTAfterQS: 134,
errATEXTAfterDomainLiteral: 135,
errExpectingQPair: 136,
errExpectingATEXT: 137,
errExpectingQTEXT: 138,
errExpectingCTEXT: 139,
errBackslashEnd: 140,
errDotStart: 141,
errDotEnd: 142,
errDomainHyphenStart: 143,
errDomainHyphenEnd: 144,
errUnclosedQuotedString: 145,
errUnclosedComment: 146,
errUnclosedDomainLiteral: 147,
errFWSCRLFx2: 148,
errFWSCRLFEnd: 149,
errCRNoLF: 150,
errUnknownTLD: 160,
errDomainTooShort: 161
},
components: {
localpart: 0,
domain: 1,
literal: 2,
contextComment: 3,
contextFWS: 4,
contextQuotedString: 5,
contextQuotedPair: 6
}
};
internals.specials = function () {
const specials = '()<>[]:;@\\,."'; // US-ASCII visible characters not valid for atext (http://tools.ietf.org/html/rfc5322#section-3.2.3)
const lookup = new Array(0x100);
lookup.fill(false);
for (let i = 0; i < specials.length; ++i) {
lookup[specials.codePointAt(i)] = true;
}
return function (code) {
return lookup[code];
};
}();
internals.c0Controls = function () {
const lookup = new Array(0x100);
lookup.fill(false);
// add C0 control characters
for (let i = 0; i < 33; ++i) {
lookup[i] = true;
}
return function (code) {
return lookup[code];
};
}();
internals.c1Controls = function () {
const lookup = new Array(0x100);
lookup.fill(false);
// add C1 control characters
for (let i = 127; i < 160; ++i) {
lookup[i] = true;
}
return function (code) {
return lookup[code];
};
}();
internals.regex = {
ipV4: /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
ipV6: /^[a-fA-F\d]{0,4}$/
};
// $lab:coverage:off$
internals.nulNormalize = function (email) {
let emailPieces = email.split('\u0000');
emailPieces = emailPieces.map((string) => {
return string.normalize('NFC');
});
return emailPieces.join('\u0000');
};
// $lab:coverage:on$
internals.checkIpV6 = function (items) {
return items.every((value) => internals.regex.ipV6.test(value));
};
internals.validDomain = function (tldAtom, options) {
if (options.tldBlacklist) {
if (Array.isArray(options.tldBlacklist)) {
return internals.indexOf.call(options.tldBlacklist, tldAtom) === -1;
}
return !internals.hasOwn.call(options.tldBlacklist, tldAtom);
}
if (Array.isArray(options.tldWhitelist)) {
return internals.indexOf.call(options.tldWhitelist, tldAtom) !== -1;
}
return internals.hasOwn.call(options.tldWhitelist, tldAtom);
};
/**
* Check that an email address conforms to RFCs 5321, 5322, 6530 and others
*
* We distinguish clearly between a Mailbox as defined by RFC 5321 and an
* addr-spec as defined by RFC 5322. Depending on the context, either can be
* regarded as a valid email address. The RFC 5321 Mailbox specification is
* more restrictive (comments, white space and obsolete forms are not allowed).
*
* @param {string} email The email address to check. See README for specifics.
* @param {Object} options The (optional) options:
* {*} errorLevel Determines the boundary between valid and invalid
* addresses.
* {*} tldBlacklist The set of domains to consider invalid.
* {*} tldWhitelist The set of domains to consider valid.
* {*} minDomainAtoms The minimum number of domain atoms which must be present
* for the address to be valid.
* @param {function(number|boolean)} callback The (optional) callback handler.
* @return {*}
*/
exports.validate = internals.validate = function (email, options, callback) {
options = options || {};
email = internals.normalize(email);
if (typeof options === 'function') {
callback = options;
options = {};
}
if (typeof callback !== 'function') {
callback = null;
}
let diagnose;
let threshold;
if (typeof options.errorLevel === 'number') {
diagnose = true;
threshold = options.errorLevel;
}
else {
diagnose = !!options.errorLevel;
threshold = internals.diagnoses.valid;
}
if (options.tldWhitelist) {
if (typeof options.tldWhitelist === 'string') {
options.tldWhitelist = [options.tldWhitelist];
}
else if (typeof options.tldWhitelist !== 'object') {
throw new TypeError('expected array or object tldWhitelist');
}
}
if (options.tldBlacklist) {
if (typeof options.tldBlacklist === 'string') {
options.tldBlacklist = [options.tldBlacklist];
}
else if (typeof options.tldBlacklist !== 'object') {
throw new TypeError('expected array or object tldBlacklist');
}
}
if (options.minDomainAtoms && (options.minDomainAtoms !== ((+options.minDomainAtoms) | 0) || options.minDomainAtoms < 0)) {
throw new TypeError('expected positive integer minDomainAtoms');
}
let maxResult = internals.diagnoses.valid;
const updateResult = (value) => {
if (value > maxResult) {
maxResult = value;
}
};
const context = {
now: internals.components.localpart,
prev: internals.components.localpart,
stack: [internals.components.localpart]
};
let prevToken = '';
const parseData = {
local: '',
domain: ''
};
const atomData = {
locals: [''],
domains: ['']
};
let elementCount = 0;
let elementLength = 0;
let crlfCount = 0;
let charCode;
let hyphenFlag = false;
let assertEnd = false;
const emailLength = email.length;
let token; // Token is used outside the loop, must declare similarly
for (let i = 0; i < emailLength; i += token.length) {
// Utilize codepoints to account for Unicode surrogate pairs
token = String.fromCodePoint(email.codePointAt(i));
switch (context.now) {
// Local-part
case internals.components.localpart:
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// local-part = dot-atom / quoted-string / obs-local-part
//
// dot-atom = [CFWS] dot-atom-text [CFWS]
//
// dot-atom-text = 1*atext *("." 1*atext)
//
// quoted-string = [CFWS]
// DQUOTE *([FWS] qcontent) [FWS] DQUOTE
// [CFWS]
//
// obs-local-part = word *("." word)
//
// word = atom / quoted-string
//
// atom = [CFWS] 1*atext [CFWS]
switch (token) {
// Comment
case '(':
if (elementLength === 0) {
// Comments are OK at the beginning of an element
updateResult(elementCount === 0 ? internals.diagnoses.cfwsComment : internals.diagnoses.deprecatedComment);
}
else {
updateResult(internals.diagnoses.cfwsComment);
// Cannot start a comment in an element, should be end
assertEnd = true;
}
context.stack.push(context.now);
context.now = internals.components.contextComment;
break;
// Next dot-atom element
case '.':
if (elementLength === 0) {
// Another dot, already?
updateResult(elementCount === 0 ? internals.diagnoses.errDotStart : internals.diagnoses.errConsecutiveDots);
}
else {
// The entire local-part can be a quoted string for RFC 5321; if one atom is quoted it's an RFC 5322 obsolete form
if (assertEnd) {
updateResult(internals.diagnoses.deprecatedLocalPart);
}
// CFWS & quoted strings are OK again now we're at the beginning of an element (although they are obsolete forms)
assertEnd = false;
elementLength = 0;
++elementCount;
parseData.local += token;
atomData.locals[elementCount] = '';
}
break;
// Quoted string
case '"':
if (elementLength === 0) {
// The entire local-part can be a quoted string for RFC 5321; if one atom is quoted it's an RFC 5322 obsolete form
updateResult(elementCount === 0 ? internals.diagnoses.rfc5321QuotedString : internals.diagnoses.deprecatedLocalPart);
parseData.local += token;
atomData.locals[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
// Quoted string must be the entire element
assertEnd = true;
context.stack.push(context.now);
context.now = internals.components.contextQuotedString;
}
else {
updateResult(internals.diagnoses.errExpectingATEXT);
}
break;
// Folding white space
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case ' ':
case '\t':
if (elementLength === 0) {
updateResult(elementCount === 0 ? internals.diagnoses.cfwsFWS : internals.diagnoses.deprecatedFWS);
}
else {
// We can't start FWS in the middle of an element, better be end
assertEnd = true;
}
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
case '@':
// At this point we should have a valid local-part
// $lab:coverage:off$
if (context.stack.length !== 1) {
throw new Error('unexpected item on context stack');
}
// $lab:coverage:on$
if (parseData.local.length === 0) {
// Fatal error
updateResult(internals.diagnoses.errNoLocalPart);
}
else if (elementLength === 0) {
// Fatal error
updateResult(internals.diagnoses.errDotEnd);
}
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.1 the maximum total length of a user name or other local-part is 64
// octets
else if (Buffer.byteLength(parseData.local, 'utf8') > 64) {
updateResult(internals.diagnoses.rfc5322LocalTooLong);
}
// http://tools.ietf.org/html/rfc5322#section-3.4.1 comments and folding white space SHOULD NOT be used around "@" in the
// addr-spec
//
// http://tools.ietf.org/html/rfc2119
// 4. SHOULD NOT this phrase, or the phrase "NOT RECOMMENDED" mean that there may exist valid reasons in particular
// circumstances when the particular behavior is acceptable or even useful, but the full implications should be understood
// and the case carefully weighed before implementing any behavior described with this label.
else if (context.prev === internals.components.contextComment || context.prev === internals.components.contextFWS) {
updateResult(internals.diagnoses.deprecatedCFWSNearAt);
}
// Clear everything down for the domain parsing
context.now = internals.components.domain;
context.stack[0] = internals.components.domain;
elementCount = 0;
elementLength = 0;
assertEnd = false; // CFWS can only appear at the end of the element
break;
// ATEXT
default:
// http://tools.ietf.org/html/rfc5322#section-3.2.3
// atext = ALPHA / DIGIT / ; Printable US-ASCII
// "!" / "#" / ; characters not including
// "$" / "%" / ; specials. Used for atoms.
// "&" / "'" /
// "*" / "+" /
// "-" / "/" /
// "=" / "?" /
// "^" / "_" /
// "`" / "{" /
// "|" / "}" /
// "~"
if (assertEnd) {
// We have encountered atext where it is no longer valid
switch (context.prev) {
case internals.components.contextComment:
case internals.components.contextFWS:
updateResult(internals.diagnoses.errATEXTAfterCFWS);
break;
case internals.components.contextQuotedString:
updateResult(internals.diagnoses.errATEXTAfterQS);
break;
// $lab:coverage:off$
default:
throw new Error('more atext found where none is allowed, but unrecognized prev context: ' + context.prev);
// $lab:coverage:on$
}
}
else {
context.prev = context.now;
charCode = token.codePointAt(0);
// Especially if charCode == 10
if (internals.specials(charCode) || internals.c0Controls(charCode) || internals.c1Controls(charCode)) {
// Fatal error
updateResult(internals.diagnoses.errExpectingATEXT);
}
parseData.local += token;
atomData.locals[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
}
}
break;
case internals.components.domain:
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// domain = dot-atom / domain-literal / obs-domain
//
// dot-atom = [CFWS] dot-atom-text [CFWS]
//
// dot-atom-text = 1*atext *("." 1*atext)
//
// domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
//
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
//
// obs-domain = atom *("." atom)
//
// atom = [CFWS] 1*atext [CFWS]
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// Mailbox = Local-part "@" ( Domain / address-literal )
//
// Domain = sub-domain *("." sub-domain)
//
// address-literal = "[" ( IPv4-address-literal /
// IPv6-address-literal /
// General-address-literal ) "]"
// ; See Section 4.1.3
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// Note: A liberal syntax for the domain portion of addr-spec is
// given here. However, the domain portion contains addressing
// information specified by and used in other protocols (e.g.,
// [RFC1034], [RFC1035], [RFC1123], [RFC5321]). It is therefore
// incumbent upon implementations to conform to the syntax of
// addresses for the context in which they are used.
//
// is_email() author's note: it's not clear how to interpret this in
// he context of a general email address validator. The conclusion I
// have reached is this: "addressing information" must comply with
// RFC 5321 (and in turn RFC 1035), anything that is "semantically
// invisible" must comply only with RFC 5322.
switch (token) {
// Comment
case '(':
if (elementLength === 0) {
// Comments at the start of the domain are deprecated in the text, comments at the start of a subdomain are obs-domain
// http://tools.ietf.org/html/rfc5322#section-3.4.1
updateResult(elementCount === 0 ? internals.diagnoses.deprecatedCFWSNearAt : internals.diagnoses.deprecatedComment);
}
else {
// We can't start a comment mid-element, better be at the end
assertEnd = true;
updateResult(internals.diagnoses.cfwsComment);
}
context.stack.push(context.now);
context.now = internals.components.contextComment;
break;
// Next dot-atom element
case '.':
const punycodeLength = Punycode.encode(atomData.domains[elementCount]).length;
if (elementLength === 0) {
// Another dot, already? Fatal error.
updateResult(elementCount === 0 ? internals.diagnoses.errDotStart : internals.diagnoses.errConsecutiveDots);
}
else if (hyphenFlag) {
// Previous subdomain ended in a hyphen. Fatal error.
updateResult(internals.diagnoses.errDomainHyphenEnd);
}
else if (punycodeLength > 63) {
// RFC 5890 specifies that domain labels that are encoded using the Punycode algorithm
// must adhere to the <= 63 octet requirement.
// This includes string prefixes from the Punycode algorithm.
//
// https://tools.ietf.org/html/rfc5890#section-2.3.2.1
// labels 63 octets or less
updateResult(internals.diagnoses.rfc5322LabelTooLong);
}
// CFWS is OK again now we're at the beginning of an element (although
// it may be obsolete CFWS)
assertEnd = false;
elementLength = 0;
++elementCount;
atomData.domains[elementCount] = '';
parseData.domain += token;
break;
// Domain literal
case '[':
if (parseData.domain.length === 0) {
// Domain literal must be the only component
assertEnd = true;
elementLength += Buffer.byteLength(token, 'utf8');
context.stack.push(context.now);
context.now = internals.components.literal;
parseData.domain += token;
atomData.domains[elementCount] += token;
parseData.literal = '';
}
else {
// Fatal error
updateResult(internals.diagnoses.errExpectingATEXT);
}
break;
// Folding white space
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case ' ':
case '\t':
if (elementLength === 0) {
updateResult(elementCount === 0 ? internals.diagnoses.deprecatedCFWSNearAt : internals.diagnoses.deprecatedFWS);
}
else {
// We can't start FWS in the middle of an element, so this better be the end
updateResult(internals.diagnoses.cfwsFWS);
assertEnd = true;
}
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
// This must be ATEXT
default:
// RFC 5322 allows any atext...
// http://tools.ietf.org/html/rfc5322#section-3.2.3
// atext = ALPHA / DIGIT / ; Printable US-ASCII
// "!" / "#" / ; characters not including
// "$" / "%" / ; specials. Used for atoms.
// "&" / "'" /
// "*" / "+" /
// "-" / "/" /
// "=" / "?" /
// "^" / "_" /
// "`" / "{" /
// "|" / "}" /
// "~"
// But RFC 5321 only allows letter-digit-hyphen to comply with DNS rules
// (RFCs 1034 & 1123)
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// sub-domain = Let-dig [Ldh-str]
//
// Let-dig = ALPHA / DIGIT
//
// Ldh-str = *( ALPHA / DIGIT / "-" ) Let-dig
//
if (assertEnd) {
// We have encountered ATEXT where it is no longer valid
switch (context.prev) {
case internals.components.contextComment:
case internals.components.contextFWS:
updateResult(internals.diagnoses.errATEXTAfterCFWS);
break;
case internals.components.literal:
updateResult(internals.diagnoses.errATEXTAfterDomainLiteral);
break;
// $lab:coverage:off$
default:
throw new Error('more atext found where none is allowed, but unrecognized prev context: ' + context.prev);
// $lab:coverage:on$
}
}
charCode = token.codePointAt(0);
// Assume this token isn't a hyphen unless we discover it is
hyphenFlag = false;
if (internals.specials(charCode) || internals.c0Controls(charCode) || internals.c1Controls(charCode)) {
// Fatal error
updateResult(internals.diagnoses.errExpectingATEXT);
}
else if (token === '-') {
if (elementLength === 0) {
// Hyphens cannot be at the beginning of a subdomain, fatal error
updateResult(internals.diagnoses.errDomainHyphenStart);
}
hyphenFlag = true;
}
// Check if it's a neither a number nor a latin/unicode letter
else if (charCode < 48 || (charCode > 122 && charCode < 192) || (charCode > 57 && charCode < 65) || (charCode > 90 && charCode < 97)) {
// This is not an RFC 5321 subdomain, but still OK by RFC 5322
updateResult(internals.diagnoses.rfc5322Domain);
}
parseData.domain += token;
atomData.domains[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
}
break;
// Domain literal
case internals.components.literal:
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// domain-literal = [CFWS] "[" *([FWS] dtext) [FWS] "]" [CFWS]
//
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
//
// obs-dtext = obs-NO-WS-CTL / quoted-pair
switch (token) {
// End of domain literal
case ']':
if (maxResult < internals.categories.deprecated) {
// Could be a valid RFC 5321 address literal, so let's check
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// address-literal = "[" ( IPv4-address-literal /
// IPv6-address-literal /
// General-address-literal ) "]"
// ; See Section 4.1.3
//
// http://tools.ietf.org/html/rfc5321#section-4.1.3
// IPv4-address-literal = Snum 3("." Snum)
//
// IPv6-address-literal = "IPv6:" IPv6-addr
//
// General-address-literal = Standardized-tag ":" 1*dcontent
//
// Standardized-tag = Ldh-str
// ; Standardized-tag MUST be specified in a
// ; Standards-Track RFC and registered with IANA
//
// dcontent = %d33-90 / ; Printable US-ASCII
// %d94-126 ; excl. "[", "\", "]"
//
// Snum = 1*3DIGIT
// ; representing a decimal integer
// ; value in the range 0 through 255
//
// IPv6-addr = IPv6-full / IPv6-comp / IPv6v4-full / IPv6v4-comp
//
// IPv6-hex = 1*4HEXDIG
//
// IPv6-full = IPv6-hex 7(":" IPv6-hex)
//
// IPv6-comp = [IPv6-hex *5(":" IPv6-hex)] "::"
// [IPv6-hex *5(":" IPv6-hex)]
// ; The "::" represents at least 2 16-bit groups of
// ; zeros. No more than 6 groups in addition to the
// ; "::" may be present.
//
// IPv6v4-full = IPv6-hex 5(":" IPv6-hex) ":" IPv4-address-literal
//
// IPv6v4-comp = [IPv6-hex *3(":" IPv6-hex)] "::"
// [IPv6-hex *3(":" IPv6-hex) ":"]
// IPv4-address-literal
// ; The "::" represents at least 2 16-bit groups of
// ; zeros. No more than 4 groups in addition to the
// ; "::" and IPv4-address-literal may be present.
let index = -1;
let addressLiteral = parseData.literal;
const matchesIP = internals.regex.ipV4.exec(addressLiteral);
// Maybe extract IPv4 part from the end of the address-literal
if (matchesIP) {
index = matchesIP.index;
if (index !== 0) {
// Convert IPv4 part to IPv6 format for futher testing
addressLiteral = addressLiteral.slice(0, index) + '0:0';
}
}
if (index === 0) {
// Nothing there except a valid IPv4 address, so...
updateResult(internals.diagnoses.rfc5321AddressLiteral);
}
else if (addressLiteral.slice(0, 5).toLowerCase() !== 'ipv6:') {
updateResult(internals.diagnoses.rfc5322DomainLiteral);
}
else {
const match = addressLiteral.slice(5);
let maxGroups = internals.maxIPv6Groups;
const groups = match.split(':');
index = match.indexOf('::');
if (!~index) {
// Need exactly the right number of groups
if (groups.length !== maxGroups) {
updateResult(internals.diagnoses.rfc5322IPv6GroupCount);
}
}
else if (index !== match.lastIndexOf('::')) {
updateResult(internals.diagnoses.rfc5322IPv62x2xColon);
}
else {
if (index === 0 || index === match.length - 2) {
// RFC 4291 allows :: at the start or end of an address with 7 other groups in addition
++maxGroups;
}
if (groups.length > maxGroups) {
updateResult(internals.diagnoses.rfc5322IPv6MaxGroups);
}
else if (groups.length === maxGroups) {
// Eliding a single "::"
updateResult(internals.diagnoses.deprecatedIPv6);
}
}
// IPv6 testing strategy
if (match[0] === ':' && match[1] !== ':') {
updateResult(internals.diagnoses.rfc5322IPv6ColonStart);
}
else if (match[match.length - 1] === ':' && match[match.length - 2] !== ':') {
updateResult(internals.diagnoses.rfc5322IPv6ColonEnd);
}
else if (internals.checkIpV6(groups)) {
updateResult(internals.diagnoses.rfc5321AddressLiteral);
}
else {
updateResult(internals.diagnoses.rfc5322IPv6BadCharacter);
}
}
}
else {
updateResult(internals.diagnoses.rfc5322DomainLiteral);
}
parseData.domain += token;
atomData.domains[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
context.prev = context.now;
context.now = context.stack.pop();
break;
case '\\':
updateResult(internals.diagnoses.rfc5322DomainLiteralOBSDText);
context.stack.push(context.now);
context.now = internals.components.contextQuotedPair;
break;
// Folding white space
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case ' ':
case '\t':
updateResult(internals.diagnoses.cfwsFWS);
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
// DTEXT
default:
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// dtext = %d33-90 / ; Printable US-ASCII
// %d94-126 / ; characters not including
// obs-dtext ; "[", "]", or "\"
//
// obs-dtext = obs-NO-WS-CTL / quoted-pair
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
charCode = token.codePointAt(0);
// '\r', '\n', ' ', and '\t' have already been parsed above
if ((charCode !== 127 && internals.c1Controls(charCode)) || charCode === 0 || token === '[') {
// Fatal error
updateResult(internals.diagnoses.errExpectingDTEXT);
break;
}
else if (internals.c0Controls(charCode) || charCode === 127) {
updateResult(internals.diagnoses.rfc5322DomainLiteralOBSDText);
}
parseData.literal += token;
parseData.domain += token;
atomData.domains[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
}
break;
// Quoted string
case internals.components.contextQuotedString:
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// quoted-string = [CFWS]
// DQUOTE *([FWS] qcontent) [FWS] DQUOTE
// [CFWS]
//
// qcontent = qtext / quoted-pair
switch (token) {
// Quoted pair
case '\\':
context.stack.push(context.now);
context.now = internals.components.contextQuotedPair;
break;
// Folding white space. Spaces are allowed as regular characters inside a quoted string - it's only FWS if we include '\t' or '\r\n'
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case '\t':
// http://tools.ietf.org/html/rfc5322#section-3.2.2
// Runs of FWS, comment, or CFWS that occur between lexical tokens in
// a structured header field are semantically interpreted as a single
// space character.
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// the CRLF in any FWS/CFWS that appears within the quoted-string [is]
// semantically "invisible" and therefore not part of the
// quoted-string
parseData.local += ' ';
atomData.locals[elementCount] += ' ';
elementLength += Buffer.byteLength(token, 'utf8');
updateResult(internals.diagnoses.cfwsFWS);
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
// End of quoted string
case '"':
parseData.local += token;
atomData.locals[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
context.prev = context.now;
context.now = context.stack.pop();
break;
// QTEXT
default:
// http://tools.ietf.org/html/rfc5322#section-3.2.4
// qtext = %d33 / ; Printable US-ASCII
// %d35-91 / ; characters not including
// %d93-126 / ; "\" or the quote character
// obs-qtext
//
// obs-qtext = obs-NO-WS-CTL
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
charCode = token.codePointAt(0);
if ((charCode !== 127 && internals.c1Controls(charCode)) || charCode === 0 || charCode === 10) {
updateResult(internals.diagnoses.errExpectingQTEXT);
}
else if (internals.c0Controls(charCode) || charCode === 127) {
updateResult(internals.diagnoses.deprecatedQTEXT);
}
parseData.local += token;
atomData.locals[elementCount] += token;
elementLength += Buffer.byteLength(token, 'utf8');
}
// http://tools.ietf.org/html/rfc5322#section-3.4.1
// If the string can be represented as a dot-atom (that is, it contains
// no characters other than atext characters or "." surrounded by atext
// characters), then the dot-atom form SHOULD be used and the quoted-
// string form SHOULD NOT be used.
break;
// Quoted pair
case internals.components.contextQuotedPair:
// http://tools.ietf.org/html/rfc5322#section-3.2.1
// quoted-pair = ("\" (VCHAR / WSP)) / obs-qp
//
// VCHAR = %d33-126 ; visible (printing) characters
// WSP = SP / HTAB ; white space
//
// obs-qp = "\" (%d0 / obs-NO-WS-CTL / LF / CR)
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
//
// i.e. obs-qp = "\" (%d0-8, %d10-31 / %d127)
charCode = token.codePointAt(0);
if (charCode !== 127 && internals.c1Controls(charCode)) {
// Fatal error
updateResult(internals.diagnoses.errExpectingQPair);
}
else if ((charCode < 31 && charCode !== 9) || charCode === 127) {
// ' ' and '\t' are allowed
updateResult(internals.diagnoses.deprecatedQP);
}
// At this point we know where this qpair occurred so we could check to see if the character actually needed to be quoted at all.
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// the sending system SHOULD transmit the form that uses the minimum quoting possible.
context.prev = context.now;
// End of qpair
context.now = context.stack.pop();
const escapeToken = '\\' + token;
switch (context.now) {
case internals.components.contextComment:
break;
case internals.components.contextQuotedString:
parseData.local += escapeToken;
atomData.locals[elementCount] += escapeToken;
// The maximum sizes specified by RFC 5321 are octet counts, so we must include the backslash
elementLength += 2;
break;
case internals.components.literal:
parseData.domain += escapeToken;
atomData.domains[elementCount] += escapeToken;
// The maximum sizes specified by RFC 5321 are octet counts, so we must include the backslash
elementLength += 2;
break;
// $lab:coverage:off$
default:
throw new Error('quoted pair logic invoked in an invalid context: ' + context.now);
// $lab:coverage:on$
}
break;
// Comment
case internals.components.contextComment:
// http://tools.ietf.org/html/rfc5322#section-3.2.2
// comment = "(" *([FWS] ccontent) [FWS] ")"
//
// ccontent = ctext / quoted-pair / comment
switch (token) {
// Nested comment
case '(':
// Nested comments are ok
context.stack.push(context.now);
context.now = internals.components.contextComment;
break;
// End of comment
case ')':
context.prev = context.now;
context.now = context.stack.pop();
break;
// Quoted pair
case '\\':
context.stack.push(context.now);
context.now = internals.components.contextQuotedPair;
break;
// Folding white space
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
break;
}
// Fallthrough
case ' ':
case '\t':
updateResult(internals.diagnoses.cfwsFWS);
context.stack.push(context.now);
context.now = internals.components.contextFWS;
prevToken = token;
break;
// CTEXT
default:
// http://tools.ietf.org/html/rfc5322#section-3.2.3
// ctext = %d33-39 / ; Printable US-ASCII
// %d42-91 / ; characters not including
// %d93-126 / ; "(", ")", or "\"
// obs-ctext
//
// obs-ctext = obs-NO-WS-CTL
//
// obs-NO-WS-CTL = %d1-8 / ; US-ASCII control
// %d11 / ; characters that do not
// %d12 / ; include the carriage
// %d14-31 / ; return, line feed, and
// %d127 ; white space characters
charCode = token.codePointAt(0);
if (charCode === 0 || charCode === 10 || (charCode !== 127 && internals.c1Controls(charCode))) {
// Fatal error
updateResult(internals.diagnoses.errExpectingCTEXT);
break;
}
else if (internals.c0Controls(charCode) || charCode === 127) {
updateResult(internals.diagnoses.deprecatedCTEXT);
}
}
break;
// Folding white space
case internals.components.contextFWS:
// http://tools.ietf.org/html/rfc5322#section-3.2.2
// FWS = ([*WSP CRLF] 1*WSP) / obs-FWS
// ; Folding white space
// But note the erratum:
// http://www.rfc-editor.org/errata_search.php?rfc=5322&eid=1908:
// In the obsolete syntax, any amount of folding white space MAY be
// inserted where the obs-FWS rule is allowed. This creates the
// possibility of having two consecutive "folds" in a line, and
// therefore the possibility that a line which makes up a folded header
// field could be composed entirely of white space.
//
// obs-FWS = 1*([CRLF] WSP)
if (prevToken === '\r') {
if (token === '\r') {
// Fatal error
updateResult(internals.diagnoses.errFWSCRLFx2);
break;
}
if (++crlfCount > 1) {
// Multiple folds => obsolete FWS
updateResult(internals.diagnoses.deprecatedFWS);
}
else {
crlfCount = 1;
}
}
switch (token) {
case '\r':
if (emailLength === ++i || email[i] !== '\n') {
// Fatal error
updateResult(internals.diagnoses.errCRNoLF);
}
break;
case ' ':
case '\t':
break;
default:
if (prevToken === '\r') {
// Fatal error
updateResult(internals.diagnoses.errFWSCRLFEnd);
}
crlfCount = 0;
// End of FWS
context.prev = context.now;
context.now = context.stack.pop();
// Look at this token again in the parent context
--i;
}
prevToken = token;
break;
// Unexpected context
// $lab:coverage:off$
default:
throw new Error('unknown context: ' + context.now);
// $lab:coverage:on$
} // Primary state machine
if (maxResult > internals.categories.rfc5322) {
// Fatal error, no point continuing
break;
}
} // Token loop
// Check for errors
if (maxResult < internals.categories.rfc5322) {
const punycodeLength = Punycode.encode(parseData.domain).length;
// Fatal errors
if (context.now === internals.components.contextQuotedString) {
updateResult(internals.diagnoses.errUnclosedQuotedString);
}
else if (context.now === internals.components.contextQuotedPair) {
updateResult(internals.diagnoses.errBackslashEnd);
}
else if (context.now === internals.components.contextComment) {
updateResult(internals.diagnoses.errUnclosedComment);
}
else if (context.now === internals.components.literal) {
updateResult(internals.diagnoses.errUnclosedDomainLiteral);
}
else if (token === '\r') {
updateResult(internals.diagnoses.errFWSCRLFEnd);
}
else if (parseData.domain.length === 0) {
updateResult(internals.diagnoses.errNoDomain);
}
else if (elementLength === 0) {
updateResult(internals.diagnoses.errDotEnd);
}
else if (hyphenFlag) {
updateResult(internals.diagnoses.errDomainHyphenEnd);
}
// Other errors
else if (punycodeLength > 255) {
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.2
// The maximum total length of a domain name or number is 255 octets.
updateResult(internals.diagnoses.rfc5322DomainTooLong);
}
else if (Buffer.byteLength(parseData.local, 'utf8') + punycodeLength + /* '@' */ 1 > 254) {
// http://tools.ietf.org/html/rfc5321#section-4.1.2
// Forward-path = Path
//
// Path = "<" [ A-d-l ":" ] Mailbox ">"
//
// http://tools.ietf.org/html/rfc5321#section-4.5.3.1.3
// The maximum total length of a reverse-path or forward-path is 256 octets (including the punctuation and element separators).
//
// Thus, even without (obsolete) routing information, the Mailbox can only be 254 characters long. This is confirmed by this verified
// erratum to RFC 3696:
//
// http://www.rfc-editor.org/errata_search.php?rfc=3696&eid=1690
// However, there is a restriction in RFC 2821 on the length of an address in MAIL and RCPT commands of 254 characters. Since
// addresses that do not fit in those fields are not normally useful, the upper limit on address lengths should normally be considered
// to be 254.
updateResult(internals.diagnoses.rfc5322TooLong);
}
else if (elementLength > 63) {
// http://tools.ietf.org/html/rfc1035#section-2.3.4
// labels 63 octets or less
updateResult(internals.diagnoses.rfc5322LabelTooLong);
}
else if (options.minDomainAtoms && atomData.domains.length < options.minDomainAtoms) {
updateResult(internals.diagnoses.errDomainTooShort);
}
else if (options.tldWhitelist || options.tldBlacklist) {
const tldAtom = atomData.domains[elementCount];
if (!internals.validDomain(tldAtom, options)) {
updateResult(internals.diagnoses.errUnknownTLD);
}
}
} // Check for errors
// Finish
if (maxResult < internals.categories.dnsWarn) {
// Per RFC 5321, domain atoms are limited to letter-digit-hyphen, so we only need to check code <= 57 to check for a digit
const code = atomData.domains[elementCount].codePointAt(0);
if (code <= 57) {
updateResult(internals.diagnoses.rfc5321TLDNumeric);
}
}
if (maxResult < threshold) {
maxResult = internals.diagnoses.valid;
}
const finishResult = diagnose ? maxResult : maxResult < internals.defaultThreshold;
if (callback) {
callback(finishResult);
}
return finishResult;
};
exports.diagnoses = internals.validate.diagnoses = (function () {
const diag = {};
const keys = Object.keys(internals.diagnoses);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
diag[key] = internals.diagnoses[key];
}
return diag;
})();
exports.normalize = internals.normalize = function (email) {
// $lab:coverage:off$
if (process.version[1] === '4' && email.indexOf('\u0000') >= 0) {
return internals.nulNormalize(email);
}
// $lab:coverage:on$
return email.normalize('NFC');
};
|
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'eo', {
title: 'Uzindikoj pri atingeblo',
contents: 'Helpilenhavo. Por fermi tiun dialogon, premu la ESKAPAN klavon.',
legend: [
{
name: 'Ĝeneralaĵoj',
items: [
{
name: 'Ilbreto de la redaktilo',
legend: 'Premu ${toolbarFocus} por atingi la ilbreton. Moviĝu al la sekva aŭ antaŭa grupoj de la ilbreto per la klavoj TABA kaj MAJUSKLIGA+TABA. Moviĝu al la sekva aŭ antaŭa butonoj de la ilbreto per la klavoj SAGO DEKSTREN kaj SAGO MALDEKSTREN. Premu la SPACETklavon aŭ la ENENklavon por aktivigi la ilbretbutonon.'
},
{
name: 'Redaktildialogo',
legend:
'Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively.' // MISSING
},
{
name: 'Kunteksta menuo de la redaktilo',
legend: 'Premu ${contextMenu} aŭ entajpu la KLAVKOMBINAĴON por malfermi la kuntekstan menuon. Poste moviĝu al la sekva opcio de la menuo per la klavoj TABA aŭ SAGO SUBEN. Moviĝu al la antaŭa opcio per la klavoj MAJUSKLGA + TABA aŭ SAGO SUPREN. Premu la SPACETklavon aŭ ENENklavon por selekti la menuopcion. Malfermu la submenuon de la kuranta opcio per la SPACETklavo aŭ la ENENklavo aŭ la SAGO DEKSTREN. Revenu al la elemento de la patra menuo per la klavoj ESKAPA aŭ SAGO MALDEKSTREN. Fermu la kuntekstan menuon per la ESKAPA klavo.'
},
{
name: 'Fallisto de la redaktilo',
legend: 'En fallisto, moviĝu al la sekva listelemento per la klavoj TABA aŭ SAGO SUBEN. Moviĝu al la antaŭa listelemento per la klavoj MAJUSKLIGA+TABA aŭ SAGO SUPREN. Premu la SPACETklavon aŭ ENENklavon por selekti la opcion en la listo. Premu la ESKAPAN klavon por fermi la falmenuon.'
},
{
name: 'Breto indikanta la vojon al la redaktilelementoj',
legend: 'Premu ${elementsPathFocus} por navigi al la breto indikanta la vojon al la redaktilelementoj. Moviĝu al la butono de la sekva elemento per la klavoj TABA aŭ SAGO DEKSTREN. Moviĝu al la butono de la antaŭa elemento per la klavoj MAJUSKLIGA+TABA aŭ SAGO MALDEKSTREN. Premu la SPACETklavon aŭ ENENklavon por selekti la elementon en la redaktilo.'
}
]
},
{
name: 'Komandoj',
items: [
{
name: 'Komando malfari',
legend: 'Premu ${undo}'
},
{
name: 'Komando refari',
legend: 'Premu ${redo}'
},
{
name: 'Komando grasa',
legend: 'Premu ${bold}'
},
{
name: 'Komando kursiva',
legend: 'Premu ${italic}'
},
{
name: 'Komando substreki',
legend: 'Premu ${underline}'
},
{
name: 'Komando ligilo',
legend: 'Premu ${link}'
},
{
name: 'Komando faldi la ilbreton',
legend: 'Premu ${toolbarCollapse}'
},
{
name: 'Komando por atingi la antaŭan fokusan spacon',
legend: 'Press ${accessPreviousSpace} por atingi la plej proksiman neatingeblan fokusan spacon antaŭ la kursoro, ekzemple : du kuntuŝiĝajn HR elementojn. Ripetu la klavkombinaĵon por atingi malproksimajn fokusajn spacojn.'
},
{
name: 'Komando por atingi la sekvan fokusan spacon',
legend: 'Press ${accessNextSpace} por atingi la plej proksiman neatingeblan fokusan spacon post la kursoro, ekzemple : du kuntuŝiĝajn HR elementojn. Ripetu la klavkombinajôn por atingi malproksimajn fokusajn spacojn'
},
{
name: 'Helpilo pri atingeblo',
legend: 'Premu ${a11yHelp}'
}
]
}
],
backspace: 'Retropaŝo',
tab: 'Tabo',
enter: 'Enigi',
shift: 'Registrumo',
ctrl: 'Stirklavo',
alt: 'Alt-klavo',
pause: 'Paŭzo',
capslock: 'Majuskla baskulo',
escape: 'Eskapa klavo',
pageUp: 'Antaŭa Paĝo',
pageDown: 'Sekva Paĝo',
end: 'Fino',
home: 'Hejmo',
leftArrow: 'Sago Maldekstren',
upArrow: 'Sago Supren',
rightArrow: 'Sago Dekstren',
downArrow: 'Sago Suben',
insert: 'Enmeti',
'delete': 'Forigi',
leftWindowKey: 'Maldekstra Windows-klavo',
rightWindowKey: 'Dekstra Windows-klavo',
selectKey: 'Selektklavo',
numpad0: 'Nombra Klavaro 0',
numpad1: 'Nombra Klavaro 1',
numpad2: 'Nombra Klavaro 2',
numpad3: 'Nombra Klavaro 3',
numpad4: 'Nombra Klavaro 4',
numpad5: 'Nombra Klavaro 5',
numpad6: 'Nombra Klavaro 6',
numpad7: 'Nombra Klavaro 7',
numpad8: 'Nombra Klavaro 8',
numpad9: 'Nombra Klavaro 9',
multiply: 'Obligi',
add: 'Almeti',
subtract: 'Subtrahi',
decimalPoint: 'Dekuma Punkto',
divide: 'Dividi',
f1: 'F1',
f2: 'F2',
f3: 'F3',
f4: 'F4',
f5: 'F5',
f6: 'F6',
f7: 'F7',
f8: 'F8',
f9: 'F9',
f10: 'F10',
f11: 'F11',
f12: 'F12',
numLock: 'Nombra Baskulo',
scrollLock: 'Ruluma Baskulo',
semiColon: 'Punktokomo',
equalSign: 'Egalsigno',
comma: 'Komo',
dash: 'Haltostreko',
period: 'Punkto',
forwardSlash: 'Oblikvo',
graveAccent: 'Malakuto',
openBracket: 'Malferma Krampo',
backSlash: 'Retroklino',
closeBracket: 'Ferma Krampo',
singleQuote: 'Citilo'
} );
|
const assert = require('assert');
const brains = require('./helpers/brains');
const Browser = require('../src');
// Parse string with cookies in it (like document.cookies) and return object
// with name/value pairs for each cookie.
function parse(cookies) {
return cookies
.split(/;\s*/)
.map((cookie)=> cookie.split('='))
.reduce(function(all, [name, value]) {
all[name] = value.replace(/^"(.*)"$/, '$1');
return all;
}, Object.create({}));
}
// Extracts cookies from @browser, parses and sets @cookies.
function cookiesFromHtml(browser) {
return parse(browser.source);
}
describe('Cookies', function() {
const browser = new Browser();
before(function() {
return brains.ready();
});
before(function() {
brains.get('/cookies', function(req, res) {
res.cookie('_name', 'value');
res.cookie('_expires1', '3s', { expires: new Date(Date.now() + 3000) });
res.cookie('_expires2', '5s', { 'Max-Age': 5000 });
res.cookie('_expires3', '0s', { expires: new Date(Date.now() - 100) });
res.cookie('_path1', 'yummy', { path: '/cookies' });
res.cookie('_path2', 'yummy', { path: '/cookies/sub' });
res.cookie('_path3', 'wrong', { path: '/wrong' });
res.cookie('_path4', 'yummy', { path: '/' });
res.cookie('_domain1', 'here', { domain: '.example.com' });
res.cookie('_domain2', 'not here', { domain: 'not.example.com' });
res.cookie('_domain3', 'wrong', { domain: 'notexample.com' });
res.cookie('_multiple', 'specific', { path: '/cookies' });
res.cookie('_multiple', 'general', { path: '/' });
res.cookie('_http_only', 'value', { httpOnly: true });
res.cookie('_dup', 'one', { path: '/' });
res.send('<html></html>');
});
brains.get('/cookies/invalid', function(req, res) {
res.setHeader('Set-Cookie', 'invalid');
res.send('<html></html>');
});
brains.get('/cookies/echo', function(req, res) {
const cookies = Object.keys(req.cookies).map((key)=> {
const value = req.cookies[key];
return `${key}=${value}`;
}).join('; ');
res.send(cookies);
});
brains.get('/cookies/empty', function(req, res) {
res.send('');
});
});
// -- Browser API --
describe('getCookie', function() {
before(function() {
browser.deleteCookies();
browser.setCookie({ name: 'foo', domain: 'www.example.com', value: 'full domain' });
browser.setCookie({ name: 'foo', domain: '.example.com', value: 'partial domain' });
browser.setCookie({ name: 'foo', domain: '.example.com', path: '/bar', value: 'full path' });
});
it('should find cookie by name', function() {
browser.visit('http://example.com/');
assert.equal(browser.getCookie('foo'), 'partial domain');
browser.window.close();
});
it('should find cookie with most specific domain', function() {
assert.equal(browser.getCookie({ name: 'foo', domain: 'dox.example.com' }), 'partial domain');
assert.equal(browser.getCookie({ name: 'foo', domain: 'example.com' }), 'partial domain');
assert.equal(browser.getCookie({ name: 'foo', domain: 'www.example.com' }), 'full domain');
});
it('should find cookie with most specific path', function() {
assert.equal(browser.getCookie({ name: 'foo', domain: 'example.com', path: '/' }), 'partial domain');
assert.equal(browser.getCookie({ name: 'foo', domain: 'example.com', path: '/bar' }), 'full path');
});
it('should return cookie object if second argument is true', function() {
assert.deepEqual(browser.getCookie({ name: 'foo', domain: 'www.example.com' }, true), {
name: 'foo',
value: 'full domain',
domain: 'www.example.com',
path: '/'
});
});
it('should return null if no match', function() {
assert.equal(browser.getCookie({ name: 'unknown', domain: 'example.com' }), null);
});
it('should return null if no match and second argument is true', function() {
assert.equal(browser.getCookie({ name: 'unknown', domain: 'example.com' }, true), null);
});
it('should fail if no domain specified', function() {
assert.throws(function() {
assert.equal(browser.getCookie('no-domain'));
}, 'No domain specified and no open page');
});
});
describe('deleteCookie', function() {
describe('by name', function() {
before(function() {
browser.deleteCookies();
browser.visit('http://example.com/');
browser.setCookie('foo', 'delete me');
browser.setCookie('bar', 'keep me');
});
it('should delete that cookie', function() {
browser.assert.cookie('foo', 'delete me');
assert(browser.deleteCookie('foo'));
browser.assert.cookie('foo', null);
browser.assert.cookie('bar', 'keep me');
});
after(function() {
browser.window.close();
});
});
describe('by name and domain', function() {
before(function() {
browser.deleteCookies();
browser.setCookie({ name: 'foo', domain: 'www.example.com', value: 'delete me' });
browser.setCookie({ name: 'foo', domain: '.example.com', value: 'keep me' });
});
it('should delete that cookie', function() {
browser.assert.cookie({ name: 'foo', domain: 'www.example.com' }, 'delete me');
assert(browser.deleteCookie({ name: 'foo', domain: 'www.example.com' }));
browser.assert.cookie({ name: 'foo', domain: 'www.example.com' }, 'keep me');
});
});
describe('by name, domain and path', function() {
before(function() {
browser.deleteCookies();
browser.setCookie({ name: 'foo', domain: 'example.com', path: '/', value: 'keep me' });
browser.setCookie({ name: 'foo', domain: 'example.com', path: '/bar', value: 'delete me' });
});
it('should delete that cookie', function() {
browser.assert.cookie({ name: 'foo', domain: 'example.com', path: '/bar' }, 'delete me');
assert(browser.deleteCookie({ name: 'foo', domain: 'example.com', path: '/bar' }));
browser.assert.cookie({ name: 'foo', domain: 'example.com', path: '/bar' }, 'keep me');
});
});
});
describe('deleteCookies', function() {
before(function() {
browser.deleteCookies();
browser.visit('http://example.com/');
browser.setCookie('foo', 'delete me');
browser.setCookie('bar', 'keep me');
});
it('should delete all cookies', function() {
browser.deleteCookies();
browser.assert.cookie('foo', null);
browser.assert.cookie('bar', null);
assert.equal(browser.cookies.length, 0);
});
after(function() {
browser.window.close();
});
});
// -- Sending and receiving --
describe('receive cookies', function() {
before(function() {
browser.deleteCookies();
return browser.visit('/cookies');
});
describe('cookies', function() {
it('should have access to session cookie', function() {
browser.assert.cookie('_name', 'value');
});
it('should have access to persistent cookie', function() {
browser.assert.cookie('_expires1', '3s');
browser.assert.cookie('_expires2', '5s');
});
it('should not have access to expired cookies', function() {
browser.assert.cookie('_expires3', null);
});
it('should have access to cookies for the path /cookies', function() {
browser.assert.cookie('_path1', 'yummy');
});
it('should have access to cookies for paths which are ancestors of /cookies', function() {
browser.assert.cookie('_path4', 'yummy');
});
it('should not have access to other paths', function() {
browser.assert.cookie('_path2', null);
browser.assert.cookie('_path3', null);
});
it('should have access to .domain', function() {
browser.assert.cookie('_domain1', 'here');
});
it('should not have access to other domains', function() {
browser.assert.cookie('_domain2', null);
browser.assert.cookie('_domain3', null);
});
it('should access most specific cookie', function() {
browser.assert.cookie('_multiple', 'specific');
});
});
describe('invalid cookie', function() {
before(function() {
return browser.visit('/cookies/invalid');
});
it('should not have the cookie', function() {
browser.assert.cookie('invalid', null);
});
});
describe('host in domain', function() {
it('should have access to host cookies', function() {
browser.assert.cookie('_domain1', 'here');
});
it('should not have access to other host cookies', function() {
browser.assert.cookie('_domain2', null);
browser.assert.cookie('_domain3', null);
});
});
describe('document.cookie', function() {
it('should return name/value pairs', function() {
const cookie = browser.document.cookie;
assert(/^(\w+=\w+; )+\w+=\w+$/.test(cookie));
});
describe('pairs', function() {
let pairs;
before(function() {
const cookie = browser.document.cookie;
pairs = parse(cookie);
});
it('should include only visible cookies', function() {
const keys = Object.keys(pairs).sort();
assert.deepEqual(keys, '_domain1 _dup _expires1 _expires2 _multiple _name _path1 _path4'.split(' '));
});
it('should match name to value', function() {
assert.equal(pairs._name, 'value');
assert.equal(pairs._path1, 'yummy');
});
it('should not include httpOnly cookies', function() {
for (let key in pairs)
assert(key !== '_http_only');
});
});
});
});
describe('host', function() {
before(function() {
browser.deleteCookies();
return browser.visit('/cookies');
});
it('should be able to set domain cookies', function() {
browser.assert.cookie({ name: '_domain1', domain: 'example.com', path: '/cookies' }, 'here');
});
});
describe('receive cookies and redirect', function() {
before(function() {
brains.get('/cookies/redirect', function(req, res) {
res.cookie('_expires4', '3s'); // expires: new Date(Date.now() + 3000), 'Path': '/'
res.redirect('/');
});
browser.deleteCookies();
return browser.visit('/cookies/redirect');
});
it('should have access to persistent cookie', function() {
browser.assert.cookie({ name: '_expires4', domain: 'example.com', path: '/cookies/redirect' }, '3s');
});
});
describe('duplicates', function() {
before(async function() {
brains.get('/cookies2', function(req, res) {
res.cookie('_dup', 'two', { path: '/' });
res.send('');
});
brains.get('/cookies3', function(req, res) {
res.cookie('_dup', 'three', { path: '/' });
res.send('');
});
browser.deleteCookies();
await browser.visit('/cookies2');
await browser.visit('/cookies3');
});
it('should retain last value', function() {
browser.assert.cookie('_dup', 'three');
});
it('should only retain last cookie', function() {
assert.equal(browser.cookies.length, 1);
});
});
describe('send cookies', function() {
let cookies;
before(async function() {
browser.deleteCookies();
browser.setCookie({ domain: 'example.com', name: '_name', value: 'value' });
browser.setCookie({ domain: 'example.com', name: '_expires1', 'max-age': 3000, value: '3s' });
browser.setCookie({ domain: 'example.com', name: '_expires2', 'max-age': 0, value: '0s' });
browser.setCookie({ domain: 'example.com', path: '/cookies', name: '_path1', value: 'here' });
browser.setCookie({ domain: 'example.com', path: '/cookies/echo', name: '_path2', value: 'here' });
browser.setCookie({ domain: 'example.com', path: '/jars', name: '_path3', value: 'there' });
browser.setCookie({ domain: 'example.com', path: '/cookies/fido', name: '_path4', value: 'there' });
browser.setCookie({ domain: 'example.com', path: '/', name: '_path5', value: 'here' });
browser.setCookie({ domain: '.example.com', name: '_domain1', value: 'here' });
browser.setCookie({ domain: 'not.example.com', name: '_domain2', value: 'there' });
browser.setCookie({ domain: 'notexample.com', name: '_domain3', value: 'there' });
await browser.visit('/cookies/echo');
cookies = cookiesFromHtml(browser);
});
it('should send session cookie', function() {
assert.equal(cookies._name, 'value');
});
it('should pass persistent cookie to server', function() {
assert.equal(cookies._expires1, '3s');
});
it('should not pass expired cookie to server', function() {
assert.equal(cookies._expires2, null);
});
it('should pass path cookies to server', function() {
assert.equal(cookies._path1, 'here');
assert.equal(cookies._path2, 'here');
assert.equal(cookies._path5, 'here');
});
it('should not pass unrelated path cookies to server', function() {
assert.equal(cookies._path3, null, 'path3');
assert.equal(cookies._path4, null, 'path4');
assert.equal(cookies._path6, null, 'path5');
});
it('should pass sub-domain cookies to server', function() {
assert.equal(cookies._domain1, 'here');
});
it('should not pass other domain cookies to server', function() {
assert.equal(cookies._domain2, null);
assert.equal(cookies._domain3, null);
});
});
describe('setting cookies from subdomains', function() {
before(function() {
browser.deleteCookies();
browser.cookies.update('foo=bar; domain=example.com');
});
it('should be accessible', function() {
browser.assert.cookie({ domain: 'example.com', name: 'foo' }, 'bar');
browser.assert.cookie({ domain: 'www.example.com', name: 'foo' }, 'bar');
});
});
// -- Access from JS --
describe('document.cookie', function() {
describe('setting cookie', function() {
before(async function() {
await browser.visit('/cookies');
browser.document.cookie = 'foo=bar';
});
it('should be available from document', function() {
assert(~browser.document.cookie.split('; ').indexOf('foo=bar'));
});
describe('on reload', function() {
before(function() {
return browser.visit('/cookies/echo');
});
it('should send to server', function() {
const cookies = cookiesFromHtml(browser);
assert.equal(cookies.foo, 'bar');
});
});
describe('different path', function() {
before(async function() {
await browser.visit('/cookies');
browser.document.cookie = 'foo=bar; path=/cookies';
await browser.visit('/cookies/invalid');
browser.document.cookie = 'foo=qux; path=/cookies/invalid'; // more specific path, not visible to /cookies.echo
await browser.visit('/cookies/echo');
});
it('should not be visible', function() {
const cookies = cookiesFromHtml(browser);
assert(!cookies.bar);
assert.equal(cookies.foo, 'bar');
});
});
});
describe('setting cookie with quotes', function() {
before(async function() {
await browser.visit('/cookies/empty');
browser.document.cookie = 'foo=bar\'baz';
});
it('should be available from document', function() {
browser.assert.cookie('foo', 'bar\'baz');
});
});
describe('setting cookie with semicolon', function() {
before(async function() {
await browser.visit('/cookies/empty');
browser.document.cookie = 'foo=bar; baz';
});
it('should be available from document', function() {
browser.assert.cookie('foo', 'bar');
});
});
});
after(function() {
browser.destroy();
});
});
|
module.exports = {
DropModal: require('./DropModal'),
WaveModal: require('./WaveModal'),
FlyModal: require('./FlyModal'),
FadeModal: require('./FadeModal'),
ScaleModal: require('./ScaleModal'),
OutlineModal: require('./OutlineModal'),
}
|
/**
* @license
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="es" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
export { default as add } from './add.js';
export { default as after } from './after.js';
export { default as ary } from './ary.js';
export { default as assign } from './assign.js';
export { default as assignIn } from './assignIn.js';
export { default as assignInWith } from './assignInWith.js';
export { default as assignWith } from './assignWith.js';
export { default as at } from './at.js';
export { default as attempt } from './attempt.js';
export { default as before } from './before.js';
export { default as bind } from './bind.js';
export { default as bindAll } from './bindAll.js';
export { default as bindKey } from './bindKey.js';
export { default as camelCase } from './camelCase.js';
export { default as capitalize } from './capitalize.js';
export { default as castArray } from './castArray.js';
export { default as ceil } from './ceil.js';
export { default as chain } from './chain.js';
export { default as chunk } from './chunk.js';
export { default as clamp } from './clamp.js';
export { default as clone } from './clone.js';
export { default as cloneDeep } from './cloneDeep.js';
export { default as cloneDeepWith } from './cloneDeepWith.js';
export { default as cloneWith } from './cloneWith.js';
export { default as commit } from './commit.js';
export { default as compact } from './compact.js';
export { default as concat } from './concat.js';
export { default as cond } from './cond.js';
export { default as conforms } from './conforms.js';
export { default as constant } from './constant.js';
export { default as countBy } from './countBy.js';
export { default as create } from './create.js';
export { default as curry } from './curry.js';
export { default as curryRight } from './curryRight.js';
export { default as debounce } from './debounce.js';
export { default as deburr } from './deburr.js';
export { default as defaults } from './defaults.js';
export { default as defaultsDeep } from './defaultsDeep.js';
export { default as defer } from './defer.js';
export { default as delay } from './delay.js';
export { default as difference } from './difference.js';
export { default as differenceBy } from './differenceBy.js';
export { default as differenceWith } from './differenceWith.js';
export { default as divide } from './divide.js';
export { default as drop } from './drop.js';
export { default as dropRight } from './dropRight.js';
export { default as dropRightWhile } from './dropRightWhile.js';
export { default as dropWhile } from './dropWhile.js';
export { default as each } from './each.js';
export { default as eachRight } from './eachRight.js';
export { default as endsWith } from './endsWith.js';
export { default as entries } from './entries.js';
export { default as entriesIn } from './entriesIn.js';
export { default as eq } from './eq.js';
export { default as escape } from './escape.js';
export { default as escapeRegExp } from './escapeRegExp.js';
export { default as every } from './every.js';
export { default as extend } from './extend.js';
export { default as extendWith } from './extendWith.js';
export { default as fill } from './fill.js';
export { default as filter } from './filter.js';
export { default as find } from './find.js';
export { default as findIndex } from './findIndex.js';
export { default as findKey } from './findKey.js';
export { default as findLast } from './findLast.js';
export { default as findLastIndex } from './findLastIndex.js';
export { default as findLastKey } from './findLastKey.js';
export { default as first } from './first.js';
export { default as flatMap } from './flatMap.js';
export { default as flatMapDeep } from './flatMapDeep.js';
export { default as flatMapDepth } from './flatMapDepth.js';
export { default as flatten } from './flatten.js';
export { default as flattenDeep } from './flattenDeep.js';
export { default as flattenDepth } from './flattenDepth.js';
export { default as flip } from './flip.js';
export { default as floor } from './floor.js';
export { default as flow } from './flow.js';
export { default as flowRight } from './flowRight.js';
export { default as forEach } from './forEach.js';
export { default as forEachRight } from './forEachRight.js';
export { default as forIn } from './forIn.js';
export { default as forInRight } from './forInRight.js';
export { default as forOwn } from './forOwn.js';
export { default as forOwnRight } from './forOwnRight.js';
export { default as fromPairs } from './fromPairs.js';
export { default as functions } from './functions.js';
export { default as functionsIn } from './functionsIn.js';
export { default as get } from './get.js';
export { default as groupBy } from './groupBy.js';
export { default as gt } from './gt.js';
export { default as gte } from './gte.js';
export { default as has } from './has.js';
export { default as hasIn } from './hasIn.js';
export { default as head } from './head.js';
export { default as identity } from './identity.js';
export { default as inRange } from './inRange.js';
export { default as includes } from './includes.js';
export { default as indexOf } from './indexOf.js';
export { default as initial } from './initial.js';
export { default as intersection } from './intersection.js';
export { default as intersectionBy } from './intersectionBy.js';
export { default as intersectionWith } from './intersectionWith.js';
export { default as invert } from './invert.js';
export { default as invertBy } from './invertBy.js';
export { default as invoke } from './invoke.js';
export { default as invokeMap } from './invokeMap.js';
export { default as isArguments } from './isArguments.js';
export { default as isArray } from './isArray.js';
export { default as isArrayBuffer } from './isArrayBuffer.js';
export { default as isArrayLike } from './isArrayLike.js';
export { default as isArrayLikeObject } from './isArrayLikeObject.js';
export { default as isBoolean } from './isBoolean.js';
export { default as isBuffer } from './isBuffer.js';
export { default as isDate } from './isDate.js';
export { default as isElement } from './isElement.js';
export { default as isEmpty } from './isEmpty.js';
export { default as isEqual } from './isEqual.js';
export { default as isEqualWith } from './isEqualWith.js';
export { default as isError } from './isError.js';
export { default as isFinite } from './isFinite.js';
export { default as isFunction } from './isFunction.js';
export { default as isInteger } from './isInteger.js';
export { default as isLength } from './isLength.js';
export { default as isMap } from './isMap.js';
export { default as isMatch } from './isMatch.js';
export { default as isMatchWith } from './isMatchWith.js';
export { default as isNaN } from './isNaN.js';
export { default as isNative } from './isNative.js';
export { default as isNil } from './isNil.js';
export { default as isNull } from './isNull.js';
export { default as isNumber } from './isNumber.js';
export { default as isObject } from './isObject.js';
export { default as isObjectLike } from './isObjectLike.js';
export { default as isPlainObject } from './isPlainObject.js';
export { default as isRegExp } from './isRegExp.js';
export { default as isSafeInteger } from './isSafeInteger.js';
export { default as isSet } from './isSet.js';
export { default as isString } from './isString.js';
export { default as isSymbol } from './isSymbol.js';
export { default as isTypedArray } from './isTypedArray.js';
export { default as isUndefined } from './isUndefined.js';
export { default as isWeakMap } from './isWeakMap.js';
export { default as isWeakSet } from './isWeakSet.js';
export { default as iteratee } from './iteratee.js';
export { default as join } from './join.js';
export { default as kebabCase } from './kebabCase.js';
export { default as keyBy } from './keyBy.js';
export { default as keys } from './keys.js';
export { default as keysIn } from './keysIn.js';
export { default as last } from './last.js';
export { default as lastIndexOf } from './lastIndexOf.js';
export { default as lodash } from './wrapperLodash.js';
export { default as lowerCase } from './lowerCase.js';
export { default as lowerFirst } from './lowerFirst.js';
export { default as lt } from './lt.js';
export { default as lte } from './lte.js';
export { default as map } from './map.js';
export { default as mapKeys } from './mapKeys.js';
export { default as mapValues } from './mapValues.js';
export { default as matches } from './matches.js';
export { default as matchesProperty } from './matchesProperty.js';
export { default as max } from './max.js';
export { default as maxBy } from './maxBy.js';
export { default as mean } from './mean.js';
export { default as meanBy } from './meanBy.js';
export { default as memoize } from './memoize.js';
export { default as merge } from './merge.js';
export { default as mergeWith } from './mergeWith.js';
export { default as method } from './method.js';
export { default as methodOf } from './methodOf.js';
export { default as min } from './min.js';
export { default as minBy } from './minBy.js';
export { default as mixin } from './mixin.js';
export { default as multiply } from './multiply.js';
export { default as negate } from './negate.js';
export { default as next } from './next.js';
export { default as noop } from './noop.js';
export { default as now } from './now.js';
export { default as nth } from './nth.js';
export { default as nthArg } from './nthArg.js';
export { default as omit } from './omit.js';
export { default as omitBy } from './omitBy.js';
export { default as once } from './once.js';
export { default as orderBy } from './orderBy.js';
export { default as over } from './over.js';
export { default as overArgs } from './overArgs.js';
export { default as overEvery } from './overEvery.js';
export { default as overSome } from './overSome.js';
export { default as pad } from './pad.js';
export { default as padEnd } from './padEnd.js';
export { default as padStart } from './padStart.js';
export { default as parseInt } from './parseInt.js';
export { default as partial } from './partial.js';
export { default as partialRight } from './partialRight.js';
export { default as partition } from './partition.js';
export { default as pick } from './pick.js';
export { default as pickBy } from './pickBy.js';
export { default as plant } from './plant.js';
export { default as property } from './property.js';
export { default as propertyOf } from './propertyOf.js';
export { default as pull } from './pull.js';
export { default as pullAll } from './pullAll.js';
export { default as pullAllBy } from './pullAllBy.js';
export { default as pullAllWith } from './pullAllWith.js';
export { default as pullAt } from './pullAt.js';
export { default as random } from './random.js';
export { default as range } from './range.js';
export { default as rangeRight } from './rangeRight.js';
export { default as rearg } from './rearg.js';
export { default as reduce } from './reduce.js';
export { default as reduceRight } from './reduceRight.js';
export { default as reject } from './reject.js';
export { default as remove } from './remove.js';
export { default as repeat } from './repeat.js';
export { default as replace } from './replace.js';
export { default as rest } from './rest.js';
export { default as result } from './result.js';
export { default as reverse } from './reverse.js';
export { default as round } from './round.js';
export { default as sample } from './sample.js';
export { default as sampleSize } from './sampleSize.js';
export { default as set } from './set.js';
export { default as setWith } from './setWith.js';
export { default as shuffle } from './shuffle.js';
export { default as size } from './size.js';
export { default as slice } from './slice.js';
export { default as snakeCase } from './snakeCase.js';
export { default as some } from './some.js';
export { default as sortBy } from './sortBy.js';
export { default as sortedIndex } from './sortedIndex.js';
export { default as sortedIndexBy } from './sortedIndexBy.js';
export { default as sortedIndexOf } from './sortedIndexOf.js';
export { default as sortedLastIndex } from './sortedLastIndex.js';
export { default as sortedLastIndexBy } from './sortedLastIndexBy.js';
export { default as sortedLastIndexOf } from './sortedLastIndexOf.js';
export { default as sortedUniq } from './sortedUniq.js';
export { default as sortedUniqBy } from './sortedUniqBy.js';
export { default as split } from './split.js';
export { default as spread } from './spread.js';
export { default as startCase } from './startCase.js';
export { default as startsWith } from './startsWith.js';
export { default as stubArray } from './stubArray.js';
export { default as stubFalse } from './stubFalse.js';
export { default as stubObject } from './stubObject.js';
export { default as stubString } from './stubString.js';
export { default as stubTrue } from './stubTrue.js';
export { default as subtract } from './subtract.js';
export { default as sum } from './sum.js';
export { default as sumBy } from './sumBy.js';
export { default as tail } from './tail.js';
export { default as take } from './take.js';
export { default as takeRight } from './takeRight.js';
export { default as takeRightWhile } from './takeRightWhile.js';
export { default as takeWhile } from './takeWhile.js';
export { default as tap } from './tap.js';
export { default as template } from './template.js';
export { default as templateSettings } from './templateSettings.js';
export { default as throttle } from './throttle.js';
export { default as thru } from './thru.js';
export { default as times } from './times.js';
export { default as toArray } from './toArray.js';
export { default as toFinite } from './toFinite.js';
export { default as toInteger } from './toInteger.js';
export { default as toIterator } from './toIterator.js';
export { default as toJSON } from './toJSON.js';
export { default as toLength } from './toLength.js';
export { default as toLower } from './toLower.js';
export { default as toNumber } from './toNumber.js';
export { default as toPairs } from './toPairs.js';
export { default as toPairsIn } from './toPairsIn.js';
export { default as toPath } from './toPath.js';
export { default as toPlainObject } from './toPlainObject.js';
export { default as toSafeInteger } from './toSafeInteger.js';
export { default as toString } from './toString.js';
export { default as toUpper } from './toUpper.js';
export { default as transform } from './transform.js';
export { default as trim } from './trim.js';
export { default as trimEnd } from './trimEnd.js';
export { default as trimStart } from './trimStart.js';
export { default as truncate } from './truncate.js';
export { default as unary } from './unary.js';
export { default as unescape } from './unescape.js';
export { default as union } from './union.js';
export { default as unionBy } from './unionBy.js';
export { default as unionWith } from './unionWith.js';
export { default as uniq } from './uniq.js';
export { default as uniqBy } from './uniqBy.js';
export { default as uniqWith } from './uniqWith.js';
export { default as uniqueId } from './uniqueId.js';
export { default as unset } from './unset.js';
export { default as unzip } from './unzip.js';
export { default as unzipWith } from './unzipWith.js';
export { default as update } from './update.js';
export { default as updateWith } from './updateWith.js';
export { default as upperCase } from './upperCase.js';
export { default as upperFirst } from './upperFirst.js';
export { default as value } from './value.js';
export { default as valueOf } from './valueOf.js';
export { default as values } from './values.js';
export { default as valuesIn } from './valuesIn.js';
export { default as without } from './without.js';
export { default as words } from './words.js';
export { default as wrap } from './wrap.js';
export { default as wrapperAt } from './wrapperAt.js';
export { default as wrapperChain } from './wrapperChain.js';
export { default as wrapperCommit } from './commit.js';
export { default as wrapperLodash } from './wrapperLodash.js';
export { default as wrapperNext } from './next.js';
export { default as wrapperPlant } from './plant.js';
export { default as wrapperReverse } from './wrapperReverse.js';
export { default as wrapperToIterator } from './toIterator.js';
export { default as wrapperValue } from './wrapperValue.js';
export { default as xor } from './xor.js';
export { default as xorBy } from './xorBy.js';
export { default as xorWith } from './xorWith.js';
export { default as zip } from './zip.js';
export { default as zipObject } from './zipObject.js';
export { default as zipObjectDeep } from './zipObjectDeep.js';
export { default as zipWith } from './zipWith.js';
export { default as default } from './lodash.default';
|
THREE.UCSCharacter = function() {
var scope = this;
var mesh;
this.scale = 1;
this.root = new THREE.Object3D();
this.numSkins;
this.numMorphs;
this.skins = [];
this.materials = [];
this.morphs = [];
this.mixer = new THREE.AnimationMixer( this.root );
this.onLoadComplete = function () {};
this.loadCounter = 0;
this.loadParts = function ( config ) {
this.numSkins = config.skins.length;
this.numMorphs = config.morphs.length;
// Character geometry + number of skins
this.loadCounter = 1 + config.skins.length;
// SKINS
this.skins = loadTextures( config.baseUrl + "skins/", config.skins );
this.materials = createMaterials( this.skins );
// MORPHS
this.morphs = config.morphs;
// CHARACTER
var loader = new THREE.JSONLoader();
console.log( config.baseUrl + config.character );
loader.load( config.baseUrl + config.character, function( geometry ) {
geometry.computeBoundingBox();
geometry.computeVertexNormals();
mesh = new THREE.SkinnedMesh( geometry, new THREE.MultiMaterial() );
mesh.name = config.character;
scope.root.add( mesh );
var bb = geometry.boundingBox;
scope.root.scale.set( config.s, config.s, config.s );
scope.root.position.set( config.x, config.y - bb.min.y * config.s, config.z );
mesh.castShadow = true;
mesh.receiveShadow = true;
scope.mixer.clipAction( geometry.animations[0], mesh ).play();
scope.setSkin( 0 );
scope.checkLoadComplete();
} );
};
this.setSkin = function( index ) {
if ( mesh && scope.materials ) {
mesh.material = scope.materials[ index ];
}
};
this.updateMorphs = function( influences ) {
if ( mesh ) {
for ( var i = 0; i < scope.numMorphs; i ++ ) {
mesh.morphTargetInfluences[ i ] = influences[ scope.morphs[ i ] ] / 100;
}
}
};
function loadTextures( baseUrl, textureUrls ) {
var textureLoader = new THREE.TextureLoader();
var textures = [];
for ( var i = 0; i < textureUrls.length; i ++ ) {
textures[ i ] = textureLoader.load( baseUrl + textureUrls[ i ], scope.checkLoadComplete );
textures[ i ].mapping = THREE.UVMapping;
textures[ i ].name = textureUrls[ i ];
}
return textures;
}
function createMaterials( skins ) {
var materials = [];
for ( var i = 0; i < skins.length; i ++ ) {
materials[ i ] = new THREE.MeshLambertMaterial( {
color: 0xeeeeee,
specular: 10.0,
map: skins[ i ],
skinning: true,
morphTargets: true
} );
}
return materials;
}
this.checkLoadComplete = function () {
scope.loadCounter -= 1;
if ( scope.loadCounter === 0 ) {
scope.onLoadComplete();
}
}
};
|
/* global LocationHashbangUrl: false, LocationHtml5Url: false */
'use strict';
describe('$location', function() {
// Mock out the $log function - see testabilityPatch.js
beforeEach(module(provideLog));
afterEach(function() {
// link rewriting used in html5 mode on legacy browsers binds to document.onClick, so we need
// to clean this up after each test.
jqLite(window.document).off('click');
});
describe('defaults', function() {
it('should have hashPrefix of "!"', function() {
initService({});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
function($location) {
$location.path('/a/b/c');
expect($location.absUrl()).toEqual('http://host.com/base/index.html#!/a/b/c');
});
});
it('should not be html5 mode', function() {
initService({});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
function($location) {
$location.path('/a/b/c');
expect($location.absUrl()).toContain('#!');
});
});
});
describe('File Protocol', function() {
/* global urlParsingNode: true */
var urlParsingNodePlaceholder;
beforeEach(function() {
// Support: non-Windows browsers
// These tests expect a Windows environment which we can only guarantee
// on IE & Edge.
if (msie || /\bEdge\/[\d.]+\b/.test(window.navigator.userAgent)) return;
urlParsingNodePlaceholder = urlParsingNode;
//temporarily overriding the DOM element
//with output from IE, if not in IE
urlParsingNode = {
hash: '#/C:/',
host: '',
hostname: '',
href: 'file:///C:/base#!/C:/foo',
pathname: '/C:/foo',
port: '',
protocol: 'file:',
search: '',
setAttribute: angular.noop
};
});
afterEach(function() {
// Support: non-Windows browsers
if (msie || /\bEdge\/[\d.]+\b/.test(window.navigator.userAgent)) return;
//reset urlParsingNode
urlParsingNode = urlParsingNodePlaceholder;
});
it('should not include the drive name in path() on WIN', function() {
//See issue #4680 for details
var locationUrl = new LocationHashbangUrl('file:///base', 'file:///', '#!');
locationUrl.$$parse('file:///base#!/foo?a=b&c#hash');
expect(locationUrl.path()).toBe('/foo');
});
it('should include the drive name if it was provided in the input url', function() {
var locationUrl = new LocationHashbangUrl('file:///base', 'file:///', '#!');
locationUrl.$$parse('file:///base#!/C:/foo?a=b&c#hash');
expect(locationUrl.path()).toBe('/C:/foo');
});
});
describe('NewUrl', function() {
function createLocationHtml5Url() {
var locationUrl = new LocationHtml5Url('http://www.domain.com:9877/', 'http://www.domain.com:9877/');
locationUrl.$$parse('http://www.domain.com:9877/path/b?search=a&b=c&d#hash');
return locationUrl;
}
it('should provide common getters', function() {
var locationUrl = createLocationHtml5Url();
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#hash');
expect(locationUrl.protocol()).toBe('http');
expect(locationUrl.host()).toBe('www.domain.com');
expect(locationUrl.port()).toBe(9877);
expect(locationUrl.path()).toBe('/path/b');
expect(locationUrl.search()).toEqual({search: 'a', b: 'c', d: true});
expect(locationUrl.hash()).toBe('hash');
expect(locationUrl.url()).toBe('/path/b?search=a&b=c&d#hash');
});
it('path() should change path', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.path('/new/path');
expect(locationUrl.path()).toBe('/new/path');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/new/path?search=a&b=c&d#hash');
});
it('path() should not break on numeric values', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.path(1);
expect(locationUrl.path()).toBe('/1');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/1?search=a&b=c&d#hash');
});
it('path() should allow using 0 as path', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.path(0);
expect(locationUrl.path()).toBe('/0');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/0?search=a&b=c&d#hash');
});
it('path() should set to empty path on null value', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.path('/foo');
expect(locationUrl.path()).toBe('/foo');
locationUrl.path(null);
expect(locationUrl.path()).toBe('/');
});
it('search() should accept string', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search('x=y&c');
expect(locationUrl.search()).toEqual({x: 'y', c: true});
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?x=y&c#hash');
});
it('search() should accept object', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search({one: 1, two: true});
expect(locationUrl.search()).toEqual({one: 1, two: true});
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?one=1&two#hash');
});
it('search() should copy object', function() {
var locationUrl = createLocationHtml5Url();
var obj = {one: 1, two: true, three: null};
locationUrl.search(obj);
expect(obj).toEqual({one: 1, two: true, three: null});
obj.one = 'changed';
expect(locationUrl.search()).toEqual({one: 1, two: true});
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?one=1&two#hash');
});
it('search() should change single parameter', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search({id: 'old', preserved: true});
locationUrl.search('id', 'new');
expect(locationUrl.search()).toEqual({id: 'new', preserved: true});
});
it('search() should remove single parameter', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search({id: 'old', preserved: true});
locationUrl.search('id', null);
expect(locationUrl.search()).toEqual({preserved: true});
});
it('search() should remove multiple parameters', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search({one: 1, two: true});
expect(locationUrl.search()).toEqual({one: 1, two: true});
locationUrl.search({one: null, two: null});
expect(locationUrl.search()).toEqual({});
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b#hash');
});
it('search() should accept numeric keys', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search({1: 'one', 2: 'two'});
expect(locationUrl.search()).toEqual({'1': 'one', '2': 'two'});
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?1=one&2=two#hash');
});
it('search() should handle multiple value', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search('a&b');
expect(locationUrl.search()).toEqual({a: true, b: true});
locationUrl.search('a', null);
expect(locationUrl.search()).toEqual({b: true});
locationUrl.search('b', undefined);
expect(locationUrl.search()).toEqual({});
});
it('search() should handle single value', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search('ignore');
expect(locationUrl.search()).toEqual({ignore: true});
locationUrl.search(1);
expect(locationUrl.search()).toEqual({1: true});
});
it('search() should throw error an incorrect argument', function() {
var locationUrl = createLocationHtml5Url();
expect(function() {
locationUrl.search(null);
}).toThrowMinErr('$location', 'isrcharg', 'The first argument of the `$location#search()` call must be a string or an object.');
expect(function() {
locationUrl.search(undefined);
}).toThrowMinErr('$location', 'isrcharg', 'The first argument of the `$location#search()` call must be a string or an object.');
});
it('hash() should change hash fragment', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.hash('new-hash');
expect(locationUrl.hash()).toBe('new-hash');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#new-hash');
});
it('hash() should accept numeric parameter', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.hash(5);
expect(locationUrl.hash()).toBe('5');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#5');
});
it('hash() should allow using 0', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.hash(0);
expect(locationUrl.hash()).toBe('0');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#0');
});
it('hash() should accept null parameter', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.hash(null);
expect(locationUrl.hash()).toBe('');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d');
});
it('url() should change the path, search and hash', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.url('/some/path?a=b&c=d#hhh');
expect(locationUrl.url()).toBe('/some/path?a=b&c=d#hhh');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/some/path?a=b&c=d#hhh');
expect(locationUrl.path()).toBe('/some/path');
expect(locationUrl.search()).toEqual({a: 'b', c: 'd'});
expect(locationUrl.hash()).toBe('hhh');
});
it('url() should change only hash when no search and path specified', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.url('#some-hash');
expect(locationUrl.hash()).toBe('some-hash');
expect(locationUrl.url()).toBe('/path/b?search=a&b=c&d#some-hash');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/path/b?search=a&b=c&d#some-hash');
});
it('url() should change only search and hash when no path specified', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.url('?a=b');
expect(locationUrl.search()).toEqual({a: 'b'});
expect(locationUrl.hash()).toBe('');
expect(locationUrl.path()).toBe('/path/b');
});
it('url() should reset search and hash when only path specified', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.url('/new/path');
expect(locationUrl.path()).toBe('/new/path');
expect(locationUrl.search()).toEqual({});
expect(locationUrl.hash()).toBe('');
});
it('url() should change path when empty string specified', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.url('');
expect(locationUrl.path()).toBe('/');
expect(locationUrl.search()).toEqual({});
expect(locationUrl.hash()).toBe('');
});
it('replace should set $$replace flag and return itself', function() {
var locationUrl = createLocationHtml5Url();
expect(locationUrl.$$replace).toBe(false);
locationUrl.replace();
expect(locationUrl.$$replace).toBe(true);
expect(locationUrl.replace()).toBe(locationUrl);
});
it('should parse new url', function() {
var locationUrl = new LocationHtml5Url('http://host.com/', 'http://host.com/');
locationUrl.$$parse('http://host.com/base');
expect(locationUrl.path()).toBe('/base');
locationUrl = new LocationHtml5Url('http://host.com/', 'http://host.com/');
locationUrl.$$parse('http://host.com/base#');
expect(locationUrl.path()).toBe('/base');
});
it('should prefix path with forward-slash', function() {
var locationUrl = new LocationHtml5Url('http://server/', 'http://server/');
locationUrl.path('b');
expect(locationUrl.path()).toBe('/b');
expect(locationUrl.absUrl()).toBe('http://server/b');
});
it('should set path to forward-slash when empty', function() {
var locationUrl = new LocationHtml5Url('http://server/', 'http://server/');
locationUrl.$$parse('http://server/');
expect(locationUrl.path()).toBe('/');
expect(locationUrl.absUrl()).toBe('http://server/');
});
it('setters should return Url object to allow chaining', function() {
var locationUrl = createLocationHtml5Url();
expect(locationUrl.path('/any')).toBe(locationUrl);
expect(locationUrl.search('')).toBe(locationUrl);
expect(locationUrl.hash('aaa')).toBe(locationUrl);
expect(locationUrl.url('/some')).toBe(locationUrl);
});
it('should not preserve old properties when parsing new url', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.$$parse('http://www.domain.com:9877/a');
expect(locationUrl.path()).toBe('/a');
expect(locationUrl.search()).toEqual({});
expect(locationUrl.hash()).toBe('');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/a');
});
it('should not rewrite when hashbang url is not given', function() {
initService({html5Mode:true,hashPrefix: '!',supportHistory: true});
inject(
initBrowser({url:'http://domain.com/base/a/b',basePath: '/base'}),
function($rootScope, $location, $browser) {
expect($browser.url()).toBe('http://domain.com/base/a/b');
}
);
});
it('should prepend path with basePath', function() {
var locationUrl = new LocationHtml5Url('http://server/base/', 'http://server/base/');
locationUrl.$$parse('http://server/base/abc?a');
expect(locationUrl.path()).toBe('/abc');
expect(locationUrl.search()).toEqual({a: true});
locationUrl.path('/new/path');
expect(locationUrl.absUrl()).toBe('http://server/base/new/path?a');
});
it('should throw error when invalid server url given', function() {
var locationUrl = new LocationHtml5Url('http://server.org/base/abc', 'http://server.org/base/');
expect(function() {
locationUrl.$$parse('http://other.server.org/path#/path');
}).toThrowMinErr('$location', 'ipthprfx', 'Invalid url "http://other.server.org/path#/path", missing path prefix "http://server.org/base/".');
});
it('should throw error when invalid base url given', function() {
var locationUrl = new LocationHtml5Url('http://server.org/base/abc', 'http://server.org/base/');
expect(function() {
locationUrl.$$parse('http://server.org/path#/path');
}).toThrowMinErr('$location', 'ipthprfx', 'Invalid url "http://server.org/path#/path", missing path prefix "http://server.org/base/".');
});
describe('state', function() {
it('should set $$state and return itself', function() {
var locationUrl = createLocationHtml5Url();
expect(locationUrl.$$state).toEqual(undefined);
var returned = locationUrl.state({a: 2});
expect(locationUrl.$$state).toEqual({a: 2});
expect(returned).toBe(locationUrl);
});
it('should set state', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.state({a: 2});
expect(locationUrl.state()).toEqual({a: 2});
});
it('should allow to set both URL and state', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.url('/foo').state({a: 2});
expect(locationUrl.url()).toEqual('/foo');
expect(locationUrl.state()).toEqual({a: 2});
});
it('should allow to mix state and various URL functions', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.path('/foo').hash('abcd').state({a: 2}).search('bar', 'baz');
expect(locationUrl.path()).toEqual('/foo');
expect(locationUrl.state()).toEqual({a: 2});
expect(locationUrl.search() && locationUrl.search().bar).toBe('baz');
expect(locationUrl.hash()).toEqual('abcd');
});
});
describe('encoding', function() {
it('should encode special characters', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.path('/a <>#');
locationUrl.search({'i j': '<>#'});
locationUrl.hash('<>#');
expect(locationUrl.path()).toBe('/a <>#');
expect(locationUrl.search()).toEqual({'i j': '<>#'});
expect(locationUrl.hash()).toBe('<>#');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/a%20%3C%3E%23?i%20j=%3C%3E%23#%3C%3E%23');
});
it('should not encode !$:@', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.path('/!$:@');
locationUrl.search('');
locationUrl.hash('!$:@');
expect(locationUrl.absUrl()).toBe('http://www.domain.com:9877/!$:@#!$:@');
});
it('should decode special characters', function() {
var locationUrl = new LocationHtml5Url('http://host.com/', 'http://host.com/');
locationUrl.$$parse('http://host.com/a%20%3C%3E%23?i%20j=%3C%3E%23#x%20%3C%3E%23');
expect(locationUrl.path()).toBe('/a <>#');
expect(locationUrl.search()).toEqual({'i j': '<>#'});
expect(locationUrl.hash()).toBe('x <>#');
});
it('should decode pluses as spaces in urls', function() {
var locationUrl = new LocationHtml5Url('http://host.com/', 'http://host.com/');
locationUrl.$$parse('http://host.com/?a+b=c+d');
expect(locationUrl.search()).toEqual({'a b':'c d'});
});
it('should retain pluses when setting search queries', function() {
var locationUrl = createLocationHtml5Url();
locationUrl.search({'a+b':'c+d'});
expect(locationUrl.search()).toEqual({'a+b':'c+d'});
});
});
});
describe('HashbangUrl', function() {
function createHashbangUrl() {
var locationUrl = new LocationHashbangUrl('http://www.server.org:1234/base', 'http://www.server.org:1234/', '#!');
locationUrl.$$parse('http://www.server.org:1234/base#!/path?a=b&c#hash');
return locationUrl;
}
it('should parse hashbang url into path and search', function() {
var locationUrl = createHashbangUrl();
expect(locationUrl.protocol()).toBe('http');
expect(locationUrl.host()).toBe('www.server.org');
expect(locationUrl.port()).toBe(1234);
expect(locationUrl.path()).toBe('/path');
expect(locationUrl.search()).toEqual({a: 'b', c: true});
expect(locationUrl.hash()).toBe('hash');
});
it('absUrl() should return hashbang url', function() {
var locationUrl = createHashbangUrl();
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base#!/path?a=b&c#hash');
locationUrl.path('/new/path');
locationUrl.search({one: 1});
locationUrl.hash('hhh');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base#!/new/path?one=1#hhh');
});
it('should preserve query params in base', function() {
var locationUrl = new LocationHashbangUrl('http://www.server.org:1234/base?base=param', 'http://www.server.org:1234/', '#');
locationUrl.$$parse('http://www.server.org:1234/base?base=param#/path?a=b&c#hash');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base?base=param#/path?a=b&c#hash');
locationUrl.path('/new/path');
locationUrl.search({one: 1});
locationUrl.hash('hhh');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base?base=param#/new/path?one=1#hhh');
});
it('should prefix path with forward-slash', function() {
var locationUrl = new LocationHashbangUrl('http://host.com/base', 'http://host.com/', '#');
locationUrl.$$parse('http://host.com/base#path');
expect(locationUrl.path()).toBe('/path');
expect(locationUrl.absUrl()).toBe('http://host.com/base#/path');
locationUrl.path('wrong');
expect(locationUrl.path()).toBe('/wrong');
expect(locationUrl.absUrl()).toBe('http://host.com/base#/wrong');
});
it('should set path to forward-slash when empty', function() {
var locationUrl = new LocationHashbangUrl('http://server/base', 'http://server/', '#!');
locationUrl.$$parse('http://server/base');
locationUrl.path('aaa');
expect(locationUrl.path()).toBe('/aaa');
expect(locationUrl.absUrl()).toBe('http://server/base#!/aaa');
});
it('should not preserve old properties when parsing new url', function() {
var locationUrl = createHashbangUrl();
locationUrl.$$parse('http://www.server.org:1234/base#!/');
expect(locationUrl.path()).toBe('/');
expect(locationUrl.search()).toEqual({});
expect(locationUrl.hash()).toBe('');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base#!/');
});
it('should insert default hashbang if a hash is given with no hashbang prefix', function() {
var locationUrl = createHashbangUrl();
locationUrl.$$parse('http://www.server.org:1234/base#/path');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base#!#%2Fpath');
expect(locationUrl.hash()).toBe('/path');
expect(locationUrl.path()).toBe('');
locationUrl.$$parse('http://www.server.org:1234/base#');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base');
expect(locationUrl.hash()).toBe('');
expect(locationUrl.path()).toBe('');
});
it('should ignore extra path segments if no hashbang is given', function() {
var locationUrl = createHashbangUrl();
locationUrl.$$parse('http://www.server.org:1234/base/extra/path');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base');
expect(locationUrl.path()).toBe('');
expect(locationUrl.hash()).toBe('');
});
describe('encoding', function() {
it('should encode special characters', function() {
var locationUrl = createHashbangUrl();
locationUrl.path('/a <>#');
locationUrl.search({'i j': '<>#'});
locationUrl.hash('<>#');
expect(locationUrl.path()).toBe('/a <>#');
expect(locationUrl.search()).toEqual({'i j': '<>#'});
expect(locationUrl.hash()).toBe('<>#');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base#!/a%20%3C%3E%23?i%20j=%3C%3E%23#%3C%3E%23');
});
it('should not encode !$:@', function() {
var locationUrl = createHashbangUrl();
locationUrl.path('/!$:@');
locationUrl.search('');
locationUrl.hash('!$:@');
expect(locationUrl.absUrl()).toBe('http://www.server.org:1234/base#!/!$:@#!$:@');
});
it('should decode special characters', function() {
var locationUrl = new LocationHashbangUrl('http://host.com/a', 'http://host.com/', '#');
locationUrl.$$parse('http://host.com/a#/%20%3C%3E%23?i%20j=%3C%3E%23#x%20%3C%3E%23');
expect(locationUrl.path()).toBe('/ <>#');
expect(locationUrl.search()).toEqual({'i j': '<>#'});
expect(locationUrl.hash()).toBe('x <>#');
});
it('should return decoded characters for search specified in URL', function() {
var locationUrl = new LocationHtml5Url('http://host.com/', 'http://host.com/');
locationUrl.$$parse('http://host.com/?q=1%2F2%203');
expect(locationUrl.search()).toEqual({'q': '1/2 3'});
});
it('should return decoded characters for search specified with setter', function() {
var locationUrl = new LocationHtml5Url('http://host.com/', 'http://host.com/');
locationUrl.$$parse('http://host.com/');
locationUrl.search('q', '1/2 3');
expect(locationUrl.search()).toEqual({'q': '1/2 3'});
});
it('should return an array for duplicate params', function() {
var locationUrl = new LocationHtml5Url('http://host.com', 'http://host.com');
locationUrl.$$parse('http://host.com');
locationUrl.search('q', ['1/2 3','4/5 6']);
expect(locationUrl.search()).toEqual({'q': ['1/2 3','4/5 6']});
});
it('should encode an array correctly from search and add to url', function() {
var locationUrl = new LocationHtml5Url('http://host.com', 'http://host.com');
locationUrl.$$parse('http://host.com');
locationUrl.search({'q': ['1/2 3','4/5 6']});
expect(locationUrl.absUrl()).toEqual('http://host.com?q=1%2F2%203&q=4%2F5%206');
});
it('should rewrite params when specifying a single param in search', function() {
var locationUrl = new LocationHtml5Url('http://host.com', 'http://host.com');
locationUrl.$$parse('http://host.com');
locationUrl.search({'q': '1/2 3'});
expect(locationUrl.absUrl()).toEqual('http://host.com?q=1%2F2%203');
locationUrl.search({'q': '4/5 6'});
expect(locationUrl.absUrl()).toEqual('http://host.com?q=4%2F5%206');
});
});
});
describe('location watch', function() {
it('should not update browser if only the empty hash fragment is cleared by updating the search', function() {
initService({supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#', baseHref:'/base/'});
inject(function($rootScope, $browser, $location) {
$browser.url('http://new.com/a/b');
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$rootScope.$digest();
expect($browserUrl).not.toHaveBeenCalled();
});
});
it('should not replace browser url if only the empty hash fragment is cleared', function() {
initService({html5Mode: true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/#', baseHref: '/'});
inject(function($browser, $location) {
expect($browser.url()).toBe('http://new.com/#');
expect($location.absUrl()).toBe('http://new.com/');
});
});
it('should not get caught in infinite digest when replacing path in locationChangeSuccess handler', function() {
initService({html5Mode:true,supportHistory:false});
mockUpBrowser({initialUrl:'http://server/base/home', baseHref:'/base/'});
inject(
function($browser, $location, $rootScope, $window) {
var handlerCalled = false;
$rootScope.$on('$locationChangeSuccess', function() {
handlerCalled = true;
if ($location.path() !== '/') {
$location.path('/').replace();
}
});
expect($browser.url()).toEqual('http://server/base/#!/home');
$rootScope.$digest();
expect(handlerCalled).toEqual(true);
expect($browser.url()).toEqual('http://server/base/#!/');
}
);
});
it('should not infinitely digest when using a semicolon in initial path', function() {
initService({html5Mode:true,supportHistory:true});
mockUpBrowser({initialUrl:'http://localhost:9876/;jsessionid=foo', baseHref:'/'});
inject(function($location, $browser, $rootScope) {
expect(function() {
$rootScope.$digest();
}).not.toThrow();
});
});
describe('when changing the browser URL/history directly during a `$digest`', function() {
beforeEach(function() {
initService({supportHistory: true});
mockUpBrowser({initialUrl: 'http://foo.bar/', baseHref: '/'});
});
it('should correctly update `$location` from history and not digest infinitely', inject(
function($browser, $location, $rootScope, $window) {
$location.url('baz');
$rootScope.$digest();
var originalUrl = $window.location.href;
$rootScope.$apply(function() {
$rootScope.$evalAsync(function() {
$window.history.pushState({}, null, originalUrl + '/qux');
});
});
expect($browser.url()).toBe('http://foo.bar/#!/baz/qux');
expect($location.absUrl()).toBe('http://foo.bar/#!/baz/qux');
$rootScope.$apply(function() {
$rootScope.$evalAsync(function() {
$window.history.replaceState({}, null, originalUrl + '/quux');
});
});
expect($browser.url()).toBe('http://foo.bar/#!/baz/quux');
expect($location.absUrl()).toBe('http://foo.bar/#!/baz/quux');
})
);
it('should correctly update `$location` from URL and not digest infinitely', inject(
function($browser, $location, $rootScope, $window) {
$location.url('baz');
$rootScope.$digest();
$rootScope.$apply(function() {
$rootScope.$evalAsync(function() {
$window.location.href += '/qux';
});
});
jqLite($window).triggerHandler('hashchange');
expect($browser.url()).toBe('http://foo.bar/#!/baz/qux');
expect($location.absUrl()).toBe('http://foo.bar/#!/baz/qux');
})
);
});
function updatePathOnLocationChangeSuccessTo(newPath) {
inject(function($rootScope, $location) {
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$location.path(newPath);
});
});
}
describe('location watch for hashbang browsers', function() {
it('should not infinite $digest when going to base URL without trailing slash when $locationChangeSuccess watcher changes path to /Home', function() {
initService({html5Mode: true, supportHistory: false});
mockUpBrowser({initialUrl:'http://server/app/', baseHref:'/app/'});
inject(function($rootScope, $location, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
updatePathOnLocationChangeSuccessTo('/Home');
$rootScope.$digest();
expect($browser.url()).toEqual('http://server/app/#!/Home');
expect($location.path()).toEqual('/Home');
expect($browserUrl).toHaveBeenCalledTimes(1);
});
});
it('should not infinite $digest when going to base URL without trailing slash when $locationChangeSuccess watcher changes path to /', function() {
initService({html5Mode: true, supportHistory: false});
mockUpBrowser({initialUrl:'http://server/app/Home', baseHref:'/app/'});
inject(function($rootScope, $location, $browser, $window) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
updatePathOnLocationChangeSuccessTo('/');
$rootScope.$digest();
expect($browser.url()).toEqual('http://server/app/#!/');
expect($location.path()).toEqual('/');
expect($browserUrl).toHaveBeenCalledTimes(1);
expect($browserUrl.calls.argsFor(0)).toEqual(['http://server/app/#!/', false, null]);
});
});
it('should not infinite $digest when going to base URL with trailing slash when $locationChangeSuccess watcher changes path to /Home', function() {
initService({html5Mode: true, supportHistory: false});
mockUpBrowser({initialUrl:'http://server/app/', baseHref:'/app/'});
inject(function($rootScope, $location, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
updatePathOnLocationChangeSuccessTo('/Home');
$rootScope.$digest();
expect($browser.url()).toEqual('http://server/app/#!/Home');
expect($location.path()).toEqual('/Home');
expect($browserUrl).toHaveBeenCalledTimes(1);
expect($browserUrl.calls.argsFor(0)).toEqual(['http://server/app/#!/Home', false, null]);
});
});
it('should not infinite $digest when going to base URL with trailing slash when $locationChangeSuccess watcher changes path to /', function() {
initService({html5Mode: true, supportHistory: false});
mockUpBrowser({initialUrl:'http://server/app/', baseHref:'/app/'});
inject(function($rootScope, $location, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
updatePathOnLocationChangeSuccessTo('/');
$rootScope.$digest();
expect($browser.url()).toEqual('http://server/app/#!/');
expect($location.path()).toEqual('/');
expect($browserUrl).toHaveBeenCalledTimes(1);
});
});
});
describe('location watch for HTML5 browsers', function() {
it('should not infinite $digest when going to base URL without trailing slash when $locationChangeSuccess watcher changes path to /Home', function() {
initService({html5Mode: true, supportHistory: true});
mockUpBrowser({initialUrl:'http://server/app/', baseHref:'/app/'});
inject(function($rootScope, $injector, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
var $location = $injector.get('$location');
updatePathOnLocationChangeSuccessTo('/Home');
$rootScope.$digest();
expect($browser.url()).toEqual('http://server/app/Home');
expect($location.path()).toEqual('/Home');
expect($browserUrl).toHaveBeenCalledTimes(1);
});
});
it('should not infinite $digest when going to base URL without trailing slash when $locationChangeSuccess watcher changes path to /', function() {
initService({html5Mode: true, supportHistory: true});
mockUpBrowser({initialUrl:'http://server/app/', baseHref:'/app/'});
inject(function($rootScope, $injector, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
var $location = $injector.get('$location');
updatePathOnLocationChangeSuccessTo('/');
$rootScope.$digest();
expect($browser.url()).toEqual('http://server/app/');
expect($location.path()).toEqual('/');
expect($browserUrl).not.toHaveBeenCalled();
});
});
it('should not infinite $digest when going to base URL with trailing slash when $locationChangeSuccess watcher changes path to /Home', function() {
initService({html5Mode: true, supportHistory: true});
mockUpBrowser({initialUrl:'http://server/app/', baseHref:'/app/'});
inject(function($rootScope, $injector, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
var $location = $injector.get('$location');
updatePathOnLocationChangeSuccessTo('/Home');
$rootScope.$digest();
expect($browser.url()).toEqual('http://server/app/Home');
expect($location.path()).toEqual('/Home');
expect($browserUrl).toHaveBeenCalledTimes(1);
});
});
it('should not infinite $digest when going to base URL with trailing slash when $locationChangeSuccess watcher changes path to /', function() {
initService({html5Mode: true, supportHistory: true});
mockUpBrowser({initialUrl:'http://server/app/', baseHref:'/app/'});
inject(function($rootScope, $injector, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
var $location = $injector.get('$location');
updatePathOnLocationChangeSuccessTo('/');
$rootScope.$digest();
expect($browser.url()).toEqual('http://server/app/');
expect($location.path()).toEqual('/');
expect($browserUrl).not.toHaveBeenCalled();
});
});
});
});
describe('wiring', function() {
it('should update $location when browser url changes', function() {
initService({html5Mode:false,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#!', baseHref:'/a/b'});
inject(function($window, $browser, $location, $rootScope) {
spyOn($location, '$$parse').and.callThrough();
$window.location.href = 'http://new.com/a/b#!/aaa';
$browser.$$checkUrlChange();
expect($location.absUrl()).toBe('http://new.com/a/b#!/aaa');
expect($location.path()).toBe('/aaa');
expect($location.$$parse).toHaveBeenCalledOnce();
});
});
// location.href = '...' fires hashchange event synchronously, so it might happen inside $apply
it('should not $apply when browser url changed inside $apply', function() {
initService({html5Mode:false,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#!', baseHref:'/a/b'});
inject(function($rootScope, $browser, $location, $window) {
var OLD_URL = $browser.url(),
NEW_URL = 'http://new.com/a/b#!/new';
$rootScope.$apply(function() {
$window.location.href = NEW_URL;
$browser.$$checkUrlChange(); // simulate firing event from browser
expect($location.absUrl()).toBe(OLD_URL); // should be async
});
expect($location.absUrl()).toBe(NEW_URL);
});
});
// location.href = '...' fires hashchange event synchronously, so it might happen inside $digest
it('should not $apply when browser url changed inside $digest', function() {
initService({html5Mode:false,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#!', baseHref:'/a/b'});
inject(function($rootScope, $browser, $location, $window) {
var OLD_URL = $browser.url(),
NEW_URL = 'http://new.com/a/b#!/new',
notRunYet = true;
$rootScope.$watch(function() {
if (notRunYet) {
notRunYet = false;
$window.location.href = NEW_URL;
$browser.$$checkUrlChange(); // simulate firing event from browser
expect($location.absUrl()).toBe(OLD_URL); // should be async
}
});
$rootScope.$digest();
expect($location.absUrl()).toBe(NEW_URL);
});
});
it('should update browser when $location changes', function() {
initService({html5Mode:false,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#!', baseHref:'/a/b'});
inject(function($rootScope, $browser, $location) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.path('/new/path');
expect($browserUrl).not.toHaveBeenCalled();
$rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browser.url()).toBe('http://new.com/a/b#!/new/path');
});
});
it('should update browser only once per $apply cycle', function() {
initService({html5Mode:false,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#!', baseHref:'/a/b'});
inject(function($rootScope, $browser, $location) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.path('/new/path');
$rootScope.$watch(function() {
$location.search('a=b');
});
$rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browser.url()).toBe('http://new.com/a/b#!/new/path?a=b');
});
});
it('should replace browser url when url was replaced at least once', function() {
initService({html5Mode:false,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#!', baseHref:'/a/b'});
inject(function($rootScope, $browser, $location) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.path('/n/url').replace();
$rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browserUrl.calls.mostRecent().args).toEqual(['http://new.com/a/b#!/n/url', true, null]);
expect($location.$$replace).toBe(false);
});
});
it('should always reset replace flag after running watch', function() {
initService({html5Mode:false,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#!', baseHref:'/a/b'});
inject(function($rootScope, $browser, $location) {
// init watches
$location.url('/initUrl');
$rootScope.$apply();
// changes url but resets it before digest
$location.url('/newUrl').replace().url('/initUrl');
$rootScope.$apply();
expect($location.$$replace).toBe(false);
// set the url to the old value
$location.url('/newUrl').replace();
$rootScope.$apply();
expect($location.$$replace).toBe(false);
// doesn't even change url only calls replace()
$location.replace();
$rootScope.$apply();
expect($location.$$replace).toBe(false);
});
});
it('should update the browser if changed from within a watcher', function() {
initService({html5Mode:false,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b#!', baseHref:'/a/b'});
inject(function($rootScope, $browser, $location) {
$rootScope.$watch(function() { return true; }, function() {
$location.path('/changed');
});
$rootScope.$digest();
expect($browser.url()).toBe('http://new.com/a/b#!/changed');
});
});
it('should not infinitely digest if hash is set when there is no hashPrefix', function() {
initService({html5Mode:false, hashPrefix:'', supportHistory:true});
mockUpBrowser({initialUrl:'http://new.com/a/b', baseHref:'/a/b'});
inject(function($rootScope, $browser, $location) {
$location.hash('test');
$rootScope.$digest();
expect($browser.url()).toBe('http://new.com/a/b##test');
});
});
});
describe('wiring in html5 mode', function() {
it('should initialize state to initial state from the browser', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/', state: {a: 2}});
inject(function($location) {
expect($location.state()).toEqual({a: 2});
});
});
it('should update $location when browser state changes', function() {
initService({html5Mode: true, supportHistory: true});
mockUpBrowser({initialUrl: 'http://new.com/a/b/', baseHref: '/a/b/'});
inject(function($location, $rootScope, $window) {
$window.history.pushState({b: 3});
$rootScope.$digest();
expect($location.state()).toEqual({b: 3});
$window.history.pushState({b: 4}, null, $window.location.href + 'c?d=e#f');
$rootScope.$digest();
expect($location.path()).toBe('/c');
expect($location.search()).toEqual({d: 'e'});
expect($location.hash()).toBe('f');
expect($location.state()).toEqual({b: 4});
});
});
it('should replace browser url & state when replace() was called at least once', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($rootScope, $location, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.path('/n/url').state({a: 2}).replace();
$rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browserUrl.calls.mostRecent().args).toEqual(['http://new.com/a/b/n/url', true, {a: 2}]);
expect($location.$$replace).toBe(false);
expect($location.$$state).toEqual({a: 2});
});
});
it('should use only the most recent url & state definition', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($rootScope, $location, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.path('/n/url').state({a: 2}).replace().state({b: 3}).path('/o/url');
$rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browserUrl.calls.mostRecent().args).toEqual(['http://new.com/a/b/o/url', true, {b: 3}]);
expect($location.$$replace).toBe(false);
expect($location.$$state).toEqual({b: 3});
});
});
it('should allow to set state without touching the URL', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($rootScope, $location, $browser) {
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.state({a: 2}).replace().state({b: 3});
$rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browserUrl.calls.mostRecent().args).toEqual(['http://new.com/a/b/', true, {b: 3}]);
expect($location.$$replace).toBe(false);
expect($location.$$state).toEqual({b: 3});
});
});
it('should always reset replace flag after running watch', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($rootScope, $location) {
// init watches
$location.url('/initUrl').state({a: 2});
$rootScope.$apply();
// changes url & state but resets them before digest
$location.url('/newUrl').state({a: 2}).replace().state({b: 3}).url('/initUrl');
$rootScope.$apply();
expect($location.$$replace).toBe(false);
// set the url to the old value
$location.url('/newUrl').state({a: 2}).replace();
$rootScope.$apply();
expect($location.$$replace).toBe(false);
// doesn't even change url only calls replace()
$location.replace();
$rootScope.$apply();
expect($location.$$replace).toBe(false);
});
});
it('should allow to modify state only before digest', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($rootScope, $location, $browser) {
var o = {a: 2};
$location.state(o);
o.a = 3;
$rootScope.$apply();
expect($browser.state()).toEqual({a: 3});
o.a = 4;
$rootScope.$apply();
expect($browser.state()).toEqual({a: 3});
});
});
it('should make $location.state() referencially identical with $browser.state() after digest', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($rootScope, $location, $browser) {
$location.state({a: 2});
$rootScope.$apply();
expect($location.state()).toBe($browser.state());
});
});
it('should allow to query the state after digest', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($rootScope, $location) {
$location.url('/foo').state({a: 2});
$rootScope.$apply();
expect($location.state()).toEqual({a: 2});
});
});
it('should reset the state on .url() after digest', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($rootScope, $location, $browser) {
$location.url('/foo').state({a: 2});
$rootScope.$apply();
var $browserUrl = spyOnlyCallsWithArgs($browser, 'url').and.callThrough();
$location.url('/bar');
$rootScope.$apply();
expect($browserUrl).toHaveBeenCalledOnce();
expect($browserUrl.calls.mostRecent().args).toEqual(['http://new.com/a/b/bar', false, null]);
});
});
it('should force a page reload if navigating outside of the application base href', function() {
initService({html5Mode:true, supportHistory: true});
mockUpBrowser({initialUrl:'http://new.com/a/b/', baseHref:'/a/b/'});
inject(function($window, $browser, $location) {
$window.location.href = 'http://new.com/a/outside.html';
spyOn($window.location, '$$setHref');
expect($window.location.$$setHref).not.toHaveBeenCalled();
$browser.$$checkUrlChange();
expect($window.location.$$setHref).toHaveBeenCalledWith('http://new.com/a/outside.html');
});
});
});
// html5 history is disabled
describe('disabled history', function() {
it('should use hashbang url with hash prefix', function() {
initService({html5Mode:false,hashPrefix: '!'});
mockUpBrowser({initialUrl:'http://domain.com/base/index.html#!/a/b', baseHref:'/base/index.html'});
inject(
function($rootScope, $location, $browser) {
expect($browser.url()).toBe('http://domain.com/base/index.html#!/a/b');
$location.path('/new');
$location.search({a: true});
$rootScope.$apply();
expect($browser.url()).toBe('http://domain.com/base/index.html#!/new?a');
}
);
});
it('should use hashbang url without hash prefix', function() {
initService({html5Mode:false,hashPrefix: ''});
mockUpBrowser({initialUrl:'http://domain.com/base/index.html#/a/b', baseHref:'/base/index.html'});
inject(
function($rootScope, $location, $browser) {
expect($browser.url()).toBe('http://domain.com/base/index.html#/a/b');
$location.path('/new');
$location.search({a: true});
$rootScope.$apply();
expect($browser.url()).toBe('http://domain.com/base/index.html#/new?a');
}
);
});
});
// html5 history enabled, but not supported by browser
describe('history on old browser', function() {
it('should use hashbang url with hash prefix', function() {
initService({html5Mode:true,hashPrefix: '!!',supportHistory: false});
inject(
initBrowser({url:'http://domain.com/base/index.html#!!/a/b',basePath: '/base/index.html'}),
function($rootScope, $location, $browser) {
expect($browser.url()).toBe('http://domain.com/base/index.html#!!/a/b');
$location.path('/new');
$location.search({a: true});
$rootScope.$apply();
expect($browser.url()).toBe('http://domain.com/base/index.html#!!/new?a');
}
);
});
it('should redirect to hashbang url when new url given', function() {
initService({html5Mode:true,hashPrefix: '!'});
inject(
initBrowser({url:'http://domain.com/base/new-path/index.html',basePath: '/base/index.html'}),
function($browser, $location) {
expect($browser.url()).toBe('http://domain.com/base/index.html#!/new-path/index.html');
}
);
});
it('should correctly convert html5 url with path matching basepath to hashbang url', function() {
initService({html5Mode:true,hashPrefix: '!',supportHistory: false});
inject(
initBrowser({url:'http://domain.com/base/index.html',basePath: '/base/index.html'}),
function($browser, $location) {
expect($browser.url()).toBe('http://domain.com/base/index.html#!/index.html');
}
);
});
});
// html5 history enabled and supported by browser
describe('history on new browser', function() {
it('should use new url', function() {
initService({html5Mode:true,hashPrefix:'',supportHistory:true});
mockUpBrowser({initialUrl:'http://domain.com/base/old/index.html#a', baseHref:'/base/index.html'});
inject(
function($rootScope, $location, $browser) {
expect($browser.url()).toBe('http://domain.com/base/old/index.html#a');
$location.path('/new');
$location.search({a: true});
$rootScope.$apply();
expect($browser.url()).toBe('http://domain.com/base/new?a#a');
}
);
});
it('should rewrite when hashbang url given', function() {
initService({html5Mode:true,hashPrefix: '!',supportHistory: true});
mockUpBrowser({initialUrl:'http://domain.com/base/index.html#!/a/b', baseHref:'/base/index.html'});
inject(
function($rootScope, $location, $browser) {
expect($browser.url()).toBe('http://domain.com/base/a/b');
$location.path('/new');
$location.hash('abc');
$rootScope.$apply();
expect($browser.url()).toBe('http://domain.com/base/new#abc');
expect($location.path()).toBe('/new');
}
);
});
it('should rewrite when hashbang url given (without hash prefix)', function() {
initService({html5Mode:true,hashPrefix: '',supportHistory: true});
mockUpBrowser({initialUrl:'http://domain.com/base/index.html#/a/b', baseHref:'/base/index.html'});
inject(
function($rootScope, $location, $browser) {
expect($browser.url()).toBe('http://domain.com/base/a/b');
expect($location.path()).toBe('/a/b');
}
);
});
});
describe('PATH_MATCH', function() {
/* global PATH_MATCH: false */
it('should parse just path', function() {
var match = PATH_MATCH.exec('/path');
expect(match[1]).toBe('/path');
});
it('should parse path with search', function() {
var match = PATH_MATCH.exec('/ppp/a?a=b&c');
expect(match[1]).toBe('/ppp/a');
expect(match[3]).toBe('a=b&c');
});
it('should parse path with hash', function() {
var match = PATH_MATCH.exec('/ppp/a#abc?');
expect(match[1]).toBe('/ppp/a');
expect(match[5]).toBe('abc?');
});
it('should parse path with both search and hash', function() {
var match = PATH_MATCH.exec('/ppp/a?a=b&c#abc/d?');
expect(match[3]).toBe('a=b&c');
});
});
describe('link rewriting', function() {
var root, link, originalBrowser, lastEventPreventDefault;
function configureTestLink(options) {
var linkHref = options.linkHref,
relLink = options.relLink,
attrs = options.attrs,
content = options.content;
attrs = attrs ? ' ' + attrs + ' ' : '';
if (typeof linkHref === 'string' && !relLink) {
if (linkHref[0] === '/') {
linkHref = 'http://host.com' + linkHref;
} else if (!linkHref.match(/:\/\//)) {
// fake the behavior of <base> tag
linkHref = 'http://host.com/base/' + linkHref;
}
}
if (linkHref) {
link = jqLite('<a href="' + linkHref + '"' + attrs + '>' + content + '</a>')[0];
} else {
link = jqLite('<a ' + attrs + '>' + content + '</a>')[0];
}
module(function($provide) {
return function($rootElement, $document) {
$rootElement.append(link);
root = $rootElement[0];
// we need to do this otherwise we can't simulate events
$document.find('body').append($rootElement);
};
});
}
function setupRewriteChecks() {
return function($browser, $location, $rootElement) {
originalBrowser = $browser.url();
// we have to prevent the default operation, as we need to test absolute links (http://...)
// and navigating to these links would kill jstd
$rootElement.on('click', function(e) {
lastEventPreventDefault = e.isDefaultPrevented();
e.preventDefault();
});
};
}
function expectRewriteTo($browser, url) {
expect(lastEventPreventDefault).toBe(true);
expect($browser.url()).toBe(url);
}
function expectNoRewrite($browser) {
expect(lastEventPreventDefault).toBe(false);
expect($browser.url()).toBe(originalBrowser);
}
afterEach(function() {
dealoc(root);
dealoc(window.document.body);
});
it('should rewrite rel link to new url when history enabled on new browser', function() {
configureTestLink({linkHref: 'link?a#b'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/link?a#b');
}
);
});
it('should do nothing if already on the same URL', function() {
configureTestLink({linkHref: '/base/'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/');
jqLite(link).attr('href', 'http://host.com/base/foo');
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/foo');
jqLite(link).attr('href', 'http://host.com/base/');
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/');
jqLite(link).
attr('href', 'http://host.com/base/foo').
on('click', function(e) { e.preventDefault(); });
browserTrigger(link, 'click');
expect($browser.url()).toBe('http://host.com/base/');
}
);
});
it('should rewrite abs link to new url when history enabled on new browser', function() {
configureTestLink({linkHref: '/base/link?a#b'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/link?a#b');
}
);
});
it('should rewrite rel link to hashbang url when history enabled on old browser', function() {
configureTestLink({linkHref: 'link?a#b'});
initService({html5Mode:true,supportHistory:false,hashPrefix:'!'});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/index.html#!/link?a#b');
}
);
});
// Regression (gh-7721)
it('should not throw when clicking anchor with no href attribute when history enabled on old browser', function() {
configureTestLink({linkHref: null});
initService({html5Mode:true,supportHistory:false});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should produce relative paths correctly when $location.path() is "/" when history enabled on old browser', function() {
configureTestLink({linkHref: 'partial1'});
initService({html5Mode:true,supportHistory:false,hashPrefix:'!'});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser, $location, $rootScope) {
$rootScope.$apply(function() {
$location.path('/');
});
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/index.html#!/partial1');
}
);
});
it('should rewrite abs link to hashbang url when history enabled on old browser', function() {
configureTestLink({linkHref: '/base/link?a#b'});
initService({html5Mode:true,supportHistory:false,hashPrefix:'!'});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/index.html#!/link?a#b');
}
);
});
it('should not rewrite full url links to different domain', function() {
configureTestLink({linkHref: 'http://www.dot.abc/a?b=c'});
initService({html5Mode:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite links with target="_blank"', function() {
configureTestLink({linkHref: 'base/a?b=c', attrs: 'target="_blank"'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite links with target specified', function() {
configureTestLink({linkHref: 'base/a?b=c', attrs: 'target="some-frame"'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite links with `javascript:` URI', function() {
configureTestLink({linkHref: ' jAvAsCrIpT:throw new Error("Boom!")', relLink: true});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite links with `mailto:` URI', function() {
configureTestLink({linkHref: ' mAiLtO:foo@bar.com', relLink: true});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite links when rewriting links is disabled', function() {
configureTestLink({linkHref: 'link?a#b'});
initService({html5Mode:{enabled: true, rewriteLinks:false},supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should rewrite links when the specified rewriteLinks attr is present', function() {
configureTestLink({linkHref: 'link?a#b', attrs: 'do-rewrite'});
initService({html5Mode: {enabled: true, rewriteLinks: 'do-rewrite'}, supportHistory: true});
inject(
initBrowser({url: 'http://host.com/base/index.html', basePath: '/base/index.html'}),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/link?a#b');
}
);
});
it('should not rewrite links when the specified rewriteLinks attr is not present', function() {
configureTestLink({linkHref: 'link?a#b'});
initService({html5Mode: {enabled: true, rewriteLinks: 'do-rewrite'}, supportHistory: true});
inject(
initBrowser({url: 'http://host.com/base/index.html', basePath: '/base/index.html'}),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should rewrite full url links to same domain and base path', function() {
configureTestLink({linkHref: 'http://host.com/base/new'});
initService({html5Mode:true,supportHistory:false,hashPrefix:'!'});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectRewriteTo($browser, 'http://host.com/base/index.html#!/new');
}
);
});
it('should rewrite when clicked span inside link', function() {
configureTestLink({linkHref: 'some/link', attrs: '', content: '<span>link</span>'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
var span = jqLite(link).find('span');
browserTrigger(span, 'click');
expectRewriteTo($browser, 'http://host.com/base/some/link');
}
);
});
it('should not rewrite when link to different base path when history enabled on new browser',
function() {
configureTestLink({linkHref: '/other_base/link'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite when link to different base path when history enabled on old browser',
function() {
configureTestLink({linkHref: '/other_base/link'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite when link to different base path when history disabled', function() {
configureTestLink({linkHref: '/other_base/link'});
initService({html5Mode:false});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite when full link to different base path when history enabled on new browser',
function() {
configureTestLink({linkHref: 'http://host.com/other_base/link'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite when full link to different base path when history enabled on old browser',
function() {
configureTestLink({linkHref: 'http://host.com/other_base/link'});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should not rewrite when full link to different base path when history disabled', function() {
configureTestLink({linkHref: 'http://host.com/other_base/link'});
initService({html5Mode:false});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click');
expectNoRewrite($browser);
}
);
});
it('should replace current hash fragment when link begins with "#" history disabled', function() {
configureTestLink({linkHref: '#link', relLink: true});
initService({html5Mode:true,supportHistory:false,hashPrefix:'!'});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser, $location, $rootScope) {
$rootScope.$apply(function() {
$location.path('/some');
$location.hash('foo');
});
browserTrigger(link, 'click');
expect($location.hash()).toBe('link');
expectRewriteTo($browser, 'http://host.com/base/index.html#!/some#link');
}
);
});
it('should replace current hash fragment when link begins with "#" history enabled', function() {
configureTestLink({linkHref: '#link', relLink: true});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser, $location, $rootScope) {
$rootScope.$apply(function() {
$location.path('/some');
$location.hash('foo');
});
browserTrigger(link, 'click');
expect($location.hash()).toBe('link');
expectRewriteTo($browser, 'http://host.com/base/some#link');
}
);
});
it('should not rewrite when clicked with ctrl pressed', function() {
configureTestLink({linkHref: 'base/a?b=c'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click', { keys: ['ctrl'] });
expectNoRewrite($browser);
}
);
});
it('should not rewrite when clicked with meta pressed', function() {
configureTestLink({linkHref: 'base/a?b=c'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click', { keys: ['meta'] });
expectNoRewrite($browser);
}
);
});
it('should not rewrite when right click pressed', function() {
configureTestLink({linkHref: 'base/a?b=c'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
var rightClick;
if (window.document.createEvent) {
rightClick = window.document.createEvent('MouseEvents');
rightClick.initMouseEvent('click', true, true, window, 1, 10, 10, 10, 10, false,
false, false, false, 2, null);
link.dispatchEvent(rightClick);
} else if (window.document.createEventObject) { // for IE
rightClick = window.document.createEventObject();
rightClick.type = 'click';
rightClick.cancelBubble = true;
rightClick.detail = 1;
rightClick.screenX = 10;
rightClick.screenY = 10;
rightClick.clientX = 10;
rightClick.clientY = 10;
rightClick.ctrlKey = false;
rightClick.altKey = false;
rightClick.shiftKey = false;
rightClick.metaKey = false;
rightClick.button = 2;
link.fireEvent('onclick', rightClick);
}
expectNoRewrite($browser);
}
);
});
it('should not rewrite when clicked with shift pressed', function() {
configureTestLink({linkHref: 'base/a?b=c'});
initService({html5Mode:true,supportHistory:true});
inject(
initBrowser({ url: 'http://host.com/base/index.html', basePath: '/base/index.html' }),
setupRewriteChecks(),
function($browser) {
browserTrigger(link, 'click', { keys: ['shift'] });
expectNoRewrite($browser);
}
);
});
it('should not mess up hash urls when clicking on links in hashbang mode', function() {
var base;
module(function() {
return function($browser) {
window.location.hash = 'someHash';
base = window.location.href;
$browser.url(base);
base = base.split('#')[0];
};
});
inject(function($rootScope, $compile, $browser, $rootElement, $document, $location) {
// we need to do this otherwise we can't simulate events
$document.find('body').append($rootElement);
var element = $compile('<a href="#!/view1">v1</a><a href="#!/view2">v2</a>')($rootScope);
$rootElement.append(element);
var av1 = $rootElement.find('a').eq(0);
var av2 = $rootElement.find('a').eq(1);
browserTrigger(av1, 'click');
expect($browser.url()).toEqual(base + '#!/view1');
browserTrigger(av2, 'click');
expect($browser.url()).toEqual(base + '#!/view2');
$rootElement.remove();
});
});
it('should not mess up hash urls when clicking on links in hashbang mode with a prefix',
function() {
var base;
module(function($locationProvider) {
return function($browser) {
window.location.hash = '!!someHash';
$browser.url(base = window.location.href);
base = base.split('#')[0];
$locationProvider.hashPrefix('!!');
};
});
inject(function($rootScope, $compile, $browser, $rootElement, $document, $location) {
// we need to do this otherwise we can't simulate events
$document.find('body').append($rootElement);
var element = $compile('<a href="#!!/view1">v1</a><a href="#!!/view2">v2</a>')($rootScope);
$rootElement.append(element);
var av1 = $rootElement.find('a').eq(0);
var av2 = $rootElement.find('a').eq(1);
browserTrigger(av1, 'click');
expect($browser.url()).toEqual(base + '#!!/view1');
browserTrigger(av2, 'click');
expect($browser.url()).toEqual(base + '#!!/view2');
});
});
it('should not intercept clicks outside the current hash prefix', function() {
var base, clickHandler;
module(function($provide) {
$provide.value('$rootElement', {
on: function(event, handler) {
expect(event).toEqual('click');
clickHandler = handler;
},
off: noop
});
return function($browser) {
$browser.url(base = 'http://server/');
};
});
inject(function($location) {
// make IE happy
jqLite(window.document.body).html('<a href="http://server/test.html">link</a>');
var event = {
target: jqLite(window.document.body).find('a')[0],
preventDefault: jasmine.createSpy('preventDefault'),
isDefaultPrevented: jasmine.createSpy().and.returnValue(false)
};
clickHandler(event);
expect(event.preventDefault).not.toHaveBeenCalled();
});
});
it('should not intercept hash link clicks outside the app base url space', function() {
var base, clickHandler;
module(function($provide) {
$provide.value('$rootElement', {
on: function(event, handler) {
expect(event).toEqual('click');
clickHandler = handler;
},
off: angular.noop
});
return function($browser) {
$browser.url(base = 'http://server/');
};
});
inject(function($rootScope, $compile, $browser, $rootElement, $document, $location) {
// make IE happy
jqLite(window.document.body).html('<a href="http://server/index.html#test">link</a>');
var event = {
target: jqLite(window.document.body).find('a')[0],
preventDefault: jasmine.createSpy('preventDefault'),
isDefaultPrevented: jasmine.createSpy().and.returnValue(false)
};
clickHandler(event);
expect(event.preventDefault).not.toHaveBeenCalled();
});
});
// regression https://github.com/angular/angular.js/issues/1058
it('should not throw if element was removed', inject(function($document, $rootElement, $location) {
// we need to do this otherwise we can't simulate events
$document.find('body').append($rootElement);
$rootElement.html('<button></button>');
var button = $rootElement.find('button');
button.on('click', function() {
button.remove();
});
browserTrigger(button, 'click');
}));
it('should not throw when clicking an SVGAElement link', function() {
var base;
module(function($locationProvider) {
return function($browser) {
window.location.hash = '!someHash';
$browser.url(base = window.location.href);
base = base.split('#')[0];
$locationProvider.hashPrefix('!');
};
});
inject(function($rootScope, $compile, $browser, $rootElement, $document, $location) {
// we need to do this otherwise we can't simulate events
$document.find('body').append($rootElement);
var template = '<svg><g><a xlink:href="#!/view1"><circle r="50"></circle></a></g></svg>';
var element = $compile(template)($rootScope);
$rootElement.append(element);
var av1 = $rootElement.find('a').eq(0);
expect(function() {
browserTrigger(av1, 'click');
}).not.toThrow();
});
});
});
describe('location cancellation', function() {
it('should fire $before/afterLocationChange event', inject(function($location, $browser, $rootScope, $log) {
expect($browser.url()).toEqual('http://server/');
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('before', newUrl, oldUrl, $browser.url());
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$log.info('after', newUrl, oldUrl, $browser.url());
});
expect($location.url()).toEqual('');
$location.url('/somePath');
expect($location.url()).toEqual('/somePath');
expect($browser.url()).toEqual('http://server/');
expect($log.info.logs).toEqual([]);
$rootScope.$apply();
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/somePath', 'http://server/', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['after', 'http://server/#!/somePath', 'http://server/', 'http://server/#!/somePath']);
expect($location.url()).toEqual('/somePath');
expect($browser.url()).toEqual('http://server/#!/somePath');
}));
it('should allow $locationChangeStart event cancellation', inject(function($location, $browser, $rootScope, $log) {
expect($browser.url()).toEqual('http://server/');
expect($location.url()).toEqual('');
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('before', newUrl, oldUrl, $browser.url());
event.preventDefault();
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
throw new Error('location should have been canceled');
});
expect($location.url()).toEqual('');
$location.url('/somePath');
expect($location.url()).toEqual('/somePath');
expect($browser.url()).toEqual('http://server/');
expect($log.info.logs).toEqual([]);
$rootScope.$apply();
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/somePath', 'http://server/', 'http://server/']);
expect($log.info.logs[1]).toBeUndefined();
expect($location.url()).toEqual('');
expect($browser.url()).toEqual('http://server/');
}));
it('should allow redirect during $locationChangeStart',
inject(function($location, $browser, $rootScope, $log) {
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('before', newUrl, oldUrl, $browser.url());
if (newUrl === 'http://server/#!/somePath') {
$location.url('/redirectPath');
}
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$log.info('after', newUrl, oldUrl, $browser.url());
});
$location.url('/somePath');
$rootScope.$apply();
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/somePath', 'http://server/', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/redirectPath', 'http://server/', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['after', 'http://server/#!/redirectPath', 'http://server/',
'http://server/#!/redirectPath']);
expect($location.url()).toEqual('/redirectPath');
expect($browser.url()).toEqual('http://server/#!/redirectPath');
})
);
it('should allow redirect during $locationChangeStart even if default prevented',
inject(function($location, $browser, $rootScope, $log) {
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('before', newUrl, oldUrl, $browser.url());
if (newUrl === 'http://server/#!/somePath') {
event.preventDefault();
$location.url('/redirectPath');
}
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$log.info('after', newUrl, oldUrl, $browser.url());
});
$location.url('/somePath');
$rootScope.$apply();
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/somePath', 'http://server/', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/redirectPath', 'http://server/', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['after', 'http://server/#!/redirectPath', 'http://server/',
'http://server/#!/redirectPath']);
expect($location.url()).toEqual('/redirectPath');
expect($browser.url()).toEqual('http://server/#!/redirectPath');
})
);
it('should allow multiple redirect during $locationChangeStart',
inject(function($location, $browser, $rootScope, $log) {
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('before', newUrl, oldUrl, $browser.url());
if (newUrl === 'http://server/#!/somePath') {
$location.url('/redirectPath');
} else if (newUrl === 'http://server/#!/redirectPath') {
$location.url('/redirectPath2');
}
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$log.info('after', newUrl, oldUrl, $browser.url());
});
$location.url('/somePath');
$rootScope.$apply();
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/somePath', 'http://server/', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/redirectPath', 'http://server/', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/redirectPath2', 'http://server/', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['after', 'http://server/#!/redirectPath2', 'http://server/',
'http://server/#!/redirectPath2']);
expect($location.url()).toEqual('/redirectPath2');
expect($browser.url()).toEqual('http://server/#!/redirectPath2');
})
);
it('should fire $locationChangeSuccess event when change from browser location bar',
inject(function($log, $location, $browser, $rootScope) {
$rootScope.$apply(); // clear initial $locationChangeStart
expect($browser.url()).toEqual('http://server/');
expect($location.url()).toEqual('');
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('start', newUrl, oldUrl);
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$log.info('after', newUrl, oldUrl);
});
$browser.url('http://server/#!/somePath');
$browser.poll();
expect($log.info.logs.shift()).
toEqual(['start', 'http://server/#!/somePath', 'http://server/']);
expect($log.info.logs.shift()).
toEqual(['after', 'http://server/#!/somePath', 'http://server/']);
})
);
it('should fire $locationChangeSuccess when browser location changes to URL which ends with #',
inject(function($location, $browser, $rootScope, $log) {
$location.url('/somepath');
$rootScope.$apply();
expect($browser.url()).toEqual('http://server/#!/somepath');
expect($location.url()).toEqual('/somepath');
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('start', newUrl, oldUrl);
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$log.info('after', newUrl, oldUrl);
});
$browser.url('http://server/#');
$browser.poll();
expect($log.info.logs.shift()).
toEqual(['start', 'http://server/', 'http://server/#!/somepath']);
expect($log.info.logs.shift()).
toEqual(['after', 'http://server/', 'http://server/#!/somepath']);
})
);
it('should allow redirect during browser url change',
inject(function($location, $browser, $rootScope, $log) {
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('before', newUrl, oldUrl, $browser.url());
if (newUrl === 'http://server/#!/somePath') {
$location.url('/redirectPath');
}
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$log.info('after', newUrl, oldUrl, $browser.url());
});
$browser.url('http://server/#!/somePath');
$browser.poll();
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/somePath', 'http://server/',
'http://server/#!/somePath']);
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/redirectPath', 'http://server/#!/somePath',
'http://server/#!/somePath']);
expect($log.info.logs.shift()).
toEqual(['after', 'http://server/#!/redirectPath', 'http://server/#!/somePath',
'http://server/#!/redirectPath']);
expect($location.url()).toEqual('/redirectPath');
expect($browser.url()).toEqual('http://server/#!/redirectPath');
})
);
it('should allow redirect during browser url change even if default prevented',
inject(function($location, $browser, $rootScope, $log) {
$rootScope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
$log.info('before', newUrl, oldUrl, $browser.url());
if (newUrl === 'http://server/#!/somePath') {
event.preventDefault();
$location.url('/redirectPath');
}
});
$rootScope.$on('$locationChangeSuccess', function(event, newUrl, oldUrl) {
$log.info('after', newUrl, oldUrl, $browser.url());
});
$browser.url('http://server/#!/somePath');
$browser.poll();
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/somePath', 'http://server/',
'http://server/#!/somePath']);
expect($log.info.logs.shift()).
toEqual(['before', 'http://server/#!/redirectPath', 'http://server/#!/somePath',
'http://server/#!/somePath']);
expect($log.info.logs.shift()).
toEqual(['after', 'http://server/#!/redirectPath', 'http://server/#!/somePath',
'http://server/#!/redirectPath']);
expect($location.url()).toEqual('/redirectPath');
expect($browser.url()).toEqual('http://server/#!/redirectPath');
})
);
it('should listen on click events on href and prevent browser default in hashbang mode', function() {
module(function() {
return function($rootElement, $compile, $rootScope) {
$rootElement.html('<a href="http://server/#!/somePath">link</a>');
$compile($rootElement)($rootScope);
jqLite(window.document.body).append($rootElement);
};
});
inject(function($location, $rootScope, $browser, $rootElement) {
var log = '',
link = $rootElement.find('a');
$rootScope.$on('$locationChangeStart', function(event) {
event.preventDefault();
log += '$locationChangeStart';
});
$rootScope.$on('$locationChangeSuccess', function() {
throw new Error('after cancellation in hashbang mode');
});
browserTrigger(link, 'click');
expect(log).toEqual('$locationChangeStart');
expect($browser.url()).toEqual('http://server/');
dealoc($rootElement);
});
});
it('should listen on click events on href and prevent browser default in html5 mode', function() {
module(function($locationProvider, $provide) {
$locationProvider.html5Mode(true);
return function($rootElement, $compile, $rootScope) {
$rootElement.html('<a href="http://server/somePath">link</a>');
$compile($rootElement)($rootScope);
jqLite(window.document.body).append($rootElement);
};
});
inject(function($location, $rootScope, $browser, $rootElement) {
var log = '',
link = $rootElement.find('a'),
browserUrlBefore = $browser.url();
$rootScope.$on('$locationChangeStart', function(event) {
event.preventDefault();
log += '$locationChangeStart';
});
$rootScope.$on('$locationChangeSuccess', function() {
throw new Error('after cancellation in html5 mode');
});
browserTrigger(link, 'click');
expect(log).toEqual('$locationChangeStart');
expect($browser.url()).toBe(browserUrlBefore);
dealoc($rootElement);
});
});
it('should always return the new url value via path() when $locationChangeStart event occurs regardless of cause',
inject(function($location, $rootScope, $browser, log) {
var base = $browser.url();
$rootScope.$on('$locationChangeStart', function() {
log($location.path());
});
// change through $location service
$rootScope.$apply(function() {
$location.path('/myNewPath');
});
// reset location
$rootScope.$apply(function() {
$location.path('');
});
// change through $browser
$browser.url(base + '#!/myNewPath');
$browser.poll();
expect(log).toEqual(['/myNewPath', '/', '/myNewPath']);
})
);
});
describe('$locationProvider', function() {
describe('html5Mode', function() {
it('should set enabled, requireBase and rewriteLinks when called with object', function() {
module(function($locationProvider) {
$locationProvider.html5Mode({enabled: true, requireBase: false, rewriteLinks: false});
expect($locationProvider.html5Mode()).toEqual({
enabled: true,
requireBase: false,
rewriteLinks: false
});
});
inject(function() {});
});
it('should only overwrite existing properties if values are of the correct type', function() {
module(function($locationProvider) {
$locationProvider.html5Mode({
enabled: 'duh',
requireBase: 'probably',
rewriteLinks: 0
});
expect($locationProvider.html5Mode()).toEqual({
enabled: false,
requireBase: true,
rewriteLinks: true
});
});
inject(function() {});
});
it('should support setting rewriteLinks to a string', function() {
module(function($locationProvider) {
$locationProvider.html5Mode({
rewriteLinks: 'yes-rewrite'
});
expect($locationProvider.html5Mode().rewriteLinks).toEqual('yes-rewrite');
});
inject(function() {});
});
it('should not set unknown input properties to html5Mode object', function() {
module(function($locationProvider) {
$locationProvider.html5Mode({
someProp: 'foo'
});
expect($locationProvider.html5Mode()).toEqual({
enabled: false,
requireBase: true,
rewriteLinks: true
});
});
inject(function() {});
});
it('should default to enabled:false, requireBase:true and rewriteLinks:true', function() {
module(function($locationProvider) {
expect($locationProvider.html5Mode()).toEqual({
enabled: false,
requireBase: true,
rewriteLinks: true
});
});
inject(function() {});
});
});
});
describe('LocationHtml5Url', function() {
var locationUrl, locationUmlautUrl, locationIndexUrl;
beforeEach(function() {
locationUrl = new LocationHtml5Url('http://server/pre/', 'http://server/pre/');
locationUmlautUrl = new LocationHtml5Url('http://särver/pre/', 'http://särver/pre/');
locationIndexUrl = new LocationHtml5Url('http://server/pre/index.html', 'http://server/pre/');
});
it('should rewrite URL', function() {
expect(parseLinkAndReturn(locationUrl, 'http://other')).toEqual(undefined);
expect(parseLinkAndReturn(locationUrl, 'http://server/pre')).toEqual('http://server/pre/');
expect(parseLinkAndReturn(locationUrl, 'http://server/pre/')).toEqual('http://server/pre/');
expect(parseLinkAndReturn(locationUrl, 'http://server/pre/otherPath')).toEqual('http://server/pre/otherPath');
// Note: relies on the previous state!
expect(parseLinkAndReturn(locationUrl, 'someIgnoredAbsoluteHref', '#test')).toEqual('http://server/pre/otherPath#test');
expect(parseLinkAndReturn(locationUmlautUrl, 'http://other')).toEqual(undefined);
expect(parseLinkAndReturn(locationUmlautUrl, 'http://särver/pre')).toEqual('http://särver/pre/');
expect(parseLinkAndReturn(locationUmlautUrl, 'http://särver/pre/')).toEqual('http://särver/pre/');
expect(parseLinkAndReturn(locationUmlautUrl, 'http://särver/pre/otherPath')).toEqual('http://särver/pre/otherPath');
// Note: relies on the previous state!
expect(parseLinkAndReturn(locationUmlautUrl, 'someIgnoredAbsoluteHref', '#test')).toEqual('http://särver/pre/otherPath#test');
expect(parseLinkAndReturn(locationIndexUrl, 'http://server/pre')).toEqual('http://server/pre/');
expect(parseLinkAndReturn(locationIndexUrl, 'http://server/pre/')).toEqual('http://server/pre/');
expect(parseLinkAndReturn(locationIndexUrl, 'http://server/pre/otherPath')).toEqual('http://server/pre/otherPath');
// Note: relies on the previous state!
expect(parseLinkAndReturn(locationUrl, 'someIgnoredAbsoluteHref', '#test')).toEqual('http://server/pre/otherPath#test');
});
it('should complain if the path starts with double slashes', function() {
expect(function() {
parseLinkAndReturn(locationUrl, 'http://server/pre///other/path');
}).toThrowMinErr('$location', 'badpath');
expect(function() {
parseLinkAndReturn(locationUrl, 'http://server/pre/\\\\other/path');
}).toThrowMinErr('$location', 'badpath');
expect(function() {
parseLinkAndReturn(locationUrl, 'http://server/pre//\\//other/path');
}).toThrowMinErr('$location', 'badpath');
});
it('should complain if no base tag present', function() {
module(function($locationProvider) {
$locationProvider.html5Mode(true);
});
inject(function($browser, $injector) {
$browser.$$baseHref = undefined;
expect(function() {
$injector.get('$location');
}).toThrowMinErr('$location', 'nobase',
'$location in HTML5 mode requires a <base> tag to be present!');
});
});
it('should not complain if baseOptOut set to true in html5Mode', function() {
module(function($locationProvider) {
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
inject(function($browser, $injector) {
$browser.$$baseHref = undefined;
expect(function() {
$injector.get('$location');
}).not.toThrowMinErr('$location', 'nobase',
'$location in HTML5 mode requires a <base> tag to be present!');
});
});
it('should support state', function() {
expect(locationUrl.state({a: 2}).state()).toEqual({a: 2});
});
});
describe('LocationHashbangUrl', function() {
var locationUrl;
it('should rewrite URL', function() {
locationUrl = new LocationHashbangUrl('http://server/pre/', 'http://server/pre/', '#');
expect(parseLinkAndReturn(locationUrl, 'http://other')).toEqual(undefined);
expect(parseLinkAndReturn(locationUrl, 'http://server/pre/')).toEqual('http://server/pre/');
expect(parseLinkAndReturn(locationUrl, 'http://server/pre/#otherPath')).toEqual('http://server/pre/#/otherPath');
// eslint-disable-next-line no-script-url
expect(parseLinkAndReturn(locationUrl, 'javascript:void(0)')).toEqual(undefined);
});
it('should not set hash if one was not originally specified', function() {
locationUrl = new LocationHashbangUrl('http://server/pre/index.html', 'http://server/pre/', '#');
locationUrl.$$parse('http://server/pre/index.html');
expect(locationUrl.url()).toBe('');
expect(locationUrl.absUrl()).toBe('http://server/pre/index.html');
});
it('should parse hash if one was specified', function() {
locationUrl = new LocationHashbangUrl('http://server/pre/index.html', 'http://server/pre/', '#');
locationUrl.$$parse('http://server/pre/index.html#/foo/bar');
expect(locationUrl.url()).toBe('/foo/bar');
expect(locationUrl.absUrl()).toBe('http://server/pre/index.html#/foo/bar');
});
it('should prefix hash url with / if one was originally missing', function() {
locationUrl = new LocationHashbangUrl('http://server/pre/index.html', 'http://server/pre/', '#');
locationUrl.$$parse('http://server/pre/index.html#not-starting-with-slash');
expect(locationUrl.url()).toBe('/not-starting-with-slash');
expect(locationUrl.absUrl()).toBe('http://server/pre/index.html#/not-starting-with-slash');
});
it('should not strip stuff from path just because it looks like Windows drive when it\'s not',
function() {
locationUrl = new LocationHashbangUrl('http://server/pre/index.html', 'http://server/pre/', '#');
locationUrl.$$parse('http://server/pre/index.html#http%3A%2F%2Fexample.com%2F');
expect(locationUrl.url()).toBe('/http://example.com/');
expect(locationUrl.absUrl()).toBe('http://server/pre/index.html#/http://example.com/');
});
it('should throw on url(urlString, stateObject)', function() {
expectThrowOnStateChange(locationUrl);
});
it('should allow navigating outside the original base URL', function() {
locationUrl = new LocationHashbangUrl('http://server/pre/index.html', 'http://server/pre/', '#');
locationUrl.$$parse('http://server/next/index.html');
expect(locationUrl.url()).toBe('');
expect(locationUrl.absUrl()).toBe('http://server/next/index.html');
});
});
describe('LocationHashbangInHtml5Url', function() {
/* global LocationHashbangInHtml5Url: false */
var locationUrl, locationIndexUrl;
beforeEach(function() {
locationUrl = new LocationHashbangInHtml5Url('http://server/pre/', 'http://server/pre/', '#!');
locationIndexUrl = new LocationHashbangInHtml5Url('http://server/pre/index.html', 'http://server/pre/', '#!');
});
it('should rewrite URL', function() {
expect(parseLinkAndReturn(locationUrl, 'http://other')).toEqual(undefined);
expect(parseLinkAndReturn(locationUrl, 'http://server/pre')).toEqual('http://server/pre/#!');
expect(parseLinkAndReturn(locationUrl, 'http://server/pre/')).toEqual('http://server/pre/#!');
expect(parseLinkAndReturn(locationUrl, 'http://server/pre/otherPath')).toEqual('http://server/pre/#!/otherPath');
// Note: relies on the previous state!
expect(parseLinkAndReturn(locationUrl, 'someIgnoredAbsoluteHref', '#test')).toEqual('http://server/pre/#!/otherPath#test');
expect(parseLinkAndReturn(locationIndexUrl, 'http://server/pre')).toEqual('http://server/pre/index.html#!');
expect(parseLinkAndReturn(locationIndexUrl, 'http://server/pre/')).toEqual(undefined);
expect(parseLinkAndReturn(locationIndexUrl, 'http://server/pre/otherPath')).toEqual('http://server/pre/index.html#!/otherPath');
// Note: relies on the previous state!
expect(parseLinkAndReturn(locationIndexUrl, 'someIgnoredAbsoluteHref', '#test')).toEqual('http://server/pre/index.html#!/otherPath#test');
});
it('should throw on url(urlString, stateObject)', function() {
expectThrowOnStateChange(locationUrl);
});
it('should not throw when base path is another domain', function() {
initService({html5Mode: true, hashPrefix: '!', supportHistory: true});
inject(
initBrowser({url: 'http://domain.com/base/', basePath: 'http://otherdomain.com/base/'}),
function($location) {
expect(function() {
$location.absUrl();
}).not.toThrow();
}
);
});
});
function initService(options) {
return module(function($provide, $locationProvider) {
$locationProvider.html5Mode(options.html5Mode);
$locationProvider.hashPrefix(options.hashPrefix);
$provide.value('$sniffer', {history: options.supportHistory});
});
}
function mockUpBrowser(options) {
module(function($windowProvider, $browserProvider) {
var browser;
var parser = window.document.createElement('a');
parser.href = options.initialUrl;
$windowProvider.$get = function() {
var win = {};
angular.extend(win, window);
// Ensure `window` is a reference to the mock global object, so that
// jqLite does the right thing.
win.window = win;
win.history = {
state: options.state || null,
replaceState: function(state, title, url) {
win.history.state = copy(state);
if (url) win.location.href = url;
},
pushState: function(state, title, url) {
win.history.state = copy(state);
if (url) win.location.href = url;
}
};
win.addEventListener = angular.noop;
win.removeEventListener = angular.noop;
win.location = {
get href() { return this.$$getHref(); },
$$getHref: function() { return parser.href; },
set href(val) { this.$$setHref(val); },
$$setHref: function(val) { parser.href = val; },
get hash() { return parser.hash; },
// The parser correctly strips on a single preceding hash character if necessary
// before joining the fragment onto the href by a new hash character
// See hash setter spec: https://url.spec.whatwg.org/#urlutils-and-urlutilsreadonly-members
set hash(val) { parser.hash = val; },
replace: function(val) {
win.location.href = val;
}
};
return win;
};
$browserProvider.$get = function($document, $window, $log, $sniffer) {
/* global Browser: false */
browser = new Browser($window, $document, $log, $sniffer);
browser.baseHref = function() {
return options.baseHref;
};
return browser;
};
});
}
function initBrowser(options) {
return function($browser) {
$browser.url(options.url);
$browser.$$baseHref = options.basePath;
};
}
function expectThrowOnStateChange(location) {
expect(function() {
location.state({a: 2});
}).toThrowMinErr('$location', 'nostate', 'History API state support is available only ' +
'in HTML5 mode and only in browsers supporting HTML5 History API'
);
}
function parseLinkAndReturn(location, url, relHref) {
if (location.$$parseLinkUrl(url, relHref)) {
return location.absUrl();
}
return undefined;
}
});
|
const passport = require('passport');
const LocalPassport = require('passport-local');
const User = require('mongoose').model('User');
module.exports = () => {
passport.use(new LocalPassport((username, password, done) => {
User.findOne({ username: username }).then(user => {
if (!user) return done(null, false);
if (!user.authenticate(password)) return done(null, false);
return done(null, user);
});
}));
passport.serializeUser((user, done) => {
if (user) return done(null, user._id);
});
passport.deserializeUser((id, done) => {
User.findById(id).then(user => {
if (!user) return done(null, false);
return done(null, user);
});
});
};
|
export { default } from '../table-route';
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("a11yhelp","ca",{title:"Instruccions d'Accessibilitat",contents:"Continguts de l'Ajuda. Per tancar aquest quadre de diàleg premi ESC.",legend:[{name:"General",items:[{name:"Editor de barra d'eines",legend:"Premi ${toolbarFocus} per desplaçar-se per la barra d'eines. Vagi en el següent i anterior grup de barra d'eines amb TAB i SHIFT+TAB. Vagi en el següent i anterior botó de la barra d'eines amb RIGHT ARROW i LEFT ARROW. Premi SPACE o ENTER per activar el botó de la barra d'eines."},
{name:"Editor de quadre de diàleg",legend:"Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively."},{name:"Editor de menú contextual",legend:"Premi ${contextMenu} o APPLICATION KEY per obrir el menú contextual. Després desplacis a la següent opció del menú amb TAB o DOWN ARROW. Desplacis a l'anterior opció amb SHIFT+TAB o UP ARROW. Premi SPACE o ENTER per seleccionar l'opció del menú. Obri el submenú de l'actual opció utilitzant SPACE o ENTER o RIGHT ARROW. Pot tornar a l'opció del menú pare amb ESC o LEFT ARROW. Tanqui el menú contextual amb ESC."},
{name:"Editor de caixa de llista",legend:"Dins d'un quadre de llista, desplacis al següent element de la llista amb TAB o DOWN ARROW. Desplacis a l'anterior element de la llista amb SHIFT+TAB o UP ARROW. Premi SPACE o ENTER per seleccionar l'opció de la llista. Premi ESC per tancar el quadre de llista."},{name:"Editor de barra de ruta de l'element",legend:"Premi ${elementsPathFocus} per anar als elements de la barra de ruta. Desplacis al botó de l'element següent amb TAB o RIGHT ARROW. Desplacis a l'anterior botó amb SHIFT+TAB o LEFT ARROW. Premi SPACE o ENTER per seleccionar l'element a l'editor."}]},
{name:"Ordres",items:[{name:"Desfer ordre",legend:"Premi ${undo}"},{name:"Refer ordre",legend:"Premi ${redo}"},{name:"Ordre negreta",legend:"Premi ${bold}"},{name:"Ordre cursiva",legend:"Premi ${italic}"},{name:"Ordre subratllat",legend:"Premi ${underline}"},{name:"Ordre enllaç",legend:"Premi ${link}"},{name:"Ordre amagar barra d'eines",legend:"Premi ${toolbarCollapse}"},{name:"Ordre per accedir a l'anterior espai enfocat",legend:"Premi ${accessPreviousSpace} per accedir a l'enfocament d'espai més proper inabastable abans del símbol d'intercalació, per exemple: dos elements HR adjacents. Repetiu la combinació de tecles per arribar a enfocaments d'espais distants."},
{name:"Ordre per accedir al següent espai enfocat",legend:"Premi ${accessNextSpace} per accedir a l'enfocament d'espai més proper inabastable després del símbol d'intercalació, per exemple: dos elements HR adjacents. Repetiu la combinació de tecles per arribar a enfocaments d'espais distants."},{name:"Ajuda d'accessibilitat",legend:"Premi ${a11yHelp}"}]}],backspace:"Retrocés",tab:"Tabulació",enter:"Intro",shift:"Majúscules",ctrl:"Ctrl",alt:"Alt",pause:"Pausa",capslock:"Bloqueig de majúscules",escape:"Escape",
pageUp:"Pàgina Amunt",pageDown:"Pàgina Avall",end:"Fi",home:"Inici",leftArrow:"Fletxa Esquerra",upArrow:"Fletxa Amunt",rightArrow:"Fletxa Dreta",downArrow:"Fletxa Avall",insert:"Inserir","delete":"Eliminar",leftWindowKey:"Tecla Windows Esquerra",rightWindowKey:"Tecla Windows Dreta",selectKey:"Tecla Seleccionar",numpad0:"Teclat Numèric 0",numpad1:"Teclat Numèric 1",numpad2:"Teclat Numèric 2",numpad3:"Teclat Numèric 3",numpad4:"Teclat Numèric 4",numpad5:"Teclat Numèric 5",numpad6:"Teclat Numèric 6",
numpad7:"Teclat Numèric 7",numpad8:"Teclat Numèric 8",numpad9:"Teclat Numèric 9",multiply:"Multiplicació",add:"Suma",subtract:"Resta",decimalPoint:"Punt Decimal",divide:"Divisió",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Bloqueig Teclat Numèric",scrollLock:"Bloqueig de Desplaçament",semiColon:"Punt i Coma",equalSign:"Símbol Igual",comma:"Coma",dash:"Guió",period:"Punt",forwardSlash:"Barra Diagonal",graveAccent:"Accent Obert",openBracket:"Claudàtor Obert",
backSlash:"Barra Invertida",closeBracket:"Claudàtor Tancat",singleQuote:"Cometa Simple"});
|
steal('jquery', function($){
// copied from jQuery 1.8.3
var uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
}
var keymap = {},
reverseKeyMap = {},
currentBrowser = uaMatch(navigator.userAgent).browser;
/**
* @hide
* @parent jQuery.Event.prototype.key
*
* Allows you to set alternate key maps or overwrite existing key codes.
* For example::
*
* $.event.key({"~" : 177});
*
* @param {Object} map A map of character - keycode pairs.
*/
$.event.key = function(browser, map){
if(browser === undefined) {
return keymap;
}
if(map === undefined) {
map = browser;
browser = currentBrowser;
}
// extend the keymap
if(!keymap[browser]) {
keymap[browser] = {};
}
$.extend(keymap[browser], map);
// and also update the reverse keymap
if(!reverseKeyMap[browser]) {
reverseKeyMap[browser] = {};
}
for(var name in map){
reverseKeyMap[browser][map[name]] = name;
}
};
$.event.key({
// backspace
'\b':'8',
// tab
'\t':'9',
// enter
'\r':'13',
// special
'shift':'16','ctrl':'17','alt':'18',
// others
'pause-break':'19',
'caps':'20',
'escape':'27',
'num-lock':'144',
'scroll-lock':'145',
'print' : '44',
// navigation
'page-up':'33','page-down':'34','end':'35','home':'36',
'left':'37','up':'38','right':'39','down':'40','insert':'45','delete':'46',
// normal characters
' ':'32',
'0':'48','1':'49','2':'50','3':'51','4':'52','5':'53','6':'54','7':'55','8':'56','9':'57',
'a':'65','b':'66','c':'67','d':'68','e':'69','f':'70','g':'71','h':'72','i':'73','j':'74','k':'75','l':'76','m':'77',
'n':'78','o':'79','p':'80','q':'81','r':'82','s':'83','t':'84','u':'85','v':'86','w':'87','x':'88','y':'89','z':'90',
// normal-characters, numpad
'num0':'96','num1':'97','num2':'98','num3':'99','num4':'100','num5':'101','num6':'102','num7':'103','num8':'104','num9':'105',
'*':'106','+':'107','-':'109','.':'110',
// normal-characters, others
'/':'111',
';':'186',
'=':'187',
',':'188',
'-':'189',
'.':'190',
'/':'191',
'`':'192',
'[':'219',
'\\':'220',
']':'221',
"'":'222',
// ignore these, you shouldn't use them
'left window key':'91','right window key':'92','select key':'93',
'f1':'112','f2':'113','f3':'114','f4':'115','f5':'116','f6':'117',
'f7':'118','f8':'119','f9':'120','f10':'121','f11':'122','f12':'123'
});
/**
* @parent jQuery.event.key
* @plugin jquerypp/event/key
* @function $.Event.prototype.keyName $.Event.prototype.keyName
*
* Returns a string representation of the key pressed:
*
* $("input").on('keypress', function(ev){
* if(ev.keyName() == 'ctrl') {
* $(this).addClass('highlight');
* }
* });
*
* The key names mapped by default can be found in the [jQuery.event.key jQuery.event.key overview].
*
* @return {String} The string representation of of the key pressed.
*/
$.Event.prototype.keyName = function(){
var event = this,
test = /\w/,
// It can be either keyCode or charCode.
// Look both cases up in the reverse key map and converted to a string
key_Key = reverseKeyMap[currentBrowser][(event.keyCode || event.which)+""],
char_Key = String.fromCharCode(event.keyCode || event.which),
key_Char = event.charCode && reverseKeyMap[currentBrowser][event.charCode+""],
char_Char = event.charCode && String.fromCharCode(event.charCode);
if( char_Char && test.test(char_Char) ) {
// string representation of event.charCode
return char_Char.toLowerCase()
}
if( key_Char && test.test(key_Char) ) {
// reverseKeyMap representation of event.charCode
return char_Char.toLowerCase()
}
if( char_Key && test.test(char_Key) ) {
// string representation of event.keyCode
return char_Key.toLowerCase()
}
if( key_Key && test.test(key_Key) ) {
// reverseKeyMap representation of event.keyCode
return key_Key.toLowerCase()
}
if (event.type == 'keypress'){
// keypress doesn't capture everything
return event.keyCode ? String.fromCharCode(event.keyCode) : String.fromCharCode(event.which)
}
if (!event.keyCode && event.which) {
// event.which
return String.fromCharCode(event.which)
}
// default
return reverseKeyMap[currentBrowser][event.keyCode+""]
}
return $;
})
|
define({scientificFormat:"#E0",infinity:"∞",superscriptingExponent:"×",list:";",percentSign:"%",minusSign:"-","decimalFormat-short":"000 tril'.'",nan:"NaN",plusSign:"+",currencyFormat:"#,##0.00 ¤;(#,##0.00 ¤)",perMille:"‰",group:".",percentFormat:"#,##0 %","decimalFormat-long":"000 de trilioane",decimalFormat:"#,##0.###","currencyFormat-short":"000 tril'.' ¤",timeSeparator:":",decimal:",",exponential:"E"});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = require("babel-runtime/helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = require("babel-runtime/core-js/object/keys");
var _keys2 = _interopRequireDefault(_keys);
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _promise = require("babel-runtime/core-js/promise");
var _promise2 = _interopRequireDefault(_promise);
exports.default = npmRunAll;
var _npmRunAll = require("../lib/npm-run-all");
var _npmRunAll2 = _interopRequireDefault(_npmRunAll);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var START_PROMISE = _promise2.default.resolve(null); /**
* @author Toru Nagashima
* @copyright 2015 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
/* eslint no-process-env: 0 */
var OVERWRITE_OPTION = /^--([^:]+?):([^=]+?)(?:=(.+))?$/;
var CONFIG_PATTERN = /^npm_package_config_(.+)$/;
/**
* Overwrites a specified package config.
*
* @param {object} config - A config object to be overwritten.
* @param {string} packageName - A package name to overwrite.
* @param {string} variable - A variable name to overwrite.
* @param {string} value - A new value to overwrite.
* @returns {void}
*/
function overwriteConfig(config, packageName, variable, value) {
var scope = config[packageName] || (config[packageName] = {}); // eslint-disable-line no-param-reassign
scope[variable] = value;
}
/**
* Creates a package config object.
* This checks `process.env` and creates the default value.
*
* @returns {object} Created config object.
*/
function createPackageConfig() {
var retv = {};
var packageName = process.env.npm_package_name;
if (!packageName) {
return retv;
}
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)((0, _keys2.default)(process.env)), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var key = _step.value;
var m = CONFIG_PATTERN.exec(key);
if (m != null) {
overwriteConfig(retv, packageName, m[1], process.env[key]);
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return retv;
}
/**
* Parses arguments.
*
* @param {string[]} args - Arguments to parse.
* @returns {{
* groups: {
* parallel: boolean,
* continueOnError: boolean,
* patterns: string[]
* }[],
* packageConfig: object
* }} A running plan.
*/
function parse(args) {
var packageConfig = createPackageConfig();
var groups = [{
parallel: false,
continueOnError: false,
printLabel: false,
printName: false,
patterns: []
}];
for (var i = 0; i < args.length; ++i) {
var arg = args[i];
switch (arg) {
case "-S":
case "-s":
case "--sequential":
case "--serial":
groups.push({
parallel: false,
continueOnError: arg === "-S",
printLabel: false,
printName: false,
patterns: []
});
break;
case "-P":
case "-p":
case "--parallel":
groups.push({
parallel: true,
continueOnError: arg === "-P",
printLabel: false,
printName: false,
patterns: []
});
break;
case "-c":
case "--continue-on-error":
groups[groups.length - 1].continueOnError = true;
break;
case "-l":
case "--print-label":
groups[groups.length - 1].printLabel = true;
break;
case "-n":
case "--print-name":
groups[groups.length - 1].printName = true;
break;
case "--color":
case "--no-color":
case "--silent":
// do nothing.
break;
default:
{
var matched = OVERWRITE_OPTION.exec(arg);
if (matched) {
overwriteConfig(packageConfig, matched[1], matched[2], matched[3] || args[++i]);
} else if (arg[0] === "-") {
throw new Error("Invalid Option: " + arg);
} else {
groups[groups.length - 1].patterns.push(arg);
}
break;
}
}
}
return { groups: groups, packageConfig: packageConfig };
}
/**
* Parses arguments, then run specified npm-scripts.
*
* @param {string[]} args - Arguments to parse.
* @param {stream.Writable} stdout - A writable stream to print logs.
* @param {stream.Writable} stderr - A writable stream to print errors.
* @returns {Promise} A promise which comes to be fulfilled when all npm-scripts are completed.
* @private
*/
function npmRunAll(args, stdout, stderr) {
try {
var _ret = function () {
var stdin = process.stdin;
var silent = args.indexOf("--silent") !== -1 || process.env.npm_config_loglevel === "silent";
var _parse = parse(args);
var groups = _parse.groups;
var packageConfig = _parse.packageConfig;
return {
v: groups.reduce(function (prev, _ref) {
var patterns = _ref.patterns;
var parallel = _ref.parallel;
var continueOnError = _ref.continueOnError;
var printLabel = _ref.printLabel;
var printName = _ref.printName;
if (patterns.length === 0) {
return prev;
}
return prev.then(function () {
return (0, _npmRunAll2.default)(patterns, {
stdout: stdout,
stderr: stderr,
stdin: stdin,
parallel: parallel,
continueOnError: continueOnError,
printLabel: printLabel,
printName: printName,
packageConfig: packageConfig,
silent: silent
});
});
}, START_PROMISE)
};
}();
if ((typeof _ret === "undefined" ? "undefined" : (0, _typeof3.default)(_ret)) === "object") return _ret.v;
} catch (err) {
return _promise2.default.reject(err);
}
}
|
var assert = Iron.utils.assert;
var env = process.env.NODE_ENV || 'development';
/**
* Server specific initialization.
*/
Router.prototype.init = function (options) {};
/**
* Give people a chance to customize the body parser
* behavior.
*/
Router.prototype.configureBodyParsers = function () {
Router.onBeforeAction(Iron.Router.bodyParser.json());
Router.onBeforeAction(Iron.Router.bodyParser.urlencoded({extended: false}));
};
/**
* Add the router to the server connect handlers.
*/
Router.prototype.start = function () {
WebApp.connectHandlers.use(this);
this.configureBodyParsers();
};
/**
* Create a new controller and dispatch into the stack.
*/
Router.prototype.dispatch = function (url, context, done) {
var self = this;
assert(typeof url === 'string', "expected url string in router dispatch");
assert(typeof context === 'object', "expected context object in router dispatch");
// assumes there is only one router
// XXX need to initialize controller either from the context itself or if the
// context already has a controller on it, just use that one.
var controller = this.createController(url, context);
controller.dispatch(this._stack, url, function (err) {
var res = this.response;
var req = this.request;
var msg;
if (err) {
if (res.statusCode < 400)
res.statusCode = 500;
if (err.status)
res.statusCode = err.status;
if (env === 'development')
msg = (err.stack || err.toString()) + '\n';
else
//XXX get this from standard dict of error messages?
msg = 'Server error.';
console.error(err.stack || err.toString());
if (res.headersSent)
return req.socket.destroy();
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(msg));
if (req.method === 'HEAD')
return res.end();
res.end(msg);
return;
}
// if there are no client or server handlers for this dispatch
// then send a 404.
// XXX we need a solution here for 404s on bad routes.
// one solution might be to provide a custom 404 page in the public
// folder. But we need a proper way to handle 404s for search engines.
// XXX might be a PR to Meteor to use an existing status code if it's set
if (!controller.isHandled() && !controller.willBeHandledOnClient()) {
return done();
/*
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
msg = req.method + ' ' + req.originalUrl + ' not found.';
console.error(msg);
if (req.method == 'HEAD')
return res.end();
res.end(msg + '\n');
return;
*/
}
// if for some reason there was a server handler but no client handler
// and the server handler called next() we might end up here. We
// want to make sure to end the response so it doesn't hang.
if (controller.isHandled() && !controller.willBeHandledOnClient()) {
res.setHeader('Content-Type', 'text/html');
if (req.method === 'HEAD')
res.end();
res.end("<p>It looks like you don't have any client routes defined, but you had at least one server handler. You probably want to define some client side routes!</p>\n");
}
// we'll have Meteor load the normal application so long as
// we have at least one client route/handler and the done() iterator
// function has been passed to us, presumably from Connect.
if (controller.willBeHandledOnClient() && done)
return done(err);
});
};
|
/**
* @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'devtools', 'bg', {
title: 'Информация за елемента',
dialogName: 'Име на диалоговия прозорец',
tabName: 'Име на таб',
elementId: 'ID на елемента',
elementType: 'Тип на елемента'
} );
|
(function (window) {
'use strict';
/*global define, module, exports, require */
var c3 = { version: "0.4.10-rc5" };
var c3_chart_fn,
c3_chart_internal_fn,
c3_chart_internal_axis_fn;
function API(owner) {
this.owner = owner;
}
function inherit(base, derived) {
if (Object.create) {
derived.prototype = Object.create(base.prototype);
} else {
var f = function f() {};
f.prototype = base.prototype;
derived.prototype = new f();
}
derived.prototype.constructor = derived;
return derived;
}
function Chart(config) {
var $$ = this.internal = new ChartInternal(this);
$$.loadConfig(config);
$$.init();
// bind "this" to nested API
(function bindThis(fn, target, argThis) {
Object.keys(fn).forEach(function (key) {
target[key] = fn[key].bind(argThis);
if (Object.keys(fn[key]).length > 0) {
bindThis(fn[key], target[key], argThis);
}
});
})(c3_chart_fn, this, this);
}
function ChartInternal(api) {
var $$ = this;
$$.d3 = window.d3 ? window.d3 : typeof require !== 'undefined' ? require("d3") : undefined;
$$.api = api;
$$.config = $$.getDefaultConfig();
$$.data = {};
$$.cache = {};
$$.axes = {};
}
c3.generate = function (config) {
return new Chart(config);
};
c3.chart = {
fn: Chart.prototype,
internal: {
fn: ChartInternal.prototype,
axis: {
fn: Axis.prototype
}
}
};
c3_chart_fn = c3.chart.fn;
c3_chart_internal_fn = c3.chart.internal.fn;
c3_chart_internal_axis_fn = c3.chart.internal.axis.fn;
c3_chart_internal_fn.init = function () {
var $$ = this, config = $$.config;
$$.initParams();
if (config.data_url) {
$$.convertUrlToData(config.data_url, config.data_mimeType, config.data_keys, $$.initWithData);
}
else if (config.data_json) {
$$.initWithData($$.convertJsonToData(config.data_json, config.data_keys));
}
else if (config.data_rows) {
$$.initWithData($$.convertRowsToData(config.data_rows));
}
else if (config.data_columns) {
$$.initWithData($$.convertColumnsToData(config.data_columns));
}
else {
throw Error('url or json or rows or columns is required.');
}
};
c3_chart_internal_fn.initParams = function () {
var $$ = this, d3 = $$.d3, config = $$.config;
// MEMO: clipId needs to be unique because it conflicts when multiple charts exist
$$.clipId = "c3-" + (+new Date()) + '-clip',
$$.clipIdForXAxis = $$.clipId + '-xaxis',
$$.clipIdForYAxis = $$.clipId + '-yaxis',
$$.clipIdForGrid = $$.clipId + '-grid',
$$.clipIdForSubchart = $$.clipId + '-subchart',
$$.clipPath = $$.getClipPath($$.clipId),
$$.clipPathForXAxis = $$.getClipPath($$.clipIdForXAxis),
$$.clipPathForYAxis = $$.getClipPath($$.clipIdForYAxis);
$$.clipPathForGrid = $$.getClipPath($$.clipIdForGrid),
$$.clipPathForSubchart = $$.getClipPath($$.clipIdForSubchart),
$$.dragStart = null;
$$.dragging = false;
$$.flowing = false;
$$.cancelClick = false;
$$.mouseover = false;
$$.transiting = false;
$$.color = $$.generateColor();
$$.levelColor = $$.generateLevelColor();
$$.dataTimeFormat = config.data_xLocaltime ? d3.time.format : d3.time.format.utc;
$$.axisTimeFormat = config.axis_x_localtime ? d3.time.format : d3.time.format.utc;
$$.defaultAxisTimeFormat = $$.axisTimeFormat.multi([
[".%L", function (d) { return d.getMilliseconds(); }],
[":%S", function (d) { return d.getSeconds(); }],
["%I:%M", function (d) { return d.getMinutes(); }],
["%I %p", function (d) { return d.getHours(); }],
["%-m/%-d", function (d) { return d.getDay() && d.getDate() !== 1; }],
["%-m/%-d", function (d) { return d.getDate() !== 1; }],
["%-m/%-d", function (d) { return d.getMonth(); }],
["%Y/%-m/%-d", function () { return true; }]
]);
$$.hiddenTargetIds = [];
$$.hiddenLegendIds = [];
$$.focusedTargetIds = [];
$$.defocusedTargetIds = [];
$$.xOrient = config.axis_rotated ? "left" : "bottom";
$$.yOrient = config.axis_rotated ? (config.axis_y_inner ? "top" : "bottom") : (config.axis_y_inner ? "right" : "left");
$$.y2Orient = config.axis_rotated ? (config.axis_y2_inner ? "bottom" : "top") : (config.axis_y2_inner ? "left" : "right");
$$.subXOrient = config.axis_rotated ? "left" : "bottom";
$$.isLegendRight = config.legend_position === 'right';
$$.isLegendInset = config.legend_position === 'inset';
$$.isLegendTop = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'top-right';
$$.isLegendLeft = config.legend_inset_anchor === 'top-left' || config.legend_inset_anchor === 'bottom-left';
$$.legendStep = 0;
$$.legendItemWidth = 0;
$$.legendItemHeight = 0;
$$.currentMaxTickWidths = {
x: 0,
y: 0,
y2: 0
};
$$.rotated_padding_left = 30;
$$.rotated_padding_right = config.axis_rotated && !config.axis_x_show ? 0 : 30;
$$.rotated_padding_top = 5;
$$.withoutFadeIn = {};
$$.intervalForObserveInserted = undefined;
$$.axes.subx = d3.selectAll([]); // needs when excluding subchart.js
};
c3_chart_internal_fn.initChartElements = function () {
if (this.initBar) { this.initBar(); }
if (this.initLine) { this.initLine(); }
if (this.initArc) { this.initArc(); }
if (this.initGauge) { this.initGauge(); }
if (this.initText) { this.initText(); }
};
c3_chart_internal_fn.initWithData = function (data) {
var $$ = this, d3 = $$.d3, config = $$.config;
var defs, main, binding = true;
$$.axis = new Axis($$);
if ($$.initPie) { $$.initPie(); }
if ($$.initBrush) { $$.initBrush(); }
if ($$.initZoom) { $$.initZoom(); }
if (!config.bindto) {
$$.selectChart = d3.selectAll([]);
}
else if (typeof config.bindto.node === 'function') {
$$.selectChart = config.bindto;
}
else {
$$.selectChart = d3.select(config.bindto);
}
if ($$.selectChart.empty()) {
$$.selectChart = d3.select(document.createElement('div')).style('opacity', 0);
$$.observeInserted($$.selectChart);
binding = false;
}
$$.selectChart.html("").classed("c3", true);
// Init data as targets
$$.data.xs = {};
$$.data.targets = $$.convertDataToTargets(data);
if (config.data_filter) {
$$.data.targets = $$.data.targets.filter(config.data_filter);
}
// Set targets to hide if needed
if (config.data_hide) {
$$.addHiddenTargetIds(config.data_hide === true ? $$.mapToIds($$.data.targets) : config.data_hide);
}
if (config.legend_hide) {
$$.addHiddenLegendIds(config.legend_hide === true ? $$.mapToIds($$.data.targets) : config.legend_hide);
}
// when gauge, hide legend // TODO: fix
if ($$.hasType('gauge')) {
config.legend_show = false;
}
// Init sizes and scales
$$.updateSizes();
$$.updateScales();
// Set domains for each scale
$$.x.domain(d3.extent($$.getXDomain($$.data.targets)));
$$.y.domain($$.getYDomain($$.data.targets, 'y'));
$$.y2.domain($$.getYDomain($$.data.targets, 'y2'));
$$.subX.domain($$.x.domain());
$$.subY.domain($$.y.domain());
$$.subY2.domain($$.y2.domain());
// Save original x domain for zoom update
$$.orgXDomain = $$.x.domain();
// Set initialized scales to brush and zoom
if ($$.brush) { $$.brush.scale($$.subX); }
if (config.zoom_enabled) { $$.zoom.scale($$.x); }
/*-- Basic Elements --*/
// Define svgs
$$.svg = $$.selectChart.append("svg")
.style("overflow", "hidden")
.on('mouseenter', function () { return config.onmouseover.call($$); })
.on('mouseleave', function () { return config.onmouseout.call($$); });
// Define defs
defs = $$.svg.append("defs");
$$.clipChart = $$.appendClip(defs, $$.clipId);
$$.clipXAxis = $$.appendClip(defs, $$.clipIdForXAxis);
$$.clipYAxis = $$.appendClip(defs, $$.clipIdForYAxis);
$$.clipGrid = $$.appendClip(defs, $$.clipIdForGrid);
$$.clipSubchart = $$.appendClip(defs, $$.clipIdForSubchart);
$$.updateSvgSize();
// Define regions
main = $$.main = $$.svg.append("g").attr("transform", $$.getTranslate('main'));
if ($$.initSubchart) { $$.initSubchart(); }
if ($$.initTooltip) { $$.initTooltip(); }
if ($$.initLegend) { $$.initLegend(); }
/*-- Main Region --*/
// text when empty
main.append("text")
.attr("class", CLASS.text + ' ' + CLASS.empty)
.attr("text-anchor", "middle") // horizontal centering of text at x position in all browsers.
.attr("dominant-baseline", "middle"); // vertical centering of text at y position in all browsers, except IE.
// Regions
$$.initRegion();
// Grids
$$.initGrid();
// Define g for chart area
main.append('g')
.attr("clip-path", $$.clipPath)
.attr('class', CLASS.chart);
// Grid lines
if (config.grid_lines_front) { $$.initGridLines(); }
// Cover whole with rects for events
$$.initEventRect();
// Define g for chart
$$.initChartElements();
// if zoom privileged, insert rect to forefront
// TODO: is this needed?
main.insert('rect', config.zoom_privileged ? null : 'g.' + CLASS.regions)
.attr('class', CLASS.zoomRect)
.attr('width', $$.width)
.attr('height', $$.height)
.style('opacity', 0)
.on("dblclick.zoom", null);
// Set default extent if defined
if (config.axis_x_extent) { $$.brush.extent($$.getDefaultExtent()); }
// Add Axis
$$.axis.init();
// Set targets
$$.updateTargets($$.data.targets);
// Draw with targets
if (binding) {
$$.updateDimension();
$$.config.oninit.call($$);
$$.redraw({
withTransition: false,
withTransform: true,
withUpdateXDomain: true,
withUpdateOrgXDomain: true,
withTransitionForAxis: false
});
}
// Bind resize event
if (window.onresize == null) {
window.onresize = $$.generateResize();
}
if (window.onresize.add) {
window.onresize.add(function () {
config.onresize.call($$);
});
window.onresize.add(function () {
$$.api.flush();
});
window.onresize.add(function () {
config.onresized.call($$);
});
}
// export element of the chart
$$.api.element = $$.selectChart.node();
};
c3_chart_internal_fn.smoothLines = function (el, type) {
var $$ = this;
if (type === 'grid') {
el.each(function () {
var g = $$.d3.select(this),
x1 = g.attr('x1'),
x2 = g.attr('x2'),
y1 = g.attr('y1'),
y2 = g.attr('y2');
g.attr({
'x1': Math.ceil(x1),
'x2': Math.ceil(x2),
'y1': Math.ceil(y1),
'y2': Math.ceil(y2)
});
});
}
};
c3_chart_internal_fn.updateSizes = function () {
var $$ = this, config = $$.config;
var legendHeight = $$.legend ? $$.getLegendHeight() : 0,
legendWidth = $$.legend ? $$.getLegendWidth() : 0,
legendHeightForBottom = $$.isLegendRight || $$.isLegendInset ? 0 : legendHeight,
hasArc = $$.hasArcType(),
xAxisHeight = config.axis_rotated || hasArc ? 0 : $$.getHorizontalAxisHeight('x'),
subchartHeight = config.subchart_show && !hasArc ? (config.subchart_size_height + xAxisHeight) : 0;
$$.currentWidth = $$.getCurrentWidth();
$$.currentHeight = $$.getCurrentHeight();
// for main
$$.margin = config.axis_rotated ? {
top: $$.getHorizontalAxisHeight('y2') + $$.getCurrentPaddingTop(),
right: hasArc ? 0 : $$.getCurrentPaddingRight(),
bottom: $$.getHorizontalAxisHeight('y') + legendHeightForBottom + $$.getCurrentPaddingBottom(),
left: subchartHeight + (hasArc ? 0 : $$.getCurrentPaddingLeft())
} : {
top: 4 + $$.getCurrentPaddingTop(), // for top tick text
right: hasArc ? 0 : $$.getCurrentPaddingRight(),
bottom: xAxisHeight + subchartHeight + legendHeightForBottom + $$.getCurrentPaddingBottom(),
left: hasArc ? 0 : $$.getCurrentPaddingLeft()
};
// for subchart
$$.margin2 = config.axis_rotated ? {
top: $$.margin.top,
right: NaN,
bottom: 20 + legendHeightForBottom,
left: $$.rotated_padding_left
} : {
top: $$.currentHeight - subchartHeight - legendHeightForBottom,
right: NaN,
bottom: xAxisHeight + legendHeightForBottom,
left: $$.margin.left
};
// for legend
$$.margin3 = {
top: 0,
right: NaN,
bottom: 0,
left: 0
};
if ($$.updateSizeForLegend) { $$.updateSizeForLegend(legendHeight, legendWidth); }
$$.width = $$.currentWidth - $$.margin.left - $$.margin.right;
$$.height = $$.currentHeight - $$.margin.top - $$.margin.bottom;
if ($$.width < 0) { $$.width = 0; }
if ($$.height < 0) { $$.height = 0; }
$$.width2 = config.axis_rotated ? $$.margin.left - $$.rotated_padding_left - $$.rotated_padding_right : $$.width;
$$.height2 = config.axis_rotated ? $$.height : $$.currentHeight - $$.margin2.top - $$.margin2.bottom;
if ($$.width2 < 0) { $$.width2 = 0; }
if ($$.height2 < 0) { $$.height2 = 0; }
// for arc
$$.arcWidth = $$.width - ($$.isLegendRight ? legendWidth + 10 : 0);
$$.arcHeight = $$.height - ($$.isLegendRight ? 0 : 10);
if ($$.hasType('gauge')) {
$$.arcHeight += $$.height - $$.getGaugeLabelHeight();
}
if ($$.updateRadius) { $$.updateRadius(); }
if ($$.isLegendRight && hasArc) {
$$.margin3.left = $$.arcWidth / 2 + $$.radiusExpanded * 1.1;
}
};
c3_chart_internal_fn.updateTargets = function (targets) {
var $$ = this;
/*-- Main --*/
//-- Text --//
$$.updateTargetsForText(targets);
//-- Bar --//
$$.updateTargetsForBar(targets);
//-- Line --//
$$.updateTargetsForLine(targets);
//-- Arc --//
if ($$.hasArcType() && $$.updateTargetsForArc) { $$.updateTargetsForArc(targets); }
/*-- Sub --*/
if ($$.updateTargetsForSubchart) { $$.updateTargetsForSubchart(targets); }
// Fade-in each chart
$$.showTargets();
};
c3_chart_internal_fn.showTargets = function () {
var $$ = this;
$$.svg.selectAll('.' + CLASS.target).filter(function (d) { return $$.isTargetToShow(d.id); })
.transition().duration($$.config.transition_duration)
.style("opacity", 1);
};
c3_chart_internal_fn.redraw = function (options, transitions) {
var $$ = this, main = $$.main, d3 = $$.d3, config = $$.config;
var areaIndices = $$.getShapeIndices($$.isAreaType), barIndices = $$.getShapeIndices($$.isBarType), lineIndices = $$.getShapeIndices($$.isLineType);
var withY, withSubchart, withTransition, withTransitionForExit, withTransitionForAxis,
withTransform, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain, withLegend,
withEventRect, withDimension, withUpdateXAxis;
var hideAxis = $$.hasArcType();
var drawArea, drawBar, drawLine, xForText, yForText;
var duration, durationForExit, durationForAxis;
var waitForDraw, flow;
var targetsToShow = $$.filterTargetsToShow($$.data.targets), tickValues, i, intervalForCulling, xDomainForZoom;
var xv = $$.xv.bind($$), cx, cy;
options = options || {};
withY = getOption(options, "withY", true);
withSubchart = getOption(options, "withSubchart", true);
withTransition = getOption(options, "withTransition", true);
withTransform = getOption(options, "withTransform", false);
withUpdateXDomain = getOption(options, "withUpdateXDomain", false);
withUpdateOrgXDomain = getOption(options, "withUpdateOrgXDomain", false);
withTrimXDomain = getOption(options, "withTrimXDomain", true);
withUpdateXAxis = getOption(options, "withUpdateXAxis", withUpdateXDomain);
withLegend = getOption(options, "withLegend", false);
withEventRect = getOption(options, "withEventRect", true);
withDimension = getOption(options, "withDimension", true);
withTransitionForExit = getOption(options, "withTransitionForExit", withTransition);
withTransitionForAxis = getOption(options, "withTransitionForAxis", withTransition);
duration = withTransition ? config.transition_duration : 0;
durationForExit = withTransitionForExit ? duration : 0;
durationForAxis = withTransitionForAxis ? duration : 0;
transitions = transitions || $$.axis.generateTransitions(durationForAxis);
// update legend and transform each g
if (withLegend && config.legend_show) {
$$.updateLegend($$.mapToIds($$.data.targets), options, transitions);
} else if (withDimension) {
// need to update dimension (e.g. axis.y.tick.values) because y tick values should change
// no need to update axis in it because they will be updated in redraw()
$$.updateDimension(true);
}
// MEMO: needed for grids calculation
if ($$.isCategorized() && targetsToShow.length === 0) {
$$.x.domain([0, $$.axes.x.selectAll('.tick').size()]);
}
if (targetsToShow.length) {
$$.updateXDomain(targetsToShow, withUpdateXDomain, withUpdateOrgXDomain, withTrimXDomain);
if (!config.axis_x_tick_values) {
tickValues = $$.axis.updateXAxisTickValues(targetsToShow);
}
} else {
$$.xAxis.tickValues([]);
$$.subXAxis.tickValues([]);
}
if (config.zoom_rescale && !options.flow) {
xDomainForZoom = $$.x.orgDomain();
}
$$.y.domain($$.getYDomain(targetsToShow, 'y', xDomainForZoom));
$$.y2.domain($$.getYDomain(targetsToShow, 'y2', xDomainForZoom));
if (!config.axis_y_tick_values && config.axis_y_tick_count) {
$$.yAxis.tickValues($$.axis.generateTickValues($$.y.domain(), config.axis_y_tick_count));
}
if (!config.axis_y2_tick_values && config.axis_y2_tick_count) {
$$.y2Axis.tickValues($$.axis.generateTickValues($$.y2.domain(), config.axis_y2_tick_count));
}
// axes
$$.axis.redraw(transitions, hideAxis);
// Update axis label
$$.axis.updateLabels(withTransition);
// show/hide if manual culling needed
if ((withUpdateXDomain || withUpdateXAxis) && targetsToShow.length) {
if (config.axis_x_tick_culling && tickValues) {
for (i = 1; i < tickValues.length; i++) {
if (tickValues.length / i < config.axis_x_tick_culling_max) {
intervalForCulling = i;
break;
}
}
$$.svg.selectAll('.' + CLASS.axisX + ' .tick text').each(function (e) {
var index = tickValues.indexOf(e);
if (index >= 0) {
d3.select(this).style('display', index % intervalForCulling ? 'none' : 'block');
}
});
} else {
$$.svg.selectAll('.' + CLASS.axisX + ' .tick text').style('display', 'block');
}
}
// setup drawer - MEMO: these must be called after axis updated
drawArea = $$.generateDrawArea ? $$.generateDrawArea(areaIndices, false) : undefined;
drawBar = $$.generateDrawBar ? $$.generateDrawBar(barIndices) : undefined;
drawLine = $$.generateDrawLine ? $$.generateDrawLine(lineIndices, false) : undefined;
xForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, true);
yForText = $$.generateXYForText(areaIndices, barIndices, lineIndices, false);
// Update sub domain
if (withY) {
$$.subY.domain($$.getYDomain(targetsToShow, 'y'));
$$.subY2.domain($$.getYDomain(targetsToShow, 'y2'));
}
// tooltip
$$.tooltip.style("display", "none");
// xgrid focus
$$.updateXgridFocus();
// Data empty label positioning and text.
main.select("text." + CLASS.text + '.' + CLASS.empty)
.attr("x", $$.width / 2)
.attr("y", $$.height / 2)
.text(config.data_empty_label_text)
.transition()
.style('opacity', targetsToShow.length ? 0 : 1);
// grid
$$.updateGrid(duration);
// rect for regions
$$.updateRegion(duration);
// bars
$$.updateBar(durationForExit);
// lines, areas and cricles
$$.updateLine(durationForExit);
$$.updateArea(durationForExit);
$$.updateCircle();
// text
if ($$.hasDataLabel()) {
$$.updateText(durationForExit);
}
// arc
if ($$.redrawArc) { $$.redrawArc(duration, durationForExit, withTransform); }
// subchart
if ($$.redrawSubchart) {
$$.redrawSubchart(withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices);
}
// circles for select
main.selectAll('.' + CLASS.selectedCircles)
.filter($$.isBarType.bind($$))
.selectAll('circle')
.remove();
// event rects will redrawn when flow called
if (config.interaction_enabled && !options.flow && withEventRect) {
$$.redrawEventRect();
if ($$.updateZoom) { $$.updateZoom(); }
}
// update circleY based on updated parameters
$$.updateCircleY();
// generate circle x/y functions depending on updated params
cx = ($$.config.axis_rotated ? $$.circleY : $$.circleX).bind($$);
cy = ($$.config.axis_rotated ? $$.circleX : $$.circleY).bind($$);
if (options.flow) {
flow = $$.generateFlow({
targets: targetsToShow,
flow: options.flow,
duration: options.flow.duration,
drawBar: drawBar,
drawLine: drawLine,
drawArea: drawArea,
cx: cx,
cy: cy,
xv: xv,
xForText: xForText,
yForText: yForText
});
}
if ((duration || flow) && $$.isTabVisible()) { // Only use transition if tab visible. See #938.
// transition should be derived from one transition
d3.transition().duration(duration).each(function () {
var transitionsToWait = [];
// redraw and gather transitions
[
$$.redrawBar(drawBar, true),
$$.redrawLine(drawLine, true),
$$.redrawArea(drawArea, true),
$$.redrawCircle(cx, cy, true),
$$.redrawText(xForText, yForText, options.flow, true),
$$.redrawRegion(true),
$$.redrawGrid(true),
].forEach(function (transitions) {
transitions.forEach(function (transition) {
transitionsToWait.push(transition);
});
});
// Wait for end of transitions to call flow and onrendered callback
waitForDraw = $$.generateWait();
transitionsToWait.forEach(function (t) {
waitForDraw.add(t);
});
})
.call(waitForDraw, function () {
if (flow) {
flow();
}
if (config.onrendered) {
config.onrendered.call($$);
}
});
}
else {
$$.redrawBar(drawBar);
$$.redrawLine(drawLine);
$$.redrawArea(drawArea);
$$.redrawCircle(cx, cy);
$$.redrawText(xForText, yForText, options.flow);
$$.redrawRegion();
$$.redrawGrid();
if (config.onrendered) {
config.onrendered.call($$);
}
}
// update fadein condition
$$.mapToIds($$.data.targets).forEach(function (id) {
$$.withoutFadeIn[id] = true;
});
};
c3_chart_internal_fn.updateAndRedraw = function (options) {
var $$ = this, config = $$.config, transitions;
options = options || {};
// same with redraw
options.withTransition = getOption(options, "withTransition", true);
options.withTransform = getOption(options, "withTransform", false);
options.withLegend = getOption(options, "withLegend", false);
// NOT same with redraw
options.withUpdateXDomain = true;
options.withUpdateOrgXDomain = true;
options.withTransitionForExit = false;
options.withTransitionForTransform = getOption(options, "withTransitionForTransform", options.withTransition);
// MEMO: this needs to be called before updateLegend and it means this ALWAYS needs to be called)
$$.updateSizes();
// MEMO: called in updateLegend in redraw if withLegend
if (!(options.withLegend && config.legend_show)) {
transitions = $$.axis.generateTransitions(options.withTransitionForAxis ? config.transition_duration : 0);
// Update scales
$$.updateScales();
$$.updateSvgSize();
// Update g positions
$$.transformAll(options.withTransitionForTransform, transitions);
}
// Draw with new sizes & scales
$$.redraw(options, transitions);
};
c3_chart_internal_fn.redrawWithoutRescale = function () {
this.redraw({
withY: false,
withSubchart: false,
withEventRect: false,
withTransitionForAxis: false
});
};
c3_chart_internal_fn.isTimeSeries = function () {
return this.config.axis_x_type === 'timeseries';
};
c3_chart_internal_fn.isCategorized = function () {
return this.config.axis_x_type.indexOf('categor') >= 0;
};
c3_chart_internal_fn.isCustomX = function () {
var $$ = this, config = $$.config;
return !$$.isTimeSeries() && (config.data_x || notEmpty(config.data_xs));
};
c3_chart_internal_fn.isTimeSeriesY = function () {
return this.config.axis_y_type === 'timeseries';
};
c3_chart_internal_fn.getTranslate = function (target) {
var $$ = this, config = $$.config, x, y;
if (target === 'main') {
x = asHalfPixel($$.margin.left);
y = asHalfPixel($$.margin.top);
} else if (target === 'context') {
x = asHalfPixel($$.margin2.left);
y = asHalfPixel($$.margin2.top);
} else if (target === 'legend') {
x = $$.margin3.left;
y = $$.margin3.top;
} else if (target === 'x') {
x = 0;
y = config.axis_rotated ? 0 : $$.height;
} else if (target === 'y') {
x = 0;
y = config.axis_rotated ? $$.height : 0;
} else if (target === 'y2') {
x = config.axis_rotated ? 0 : $$.width;
y = config.axis_rotated ? 1 : 0;
} else if (target === 'subx') {
x = 0;
y = config.axis_rotated ? 0 : $$.height2;
} else if (target === 'arc') {
x = $$.arcWidth / 2;
y = $$.arcHeight / 2;
}
return "translate(" + x + "," + y + ")";
};
c3_chart_internal_fn.initialOpacity = function (d) {
return d.value !== null && this.withoutFadeIn[d.id] ? 1 : 0;
};
c3_chart_internal_fn.initialOpacityForCircle = function (d) {
return d.value !== null && this.withoutFadeIn[d.id] ? this.opacityForCircle(d) : 0;
};
c3_chart_internal_fn.opacityForCircle = function (d) {
var opacity = this.config.point_show ? 1 : 0;
return isValue(d.value) ? (this.isScatterType(d) ? 0.5 : opacity) : 0;
};
c3_chart_internal_fn.opacityForText = function () {
return this.hasDataLabel() ? 1 : 0;
};
c3_chart_internal_fn.xx = function (d) {
return d ? this.x(d.x) : null;
};
c3_chart_internal_fn.xv = function (d) {
var $$ = this, value = d.value;
if ($$.isTimeSeries()) {
value = $$.parseDate(d.value);
}
else if ($$.isCategorized() && typeof d.value === 'string') {
value = $$.config.axis_x_categories.indexOf(d.value);
}
return Math.ceil($$.x(value));
};
c3_chart_internal_fn.yv = function (d) {
var $$ = this,
yScale = d.axis && d.axis === 'y2' ? $$.y2 : $$.y;
return Math.ceil(yScale(d.value));
};
c3_chart_internal_fn.subxx = function (d) {
return d ? this.subX(d.x) : null;
};
c3_chart_internal_fn.transformMain = function (withTransition, transitions) {
var $$ = this,
xAxis, yAxis, y2Axis;
if (transitions && transitions.axisX) {
xAxis = transitions.axisX;
} else {
xAxis = $$.main.select('.' + CLASS.axisX);
if (withTransition) { xAxis = xAxis.transition(); }
}
if (transitions && transitions.axisY) {
yAxis = transitions.axisY;
} else {
yAxis = $$.main.select('.' + CLASS.axisY);
if (withTransition) { yAxis = yAxis.transition(); }
}
if (transitions && transitions.axisY2) {
y2Axis = transitions.axisY2;
} else {
y2Axis = $$.main.select('.' + CLASS.axisY2);
if (withTransition) { y2Axis = y2Axis.transition(); }
}
(withTransition ? $$.main.transition() : $$.main).attr("transform", $$.getTranslate('main'));
xAxis.attr("transform", $$.getTranslate('x'));
yAxis.attr("transform", $$.getTranslate('y'));
y2Axis.attr("transform", $$.getTranslate('y2'));
$$.main.select('.' + CLASS.chartArcs).attr("transform", $$.getTranslate('arc'));
};
c3_chart_internal_fn.transformAll = function (withTransition, transitions) {
var $$ = this;
$$.transformMain(withTransition, transitions);
if ($$.config.subchart_show) { $$.transformContext(withTransition, transitions); }
if ($$.legend) { $$.transformLegend(withTransition); }
};
c3_chart_internal_fn.updateSvgSize = function () {
var $$ = this,
brush = $$.svg.select(".c3-brush .background");
$$.svg.attr('width', $$.currentWidth).attr('height', $$.currentHeight);
$$.svg.selectAll(['#' + $$.clipId, '#' + $$.clipIdForGrid]).select('rect')
.attr('width', $$.width)
.attr('height', $$.height);
$$.svg.select('#' + $$.clipIdForXAxis).select('rect')
.attr('x', $$.getXAxisClipX.bind($$))
.attr('y', $$.getXAxisClipY.bind($$))
.attr('width', $$.getXAxisClipWidth.bind($$))
.attr('height', $$.getXAxisClipHeight.bind($$));
$$.svg.select('#' + $$.clipIdForYAxis).select('rect')
.attr('x', $$.getYAxisClipX.bind($$))
.attr('y', $$.getYAxisClipY.bind($$))
.attr('width', $$.getYAxisClipWidth.bind($$))
.attr('height', $$.getYAxisClipHeight.bind($$));
$$.svg.select('#' + $$.clipIdForSubchart).select('rect')
.attr('width', $$.width)
.attr('height', brush.size() ? brush.attr('height') : 0);
$$.svg.select('.' + CLASS.zoomRect)
.attr('width', $$.width)
.attr('height', $$.height);
// MEMO: parent div's height will be bigger than svg when <!DOCTYPE html>
$$.selectChart.style('max-height', $$.currentHeight + "px");
};
c3_chart_internal_fn.updateDimension = function (withoutAxis) {
var $$ = this;
if (!withoutAxis) {
if ($$.config.axis_rotated) {
$$.axes.x.call($$.xAxis);
$$.axes.subx.call($$.subXAxis);
} else {
$$.axes.y.call($$.yAxis);
$$.axes.y2.call($$.y2Axis);
}
}
$$.updateSizes();
$$.updateScales();
$$.updateSvgSize();
$$.transformAll(false);
};
c3_chart_internal_fn.observeInserted = function (selection) {
var $$ = this, observer;
if (typeof MutationObserver === 'undefined') {
window.console.error("MutationObserver not defined.");
return;
}
observer= new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
if (mutation.type === 'childList' && mutation.previousSibling) {
observer.disconnect();
// need to wait for completion of load because size calculation requires the actual sizes determined after that completion
$$.intervalForObserveInserted = window.setInterval(function () {
// parentNode will NOT be null when completed
if (selection.node().parentNode) {
window.clearInterval($$.intervalForObserveInserted);
$$.updateDimension();
$$.config.oninit.call($$);
$$.redraw({
withTransform: true,
withUpdateXDomain: true,
withUpdateOrgXDomain: true,
withTransition: false,
withTransitionForTransform: false,
withLegend: true
});
selection.transition().style('opacity', 1);
}
}, 10);
}
});
});
observer.observe(selection.node(), {attributes: true, childList: true, characterData: true});
};
c3_chart_internal_fn.generateResize = function () {
var resizeFunctions = [];
function callResizeFunctions() {
resizeFunctions.forEach(function (f) {
f();
});
}
callResizeFunctions.add = function (f) {
resizeFunctions.push(f);
};
return callResizeFunctions;
};
c3_chart_internal_fn.endall = function (transition, callback) {
var n = 0;
transition
.each(function () { ++n; })
.each("end", function () {
if (!--n) { callback.apply(this, arguments); }
});
};
c3_chart_internal_fn.generateWait = function () {
var transitionsToWait = [],
f = function (transition, callback) {
var timer = setInterval(function () {
var done = 0;
transitionsToWait.forEach(function (t) {
if (t.empty()) {
done += 1;
return;
}
try {
t.transition();
} catch (e) {
done += 1;
}
});
if (done === transitionsToWait.length) {
clearInterval(timer);
if (callback) { callback(); }
}
}, 10);
};
f.add = function (transition) {
transitionsToWait.push(transition);
};
return f;
};
c3_chart_internal_fn.parseDate = function (date) {
var $$ = this, parsedDate;
if (date instanceof Date) {
parsedDate = date;
} else if (typeof date === 'string') {
parsedDate = $$.dataTimeFormat($$.config.data_xFormat).parse(date);
} else if (typeof date === 'number' || !isNaN(date)) {
parsedDate = new Date(+date);
}
if (!parsedDate || isNaN(+parsedDate)) {
window.console.error("Failed to parse x '" + date + "' to Date object");
}
return parsedDate;
};
c3_chart_internal_fn.isTabVisible = function () {
var hidden;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
} else if (typeof document.mozHidden !== "undefined") {
hidden = "mozHidden";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
}
return document[hidden] ? false : true;
};
c3_chart_internal_fn.getDefaultConfig = function () {
var config = {
bindto: '#chart',
size_width: undefined,
size_height: undefined,
padding_left: undefined,
padding_right: undefined,
padding_top: undefined,
padding_bottom: undefined,
zoom_enabled: false,
zoom_extent: undefined,
zoom_privileged: false,
zoom_rescale: false,
zoom_onzoom: function () {},
zoom_onzoomstart: function () {},
zoom_onzoomend: function () {},
interaction_enabled: true,
onmouseover: function () {},
onmouseout: function () {},
onresize: function () {},
onresized: function () {},
oninit: function () {},
onrendered: function () {},
transition_duration: 350,
data_x: undefined,
data_xs: {},
data_xFormat: '%Y-%m-%d',
data_xLocaltime: true,
data_xSort: true,
data_idConverter: function (id) { return id; },
data_names: {},
data_classes: {},
data_groups: [],
data_axes: {},
data_type: undefined,
data_types: {},
data_labels: {},
data_order: 'desc',
data_regions: {},
data_color: undefined,
data_colors: {},
data_hide: false,
data_filter: undefined,
data_selection_enabled: false,
data_selection_grouped: false,
data_selection_isselectable: function () { return true; },
data_selection_multiple: true,
data_selection_draggable: false,
data_onclick: function () {},
data_onmouseover: function () {},
data_onmouseout: function () {},
data_onselected: function () {},
data_onunselected: function () {},
data_url: undefined,
data_json: undefined,
data_rows: undefined,
data_columns: undefined,
data_mimeType: undefined,
data_keys: undefined,
// configuration for no plot-able data supplied.
data_empty_label_text: "",
// subchart
subchart_show: false,
subchart_size_height: 60,
subchart_onbrush: function () {},
// color
color_pattern: [],
color_threshold: {},
// legend
legend_show: true,
legend_hide: false,
legend_position: 'bottom',
legend_inset_anchor: 'top-left',
legend_inset_x: 10,
legend_inset_y: 0,
legend_inset_step: undefined,
legend_item_onclick: undefined,
legend_item_onmouseover: undefined,
legend_item_onmouseout: undefined,
legend_equally: false,
// axis
axis_rotated: false,
axis_x_show: true,
axis_x_type: 'indexed',
axis_x_localtime: true,
axis_x_categories: [],
axis_x_tick_centered: false,
axis_x_tick_format: undefined,
axis_x_tick_culling: {},
axis_x_tick_culling_max: 10,
axis_x_tick_count: undefined,
axis_x_tick_fit: true,
axis_x_tick_values: null,
axis_x_tick_rotate: 0,
axis_x_tick_outer: true,
axis_x_tick_multiline: true,
axis_x_tick_width: null,
axis_x_max: undefined,
axis_x_min: undefined,
axis_x_padding: {},
axis_x_height: undefined,
axis_x_extent: undefined,
axis_x_label: {},
axis_y_show: true,
axis_y_type: undefined,
axis_y_max: undefined,
axis_y_min: undefined,
axis_y_inverted: false,
axis_y_center: undefined,
axis_y_inner: undefined,
axis_y_label: {},
axis_y_tick_format: undefined,
axis_y_tick_outer: true,
axis_y_tick_values: null,
axis_y_tick_count: undefined,
axis_y_tick_time_value: undefined,
axis_y_tick_time_interval: undefined,
axis_y_padding: {},
axis_y_default: undefined,
axis_y2_show: false,
axis_y2_max: undefined,
axis_y2_min: undefined,
axis_y2_inverted: false,
axis_y2_center: undefined,
axis_y2_inner: undefined,
axis_y2_label: {},
axis_y2_tick_format: undefined,
axis_y2_tick_outer: true,
axis_y2_tick_values: null,
axis_y2_tick_count: undefined,
axis_y2_padding: {},
axis_y2_default: undefined,
// grid
grid_x_show: false,
grid_x_type: 'tick',
grid_x_lines: [],
grid_y_show: false,
// not used
// grid_y_type: 'tick',
grid_y_lines: [],
grid_y_ticks: 10,
grid_focus_show: true,
grid_lines_front: true,
// point - point of each data
point_show: true,
point_r: 2.5,
point_focus_expand_enabled: true,
point_focus_expand_r: undefined,
point_select_r: undefined,
// line
line_connectNull: false,
line_step_type: 'step',
// bar
bar_width: undefined,
bar_width_ratio: 0.6,
bar_width_max: undefined,
bar_zerobased: true,
// area
area_zerobased: true,
// pie
pie_label_show: true,
pie_label_format: undefined,
pie_label_threshold: 0.05,
pie_expand: true,
// gauge
gauge_label_show: true,
gauge_label_format: undefined,
gauge_expand: true,
gauge_min: 0,
gauge_max: 100,
gauge_units: undefined,
gauge_width: undefined,
// donut
donut_label_show: true,
donut_label_format: undefined,
donut_label_threshold: 0.05,
donut_width: undefined,
donut_expand: true,
donut_title: "",
// region - region to change style
regions: [],
// tooltip - show when mouseover on each data
tooltip_show: true,
tooltip_grouped: true,
tooltip_format_title: undefined,
tooltip_format_name: undefined,
tooltip_format_value: undefined,
tooltip_position: undefined,
tooltip_contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
return this.getTooltipContent ? this.getTooltipContent(d, defaultTitleFormat, defaultValueFormat, color) : '';
},
tooltip_init_show: false,
tooltip_init_x: 0,
tooltip_init_position: {top: '0px', left: '50px'}
};
Object.keys(this.additionalConfig).forEach(function (key) {
config[key] = this.additionalConfig[key];
}, this);
return config;
};
c3_chart_internal_fn.additionalConfig = {};
c3_chart_internal_fn.loadConfig = function (config) {
var this_config = this.config, target, keys, read;
function find() {
var key = keys.shift();
// console.log("key =>", key, ", target =>", target);
if (key && target && typeof target === 'object' && key in target) {
target = target[key];
return find();
}
else if (!key) {
return target;
}
else {
return undefined;
}
}
Object.keys(this_config).forEach(function (key) {
target = config;
keys = key.split('_');
read = find();
// console.log("CONFIG : ", key, read);
if (isDefined(read)) {
this_config[key] = read;
}
});
};
c3_chart_internal_fn.getScale = function (min, max, forTimeseries) {
return (forTimeseries ? this.d3.time.scale() : this.d3.scale.linear()).range([min, max]);
};
c3_chart_internal_fn.getX = function (min, max, domain, offset) {
var $$ = this,
scale = $$.getScale(min, max, $$.isTimeSeries()),
_scale = domain ? scale.domain(domain) : scale, key;
// Define customized scale if categorized axis
if ($$.isCategorized()) {
offset = offset || function () { return 0; };
scale = function (d, raw) {
var v = _scale(d) + offset(d);
return raw ? v : Math.ceil(v);
};
} else {
scale = function (d, raw) {
var v = _scale(d);
return raw ? v : Math.ceil(v);
};
}
// define functions
for (key in _scale) {
scale[key] = _scale[key];
}
scale.orgDomain = function () {
return _scale.domain();
};
// define custom domain() for categorized axis
if ($$.isCategorized()) {
scale.domain = function (domain) {
if (!arguments.length) {
domain = this.orgDomain();
return [domain[0], domain[1] + 1];
}
_scale.domain(domain);
return scale;
};
}
return scale;
};
c3_chart_internal_fn.getY = function (min, max, domain) {
var scale = this.getScale(min, max, this.isTimeSeriesY());
if (domain) { scale.domain(domain); }
return scale;
};
c3_chart_internal_fn.getYScale = function (id) {
return this.axis.getId(id) === 'y2' ? this.y2 : this.y;
};
c3_chart_internal_fn.getSubYScale = function (id) {
return this.axis.getId(id) === 'y2' ? this.subY2 : this.subY;
};
c3_chart_internal_fn.updateScales = function () {
var $$ = this, config = $$.config,
forInit = !$$.x;
// update edges
$$.xMin = config.axis_rotated ? 1 : 0;
$$.xMax = config.axis_rotated ? $$.height : $$.width;
$$.yMin = config.axis_rotated ? 0 : $$.height;
$$.yMax = config.axis_rotated ? $$.width : 1;
$$.subXMin = $$.xMin;
$$.subXMax = $$.xMax;
$$.subYMin = config.axis_rotated ? 0 : $$.height2;
$$.subYMax = config.axis_rotated ? $$.width2 : 1;
// update scales
$$.x = $$.getX($$.xMin, $$.xMax, forInit ? undefined : $$.x.orgDomain(), function () { return $$.xAxis.tickOffset(); });
$$.y = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y_default : $$.y.domain());
$$.y2 = $$.getY($$.yMin, $$.yMax, forInit ? config.axis_y2_default : $$.y2.domain());
$$.subX = $$.getX($$.xMin, $$.xMax, $$.orgXDomain, function (d) { return d % 1 ? 0 : $$.subXAxis.tickOffset(); });
$$.subY = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y_default : $$.subY.domain());
$$.subY2 = $$.getY($$.subYMin, $$.subYMax, forInit ? config.axis_y2_default : $$.subY2.domain());
// update axes
$$.xAxisTickFormat = $$.axis.getXAxisTickFormat();
$$.xAxisTickValues = $$.axis.getXAxisTickValues();
$$.yAxisTickValues = $$.axis.getYAxisTickValues();
$$.y2AxisTickValues = $$.axis.getY2AxisTickValues();
$$.xAxis = $$.axis.getXAxis($$.x, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
$$.subXAxis = $$.axis.getXAxis($$.subX, $$.subXOrient, $$.xAxisTickFormat, $$.xAxisTickValues, config.axis_x_tick_outer);
$$.yAxis = $$.axis.getYAxis($$.y, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, config.axis_y_tick_outer);
$$.y2Axis = $$.axis.getYAxis($$.y2, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, config.axis_y2_tick_outer);
// Set initialized scales to brush and zoom
if (!forInit) {
if ($$.brush) { $$.brush.scale($$.subX); }
if (config.zoom_enabled) { $$.zoom.scale($$.x); }
}
// update for arc
if ($$.updateArc) { $$.updateArc(); }
};
c3_chart_internal_fn.getYDomainMin = function (targets) {
var $$ = this, config = $$.config,
ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
j, k, baseId, idsInGroup, id, hasNegativeValue;
if (config.data_groups.length > 0) {
hasNegativeValue = $$.hasNegativeValueInTargets(targets);
for (j = 0; j < config.data_groups.length; j++) {
// Determine baseId
idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
if (idsInGroup.length === 0) { continue; }
baseId = idsInGroup[0];
// Consider negative values
if (hasNegativeValue && ys[baseId]) {
ys[baseId].forEach(function (v, i) {
ys[baseId][i] = v < 0 ? v : 0;
});
}
// Compute min
for (k = 1; k < idsInGroup.length; k++) {
id = idsInGroup[k];
if (! ys[id]) { continue; }
ys[id].forEach(function (v, i) {
if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) {
ys[baseId][i] += +v;
}
});
}
}
}
return $$.d3.min(Object.keys(ys).map(function (key) { return $$.d3.min(ys[key]); }));
};
c3_chart_internal_fn.getYDomainMax = function (targets) {
var $$ = this, config = $$.config,
ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets),
j, k, baseId, idsInGroup, id, hasPositiveValue;
if (config.data_groups.length > 0) {
hasPositiveValue = $$.hasPositiveValueInTargets(targets);
for (j = 0; j < config.data_groups.length; j++) {
// Determine baseId
idsInGroup = config.data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; });
if (idsInGroup.length === 0) { continue; }
baseId = idsInGroup[0];
// Consider positive values
if (hasPositiveValue && ys[baseId]) {
ys[baseId].forEach(function (v, i) {
ys[baseId][i] = v > 0 ? v : 0;
});
}
// Compute max
for (k = 1; k < idsInGroup.length; k++) {
id = idsInGroup[k];
if (! ys[id]) { continue; }
ys[id].forEach(function (v, i) {
if ($$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) {
ys[baseId][i] += +v;
}
});
}
}
}
return $$.d3.max(Object.keys(ys).map(function (key) { return $$.d3.max(ys[key]); }));
};
c3_chart_internal_fn.getYDomain = function (targets, axisId, xDomain) {
var $$ = this, config = $$.config,
targetsByAxisId = targets.filter(function (t) { return $$.axis.getId(t.id) === axisId; }),
yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId,
yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min,
yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max,
yDomainMin = $$.getYDomainMin(yTargets),
yDomainMax = $$.getYDomainMax(yTargets),
domain, domainLength, padding, padding_top, padding_bottom,
center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center,
yDomainAbs, lengths, diff, ratio, isAllPositive, isAllNegative,
isZeroBased = ($$.hasType('bar', yTargets) && config.bar_zerobased) || ($$.hasType('area', yTargets) && config.area_zerobased),
isInverted = axisId === 'y2' ? config.axis_y2_inverted : config.axis_y_inverted,
showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated,
showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated;
// MEMO: avoid inverting domain unexpectedly
yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? (yDomainMin < yMax ? yDomainMin : yMax - 10) : yDomainMin;
yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? (yMin < yDomainMax ? yDomainMax : yMin + 10) : yDomainMax;
if (yTargets.length === 0) { // use current domain if target of axisId is none
return axisId === 'y2' ? $$.y2.domain() : $$.y.domain();
}
if (isNaN(yDomainMin)) { // set minimum to zero when not number
yDomainMin = 0;
}
if (isNaN(yDomainMax)) { // set maximum to have same value as yDomainMin
yDomainMax = yDomainMin;
}
if (yDomainMin === yDomainMax) {
yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0;
}
isAllPositive = yDomainMin >= 0 && yDomainMax >= 0;
isAllNegative = yDomainMin <= 0 && yDomainMax <= 0;
// Cancel zerobased if axis_*_min / axis_*_max specified
if ((isValue(yMin) && isAllPositive) || (isValue(yMax) && isAllNegative)) {
isZeroBased = false;
}
// Bar/Area chart should be 0-based if all positive|negative
if (isZeroBased) {
if (isAllPositive) { yDomainMin = 0; }
if (isAllNegative) { yDomainMax = 0; }
}
domainLength = Math.abs(yDomainMax - yDomainMin);
padding = padding_top = padding_bottom = domainLength * 0.1;
if (typeof center !== 'undefined') {
yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax));
yDomainMax = center + yDomainAbs;
yDomainMin = center - yDomainAbs;
}
// add padding for data label
if (showHorizontalDataLabel) {
lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'width');
diff = diffDomain($$.y.range());
ratio = [lengths[0] / diff, lengths[1] / diff];
padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1]));
padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1]));
} else if (showVerticalDataLabel) {
lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'height');
padding_top += $$.axis.convertPixelsToAxisPadding(lengths[1], domainLength);
padding_bottom += $$.axis.convertPixelsToAxisPadding(lengths[0], domainLength);
}
if (axisId === 'y' && notEmpty(config.axis_y_padding)) {
padding_top = $$.axis.getPadding(config.axis_y_padding, 'top', padding_top, domainLength);
padding_bottom = $$.axis.getPadding(config.axis_y_padding, 'bottom', padding_bottom, domainLength);
}
if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) {
padding_top = $$.axis.getPadding(config.axis_y2_padding, 'top', padding_top, domainLength);
padding_bottom = $$.axis.getPadding(config.axis_y2_padding, 'bottom', padding_bottom, domainLength);
}
// Bar/Area chart should be 0-based if all positive|negative
if (isZeroBased) {
if (isAllPositive) { padding_bottom = yDomainMin; }
if (isAllNegative) { padding_top = -yDomainMax; }
}
domain = [yDomainMin - padding_bottom, yDomainMax + padding_top];
return isInverted ? domain.reverse() : domain;
};
c3_chart_internal_fn.getXDomainMin = function (targets) {
var $$ = this, config = $$.config;
return isDefined(config.axis_x_min) ?
($$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min) :
$$.d3.min(targets, function (t) { return $$.d3.min(t.values, function (v) { return v.x; }); });
};
c3_chart_internal_fn.getXDomainMax = function (targets) {
var $$ = this, config = $$.config;
return isDefined(config.axis_x_max) ?
($$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max) :
$$.d3.max(targets, function (t) { return $$.d3.max(t.values, function (v) { return v.x; }); });
};
c3_chart_internal_fn.getXDomainPadding = function (domain) {
var $$ = this, config = $$.config,
diff = domain[1] - domain[0],
maxDataCount, padding, paddingLeft, paddingRight;
if ($$.isCategorized()) {
padding = 0;
} else if ($$.hasType('bar')) {
maxDataCount = $$.getMaxDataCount();
padding = maxDataCount > 1 ? (diff / (maxDataCount - 1)) / 2 : 0.5;
} else {
padding = diff * 0.01;
}
if (typeof config.axis_x_padding === 'object' && notEmpty(config.axis_x_padding)) {
paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding;
paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding;
} else if (typeof config.axis_x_padding === 'number') {
paddingLeft = paddingRight = config.axis_x_padding;
} else {
paddingLeft = paddingRight = padding;
}
return {left: paddingLeft, right: paddingRight};
};
c3_chart_internal_fn.getXDomain = function (targets) {
var $$ = this,
xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)],
firstX = xDomain[0], lastX = xDomain[1],
padding = $$.getXDomainPadding(xDomain),
min = 0, max = 0;
// show center of x domain if min and max are the same
if ((firstX - lastX) === 0 && !$$.isCategorized()) {
if ($$.isTimeSeries()) {
firstX = new Date(firstX.getTime() * 0.5);
lastX = new Date(lastX.getTime() * 1.5);
} else {
firstX = firstX === 0 ? 1 : (firstX * 0.5);
lastX = lastX === 0 ? -1 : (lastX * 1.5);
}
}
if (firstX || firstX === 0) {
min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left;
}
if (lastX || lastX === 0) {
max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right;
}
return [min, max];
};
c3_chart_internal_fn.updateXDomain = function (targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain) {
var $$ = this, config = $$.config;
if (withUpdateOrgXDomain) {
$$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets)));
$$.orgXDomain = $$.x.domain();
if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); }
$$.subX.domain($$.x.domain());
if ($$.brush) { $$.brush.scale($$.subX); }
}
if (withUpdateXDomain) {
$$.x.domain(domain ? domain : (!$$.brush || $$.brush.empty()) ? $$.orgXDomain : $$.brush.extent());
if (config.zoom_enabled) { $$.zoom.scale($$.x).updateScaleExtent(); }
}
// Trim domain when too big by zoom mousemove event
if (withTrim) { $$.x.domain($$.trimXDomain($$.x.orgDomain())); }
return $$.x.domain();
};
c3_chart_internal_fn.trimXDomain = function (domain) {
var $$ = this;
if (domain[0] <= $$.orgXDomain[0]) {
domain[1] = +domain[1] + ($$.orgXDomain[0] - domain[0]);
domain[0] = $$.orgXDomain[0];
}
if ($$.orgXDomain[1] <= domain[1]) {
domain[0] = +domain[0] - (domain[1] - $$.orgXDomain[1]);
domain[1] = $$.orgXDomain[1];
}
return domain;
};
c3_chart_internal_fn.isX = function (key) {
var $$ = this, config = $$.config;
return (config.data_x && key === config.data_x) || (notEmpty(config.data_xs) && hasValue(config.data_xs, key));
};
c3_chart_internal_fn.isNotX = function (key) {
return !this.isX(key);
};
c3_chart_internal_fn.getXKey = function (id) {
var $$ = this, config = $$.config;
return config.data_x ? config.data_x : notEmpty(config.data_xs) ? config.data_xs[id] : null;
};
c3_chart_internal_fn.getXValuesOfXKey = function (key, targets) {
var $$ = this,
xValues, ids = targets && notEmpty(targets) ? $$.mapToIds(targets) : [];
ids.forEach(function (id) {
if ($$.getXKey(id) === key) {
xValues = $$.data.xs[id];
}
});
return xValues;
};
c3_chart_internal_fn.getIndexByX = function (x) {
var $$ = this,
data = $$.filterByX($$.data.targets, x);
return data.length ? data[0].index : null;
};
c3_chart_internal_fn.getXValue = function (id, i) {
var $$ = this;
return id in $$.data.xs && $$.data.xs[id] && isValue($$.data.xs[id][i]) ? $$.data.xs[id][i] : i;
};
c3_chart_internal_fn.getOtherTargetXs = function () {
var $$ = this,
idsForX = Object.keys($$.data.xs);
return idsForX.length ? $$.data.xs[idsForX[0]] : null;
};
c3_chart_internal_fn.getOtherTargetX = function (index) {
var xs = this.getOtherTargetXs();
return xs && index < xs.length ? xs[index] : null;
};
c3_chart_internal_fn.addXs = function (xs) {
var $$ = this;
Object.keys(xs).forEach(function (id) {
$$.config.data_xs[id] = xs[id];
});
};
c3_chart_internal_fn.hasMultipleX = function (xs) {
return this.d3.set(Object.keys(xs).map(function (id) { return xs[id]; })).size() > 1;
};
c3_chart_internal_fn.isMultipleX = function () {
return notEmpty(this.config.data_xs) || !this.config.data_xSort || this.hasType('scatter');
};
c3_chart_internal_fn.addName = function (data) {
var $$ = this, name;
if (data) {
name = $$.config.data_names[data.id];
data.name = name ? name : data.id;
}
return data;
};
c3_chart_internal_fn.getValueOnIndex = function (values, index) {
var valueOnIndex = values.filter(function (v) { return v.index === index; });
return valueOnIndex.length ? valueOnIndex[0] : null;
};
c3_chart_internal_fn.updateTargetX = function (targets, x) {
var $$ = this;
targets.forEach(function (t) {
t.values.forEach(function (v, i) {
v.x = $$.generateTargetX(x[i], t.id, i);
});
$$.data.xs[t.id] = x;
});
};
c3_chart_internal_fn.updateTargetXs = function (targets, xs) {
var $$ = this;
targets.forEach(function (t) {
if (xs[t.id]) {
$$.updateTargetX([t], xs[t.id]);
}
});
};
c3_chart_internal_fn.generateTargetX = function (rawX, id, index) {
var $$ = this, x;
if ($$.isTimeSeries()) {
x = rawX ? $$.parseDate(rawX) : $$.parseDate($$.getXValue(id, index));
}
else if ($$.isCustomX() && !$$.isCategorized()) {
x = isValue(rawX) ? +rawX : $$.getXValue(id, index);
}
else {
x = index;
}
return x;
};
c3_chart_internal_fn.cloneTarget = function (target) {
return {
id : target.id,
id_org : target.id_org,
values : target.values.map(function (d) {
return {x: d.x, value: d.value, id: d.id};
})
};
};
c3_chart_internal_fn.updateXs = function () {
var $$ = this;
if ($$.data.targets.length) {
$$.xs = [];
$$.data.targets[0].values.forEach(function (v) {
$$.xs[v.index] = v.x;
});
}
};
c3_chart_internal_fn.getPrevX = function (i) {
var x = this.xs[i - 1];
return typeof x !== 'undefined' ? x : null;
};
c3_chart_internal_fn.getNextX = function (i) {
var x = this.xs[i + 1];
return typeof x !== 'undefined' ? x : null;
};
c3_chart_internal_fn.getMaxDataCount = function () {
var $$ = this;
return $$.d3.max($$.data.targets, function (t) { return t.values.length; });
};
c3_chart_internal_fn.getMaxDataCountTarget = function (targets) {
var length = targets.length, max = 0, maxTarget;
if (length > 1) {
targets.forEach(function (t) {
if (t.values.length > max) {
maxTarget = t;
max = t.values.length;
}
});
} else {
maxTarget = length ? targets[0] : null;
}
return maxTarget;
};
c3_chart_internal_fn.getEdgeX = function (targets) {
var $$ = this;
return !targets.length ? [0, 0] : [
$$.d3.min(targets, function (t) { return t.values[0].x; }),
$$.d3.max(targets, function (t) { return t.values[t.values.length - 1].x; })
];
};
c3_chart_internal_fn.mapToIds = function (targets) {
return targets.map(function (d) { return d.id; });
};
c3_chart_internal_fn.mapToTargetIds = function (ids) {
var $$ = this;
return ids ? (isString(ids) ? [ids] : ids) : $$.mapToIds($$.data.targets);
};
c3_chart_internal_fn.hasTarget = function (targets, id) {
var ids = this.mapToIds(targets), i;
for (i = 0; i < ids.length; i++) {
if (ids[i] === id) {
return true;
}
}
return false;
};
c3_chart_internal_fn.isTargetToShow = function (targetId) {
return this.hiddenTargetIds.indexOf(targetId) < 0;
};
c3_chart_internal_fn.isLegendToShow = function (targetId) {
return this.hiddenLegendIds.indexOf(targetId) < 0;
};
c3_chart_internal_fn.filterTargetsToShow = function (targets) {
var $$ = this;
return targets.filter(function (t) { return $$.isTargetToShow(t.id); });
};
c3_chart_internal_fn.mapTargetsToUniqueXs = function (targets) {
var $$ = this;
var xs = $$.d3.set($$.d3.merge(targets.map(function (t) { return t.values.map(function (v) { return +v.x; }); }))).values();
return $$.isTimeSeries() ? xs.map(function (x) { return new Date(+x); }) : xs.map(function (x) { return +x; });
};
c3_chart_internal_fn.addHiddenTargetIds = function (targetIds) {
this.hiddenTargetIds = this.hiddenTargetIds.concat(targetIds);
};
c3_chart_internal_fn.removeHiddenTargetIds = function (targetIds) {
this.hiddenTargetIds = this.hiddenTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; });
};
c3_chart_internal_fn.addHiddenLegendIds = function (targetIds) {
this.hiddenLegendIds = this.hiddenLegendIds.concat(targetIds);
};
c3_chart_internal_fn.removeHiddenLegendIds = function (targetIds) {
this.hiddenLegendIds = this.hiddenLegendIds.filter(function (id) { return targetIds.indexOf(id) < 0; });
};
c3_chart_internal_fn.getValuesAsIdKeyed = function (targets) {
var ys = {};
targets.forEach(function (t) {
ys[t.id] = [];
t.values.forEach(function (v) {
ys[t.id].push(v.value);
});
});
return ys;
};
c3_chart_internal_fn.checkValueInTargets = function (targets, checker) {
var ids = Object.keys(targets), i, j, values;
for (i = 0; i < ids.length; i++) {
values = targets[ids[i]].values;
for (j = 0; j < values.length; j++) {
if (checker(values[j].value)) {
return true;
}
}
}
return false;
};
c3_chart_internal_fn.hasNegativeValueInTargets = function (targets) {
return this.checkValueInTargets(targets, function (v) { return v < 0; });
};
c3_chart_internal_fn.hasPositiveValueInTargets = function (targets) {
return this.checkValueInTargets(targets, function (v) { return v > 0; });
};
c3_chart_internal_fn.isOrderDesc = function () {
var config = this.config;
return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'desc';
};
c3_chart_internal_fn.isOrderAsc = function () {
var config = this.config;
return typeof(config.data_order) === 'string' && config.data_order.toLowerCase() === 'asc';
};
c3_chart_internal_fn.orderTargets = function (targets) {
var $$ = this, config = $$.config, orderAsc = $$.isOrderAsc(), orderDesc = $$.isOrderDesc();
if (orderAsc || orderDesc) {
targets.sort(function (t1, t2) {
var reducer = function (p, c) { return p + Math.abs(c.value); };
var t1Sum = t1.values.reduce(reducer, 0),
t2Sum = t2.values.reduce(reducer, 0);
return orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum;
});
} else if (isFunction(config.data_order)) {
targets.sort(config.data_order);
} // TODO: accept name array for order
return targets;
};
c3_chart_internal_fn.filterByX = function (targets, x) {
return this.d3.merge(targets.map(function (t) { return t.values; })).filter(function (v) { return v.x - x === 0; });
};
c3_chart_internal_fn.filterRemoveNull = function (data) {
return data.filter(function (d) { return isValue(d.value); });
};
c3_chart_internal_fn.filterByXDomain = function (targets, xDomain) {
return targets.map(function (t) {
return {
id: t.id,
id_org: t.id_org,
values: t.values.filter(function (v) {
return xDomain[0] <= v.x && v.x <= xDomain[1];
})
};
});
};
c3_chart_internal_fn.hasDataLabel = function () {
var config = this.config;
if (typeof config.data_labels === 'boolean' && config.data_labels) {
return true;
} else if (typeof config.data_labels === 'object' && notEmpty(config.data_labels)) {
return true;
}
return false;
};
c3_chart_internal_fn.getDataLabelLength = function (min, max, key) {
var $$ = this,
lengths = [0, 0], paddingCoef = 1.3;
$$.selectChart.select('svg').selectAll('.dummy')
.data([min, max])
.enter().append('text')
.text(function (d) { return $$.dataLabelFormat(d.id)(d); })
.each(function (d, i) {
lengths[i] = this.getBoundingClientRect()[key] * paddingCoef;
})
.remove();
return lengths;
};
c3_chart_internal_fn.isNoneArc = function (d) {
return this.hasTarget(this.data.targets, d.id);
},
c3_chart_internal_fn.isArc = function (d) {
return 'data' in d && this.hasTarget(this.data.targets, d.data.id);
};
c3_chart_internal_fn.findSameXOfValues = function (values, index) {
var i, targetX = values[index].x, sames = [];
for (i = index - 1; i >= 0; i--) {
if (targetX !== values[i].x) { break; }
sames.push(values[i]);
}
for (i = index; i < values.length; i++) {
if (targetX !== values[i].x) { break; }
sames.push(values[i]);
}
return sames;
};
c3_chart_internal_fn.findClosestFromTargets = function (targets, pos) {
var $$ = this, candidates;
// map to array of closest points of each target
candidates = targets.map(function (target) {
return $$.findClosest(target.values, pos);
});
// decide closest point and return
return $$.findClosest(candidates, pos);
};
c3_chart_internal_fn.findClosest = function (values, pos) {
var $$ = this, minDist = 100, closest;
// find mouseovering bar
values.filter(function (v) { return v && $$.isBarType(v.id); }).forEach(function (v) {
var shape = $$.main.select('.' + CLASS.bars + $$.getTargetSelectorSuffix(v.id) + ' .' + CLASS.bar + '-' + v.index).node();
if (!closest && $$.isWithinBar(shape)) {
closest = v;
}
});
// find closest point from non-bar
values.filter(function (v) { return v && !$$.isBarType(v.id); }).forEach(function (v) {
var d = $$.dist(v, pos);
if (d < minDist) {
minDist = d;
closest = v;
}
});
return closest;
};
c3_chart_internal_fn.dist = function (data, pos) {
var $$ = this, config = $$.config,
xIndex = config.axis_rotated ? 1 : 0,
yIndex = config.axis_rotated ? 0 : 1,
y = $$.circleY(data, data.index),
x = $$.x(data.x);
return Math.pow(x - pos[xIndex], 2) + Math.pow(y - pos[yIndex], 2);
};
c3_chart_internal_fn.convertValuesToStep = function (values) {
var converted = [].concat(values), i;
if (!this.isCategorized()) {
return values;
}
for (i = values.length + 1; 0 < i; i--) {
converted[i] = converted[i - 1];
}
converted[0] = {
x: converted[0].x - 1,
value: converted[0].value,
id: converted[0].id
};
converted[values.length + 1] = {
x: converted[values.length].x + 1,
value: converted[values.length].value,
id: converted[values.length].id
};
return converted;
};
c3_chart_internal_fn.updateDataAttributes = function (name, attrs) {
var $$ = this, config = $$.config, current = config['data_' + name];
if (typeof attrs === 'undefined') { return current; }
Object.keys(attrs).forEach(function (id) {
current[id] = attrs[id];
});
$$.redraw({withLegend: true});
return current;
};
c3_chart_internal_fn.convertUrlToData = function (url, mimeType, keys, done) {
var $$ = this, type = mimeType ? mimeType : 'csv';
$$.d3.xhr(url, function (error, data) {
var d;
if (!data) {
throw new Error(error.responseURL + ' ' + error.status + ' (' + error.statusText + ')');
}
if (type === 'json') {
d = $$.convertJsonToData(JSON.parse(data.response), keys);
} else if (type === 'tsv') {
d = $$.convertTsvToData(data.response);
} else {
d = $$.convertCsvToData(data.response);
}
done.call($$, d);
});
};
c3_chart_internal_fn.convertXsvToData = function (xsv, parser) {
var rows = parser.parseRows(xsv), d;
if (rows.length === 1) {
d = [{}];
rows[0].forEach(function (id) {
d[0][id] = null;
});
} else {
d = parser.parse(xsv);
}
return d;
};
c3_chart_internal_fn.convertCsvToData = function (csv) {
return this.convertXsvToData(csv, this.d3.csv);
};
c3_chart_internal_fn.convertTsvToData = function (tsv) {
return this.convertXsvToData(tsv, this.d3.tsv);
};
c3_chart_internal_fn.convertJsonToData = function (json, keys) {
var $$ = this,
new_rows = [], targetKeys, data;
if (keys) { // when keys specified, json would be an array that includes objects
if (keys.x) {
targetKeys = keys.value.concat(keys.x);
$$.config.data_x = keys.x;
} else {
targetKeys = keys.value;
}
new_rows.push(targetKeys);
json.forEach(function (o) {
var new_row = [];
targetKeys.forEach(function (key) {
// convert undefined to null because undefined data will be removed in convertDataToTargets()
var v = isUndefined(o[key]) ? null : o[key];
new_row.push(v);
});
new_rows.push(new_row);
});
data = $$.convertRowsToData(new_rows);
} else {
Object.keys(json).forEach(function (key) {
new_rows.push([key].concat(json[key]));
});
data = $$.convertColumnsToData(new_rows);
}
return data;
};
c3_chart_internal_fn.convertRowsToData = function (rows) {
var keys = rows[0], new_row = {}, new_rows = [], i, j;
for (i = 1; i < rows.length; i++) {
new_row = {};
for (j = 0; j < rows[i].length; j++) {
if (isUndefined(rows[i][j])) {
throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
}
new_row[keys[j]] = rows[i][j];
}
new_rows.push(new_row);
}
return new_rows;
};
c3_chart_internal_fn.convertColumnsToData = function (columns) {
var new_rows = [], i, j, key;
for (i = 0; i < columns.length; i++) {
key = columns[i][0];
for (j = 1; j < columns[i].length; j++) {
if (isUndefined(new_rows[j - 1])) {
new_rows[j - 1] = {};
}
if (isUndefined(columns[i][j])) {
throw new Error("Source data is missing a component at (" + i + "," + j + ")!");
}
new_rows[j - 1][key] = columns[i][j];
}
}
return new_rows;
};
c3_chart_internal_fn.convertDataToTargets = function (data, appendXs) {
var $$ = this, config = $$.config,
ids = $$.d3.keys(data[0]).filter($$.isNotX, $$),
xs = $$.d3.keys(data[0]).filter($$.isX, $$),
targets;
// save x for update data by load when custom x and c3.x API
ids.forEach(function (id) {
var xKey = $$.getXKey(id);
if ($$.isCustomX() || $$.isTimeSeries()) {
// if included in input data
if (xs.indexOf(xKey) >= 0) {
$$.data.xs[id] = (appendXs && $$.data.xs[id] ? $$.data.xs[id] : []).concat(
data.map(function (d) { return d[xKey]; })
.filter(isValue)
.map(function (rawX, i) { return $$.generateTargetX(rawX, id, i); })
);
}
// if not included in input data, find from preloaded data of other id's x
else if (config.data_x) {
$$.data.xs[id] = $$.getOtherTargetXs();
}
// if not included in input data, find from preloaded data
else if (notEmpty(config.data_xs)) {
$$.data.xs[id] = $$.getXValuesOfXKey(xKey, $$.data.targets);
}
// MEMO: if no x included, use same x of current will be used
} else {
$$.data.xs[id] = data.map(function (d, i) { return i; });
}
});
// check x is defined
ids.forEach(function (id) {
if (!$$.data.xs[id]) {
throw new Error('x is not defined for id = "' + id + '".');
}
});
// convert to target
targets = ids.map(function (id, index) {
var convertedId = config.data_idConverter(id);
return {
id: convertedId,
id_org: id,
values: data.map(function (d, i) {
var xKey = $$.getXKey(id), rawX = d[xKey], x = $$.generateTargetX(rawX, id, i);
// use x as categories if custom x and categorized
if ($$.isCustomX() && $$.isCategorized() && index === 0 && rawX) {
if (i === 0) { config.axis_x_categories = []; }
config.axis_x_categories.push(rawX);
}
// mark as x = undefined if value is undefined and filter to remove after mapped
if (isUndefined(d[id]) || $$.data.xs[id].length <= i) {
x = undefined;
}
return {x: x, value: d[id] !== null && !isNaN(d[id]) ? +d[id] : null, id: convertedId};
}).filter(function (v) { return isDefined(v.x); })
};
});
// finish targets
targets.forEach(function (t) {
var i;
// sort values by its x
if (config.data_xSort) {
t.values = t.values.sort(function (v1, v2) {
var x1 = v1.x || v1.x === 0 ? v1.x : Infinity,
x2 = v2.x || v2.x === 0 ? v2.x : Infinity;
return x1 - x2;
});
}
// indexing each value
i = 0;
t.values.forEach(function (v) {
v.index = i++;
});
// this needs to be sorted because its index and value.index is identical
$$.data.xs[t.id].sort(function (v1, v2) {
return v1 - v2;
});
});
// set target types
if (config.data_type) {
$$.setTargetType($$.mapToIds(targets).filter(function (id) { return ! (id in config.data_types); }), config.data_type);
}
// cache as original id keyed
targets.forEach(function (d) {
$$.addCache(d.id_org, d);
});
return targets;
};
c3_chart_internal_fn.load = function (targets, args) {
var $$ = this;
if (targets) {
// filter loading targets if needed
if (args.filter) {
targets = targets.filter(args.filter);
}
// set type if args.types || args.type specified
if (args.type || args.types) {
targets.forEach(function (t) {
var type = args.types && args.types[t.id] ? args.types[t.id] : args.type;
$$.setTargetType(t.id, type);
});
}
// Update/Add data
$$.data.targets.forEach(function (d) {
for (var i = 0; i < targets.length; i++) {
if (d.id === targets[i].id) {
d.values = targets[i].values;
targets.splice(i, 1);
break;
}
}
});
$$.data.targets = $$.data.targets.concat(targets); // add remained
}
// Set targets
$$.updateTargets($$.data.targets);
// Redraw with new targets
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
if (args.done) { args.done(); }
};
c3_chart_internal_fn.loadFromArgs = function (args) {
var $$ = this;
if (args.data) {
$$.load($$.convertDataToTargets(args.data), args);
}
else if (args.url) {
$$.convertUrlToData(args.url, args.mimeType, args.keys, function (data) {
$$.load($$.convertDataToTargets(data), args);
});
}
else if (args.json) {
$$.load($$.convertDataToTargets($$.convertJsonToData(args.json, args.keys)), args);
}
else if (args.rows) {
$$.load($$.convertDataToTargets($$.convertRowsToData(args.rows)), args);
}
else if (args.columns) {
$$.load($$.convertDataToTargets($$.convertColumnsToData(args.columns)), args);
}
else {
$$.load(null, args);
}
};
c3_chart_internal_fn.unload = function (targetIds, done) {
var $$ = this;
if (!done) {
done = function () {};
}
// filter existing target
targetIds = targetIds.filter(function (id) { return $$.hasTarget($$.data.targets, id); });
// If no target, call done and return
if (!targetIds || targetIds.length === 0) {
done();
return;
}
$$.svg.selectAll(targetIds.map(function (id) { return $$.selectorTarget(id); }))
.transition()
.style('opacity', 0)
.remove()
.call($$.endall, done);
targetIds.forEach(function (id) {
// Reset fadein for future load
$$.withoutFadeIn[id] = false;
// Remove target's elements
if ($$.legend) {
$$.legend.selectAll('.' + CLASS.legendItem + $$.getTargetSelectorSuffix(id)).remove();
}
// Remove target
$$.data.targets = $$.data.targets.filter(function (t) {
return t.id !== id;
});
});
};
c3_chart_internal_fn.categoryName = function (i) {
var config = this.config;
return i < config.axis_x_categories.length ? config.axis_x_categories[i] : i;
};
c3_chart_internal_fn.initEventRect = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.eventRects)
.style('fill-opacity', 0);
};
c3_chart_internal_fn.redrawEventRect = function () {
var $$ = this, config = $$.config,
eventRectUpdate, maxDataCountTarget,
isMultipleX = $$.isMultipleX();
// rects for mouseover
var eventRects = $$.main.select('.' + CLASS.eventRects)
.style('cursor', config.zoom_enabled ? config.axis_rotated ? 'ns-resize' : 'ew-resize' : null)
.classed(CLASS.eventRectsMultiple, isMultipleX)
.classed(CLASS.eventRectsSingle, !isMultipleX);
// clear old rects
eventRects.selectAll('.' + CLASS.eventRect).remove();
// open as public variable
$$.eventRect = eventRects.selectAll('.' + CLASS.eventRect);
if (isMultipleX) {
eventRectUpdate = $$.eventRect.data([0]);
// enter : only one rect will be added
$$.generateEventRectsForMultipleXs(eventRectUpdate.enter());
// update
$$.updateEventRect(eventRectUpdate);
// exit : not needed because always only one rect exists
}
else {
// Set data and update $$.eventRect
maxDataCountTarget = $$.getMaxDataCountTarget($$.data.targets);
eventRects.datum(maxDataCountTarget ? maxDataCountTarget.values : []);
$$.eventRect = eventRects.selectAll('.' + CLASS.eventRect);
eventRectUpdate = $$.eventRect.data(function (d) { return d; });
// enter
$$.generateEventRectsForSingleX(eventRectUpdate.enter());
// update
$$.updateEventRect(eventRectUpdate);
// exit
eventRectUpdate.exit().remove();
}
};
c3_chart_internal_fn.updateEventRect = function (eventRectUpdate) {
var $$ = this, config = $$.config,
x, y, w, h, rectW, rectX;
// set update selection if null
eventRectUpdate = eventRectUpdate || $$.eventRect.data(function (d) { return d; });
if ($$.isMultipleX()) {
// TODO: rotated not supported yet
x = 0;
y = 0;
w = $$.width;
h = $$.height;
}
else {
if (($$.isCustomX() || $$.isTimeSeries()) && !$$.isCategorized()) {
// update index for x that is used by prevX and nextX
$$.updateXs();
rectW = function (d) {
var prevX = $$.getPrevX(d.index), nextX = $$.getNextX(d.index);
// if there this is a single data point make the eventRect full width (or height)
if (prevX === null && nextX === null) {
return config.axis_rotated ? $$.height : $$.width;
}
if (prevX === null) { prevX = $$.x.domain()[0]; }
if (nextX === null) { nextX = $$.x.domain()[1]; }
return Math.max(0, ($$.x(nextX) - $$.x(prevX)) / 2);
};
rectX = function (d) {
var prevX = $$.getPrevX(d.index), nextX = $$.getNextX(d.index),
thisX = $$.data.xs[d.id][d.index];
// if there this is a single data point position the eventRect at 0
if (prevX === null && nextX === null) {
return 0;
}
if (prevX === null) { prevX = $$.x.domain()[0]; }
return ($$.x(thisX) + $$.x(prevX)) / 2;
};
} else {
rectW = $$.getEventRectWidth();
rectX = function (d) {
return $$.x(d.x) - (rectW / 2);
};
}
x = config.axis_rotated ? 0 : rectX;
y = config.axis_rotated ? rectX : 0;
w = config.axis_rotated ? $$.width : rectW;
h = config.axis_rotated ? rectW : $$.height;
}
eventRectUpdate
.attr('class', $$.classEvent.bind($$))
.attr("x", x)
.attr("y", y)
.attr("width", w)
.attr("height", h);
};
c3_chart_internal_fn.generateEventRectsForSingleX = function (eventRectEnter) {
var $$ = this, d3 = $$.d3, config = $$.config;
eventRectEnter.append("rect")
.attr("class", $$.classEvent.bind($$))
.style("cursor", config.data_selection_enabled && config.data_selection_grouped ? "pointer" : null)
.on('mouseover', function (d) {
var index = d.index;
if ($$.dragging || $$.flowing) { return; } // do nothing while dragging/flowing
if ($$.hasArcType()) { return; }
// Expand shapes for selection
if (config.point_focus_expand_enabled) { $$.expandCircles(index, null, true); }
$$.expandBars(index, null, true);
// Call event handler
$$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
config.data_onmouseover.call($$.api, d);
});
})
.on('mouseout', function (d) {
var index = d.index;
if (!$$.config) { return; } // chart is destroyed
if ($$.hasArcType()) { return; }
$$.hideXGridFocus();
$$.hideTooltip();
// Undo expanded shapes
$$.unexpandCircles();
$$.unexpandBars();
// Call event handler
$$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
config.data_onmouseout.call($$.api, d);
});
})
.on('mousemove', function (d) {
var selectedData, index = d.index,
eventRect = $$.svg.select('.' + CLASS.eventRect + '-' + index);
if ($$.dragging || $$.flowing) { return; } // do nothing while dragging/flowing
if ($$.hasArcType()) { return; }
if ($$.isStepType(d) && $$.config.line_step_type === 'step-after' && d3.mouse(this)[0] < $$.x($$.getXValue(d.id, index))) {
index -= 1;
}
// Show tooltip
selectedData = $$.filterTargetsToShow($$.data.targets).map(function (t) {
return $$.addName($$.getValueOnIndex(t.values, index));
});
if (config.tooltip_grouped) {
$$.showTooltip(selectedData, this);
$$.showXGridFocus(selectedData);
}
if (config.tooltip_grouped && (!config.data_selection_enabled || config.data_selection_grouped)) {
return;
}
$$.main.selectAll('.' + CLASS.shape + '-' + index)
.each(function () {
d3.select(this).classed(CLASS.EXPANDED, true);
if (config.data_selection_enabled) {
eventRect.style('cursor', config.data_selection_grouped ? 'pointer' : null);
}
if (!config.tooltip_grouped) {
$$.hideXGridFocus();
$$.hideTooltip();
if (!config.data_selection_grouped) {
$$.unexpandCircles(index);
$$.unexpandBars(index);
}
}
})
.filter(function (d) {
return $$.isWithinShape(this, d);
})
.each(function (d) {
if (config.data_selection_enabled && (config.data_selection_grouped || config.data_selection_isselectable(d))) {
eventRect.style('cursor', 'pointer');
}
if (!config.tooltip_grouped) {
$$.showTooltip([d], this);
$$.showXGridFocus([d]);
if (config.point_focus_expand_enabled) { $$.expandCircles(index, d.id, true); }
$$.expandBars(index, d.id, true);
}
});
})
.on('click', function (d) {
var index = d.index;
if ($$.hasArcType() || !$$.toggleShape) { return; }
if ($$.cancelClick) {
$$.cancelClick = false;
return;
}
if ($$.isStepType(d) && config.line_step_type === 'step-after' && d3.mouse(this)[0] < $$.x($$.getXValue(d.id, index))) {
index -= 1;
}
$$.main.selectAll('.' + CLASS.shape + '-' + index).each(function (d) {
if (config.data_selection_grouped || $$.isWithinShape(this, d)) {
$$.toggleShape(this, d, index);
$$.config.data_onclick.call($$.api, d, this);
}
});
})
.call(
config.data_selection_draggable && $$.drag ? (
d3.behavior.drag().origin(Object)
.on('drag', function () { $$.drag(d3.mouse(this)); })
.on('dragstart', function () { $$.dragstart(d3.mouse(this)); })
.on('dragend', function () { $$.dragend(); })
) : function () {}
);
};
c3_chart_internal_fn.generateEventRectsForMultipleXs = function (eventRectEnter) {
var $$ = this, d3 = $$.d3, config = $$.config;
function mouseout() {
$$.svg.select('.' + CLASS.eventRect).style('cursor', null);
$$.hideXGridFocus();
$$.hideTooltip();
$$.unexpandCircles();
$$.unexpandBars();
}
eventRectEnter.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', $$.width)
.attr('height', $$.height)
.attr('class', CLASS.eventRect)
.on('mouseout', function () {
if (!$$.config) { return; } // chart is destroyed
if ($$.hasArcType()) { return; }
mouseout();
})
.on('mousemove', function () {
var targetsToShow = $$.filterTargetsToShow($$.data.targets);
var mouse, closest, sameXData, selectedData;
if ($$.dragging) { return; } // do nothing when dragging
if ($$.hasArcType(targetsToShow)) { return; }
mouse = d3.mouse(this);
closest = $$.findClosestFromTargets(targetsToShow, mouse);
if ($$.mouseover && (!closest || closest.id !== $$.mouseover.id)) {
config.data_onmouseout.call($$.api, $$.mouseover);
$$.mouseover = undefined;
}
if (! closest) {
mouseout();
return;
}
if ($$.isScatterType(closest) || !config.tooltip_grouped) {
sameXData = [closest];
} else {
sameXData = $$.filterByX(targetsToShow, closest.x);
}
// show tooltip when cursor is close to some point
selectedData = sameXData.map(function (d) {
return $$.addName(d);
});
$$.showTooltip(selectedData, this);
// expand points
if (config.point_focus_expand_enabled) {
$$.expandCircles(closest.index, closest.id, true);
}
$$.expandBars(closest.index, closest.id, true);
// Show xgrid focus line
$$.showXGridFocus(selectedData);
// Show cursor as pointer if point is close to mouse position
if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < 100) {
$$.svg.select('.' + CLASS.eventRect).style('cursor', 'pointer');
if (!$$.mouseover) {
config.data_onmouseover.call($$.api, closest);
$$.mouseover = closest;
}
}
})
.on('click', function () {
var targetsToShow = $$.filterTargetsToShow($$.data.targets);
var mouse, closest;
if ($$.hasArcType(targetsToShow)) { return; }
mouse = d3.mouse(this);
closest = $$.findClosestFromTargets(targetsToShow, mouse);
if (! closest) { return; }
// select if selection enabled
if ($$.isBarType(closest.id) || $$.dist(closest, mouse) < 100) {
$$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(closest.id)).selectAll('.' + CLASS.shape + '-' + closest.index).each(function () {
if (config.data_selection_grouped || $$.isWithinShape(this, closest)) {
$$.toggleShape(this, closest, closest.index);
$$.config.data_onclick.call($$.api, closest, this);
}
});
}
})
.call(
config.data_selection_draggable && $$.drag ? (
d3.behavior.drag().origin(Object)
.on('drag', function () { $$.drag(d3.mouse(this)); })
.on('dragstart', function () { $$.dragstart(d3.mouse(this)); })
.on('dragend', function () { $$.dragend(); })
) : function () {}
);
};
c3_chart_internal_fn.dispatchEvent = function (type, index, mouse) {
var $$ = this,
selector = '.' + CLASS.eventRect + (!$$.isMultipleX() ? '-' + index : ''),
eventRect = $$.main.select(selector).node(),
box = eventRect.getBoundingClientRect(),
x = box.left + (mouse ? mouse[0] : 0),
y = box.top + (mouse ? mouse[1] : 0),
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, window, 0, x, y, x, y,
false, false, false, false, 0, null);
eventRect.dispatchEvent(event);
};
c3_chart_internal_fn.getCurrentWidth = function () {
var $$ = this, config = $$.config;
return config.size_width ? config.size_width : $$.getParentWidth();
};
c3_chart_internal_fn.getCurrentHeight = function () {
var $$ = this, config = $$.config,
h = config.size_height ? config.size_height : $$.getParentHeight();
return h > 0 ? h : 320 / ($$.hasType('gauge') ? 2 : 1);
};
c3_chart_internal_fn.getCurrentPaddingTop = function () {
var config = this.config;
return isValue(config.padding_top) ? config.padding_top : 0;
};
c3_chart_internal_fn.getCurrentPaddingBottom = function () {
var config = this.config;
return isValue(config.padding_bottom) ? config.padding_bottom : 0;
};
c3_chart_internal_fn.getCurrentPaddingLeft = function (withoutRecompute) {
var $$ = this, config = $$.config;
if (isValue(config.padding_left)) {
return config.padding_left;
} else if (config.axis_rotated) {
return !config.axis_x_show ? 1 : Math.max(ceil10($$.getAxisWidthByAxisId('x', withoutRecompute)), 40);
} else if (!config.axis_y_show || config.axis_y_inner) { // && !config.axis_rotated
return $$.axis.getYAxisLabelPosition().isOuter ? 30 : 1;
} else {
return ceil10($$.getAxisWidthByAxisId('y', withoutRecompute));
}
};
c3_chart_internal_fn.getCurrentPaddingRight = function () {
var $$ = this, config = $$.config,
defaultPadding = 10, legendWidthOnRight = $$.isLegendRight ? $$.getLegendWidth() + 20 : 0;
if (isValue(config.padding_right)) {
return config.padding_right + 1; // 1 is needed not to hide tick line
} else if (config.axis_rotated) {
return defaultPadding + legendWidthOnRight;
} else if (!config.axis_y2_show || config.axis_y2_inner) { // && !config.axis_rotated
return 2 + legendWidthOnRight + ($$.axis.getY2AxisLabelPosition().isOuter ? 20 : 0);
} else {
return ceil10($$.getAxisWidthByAxisId('y2')) + legendWidthOnRight;
}
};
c3_chart_internal_fn.getParentRectValue = function (key) {
var parent = this.selectChart.node(), v;
while (parent && parent.tagName !== 'BODY') {
try {
v = parent.getBoundingClientRect()[key];
} catch(e) {
if (key === 'width') {
// In IE in certain cases getBoundingClientRect
// will cause an "unspecified error"
v = parent.offsetWidth;
}
}
if (v) {
break;
}
parent = parent.parentNode;
}
return v;
};
c3_chart_internal_fn.getParentWidth = function () {
return this.getParentRectValue('width');
};
c3_chart_internal_fn.getParentHeight = function () {
var h = this.selectChart.style('height');
return h.indexOf('px') > 0 ? +h.replace('px', '') : 0;
};
c3_chart_internal_fn.getSvgLeft = function (withoutRecompute) {
var $$ = this, config = $$.config,
hasLeftAxisRect = config.axis_rotated || (!config.axis_rotated && !config.axis_y_inner),
leftAxisClass = config.axis_rotated ? CLASS.axisX : CLASS.axisY,
leftAxis = $$.main.select('.' + leftAxisClass).node(),
svgRect = leftAxis && hasLeftAxisRect ? leftAxis.getBoundingClientRect() : {right: 0},
chartRect = $$.selectChart.node().getBoundingClientRect(),
hasArc = $$.hasArcType(),
svgLeft = svgRect.right - chartRect.left - (hasArc ? 0 : $$.getCurrentPaddingLeft(withoutRecompute));
return svgLeft > 0 ? svgLeft : 0;
};
c3_chart_internal_fn.getAxisWidthByAxisId = function (id, withoutRecompute) {
var $$ = this, position = $$.axis.getLabelPositionById(id);
return $$.axis.getMaxTickWidth(id, withoutRecompute) + (position.isInner ? 20 : 40);
};
c3_chart_internal_fn.getHorizontalAxisHeight = function (axisId) {
var $$ = this, config = $$.config, h = 30;
if (axisId === 'x' && !config.axis_x_show) { return 8; }
if (axisId === 'x' && config.axis_x_height) { return config.axis_x_height; }
if (axisId === 'y' && !config.axis_y_show) { return config.legend_show && !$$.isLegendRight && !$$.isLegendInset ? 10 : 1; }
if (axisId === 'y2' && !config.axis_y2_show) { return $$.rotated_padding_top; }
// Calculate x axis height when tick rotated
if (axisId === 'x' && !config.axis_rotated && config.axis_x_tick_rotate) {
h = 30 + $$.axis.getMaxTickWidth(axisId) * Math.cos(Math.PI * (90 - config.axis_x_tick_rotate) / 180);
}
return h + ($$.axis.getLabelPositionById(axisId).isInner ? 0 : 10) + (axisId === 'y2' ? -10 : 0);
};
c3_chart_internal_fn.getEventRectWidth = function () {
return this.xAxis.tickInterval();
};
c3_chart_internal_fn.getShapeIndices = function (typeFilter) {
var $$ = this, config = $$.config,
indices = {}, i = 0, j, k;
$$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$)).forEach(function (d) {
for (j = 0; j < config.data_groups.length; j++) {
if (config.data_groups[j].indexOf(d.id) < 0) { continue; }
for (k = 0; k < config.data_groups[j].length; k++) {
if (config.data_groups[j][k] in indices) {
indices[d.id] = indices[config.data_groups[j][k]];
break;
}
}
}
if (isUndefined(indices[d.id])) { indices[d.id] = i++; }
});
indices.__max__ = i - 1;
return indices;
};
c3_chart_internal_fn.getShapeX = function (offset, targetsNum, indices, isSub) {
var $$ = this, scale = isSub ? $$.subX : $$.x;
return function (d) {
var index = d.id in indices ? indices[d.id] : 0;
return d.x || d.x === 0 ? scale(d.x) - offset * (targetsNum / 2 - index) : 0;
};
};
c3_chart_internal_fn.getShapeY = function (isSub) {
var $$ = this;
return function (d) {
var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id);
return scale(d.value);
};
};
c3_chart_internal_fn.getShapeOffset = function (typeFilter, indices, isSub) {
var $$ = this,
targets = $$.orderTargets($$.filterTargetsToShow($$.data.targets.filter(typeFilter, $$))),
targetIds = targets.map(function (t) { return t.id; });
return function (d, i) {
var scale = isSub ? $$.getSubYScale(d.id) : $$.getYScale(d.id),
y0 = scale(0), offset = y0;
targets.forEach(function (t) {
var values = $$.isStepType(d) ? $$.convertValuesToStep(t.values) : t.values;
if (t.id === d.id || indices[t.id] !== indices[d.id]) { return; }
if (targetIds.indexOf(t.id) < targetIds.indexOf(d.id)) {
if (values[i].value * d.value >= 0) {
offset += scale(values[i].value) - y0;
}
}
});
return offset;
};
};
c3_chart_internal_fn.isWithinShape = function (that, d) {
var $$ = this,
shape = $$.d3.select(that), isWithin;
if (!$$.isTargetToShow(d.id)) {
isWithin = false;
}
else if (that.nodeName === 'circle') {
isWithin = $$.isStepType(d) ? $$.isWithinStep(that, $$.getYScale(d.id)(d.value)) : $$.isWithinCircle(that, $$.pointSelectR(d) * 1.5);
}
else if (that.nodeName === 'path') {
isWithin = shape.classed(CLASS.bar) ? $$.isWithinBar(that) : true;
}
return isWithin;
};
c3_chart_internal_fn.getInterpolate = function (d) {
var $$ = this;
return $$.isSplineType(d) ? "cardinal" : $$.isStepType(d) ? $$.config.line_step_type : "linear";
};
c3_chart_internal_fn.initLine = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartLines);
};
c3_chart_internal_fn.updateTargetsForLine = function (targets) {
var $$ = this, config = $$.config,
mainLineUpdate, mainLineEnter,
classChartLine = $$.classChartLine.bind($$),
classLines = $$.classLines.bind($$),
classAreas = $$.classAreas.bind($$),
classCircles = $$.classCircles.bind($$),
classFocus = $$.classFocus.bind($$);
mainLineUpdate = $$.main.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine)
.data(targets)
.attr('class', function (d) { return classChartLine(d) + classFocus(d); });
mainLineEnter = mainLineUpdate.enter().append('g')
.attr('class', classChartLine)
.style('opacity', 0)
.style("pointer-events", "none");
// Lines for each data
mainLineEnter.append('g')
.attr("class", classLines);
// Areas
mainLineEnter.append('g')
.attr('class', classAreas);
// Circles for each data point on lines
mainLineEnter.append('g')
.attr("class", function (d) { return $$.generateClass(CLASS.selectedCircles, d.id); });
mainLineEnter.append('g')
.attr("class", classCircles)
.style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });
// Update date for selected circles
targets.forEach(function (t) {
$$.main.selectAll('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(t.id)).selectAll('.' + CLASS.selectedCircle).each(function (d) {
d.value = t.values[d.index].value;
});
});
// MEMO: can not keep same color...
//mainLineUpdate.exit().remove();
};
c3_chart_internal_fn.updateLine = function (durationForExit) {
var $$ = this;
$$.mainLine = $$.main.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
.data($$.lineData.bind($$));
$$.mainLine.enter().append('path')
.attr('class', $$.classLine.bind($$))
.style("stroke", $$.color);
$$.mainLine
.style("opacity", $$.initialOpacity.bind($$))
.style('shape-rendering', function (d) { return $$.isStepType(d) ? 'crispEdges' : ''; })
.attr('transform', null);
$$.mainLine.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawLine = function (drawLine, withTransition) {
return [
(withTransition ? this.mainLine.transition() : this.mainLine)
.attr("d", drawLine)
.style("stroke", this.color)
.style("opacity", 1)
];
};
c3_chart_internal_fn.generateDrawLine = function (lineIndices, isSub) {
var $$ = this, config = $$.config,
line = $$.d3.svg.line(),
getPoints = $$.generateGetLinePoints(lineIndices, isSub),
yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); },
yValue = function (d, i) {
return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)(d.value);
};
line = config.axis_rotated ? line.x(yValue).y(xValue) : line.x(xValue).y(yValue);
if (!config.line_connectNull) { line = line.defined(function (d) { return d.value != null; }); }
return function (d) {
var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
x = isSub ? $$.x : $$.subX, y = yScaleGetter.call($$, d.id), x0 = 0, y0 = 0, path;
if ($$.isLineType(d)) {
if (config.data_regions[d.id]) {
path = $$.lineWithRegions(values, x, y, config.data_regions[d.id]);
} else {
if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); }
path = line.interpolate($$.getInterpolate(d))(values);
}
} else {
if (values[0]) {
x0 = x(values[0].x);
y0 = y(values[0].value);
}
path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
}
return path ? path : "M 0 0";
};
};
c3_chart_internal_fn.generateGetLinePoints = function (lineIndices, isSub) { // partial duplication of generateGetBarPoints
var $$ = this, config = $$.config,
lineTargetsNum = lineIndices.__max__ + 1,
x = $$.getShapeX(0, lineTargetsNum, lineIndices, !!isSub),
y = $$.getShapeY(!!isSub),
lineOffset = $$.getShapeOffset($$.isLineType, lineIndices, !!isSub),
yScale = isSub ? $$.getSubYScale : $$.getYScale;
return function (d, i) {
var y0 = yScale.call($$, d.id)(0),
offset = lineOffset(d, i) || y0, // offset is for stacked area chart
posX = x(d), posY = y(d);
// fix posY not to overflow opposite quadrant
if (config.axis_rotated) {
if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
}
// 1 point that marks the line position
return [
[posX, posY - (y0 - offset)],
[posX, posY - (y0 - offset)], // needed for compatibility
[posX, posY - (y0 - offset)], // needed for compatibility
[posX, posY - (y0 - offset)] // needed for compatibility
];
};
};
c3_chart_internal_fn.lineWithRegions = function (d, x, y, _regions) {
var $$ = this, config = $$.config,
prev = -1, i, j,
s = "M", sWithRegion,
xp, yp, dx, dy, dd, diff, diffx2,
xOffset = $$.isCategorized() ? 0.5 : 0,
xValue, yValue,
regions = [];
function isWithinRegions(x, regions) {
var i;
for (i = 0; i < regions.length; i++) {
if (regions[i].start < x && x <= regions[i].end) { return true; }
}
return false;
}
// Check start/end of regions
if (isDefined(_regions)) {
for (i = 0; i < _regions.length; i++) {
regions[i] = {};
if (isUndefined(_regions[i].start)) {
regions[i].start = d[0].x;
} else {
regions[i].start = $$.isTimeSeries() ? $$.parseDate(_regions[i].start) : _regions[i].start;
}
if (isUndefined(_regions[i].end)) {
regions[i].end = d[d.length - 1].x;
} else {
regions[i].end = $$.isTimeSeries() ? $$.parseDate(_regions[i].end) : _regions[i].end;
}
}
}
// Set scales
xValue = config.axis_rotated ? function (d) { return y(d.value); } : function (d) { return x(d.x); };
yValue = config.axis_rotated ? function (d) { return x(d.x); } : function (d) { return y(d.value); };
// Define svg generator function for region
function generateM(points) {
return 'M' + points[0][0] + ' ' + points[0][1] + ' ' + points[1][0] + ' ' + points[1][1];
}
if ($$.isTimeSeries()) {
sWithRegion = function (d0, d1, j, diff) {
var x0 = d0.x.getTime(), x_diff = d1.x - d0.x,
xv0 = new Date(x0 + x_diff * j),
xv1 = new Date(x0 + x_diff * (j + diff)),
points;
if (config.axis_rotated) {
points = [[y(yp(j)), x(xv0)], [y(yp(j + diff)), x(xv1)]];
} else {
points = [[x(xv0), y(yp(j))], [x(xv1), y(yp(j + diff))]];
}
return generateM(points);
};
} else {
sWithRegion = function (d0, d1, j, diff) {
var points;
if (config.axis_rotated) {
points = [[y(yp(j), true), x(xp(j))], [y(yp(j + diff), true), x(xp(j + diff))]];
} else {
points = [[x(xp(j), true), y(yp(j))], [x(xp(j + diff), true), y(yp(j + diff))]];
}
return generateM(points);
};
}
// Generate
for (i = 0; i < d.length; i++) {
// Draw as normal
if (isUndefined(regions) || ! isWithinRegions(d[i].x, regions)) {
s += " " + xValue(d[i]) + " " + yValue(d[i]);
}
// Draw with region // TODO: Fix for horizotal charts
else {
xp = $$.getScale(d[i - 1].x + xOffset, d[i].x + xOffset, $$.isTimeSeries());
yp = $$.getScale(d[i - 1].value, d[i].value);
dx = x(d[i].x) - x(d[i - 1].x);
dy = y(d[i].value) - y(d[i - 1].value);
dd = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
diff = 2 / dd;
diffx2 = diff * 2;
for (j = diff; j <= 1; j += diffx2) {
s += sWithRegion(d[i - 1], d[i], j, diff);
}
}
prev = d[i].x;
}
return s;
};
c3_chart_internal_fn.updateArea = function (durationForExit) {
var $$ = this, d3 = $$.d3;
$$.mainArea = $$.main.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
.data($$.lineData.bind($$));
$$.mainArea.enter().append('path')
.attr("class", $$.classArea.bind($$))
.style("fill", $$.color)
.style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; });
$$.mainArea
.style("opacity", $$.orgAreaOpacity);
$$.mainArea.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawArea = function (drawArea, withTransition) {
return [
(withTransition ? this.mainArea.transition() : this.mainArea)
.attr("d", drawArea)
.style("fill", this.color)
.style("opacity", this.orgAreaOpacity)
];
};
c3_chart_internal_fn.generateDrawArea = function (areaIndices, isSub) {
var $$ = this, config = $$.config, area = $$.d3.svg.area(),
getPoints = $$.generateGetAreaPoints(areaIndices, isSub),
yScaleGetter = isSub ? $$.getSubYScale : $$.getYScale,
xValue = function (d) { return (isSub ? $$.subxx : $$.xx).call($$, d); },
value0 = function (d, i) {
return config.data_groups.length > 0 ? getPoints(d, i)[0][1] : yScaleGetter.call($$, d.id)($$.getAreaBaseValue(d.id));
},
value1 = function (d, i) {
return config.data_groups.length > 0 ? getPoints(d, i)[1][1] : yScaleGetter.call($$, d.id)(d.value);
};
area = config.axis_rotated ? area.x0(value0).x1(value1).y(xValue) : area.x(xValue).y0(value0).y1(value1);
if (!config.line_connectNull) {
area = area.defined(function (d) { return d.value !== null; });
}
return function (d) {
var values = config.line_connectNull ? $$.filterRemoveNull(d.values) : d.values,
x0 = 0, y0 = 0, path;
if ($$.isAreaType(d)) {
if ($$.isStepType(d)) { values = $$.convertValuesToStep(values); }
path = area.interpolate($$.getInterpolate(d))(values);
} else {
if (values[0]) {
x0 = $$.x(values[0].x);
y0 = $$.getYScale(d.id)(values[0].value);
}
path = config.axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0;
}
return path ? path : "M 0 0";
};
};
c3_chart_internal_fn.getAreaBaseValue = function () {
return 0;
};
c3_chart_internal_fn.generateGetAreaPoints = function (areaIndices, isSub) { // partial duplication of generateGetBarPoints
var $$ = this, config = $$.config,
areaTargetsNum = areaIndices.__max__ + 1,
x = $$.getShapeX(0, areaTargetsNum, areaIndices, !!isSub),
y = $$.getShapeY(!!isSub),
areaOffset = $$.getShapeOffset($$.isAreaType, areaIndices, !!isSub),
yScale = isSub ? $$.getSubYScale : $$.getYScale;
return function (d, i) {
var y0 = yScale.call($$, d.id)(0),
offset = areaOffset(d, i) || y0, // offset is for stacked area chart
posX = x(d), posY = y(d);
// fix posY not to overflow opposite quadrant
if (config.axis_rotated) {
if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
}
// 1 point that marks the area position
return [
[posX, offset],
[posX, posY - (y0 - offset)],
[posX, posY - (y0 - offset)], // needed for compatibility
[posX, offset] // needed for compatibility
];
};
};
c3_chart_internal_fn.updateCircle = function () {
var $$ = this;
$$.mainCircle = $$.main.selectAll('.' + CLASS.circles).selectAll('.' + CLASS.circle)
.data($$.lineOrScatterData.bind($$));
$$.mainCircle.enter().append("circle")
.attr("class", $$.classCircle.bind($$))
.attr("r", $$.pointR.bind($$))
.style("fill", $$.color);
$$.mainCircle
.style("opacity", $$.initialOpacityForCircle.bind($$));
$$.mainCircle.exit().remove();
};
c3_chart_internal_fn.redrawCircle = function (cx, cy, withTransition) {
var selectedCircles = this.main.selectAll('.' + CLASS.selectedCircle);
return [
(withTransition ? this.mainCircle.transition() : this.mainCircle)
.style('opacity', this.opacityForCircle.bind(this))
.style("fill", this.color)
.attr("cx", cx)
.attr("cy", cy),
(withTransition ? selectedCircles.transition() : selectedCircles)
.attr("cx", cx)
.attr("cy", cy)
];
};
c3_chart_internal_fn.circleX = function (d) {
return d.x || d.x === 0 ? this.x(d.x) : null;
};
c3_chart_internal_fn.updateCircleY = function () {
var $$ = this, lineIndices, getPoints;
if ($$.config.data_groups.length > 0) {
lineIndices = $$.getShapeIndices($$.isLineType),
getPoints = $$.generateGetLinePoints(lineIndices);
$$.circleY = function (d, i) {
return getPoints(d, i)[0][1];
};
} else {
$$.circleY = function (d) {
return $$.getYScale(d.id)(d.value);
};
}
};
c3_chart_internal_fn.getCircles = function (i, id) {
var $$ = this;
return (id ? $$.main.selectAll('.' + CLASS.circles + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.circle + (isValue(i) ? '-' + i : ''));
};
c3_chart_internal_fn.expandCircles = function (i, id, reset) {
var $$ = this,
r = $$.pointExpandedR.bind($$);
if (reset) { $$.unexpandCircles(); }
$$.getCircles(i, id)
.classed(CLASS.EXPANDED, true)
.attr('r', r);
};
c3_chart_internal_fn.unexpandCircles = function (i) {
var $$ = this,
r = $$.pointR.bind($$);
$$.getCircles(i)
.filter(function () { return $$.d3.select(this).classed(CLASS.EXPANDED); })
.classed(CLASS.EXPANDED, false)
.attr('r', r);
};
c3_chart_internal_fn.pointR = function (d) {
var $$ = this, config = $$.config;
return $$.isStepType(d) ? 0 : (isFunction(config.point_r) ? config.point_r(d) : config.point_r);
};
c3_chart_internal_fn.pointExpandedR = function (d) {
var $$ = this, config = $$.config;
return config.point_focus_expand_enabled ? (config.point_focus_expand_r ? config.point_focus_expand_r : $$.pointR(d) * 1.75) : $$.pointR(d);
};
c3_chart_internal_fn.pointSelectR = function (d) {
var $$ = this, config = $$.config;
return config.point_select_r ? config.point_select_r : $$.pointR(d) * 4;
};
c3_chart_internal_fn.isWithinCircle = function (that, r) {
var d3 = this.d3,
mouse = d3.mouse(that), d3_this = d3.select(that),
cx = +d3_this.attr("cx"), cy = +d3_this.attr("cy");
return Math.sqrt(Math.pow(cx - mouse[0], 2) + Math.pow(cy - mouse[1], 2)) < r;
};
c3_chart_internal_fn.isWithinStep = function (that, y) {
return Math.abs(y - this.d3.mouse(that)[1]) < 30;
};
c3_chart_internal_fn.initBar = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartBars);
};
c3_chart_internal_fn.updateTargetsForBar = function (targets) {
var $$ = this, config = $$.config,
mainBarUpdate, mainBarEnter,
classChartBar = $$.classChartBar.bind($$),
classBars = $$.classBars.bind($$),
classFocus = $$.classFocus.bind($$);
mainBarUpdate = $$.main.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar)
.data(targets)
.attr('class', function (d) { return classChartBar(d) + classFocus(d); });
mainBarEnter = mainBarUpdate.enter().append('g')
.attr('class', classChartBar)
.style('opacity', 0)
.style("pointer-events", "none");
// Bars for each data
mainBarEnter.append('g')
.attr("class", classBars)
.style("cursor", function (d) { return config.data_selection_isselectable(d) ? "pointer" : null; });
};
c3_chart_internal_fn.updateBar = function (durationForExit) {
var $$ = this,
barData = $$.barData.bind($$),
classBar = $$.classBar.bind($$),
initialOpacity = $$.initialOpacity.bind($$),
color = function (d) { return $$.color(d.id); };
$$.mainBar = $$.main.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
.data(barData);
$$.mainBar.enter().append('path')
.attr("class", classBar)
.style("stroke", color)
.style("fill", color);
$$.mainBar
.style("opacity", initialOpacity);
$$.mainBar.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawBar = function (drawBar, withTransition) {
return [
(withTransition ? this.mainBar.transition() : this.mainBar)
.attr('d', drawBar)
.style("fill", this.color)
.style("opacity", 1)
];
};
c3_chart_internal_fn.getBarW = function (axis, barTargetsNum) {
var $$ = this, config = $$.config,
w = typeof config.bar_width === 'number' ? config.bar_width : barTargetsNum ? (axis.tickInterval() * config.bar_width_ratio) / barTargetsNum : 0;
return config.bar_width_max && w > config.bar_width_max ? config.bar_width_max : w;
};
c3_chart_internal_fn.getBars = function (i, id) {
var $$ = this;
return (id ? $$.main.selectAll('.' + CLASS.bars + $$.getTargetSelectorSuffix(id)) : $$.main).selectAll('.' + CLASS.bar + (isValue(i) ? '-' + i : ''));
};
c3_chart_internal_fn.expandBars = function (i, id, reset) {
var $$ = this;
if (reset) { $$.unexpandBars(); }
$$.getBars(i, id).classed(CLASS.EXPANDED, true);
};
c3_chart_internal_fn.unexpandBars = function (i) {
var $$ = this;
$$.getBars(i).classed(CLASS.EXPANDED, false);
};
c3_chart_internal_fn.generateDrawBar = function (barIndices, isSub) {
var $$ = this, config = $$.config,
getPoints = $$.generateGetBarPoints(barIndices, isSub);
return function (d, i) {
// 4 points that make a bar
var points = getPoints(d, i);
// switch points if axis is rotated, not applicable for sub chart
var indexX = config.axis_rotated ? 1 : 0;
var indexY = config.axis_rotated ? 0 : 1;
var path = 'M ' + points[0][indexX] + ',' + points[0][indexY] + ' ' +
'L' + points[1][indexX] + ',' + points[1][indexY] + ' ' +
'L' + points[2][indexX] + ',' + points[2][indexY] + ' ' +
'L' + points[3][indexX] + ',' + points[3][indexY] + ' ' +
'z';
return path;
};
};
c3_chart_internal_fn.generateGetBarPoints = function (barIndices, isSub) {
var $$ = this,
axis = isSub ? $$.subXAxis : $$.xAxis,
barTargetsNum = barIndices.__max__ + 1,
barW = $$.getBarW(axis, barTargetsNum),
barX = $$.getShapeX(barW, barTargetsNum, barIndices, !!isSub),
barY = $$.getShapeY(!!isSub),
barOffset = $$.getShapeOffset($$.isBarType, barIndices, !!isSub),
yScale = isSub ? $$.getSubYScale : $$.getYScale;
return function (d, i) {
var y0 = yScale.call($$, d.id)(0),
offset = barOffset(d, i) || y0, // offset is for stacked bar chart
posX = barX(d), posY = barY(d);
// fix posY not to overflow opposite quadrant
if ($$.config.axis_rotated) {
if ((0 < d.value && posY < y0) || (d.value < 0 && y0 < posY)) { posY = y0; }
}
// 4 points that make a bar
return [
[posX, offset],
[posX, posY - (y0 - offset)],
[posX + barW, posY - (y0 - offset)],
[posX + barW, offset]
];
};
};
c3_chart_internal_fn.isWithinBar = function (that) {
var mouse = this.d3.mouse(that), box = that.getBoundingClientRect(),
seg0 = that.pathSegList.getItem(0), seg1 = that.pathSegList.getItem(1),
x = Math.min(seg0.x, seg1.x), y = Math.min(seg0.y, seg1.y),
w = box.width, h = box.height, offset = 2,
sx = x - offset, ex = x + w + offset, sy = y + h + offset, ey = y - offset;
return sx < mouse[0] && mouse[0] < ex && ey < mouse[1] && mouse[1] < sy;
};
c3_chart_internal_fn.initText = function () {
var $$ = this;
$$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartTexts);
$$.mainText = $$.d3.selectAll([]);
};
c3_chart_internal_fn.updateTargetsForText = function (targets) {
var $$ = this, mainTextUpdate, mainTextEnter,
classChartText = $$.classChartText.bind($$),
classTexts = $$.classTexts.bind($$),
classFocus = $$.classFocus.bind($$);
mainTextUpdate = $$.main.select('.' + CLASS.chartTexts).selectAll('.' + CLASS.chartText)
.data(targets)
.attr('class', function (d) { return classChartText(d) + classFocus(d); });
mainTextEnter = mainTextUpdate.enter().append('g')
.attr('class', classChartText)
.style('opacity', 0)
.style("pointer-events", "none");
mainTextEnter.append('g')
.attr('class', classTexts);
};
c3_chart_internal_fn.updateText = function (durationForExit) {
var $$ = this, config = $$.config,
barOrLineData = $$.barOrLineData.bind($$),
classText = $$.classText.bind($$);
$$.mainText = $$.main.selectAll('.' + CLASS.texts).selectAll('.' + CLASS.text)
.data(barOrLineData);
$$.mainText.enter().append('text')
.attr("class", classText)
.attr('text-anchor', function (d) { return config.axis_rotated ? (d.value < 0 ? 'end' : 'start') : 'middle'; })
.style("stroke", 'none')
.style("fill", function (d) { return $$.color(d); })
.style("fill-opacity", 0);
$$.mainText
.text(function (d, i, j) { return $$.dataLabelFormat(d.id)(d.value, d.id, i, j); });
$$.mainText.exit()
.transition().duration(durationForExit)
.style('fill-opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawText = function (xForText, yForText, forFlow, withTransition) {
return [
(withTransition ? this.mainText.transition() : this.mainText)
.attr('x', xForText)
.attr('y', yForText)
.style("fill", this.color)
.style("fill-opacity", forFlow ? 0 : this.opacityForText.bind(this))
];
};
c3_chart_internal_fn.getTextRect = function (text, cls) {
var dummy = this.d3.select('body').append('div').classed('c3', true),
svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
rect;
svg.selectAll('.dummy')
.data([text])
.enter().append('text')
.classed(cls ? cls : "", true)
.text(text)
.each(function () { rect = this.getBoundingClientRect(); });
dummy.remove();
return rect;
};
c3_chart_internal_fn.generateXYForText = function (areaIndices, barIndices, lineIndices, forX) {
var $$ = this,
getAreaPoints = $$.generateGetAreaPoints(areaIndices, false),
getBarPoints = $$.generateGetBarPoints(barIndices, false),
getLinePoints = $$.generateGetLinePoints(lineIndices, false),
getter = forX ? $$.getXForText : $$.getYForText;
return function (d, i) {
var getPoints = $$.isAreaType(d) ? getAreaPoints : $$.isBarType(d) ? getBarPoints : getLinePoints;
return getter.call($$, getPoints(d, i), d, this);
};
};
c3_chart_internal_fn.getXForText = function (points, d, textElement) {
var $$ = this,
box = textElement.getBoundingClientRect(), xPos, padding;
if ($$.config.axis_rotated) {
padding = $$.isBarType(d) ? 4 : 6;
xPos = points[2][1] + padding * (d.value < 0 ? -1 : 1);
} else {
xPos = $$.hasType('bar') ? (points[2][0] + points[0][0]) / 2 : points[0][0];
}
// show labels regardless of the domain if value is null
if (d.value === null) {
if (xPos > $$.width) {
xPos = $$.width - box.width;
} else if (xPos < 0) {
xPos = 4;
}
}
return xPos;
};
c3_chart_internal_fn.getYForText = function (points, d, textElement) {
var $$ = this,
box = textElement.getBoundingClientRect(), yPos;
if ($$.config.axis_rotated) {
yPos = (points[0][0] + points[2][0] + box.height * 0.6) / 2;
} else {
yPos = points[2][1] + (d.value < 0 ? box.height * 1.3 : $$.isBarType(d) ? -3 : -6);
}
// show labels regardless of the domain if value is null
if (d.value === null && !$$.config.axis_rotated) {
if (yPos < box.height) {
yPos = box.height;
} else if (yPos > this.height) {
yPos = this.height - 4;
}
}
return yPos;
};
c3_chart_internal_fn.setTargetType = function (targetIds, type) {
var $$ = this, config = $$.config;
$$.mapToTargetIds(targetIds).forEach(function (id) {
$$.withoutFadeIn[id] = (type === config.data_types[id]);
config.data_types[id] = type;
});
if (!targetIds) {
config.data_type = type;
}
};
c3_chart_internal_fn.hasType = function (type, targets) {
var $$ = this, types = $$.config.data_types, has = false;
targets = targets || $$.data.targets;
if (targets && targets.length) {
targets.forEach(function (target) {
var t = types[target.id];
if ((t && t.indexOf(type) >= 0) || (!t && type === 'line')) {
has = true;
}
});
} else if (Object.keys(types).length) {
Object.keys(types).forEach(function (id) {
if (types[id] === type) { has = true; }
});
} else {
has = $$.config.data_type === type;
}
return has;
};
c3_chart_internal_fn.hasArcType = function (targets) {
return this.hasType('pie', targets) || this.hasType('donut', targets) || this.hasType('gauge', targets);
};
c3_chart_internal_fn.isLineType = function (d) {
var config = this.config, id = isString(d) ? d : d.id;
return !config.data_types[id] || ['line', 'spline', 'area', 'area-spline', 'step', 'area-step'].indexOf(config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isStepType = function (d) {
var id = isString(d) ? d : d.id;
return ['step', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isSplineType = function (d) {
var id = isString(d) ? d : d.id;
return ['spline', 'area-spline'].indexOf(this.config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isAreaType = function (d) {
var id = isString(d) ? d : d.id;
return ['area', 'area-spline', 'area-step'].indexOf(this.config.data_types[id]) >= 0;
};
c3_chart_internal_fn.isBarType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'bar';
};
c3_chart_internal_fn.isScatterType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'scatter';
};
c3_chart_internal_fn.isPieType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'pie';
};
c3_chart_internal_fn.isGaugeType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'gauge';
};
c3_chart_internal_fn.isDonutType = function (d) {
var id = isString(d) ? d : d.id;
return this.config.data_types[id] === 'donut';
};
c3_chart_internal_fn.isArcType = function (d) {
return this.isPieType(d) || this.isDonutType(d) || this.isGaugeType(d);
};
c3_chart_internal_fn.lineData = function (d) {
return this.isLineType(d) ? [d] : [];
};
c3_chart_internal_fn.arcData = function (d) {
return this.isArcType(d.data) ? [d] : [];
};
/* not used
function scatterData(d) {
return isScatterType(d) ? d.values : [];
}
*/
c3_chart_internal_fn.barData = function (d) {
return this.isBarType(d) ? d.values : [];
};
c3_chart_internal_fn.lineOrScatterData = function (d) {
return this.isLineType(d) || this.isScatterType(d) ? d.values : [];
};
c3_chart_internal_fn.barOrLineData = function (d) {
return this.isBarType(d) || this.isLineType(d) ? d.values : [];
};
c3_chart_internal_fn.initGrid = function () {
var $$ = this, config = $$.config, d3 = $$.d3;
$$.grid = $$.main.append('g')
.attr("clip-path", $$.clipPathForGrid)
.attr('class', CLASS.grid);
if (config.grid_x_show) {
$$.grid.append("g").attr("class", CLASS.xgrids);
}
if (config.grid_y_show) {
$$.grid.append('g').attr('class', CLASS.ygrids);
}
if (config.grid_focus_show) {
$$.grid.append('g')
.attr("class", CLASS.xgridFocus)
.append('line')
.attr('class', CLASS.xgridFocus);
}
$$.xgrid = d3.selectAll([]);
if (!config.grid_lines_front) { $$.initGridLines(); }
};
c3_chart_internal_fn.initGridLines = function () {
var $$ = this, d3 = $$.d3;
$$.gridLines = $$.main.append('g')
.attr("clip-path", $$.clipPathForGrid)
.attr('class', CLASS.grid + ' ' + CLASS.gridLines);
$$.gridLines.append('g').attr("class", CLASS.xgridLines);
$$.gridLines.append('g').attr('class', CLASS.ygridLines);
$$.xgridLines = d3.selectAll([]);
};
c3_chart_internal_fn.updateXGrid = function (withoutUpdate) {
var $$ = this, config = $$.config, d3 = $$.d3,
xgridData = $$.generateGridData(config.grid_x_type, $$.x),
tickOffset = $$.isCategorized() ? $$.xAxis.tickOffset() : 0;
$$.xgridAttr = config.axis_rotated ? {
'x1': 0,
'x2': $$.width,
'y1': function (d) { return $$.x(d) - tickOffset; },
'y2': function (d) { return $$.x(d) - tickOffset; }
} : {
'x1': function (d) { return $$.x(d) + tickOffset; },
'x2': function (d) { return $$.x(d) + tickOffset; },
'y1': 0,
'y2': $$.height
};
$$.xgrid = $$.main.select('.' + CLASS.xgrids).selectAll('.' + CLASS.xgrid)
.data(xgridData);
$$.xgrid.enter().append('line').attr("class", CLASS.xgrid);
if (!withoutUpdate) {
$$.xgrid.attr($$.xgridAttr)
.style("opacity", function () { return +d3.select(this).attr(config.axis_rotated ? 'y1' : 'x1') === (config.axis_rotated ? $$.height : 0) ? 0 : 1; });
}
$$.xgrid.exit().remove();
};
c3_chart_internal_fn.updateYGrid = function () {
var $$ = this, config = $$.config,
gridValues = $$.yAxis.tickValues() || $$.y.ticks(config.grid_y_ticks);
$$.ygrid = $$.main.select('.' + CLASS.ygrids).selectAll('.' + CLASS.ygrid)
.data(gridValues);
$$.ygrid.enter().append('line')
.attr('class', CLASS.ygrid);
$$.ygrid.attr("x1", config.axis_rotated ? $$.y : 0)
.attr("x2", config.axis_rotated ? $$.y : $$.width)
.attr("y1", config.axis_rotated ? 0 : $$.y)
.attr("y2", config.axis_rotated ? $$.height : $$.y);
$$.ygrid.exit().remove();
$$.smoothLines($$.ygrid, 'grid');
};
c3_chart_internal_fn.gridTextAnchor = function (d) {
return d.position ? d.position : "end";
};
c3_chart_internal_fn.gridTextDx = function (d) {
return d.position === 'start' ? 4 : d.position === 'middle' ? 0 : -4;
};
c3_chart_internal_fn.xGridTextX = function (d) {
return d.position === 'start' ? -this.height : d.position === 'middle' ? -this.height / 2 : 0;
};
c3_chart_internal_fn.yGridTextX = function (d) {
return d.position === 'start' ? 0 : d.position === 'middle' ? this.width / 2 : this.width;
};
c3_chart_internal_fn.updateGrid = function (duration) {
var $$ = this, main = $$.main, config = $$.config,
xgridLine, ygridLine, yv;
// hide if arc type
$$.grid.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');
main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
if (config.grid_x_show) {
$$.updateXGrid();
}
$$.xgridLines = main.select('.' + CLASS.xgridLines).selectAll('.' + CLASS.xgridLine)
.data(config.grid_x_lines);
// enter
xgridLine = $$.xgridLines.enter().append('g')
.attr("class", function (d) { return CLASS.xgridLine + (d['class'] ? ' ' + d['class'] : ''); });
xgridLine.append('line')
.style("opacity", 0);
xgridLine.append('text')
.attr("text-anchor", $$.gridTextAnchor)
.attr("transform", config.axis_rotated ? "" : "rotate(-90)")
.attr('dx', $$.gridTextDx)
.attr('dy', -5)
.style("opacity", 0);
// udpate
// done in d3.transition() of the end of this function
// exit
$$.xgridLines.exit().transition().duration(duration)
.style("opacity", 0)
.remove();
// Y-Grid
if (config.grid_y_show) {
$$.updateYGrid();
}
$$.ygridLines = main.select('.' + CLASS.ygridLines).selectAll('.' + CLASS.ygridLine)
.data(config.grid_y_lines);
// enter
ygridLine = $$.ygridLines.enter().append('g')
.attr("class", function (d) { return CLASS.ygridLine + (d['class'] ? ' ' + d['class'] : ''); });
ygridLine.append('line')
.style("opacity", 0);
ygridLine.append('text')
.attr("text-anchor", $$.gridTextAnchor)
.attr("transform", config.axis_rotated ? "rotate(-90)" : "")
.attr('dx', $$.gridTextDx)
.attr('dy', -5)
.style("opacity", 0);
// update
yv = $$.yv.bind($$);
$$.ygridLines.select('line')
.transition().duration(duration)
.attr("x1", config.axis_rotated ? yv : 0)
.attr("x2", config.axis_rotated ? yv : $$.width)
.attr("y1", config.axis_rotated ? 0 : yv)
.attr("y2", config.axis_rotated ? $$.height : yv)
.style("opacity", 1);
$$.ygridLines.select('text')
.transition().duration(duration)
.attr("x", config.axis_rotated ? $$.xGridTextX.bind($$) : $$.yGridTextX.bind($$))
.attr("y", yv)
.text(function (d) { return d.text; })
.style("opacity", 1);
// exit
$$.ygridLines.exit().transition().duration(duration)
.style("opacity", 0)
.remove();
};
c3_chart_internal_fn.redrawGrid = function (withTransition) {
var $$ = this, config = $$.config, xv = $$.xv.bind($$),
lines = $$.xgridLines.select('line'),
texts = $$.xgridLines.select('text');
return [
(withTransition ? lines.transition() : lines)
.attr("x1", config.axis_rotated ? 0 : xv)
.attr("x2", config.axis_rotated ? $$.width : xv)
.attr("y1", config.axis_rotated ? xv : 0)
.attr("y2", config.axis_rotated ? xv : $$.height)
.style("opacity", 1),
(withTransition ? texts.transition() : texts)
.attr("x", config.axis_rotated ? $$.yGridTextX.bind($$) : $$.xGridTextX.bind($$))
.attr("y", xv)
.text(function (d) { return d.text; })
.style("opacity", 1)
];
};
c3_chart_internal_fn.showXGridFocus = function (selectedData) {
var $$ = this, config = $$.config,
dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }),
focusEl = $$.main.selectAll('line.' + CLASS.xgridFocus),
xx = $$.xx.bind($$);
if (! config.tooltip_show) { return; }
// Hide when scatter plot exists
if ($$.hasType('scatter') || $$.hasArcType()) { return; }
focusEl
.style("visibility", "visible")
.data([dataToShow[0]])
.attr(config.axis_rotated ? 'y1' : 'x1', xx)
.attr(config.axis_rotated ? 'y2' : 'x2', xx);
$$.smoothLines(focusEl, 'grid');
};
c3_chart_internal_fn.hideXGridFocus = function () {
this.main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden");
};
c3_chart_internal_fn.updateXgridFocus = function () {
var $$ = this, config = $$.config;
$$.main.select('line.' + CLASS.xgridFocus)
.attr("x1", config.axis_rotated ? 0 : -10)
.attr("x2", config.axis_rotated ? $$.width : -10)
.attr("y1", config.axis_rotated ? -10 : 0)
.attr("y2", config.axis_rotated ? -10 : $$.height);
};
c3_chart_internal_fn.generateGridData = function (type, scale) {
var $$ = this,
gridData = [], xDomain, firstYear, lastYear, i,
tickNum = $$.main.select("." + CLASS.axisX).selectAll('.tick').size();
if (type === 'year') {
xDomain = $$.getXDomain();
firstYear = xDomain[0].getFullYear();
lastYear = xDomain[1].getFullYear();
for (i = firstYear; i <= lastYear; i++) {
gridData.push(new Date(i + '-01-01 00:00:00'));
}
} else {
gridData = scale.ticks(10);
if (gridData.length > tickNum) { // use only int
gridData = gridData.filter(function (d) { return ("" + d).indexOf('.') < 0; });
}
}
return gridData;
};
c3_chart_internal_fn.getGridFilterToRemove = function (params) {
return params ? function (line) {
var found = false;
[].concat(params).forEach(function (param) {
if ((('value' in param && line.value === param.value) || ('class' in param && line['class'] === param['class']))) {
found = true;
}
});
return found;
} : function () { return true; };
};
c3_chart_internal_fn.removeGridLines = function (params, forX) {
var $$ = this, config = $$.config,
toRemove = $$.getGridFilterToRemove(params),
toShow = function (line) { return !toRemove(line); },
classLines = forX ? CLASS.xgridLines : CLASS.ygridLines,
classLine = forX ? CLASS.xgridLine : CLASS.ygridLine;
$$.main.select('.' + classLines).selectAll('.' + classLine).filter(toRemove)
.transition().duration(config.transition_duration)
.style('opacity', 0).remove();
if (forX) {
config.grid_x_lines = config.grid_x_lines.filter(toShow);
} else {
config.grid_y_lines = config.grid_y_lines.filter(toShow);
}
};
c3_chart_internal_fn.initTooltip = function () {
var $$ = this, config = $$.config, i;
$$.tooltip = $$.selectChart
.style("position", "relative")
.append("div")
.attr('class', CLASS.tooltipContainer)
.style("position", "absolute")
.style("pointer-events", "none")
.style("display", "none");
// Show tooltip if needed
if (config.tooltip_init_show) {
if ($$.isTimeSeries() && isString(config.tooltip_init_x)) {
config.tooltip_init_x = $$.parseDate(config.tooltip_init_x);
for (i = 0; i < $$.data.targets[0].values.length; i++) {
if (($$.data.targets[0].values[i].x - config.tooltip_init_x) === 0) { break; }
}
config.tooltip_init_x = i;
}
$$.tooltip.html(config.tooltip_contents.call($$, $$.data.targets.map(function (d) {
return $$.addName(d.values[config.tooltip_init_x]);
}), $$.axis.getXAxisTickFormat(), $$.getYFormat($$.hasArcType()), $$.color));
$$.tooltip.style("top", config.tooltip_init_position.top)
.style("left", config.tooltip_init_position.left)
.style("display", "block");
}
};
c3_chart_internal_fn.getTooltipContent = function (d, defaultTitleFormat, defaultValueFormat, color) {
var $$ = this, config = $$.config,
titleFormat = config.tooltip_format_title || defaultTitleFormat,
nameFormat = config.tooltip_format_name || function (name) { return name; },
valueFormat = config.tooltip_format_value || defaultValueFormat,
text, i, title, value, name, bgcolor;
for (i = 0; i < d.length; i++) {
if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; }
if (! text) {
title = titleFormat ? titleFormat(d[i].x) : d[i].x;
text = "<table class='" + CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : "");
}
value = valueFormat(d[i].value, d[i].ratio, d[i].id, d[i].index);
if (value !== undefined) {
name = nameFormat(d[i].name, d[i].ratio, d[i].id, d[i].index);
bgcolor = $$.levelColor ? $$.levelColor(d[i].value) : color(d[i].id);
text += "<tr class='" + CLASS.tooltipName + "-" + d[i].id + "'>";
text += "<td class='name'><span style='background-color:" + bgcolor + "'></span>" + name + "</td>";
text += "<td class='value'>" + value + "</td>";
text += "</tr>";
}
}
return text + "</table>";
};
c3_chart_internal_fn.tooltipPosition = function (dataToShow, tWidth, tHeight, element) {
var $$ = this, config = $$.config, d3 = $$.d3;
var svgLeft, tooltipLeft, tooltipRight, tooltipTop, chartRight;
var forArc = $$.hasArcType(),
mouse = d3.mouse(element);
// Determin tooltip position
if (forArc) {
tooltipLeft = (($$.width - ($$.isLegendRight ? $$.getLegendWidth() : 0)) / 2) + mouse[0];
tooltipTop = ($$.height / 2) + mouse[1] + 20;
} else {
svgLeft = $$.getSvgLeft(true);
if (config.axis_rotated) {
tooltipLeft = svgLeft + mouse[0] + 100;
tooltipRight = tooltipLeft + tWidth;
chartRight = $$.currentWidth - $$.getCurrentPaddingRight();
tooltipTop = $$.x(dataToShow[0].x) + 20;
} else {
tooltipLeft = svgLeft + $$.getCurrentPaddingLeft(true) + $$.x(dataToShow[0].x) + 20;
tooltipRight = tooltipLeft + tWidth;
chartRight = svgLeft + $$.currentWidth - $$.getCurrentPaddingRight();
tooltipTop = mouse[1] + 15;
}
if (tooltipRight > chartRight) {
// 20 is needed for Firefox to keep tooletip width
tooltipLeft -= tooltipRight - chartRight + 20;
}
if (tooltipTop + tHeight > $$.currentHeight) {
tooltipTop -= tHeight + 30;
}
}
if (tooltipTop < 0) {
tooltipTop = 0;
}
return {top: tooltipTop, left: tooltipLeft};
};
c3_chart_internal_fn.showTooltip = function (selectedData, element) {
var $$ = this, config = $$.config;
var tWidth, tHeight, position;
var forArc = $$.hasArcType(),
dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }),
positionFunction = config.tooltip_position || c3_chart_internal_fn.tooltipPosition;
if (dataToShow.length === 0 || !config.tooltip_show) {
return;
}
$$.tooltip.html(config.tooltip_contents.call($$, selectedData, $$.axis.getXAxisTickFormat(), $$.getYFormat(forArc), $$.color)).style("display", "block");
// Get tooltip dimensions
tWidth = $$.tooltip.property('offsetWidth');
tHeight = $$.tooltip.property('offsetHeight');
position = positionFunction.call(this, dataToShow, tWidth, tHeight, element);
// Set tooltip
$$.tooltip
.style("top", position.top + "px")
.style("left", position.left + 'px');
};
c3_chart_internal_fn.hideTooltip = function () {
this.tooltip.style("display", "none");
};
c3_chart_internal_fn.initLegend = function () {
var $$ = this;
$$.legendItemTextBox = {};
$$.legendHasRendered = false;
$$.legend = $$.svg.append("g").attr("transform", $$.getTranslate('legend'));
if (!$$.config.legend_show) {
$$.legend.style('visibility', 'hidden');
$$.hiddenLegendIds = $$.mapToIds($$.data.targets);
return;
}
// MEMO: call here to update legend box and tranlate for all
// MEMO: translate will be upated by this, so transform not needed in updateLegend()
$$.updateLegendWithDefaults();
};
c3_chart_internal_fn.updateLegendWithDefaults = function () {
var $$ = this;
$$.updateLegend($$.mapToIds($$.data.targets), {withTransform: false, withTransitionForTransform: false, withTransition: false});
};
c3_chart_internal_fn.updateSizeForLegend = function (legendHeight, legendWidth) {
var $$ = this, config = $$.config, insetLegendPosition = {
top: $$.isLegendTop ? $$.getCurrentPaddingTop() + config.legend_inset_y + 5.5 : $$.currentHeight - legendHeight - $$.getCurrentPaddingBottom() - config.legend_inset_y,
left: $$.isLegendLeft ? $$.getCurrentPaddingLeft() + config.legend_inset_x + 0.5 : $$.currentWidth - legendWidth - $$.getCurrentPaddingRight() - config.legend_inset_x + 0.5
};
$$.margin3 = {
top: $$.isLegendRight ? 0 : $$.isLegendInset ? insetLegendPosition.top : $$.currentHeight - legendHeight,
right: NaN,
bottom: 0,
left: $$.isLegendRight ? $$.currentWidth - legendWidth : $$.isLegendInset ? insetLegendPosition.left : 0
};
};
c3_chart_internal_fn.transformLegend = function (withTransition) {
var $$ = this;
(withTransition ? $$.legend.transition() : $$.legend).attr("transform", $$.getTranslate('legend'));
};
c3_chart_internal_fn.updateLegendStep = function (step) {
this.legendStep = step;
};
c3_chart_internal_fn.updateLegendItemWidth = function (w) {
this.legendItemWidth = w;
};
c3_chart_internal_fn.updateLegendItemHeight = function (h) {
this.legendItemHeight = h;
};
c3_chart_internal_fn.getLegendWidth = function () {
var $$ = this;
return $$.config.legend_show ? $$.isLegendRight || $$.isLegendInset ? $$.legendItemWidth * ($$.legendStep + 1) : $$.currentWidth : 0;
};
c3_chart_internal_fn.getLegendHeight = function () {
var $$ = this, h = 0;
if ($$.config.legend_show) {
if ($$.isLegendRight) {
h = $$.currentHeight;
} else {
h = Math.max(20, $$.legendItemHeight) * ($$.legendStep + 1);
}
}
return h;
};
c3_chart_internal_fn.opacityForLegend = function (legendItem) {
return legendItem.classed(CLASS.legendItemHidden) ? null : 1;
};
c3_chart_internal_fn.opacityForUnfocusedLegend = function (legendItem) {
return legendItem.classed(CLASS.legendItemHidden) ? null : 0.3;
};
c3_chart_internal_fn.toggleFocusLegend = function (targetIds, focus) {
var $$ = this;
targetIds = $$.mapToTargetIds(targetIds);
$$.legend.selectAll('.' + CLASS.legendItem)
.filter(function (id) { return targetIds.indexOf(id) >= 0; })
.classed(CLASS.legendItemFocused, focus)
.transition().duration(100)
.style('opacity', function () {
var opacity = focus ? $$.opacityForLegend : $$.opacityForUnfocusedLegend;
return opacity.call($$, $$.d3.select(this));
});
};
c3_chart_internal_fn.revertLegend = function () {
var $$ = this, d3 = $$.d3;
$$.legend.selectAll('.' + CLASS.legendItem)
.classed(CLASS.legendItemFocused, false)
.transition().duration(100)
.style('opacity', function () { return $$.opacityForLegend(d3.select(this)); });
};
c3_chart_internal_fn.showLegend = function (targetIds) {
var $$ = this, config = $$.config;
if (!config.legend_show) {
config.legend_show = true;
$$.legend.style('visibility', 'visible');
if (!$$.legendHasRendered) {
$$.updateLegendWithDefaults();
}
}
$$.removeHiddenLegendIds(targetIds);
$$.legend.selectAll($$.selectorLegends(targetIds))
.style('visibility', 'visible')
.transition()
.style('opacity', function () { return $$.opacityForLegend($$.d3.select(this)); });
};
c3_chart_internal_fn.hideLegend = function (targetIds) {
var $$ = this, config = $$.config;
if (config.legend_show && isEmpty(targetIds)) {
config.legend_show = false;
$$.legend.style('visibility', 'hidden');
}
$$.addHiddenLegendIds(targetIds);
$$.legend.selectAll($$.selectorLegends(targetIds))
.style('opacity', 0)
.style('visibility', 'hidden');
};
c3_chart_internal_fn.clearLegendItemTextBoxCache = function () {
this.legendItemTextBox = {};
};
c3_chart_internal_fn.updateLegend = function (targetIds, options, transitions) {
var $$ = this, config = $$.config;
var xForLegend, xForLegendText, xForLegendRect, yForLegend, yForLegendText, yForLegendRect;
var paddingTop = 4, paddingRight = 10, maxWidth = 0, maxHeight = 0, posMin = 10, tileWidth = 15;
var l, totalLength = 0, offsets = {}, widths = {}, heights = {}, margins = [0], steps = {}, step = 0;
var withTransition, withTransitionForTransform;
var texts, rects, tiles, background;
options = options || {};
withTransition = getOption(options, "withTransition", true);
withTransitionForTransform = getOption(options, "withTransitionForTransform", true);
function getTextBox(textElement, id) {
if (!$$.legendItemTextBox[id]) {
$$.legendItemTextBox[id] = $$.getTextRect(textElement.textContent, CLASS.legendItem);
}
return $$.legendItemTextBox[id];
}
function updatePositions(textElement, id, index) {
var reset = index === 0, isLast = index === targetIds.length - 1,
box = getTextBox(textElement, id),
itemWidth = box.width + tileWidth + (isLast && !($$.isLegendRight || $$.isLegendInset) ? 0 : paddingRight),
itemHeight = box.height + paddingTop,
itemLength = $$.isLegendRight || $$.isLegendInset ? itemHeight : itemWidth,
areaLength = $$.isLegendRight || $$.isLegendInset ? $$.getLegendHeight() : $$.getLegendWidth(),
margin, maxLength;
// MEMO: care about condifion of step, totalLength
function updateValues(id, withoutStep) {
if (!withoutStep) {
margin = (areaLength - totalLength - itemLength) / 2;
if (margin < posMin) {
margin = (areaLength - itemLength) / 2;
totalLength = 0;
step++;
}
}
steps[id] = step;
margins[step] = $$.isLegendInset ? 10 : margin;
offsets[id] = totalLength;
totalLength += itemLength;
}
if (reset) {
totalLength = 0;
step = 0;
maxWidth = 0;
maxHeight = 0;
}
if (config.legend_show && !$$.isLegendToShow(id)) {
widths[id] = heights[id] = steps[id] = offsets[id] = 0;
return;
}
widths[id] = itemWidth;
heights[id] = itemHeight;
if (!maxWidth || itemWidth >= maxWidth) { maxWidth = itemWidth; }
if (!maxHeight || itemHeight >= maxHeight) { maxHeight = itemHeight; }
maxLength = $$.isLegendRight || $$.isLegendInset ? maxHeight : maxWidth;
if (config.legend_equally) {
Object.keys(widths).forEach(function (id) { widths[id] = maxWidth; });
Object.keys(heights).forEach(function (id) { heights[id] = maxHeight; });
margin = (areaLength - maxLength * targetIds.length) / 2;
if (margin < posMin) {
totalLength = 0;
step = 0;
targetIds.forEach(function (id) { updateValues(id); });
}
else {
updateValues(id, true);
}
} else {
updateValues(id);
}
}
if ($$.isLegendInset) {
step = config.legend_inset_step ? config.legend_inset_step : targetIds.length;
$$.updateLegendStep(step);
}
if ($$.isLegendRight) {
xForLegend = function (id) { return maxWidth * steps[id]; };
yForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
} else if ($$.isLegendInset) {
xForLegend = function (id) { return maxWidth * steps[id] + 10; };
yForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
} else {
xForLegend = function (id) { return margins[steps[id]] + offsets[id]; };
yForLegend = function (id) { return maxHeight * steps[id]; };
}
xForLegendText = function (id, i) { return xForLegend(id, i) + 14; };
yForLegendText = function (id, i) { return yForLegend(id, i) + 9; };
xForLegendRect = function (id, i) { return xForLegend(id, i); };
yForLegendRect = function (id, i) { return yForLegend(id, i) - 5; };
// Define g for legend area
l = $$.legend.selectAll('.' + CLASS.legendItem)
.data(targetIds)
.enter().append('g')
.attr('class', function (id) { return $$.generateClass(CLASS.legendItem, id); })
.style('visibility', function (id) { return $$.isLegendToShow(id) ? 'visible' : 'hidden'; })
.style('cursor', 'pointer')
.on('click', function (id) {
if (config.legend_item_onclick) {
config.legend_item_onclick.call($$, id);
} else {
if ($$.d3.event.altKey) {
$$.api.hide();
$$.api.show(id);
} else {
$$.api.toggle(id);
$$.isTargetToShow(id) ? $$.api.focus(id) : $$.api.revert();
}
}
})
.on('mouseover', function (id) {
$$.d3.select(this).classed(CLASS.legendItemFocused, true);
if (!$$.transiting && $$.isTargetToShow(id)) {
$$.api.focus(id);
}
if (config.legend_item_onmouseover) {
config.legend_item_onmouseover.call($$, id);
}
})
.on('mouseout', function (id) {
$$.d3.select(this).classed(CLASS.legendItemFocused, false);
$$.api.revert();
if (config.legend_item_onmouseout) {
config.legend_item_onmouseout.call($$, id);
}
});
l.append('text')
.text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; })
.each(function (id, i) { updatePositions(this, id, i); })
.style("pointer-events", "none")
.attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendText : -200)
.attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendText);
l.append('rect')
.attr("class", CLASS.legendItemEvent)
.style('fill-opacity', 0)
.attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendRect : -200)
.attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegendRect);
l.append('rect')
.attr("class", CLASS.legendItemTile)
.style("pointer-events", "none")
.style('fill', $$.color)
.attr('x', $$.isLegendRight || $$.isLegendInset ? xForLegendText : -200)
.attr('y', $$.isLegendRight || $$.isLegendInset ? -200 : yForLegend)
.attr('width', 10)
.attr('height', 10);
// Set background for inset legend
background = $$.legend.select('.' + CLASS.legendBackground + ' rect');
if ($$.isLegendInset && maxWidth > 0 && background.size() === 0) {
background = $$.legend.insert('g', '.' + CLASS.legendItem)
.attr("class", CLASS.legendBackground)
.append('rect');
}
texts = $$.legend.selectAll('text')
.data(targetIds)
.text(function (id) { return isDefined(config.data_names[id]) ? config.data_names[id] : id; }) // MEMO: needed for update
.each(function (id, i) { updatePositions(this, id, i); });
(withTransition ? texts.transition() : texts)
.attr('x', xForLegendText)
.attr('y', yForLegendText);
rects = $$.legend.selectAll('rect.' + CLASS.legendItemEvent)
.data(targetIds);
(withTransition ? rects.transition() : rects)
.attr('width', function (id) { return widths[id]; })
.attr('height', function (id) { return heights[id]; })
.attr('x', xForLegendRect)
.attr('y', yForLegendRect);
tiles = $$.legend.selectAll('rect.' + CLASS.legendItemTile)
.data(targetIds);
(withTransition ? tiles.transition() : tiles)
.style('fill', $$.color)
.attr('x', xForLegend)
.attr('y', yForLegend);
if (background) {
(withTransition ? background.transition() : background)
.attr('height', $$.getLegendHeight() - 12)
.attr('width', maxWidth * (step + 1) + 10);
}
// toggle legend state
$$.legend.selectAll('.' + CLASS.legendItem)
.classed(CLASS.legendItemHidden, function (id) { return !$$.isTargetToShow(id); });
// Update all to reflect change of legend
$$.updateLegendItemWidth(maxWidth);
$$.updateLegendItemHeight(maxHeight);
$$.updateLegendStep(step);
// Update size and scale
$$.updateSizes();
$$.updateScales();
$$.updateSvgSize();
// Update g positions
$$.transformAll(withTransitionForTransform, transitions);
$$.legendHasRendered = true;
};
function Axis(owner) {
API.call(this, owner);
}
inherit(API, Axis);
Axis.prototype.init = function init() {
var $$ = this.owner, config = $$.config, main = $$.main;
$$.axes.x = main.append("g")
.attr("class", CLASS.axis + ' ' + CLASS.axisX)
.attr("clip-path", $$.clipPathForXAxis)
.attr("transform", $$.getTranslate('x'))
.style("visibility", config.axis_x_show ? 'visible' : 'hidden');
$$.axes.x.append("text")
.attr("class", CLASS.axisXLabel)
.attr("transform", config.axis_rotated ? "rotate(-90)" : "")
.style("text-anchor", this.textAnchorForXAxisLabel.bind(this));
$$.axes.y = main.append("g")
.attr("class", CLASS.axis + ' ' + CLASS.axisY)
.attr("clip-path", config.axis_y_inner ? "" : $$.clipPathForYAxis)
.attr("transform", $$.getTranslate('y'))
.style("visibility", config.axis_y_show ? 'visible' : 'hidden');
$$.axes.y.append("text")
.attr("class", CLASS.axisYLabel)
.attr("transform", config.axis_rotated ? "" : "rotate(-90)")
.style("text-anchor", this.textAnchorForYAxisLabel.bind(this));
$$.axes.y2 = main.append("g")
.attr("class", CLASS.axis + ' ' + CLASS.axisY2)
// clip-path?
.attr("transform", $$.getTranslate('y2'))
.style("visibility", config.axis_y2_show ? 'visible' : 'hidden');
$$.axes.y2.append("text")
.attr("class", CLASS.axisY2Label)
.attr("transform", config.axis_rotated ? "" : "rotate(-90)")
.style("text-anchor", this.textAnchorForY2AxisLabel.bind(this));
};
Axis.prototype.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
var $$ = this.owner, config = $$.config,
axisParams = {
isCategory: $$.isCategorized(),
withOuterTick: withOuterTick,
tickMultiline: config.axis_x_tick_multiline,
tickWidth: config.axis_x_tick_width,
tickTextRotate: withoutRotateTickText ? 0 : config.axis_x_tick_rotate,
withoutTransition: withoutTransition,
},
axis = c3_axis($$.d3, axisParams).scale(scale).orient(orient);
if ($$.isTimeSeries() && tickValues) {
tickValues = tickValues.map(function (v) { return $$.parseDate(v); });
}
// Set tick
axis.tickFormat(tickFormat).tickValues(tickValues);
if ($$.isCategorized()) {
axis.tickCentered(config.axis_x_tick_centered);
if (isEmpty(config.axis_x_tick_culling)) {
config.axis_x_tick_culling = false;
}
}
return axis;
};
Axis.prototype.updateXAxisTickValues = function updateXAxisTickValues(targets, axis) {
var $$ = this.owner, config = $$.config, tickValues;
if (config.axis_x_tick_fit || config.axis_x_tick_count) {
tickValues = this.generateTickValues($$.mapTargetsToUniqueXs(targets), config.axis_x_tick_count, $$.isTimeSeries());
}
if (axis) {
axis.tickValues(tickValues);
} else {
$$.xAxis.tickValues(tickValues);
$$.subXAxis.tickValues(tickValues);
}
return tickValues;
};
Axis.prototype.getYAxis = function getYAxis(scale, orient, tickFormat, tickValues, withOuterTick) {
var axisParams = {withOuterTick: withOuterTick},
$$ = this.owner,
d3 = $$.d3,
config = $$.config,
axis = c3_axis(d3, axisParams).scale(scale).orient(orient).tickFormat(tickFormat);
if ($$.isTimeSeriesY()) {
axis.ticks(d3.time[config.axis_y_tick_time_value], config.axis_y_tick_time_interval);
} else {
axis.tickValues(tickValues);
}
return axis;
};
Axis.prototype.getId = function getId(id) {
var config = this.owner.config;
return id in config.data_axes ? config.data_axes[id] : 'y';
};
Axis.prototype.getXAxisTickFormat = function getXAxisTickFormat() {
var $$ = this.owner, config = $$.config,
format = $$.isTimeSeries() ? $$.defaultAxisTimeFormat : $$.isCategorized() ? $$.categoryName : function (v) { return v < 0 ? v.toFixed(0) : v; };
if (config.axis_x_tick_format) {
if (isFunction(config.axis_x_tick_format)) {
format = config.axis_x_tick_format;
} else if ($$.isTimeSeries()) {
format = function (date) {
return date ? $$.axisTimeFormat(config.axis_x_tick_format)(date) : "";
};
}
}
return isFunction(format) ? function (v) { return format.call($$, v); } : format;
};
Axis.prototype.getTickValues = function getTickValues(tickValues, axis) {
return tickValues ? tickValues : axis ? axis.tickValues() : undefined;
};
Axis.prototype.getXAxisTickValues = function getXAxisTickValues() {
return this.getTickValues(this.owner.config.axis_x_tick_values, this.owner.xAxis);
};
Axis.prototype.getYAxisTickValues = function getYAxisTickValues() {
return this.getTickValues(this.owner.config.axis_y_tick_values, this.owner.yAxis);
};
Axis.prototype.getY2AxisTickValues = function getY2AxisTickValues() {
return this.getTickValues(this.owner.config.axis_y2_tick_values, this.owner.y2Axis);
};
Axis.prototype.getLabelOptionByAxisId = function getLabelOptionByAxisId(axisId) {
var $$ = this.owner, config = $$.config, option;
if (axisId === 'y') {
option = config.axis_y_label;
} else if (axisId === 'y2') {
option = config.axis_y2_label;
} else if (axisId === 'x') {
option = config.axis_x_label;
}
return option;
};
Axis.prototype.getLabelText = function getLabelText(axisId) {
var option = this.getLabelOptionByAxisId(axisId);
return isString(option) ? option : option ? option.text : null;
};
Axis.prototype.setLabelText = function setLabelText(axisId, text) {
var $$ = this.owner, config = $$.config,
option = this.getLabelOptionByAxisId(axisId);
if (isString(option)) {
if (axisId === 'y') {
config.axis_y_label = text;
} else if (axisId === 'y2') {
config.axis_y2_label = text;
} else if (axisId === 'x') {
config.axis_x_label = text;
}
} else if (option) {
option.text = text;
}
};
Axis.prototype.getLabelPosition = function getLabelPosition(axisId, defaultPosition) {
var option = this.getLabelOptionByAxisId(axisId),
position = (option && typeof option === 'object' && option.position) ? option.position : defaultPosition;
return {
isInner: position.indexOf('inner') >= 0,
isOuter: position.indexOf('outer') >= 0,
isLeft: position.indexOf('left') >= 0,
isCenter: position.indexOf('center') >= 0,
isRight: position.indexOf('right') >= 0,
isTop: position.indexOf('top') >= 0,
isMiddle: position.indexOf('middle') >= 0,
isBottom: position.indexOf('bottom') >= 0
};
};
Axis.prototype.getXAxisLabelPosition = function getXAxisLabelPosition() {
return this.getLabelPosition('x', this.owner.config.axis_rotated ? 'inner-top' : 'inner-right');
};
Axis.prototype.getYAxisLabelPosition = function getYAxisLabelPosition() {
return this.getLabelPosition('y', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
};
Axis.prototype.getY2AxisLabelPosition = function getY2AxisLabelPosition() {
return this.getLabelPosition('y2', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
};
Axis.prototype.getLabelPositionById = function getLabelPositionById(id) {
return id === 'y2' ? this.getY2AxisLabelPosition() : id === 'y' ? this.getYAxisLabelPosition() : this.getXAxisLabelPosition();
};
Axis.prototype.textForXAxisLabel = function textForXAxisLabel() {
return this.getLabelText('x');
};
Axis.prototype.textForYAxisLabel = function textForYAxisLabel() {
return this.getLabelText('y');
};
Axis.prototype.textForY2AxisLabel = function textForY2AxisLabel() {
return this.getLabelText('y2');
};
Axis.prototype.xForAxisLabel = function xForAxisLabel(forHorizontal, position) {
var $$ = this.owner;
if (forHorizontal) {
return position.isLeft ? 0 : position.isCenter ? $$.width / 2 : $$.width;
} else {
return position.isBottom ? -$$.height : position.isMiddle ? -$$.height / 2 : 0;
}
};
Axis.prototype.dxForAxisLabel = function dxForAxisLabel(forHorizontal, position) {
if (forHorizontal) {
return position.isLeft ? "0.5em" : position.isRight ? "-0.5em" : "0";
} else {
return position.isTop ? "-0.5em" : position.isBottom ? "0.5em" : "0";
}
};
Axis.prototype.textAnchorForAxisLabel = function textAnchorForAxisLabel(forHorizontal, position) {
if (forHorizontal) {
return position.isLeft ? 'start' : position.isCenter ? 'middle' : 'end';
} else {
return position.isBottom ? 'start' : position.isMiddle ? 'middle' : 'end';
}
};
Axis.prototype.xForXAxisLabel = function xForXAxisLabel() {
return this.xForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
};
Axis.prototype.xForYAxisLabel = function xForYAxisLabel() {
return this.xForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
};
Axis.prototype.xForY2AxisLabel = function xForY2AxisLabel() {
return this.xForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
};
Axis.prototype.dxForXAxisLabel = function dxForXAxisLabel() {
return this.dxForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
};
Axis.prototype.dxForYAxisLabel = function dxForYAxisLabel() {
return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
};
Axis.prototype.dxForY2AxisLabel = function dxForY2AxisLabel() {
return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
};
Axis.prototype.dyForXAxisLabel = function dyForXAxisLabel() {
var $$ = this.owner, config = $$.config,
position = this.getXAxisLabelPosition();
if (config.axis_rotated) {
return position.isInner ? "1.2em" : -25 - this.getMaxTickWidth('x');
} else {
return position.isInner ? "-0.5em" : config.axis_x_height ? config.axis_x_height - 10 : "3em";
}
};
Axis.prototype.dyForYAxisLabel = function dyForYAxisLabel() {
var $$ = this.owner,
position = this.getYAxisLabelPosition();
if ($$.config.axis_rotated) {
return position.isInner ? "-0.5em" : "3em";
} else {
return position.isInner ? "1.2em" : -10 - ($$.config.axis_y_inner ? 0 : (this.getMaxTickWidth('y') + 10));
}
};
Axis.prototype.dyForY2AxisLabel = function dyForY2AxisLabel() {
var $$ = this.owner,
position = this.getY2AxisLabelPosition();
if ($$.config.axis_rotated) {
return position.isInner ? "1.2em" : "-2.2em";
} else {
return position.isInner ? "-0.5em" : 15 + ($$.config.axis_y2_inner ? 0 : (this.getMaxTickWidth('y2') + 15));
}
};
Axis.prototype.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel(!$$.config.axis_rotated, this.getXAxisLabelPosition());
};
Axis.prototype.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getYAxisLabelPosition());
};
Axis.prototype.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() {
var $$ = this.owner;
return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getY2AxisLabelPosition());
};
Axis.prototype.getMaxTickWidth = function getMaxTickWidth(id, withoutRecompute) {
var $$ = this.owner, config = $$.config,
maxWidth = 0, targetsToShow, scale, axis, dummy, svg;
if (withoutRecompute && $$.currentMaxTickWidths[id]) {
return $$.currentMaxTickWidths[id];
}
if ($$.svg) {
targetsToShow = $$.filterTargetsToShow($$.data.targets);
if (id === 'y') {
scale = $$.y.copy().domain($$.getYDomain(targetsToShow, 'y'));
axis = this.getYAxis(scale, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues);
} else if (id === 'y2') {
scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2'));
axis = this.getYAxis(scale, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues);
} else {
scale = $$.x.copy().domain($$.getXDomain(targetsToShow));
axis = this.getXAxis(scale, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, false, true, true);
this.updateXAxisTickValues(targetsToShow, axis);
}
dummy = $$.d3.select('body').append('div').classed('c3', true);
svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
svg.append('g').call(axis).each(function () {
$$.d3.select(this).selectAll('text').each(function () {
var box = this.getBoundingClientRect();
if (maxWidth < box.width) { maxWidth = box.width; }
});
dummy.remove();
});
}
$$.currentMaxTickWidths[id] = maxWidth <= 0 ? $$.currentMaxTickWidths[id] : maxWidth;
return $$.currentMaxTickWidths[id];
};
Axis.prototype.updateLabels = function updateLabels(withTransition) {
var $$ = this.owner;
var axisXLabel = $$.main.select('.' + CLASS.axisX + ' .' + CLASS.axisXLabel),
axisYLabel = $$.main.select('.' + CLASS.axisY + ' .' + CLASS.axisYLabel),
axisY2Label = $$.main.select('.' + CLASS.axisY2 + ' .' + CLASS.axisY2Label);
(withTransition ? axisXLabel.transition() : axisXLabel)
.attr("x", this.xForXAxisLabel.bind(this))
.attr("dx", this.dxForXAxisLabel.bind(this))
.attr("dy", this.dyForXAxisLabel.bind(this))
.text(this.textForXAxisLabel.bind(this));
(withTransition ? axisYLabel.transition() : axisYLabel)
.attr("x", this.xForYAxisLabel.bind(this))
.attr("dx", this.dxForYAxisLabel.bind(this))
.attr("dy", this.dyForYAxisLabel.bind(this))
.text(this.textForYAxisLabel.bind(this));
(withTransition ? axisY2Label.transition() : axisY2Label)
.attr("x", this.xForY2AxisLabel.bind(this))
.attr("dx", this.dxForY2AxisLabel.bind(this))
.attr("dy", this.dyForY2AxisLabel.bind(this))
.text(this.textForY2AxisLabel.bind(this));
};
Axis.prototype.getPadding = function getPadding(padding, key, defaultValue, domainLength) {
if (!isValue(padding[key])) {
return defaultValue;
}
if (padding.unit === 'ratio') {
return padding[key] * domainLength;
}
// assume padding is pixels if unit is not specified
return this.convertPixelsToAxisPadding(padding[key], domainLength);
};
Axis.prototype.convertPixelsToAxisPadding = function convertPixelsToAxisPadding(pixels, domainLength) {
var $$ = this.owner,
length = $$.config.axis_rotated ? $$.width : $$.height;
return domainLength * (pixels / length);
};
Axis.prototype.generateTickValues = function generateTickValues(values, tickCount, forTimeSeries) {
var tickValues = values, targetCount, start, end, count, interval, i, tickValue;
if (tickCount) {
targetCount = isFunction(tickCount) ? tickCount() : tickCount;
// compute ticks according to tickCount
if (targetCount === 1) {
tickValues = [values[0]];
} else if (targetCount === 2) {
tickValues = [values[0], values[values.length - 1]];
} else if (targetCount > 2) {
count = targetCount - 2;
start = values[0];
end = values[values.length - 1];
interval = (end - start) / (count + 1);
// re-construct unique values
tickValues = [start];
for (i = 0; i < count; i++) {
tickValue = +start + interval * (i + 1);
tickValues.push(forTimeSeries ? new Date(tickValue) : tickValue);
}
tickValues.push(end);
}
}
if (!forTimeSeries) { tickValues = tickValues.sort(function (a, b) { return a - b; }); }
return tickValues;
};
Axis.prototype.generateTransitions = function generateTransitions(duration) {
var $$ = this.owner, axes = $$.axes;
return {
axisX: duration ? axes.x.transition().duration(duration) : axes.x,
axisY: duration ? axes.y.transition().duration(duration) : axes.y,
axisY2: duration ? axes.y2.transition().duration(duration) : axes.y2,
axisSubX: duration ? axes.subx.transition().duration(duration) : axes.subx
};
};
Axis.prototype.redraw = function redraw(transitions, isHidden) {
var $$ = this.owner;
$$.axes.x.style("opacity", isHidden ? 0 : 1);
$$.axes.y.style("opacity", isHidden ? 0 : 1);
$$.axes.y2.style("opacity", isHidden ? 0 : 1);
$$.axes.subx.style("opacity", isHidden ? 0 : 1);
transitions.axisX.call($$.xAxis);
transitions.axisY.call($$.yAxis);
transitions.axisY2.call($$.y2Axis);
transitions.axisSubX.call($$.subXAxis);
};
c3_chart_internal_fn.getClipPath = function (id) {
var isIE9 = window.navigator.appVersion.toLowerCase().indexOf("msie 9.") >= 0;
return "url(" + (isIE9 ? "" : document.URL.split('#')[0]) + "#" + id + ")";
};
c3_chart_internal_fn.appendClip = function (parent, id) {
return parent.append("clipPath").attr("id", id).append("rect");
};
c3_chart_internal_fn.getAxisClipX = function (forHorizontal) {
// axis line width + padding for left
var left = Math.max(30, this.margin.left);
return forHorizontal ? -(1 + left) : -(left - 1);
};
c3_chart_internal_fn.getAxisClipY = function (forHorizontal) {
return forHorizontal ? -20 : -this.margin.top;
};
c3_chart_internal_fn.getXAxisClipX = function () {
var $$ = this;
return $$.getAxisClipX(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getXAxisClipY = function () {
var $$ = this;
return $$.getAxisClipY(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipX = function () {
var $$ = this;
return $$.config.axis_y_inner ? -1 : $$.getAxisClipX($$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipY = function () {
var $$ = this;
return $$.getAxisClipY($$.config.axis_rotated);
};
c3_chart_internal_fn.getAxisClipWidth = function (forHorizontal) {
var $$ = this,
left = Math.max(30, $$.margin.left),
right = Math.max(30, $$.margin.right);
// width + axis line width + padding for left/right
return forHorizontal ? $$.width + 2 + left + right : $$.margin.left + 20;
};
c3_chart_internal_fn.getAxisClipHeight = function (forHorizontal) {
// less than 20 is not enough to show the axis label 'outer' without legend
return (forHorizontal ? this.margin.bottom : (this.margin.top + this.height)) + 20;
};
c3_chart_internal_fn.getXAxisClipWidth = function () {
var $$ = this;
return $$.getAxisClipWidth(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getXAxisClipHeight = function () {
var $$ = this;
return $$.getAxisClipHeight(!$$.config.axis_rotated);
};
c3_chart_internal_fn.getYAxisClipWidth = function () {
var $$ = this;
return $$.getAxisClipWidth($$.config.axis_rotated) + ($$.config.axis_y_inner ? 20 : 0);
};
c3_chart_internal_fn.getYAxisClipHeight = function () {
var $$ = this;
return $$.getAxisClipHeight($$.config.axis_rotated);
};
c3_chart_internal_fn.initPie = function () {
var $$ = this, d3 = $$.d3, config = $$.config;
$$.pie = d3.layout.pie().value(function (d) {
return d.values.reduce(function (a, b) { return a + b.value; }, 0);
});
if (!config.data_order) {
$$.pie.sort(null);
}
};
c3_chart_internal_fn.updateRadius = function () {
var $$ = this, config = $$.config,
w = config.gauge_width || config.donut_width;
$$.radiusExpanded = Math.min($$.arcWidth, $$.arcHeight) / 2;
$$.radius = $$.radiusExpanded * 0.95;
$$.innerRadiusRatio = w ? ($$.radius - w) / $$.radius : 0.6;
$$.innerRadius = $$.hasType('donut') || $$.hasType('gauge') ? $$.radius * $$.innerRadiusRatio : 0;
};
c3_chart_internal_fn.updateArc = function () {
var $$ = this;
$$.svgArc = $$.getSvgArc();
$$.svgArcExpanded = $$.getSvgArcExpanded();
$$.svgArcExpandedSub = $$.getSvgArcExpanded(0.98);
};
c3_chart_internal_fn.updateAngle = function (d) {
var $$ = this, config = $$.config,
found = false, index = 0,
gMin = config.gauge_min, gMax = config.gauge_max, gTic, gValue;
$$.pie($$.filterTargetsToShow($$.data.targets)).forEach(function (t) {
if (! found && t.data.id === d.data.id) {
found = true;
d = t;
d.index = index;
}
index++;
});
if (isNaN(d.startAngle)) {
d.startAngle = 0;
}
if (isNaN(d.endAngle)) {
d.endAngle = d.startAngle;
}
if ($$.isGaugeType(d.data)) {
gTic = (Math.PI) / (gMax - gMin);
gValue = d.value < gMin ? 0 : d.value < gMax ? d.value - gMin : (gMax - gMin);
d.startAngle = -1 * (Math.PI / 2);
d.endAngle = d.startAngle + gTic * gValue;
}
return found ? d : null;
};
c3_chart_internal_fn.getSvgArc = function () {
var $$ = this,
arc = $$.d3.svg.arc().outerRadius($$.radius).innerRadius($$.innerRadius),
newArc = function (d, withoutUpdate) {
var updated;
if (withoutUpdate) { return arc(d); } // for interpolate
updated = $$.updateAngle(d);
return updated ? arc(updated) : "M 0 0";
};
// TODO: extends all function
newArc.centroid = arc.centroid;
return newArc;
};
c3_chart_internal_fn.getSvgArcExpanded = function (rate) {
var $$ = this,
arc = $$.d3.svg.arc().outerRadius($$.radiusExpanded * (rate ? rate : 1)).innerRadius($$.innerRadius);
return function (d) {
var updated = $$.updateAngle(d);
return updated ? arc(updated) : "M 0 0";
};
};
c3_chart_internal_fn.getArc = function (d, withoutUpdate, force) {
return force || this.isArcType(d.data) ? this.svgArc(d, withoutUpdate) : "M 0 0";
};
c3_chart_internal_fn.transformForArcLabel = function (d) {
var $$ = this,
updated = $$.updateAngle(d), c, x, y, h, ratio, translate = "";
if (updated && !$$.hasType('gauge')) {
c = this.svgArc.centroid(updated);
x = isNaN(c[0]) ? 0 : c[0];
y = isNaN(c[1]) ? 0 : c[1];
h = Math.sqrt(x * x + y * y);
// TODO: ratio should be an option?
ratio = $$.radius && h ? (36 / $$.radius > 0.375 ? 1.175 - 36 / $$.radius : 0.8) * $$.radius / h : 0;
translate = "translate(" + (x * ratio) + ',' + (y * ratio) + ")";
}
return translate;
};
c3_chart_internal_fn.getArcRatio = function (d) {
var $$ = this,
whole = $$.hasType('gauge') ? Math.PI : (Math.PI * 2);
return d ? (d.endAngle - d.startAngle) / whole : null;
};
c3_chart_internal_fn.convertToArcData = function (d) {
return this.addName({
id: d.data.id,
value: d.value,
ratio: this.getArcRatio(d),
index: d.index
});
};
c3_chart_internal_fn.textForArcLabel = function (d) {
var $$ = this,
updated, value, ratio, id, format;
if (! $$.shouldShowArcLabel()) { return ""; }
updated = $$.updateAngle(d);
value = updated ? updated.value : null;
ratio = $$.getArcRatio(updated);
id = d.data.id;
if (! $$.hasType('gauge') && ! $$.meetsArcLabelThreshold(ratio)) { return ""; }
format = $$.getArcLabelFormat();
return format ? format(value, ratio, id) : $$.defaultArcValueFormat(value, ratio);
};
c3_chart_internal_fn.expandArc = function (targetIds) {
var $$ = this, interval;
// MEMO: avoid to cancel transition
if ($$.transiting) {
interval = window.setInterval(function () {
if (!$$.transiting) {
window.clearInterval(interval);
if ($$.legend.selectAll('.c3-legend-item-focused').size() > 0) {
$$.expandArc(targetIds);
}
}
}, 10);
return;
}
targetIds = $$.mapToTargetIds(targetIds);
$$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).each(function (d) {
if (! $$.shouldExpand(d.data.id)) { return; }
$$.d3.select(this).selectAll('path')
.transition().duration(50)
.attr("d", $$.svgArcExpanded)
.transition().duration(100)
.attr("d", $$.svgArcExpandedSub)
.each(function (d) {
if ($$.isDonutType(d.data)) {
// callback here
}
});
});
};
c3_chart_internal_fn.unexpandArc = function (targetIds) {
var $$ = this;
if ($$.transiting) { return; }
targetIds = $$.mapToTargetIds(targetIds);
$$.svg.selectAll($$.selectorTargets(targetIds, '.' + CLASS.chartArc)).selectAll('path')
.transition().duration(50)
.attr("d", $$.svgArc);
$$.svg.selectAll('.' + CLASS.arc)
.style("opacity", 1);
};
c3_chart_internal_fn.shouldExpand = function (id) {
var $$ = this, config = $$.config;
return ($$.isDonutType(id) && config.donut_expand) || ($$.isGaugeType(id) && config.gauge_expand) || ($$.isPieType(id) && config.pie_expand);
};
c3_chart_internal_fn.shouldShowArcLabel = function () {
var $$ = this, config = $$.config, shouldShow = true;
if ($$.hasType('donut')) {
shouldShow = config.donut_label_show;
} else if ($$.hasType('pie')) {
shouldShow = config.pie_label_show;
}
// when gauge, always true
return shouldShow;
};
c3_chart_internal_fn.meetsArcLabelThreshold = function (ratio) {
var $$ = this, config = $$.config,
threshold = $$.hasType('donut') ? config.donut_label_threshold : config.pie_label_threshold;
return ratio >= threshold;
};
c3_chart_internal_fn.getArcLabelFormat = function () {
var $$ = this, config = $$.config,
format = config.pie_label_format;
if ($$.hasType('gauge')) {
format = config.gauge_label_format;
} else if ($$.hasType('donut')) {
format = config.donut_label_format;
}
return format;
};
c3_chart_internal_fn.getArcTitle = function () {
var $$ = this;
return $$.hasType('donut') ? $$.config.donut_title : "";
};
c3_chart_internal_fn.updateTargetsForArc = function (targets) {
var $$ = this, main = $$.main,
mainPieUpdate, mainPieEnter,
classChartArc = $$.classChartArc.bind($$),
classArcs = $$.classArcs.bind($$),
classFocus = $$.classFocus.bind($$);
mainPieUpdate = main.select('.' + CLASS.chartArcs).selectAll('.' + CLASS.chartArc)
.data($$.pie(targets))
.attr("class", function (d) { return classChartArc(d) + classFocus(d.data); });
mainPieEnter = mainPieUpdate.enter().append("g")
.attr("class", classChartArc);
mainPieEnter.append('g')
.attr('class', classArcs);
mainPieEnter.append("text")
.attr("dy", $$.hasType('gauge') ? "-.1em" : ".35em")
.style("opacity", 0)
.style("text-anchor", "middle")
.style("pointer-events", "none");
// MEMO: can not keep same color..., but not bad to update color in redraw
//mainPieUpdate.exit().remove();
};
c3_chart_internal_fn.initArc = function () {
var $$ = this;
$$.arcs = $$.main.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartArcs)
.attr("transform", $$.getTranslate('arc'));
$$.arcs.append('text')
.attr('class', CLASS.chartArcsTitle)
.style("text-anchor", "middle")
.text($$.getArcTitle());
};
c3_chart_internal_fn.redrawArc = function (duration, durationForExit, withTransform) {
var $$ = this, d3 = $$.d3, config = $$.config, main = $$.main,
mainArc;
mainArc = main.selectAll('.' + CLASS.arcs).selectAll('.' + CLASS.arc)
.data($$.arcData.bind($$));
mainArc.enter().append('path')
.attr("class", $$.classArc.bind($$))
.style("fill", function (d) { return $$.color(d.data); })
.style("cursor", function (d) { return config.interaction_enabled && config.data_selection_isselectable(d) ? "pointer" : null; })
.style("opacity", 0)
.each(function (d) {
if ($$.isGaugeType(d.data)) {
d.startAngle = d.endAngle = -1 * (Math.PI / 2);
}
this._current = d;
});
mainArc
.attr("transform", function (d) { return !$$.isGaugeType(d.data) && withTransform ? "scale(0)" : ""; })
.style("opacity", function (d) { return d === this._current ? 0 : 1; })
.on('mouseover', config.interaction_enabled ? function (d) {
var updated, arcData;
if ($$.transiting) { // skip while transiting
return;
}
updated = $$.updateAngle(d);
arcData = $$.convertToArcData(updated);
// transitions
$$.expandArc(updated.data.id);
$$.api.focus(updated.data.id);
$$.toggleFocusLegend(updated.data.id, true);
$$.config.data_onmouseover(arcData, this);
} : null)
.on('mousemove', config.interaction_enabled ? function (d) {
var updated = $$.updateAngle(d),
arcData = $$.convertToArcData(updated),
selectedData = [arcData];
$$.showTooltip(selectedData, this);
} : null)
.on('mouseout', config.interaction_enabled ? function (d) {
var updated, arcData;
if ($$.transiting) { // skip while transiting
return;
}
updated = $$.updateAngle(d);
arcData = $$.convertToArcData(updated);
// transitions
$$.unexpandArc(updated.data.id);
$$.api.revert();
$$.revertLegend();
$$.hideTooltip();
$$.config.data_onmouseout(arcData, this);
} : null)
.on('click', config.interaction_enabled ? function (d, i) {
var updated = $$.updateAngle(d),
arcData = $$.convertToArcData(updated);
if ($$.toggleShape) { $$.toggleShape(this, arcData, i); }
$$.config.data_onclick.call($$.api, arcData, this);
} : null)
.each(function () { $$.transiting = true; })
.transition().duration(duration)
.attrTween("d", function (d) {
var updated = $$.updateAngle(d), interpolate;
if (! updated) {
return function () { return "M 0 0"; };
}
// if (this._current === d) {
// this._current = {
// startAngle: Math.PI*2,
// endAngle: Math.PI*2,
// };
// }
if (isNaN(this._current.startAngle)) {
this._current.startAngle = 0;
}
if (isNaN(this._current.endAngle)) {
this._current.endAngle = this._current.startAngle;
}
interpolate = d3.interpolate(this._current, updated);
this._current = interpolate(0);
return function (t) {
var interpolated = interpolate(t);
interpolated.data = d.data; // data.id will be updated by interporator
return $$.getArc(interpolated, true);
};
})
.attr("transform", withTransform ? "scale(1)" : "")
.style("fill", function (d) {
return $$.levelColor ? $$.levelColor(d.data.values[0].value) : $$.color(d.data.id);
}) // Where gauge reading color would receive customization.
.style("opacity", 1)
.call($$.endall, function () {
$$.transiting = false;
});
mainArc.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
main.selectAll('.' + CLASS.chartArc).select('text')
.style("opacity", 0)
.attr('class', function (d) { return $$.isGaugeType(d.data) ? CLASS.gaugeValue : ''; })
.text($$.textForArcLabel.bind($$))
.attr("transform", $$.transformForArcLabel.bind($$))
.style('font-size', function (d) { return $$.isGaugeType(d.data) ? Math.round($$.radius / 5) + 'px' : ''; })
.transition().duration(duration)
.style("opacity", function (d) { return $$.isTargetToShow(d.data.id) && $$.isArcType(d.data) ? 1 : 0; });
main.select('.' + CLASS.chartArcsTitle)
.style("opacity", $$.hasType('donut') || $$.hasType('gauge') ? 1 : 0);
if ($$.hasType('gauge')) {
$$.arcs.select('.' + CLASS.chartArcsBackground)
.attr("d", function () {
var d = {
data: [{value: config.gauge_max}],
startAngle: -1 * (Math.PI / 2),
endAngle: Math.PI / 2
};
return $$.getArc(d, true, true);
});
$$.arcs.select('.' + CLASS.chartArcsGaugeUnit)
.attr("dy", ".75em")
.text(config.gauge_label_show ? config.gauge_units : '');
$$.arcs.select('.' + CLASS.chartArcsGaugeMin)
.attr("dx", -1 * ($$.innerRadius + (($$.radius - $$.innerRadius) / 2)) + "px")
.attr("dy", "1.2em")
.text(config.gauge_label_show ? config.gauge_min : '');
$$.arcs.select('.' + CLASS.chartArcsGaugeMax)
.attr("dx", $$.innerRadius + (($$.radius - $$.innerRadius) / 2) + "px")
.attr("dy", "1.2em")
.text(config.gauge_label_show ? config.gauge_max : '');
}
};
c3_chart_internal_fn.initGauge = function () {
var arcs = this.arcs;
if (this.hasType('gauge')) {
arcs.append('path')
.attr("class", CLASS.chartArcsBackground);
arcs.append("text")
.attr("class", CLASS.chartArcsGaugeUnit)
.style("text-anchor", "middle")
.style("pointer-events", "none");
arcs.append("text")
.attr("class", CLASS.chartArcsGaugeMin)
.style("text-anchor", "middle")
.style("pointer-events", "none");
arcs.append("text")
.attr("class", CLASS.chartArcsGaugeMax)
.style("text-anchor", "middle")
.style("pointer-events", "none");
}
};
c3_chart_internal_fn.getGaugeLabelHeight = function () {
return this.config.gauge_label_show ? 20 : 0;
};
c3_chart_internal_fn.initRegion = function () {
var $$ = this;
$$.region = $$.main.append('g')
.attr("clip-path", $$.clipPath)
.attr("class", CLASS.regions);
};
c3_chart_internal_fn.updateRegion = function (duration) {
var $$ = this, config = $$.config;
// hide if arc type
$$.region.style('visibility', $$.hasArcType() ? 'hidden' : 'visible');
$$.mainRegion = $$.main.select('.' + CLASS.regions).selectAll('.' + CLASS.region)
.data(config.regions);
$$.mainRegion.enter().append('g')
.attr('class', $$.classRegion.bind($$))
.append('rect')
.style("fill-opacity", 0);
$$.mainRegion.exit().transition().duration(duration)
.style("opacity", 0)
.remove();
};
c3_chart_internal_fn.redrawRegion = function (withTransition) {
var $$ = this,
regions = $$.mainRegion.selectAll('rect'),
x = $$.regionX.bind($$),
y = $$.regionY.bind($$),
w = $$.regionWidth.bind($$),
h = $$.regionHeight.bind($$);
return [
(withTransition ? regions.transition() : regions)
.attr("x", x)
.attr("y", y)
.attr("width", w)
.attr("height", h)
.style("fill-opacity", function (d) { return isValue(d.opacity) ? d.opacity : 0.1; })
];
};
c3_chart_internal_fn.regionX = function (d) {
var $$ = this, config = $$.config,
xPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
xPos = config.axis_rotated ? ('start' in d ? yScale(d.start) : 0) : 0;
} else {
xPos = config.axis_rotated ? 0 : ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0);
}
return xPos;
};
c3_chart_internal_fn.regionY = function (d) {
var $$ = this, config = $$.config,
yPos, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
yPos = config.axis_rotated ? 0 : ('end' in d ? yScale(d.end) : 0);
} else {
yPos = config.axis_rotated ? ('start' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.start) : d.start) : 0) : 0;
}
return yPos;
};
c3_chart_internal_fn.regionWidth = function (d) {
var $$ = this, config = $$.config,
start = $$.regionX(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
end = config.axis_rotated ? ('end' in d ? yScale(d.end) : $$.width) : $$.width;
} else {
end = config.axis_rotated ? $$.width : ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.width);
}
return end < start ? 0 : end - start;
};
c3_chart_internal_fn.regionHeight = function (d) {
var $$ = this, config = $$.config,
start = this.regionY(d), end, yScale = d.axis === 'y' ? $$.y : $$.y2;
if (d.axis === 'y' || d.axis === 'y2') {
end = config.axis_rotated ? $$.height : ('start' in d ? yScale(d.start) : $$.height);
} else {
end = config.axis_rotated ? ('end' in d ? $$.x($$.isTimeSeries() ? $$.parseDate(d.end) : d.end) : $$.height) : $$.height;
}
return end < start ? 0 : end - start;
};
c3_chart_internal_fn.isRegionOnX = function (d) {
return !d.axis || d.axis === 'x';
};
c3_chart_internal_fn.drag = function (mouse) {
var $$ = this, config = $$.config, main = $$.main, d3 = $$.d3;
var sx, sy, mx, my, minX, maxX, minY, maxY;
if ($$.hasArcType()) { return; }
if (! config.data_selection_enabled) { return; } // do nothing if not selectable
if (config.zoom_enabled && ! $$.zoom.altDomain) { return; } // skip if zoomable because of conflict drag dehavior
if (!config.data_selection_multiple) { return; } // skip when single selection because drag is used for multiple selection
sx = $$.dragStart[0];
sy = $$.dragStart[1];
mx = mouse[0];
my = mouse[1];
minX = Math.min(sx, mx);
maxX = Math.max(sx, mx);
minY = (config.data_selection_grouped) ? $$.margin.top : Math.min(sy, my);
maxY = (config.data_selection_grouped) ? $$.height : Math.max(sy, my);
main.select('.' + CLASS.dragarea)
.attr('x', minX)
.attr('y', minY)
.attr('width', maxX - minX)
.attr('height', maxY - minY);
// TODO: binary search when multiple xs
main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape)
.filter(function (d) { return config.data_selection_isselectable(d); })
.each(function (d, i) {
var shape = d3.select(this),
isSelected = shape.classed(CLASS.SELECTED),
isIncluded = shape.classed(CLASS.INCLUDED),
_x, _y, _w, _h, toggle, isWithin = false, box;
if (shape.classed(CLASS.circle)) {
_x = shape.attr("cx") * 1;
_y = shape.attr("cy") * 1;
toggle = $$.togglePoint;
isWithin = minX < _x && _x < maxX && minY < _y && _y < maxY;
}
else if (shape.classed(CLASS.bar)) {
box = getPathBox(this);
_x = box.x;
_y = box.y;
_w = box.width;
_h = box.height;
toggle = $$.togglePath;
isWithin = !(maxX < _x || _x + _w < minX) && !(maxY < _y || _y + _h < minY);
} else {
// line/area selection not supported yet
return;
}
if (isWithin ^ isIncluded) {
shape.classed(CLASS.INCLUDED, !isIncluded);
// TODO: included/unincluded callback here
shape.classed(CLASS.SELECTED, !isSelected);
toggle.call($$, !isSelected, shape, d, i);
}
});
};
c3_chart_internal_fn.dragstart = function (mouse) {
var $$ = this, config = $$.config;
if ($$.hasArcType()) { return; }
if (! config.data_selection_enabled) { return; } // do nothing if not selectable
$$.dragStart = mouse;
$$.main.select('.' + CLASS.chart).append('rect')
.attr('class', CLASS.dragarea)
.style('opacity', 0.1);
$$.dragging = true;
};
c3_chart_internal_fn.dragend = function () {
var $$ = this, config = $$.config;
if ($$.hasArcType()) { return; }
if (! config.data_selection_enabled) { return; } // do nothing if not selectable
$$.main.select('.' + CLASS.dragarea)
.transition().duration(100)
.style('opacity', 0)
.remove();
$$.main.selectAll('.' + CLASS.shape)
.classed(CLASS.INCLUDED, false);
$$.dragging = false;
};
c3_chart_internal_fn.selectPoint = function (target, d, i) {
var $$ = this, config = $$.config,
cx = (config.axis_rotated ? $$.circleY : $$.circleX).bind($$),
cy = (config.axis_rotated ? $$.circleX : $$.circleY).bind($$),
r = $$.pointSelectR.bind($$);
config.data_onselected.call($$.api, d, target.node());
// add selected-circle on low layer g
$$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
.data([d])
.enter().append('circle')
.attr("class", function () { return $$.generateClass(CLASS.selectedCircle, i); })
.attr("cx", cx)
.attr("cy", cy)
.attr("stroke", function () { return $$.color(d); })
.attr("r", function (d) { return $$.pointSelectR(d) * 1.4; })
.transition().duration(100)
.attr("r", r);
};
c3_chart_internal_fn.unselectPoint = function (target, d, i) {
var $$ = this;
$$.config.data_onunselected(d, target.node());
// remove selected-circle from low layer g
$$.main.select('.' + CLASS.selectedCircles + $$.getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i)
.transition().duration(100).attr('r', 0)
.remove();
};
c3_chart_internal_fn.togglePoint = function (selected, target, d, i) {
selected ? this.selectPoint(target, d, i) : this.unselectPoint(target, d, i);
};
c3_chart_internal_fn.selectPath = function (target, d) {
var $$ = this;
$$.config.data_onselected.call($$, d, target.node());
target.transition().duration(100)
.style("fill", function () { return $$.d3.rgb($$.color(d)).brighter(0.75); });
};
c3_chart_internal_fn.unselectPath = function (target, d) {
var $$ = this;
$$.config.data_onunselected.call($$, d, target.node());
target.transition().duration(100)
.style("fill", function () { return $$.color(d); });
};
c3_chart_internal_fn.togglePath = function (selected, target, d, i) {
selected ? this.selectPath(target, d, i) : this.unselectPath(target, d, i);
};
c3_chart_internal_fn.getToggle = function (that, d) {
var $$ = this, toggle;
if (that.nodeName === 'circle') {
if ($$.isStepType(d)) {
// circle is hidden in step chart, so treat as within the click area
toggle = function () {}; // TODO: how to select step chart?
} else {
toggle = $$.togglePoint;
}
}
else if (that.nodeName === 'path') {
toggle = $$.togglePath;
}
return toggle;
};
c3_chart_internal_fn.toggleShape = function (that, d, i) {
var $$ = this, d3 = $$.d3, config = $$.config,
shape = d3.select(that), isSelected = shape.classed(CLASS.SELECTED),
toggle = $$.getToggle(that, d).bind($$);
if (config.data_selection_enabled && config.data_selection_isselectable(d)) {
if (!config.data_selection_multiple) {
$$.main.selectAll('.' + CLASS.shapes + (config.data_selection_grouped ? $$.getTargetSelectorSuffix(d.id) : "")).selectAll('.' + CLASS.shape).each(function (d, i) {
var shape = d3.select(this);
if (shape.classed(CLASS.SELECTED)) { toggle(false, shape.classed(CLASS.SELECTED, false), d, i); }
});
}
shape.classed(CLASS.SELECTED, !isSelected);
toggle(!isSelected, shape, d, i);
}
};
c3_chart_internal_fn.initBrush = function () {
var $$ = this, d3 = $$.d3;
$$.brush = d3.svg.brush().on("brush", function () { $$.redrawForBrush(); });
$$.brush.update = function () {
if ($$.context) { $$.context.select('.' + CLASS.brush).call(this); }
return this;
};
$$.brush.scale = function (scale) {
return $$.config.axis_rotated ? this.y(scale) : this.x(scale);
};
};
c3_chart_internal_fn.initSubchart = function () {
var $$ = this, config = $$.config,
context = $$.context = $$.svg.append("g").attr("transform", $$.getTranslate('context'));
context.style('visibility', config.subchart_show ? 'visible' : 'hidden');
// Define g for chart area
context.append('g')
.attr("clip-path", $$.clipPathForSubchart)
.attr('class', CLASS.chart);
// Define g for bar chart area
context.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartBars);
// Define g for line chart area
context.select('.' + CLASS.chart).append("g")
.attr("class", CLASS.chartLines);
// Add extent rect for Brush
context.append("g")
.attr("clip-path", $$.clipPath)
.attr("class", CLASS.brush)
.call($$.brush);
// ATTENTION: This must be called AFTER chart added
// Add Axis
$$.axes.subx = context.append("g")
.attr("class", CLASS.axisX)
.attr("transform", $$.getTranslate('subx'))
.attr("clip-path", config.axis_rotated ? "" : $$.clipPathForXAxis);
};
c3_chart_internal_fn.updateTargetsForSubchart = function (targets) {
var $$ = this, context = $$.context, config = $$.config,
contextLineEnter, contextLineUpdate, contextBarEnter, contextBarUpdate,
classChartBar = $$.classChartBar.bind($$),
classBars = $$.classBars.bind($$),
classChartLine = $$.classChartLine.bind($$),
classLines = $$.classLines.bind($$),
classAreas = $$.classAreas.bind($$);
if (config.subchart_show) {
//-- Bar --//
contextBarUpdate = context.select('.' + CLASS.chartBars).selectAll('.' + CLASS.chartBar)
.data(targets)
.attr('class', classChartBar);
contextBarEnter = contextBarUpdate.enter().append('g')
.style('opacity', 0)
.attr('class', classChartBar);
// Bars for each data
contextBarEnter.append('g')
.attr("class", classBars);
//-- Line --//
contextLineUpdate = context.select('.' + CLASS.chartLines).selectAll('.' + CLASS.chartLine)
.data(targets)
.attr('class', classChartLine);
contextLineEnter = contextLineUpdate.enter().append('g')
.style('opacity', 0)
.attr('class', classChartLine);
// Lines for each data
contextLineEnter.append("g")
.attr("class", classLines);
// Area
contextLineEnter.append("g")
.attr("class", classAreas);
//-- Brush --//
context.selectAll('.' + CLASS.brush + ' rect')
.attr(config.axis_rotated ? "width" : "height", config.axis_rotated ? $$.width2 : $$.height2);
}
};
c3_chart_internal_fn.updateBarForSubchart = function (durationForExit) {
var $$ = this;
$$.contextBar = $$.context.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar)
.data($$.barData.bind($$));
$$.contextBar.enter().append('path')
.attr("class", $$.classBar.bind($$))
.style("stroke", 'none')
.style("fill", $$.color);
$$.contextBar
.style("opacity", $$.initialOpacity.bind($$));
$$.contextBar.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawBarForSubchart = function (drawBarOnSub, withTransition, duration) {
(withTransition ? this.contextBar.transition().duration(duration) : this.contextBar)
.attr('d', drawBarOnSub)
.style('opacity', 1);
};
c3_chart_internal_fn.updateLineForSubchart = function (durationForExit) {
var $$ = this;
$$.contextLine = $$.context.selectAll('.' + CLASS.lines).selectAll('.' + CLASS.line)
.data($$.lineData.bind($$));
$$.contextLine.enter().append('path')
.attr('class', $$.classLine.bind($$))
.style('stroke', $$.color);
$$.contextLine
.style("opacity", $$.initialOpacity.bind($$));
$$.contextLine.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawLineForSubchart = function (drawLineOnSub, withTransition, duration) {
(withTransition ? this.contextLine.transition().duration(duration) : this.contextLine)
.attr("d", drawLineOnSub)
.style('opacity', 1);
};
c3_chart_internal_fn.updateAreaForSubchart = function (durationForExit) {
var $$ = this, d3 = $$.d3;
$$.contextArea = $$.context.selectAll('.' + CLASS.areas).selectAll('.' + CLASS.area)
.data($$.lineData.bind($$));
$$.contextArea.enter().append('path')
.attr("class", $$.classArea.bind($$))
.style("fill", $$.color)
.style("opacity", function () { $$.orgAreaOpacity = +d3.select(this).style('opacity'); return 0; });
$$.contextArea
.style("opacity", 0);
$$.contextArea.exit().transition().duration(durationForExit)
.style('opacity', 0)
.remove();
};
c3_chart_internal_fn.redrawAreaForSubchart = function (drawAreaOnSub, withTransition, duration) {
(withTransition ? this.contextArea.transition().duration(duration) : this.contextArea)
.attr("d", drawAreaOnSub)
.style("fill", this.color)
.style("opacity", this.orgAreaOpacity);
};
c3_chart_internal_fn.redrawSubchart = function (withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices) {
var $$ = this, d3 = $$.d3, config = $$.config,
drawAreaOnSub, drawBarOnSub, drawLineOnSub;
$$.context.style('visibility', config.subchart_show ? 'visible' : 'hidden');
// subchart
if (config.subchart_show) {
// reflect main chart to extent on subchart if zoomed
if (d3.event && d3.event.type === 'zoom') {
$$.brush.extent($$.x.orgDomain()).update();
}
// update subchart elements if needed
if (withSubchart) {
// extent rect
if (!$$.brush.empty()) {
$$.brush.extent($$.x.orgDomain()).update();
}
// setup drawer - MEMO: this must be called after axis updated
drawAreaOnSub = $$.generateDrawArea(areaIndices, true);
drawBarOnSub = $$.generateDrawBar(barIndices, true);
drawLineOnSub = $$.generateDrawLine(lineIndices, true);
$$.updateBarForSubchart(duration);
$$.updateLineForSubchart(duration);
$$.updateAreaForSubchart(duration);
$$.redrawBarForSubchart(drawBarOnSub, duration, duration);
$$.redrawLineForSubchart(drawLineOnSub, duration, duration);
$$.redrawAreaForSubchart(drawAreaOnSub, duration, duration);
}
}
};
c3_chart_internal_fn.redrawForBrush = function () {
var $$ = this, x = $$.x;
$$.redraw({
withTransition: false,
withY: $$.config.zoom_rescale,
withSubchart: false,
withUpdateXDomain: true,
withDimension: false
});
$$.config.subchart_onbrush.call($$.api, x.orgDomain());
};
c3_chart_internal_fn.transformContext = function (withTransition, transitions) {
var $$ = this, subXAxis;
if (transitions && transitions.axisSubX) {
subXAxis = transitions.axisSubX;
} else {
subXAxis = $$.context.select('.' + CLASS.axisX);
if (withTransition) { subXAxis = subXAxis.transition(); }
}
$$.context.attr("transform", $$.getTranslate('context'));
subXAxis.attr("transform", $$.getTranslate('subx'));
};
c3_chart_internal_fn.getDefaultExtent = function () {
var $$ = this, config = $$.config,
extent = isFunction(config.axis_x_extent) ? config.axis_x_extent($$.getXDomain($$.data.targets)) : config.axis_x_extent;
if ($$.isTimeSeries()) {
extent = [$$.parseDate(extent[0]), $$.parseDate(extent[1])];
}
return extent;
};
c3_chart_internal_fn.initZoom = function () {
var $$ = this, d3 = $$.d3, config = $$.config, startEvent;
$$.zoom = d3.behavior.zoom()
.on("zoomstart", function () {
startEvent = d3.event.sourceEvent;
$$.zoom.altDomain = d3.event.sourceEvent.altKey ? $$.x.orgDomain() : null;
config.zoom_onzoomstart.call($$.api, d3.event.sourceEvent);
})
.on("zoom", function () {
$$.redrawForZoom.call($$);
})
.on('zoomend', function () {
var event = d3.event.sourceEvent;
// if click, do nothing. otherwise, click interaction will be canceled.
if (event && startEvent.clientX === event.clientX && startEvent.clientY === event.clientY) {
return;
}
$$.redrawEventRect();
$$.updateZoom();
config.zoom_onzoomend.call($$.api, $$.x.orgDomain());
});
$$.zoom.scale = function (scale) {
return config.axis_rotated ? this.y(scale) : this.x(scale);
};
$$.zoom.orgScaleExtent = function () {
var extent = config.zoom_extent ? config.zoom_extent : [1, 10];
return [extent[0], Math.max($$.getMaxDataCount() / extent[1], extent[1])];
};
$$.zoom.updateScaleExtent = function () {
var ratio = diffDomain($$.x.orgDomain()) / diffDomain($$.orgXDomain),
extent = this.orgScaleExtent();
this.scaleExtent([extent[0] * ratio, extent[1] * ratio]);
return this;
};
};
c3_chart_internal_fn.updateZoom = function () {
var $$ = this, z = $$.config.zoom_enabled ? $$.zoom : function () {};
$$.main.select('.' + CLASS.zoomRect).call(z).on("dblclick.zoom", null);
$$.main.selectAll('.' + CLASS.eventRect).call(z).on("dblclick.zoom", null);
};
c3_chart_internal_fn.redrawForZoom = function () {
var $$ = this, d3 = $$.d3, config = $$.config, zoom = $$.zoom, x = $$.x;
if (!config.zoom_enabled) {
return;
}
if ($$.filterTargetsToShow($$.data.targets).length === 0) {
return;
}
if (d3.event.sourceEvent.type === 'mousemove' && zoom.altDomain) {
x.domain(zoom.altDomain);
zoom.scale(x).updateScaleExtent();
return;
}
if ($$.isCategorized() && x.orgDomain()[0] === $$.orgXDomain[0]) {
x.domain([$$.orgXDomain[0] - 1e-10, x.orgDomain()[1]]);
}
$$.redraw({
withTransition: false,
withY: config.zoom_rescale,
withSubchart: false,
withEventRect: false,
withDimension: false
});
if (d3.event.sourceEvent.type === 'mousemove') {
$$.cancelClick = true;
}
config.zoom_onzoom.call($$.api, x.orgDomain());
};
c3_chart_internal_fn.generateColor = function () {
var $$ = this, config = $$.config, d3 = $$.d3,
colors = config.data_colors,
pattern = notEmpty(config.color_pattern) ? config.color_pattern : d3.scale.category10().range(),
callback = config.data_color,
ids = [];
return function (d) {
var id = d.id || (d.data && d.data.id) || d, color;
// if callback function is provided
if (colors[id] instanceof Function) {
color = colors[id](d);
}
// if specified, choose that color
else if (colors[id]) {
color = colors[id];
}
// if not specified, choose from pattern
else {
if (ids.indexOf(id) < 0) { ids.push(id); }
color = pattern[ids.indexOf(id) % pattern.length];
colors[id] = color;
}
return callback instanceof Function ? callback(color, d) : color;
};
};
c3_chart_internal_fn.generateLevelColor = function () {
var $$ = this, config = $$.config,
colors = config.color_pattern,
threshold = config.color_threshold,
asValue = threshold.unit === 'value',
values = threshold.values && threshold.values.length ? threshold.values : [],
max = threshold.max || 100;
return notEmpty(config.color_threshold) ? function (value) {
var i, v, color = colors[colors.length - 1];
for (i = 0; i < values.length; i++) {
v = asValue ? value : (value * 100 / max);
if (v < values[i]) {
color = colors[i];
break;
}
}
return color;
} : null;
};
c3_chart_internal_fn.getYFormat = function (forArc) {
var $$ = this,
formatForY = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.yFormat,
formatForY2 = forArc && !$$.hasType('gauge') ? $$.defaultArcValueFormat : $$.y2Format;
return function (v, ratio, id) {
var format = $$.axis.getId(id) === 'y2' ? formatForY2 : formatForY;
return format.call($$, v, ratio);
};
};
c3_chart_internal_fn.yFormat = function (v) {
var $$ = this, config = $$.config,
format = config.axis_y_tick_format ? config.axis_y_tick_format : $$.defaultValueFormat;
return format(v);
};
c3_chart_internal_fn.y2Format = function (v) {
var $$ = this, config = $$.config,
format = config.axis_y2_tick_format ? config.axis_y2_tick_format : $$.defaultValueFormat;
return format(v);
};
c3_chart_internal_fn.defaultValueFormat = function (v) {
return isValue(v) ? +v : "";
};
c3_chart_internal_fn.defaultArcValueFormat = function (v, ratio) {
return (ratio * 100).toFixed(1) + '%';
};
c3_chart_internal_fn.dataLabelFormat = function (targetId) {
var $$ = this, data_labels = $$.config.data_labels,
format, defaultFormat = function (v) { return isValue(v) ? +v : ""; };
// find format according to axis id
if (typeof data_labels.format === 'function') {
format = data_labels.format;
} else if (typeof data_labels.format === 'object') {
if (data_labels.format[targetId]) {
format = data_labels.format[targetId] === true ? defaultFormat : data_labels.format[targetId];
} else {
format = function () { return ''; };
}
} else {
format = defaultFormat;
}
return format;
};
c3_chart_internal_fn.hasCaches = function (ids) {
for (var i = 0; i < ids.length; i++) {
if (! (ids[i] in this.cache)) { return false; }
}
return true;
};
c3_chart_internal_fn.addCache = function (id, target) {
this.cache[id] = this.cloneTarget(target);
};
c3_chart_internal_fn.getCaches = function (ids) {
var targets = [], i;
for (i = 0; i < ids.length; i++) {
if (ids[i] in this.cache) { targets.push(this.cloneTarget(this.cache[ids[i]])); }
}
return targets;
};
var CLASS = c3_chart_internal_fn.CLASS = {
target: 'c3-target',
chart: 'c3-chart',
chartLine: 'c3-chart-line',
chartLines: 'c3-chart-lines',
chartBar: 'c3-chart-bar',
chartBars: 'c3-chart-bars',
chartText: 'c3-chart-text',
chartTexts: 'c3-chart-texts',
chartArc: 'c3-chart-arc',
chartArcs: 'c3-chart-arcs',
chartArcsTitle: 'c3-chart-arcs-title',
chartArcsBackground: 'c3-chart-arcs-background',
chartArcsGaugeUnit: 'c3-chart-arcs-gauge-unit',
chartArcsGaugeMax: 'c3-chart-arcs-gauge-max',
chartArcsGaugeMin: 'c3-chart-arcs-gauge-min',
selectedCircle: 'c3-selected-circle',
selectedCircles: 'c3-selected-circles',
eventRect: 'c3-event-rect',
eventRects: 'c3-event-rects',
eventRectsSingle: 'c3-event-rects-single',
eventRectsMultiple: 'c3-event-rects-multiple',
zoomRect: 'c3-zoom-rect',
brush: 'c3-brush',
focused: 'c3-focused',
defocused: 'c3-defocused',
region: 'c3-region',
regions: 'c3-regions',
tooltipContainer: 'c3-tooltip-container',
tooltip: 'c3-tooltip',
tooltipName: 'c3-tooltip-name',
shape: 'c3-shape',
shapes: 'c3-shapes',
line: 'c3-line',
lines: 'c3-lines',
bar: 'c3-bar',
bars: 'c3-bars',
circle: 'c3-circle',
circles: 'c3-circles',
arc: 'c3-arc',
arcs: 'c3-arcs',
area: 'c3-area',
areas: 'c3-areas',
empty: 'c3-empty',
text: 'c3-text',
texts: 'c3-texts',
gaugeValue: 'c3-gauge-value',
grid: 'c3-grid',
gridLines: 'c3-grid-lines',
xgrid: 'c3-xgrid',
xgrids: 'c3-xgrids',
xgridLine: 'c3-xgrid-line',
xgridLines: 'c3-xgrid-lines',
xgridFocus: 'c3-xgrid-focus',
ygrid: 'c3-ygrid',
ygrids: 'c3-ygrids',
ygridLine: 'c3-ygrid-line',
ygridLines: 'c3-ygrid-lines',
axis: 'c3-axis',
axisX: 'c3-axis-x',
axisXLabel: 'c3-axis-x-label',
axisY: 'c3-axis-y',
axisYLabel: 'c3-axis-y-label',
axisY2: 'c3-axis-y2',
axisY2Label: 'c3-axis-y2-label',
legendBackground: 'c3-legend-background',
legendItem: 'c3-legend-item',
legendItemEvent: 'c3-legend-item-event',
legendItemTile: 'c3-legend-item-tile',
legendItemHidden: 'c3-legend-item-hidden',
legendItemFocused: 'c3-legend-item-focused',
dragarea: 'c3-dragarea',
EXPANDED: '_expanded_',
SELECTED: '_selected_',
INCLUDED: '_included_'
};
c3_chart_internal_fn.generateClass = function (prefix, targetId) {
return " " + prefix + " " + prefix + this.getTargetSelectorSuffix(targetId);
};
c3_chart_internal_fn.classText = function (d) {
return this.generateClass(CLASS.text, d.index);
};
c3_chart_internal_fn.classTexts = function (d) {
return this.generateClass(CLASS.texts, d.id);
};
c3_chart_internal_fn.classShape = function (d) {
return this.generateClass(CLASS.shape, d.index);
};
c3_chart_internal_fn.classShapes = function (d) {
return this.generateClass(CLASS.shapes, d.id);
};
c3_chart_internal_fn.classLine = function (d) {
return this.classShape(d) + this.generateClass(CLASS.line, d.id);
};
c3_chart_internal_fn.classLines = function (d) {
return this.classShapes(d) + this.generateClass(CLASS.lines, d.id);
};
c3_chart_internal_fn.classCircle = function (d) {
return this.classShape(d) + this.generateClass(CLASS.circle, d.index);
};
c3_chart_internal_fn.classCircles = function (d) {
return this.classShapes(d) + this.generateClass(CLASS.circles, d.id);
};
c3_chart_internal_fn.classBar = function (d) {
return this.classShape(d) + this.generateClass(CLASS.bar, d.index);
};
c3_chart_internal_fn.classBars = function (d) {
return this.classShapes(d) + this.generateClass(CLASS.bars, d.id);
};
c3_chart_internal_fn.classArc = function (d) {
return this.classShape(d.data) + this.generateClass(CLASS.arc, d.data.id);
};
c3_chart_internal_fn.classArcs = function (d) {
return this.classShapes(d.data) + this.generateClass(CLASS.arcs, d.data.id);
};
c3_chart_internal_fn.classArea = function (d) {
return this.classShape(d) + this.generateClass(CLASS.area, d.id);
};
c3_chart_internal_fn.classAreas = function (d) {
return this.classShapes(d) + this.generateClass(CLASS.areas, d.id);
};
c3_chart_internal_fn.classRegion = function (d, i) {
return this.generateClass(CLASS.region, i) + ' ' + ('class' in d ? d['class'] : '');
};
c3_chart_internal_fn.classEvent = function (d) {
return this.generateClass(CLASS.eventRect, d.index);
};
c3_chart_internal_fn.classTarget = function (id) {
var $$ = this;
var additionalClassSuffix = $$.config.data_classes[id], additionalClass = '';
if (additionalClassSuffix) {
additionalClass = ' ' + CLASS.target + '-' + additionalClassSuffix;
}
return $$.generateClass(CLASS.target, id) + additionalClass;
};
c3_chart_internal_fn.classFocus = function (d) {
return this.classFocused(d) + this.classDefocused(d);
};
c3_chart_internal_fn.classFocused = function (d) {
return ' ' + (this.focusedTargetIds.indexOf(d.id) >= 0 ? CLASS.focused : '');
};
c3_chart_internal_fn.classDefocused = function (d) {
return ' ' + (this.defocusedTargetIds.indexOf(d.id) >= 0 ? CLASS.defocused : '');
};
c3_chart_internal_fn.classChartText = function (d) {
return CLASS.chartText + this.classTarget(d.id);
};
c3_chart_internal_fn.classChartLine = function (d) {
return CLASS.chartLine + this.classTarget(d.id);
};
c3_chart_internal_fn.classChartBar = function (d) {
return CLASS.chartBar + this.classTarget(d.id);
};
c3_chart_internal_fn.classChartArc = function (d) {
return CLASS.chartArc + this.classTarget(d.data.id);
};
c3_chart_internal_fn.getTargetSelectorSuffix = function (targetId) {
return targetId || targetId === 0 ? ('-' + targetId).replace(/[\s?!@#$%^&*()_=+,.<>'":;\[\]\/|~`{}\\]/g, '-') : '';
};
c3_chart_internal_fn.selectorTarget = function (id, prefix) {
return (prefix || '') + '.' + CLASS.target + this.getTargetSelectorSuffix(id);
};
c3_chart_internal_fn.selectorTargets = function (ids, prefix) {
var $$ = this;
ids = ids || [];
return ids.length ? ids.map(function (id) { return $$.selectorTarget(id, prefix); }) : null;
};
c3_chart_internal_fn.selectorLegend = function (id) {
return '.' + CLASS.legendItem + this.getTargetSelectorSuffix(id);
};
c3_chart_internal_fn.selectorLegends = function (ids) {
var $$ = this;
return ids && ids.length ? ids.map(function (id) { return $$.selectorLegend(id); }) : null;
};
var isValue = c3_chart_internal_fn.isValue = function (v) {
return v || v === 0;
},
isFunction = c3_chart_internal_fn.isFunction = function (o) {
return typeof o === 'function';
},
isString = c3_chart_internal_fn.isString = function (o) {
return typeof o === 'string';
},
isUndefined = c3_chart_internal_fn.isUndefined = function (v) {
return typeof v === 'undefined';
},
isDefined = c3_chart_internal_fn.isDefined = function (v) {
return typeof v !== 'undefined';
},
ceil10 = c3_chart_internal_fn.ceil10 = function (v) {
return Math.ceil(v / 10) * 10;
},
asHalfPixel = c3_chart_internal_fn.asHalfPixel = function (n) {
return Math.ceil(n) + 0.5;
},
diffDomain = c3_chart_internal_fn.diffDomain = function (d) {
return d[1] - d[0];
},
isEmpty = c3_chart_internal_fn.isEmpty = function (o) {
return !o || (isString(o) && o.length === 0) || (typeof o === 'object' && Object.keys(o).length === 0);
},
notEmpty = c3_chart_internal_fn.notEmpty = function (o) {
return Object.keys(o).length > 0;
},
getOption = c3_chart_internal_fn.getOption = function (options, key, defaultValue) {
return isDefined(options[key]) ? options[key] : defaultValue;
},
hasValue = c3_chart_internal_fn.hasValue = function (dict, value) {
var found = false;
Object.keys(dict).forEach(function (key) {
if (dict[key] === value) { found = true; }
});
return found;
},
getPathBox = c3_chart_internal_fn.getPathBox = function (path) {
var box = path.getBoundingClientRect(),
items = [path.pathSegList.getItem(0), path.pathSegList.getItem(1)],
minX = items[0].x, minY = Math.min(items[0].y, items[1].y);
return {x: minX, y: minY, width: box.width, height: box.height};
};
c3_chart_fn.focus = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);
candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))),
this.revert();
this.defocus();
candidates.classed(CLASS.focused, true).classed(CLASS.defocused, false);
if ($$.hasArcType()) {
$$.expandArc(targetIds);
}
$$.toggleFocusLegend(targetIds, true);
$$.focusedTargetIds = targetIds;
$$.defocusedTargetIds = $$.defocusedTargetIds.filter(function (id) {
return targetIds.indexOf(id) < 0;
});
};
c3_chart_fn.defocus = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);
candidates = $$.svg.selectAll($$.selectorTargets(targetIds.filter($$.isTargetToShow, $$))),
candidates.classed(CLASS.focused, false).classed(CLASS.defocused, true);
if ($$.hasArcType()) {
$$.unexpandArc(targetIds);
}
$$.toggleFocusLegend(targetIds, false);
$$.focusedTargetIds = $$.focusedTargetIds.filter(function (id) {
return targetIds.indexOf(id) < 0;
});
$$.defocusedTargetIds = targetIds;
};
c3_chart_fn.revert = function (targetIds) {
var $$ = this.internal, candidates;
targetIds = $$.mapToTargetIds(targetIds);
candidates = $$.svg.selectAll($$.selectorTargets(targetIds)); // should be for all targets
candidates.classed(CLASS.focused, false).classed(CLASS.defocused, false);
if ($$.hasArcType()) {
$$.unexpandArc(targetIds);
}
if ($$.config.legend_show) {
$$.showLegend(targetIds.filter($$.isLegendToShow.bind($$)));
$$.legend.selectAll($$.selectorLegends(targetIds))
.filter(function () {
return $$.d3.select(this).classed(CLASS.legendItemFocused);
})
.classed(CLASS.legendItemFocused, false);
}
$$.focusedTargetIds = [];
$$.defocusedTargetIds = [];
};
c3_chart_fn.show = function (targetIds, options) {
var $$ = this.internal, targets;
targetIds = $$.mapToTargetIds(targetIds);
options = options || {};
$$.removeHiddenTargetIds(targetIds);
targets = $$.svg.selectAll($$.selectorTargets(targetIds));
targets.transition()
.style('opacity', 1, 'important')
.call($$.endall, function () {
targets.style('opacity', null).style('opacity', 1);
});
if (options.withLegend) {
$$.showLegend(targetIds);
}
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
};
c3_chart_fn.hide = function (targetIds, options) {
var $$ = this.internal, targets;
targetIds = $$.mapToTargetIds(targetIds);
options = options || {};
$$.addHiddenTargetIds(targetIds);
targets = $$.svg.selectAll($$.selectorTargets(targetIds));
targets.transition()
.style('opacity', 0, 'important')
.call($$.endall, function () {
targets.style('opacity', null).style('opacity', 0);
});
if (options.withLegend) {
$$.hideLegend(targetIds);
}
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
};
c3_chart_fn.toggle = function (targetIds, options) {
var that = this, $$ = this.internal;
$$.mapToTargetIds(targetIds).forEach(function (targetId) {
$$.isTargetToShow(targetId) ? that.hide(targetId, options) : that.show(targetId, options);
});
};
c3_chart_fn.zoom = function (domain) {
var $$ = this.internal;
if (domain) {
if ($$.isTimeSeries()) {
domain = domain.map(function (x) { return $$.parseDate(x); });
}
$$.brush.extent(domain);
$$.redraw({withUpdateXDomain: true, withY: $$.config.zoom_rescale});
$$.config.zoom_onzoom.call(this, $$.x.orgDomain());
}
return $$.brush.extent();
};
c3_chart_fn.zoom.enable = function (enabled) {
var $$ = this.internal;
$$.config.zoom_enabled = enabled;
$$.updateAndRedraw();
};
c3_chart_fn.unzoom = function () {
var $$ = this.internal;
$$.brush.clear().update();
$$.redraw({withUpdateXDomain: true});
};
c3_chart_fn.load = function (args) {
var $$ = this.internal, config = $$.config;
// update xs if specified
if (args.xs) {
$$.addXs(args.xs);
}
// update classes if exists
if ('classes' in args) {
Object.keys(args.classes).forEach(function (id) {
config.data_classes[id] = args.classes[id];
});
}
// update categories if exists
if ('categories' in args && $$.isCategorized()) {
config.axis_x_categories = args.categories;
}
// update axes if exists
if ('axes' in args) {
Object.keys(args.axes).forEach(function (id) {
config.data_axes[id] = args.axes[id];
});
}
// use cache if exists
if ('cacheIds' in args && $$.hasCaches(args.cacheIds)) {
$$.load($$.getCaches(args.cacheIds), args.done);
return;
}
// unload if needed
if ('unload' in args) {
// TODO: do not unload if target will load (included in url/rows/columns)
$$.unload($$.mapToTargetIds((typeof args.unload === 'boolean' && args.unload) ? null : args.unload), function () {
$$.loadFromArgs(args);
});
} else {
$$.loadFromArgs(args);
}
};
c3_chart_fn.unload = function (args) {
var $$ = this.internal;
args = args || {};
if (args instanceof Array) {
args = {ids: args};
} else if (typeof args === 'string') {
args = {ids: [args]};
}
$$.unload($$.mapToTargetIds(args.ids), function () {
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true});
if (args.done) { args.done(); }
});
};
c3_chart_fn.flow = function (args) {
var $$ = this.internal,
targets, data, notfoundIds = [], orgDataCount = $$.getMaxDataCount(),
dataCount, domain, baseTarget, baseValue, length = 0, tail = 0, diff, to;
if (args.json) {
data = $$.convertJsonToData(args.json, args.keys);
}
else if (args.rows) {
data = $$.convertRowsToData(args.rows);
}
else if (args.columns) {
data = $$.convertColumnsToData(args.columns);
}
else {
return;
}
targets = $$.convertDataToTargets(data, true);
// Update/Add data
$$.data.targets.forEach(function (t) {
var found = false, i, j;
for (i = 0; i < targets.length; i++) {
if (t.id === targets[i].id) {
found = true;
if (t.values[t.values.length - 1]) {
tail = t.values[t.values.length - 1].index + 1;
}
length = targets[i].values.length;
for (j = 0; j < length; j++) {
targets[i].values[j].index = tail + j;
if (!$$.isTimeSeries()) {
targets[i].values[j].x = tail + j;
}
}
t.values = t.values.concat(targets[i].values);
targets.splice(i, 1);
break;
}
}
if (!found) { notfoundIds.push(t.id); }
});
// Append null for not found targets
$$.data.targets.forEach(function (t) {
var i, j;
for (i = 0; i < notfoundIds.length; i++) {
if (t.id === notfoundIds[i]) {
tail = t.values[t.values.length - 1].index + 1;
for (j = 0; j < length; j++) {
t.values.push({
id: t.id,
index: tail + j,
x: $$.isTimeSeries() ? $$.getOtherTargetX(tail + j) : tail + j,
value: null
});
}
}
}
});
// Generate null values for new target
if ($$.data.targets.length) {
targets.forEach(function (t) {
var i, missing = [];
for (i = $$.data.targets[0].values[0].index; i < tail; i++) {
missing.push({
id: t.id,
index: i,
x: $$.isTimeSeries() ? $$.getOtherTargetX(i) : i,
value: null
});
}
t.values.forEach(function (v) {
v.index += tail;
if (!$$.isTimeSeries()) {
v.x += tail;
}
});
t.values = missing.concat(t.values);
});
}
$$.data.targets = $$.data.targets.concat(targets); // add remained
// check data count because behavior needs to change when it's only one
dataCount = $$.getMaxDataCount();
baseTarget = $$.data.targets[0];
baseValue = baseTarget.values[0];
// Update length to flow if needed
if (isDefined(args.to)) {
length = 0;
to = $$.isTimeSeries() ? $$.parseDate(args.to) : args.to;
baseTarget.values.forEach(function (v) {
if (v.x < to) { length++; }
});
} else if (isDefined(args.length)) {
length = args.length;
}
// If only one data, update the domain to flow from left edge of the chart
if (!orgDataCount) {
if ($$.isTimeSeries()) {
if (baseTarget.values.length > 1) {
diff = baseTarget.values[baseTarget.values.length - 1].x - baseValue.x;
} else {
diff = baseValue.x - $$.getXDomain($$.data.targets)[0];
}
} else {
diff = 1;
}
domain = [baseValue.x - diff, baseValue.x];
$$.updateXDomain(null, true, true, false, domain);
} else if (orgDataCount === 1) {
if ($$.isTimeSeries()) {
diff = (baseTarget.values[baseTarget.values.length - 1].x - baseValue.x) / 2;
domain = [new Date(+baseValue.x - diff), new Date(+baseValue.x + diff)];
$$.updateXDomain(null, true, true, false, domain);
}
}
// Set targets
$$.updateTargets($$.data.targets);
// Redraw with new targets
$$.redraw({
flow: {
index: baseValue.index,
length: length,
duration: isValue(args.duration) ? args.duration : $$.config.transition_duration,
done: args.done,
orgDataCount: orgDataCount,
},
withLegend: true,
withTransition: orgDataCount > 1,
withTrimXDomain: false,
withUpdateXAxis: true,
});
};
c3_chart_internal_fn.generateFlow = function (args) {
var $$ = this, config = $$.config, d3 = $$.d3;
return function () {
var targets = args.targets,
flow = args.flow,
drawBar = args.drawBar,
drawLine = args.drawLine,
drawArea = args.drawArea,
cx = args.cx,
cy = args.cy,
xv = args.xv,
xForText = args.xForText,
yForText = args.yForText,
duration = args.duration;
var translateX, scaleX = 1, transform,
flowIndex = flow.index,
flowLength = flow.length,
flowStart = $$.getValueOnIndex($$.data.targets[0].values, flowIndex),
flowEnd = $$.getValueOnIndex($$.data.targets[0].values, flowIndex + flowLength),
orgDomain = $$.x.domain(), domain,
durationForFlow = flow.duration || duration,
done = flow.done || function () {},
wait = $$.generateWait();
var xgrid = $$.xgrid || d3.selectAll([]),
xgridLines = $$.xgridLines || d3.selectAll([]),
mainRegion = $$.mainRegion || d3.selectAll([]),
mainText = $$.mainText || d3.selectAll([]),
mainBar = $$.mainBar || d3.selectAll([]),
mainLine = $$.mainLine || d3.selectAll([]),
mainArea = $$.mainArea || d3.selectAll([]),
mainCircle = $$.mainCircle || d3.selectAll([]);
// set flag
$$.flowing = true;
// remove head data after rendered
$$.data.targets.forEach(function (d) {
d.values.splice(0, flowLength);
});
// update x domain to generate axis elements for flow
domain = $$.updateXDomain(targets, true, true);
// update elements related to x scale
if ($$.updateXGrid) { $$.updateXGrid(true); }
// generate transform to flow
if (!flow.orgDataCount) { // if empty
if ($$.data.targets[0].values.length !== 1) {
translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
} else {
if ($$.isTimeSeries()) {
flowStart = $$.getValueOnIndex($$.data.targets[0].values, 0);
flowEnd = $$.getValueOnIndex($$.data.targets[0].values, $$.data.targets[0].values.length - 1);
translateX = $$.x(flowStart.x) - $$.x(flowEnd.x);
} else {
translateX = diffDomain(domain) / 2;
}
}
} else if (flow.orgDataCount === 1 || flowStart.x === flowEnd.x) {
translateX = $$.x(orgDomain[0]) - $$.x(domain[0]);
} else {
if ($$.isTimeSeries()) {
translateX = ($$.x(orgDomain[0]) - $$.x(domain[0]));
} else {
translateX = ($$.x(flowStart.x) - $$.x(flowEnd.x));
}
}
scaleX = (diffDomain(orgDomain) / diffDomain(domain));
transform = 'translate(' + translateX + ',0) scale(' + scaleX + ',1)';
// hide tooltip
$$.hideXGridFocus();
$$.hideTooltip();
d3.transition().ease('linear').duration(durationForFlow).each(function () {
wait.add($$.axes.x.transition().call($$.xAxis));
wait.add(mainBar.transition().attr('transform', transform));
wait.add(mainLine.transition().attr('transform', transform));
wait.add(mainArea.transition().attr('transform', transform));
wait.add(mainCircle.transition().attr('transform', transform));
wait.add(mainText.transition().attr('transform', transform));
wait.add(mainRegion.filter($$.isRegionOnX).transition().attr('transform', transform));
wait.add(xgrid.transition().attr('transform', transform));
wait.add(xgridLines.transition().attr('transform', transform));
})
.call(wait, function () {
var i, shapes = [], texts = [], eventRects = [];
// remove flowed elements
if (flowLength) {
for (i = 0; i < flowLength; i++) {
shapes.push('.' + CLASS.shape + '-' + (flowIndex + i));
texts.push('.' + CLASS.text + '-' + (flowIndex + i));
eventRects.push('.' + CLASS.eventRect + '-' + (flowIndex + i));
}
$$.svg.selectAll('.' + CLASS.shapes).selectAll(shapes).remove();
$$.svg.selectAll('.' + CLASS.texts).selectAll(texts).remove();
$$.svg.selectAll('.' + CLASS.eventRects).selectAll(eventRects).remove();
$$.svg.select('.' + CLASS.xgrid).remove();
}
// draw again for removing flowed elements and reverting attr
xgrid
.attr('transform', null)
.attr($$.xgridAttr);
xgridLines
.attr('transform', null);
xgridLines.select('line')
.attr("x1", config.axis_rotated ? 0 : xv)
.attr("x2", config.axis_rotated ? $$.width : xv);
xgridLines.select('text')
.attr("x", config.axis_rotated ? $$.width : 0)
.attr("y", xv);
mainBar
.attr('transform', null)
.attr("d", drawBar);
mainLine
.attr('transform', null)
.attr("d", drawLine);
mainArea
.attr('transform', null)
.attr("d", drawArea);
mainCircle
.attr('transform', null)
.attr("cx", cx)
.attr("cy", cy);
mainText
.attr('transform', null)
.attr('x', xForText)
.attr('y', yForText)
.style('fill-opacity', $$.opacityForText.bind($$));
mainRegion
.attr('transform', null);
mainRegion.select('rect').filter($$.isRegionOnX)
.attr("x", $$.regionX.bind($$))
.attr("width", $$.regionWidth.bind($$));
if (config.interaction_enabled) {
$$.redrawEventRect();
}
// callback for end of flow
done();
$$.flowing = false;
});
};
};
c3_chart_fn.selected = function (targetId) {
var $$ = this.internal, d3 = $$.d3;
return d3.merge(
$$.main.selectAll('.' + CLASS.shapes + $$.getTargetSelectorSuffix(targetId)).selectAll('.' + CLASS.shape)
.filter(function () { return d3.select(this).classed(CLASS.SELECTED); })
.map(function (d) { return d.map(function (d) { var data = d.__data__; return data.data ? data.data : data; }); })
);
};
c3_chart_fn.select = function (ids, indices, resetOther) {
var $$ = this.internal, d3 = $$.d3, config = $$.config;
if (! config.data_selection_enabled) { return; }
$$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
var shape = d3.select(this), id = d.data ? d.data.id : d.id,
toggle = $$.getToggle(this, d).bind($$),
isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
isTargetIndex = !indices || indices.indexOf(i) >= 0,
isSelected = shape.classed(CLASS.SELECTED);
// line/area selection not supported yet
if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
return;
}
if (isTargetId && isTargetIndex) {
if (config.data_selection_isselectable(d) && !isSelected) {
toggle(true, shape.classed(CLASS.SELECTED, true), d, i);
}
} else if (isDefined(resetOther) && resetOther) {
if (isSelected) {
toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
}
}
});
};
c3_chart_fn.unselect = function (ids, indices) {
var $$ = this.internal, d3 = $$.d3, config = $$.config;
if (! config.data_selection_enabled) { return; }
$$.main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) {
var shape = d3.select(this), id = d.data ? d.data.id : d.id,
toggle = $$.getToggle(this, d).bind($$),
isTargetId = config.data_selection_grouped || !ids || ids.indexOf(id) >= 0,
isTargetIndex = !indices || indices.indexOf(i) >= 0,
isSelected = shape.classed(CLASS.SELECTED);
// line/area selection not supported yet
if (shape.classed(CLASS.line) || shape.classed(CLASS.area)) {
return;
}
if (isTargetId && isTargetIndex) {
if (config.data_selection_isselectable(d)) {
if (isSelected) {
toggle(false, shape.classed(CLASS.SELECTED, false), d, i);
}
}
}
});
};
c3_chart_fn.transform = function (type, targetIds) {
var $$ = this.internal,
options = ['pie', 'donut'].indexOf(type) >= 0 ? {withTransform: true} : null;
$$.transformTo(targetIds, type, options);
};
c3_chart_internal_fn.transformTo = function (targetIds, type, optionsForRedraw) {
var $$ = this,
withTransitionForAxis = !$$.hasArcType(),
options = optionsForRedraw || {withTransitionForAxis: withTransitionForAxis};
options.withTransitionForTransform = false;
$$.transiting = false;
$$.setTargetType(targetIds, type);
$$.updateTargets($$.data.targets); // this is needed when transforming to arc
$$.updateAndRedraw(options);
};
c3_chart_fn.groups = function (groups) {
var $$ = this.internal, config = $$.config;
if (isUndefined(groups)) { return config.data_groups; }
config.data_groups = groups;
$$.redraw();
return config.data_groups;
};
c3_chart_fn.xgrids = function (grids) {
var $$ = this.internal, config = $$.config;
if (! grids) { return config.grid_x_lines; }
config.grid_x_lines = grids;
$$.redrawWithoutRescale();
return config.grid_x_lines;
};
c3_chart_fn.xgrids.add = function (grids) {
var $$ = this.internal;
return this.xgrids($$.config.grid_x_lines.concat(grids ? grids : []));
};
c3_chart_fn.xgrids.remove = function (params) { // TODO: multiple
var $$ = this.internal;
$$.removeGridLines(params, true);
};
c3_chart_fn.ygrids = function (grids) {
var $$ = this.internal, config = $$.config;
if (! grids) { return config.grid_y_lines; }
config.grid_y_lines = grids;
$$.redrawWithoutRescale();
return config.grid_y_lines;
};
c3_chart_fn.ygrids.add = function (grids) {
var $$ = this.internal;
return this.ygrids($$.config.grid_y_lines.concat(grids ? grids : []));
};
c3_chart_fn.ygrids.remove = function (params) { // TODO: multiple
var $$ = this.internal;
$$.removeGridLines(params, false);
};
c3_chart_fn.regions = function (regions) {
var $$ = this.internal, config = $$.config;
if (!regions) { return config.regions; }
config.regions = regions;
$$.redrawWithoutRescale();
return config.regions;
};
c3_chart_fn.regions.add = function (regions) {
var $$ = this.internal, config = $$.config;
if (!regions) { return config.regions; }
config.regions = config.regions.concat(regions);
$$.redrawWithoutRescale();
return config.regions;
};
c3_chart_fn.regions.remove = function (options) {
var $$ = this.internal, config = $$.config,
duration, classes, regions;
options = options || {};
duration = $$.getOption(options, "duration", config.transition_duration);
classes = $$.getOption(options, "classes", [CLASS.region]);
regions = $$.main.select('.' + CLASS.regions).selectAll(classes.map(function (c) { return '.' + c; }));
(duration ? regions.transition().duration(duration) : regions)
.style('opacity', 0)
.remove();
config.regions = config.regions.filter(function (region) {
var found = false;
if (!region['class']) {
return true;
}
region['class'].split(' ').forEach(function (c) {
if (classes.indexOf(c) >= 0) { found = true; }
});
return !found;
});
return config.regions;
};
c3_chart_fn.data = function (targetIds) {
var targets = this.internal.data.targets;
return typeof targetIds === 'undefined' ? targets : targets.filter(function (t) {
return [].concat(targetIds).indexOf(t.id) >= 0;
});
};
c3_chart_fn.data.shown = function (targetIds) {
return this.internal.filterTargetsToShow(this.data(targetIds));
};
c3_chart_fn.data.values = function (targetId) {
var targets, values = null;
if (targetId) {
targets = this.data(targetId);
values = targets[0] ? targets[0].values.map(function (d) { return d.value; }) : null;
}
return values;
};
c3_chart_fn.data.names = function (names) {
this.internal.clearLegendItemTextBoxCache();
return this.internal.updateDataAttributes('names', names);
};
c3_chart_fn.data.colors = function (colors) {
return this.internal.updateDataAttributes('colors', colors);
};
c3_chart_fn.data.axes = function (axes) {
return this.internal.updateDataAttributes('axes', axes);
};
c3_chart_fn.category = function (i, category) {
var $$ = this.internal, config = $$.config;
if (arguments.length > 1) {
config.axis_x_categories[i] = category;
$$.redraw();
}
return config.axis_x_categories[i];
};
c3_chart_fn.categories = function (categories) {
var $$ = this.internal, config = $$.config;
if (!arguments.length) { return config.axis_x_categories; }
config.axis_x_categories = categories;
$$.redraw();
return config.axis_x_categories;
};
// TODO: fix
c3_chart_fn.color = function (id) {
var $$ = this.internal;
return $$.color(id); // more patterns
};
c3_chart_fn.x = function (x) {
var $$ = this.internal;
if (arguments.length) {
$$.updateTargetX($$.data.targets, x);
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
}
return $$.data.xs;
};
c3_chart_fn.xs = function (xs) {
var $$ = this.internal;
if (arguments.length) {
$$.updateTargetXs($$.data.targets, xs);
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
}
return $$.data.xs;
};
c3_chart_fn.axis = function () {};
c3_chart_fn.axis.labels = function (labels) {
var $$ = this.internal;
if (arguments.length) {
Object.keys(labels).forEach(function (axisId) {
$$.axis.setLabelText(axisId, labels[axisId]);
});
$$.axis.updateLabels();
}
// TODO: return some values?
};
c3_chart_fn.axis.max = function (max) {
var $$ = this.internal, config = $$.config;
if (arguments.length) {
if (typeof max === 'object') {
if (isValue(max.x)) { config.axis_x_max = max.x; }
if (isValue(max.y)) { config.axis_y_max = max.y; }
if (isValue(max.y2)) { config.axis_y2_max = max.y2; }
} else {
config.axis_y_max = config.axis_y2_max = max;
}
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
} else {
return {
x: config.axis_x_max,
y: config.axis_y_max,
y2: config.axis_y2_max
};
}
};
c3_chart_fn.axis.min = function (min) {
var $$ = this.internal, config = $$.config;
if (arguments.length) {
if (typeof min === 'object') {
if (isValue(min.x)) { config.axis_x_min = min.x; }
if (isValue(min.y)) { config.axis_y_min = min.y; }
if (isValue(min.y2)) { config.axis_y2_min = min.y2; }
} else {
config.axis_y_min = config.axis_y2_min = min;
}
$$.redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true});
} else {
return {
x: config.axis_x_min,
y: config.axis_y_min,
y2: config.axis_y2_min
};
}
};
c3_chart_fn.axis.range = function (range) {
if (arguments.length) {
if (isDefined(range.max)) { this.axis.max(range.max); }
if (isDefined(range.min)) { this.axis.min(range.min); }
} else {
return {
max: this.axis.max(),
min: this.axis.min()
};
}
};
c3_chart_fn.legend = function () {};
c3_chart_fn.legend.show = function (targetIds) {
var $$ = this.internal;
$$.showLegend($$.mapToTargetIds(targetIds));
$$.updateAndRedraw({withLegend: true});
};
c3_chart_fn.legend.hide = function (targetIds) {
var $$ = this.internal;
$$.hideLegend($$.mapToTargetIds(targetIds));
$$.updateAndRedraw({withLegend: true});
};
c3_chart_fn.resize = function (size) {
var $$ = this.internal, config = $$.config;
config.size_width = size ? size.width : null;
config.size_height = size ? size.height : null;
this.flush();
};
c3_chart_fn.flush = function () {
var $$ = this.internal;
$$.updateAndRedraw({withLegend: true, withTransition: false, withTransitionForTransform: false});
};
c3_chart_fn.destroy = function () {
var $$ = this.internal;
window.clearInterval($$.intervalForObserveInserted);
window.onresize = null;
$$.selectChart.classed('c3', false).html("");
// MEMO: this is needed because the reference of some elements will not be released, then memory leak will happen.
Object.keys($$).forEach(function (key) {
$$[key] = null;
});
return null;
};
c3_chart_fn.tooltip = function () {};
c3_chart_fn.tooltip.show = function (args) {
var $$ = this.internal, index, mouse;
// determine mouse position on the chart
if (args.mouse) {
mouse = args.mouse;
}
// determine focus data
if (args.data) {
if ($$.isMultipleX()) {
// if multiple xs, target point will be determined by mouse
mouse = [$$.x(args.data.x), $$.getYScale(args.data.id)(args.data.value)];
index = null;
} else {
// TODO: when tooltip_grouped = false
index = isValue(args.data.index) ? args.data.index : $$.getIndexByX(args.data.x);
}
}
else if (typeof args.x !== 'undefined') {
index = $$.getIndexByX(args.x);
}
else if (typeof args.index !== 'undefined') {
index = args.index;
}
// emulate mouse events to show
$$.dispatchEvent('mouseover', index, mouse);
$$.dispatchEvent('mousemove', index, mouse);
};
c3_chart_fn.tooltip.hide = function () {
// TODO: get target data by checking the state of focus
this.internal.dispatchEvent('mouseout', 0);
};
// Features:
// 1. category axis
// 2. ceil values of translate/x/y to int for half pixel antialiasing
// 3. multiline tick text
var tickTextCharSize;
function c3_axis(d3, params) {
var scale = d3.scale.linear(), orient = "bottom", innerTickSize = 6, outerTickSize, tickPadding = 3, tickValues = null, tickFormat, tickArguments;
var tickOffset = 0, tickCulling = true, tickCentered;
params = params || {};
outerTickSize = params.withOuterTick ? 6 : 0;
function axisX(selection, x) {
selection.attr("transform", function (d) {
return "translate(" + Math.ceil(x(d) + tickOffset) + ", 0)";
});
}
function axisY(selection, y) {
selection.attr("transform", function (d) {
return "translate(0," + Math.ceil(y(d)) + ")";
});
}
function scaleExtent(domain) {
var start = domain[0], stop = domain[domain.length - 1];
return start < stop ? [ start, stop ] : [ stop, start ];
}
function generateTicks(scale) {
var i, domain, ticks = [];
if (scale.ticks) {
return scale.ticks.apply(scale, tickArguments);
}
domain = scale.domain();
for (i = Math.ceil(domain[0]); i < domain[1]; i++) {
ticks.push(i);
}
if (ticks.length > 0 && ticks[0] > 0) {
ticks.unshift(ticks[0] - (ticks[1] - ticks[0]));
}
return ticks;
}
function copyScale() {
var newScale = scale.copy(), domain;
if (params.isCategory) {
domain = scale.domain();
newScale.domain([domain[0], domain[1] - 1]);
}
return newScale;
}
function textFormatted(v) {
var formatted = tickFormat ? tickFormat(v) : v;
return typeof formatted !== 'undefined' ? formatted : '';
}
function getSizeFor1Char(tick) {
if (tickTextCharSize) {
return tickTextCharSize;
}
var size = {
h: 11.5,
w: 5.5
};
tick.select('text').text(textFormatted).each(function (d) {
var box = this.getBoundingClientRect(),
text = textFormatted(d),
h = box.height,
w = text ? (box.width / text.length) : undefined;
if (h && w) {
size.h = h;
size.w = w;
}
}).text('');
tickTextCharSize = size;
return size;
}
function axis(g) {
g.each(function () {
var g = axis.g = d3.select(this);
var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = copyScale();
var ticks = tickValues ? tickValues : generateTicks(scale1),
tick = g.selectAll(".tick").data(ticks, scale1),
tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", 1e-6),
// MEMO: No exit transition. The reason is this transition affects max tick width calculation because old tick will be included in the ticks.
tickExit = tick.exit().remove(),
tickUpdate = d3.transition(tick).style("opacity", 1),
tickTransform, tickX, tickY;
var range = scale.rangeExtent ? scale.rangeExtent() : scaleExtent(scale.range()),
path = g.selectAll(".domain").data([ 0 ]),
pathUpdate = (path.enter().append("path").attr("class", "domain"), d3.transition(path));
tickEnter.append("line");
tickEnter.append("text");
var lineEnter = tickEnter.select("line"),
lineUpdate = tickUpdate.select("line"),
textEnter = tickEnter.select("text"),
textUpdate = tickUpdate.select("text");
if (params.isCategory) {
tickOffset = Math.ceil((scale1(1) - scale1(0)) / 2);
tickX = tickCentered ? 0 : tickOffset;
tickY = tickCentered ? tickOffset : 0;
} else {
tickOffset = tickX = 0;
}
var text, tspan, sizeFor1Char = getSizeFor1Char(g.select('.tick')), counts = [];
var tickLength = Math.max(innerTickSize, 0) + tickPadding,
isVertical = orient === 'left' || orient === 'right';
// this should be called only when category axis
function splitTickText(d, maxWidth) {
var tickText = textFormatted(d),
subtext, spaceIndex, textWidth, splitted = [];
if (Object.prototype.toString.call(tickText) === "[object Array]") {
return tickText;
}
if (!maxWidth || maxWidth <= 0) {
maxWidth = isVertical ? 95 : params.isCategory ? (Math.ceil(scale1(ticks[1]) - scale1(ticks[0])) - 12) : 110;
}
function split(splitted, text) {
spaceIndex = undefined;
for (var i = 1; i < text.length; i++) {
if (text.charAt(i) === ' ') {
spaceIndex = i;
}
subtext = text.substr(0, i + 1);
textWidth = sizeFor1Char.w * subtext.length;
// if text width gets over tick width, split by space index or crrent index
if (maxWidth < textWidth) {
return split(
splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)),
text.slice(spaceIndex ? spaceIndex + 1 : i)
);
}
}
return splitted.concat(text);
}
return split(splitted, tickText + "");
}
function tspanDy(d, i) {
var dy = sizeFor1Char.h;
if (i === 0) {
if (orient === 'left' || orient === 'right') {
dy = -((counts[d.index] - 1) * (sizeFor1Char.h / 2) - 3);
} else {
dy = ".71em";
}
}
return dy;
}
function tickSize(d) {
var tickPosition = scale(d) + (tickCentered ? 0 : tickOffset);
return range[0] < tickPosition && tickPosition < range[1] ? innerTickSize : 0;
}
text = tick.select("text");
tspan = text.selectAll('tspan')
.data(function (d, i) {
var splitted = params.tickMultiline ? splitTickText(d, params.tickWidth) : [].concat(textFormatted(d));
counts[i] = splitted.length;
return splitted.map(function (s) {
return { index: i, splitted: s };
});
});
tspan.enter().append('tspan');
tspan.exit().remove();
tspan.text(function (d) { return d.splitted; });
var rotate = params.tickTextRotate;
function textAnchorForText(rotate) {
if (!rotate) {
return 'middle';
}
return rotate > 0 ? "start" : "end";
}
function textTransform(rotate) {
if (!rotate) {
return '';
}
return "rotate(" + rotate + ")";
}
function dxForText(rotate) {
if (!rotate) {
return 0;
}
return 8 * Math.sin(Math.PI * (rotate / 180));
}
function yForText(rotate) {
if (!rotate) {
return tickLength;
}
return 11.5 - 2.5 * (rotate / 15) * (rotate > 0 ? 1 : -1);
}
switch (orient) {
case "bottom":
{
tickTransform = axisX;
lineEnter.attr("y2", innerTickSize);
textEnter.attr("y", tickLength);
lineUpdate.attr("x1", tickX).attr("x2", tickX).attr("y2", tickSize);
textUpdate.attr("x", 0).attr("y", yForText(rotate))
.style("text-anchor", textAnchorForText(rotate))
.attr("transform", textTransform(rotate));
tspan.attr('x', 0).attr("dy", tspanDy).attr('dx', dxForText(rotate));
pathUpdate.attr("d", "M" + range[0] + "," + outerTickSize + "V0H" + range[1] + "V" + outerTickSize);
break;
}
case "top":
{
// TODO: rotated tick text
tickTransform = axisX;
lineEnter.attr("y2", -innerTickSize);
textEnter.attr("y", -tickLength);
lineUpdate.attr("x2", 0).attr("y2", -innerTickSize);
textUpdate.attr("x", 0).attr("y", -tickLength);
text.style("text-anchor", "middle");
tspan.attr('x', 0).attr("dy", "0em");
pathUpdate.attr("d", "M" + range[0] + "," + -outerTickSize + "V0H" + range[1] + "V" + -outerTickSize);
break;
}
case "left":
{
tickTransform = axisY;
lineEnter.attr("x2", -innerTickSize);
textEnter.attr("x", -tickLength);
lineUpdate.attr("x2", -innerTickSize).attr("y1", tickY).attr("y2", tickY);
textUpdate.attr("x", -tickLength).attr("y", tickOffset);
text.style("text-anchor", "end");
tspan.attr('x', -tickLength).attr("dy", tspanDy);
pathUpdate.attr("d", "M" + -outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + -outerTickSize);
break;
}
case "right":
{
tickTransform = axisY;
lineEnter.attr("x2", innerTickSize);
textEnter.attr("x", tickLength);
lineUpdate.attr("x2", innerTickSize).attr("y2", 0);
textUpdate.attr("x", tickLength).attr("y", 0);
text.style("text-anchor", "start");
tspan.attr('x', tickLength).attr("dy", tspanDy);
pathUpdate.attr("d", "M" + outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + outerTickSize);
break;
}
}
if (scale1.rangeBand) {
var x = scale1, dx = x.rangeBand() / 2;
scale0 = scale1 = function (d) {
return x(d) + dx;
};
} else if (scale0.rangeBand) {
scale0 = scale1;
} else {
tickExit.call(tickTransform, scale1);
}
tickEnter.call(tickTransform, scale0);
tickUpdate.call(tickTransform, scale1);
});
}
axis.scale = function (x) {
if (!arguments.length) { return scale; }
scale = x;
return axis;
};
axis.orient = function (x) {
if (!arguments.length) { return orient; }
orient = x in {top: 1, right: 1, bottom: 1, left: 1} ? x + "" : "bottom";
return axis;
};
axis.tickFormat = function (format) {
if (!arguments.length) { return tickFormat; }
tickFormat = format;
return axis;
};
axis.tickCentered = function (isCentered) {
if (!arguments.length) { return tickCentered; }
tickCentered = isCentered;
return axis;
};
axis.tickOffset = function () {
return tickOffset;
};
axis.tickInterval = function () {
var interval, length;
if (params.isCategory) {
interval = tickOffset * 2;
}
else {
length = axis.g.select('path.domain').node().getTotalLength() - outerTickSize * 2;
interval = length / axis.g.selectAll('line').size();
}
return interval === Infinity ? 0 : interval;
};
axis.ticks = function () {
if (!arguments.length) { return tickArguments; }
tickArguments = arguments;
return axis;
};
axis.tickCulling = function (culling) {
if (!arguments.length) { return tickCulling; }
tickCulling = culling;
return axis;
};
axis.tickValues = function (x) {
if (typeof x === 'function') {
tickValues = function () {
return x(scale.domain());
};
}
else {
if (!arguments.length) { return tickValues; }
tickValues = x;
}
return axis;
};
return axis;
}
// PhantomJS doesn't have support for Function.prototype.bind, which has caused confusion. Use
// this polyfill to avoid the confusion.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
if (typeof define === 'function' && define.amd) {
define("c3", ["d3"], c3);
} else if ('undefined' !== typeof exports && 'undefined' !== typeof module) {
module.exports = c3;
} else {
window.c3 = c3;
}
})(window);
|
try {
console.log;
}
catch (e) {
window.console = undefined;
}
(function($) {
/* Create a subclass of the jQuery object. This was introduced in jQuery 1.5, but removed again in 1.9 */
var sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, $ );
jQuerySub.superclass = $;
jQuerySub.fn = jQuerySub.prototype = $();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
var namespaces = {};
$.entwine = function() {
$.fn.entwine.apply(null, arguments);
};
/**
* A couple of utility functions for accessing the store outside of this closure, and for making things
* operate in a little more easy-to-test manner
*/
$.extend($.entwine, {
/**
* Get all the namespaces. Useful for introspection? Internal interface of Namespace not guaranteed consistant
*/
namespaces: namespaces,
/**
* Remove all entwine rules
*/
clear_all_rules: function() {
// Remove proxy functions
for (var k in $.fn) { if ($.fn[k].isentwinemethod) delete $.fn[k]; }
// Remove bound events - TODO: Make this pluggable, so this code can be moved to jquery.entwine.events.js
$(document).unbind('.entwine');
$(window).unbind('.entwine');
// Remove namespaces, and start over again
for (var k in namespaces) delete namespaces[k];
for (var k in $.entwine.capture_bindings) delete $.entwine.capture_bindings[k];
},
WARN_LEVEL_NONE: 0,
WARN_LEVEL_IMPORTANT: 1,
WARN_LEVEL_BESTPRACTISE: 2,
/**
* Warning level. Set to a higher level to get warnings dumped to console.
*/
warningLevel: 0,
/** Utility to optionally display warning messages depending on level */
warn: function(message, level) {
if (level <= $.entwine.warningLevel && console && console.warn) {
console.warn(message);
if (console.trace) console.trace();
}
},
warn_exception: function(where, /* optional: */ on, e) {
if ($.entwine.WARN_LEVEL_IMPORTANT <= $.entwine.warningLevel && console && console.warn) {
if (arguments.length == 2) { e = on; on = null; }
if (on) console.warn('Uncaught exception',e,'in',where,'on',on);
else console.warn('Uncaught exception',e,'in',where);
if (e.stack) console.warn("Stack Trace:\n" + e.stack);
}
}
});
/** Stores a count of definitions, so that we can sort identical selectors by definition order */
var rulecount = 0;
var Rule = Base.extend({
init: function(selector, name) {
this.selector = selector;
this.specifity = selector.specifity();
this.important = 0;
this.name = name;
this.rulecount = rulecount++;
}
});
Rule.compare = function(a, b) {
var as = a.specifity, bs = b.specifity;
return (a.important - b.important) ||
(as[0] - bs[0]) ||
(as[1] - bs[1]) ||
(as[2] - bs[2]) ||
(a.rulecount - b.rulecount) ;
};
$.entwine.RuleList = function() {
var list = [];
list.addRule = function(selector, name){
var rule = Rule(selector, name);
list[list.length] = rule;
list.sort(Rule.compare);
return rule;
};
return list;
};
var handlers = [];
/**
* A Namespace holds all the information needed for adding entwine methods to a namespace (including the _null_ namespace)
*/
$.entwine.Namespace = Base.extend({
init: function(name){
if (name && !name.match(/^[A-Za-z0-9.]+$/)) $.entwine.warn('Entwine namespace '+name+' is not formatted as period seperated identifiers', $.entwine.WARN_LEVEL_BESTPRACTISE);
name = name || '__base';
this.name = name;
this.store = {};
namespaces[name] = this;
if (name == "__base") {
this.injectee = $.fn;
this.$ = $;
}
else {
// We're in a namespace, so we build a Class that subclasses the jQuery Object Class to inject namespace functions into
this.$ = $.sub ? $.sub() : sub();
// Work around bug in sub() - subclass must share cache with root or data won't get cleared by cleanData
this.$.cache = $.cache;
this.injectee = this.$.prototype;
// We override entwine to inject the name of this namespace when defining blocks inside this namespace
var entwine_wrapper = this.injectee.entwine = function(spacename) {
var args = arguments;
if (!spacename || typeof spacename != 'string') { args = $.makeArray(args); args.unshift(name); }
else if (spacename.charAt(0) != '.') args[0] = name+'.'+spacename;
return $.fn.entwine.apply(this, args);
};
this.$.entwine = function() {
entwine_wrapper.apply(null, arguments);
};
for (var i = 0; i < handlers.length; i++) {
var handler = handlers[i], builder;
// Inject jQuery object method overrides
if (builder = handler.namespaceMethodOverrides) {
var overrides = builder(this);
for (var k in overrides) this.injectee[k] = overrides[k];
}
// Inject $.entwine function overrides
if (builder = handler.namespaceStaticOverrides) {
var overrides = builder(this);
for (var k in overrides) this.$.entwine[k] = overrides[k];
}
}
}
},
/**
* Returns a function that does selector matching against the function list for a function name
* Used by proxy for all calls, and by ctorProxy to handle _super calls
* @param {String} name - name of the function as passed in the construction object
* @param {String} funcprop - the property on the Rule object that gives the actual function to call
* @param {function} basefunc - the non-entwine function to use as the catch-all function at the bottom of the stack
*/
one: function(name, funcprop, basefunc) {
var namespace = this;
var funcs = this.store[name];
var one = function(el, args, i){
if (i === undefined) i = funcs.length;
while (i--) {
if (funcs[i].selector.matches(el)) {
var ret, tmp_i = el.i, tmp_f = el.f;
el.i = i; el.f = one;
try { ret = funcs[i][funcprop].apply(namespace.$(el), args); }
finally { el.i = tmp_i; el.f = tmp_f; }
return ret;
}
}
// If we didn't find a entwine-defined function, but there is a non-entwine function to use as a base, try that
if (basefunc) return basefunc.apply(namespace.$(el), args);
};
return one;
},
/**
* A proxy is a function attached to a callable object (either the base jQuery.fn or a subspace object) which handles
* finding and calling the correct function for each member of the current jQuery context
* @param {String} name - name of the function as passed in the construction object
* @param {function} basefunc - the non-entwine function to use as the catch-all function at the bottom of the stack
*/
build_proxy: function(name, basefunc) {
var one = this.one(name, 'func', basefunc);
var prxy = function() {
var rv, ctx = $(this);
var i = ctx.length;
while (i--) rv = one(ctx[i], arguments);
return rv;
};
return prxy;
},
bind_proxy: function(selector, name, func) {
var rulelist = this.store[name] || (this.store[name] = $.entwine.RuleList());
var rule = rulelist.addRule(selector, name); rule.func = func;
if (!this.injectee.hasOwnProperty(name) || !this.injectee[name].isentwinemethod) {
this.injectee[name] = this.build_proxy(name, this.injectee.hasOwnProperty(name) ? this.injectee[name] : null);
this.injectee[name].isentwinemethod = true;
}
if (!this.injectee[name].isentwinemethod) {
$.entwine.warn('Warning: Entwine function '+name+' clashes with regular jQuery function - entwine function will not be callable directly on jQuery object', $.entwine.WARN_LEVEL_IMPORTANT);
}
},
add: function(selector, data) {
// For every item in the hash, try ever method handler, until one returns true
for (var k in data) {
var v = data[k];
for (var i = 0; i < handlers.length; i++) {
if (handlers[i].bind && handlers[i].bind.call(this, selector, k, v)) break;
}
}
},
has: function(ctx, name) {
var rulelist = this.store[name];
if (!rulelist) return false;
/* We go forward this time, since low specifity is likely to knock out a bunch of elements quickly */
for (var i = 0 ; i < rulelist.length; i++) {
ctx = ctx.not(rulelist[i].selector);
if (!ctx.length) return true;
}
return false;
}
});
/**
* A handler is some javascript code that adds support for some time of key / value pair passed in the hash to the Namespace add method.
* The default handlers provided (and included by default) are event, ctor and properties
*/
$.entwine.Namespace.addHandler = function(handler) {
for (var i = 0; i < handlers.length && handlers[i].order < handler.order; i++) { /* Pass */ }
handlers.splice(i, 0, handler);
};
$.entwine.Namespace.addHandler({
order: 50,
bind: function(selector, k, v){
if ($.isFunction(v)) {
this.bind_proxy(selector, k, v);
return true;
}
}
});
$.extend($.fn, {
/**
* Main entwine function. Used for new definitions, calling into a namespace (or forcing the base namespace) and entering a using block
*
*/
entwine: function(spacename) {
var i = 0;
/* Don't actually work out selector until we try and define something on it - we might be opening a namespace on an function-traveresed object
which have non-standard selectors like .parents(.foo).slice(0,1) */
var selector = null;
/* By default we operator on the base namespace */
var namespace = namespaces.__base || $.entwine.Namespace();
/* If the first argument is a string, then it's the name of a namespace. Look it up */
if (typeof spacename == 'string') {
if (spacename.charAt('0') == '.') spacename = spacename.substr(1);
if (spacename) namespace = namespaces[spacename] || $.entwine.Namespace(spacename);
i=1;
}
/* All remaining arguments should either be using blocks or definition hashs */
while (i < arguments.length) {
var res = arguments[i++];
// If it's a function, call it - either it's a using block or it's a namespaced entwine definition
if ($.isFunction(res)) {
if (res.length != 1) $.entwine.warn('Function block inside entwine definition does not take $ argument properly', $.entwine.WARN_LEVEL_IMPORTANT);
res = res.call(namespace.$(this), namespace.$);
}
// If we have a entwine definition hash, inject it into namespace
if (res) {
if (selector === null) selector = this.selector ? $.selector(this.selector) : false;
if (selector) namespace.add(selector, res);
else $.entwine.warn('Entwine block given to entwine call without selector. Make sure you call $(selector).entwine when defining blocks', $.entwine.WARN_LEVEL_IMPORTANT);
}
}
/* Finally, return the jQuery object 'this' refers to, wrapped in the new namespace */
return namespace.$(this);
},
/**
* Calls the next most specific version of the current entwine method
*/
_super: function(){
var rv, i = this.length;
while (i--) {
var el = this[0];
rv = el.f(el, arguments, el.i);
}
return rv;
}
});
})(jQuery);
|
/**
* Dynamic Queries
*
* Query the collection using the name of the attribute directly
*/
var _ = require('lodash');
var usageError = require('../../utils/usageError');
var utils = require('../../utils/helpers');
var normalize = require('../../utils/normalize');
var hasOwnProperty = utils.object.hasOwnProperty;
var finder = module.exports = {};
/**
* buildDynamicFinders
*
* Attaches shorthand dynamic methods to the prototype for each attribute
* in the schema.
*/
finder.buildDynamicFinders = function() {
var self = this;
// For each defined attribute, create a dynamic finder function
Object.keys(this._schema.schema).forEach(function(attrName) {
// Check if attribute is an association, if so generate limited dynamic finders
if (hasOwnProperty(self._schema.schema[attrName], 'foreignKey')) {
if (self.associationFinders !== false) {
self.generateAssociationFinders(attrName);
}
return;
}
var capitalizedMethods = ['findOneBy*', 'findOneBy*In', 'findOneBy*Like', 'findBy*', 'findBy*In',
'findBy*Like', 'countBy*', 'countBy*In', 'countBy*Like'];
var lowercasedMethods = ['*StartsWith', '*Contains', '*EndsWith'];
if (self.dynamicFinders !== false) {
capitalizedMethods.forEach(function(method) {
self.generateDynamicFinder(attrName, method);
});
lowercasedMethods.forEach(function(method) {
self.generateDynamicFinder(attrName, method, true);
});
}
});
};
/**
* generateDynamicFinder
*
* Creates a dynamic method based off the schema. Used for shortcuts for various
* methods where a criteria object can automatically be built.
*
* @param {String} attrName
* @param {String} method
* @param {Boolean} dont capitalize the attrName or do, defaults to false
*/
finder.generateDynamicFinder = function(attrName, method, dontCapitalize) {
var self = this;
var criteria;
// Capitalize Attribute Name for camelCase
var preparedAttrName = dontCapitalize ? attrName : utils.capitalize(attrName);
// Figure out actual dynamic method name by injecting attribute name
var actualMethodName = method.replace(/\*/g, preparedAttrName);
// Assign this finder to the collection
this[actualMethodName] = function dynamicMethod(value, options, cb) {
if (typeof options === 'function') {
cb = options;
options = null;
}
options = options || {};
var usage = utils.capitalize(self.identity) + '.' + actualMethodName + '(someValue,[options],callback)';
if (typeof value === 'undefined') return usageError('No value specified!', usage, cb);
if (options.where) return usageError('Cannot specify `where` option in a dynamic ' + method + '*() query!', usage, cb);
// Build criteria query and submit it
options.where = {};
options.where[attrName] = value;
switch (method) {
///////////////////////////////////////
// Finders
///////////////////////////////////////
case 'findOneBy*':
case 'findOneBy*In':
return self.findOne(options, cb);
case 'findOneBy*Like':
criteria = _.extend(options, {
where: {
like: options.where
}
});
return self.findOne(criteria, cb);
///////////////////////////////////////
// Aggregate Finders
///////////////////////////////////////
case 'findBy*':
case 'findBy*In':
return self.find(options, cb);
case 'findBy*Like':
criteria = _.extend(options, {
where: {
like: options.where
}
});
return self.find(criteria, cb);
///////////////////////////////////////
// Count Finders
///////////////////////////////////////
case 'countBy*':
case 'countBy*In':
return self.count(options, cb);
case 'countBy*Like':
criteria = _.extend(options, {
where: {
like: options.where
}
});
return self.count(criteria, cb);
///////////////////////////////////////
// Searchers
///////////////////////////////////////
case '*StartsWith':
return self.startsWith(options, cb);
case '*Contains':
return self.contains(options, cb);
case '*EndsWith':
return self.endsWith(options, cb);
}
};
};
/**
* generateAssociationFinders
*
* Generate Dynamic Finders for an association.
* Adds a .findBy<name>() method for has_one and belongs_to associations.
*
* @param {String} attrName, the column name of the attribute
*/
finder.generateAssociationFinders = function(attrName) {
var self = this;
var name, model;
// Find the user defined key for this attrName, look in self defined columnName
// properties and if that's not set see if the generated columnName matches the attrName
for (var key in this._attributes) {
// Cache the value
var cache = this._attributes[key];
if (!hasOwnProperty(cache, 'model')) continue;
if (cache.model.toLowerCase() + '_id' === attrName) {
name = key;
model = cache.model;
}
}
if (!name || !model) return;
// Build a findOneBy<attrName> dynamic finder that forces a join on the association
this['findOneBy' + utils.capitalize(name)] = function dynamicAssociationMethod(value, cb) {
// Check proper usage
var usage = utils.capitalize(self.identity) + '.' + 'findBy' + utils.capitalize(name) +
'(someValue, callback)';
if (typeof value === 'undefined') return usageError('No value specified!', usage, cb);
if (typeof value === 'function') return usageError('No value specified!', usage, cb);
var criteria = associationQueryCriteria(self, value, attrName);
return this.findOne(criteria, cb);
};
// Build a findBy<attrName> dynamic finder that forces a join on the association
this['findBy' + utils.capitalize(name)] = function dynamicAssociationMethod(value, cb) {
// Check proper usage
var usage = utils.capitalize(self.identity) + '.' + 'findBy' + utils.capitalize(name) +
'(someValue, callback)';
if (typeof value === 'undefined') return usageError('No value specified!', usage, cb);
if (typeof value === 'function') return usageError('No value specified!', usage, cb);
var criteria = associationQueryCriteria(self, value, attrName);
return this.find(criteria, cb);
};
};
/**
* Build Join Array
*/
function buildJoin() {
var self = this;
var pk, attr;
// Set the attr value to the generated schema attribute
attr = self.waterline.schema[self.identity].attributes[name];
// Get the current collection's primary key attribute
Object.keys(self._attributes).forEach(function(key) {
if (hasOwnProperty(self._attributes[key], 'primaryKey') && self._attributes[key].primaryKey) {
pk = key;
}
});
if (!attr) throw new Error('Attempting to populate an attribute that doesn\'t exist');
// Grab the key being populated to check if it is a has many to belongs to
// If it's a belongs_to the adapter needs to know that it should replace the foreign key
// with the associated value.
var parentKey = self.waterline.collections[self.identity].attributes[name];
// Build the initial join object that will link this collection to either another collection
// or to a junction table.
var join = {
parent: self._tableName,
parentKey: attr.columnName || pk,
child: attr.references,
childKey: attr.on,
select: true,
removeParentKey: !!parentKey.model
};
return join;
}
/**
* Query Criteria Builder for associations
*/
function associationQueryCriteria(context, value, attrName) {
// Build a criteria object
var criteria = {
where: {},
joins: []
};
// Build a join condition
var join = buildJoin.call(context);
criteria.joins.push(join);
// Add where values
criteria.where[attrName] = value;
return criteria;
}
|
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/layout"
import SEO from "../components/seo"
class NotFoundPage extends React.Component {
render() {
const { data } = this.props
const siteTitle = data.site.siteMetadata.title
return (
<Layout location={this.props.location} title={siteTitle}>
<SEO title="404: Not Found" />
<h1>Not Found</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</Layout>
)
}
}
export default NotFoundPage
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
}
`
|
var chai = require('chai'),
expect = chai.expect,
cron = require('../lib/cron');
describe('crontime', function() {
it('should test stars (* * * * * *)', function() {
expect(function() {
new cron.CronTime('* * * * * *');
}).to.not.throw;
});
it('should test digit (0 * * * * *)', function() {
expect(function() {
new cron.CronTime('0 * * * * *');
}).to.not.throw;
});
it('should test multi digits (08 * * * * *)', function() {
expect(function() {
new cron.CronTime('08 * * * * *');
}).to.not.throw;
});
it('should test all digits (08 8 8 8 8 5)', function() {
expect(function() {
new cron.CronTime('08 * * * * *');
}).to.not.throw;
});
it('should test too many digits (08 8 8 8 8 5)', function() {
expect(function() {
new cron.CronTime('08 * * * * *');
}).to.not.throw;
});
it('should test standard cron format (* * * * *)', function() {
expect(function() {
new cron.CronTime('* * * * *');
}).to.not.throw;
});
it('should test standard cron format (8 8 8 8 5)', function() {
var now = Date.now();
var standard = new cron.CronTime('8 8 8 8 5');
var extended = new cron.CronTime('0 8 8 8 8 5');
expect(standard.dayOfWeek).to.deep.eql(extended.dayOfWeek);
expect(standard.month).to.deep.eql(extended.month);
expect(standard.dayOfMonth).to.deep.eql(extended.dayOfMonth);
expect(standard.hour).to.deep.eql(extended.hour);
expect(standard.minute).to.deep.eql(extended.minute);
expect(standard.second).to.deep.eql(extended.second);
});
it('should test hyphen (0-10 * * * * *)', function() {
expect(function() {
new cron.CronTime('0-10 * * * * *');
}).to.not.throw;
});
it('should test multi hyphens (0-10 0-10 * * * *)', function() {
expect(function() {
new cron.CronTime('0-10 0-10 * * * *');
}).to.not.throw;
});
it('should test all hyphens (0-10 0-10 0-10 0-10 0-10 0-1)', function() {
expect(function() {
new cron.CronTime('0-10 0-10 0-10 0-10 0-10 0-1');
}).to.not.throw;
});
it('should test comma (0,10 * * * * *)', function() {
expect(function() {
new cron.CronTime('0,10 * * * * *');
}).to.not.throw;
});
it('should test multi commas (0,10 0,10 * * * *)', function() {
expect(function() {
new cron.CronTime('0,10 0,10 * * * *');
}).to.not.throw;
});
it('should test all commas (0,10 0,10 0,10 0,10 0,10 0,1)', function() {
expect(function() {
new cron.CronTime('0,10 0,10 0,10 0,10 0,10 0,1');
}).to.not.throw;
});
it('should test alias (* * * * jan *)', function() {
expect(function() {
new cron.CronTime('* * * * jan *');
}).to.not.throw;
});
it('should test multi aliases (* * * * jan,feb *)', function() {
expect(function() {
new cron.CronTime('* * * * jan,feb *');
}).to.not.throw;
});
it('should test all aliases (* * * * jan,feb mon,tue)', function() {
expect(function() {
new cron.CronTime('* * * * jan,feb mon,tue');
}).to.not.throw;
});
it('should test every second monday (* * * * * mon/2)');
it('should test unknown alias (* * * * jar *)', function() {
expect(function() {
new cron.CronTime('* * * * jar *');
}).to.throw;
});
it('should test unknown alias - short (* * * * j *)', function() {
expect(function() {
new cron.CronTime('* * * * j *');
}).to.throw;
});
it('should test Date', function() {
var d = new Date();
var ct = new cron.CronTime(d);
expect(ct.source.isSame(d.getTime())).to.be.true
});
it('should test day roll-over', function() {
var numHours = 24;
var ct = new cron.CronTime('0 0 17 * * *');
for (var hr = 0; hr < numHours; hr++) {
var start = new Date(2012, 3, 16, hr, 30, 30);
var next = ct._getNextDateFrom(start);
expect(next - start).to.be.lt(24*60*60*1000);
expect(next).to.be.gt(start);
}
});
it('should test illegal repetition syntax', function() {
expect(function(){
new cron.CronTime('* * /4 * * *');
}).to.throw;
});
it('should test next date', function() {
var ct = new cron.CronTime('0 0 */4 * * *');
var nextDate = new Date();
nextDate.setHours(23);
var nextdt = ct._getNextDateFrom(nextDate);
expect(nextdt).to.be.gt(nextDate);
expect(nextdt.hours() % 4).to.eql(0);
});
it('should test next date from invalid date', function() {
var ct = new cron.CronTime('0 0 * * * *');
var nextDate = new Date('My invalid date string');
var nextdt = ct._getNextDateFrom(nextDate);
expect(nextdt.toString()).to.eql('Invalid date');
});
it('should test next real date', function() {
var ct = new cron.CronTime(new Date());
var nextDate = new Date();
nextDate.setMonth(nextDate.getMonth()+1);
expect(nextDate).to.be.gt(ct.source);
var nextdt = ct._getNextDateFrom(nextDate);
expect(nextdt.isSame(nextDate)).to.be.true;
});
it('should test < constraints day of month', function() {
var ltm = [1, 3, 5, 8, 10];
for (var i = 0; i < ltm.length; i++) {
(function(m) {
expect(function() {
var ct = new cron.CronTime('0 0 0 33 ' + m + ' *');
}).to.throw;
})(ltm[i]);
}
});
it('should test next month selection');
describe('should throw an exception because `L` not supported', function() {
it('(* * * L * *)', function() {
expect(function() {
new cron.CronTime('* * * L * *');
}).to.throw(Error);
});
it('(* * * * * L)', function() {
expect(function() {
new cron.CronTime('* * * * * L');
}).to.throw(Error);
});
});
});
|
var tap = require("tap")
var server = require("./lib/server.js")
var common = require("./lib/common.js")
var client = common.freshClient()
var password = "%1234@asdf%"
, username = "username"
, email = "i@izs.me"
, userdata = {
name: username,
email: email,
_id: "org.couchdb.user:username",
type: "user",
roles: [],
date: "2012-06-07T04:11:21.591Z" }
, SD = require("string_decoder").StringDecoder
, decoder = new SD()
tap.test("update a user acct", function (t) {
server.expect("PUT", "/-/user/org.couchdb.user:username", function (req, res) {
t.equal(req.method, "PUT")
res.statusCode = 409
res.json({error: "conflict"})
})
server.expect("GET", "/-/user/org.couchdb.user:username?write=true", function (req, res) {
t.equal(req.method, "GET")
res.json(userdata)
})
server.expect("PUT", "/-/user/org.couchdb.user:username/-rev/" + userdata._rev, function (req, res) {
t.equal(req.method, "PUT")
var b = ""
req.on("data", function (d) {
b += decoder.write(d)
})
req.on("end", function () {
var o = JSON.parse(b)
userdata.password = password
userdata.date = o.date
t.deepEqual(o, userdata)
res.statusCode = 201
res.json({created:true})
})
})
client.adduser("http://localhost:1337/", username, password, email, function (er, data) {
if (er) throw er
t.deepEqual(data, { created: true })
t.end()
})
})
|
/*
Highcharts JS v6.0.5 (2018-01-31)
Indicator series type for Highstock
(c) 2010-2017 Sebastian Bochan
License: www.highcharts.com/license
*/
(function(n){"object"===typeof module&&module.exports?module.exports=n:n(Highcharts)})(function(n){(function(l){function n(a){return a.reduce(function(a,b){return Math.max(a,b[1])},-Infinity)}function B(a){return a.reduce(function(a,b){return Math.min(a,b[2])},Infinity)}function x(a){return{high:n(a),low:B(a)}}function C(a){var c,b,h,f,g;w(a.series,function(a){if(a.xData)for(f=a.xData,g=b=a.xIncrement?1:f.length-1;0<g;g--)if(h=f[g]-f[g-1],c===t||h<c)c=h});return c}var t,D=l.seriesType,w=l.each,y=
l.merge,z=l.color,E=l.isArray,A=l.defined,v=l.seriesTypes.sma;D("ikh","sma",{params:{period:26,periodTenkan:9,periodSenkouSpanB:52},marker:{enabled:!1},tooltip:{pointFormat:'\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e \x3cb\x3e {series.name}\x3c/b\x3e\x3cbr/\x3eTENKAN SEN: {point.tenkanSen:.3f}\x3cbr/\x3eKIJUN SEN: {point.kijunSen:.3f}\x3cbr/\x3eCHIKOU SPAN: {point.chikouSpan:.3f}\x3cbr/\x3eSENKOU SPAN A: {point.senkouSpanA:.3f}\x3cbr/\x3eSENKOU SPAN B: {point.senkouSpanB:.3f}\x3cbr/\x3e'},
tenkanLine:{styles:{lineWidth:1,lineColor:void 0}},kijunLine:{styles:{lineWidth:1,lineColor:void 0}},chikouLine:{styles:{lineWidth:1,lineColor:void 0}},senkouSpanA:{styles:{lineWidth:1,lineColor:void 0}},senkouSpanB:{styles:{lineWidth:1,lineColor:void 0}},senkouSpan:{styles:{fill:"rgba(255, 0, 0, 0.5)"}},dataGrouping:{approximation:"averages"}},{pointArrayMap:["tenkanSen","kijunSen","chikouSpan","senkouSpanA","senkouSpanB"],pointValKey:"tenkanSen",nameComponents:["periodSenkouSpanB","period","periodTenkan"],
init:function(){v.prototype.init.apply(this,arguments);this.options=y({tenkanLine:{styles:{lineColor:this.color}},kijunLine:{styles:{lineColor:this.color}},chikouLine:{styles:{lineColor:this.color}},senkouSpanA:{styles:{lineColor:this.color,fill:z(this.color).setOpacity(.5).get()}},senkouSpanB:{styles:{lineColor:this.color,fill:z(this.color).setOpacity(.5).get()}},senkouSpan:{styles:{fill:z(this.color).setOpacity(.2).get()}}},this.options)},toYData:function(a){return[a.tenkanSen,a.kijunSen,a.chikouSpan,
a.senkouSpanA,a.senkouSpanB]},translate:function(){var a=this;v.prototype.translate.apply(a);w(a.points,function(c){w(a.pointArrayMap,function(b){A(c[b])&&(c["plot"+b]=a.yAxis.toPixels(c[b],!0),c.plotY=c["plot"+b],c.tooltipPos=[c.plotX,c["plot"+b]],c.isNull=!1)})})},drawGraph:function(){for(var a=this,c=a.points,b=c.length,h=a.options,f=a.graph,g=a.color,l={options:{gapSize:h.gapSize}},e=a.pointArrayMap.length,m=[[],[],[],[],[],[]],p,q,k;b--;)for(q=c[b],k=0;k<e;k++)p=a.pointArrayMap[k],A(q[p])&&m[k].push({plotX:q.plotX,
plotY:q["plot"+p],isNull:!1});w("tenkanLine kijunLine chikouLine senkouSpanA senkouSpanB senkouSpan".split(" "),function(b,c){a.points=m[c];a.options=y(h[b].styles,l);a.graph=a["graph"+b];a.nextPoints=m[c-1];5===c?(a.points=m[c-1],a.options=y(h[b].styles,l),a.graph=a["graph"+b],a.nextPoints=m[c-2],a.fillGraph=!0,a.color=a.options.fill):(a.fillGraph=!1,a.color=g);v.prototype.drawGraph.call(a);a["graph"+b]=a.graph});delete a.nextPoints;delete a.fillGraph;a.points=c;a.options=h;a.graph=f},getGraphPath:function(a){var c,
b,h=[];a=a||this.points;if(this.fillGraph&&this.nextPoints){b=v.prototype.getGraphPath.call(this,this.nextPoints);b[0]="L";c=v.prototype.getGraphPath.call(this,a);b=b.slice(0,c.length);for(var f=b.length-1;0<f;f-=3)h.push(b[f-2],b[f-1],b[f]);c=c.concat(h)}else c=v.prototype.getGraphPath.apply(this,arguments);return c},getValues:function(a,c){var b=c.period,h=c.periodTenkan;c=c.periodSenkouSpanB;var f=a.xData,g=a.yData,l=g&&g.length||0;a=C(a.xAxis);var e=[],m=[],p,q,k,r,u,d,n;if(f.length<=b||!E(g[0])||
4!==g[0].length)return!1;p=f[0]-b*a;for(d=0;d<b;d++)m.push(p+d*a);for(d=0;d<l;d++)d>=h&&(k=g.slice(d-h,d),k=x(k),k=(k.high+k.low)/2),d>=b&&(r=g.slice(d-b,d),r=x(r),r=(r.high+r.low)/2,n=(k+r)/2),d>=c&&(u=g.slice(d-c,d),u=x(u),u=(u.high+u.low)/2),p=g[d][0],q=f[d],e[d]===t&&(e[d]=[]),e[d+b]===t&&(e[d+b]=[]),e[d+b][0]=k,e[d+b][1]=r,e[d+b][2]=t,d>=b?e[d-b][2]=p:(e[d+b][3]=t,e[d+b][4]=t),e[d+2*b]===t&&(e[d+2*b]=[]),e[d+2*b][3]=n,e[d+2*b][4]=u,m.push(q);for(d=1;d<=b;d++)m.push(q+d*a);return{values:e,xData:m,
yData:e}}})})(n)});
|
+function($) {
'use strict'
// Hide the post bottom bar when the post footer is visible by the user,
// and show it when the post footer isn't visible by the user
/**
* PostBottomBar
* @constructor
*/
var PostBottomBar = function() {
this.$postBottomBar = $('.post-bottom-bar');
this.$postFooter = $('.post-footer');
}
PostBottomBar.prototype = {
/**
* Run PostBottomBar feature
*/
run: function() {
var self = this;
var didScroll;
// Run animation for first time
self.swipePostBottomBar();
// Detects if the user is scrolling
$(window).scroll(function() {
self.didScroll = true;
});
// Check if the user scrolled every 250 milliseconds
setInterval(function() {
if (self.didScroll) {
self.swipePostBottomBar();
self.didScroll = false;
}
}, 250);
},
/**
* Animate the post bottom bar
*/
swipePostBottomBar: function() {
var postFooterElemPos = (this.$postFooter.offset().top + this.$postBottomBar.height());
// Check if the post footer element is visible by the user
if (($(window).scrollTop() + $(window).height()) > (postFooterElemPos)) {
this.$postBottomBar.slideUp();
}
else {
this.$postBottomBar.slideDown();
}
}
};
$(document).ready(function() {
if ($('.post-bottom-bar').length) {
var postBottomBar = new PostBottomBar();
postBottomBar.run();
}
});
}(jQuery);
|
var baseFlatten = require('./_baseFlatten');
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten(array, 1) : [];
}
module.exports = flatten;
|
/*!
* Draggabilly PACKAGED v1.2.0
* Make that shiz draggable
* http://draggabilly.desandro.com
* MIT license
*/
/**
* Bridget makes jQuery widgets
* v1.1.0
* MIT license
*/
( function( window ) {
// -------------------------- utils -------------------------- //
var slice = Array.prototype.slice;
function noop() {}
// -------------------------- definition -------------------------- //
function defineBridget( $ ) {
// bail if no jQuery
if ( !$ ) {
return;
}
// -------------------------- addOptionMethod -------------------------- //
/**
* adds option method -> $().plugin('option', {...})
* @param {Function} PluginClass - constructor class
*/
function addOptionMethod( PluginClass ) {
// don't overwrite original option method
if ( PluginClass.prototype.option ) {
return;
}
// option setter
PluginClass.prototype.option = function( opts ) {
// bail out if not an object
if ( !$.isPlainObject( opts ) ){
return;
}
this.options = $.extend( true, this.options, opts );
};
}
// -------------------------- plugin bridge -------------------------- //
// helper function for logging errors
// $.error breaks jQuery chaining
var logError = typeof console === 'undefined' ? noop :
function( message ) {
console.error( message );
};
/**
* jQuery plugin bridge, access methods like $elem.plugin('method')
* @param {String} namespace - plugin name
* @param {Function} PluginClass - constructor class
*/
function bridge( namespace, PluginClass ) {
// add to jQuery fn namespace
$.fn[ namespace ] = function( options ) {
if ( typeof options === 'string' ) {
// call plugin method when first argument is a string
// get arguments for method
var args = slice.call( arguments, 1 );
for ( var i=0, len = this.length; i < len; i++ ) {
var elem = this[i];
var instance = $.data( elem, namespace );
if ( !instance ) {
logError( "cannot call methods on " + namespace + " prior to initialization; " +
"attempted to call '" + options + "'" );
continue;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
logError( "no such method '" + options + "' for " + namespace + " instance" );
continue;
}
// trigger method with arguments
var returnValue = instance[ options ].apply( instance, args );
// break look and return first value if provided
if ( returnValue !== undefined ) {
return returnValue;
}
}
// return this if no return value
return this;
} else {
return this.each( function() {
var instance = $.data( this, namespace );
if ( instance ) {
// apply options & init
instance.option( options );
instance._init();
} else {
// initialize new instance
instance = new PluginClass( this, options );
$.data( this, namespace, instance );
}
});
}
};
}
// -------------------------- bridget -------------------------- //
/**
* converts a Prototypical class into a proper jQuery plugin
* the class must have a ._init method
* @param {String} namespace - plugin name, used in $().pluginName
* @param {Function} PluginClass - constructor class
*/
$.bridget = function( namespace, PluginClass ) {
addOptionMethod( PluginClass );
bridge( namespace, PluginClass );
};
return $.bridget;
}
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( 'jquery-bridget/jquery.bridget',[ 'jquery' ], defineBridget );
} else if ( typeof exports === 'object' ) {
defineBridget( require('jquery') );
} else {
// get jquery from browser global
defineBridget( window.jQuery );
}
})( window );
/*!
* classie v1.0.1
* class helper functions
* from bonzo https://github.com/ded/bonzo
* MIT license
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
* classie.toggle( elem, 'my-class' )
*/
/*jshint browser: true, strict: true, undef: true, unused: true */
/*global define: false, module: false */
( function( window ) {
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( 'classie/classie',classie );
} else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = classie;
} else {
// browser global
window.classie = classie;
}
})( window );
/*!
* getStyleProperty v1.0.4
* original by kangax
* http://perfectionkills.com/feature-testing-css-properties/
* MIT license
*/
/*jshint browser: true, strict: true, undef: true */
/*global define: false, exports: false, module: false */
( function( window ) {
var prefixes = 'Webkit Moz ms Ms O'.split(' ');
var docElemStyle = document.documentElement.style;
function getStyleProperty( propName ) {
if ( !propName ) {
return;
}
// test standard property first
if ( typeof docElemStyle[ propName ] === 'string' ) {
return propName;
}
// capitalize
propName = propName.charAt(0).toUpperCase() + propName.slice(1);
// test vendor specific properties
var prefixed;
for ( var i=0, len = prefixes.length; i < len; i++ ) {
prefixed = prefixes[i] + propName;
if ( typeof docElemStyle[ prefixed ] === 'string' ) {
return prefixed;
}
}
}
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( 'get-style-property/get-style-property',[],function() {
return getStyleProperty;
});
} else if ( typeof exports === 'object' ) {
// CommonJS for Component
module.exports = getStyleProperty;
} else {
// browser global
window.getStyleProperty = getStyleProperty;
}
})( window );
/*!
* getSize v1.2.2
* measure size of elements
* MIT license
*/
/*jshint browser: true, strict: true, undef: true, unused: true */
/*global define: false, exports: false, require: false, module: false, console: false */
( function( window, undefined ) {
// -------------------------- helpers -------------------------- //
// get a number from a string, not a percentage
function getStyleSize( value ) {
var num = parseFloat( value );
// not a percent like '100%', and a number
var isValid = value.indexOf('%') === -1 && !isNaN( num );
return isValid && num;
}
function noop() {}
var logError = typeof console === 'undefined' ? noop :
function( message ) {
console.error( message );
};
// -------------------------- measurements -------------------------- //
var measurements = [
'paddingLeft',
'paddingRight',
'paddingTop',
'paddingBottom',
'marginLeft',
'marginRight',
'marginTop',
'marginBottom',
'borderLeftWidth',
'borderRightWidth',
'borderTopWidth',
'borderBottomWidth'
];
function getZeroSize() {
var size = {
width: 0,
height: 0,
innerWidth: 0,
innerHeight: 0,
outerWidth: 0,
outerHeight: 0
};
for ( var i=0, len = measurements.length; i < len; i++ ) {
var measurement = measurements[i];
size[ measurement ] = 0;
}
return size;
}
function defineGetSize( getStyleProperty ) {
// -------------------------- setup -------------------------- //
var isSetup = false;
var getStyle, boxSizingProp, isBoxSizeOuter;
/**
* setup vars and functions
* do it on initial getSize(), rather than on script load
* For Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=548397
*/
function setup() {
// setup once
if ( isSetup ) {
return;
}
isSetup = true;
var getComputedStyle = window.getComputedStyle;
getStyle = ( function() {
var getStyleFn = getComputedStyle ?
function( elem ) {
return getComputedStyle( elem, null );
} :
function( elem ) {
return elem.currentStyle;
};
return function getStyle( elem ) {
var style = getStyleFn( elem );
if ( !style ) {
logError( 'Style returned ' + style +
'. Are you running this code in a hidden iframe on Firefox? ' +
'See http://bit.ly/getsizebug1' );
}
return style;
};
})();
// -------------------------- box sizing -------------------------- //
boxSizingProp = getStyleProperty('boxSizing');
/**
* WebKit measures the outer-width on style.width on border-box elems
* IE & Firefox measures the inner-width
*/
if ( boxSizingProp ) {
var div = document.createElement('div');
div.style.width = '200px';
div.style.padding = '1px 2px 3px 4px';
div.style.borderStyle = 'solid';
div.style.borderWidth = '1px 2px 3px 4px';
div.style[ boxSizingProp ] = 'border-box';
var body = document.body || document.documentElement;
body.appendChild( div );
var style = getStyle( div );
isBoxSizeOuter = getStyleSize( style.width ) === 200;
body.removeChild( div );
}
}
// -------------------------- getSize -------------------------- //
function getSize( elem ) {
setup();
// use querySeletor if elem is string
if ( typeof elem === 'string' ) {
elem = document.querySelector( elem );
}
// do not proceed on non-objects
if ( !elem || typeof elem !== 'object' || !elem.nodeType ) {
return;
}
var style = getStyle( elem );
// if hidden, everything is 0
if ( style.display === 'none' ) {
return getZeroSize();
}
var size = {};
size.width = elem.offsetWidth;
size.height = elem.offsetHeight;
var isBorderBox = size.isBorderBox = !!( boxSizingProp &&
style[ boxSizingProp ] && style[ boxSizingProp ] === 'border-box' );
// get all measurements
for ( var i=0, len = measurements.length; i < len; i++ ) {
var measurement = measurements[i];
var value = style[ measurement ];
value = mungeNonPixel( elem, value );
var num = parseFloat( value );
// any 'auto', 'medium' value will be 0
size[ measurement ] = !isNaN( num ) ? num : 0;
}
var paddingWidth = size.paddingLeft + size.paddingRight;
var paddingHeight = size.paddingTop + size.paddingBottom;
var marginWidth = size.marginLeft + size.marginRight;
var marginHeight = size.marginTop + size.marginBottom;
var borderWidth = size.borderLeftWidth + size.borderRightWidth;
var borderHeight = size.borderTopWidth + size.borderBottomWidth;
var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;
// overwrite width and height if we can get it from style
var styleWidth = getStyleSize( style.width );
if ( styleWidth !== false ) {
size.width = styleWidth +
// add padding and border unless it's already including it
( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
}
var styleHeight = getStyleSize( style.height );
if ( styleHeight !== false ) {
size.height = styleHeight +
// add padding and border unless it's already including it
( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
}
size.innerWidth = size.width - ( paddingWidth + borderWidth );
size.innerHeight = size.height - ( paddingHeight + borderHeight );
size.outerWidth = size.width + marginWidth;
size.outerHeight = size.height + marginHeight;
return size;
}
// IE8 returns percent values, not pixels
// taken from jQuery's curCSS
function mungeNonPixel( elem, value ) {
// IE8 and has percent value
if ( window.getComputedStyle || value.indexOf('%') === -1 ) {
return value;
}
var style = elem.style;
// Remember the original values
var left = style.left;
var rs = elem.runtimeStyle;
var rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = value;
value = style.pixelLeft;
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
return value;
}
return getSize;
}
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD for RequireJS
define( 'get-size/get-size',[ 'get-style-property/get-style-property' ], defineGetSize );
} else if ( typeof exports === 'object' ) {
// CommonJS for Component
module.exports = defineGetSize( require('desandro-get-style-property') );
} else {
// browser global
window.getSize = defineGetSize( window.getStyleProperty );
}
})( window );
/*!
* eventie v1.0.6
* event binding helper
* eventie.bind( elem, 'click', myFn )
* eventie.unbind( elem, 'click', myFn )
* MIT license
*/
/*jshint browser: true, undef: true, unused: true */
/*global define: false, module: false */
( function( window ) {
var docElem = document.documentElement;
var bind = function() {};
function getIEEvent( obj ) {
var event = window.event;
// add event.target
event.target = event.target || event.srcElement || obj;
return event;
}
if ( docElem.addEventListener ) {
bind = function( obj, type, fn ) {
obj.addEventListener( type, fn, false );
};
} else if ( docElem.attachEvent ) {
bind = function( obj, type, fn ) {
obj[ type + fn ] = fn.handleEvent ?
function() {
var event = getIEEvent( obj );
fn.handleEvent.call( fn, event );
} :
function() {
var event = getIEEvent( obj );
fn.call( obj, event );
};
obj.attachEvent( "on" + type, obj[ type + fn ] );
};
}
var unbind = function() {};
if ( docElem.removeEventListener ) {
unbind = function( obj, type, fn ) {
obj.removeEventListener( type, fn, false );
};
} else if ( docElem.detachEvent ) {
unbind = function( obj, type, fn ) {
obj.detachEvent( "on" + type, obj[ type + fn ] );
try {
delete obj[ type + fn ];
} catch ( err ) {
// can't delete window object properties
obj[ type + fn ] = undefined;
}
};
}
var eventie = {
bind: bind,
unbind: unbind
};
// ----- module definition ----- //
if ( typeof define === 'function' && define.amd ) {
// AMD
define( 'eventie/eventie',eventie );
} else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = eventie;
} else {
// browser global
window.eventie = eventie;
}
})( window );
/*!
* EventEmitter v4.2.11 - git.io/ee
* Unlicense - http://unlicense.org/
* Oliver Caldwell - http://oli.me.uk/
* @preserve
*/
;(function () {
/**
* Class for managing events.
* Can be extended to provide event functionality in other classes.
*
* @class EventEmitter Manages event registering and emitting.
*/
function EventEmitter() {}
// Shortcuts to improve speed and size
var proto = EventEmitter.prototype;
var exports = this;
var originalGlobalValue = exports.EventEmitter;
/**
* Finds the index of the listener for the event in its storage array.
*
* @param {Function[]} listeners Array of listeners to search through.
* @param {Function} listener Method to look for.
* @return {Number} Index of the specified listener, -1 if not found
* @api private
*/
function indexOfListener(listeners, listener) {
var i = listeners.length;
while (i--) {
if (listeners[i].listener === listener) {
return i;
}
}
return -1;
}
/**
* Alias a method while keeping the context correct, to allow for overwriting of target method.
*
* @param {String} name The name of the target method.
* @return {Function} The aliased method
* @api private
*/
function alias(name) {
return function aliasClosure() {
return this[name].apply(this, arguments);
};
}
/**
* Returns the listener array for the specified event.
* Will initialise the event object and listener arrays if required.
* Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them.
* Each property in the object response is an array of listener functions.
*
* @param {String|RegExp} evt Name of the event to return the listeners from.
* @return {Function[]|Object} All listener functions for the event.
*/
proto.getListeners = function getListeners(evt) {
var events = this._getEvents();
var response;
var key;
// Return a concatenated array of all matching events if
// the selector is a regular expression.
if (evt instanceof RegExp) {
response = {};
for (key in events) {
if (events.hasOwnProperty(key) && evt.test(key)) {
response[key] = events[key];
}
}
}
else {
response = events[evt] || (events[evt] = []);
}
return response;
};
/**
* Takes a list of listener objects and flattens it into a list of listener functions.
*
* @param {Object[]} listeners Raw listener objects.
* @return {Function[]} Just the listener functions.
*/
proto.flattenListeners = function flattenListeners(listeners) {
var flatListeners = [];
var i;
for (i = 0; i < listeners.length; i += 1) {
flatListeners.push(listeners[i].listener);
}
return flatListeners;
};
/**
* Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful.
*
* @param {String|RegExp} evt Name of the event to return the listeners from.
* @return {Object} All listener functions for an event in an object.
*/
proto.getListenersAsObject = function getListenersAsObject(evt) {
var listeners = this.getListeners(evt);
var response;
if (listeners instanceof Array) {
response = {};
response[evt] = listeners;
}
return response || listeners;
};
/**
* Adds a listener function to the specified event.
* The listener will not be added if it is a duplicate.
* If the listener returns true then it will be removed after it is called.
* If you pass a regular expression as the event name then the listener will be added to all events that match it.
*
* @param {String|RegExp} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListener = function addListener(evt, listener) {
var listeners = this.getListenersAsObject(evt);
var listenerIsWrapped = typeof listener === 'object';
var key;
for (key in listeners) {
if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) {
listeners[key].push(listenerIsWrapped ? listener : {
listener: listener,
once: false
});
}
}
return this;
};
/**
* Alias of addListener
*/
proto.on = alias('addListener');
/**
* Semi-alias of addListener. It will add a listener that will be
* automatically removed after its first execution.
*
* @param {String|RegExp} evt Name of the event to attach the listener to.
* @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addOnceListener = function addOnceListener(evt, listener) {
return this.addListener(evt, {
listener: listener,
once: true
});
};
/**
* Alias of addOnceListener.
*/
proto.once = alias('addOnceListener');
/**
* Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad.
* You need to tell it what event names should be matched by a regex.
*
* @param {String} evt Name of the event to create.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.defineEvent = function defineEvent(evt) {
this.getListeners(evt);
return this;
};
/**
* Uses defineEvent to define multiple events.
*
* @param {String[]} evts An array of event names to define.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.defineEvents = function defineEvents(evts) {
for (var i = 0; i < evts.length; i += 1) {
this.defineEvent(evts[i]);
}
return this;
};
/**
* Removes a listener function from the specified event.
* When passed a regular expression as the event name, it will remove the listener from all events that match it.
*
* @param {String|RegExp} evt Name of the event to remove the listener from.
* @param {Function} listener Method to remove from the event.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeListener = function removeListener(evt, listener) {
var listeners = this.getListenersAsObject(evt);
var index;
var key;
for (key in listeners) {
if (listeners.hasOwnProperty(key)) {
index = indexOfListener(listeners[key], listener);
if (index !== -1) {
listeners[key].splice(index, 1);
}
}
}
return this;
};
/**
* Alias of removeListener
*/
proto.off = alias('removeListener');
/**
* Adds listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added.
* You can also pass it a regular expression to add the array of listeners to all events that match it.
* Yeah, this function does quite a bit. That's probably a bad thing.
*
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.addListeners = function addListeners(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(false, evt, listeners);
};
/**
* Removes listeners in bulk using the manipulateListeners method.
* If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be removed.
* You can also pass it a regular expression to remove the listeners from all events that match it.
*
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to remove.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeListeners = function removeListeners(evt, listeners) {
// Pass through to manipulateListeners
return this.manipulateListeners(true, evt, listeners);
};
/**
* Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level.
* The first argument will determine if the listeners are removed (true) or added (false).
* If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays.
* You can also pass it an event name and an array of listeners to be added/removed.
* You can also pass it a regular expression to manipulate the listeners of all events that match it.
*
* @param {Boolean} remove True if you want to remove listeners, false if you want to add.
* @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once.
* @param {Function[]} [listeners] An optional array of listener functions to add/remove.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) {
var i;
var value;
var single = remove ? this.removeListener : this.addListener;
var multiple = remove ? this.removeListeners : this.addListeners;
// If evt is an object then pass each of its properties to this method
if (typeof evt === 'object' && !(evt instanceof RegExp)) {
for (i in evt) {
if (evt.hasOwnProperty(i) && (value = evt[i])) {
// Pass the single listener straight through to the singular method
if (typeof value === 'function') {
single.call(this, i, value);
}
else {
// Otherwise pass back to the multiple function
multiple.call(this, i, value);
}
}
}
}
else {
// So evt must be a string
// And listeners must be an array of listeners
// Loop over it and pass each one to the multiple method
i = listeners.length;
while (i--) {
single.call(this, evt, listeners[i]);
}
}
return this;
};
/**
* Removes all listeners from a specified event.
* If you do not specify an event then all listeners will be removed.
* That means every event will be emptied.
* You can also pass a regex to remove all events that match it.
*
* @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.removeEvent = function removeEvent(evt) {
var type = typeof evt;
var events = this._getEvents();
var key;
// Remove different things depending on the state of evt
if (type === 'string') {
// Remove all listeners for the specified event
delete events[evt];
}
else if (evt instanceof RegExp) {
// Remove all events matching the regex.
for (key in events) {
if (events.hasOwnProperty(key) && evt.test(key)) {
delete events[key];
}
}
}
else {
// Remove all listeners in all events
delete this._events;
}
return this;
};
/**
* Alias of removeEvent.
*
* Added to mirror the node API.
*/
proto.removeAllListeners = alias('removeEvent');
/**
* Emits an event of your choice.
* When emitted, every listener attached to that event will be executed.
* If you pass the optional argument array then those arguments will be passed to every listener upon execution.
* Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately.
* So they will not arrive within the array on the other side, they will be separate.
* You can also pass a regular expression to emit to all events that match it.
*
* @param {String|RegExp} evt Name of the event to emit and execute listeners for.
* @param {Array} [args] Optional array of arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.emitEvent = function emitEvent(evt, args) {
var listeners = this.getListenersAsObject(evt);
var listener;
var i;
var key;
var response;
for (key in listeners) {
if (listeners.hasOwnProperty(key)) {
i = listeners[key].length;
while (i--) {
// If the listener returns true then it shall be removed from the event
// The function is executed either with a basic call or an apply if there is an args array
listener = listeners[key][i];
if (listener.once === true) {
this.removeListener(evt, listener.listener);
}
response = listener.listener.apply(this, args || []);
if (response === this._getOnceReturnValue()) {
this.removeListener(evt, listener.listener);
}
}
}
}
return this;
};
/**
* Alias of emitEvent
*/
proto.trigger = alias('emitEvent');
/**
* Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on.
* As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it.
*
* @param {String|RegExp} evt Name of the event to emit and execute listeners for.
* @param {...*} Optional additional arguments to be passed to each listener.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.emit = function emit(evt) {
var args = Array.prototype.slice.call(arguments, 1);
return this.emitEvent(evt, args);
};
/**
* Sets the current value to check against when executing listeners. If a
* listeners return value matches the one set here then it will be removed
* after execution. This value defaults to true.
*
* @param {*} value The new value to check for when executing listeners.
* @return {Object} Current instance of EventEmitter for chaining.
*/
proto.setOnceReturnValue = function setOnceReturnValue(value) {
this._onceReturnValue = value;
return this;
};
/**
* Fetches the current value to check against when executing listeners. If
* the listeners return value matches this one then it should be removed
* automatically. It will return true by default.
*
* @return {*|Boolean} The current value to check for or the default, true.
* @api private
*/
proto._getOnceReturnValue = function _getOnceReturnValue() {
if (this.hasOwnProperty('_onceReturnValue')) {
return this._onceReturnValue;
}
else {
return true;
}
};
/**
* Fetches the events object and creates one if required.
*
* @return {Object} The events storage object.
* @api private
*/
proto._getEvents = function _getEvents() {
return this._events || (this._events = {});
};
/**
* Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version.
*
* @return {Function} Non conflicting EventEmitter class.
*/
EventEmitter.noConflict = function noConflict() {
exports.EventEmitter = originalGlobalValue;
return EventEmitter;
};
// Expose the class either via AMD, CommonJS or the global object
if (typeof define === 'function' && define.amd) {
define('eventEmitter/EventEmitter',[],function () {
return EventEmitter;
});
}
else if (typeof module === 'object' && module.exports){
module.exports = EventEmitter;
}
else {
exports.EventEmitter = EventEmitter;
}
}.call(this));
/*!
* Unipointer v1.1.0
* base class for doing one thing with pointer event
* MIT license
*/
/*jshint browser: true, undef: true, unused: true, strict: true */
/*global define: false, module: false, require: false */
( function( window, factory ) {
// universal module definition
if ( typeof define == 'function' && define.amd ) {
// AMD
define( 'unipointer/unipointer',[
'eventEmitter/EventEmitter',
'eventie/eventie'
], function( EventEmitter, eventie ) {
return factory( window, EventEmitter, eventie );
});
} else if ( typeof exports == 'object' ) {
// CommonJS
module.exports = factory(
window,
require('wolfy87-eventemitter'),
require('eventie')
);
} else {
// browser global
window.Unipointer = factory(
window,
window.EventEmitter,
window.eventie
);
}
}( window, function factory( window, EventEmitter, eventie ) {
function noop() {}
function Unipointer() {}
// inherit EventEmitter
Unipointer.prototype = new EventEmitter();
Unipointer.prototype.bindStartEvent = function( elem ) {
this._bindStartEvent( elem, true );
};
Unipointer.prototype.unbindStartEvent = function( elem ) {
this._bindStartEvent( elem, false );
};
/**
* works as unbinder, as you can ._bindStart( false ) to unbind
* @param {Boolean} isBind - will unbind if falsey
*/
Unipointer.prototype._bindStartEvent = function( elem, isBind ) {
// munge isBind, default to true
isBind = isBind === undefined ? true : !!isBind;
var bindMethod = isBind ? 'bind' : 'unbind';
if ( window.navigator.pointerEnabled ) {
// W3C Pointer Events, IE11. See https://coderwall.com/p/mfreca
eventie[ bindMethod ]( elem, 'pointerdown', this );
} else if ( window.navigator.msPointerEnabled ) {
// IE10 Pointer Events
eventie[ bindMethod ]( elem, 'MSPointerDown', this );
} else {
// listen for both, for devices like Chrome Pixel
eventie[ bindMethod ]( elem, 'mousedown', this );
eventie[ bindMethod ]( elem, 'touchstart', this );
}
};
// trigger handler methods for events
Unipointer.prototype.handleEvent = function( event ) {
var method = 'on' + event.type;
if ( this[ method ] ) {
this[ method ]( event );
}
};
// returns the touch that we're keeping track of
Unipointer.prototype.getTouch = function( touches ) {
for ( var i=0, len = touches.length; i < len; i++ ) {
var touch = touches[i];
if ( touch.identifier == this.pointerIdentifier ) {
return touch;
}
}
};
// ----- start event ----- //
Unipointer.prototype.onmousedown = function( event ) {
// dismiss clicks from right or middle buttons
var button = event.button;
if ( button && ( button !== 0 && button !== 1 ) ) {
return;
}
this._pointerDown( event, event );
};
Unipointer.prototype.ontouchstart = function( event ) {
this._pointerDown( event, event.changedTouches[0] );
};
Unipointer.prototype.onMSPointerDown =
Unipointer.prototype.onpointerdown = function( event ) {
this._pointerDown( event, event );
};
/**
* pointer start
* @param {Event} event
* @param {Event or Touch} pointer
*/
Unipointer.prototype._pointerDown = function( event, pointer ) {
// dismiss other pointers
if ( this.isPointerDown ) {
return;
}
this.isPointerDown = true;
// save pointer identifier to match up touch events
this.pointerIdentifier = pointer.pointerId !== undefined ?
// pointerId for pointer events, touch.indentifier for touch events
pointer.pointerId : pointer.identifier;
this.pointerDown( event, pointer );
};
Unipointer.prototype.pointerDown = function( event, pointer ) {
this._bindPostStartEvents( event );
this.emitEvent( 'pointerDown', [ event, pointer ] );
};
// hash of events to be bound after start event
var postStartEvents = {
mousedown: [ 'mousemove', 'mouseup' ],
touchstart: [ 'touchmove', 'touchend', 'touchcancel' ],
pointerdown: [ 'pointermove', 'pointerup', 'pointercancel' ],
MSPointerDown: [ 'MSPointerMove', 'MSPointerUp', 'MSPointerCancel' ]
};
Unipointer.prototype._bindPostStartEvents = function( event ) {
if ( !event ) {
return;
}
// get proper events to match start event
var events = postStartEvents[ event.type ];
// IE8 needs to be bound to document
var node = event.preventDefault ? window : document;
// bind events to node
for ( var i=0, len = events.length; i < len; i++ ) {
var evnt = events[i];
eventie.bind( node, evnt, this );
}
// save these arguments
this._boundPointerEvents = {
events: events,
node: node
};
};
Unipointer.prototype._unbindPostStartEvents = function() {
var args = this._boundPointerEvents;
// IE8 can trigger dragEnd twice, check for _boundEvents
if ( !args || !args.events ) {
return;
}
for ( var i=0, len = args.events.length; i < len; i++ ) {
var event = args.events[i];
eventie.unbind( args.node, event, this );
}
delete this._boundPointerEvents;
};
// ----- move event ----- //
Unipointer.prototype.onmousemove = function( event ) {
this._pointerMove( event, event );
};
Unipointer.prototype.onMSPointerMove =
Unipointer.prototype.onpointermove = function( event ) {
if ( event.pointerId == this.pointerIdentifier ) {
this._pointerMove( event, event );
}
};
Unipointer.prototype.ontouchmove = function( event ) {
var touch = this.getTouch( event.changedTouches );
if ( touch ) {
this._pointerMove( event, touch );
}
};
/**
* pointer move
* @param {Event} event
* @param {Event or Touch} pointer
* @private
*/
Unipointer.prototype._pointerMove = function( event, pointer ) {
this.pointerMove( event, pointer );
};
// public
Unipointer.prototype.pointerMove = function( event, pointer ) {
this.emitEvent( 'pointerMove', [ event, pointer ] );
};
// ----- end event ----- //
Unipointer.prototype.onmouseup = function( event ) {
this._pointerUp( event, event );
};
Unipointer.prototype.onMSPointerUp =
Unipointer.prototype.onpointerup = function( event ) {
if ( event.pointerId == this.pointerIdentifier ) {
this._pointerUp( event, event );
}
};
Unipointer.prototype.ontouchend = function( event ) {
var touch = this.getTouch( event.changedTouches );
if ( touch ) {
this._pointerUp( event, touch );
}
};
/**
* pointer up
* @param {Event} event
* @param {Event or Touch} pointer
* @private
*/
Unipointer.prototype._pointerUp = function( event, pointer ) {
this._pointerDone();
this.pointerUp( event, pointer );
};
// public
Unipointer.prototype.pointerUp = function( event, pointer ) {
this.emitEvent( 'pointerUp', [ event, pointer ] );
};
// ----- pointer done ----- //
// triggered on pointer up & pointer cancel
Unipointer.prototype._pointerDone = function() {
// reset properties
this.isPointerDown = false;
delete this.pointerIdentifier;
// remove events
this._unbindPostStartEvents();
this.pointerDone();
};
Unipointer.prototype.pointerDone = noop;
// ----- pointer cancel ----- //
Unipointer.prototype.onMSPointerCancel =
Unipointer.prototype.onpointercancel = function( event ) {
if ( event.pointerId == this.pointerIdentifier ) {
this._pointerCancel( event, event );
}
};
Unipointer.prototype.ontouchcancel = function( event ) {
var touch = this.getTouch( event.changedTouches );
if ( touch ) {
this._pointerCancel( event, touch );
}
};
/**
* pointer cancel
* @param {Event} event
* @param {Event or Touch} pointer
* @private
*/
Unipointer.prototype._pointerCancel = function( event, pointer ) {
this._pointerDone();
this.pointerCancel( event, pointer );
};
// public
Unipointer.prototype.pointerCancel = function( event, pointer ) {
this.emitEvent( 'pointerCancel', [ event, pointer ] );
};
// ----- ----- //
// utility function for getting x/y cooridinates from event, because IE8
Unipointer.getPointerPoint = function( pointer ) {
return {
x: pointer.pageX !== undefined ? pointer.pageX : pointer.clientX,
y: pointer.pageY !== undefined ? pointer.pageY : pointer.clientY
};
};
// ----- ----- //
return Unipointer;
}));
/*!
* Unidragger v1.1.0
* Draggable base class
* MIT license
*/
/*jshint browser: true, unused: true, undef: true, strict: true */
( function( window, factory ) {
/*global define: false, module: false, require: false */
// universal module definition
if ( typeof define == 'function' && define.amd ) {
// AMD
define( 'unidragger/unidragger',[
'eventie/eventie',
'unipointer/unipointer'
], function( eventie, Unipointer ) {
return factory( window, eventie, Unipointer );
});
} else if ( typeof exports == 'object' ) {
// CommonJS
module.exports = factory(
window,
require('eventie'),
require('unipointer')
);
} else {
// browser global
window.Unidragger = factory(
window,
window.eventie,
window.Unipointer
);
}
}( window, function factory( window, eventie, Unipointer ) {
// ----- ----- //
function noop() {}
// handle IE8 prevent default
function preventDefaultEvent( event ) {
if ( event.preventDefault ) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
function getParentLink( elem ) {
while ( elem != document.body ) {
elem = elem.parentNode;
if ( elem.nodeName == 'A' ) {
return elem;
}
}
}
// -------------------------- Unidragger -------------------------- //
function Unidragger() {}
// inherit Unipointer & EventEmitter
Unidragger.prototype = new Unipointer();
// ----- bind start ----- //
Unidragger.prototype.bindHandles = function() {
this._bindHandles( true );
};
Unidragger.prototype.unbindHandles = function() {
this._bindHandles( false );
};
var navigator = window.navigator;
/**
* works as unbinder, as you can .bindHandles( false ) to unbind
* @param {Boolean} isBind - will unbind if falsey
*/
Unidragger.prototype._bindHandles = function( isBind ) {
// munge isBind, default to true
isBind = isBind === undefined ? true : !!isBind;
// extra bind logic
var binderExtra;
if ( navigator.pointerEnabled ) {
binderExtra = function( handle ) {
// disable scrolling on the element
handle.style.touchAction = isBind ? 'none' : '';
};
} else if ( navigator.msPointerEnabled ) {
binderExtra = function( handle ) {
// disable scrolling on the element
handle.style.msTouchAction = isBind ? 'none' : '';
};
} else {
binderExtra = function() {
// TODO re-enable img.ondragstart when unbinding
if ( isBind ) {
disableImgOndragstart( handle );
}
};
}
// bind each handle
var bindMethod = isBind ? 'bind' : 'unbind';
for ( var i=0, len = this.handles.length; i < len; i++ ) {
var handle = this.handles[i];
this._bindStartEvent( handle, isBind );
binderExtra( handle );
eventie[ bindMethod ]( handle, 'click', this );
}
};
// remove default dragging interaction on all images in IE8
// IE8 does its own drag thing on images, which messes stuff up
function noDragStart() {
return false;
}
// TODO replace this with a IE8 test
var isIE8 = 'attachEvent' in document.documentElement;
// IE8 only
var disableImgOndragstart = !isIE8 ? noop : function( handle ) {
if ( handle.nodeName == 'IMG' ) {
handle.ondragstart = noDragStart;
}
var images = handle.querySelectorAll('img');
for ( var i=0, len = images.length; i < len; i++ ) {
var img = images[i];
img.ondragstart = noDragStart;
}
};
// ----- start event ----- //
var allowTouchstartNodes = Unidragger.allowTouchstartNodes = {
INPUT: true,
A: true,
BUTTON: true,
SELECT: true
};
/**
* pointer start
* @param {Event} event
* @param {Event or Touch} pointer
*/
Unidragger.prototype.pointerDown = function( event, pointer ) {
this._dragPointerDown( event, pointer );
// kludge to blur focused inputs in dragger
var focused = document.activeElement;
if ( focused && focused.blur ) {
focused.blur();
}
// bind move and end events
this._bindPostStartEvents( event );
this.emitEvent( 'pointerDown', [ event, pointer ] );
};
// base pointer down logic
Unidragger.prototype._dragPointerDown = function( event, pointer ) {
// track to see when dragging starts
this.pointerDownPoint = Unipointer.getPointerPoint( pointer );
var targetNodeName = event.target.nodeName;
// HACK iOS, allow clicks on buttons, inputs, and links, or children of links
var isTouchstartNode = event.type == 'touchstart' &&
( allowTouchstartNodes[ targetNodeName ] || getParentLink( event.target ) );
// do not prevent default on touchstart nodes or <select>
if ( !isTouchstartNode && targetNodeName != 'SELECT' ) {
preventDefaultEvent( event );
}
};
// ----- move event ----- //
/**
* drag move
* @param {Event} event
* @param {Event or Touch} pointer
*/
Unidragger.prototype.pointerMove = function( event, pointer ) {
var moveVector = this._dragPointerMove( event, pointer );
this.emitEvent( 'pointerMove', [ event, pointer, moveVector ] );
this._dragMove( event, pointer, moveVector );
};
// base pointer move logic
Unidragger.prototype._dragPointerMove = function( event, pointer ) {
var movePoint = Unipointer.getPointerPoint( pointer );
var moveVector = {
x: movePoint.x - this.pointerDownPoint.x,
y: movePoint.y - this.pointerDownPoint.y
};
// start drag if pointer has moved far enough to start drag
if ( !this.isDragging && this.hasDragStarted( moveVector ) ) {
this._dragStart( event, pointer );
}
return moveVector;
};
// condition if pointer has moved far enough to start drag
Unidragger.prototype.hasDragStarted = function( moveVector ) {
return Math.abs( moveVector.x ) > 3 || Math.abs( moveVector.y ) > 3;
};
// ----- end event ----- //
/**
* pointer up
* @param {Event} event
* @param {Event or Touch} pointer
*/
Unidragger.prototype.pointerUp = function( event, pointer ) {
this.emitEvent( 'pointerUp', [ event, pointer ] );
this._dragPointerUp( event, pointer );
};
Unidragger.prototype._dragPointerUp = function( event, pointer ) {
if ( this.isDragging ) {
this._dragEnd( event, pointer );
} else {
// pointer didn't move enough for drag to start
this._staticClick( event, pointer );
}
};
// -------------------------- drag -------------------------- //
// dragStart
Unidragger.prototype._dragStart = function( event, pointer ) {
this.isDragging = true;
this.dragStartPoint = Unidragger.getPointerPoint( pointer );
// prevent clicks
this.isPreventingClicks = true;
this.dragStart( event, pointer );
};
Unidragger.prototype.dragStart = function( event, pointer ) {
this.emitEvent( 'dragStart', [ event, pointer ] );
};
// dragMove
Unidragger.prototype._dragMove = function( event, pointer, moveVector ) {
// do not drag if not dragging yet
if ( !this.isDragging ) {
return;
}
this.dragMove( event, pointer, moveVector );
};
Unidragger.prototype.dragMove = function( event, pointer, moveVector ) {
this.emitEvent( 'dragMove', [ event, pointer, moveVector ] );
};
// dragEnd
Unidragger.prototype._dragEnd = function( event, pointer ) {
// set flags
this.isDragging = false;
// re-enable clicking async
var _this = this;
setTimeout( function() {
delete _this.isPreventingClicks;
});
this.dragEnd( event, pointer );
};
Unidragger.prototype.dragEnd = function( event, pointer ) {
this.emitEvent( 'dragEnd', [ event, pointer ] );
};
// ----- onclick ----- //
// handle all clicks and prevent clicks when dragging
Unidragger.prototype.onclick = function( event ) {
if ( this.isPreventingClicks ) {
preventDefaultEvent( event );
}
};
// ----- staticClick ----- //
// triggered after pointer down & up with no/tiny movement
Unidragger.prototype._staticClick = function( event, pointer ) {
// allow click in text input
if ( event.target.nodeName == 'INPUT' && event.target.type == 'text' ) {
event.target.focus();
}
this.staticClick( event, pointer );
};
Unidragger.prototype.staticClick = function( event, pointer ) {
this.emitEvent( 'staticClick', [ event, pointer ] );
};
// ----- ----- //
Unidragger.getPointerPoint = function( pointer ) {
return {
x: pointer.pageX !== undefined ? pointer.pageX : pointer.clientX,
y: pointer.pageY !== undefined ? pointer.pageY : pointer.clientY
};
};
// ----- ----- //
Unidragger.getPointerPoint = Unipointer.getPointerPoint;
return Unidragger;
}));
/*!
* Draggabilly v1.2.0
* Make that shiz draggable
* http://draggabilly.desandro.com
* MIT license
*/
( function( window, factory ) {
if ( typeof define == 'function' && define.amd ) {
// AMD
define( 'draggabilly/draggabilly',[
'classie/classie',
'get-style-property/get-style-property',
'get-size/get-size',
'unidragger/unidragger'
],
function( classie, getStyleProperty, getSize, Unidragger ) {
factory( window, classie, getStyleProperty, getSize, Unidragger );
});
} else if ( typeof exports == 'object' ) {
// CommonJS
module.exports = factory(
window,
require('desandro-classie'),
require('desandro-get-style-property'),
require('get-size'),
require('unidragger')
);
} else {
// browser global
window.Draggabilly = factory(
window,
window.classie,
window.getStyleProperty,
window.getSize,
window.Unidragger
);
}
}( window, function factory( window, classie, getStyleProperty, getSize, Unidragger ) {
// vars
var document = window.document;
function noop() {}
// -------------------------- helpers -------------------------- //
// extend objects
function extend( a, b ) {
for ( var prop in b ) {
a[ prop ] = b[ prop ];
}
return a;
}
// ----- get style ----- //
var defView = document.defaultView;
var getStyle = defView && defView.getComputedStyle ?
function( elem ) {
return defView.getComputedStyle( elem, null );
} :
function( elem ) {
return elem.currentStyle;
};
// http://stackoverflow.com/a/384380/182183
var isElement = ( typeof HTMLElement == 'object' ) ?
function isElementDOM2( obj ) {
return obj instanceof HTMLElement;
} :
function isElementQuirky( obj ) {
return obj && typeof obj == 'object' &&
obj.nodeType == 1 && typeof obj.nodeName == 'string';
};
// -------------------------- requestAnimationFrame -------------------------- //
// https://gist.github.com/1866474
var lastTime = 0;
var prefixes = 'webkit moz ms o'.split(' ');
// get unprefixed rAF and cAF, if present
var requestAnimationFrame = window.requestAnimationFrame;
var cancelAnimationFrame = window.cancelAnimationFrame;
// loop through vendor prefixes and get prefixed rAF and cAF
var prefix;
for( var i = 0; i < prefixes.length; i++ ) {
if ( requestAnimationFrame && cancelAnimationFrame ) {
break;
}
prefix = prefixes[i];
requestAnimationFrame = requestAnimationFrame || window[ prefix + 'RequestAnimationFrame' ];
cancelAnimationFrame = cancelAnimationFrame || window[ prefix + 'CancelAnimationFrame' ] ||
window[ prefix + 'CancelRequestAnimationFrame' ];
}
// fallback to setTimeout and clearTimeout if either request/cancel is not supported
if ( !requestAnimationFrame || !cancelAnimationFrame ) {
requestAnimationFrame = function( callback ) {
var currTime = new Date().getTime();
var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
var id = window.setTimeout( function() {
callback( currTime + timeToCall );
}, timeToCall );
lastTime = currTime + timeToCall;
return id;
};
cancelAnimationFrame = function( id ) {
window.clearTimeout( id );
};
}
// -------------------------- support -------------------------- //
var transformProperty = getStyleProperty('transform');
// TODO fix quick & dirty check for 3D support
var is3d = !!getStyleProperty('perspective');
var jQuery = window.jQuery;
// -------------------------- -------------------------- //
function Draggabilly( element, options ) {
// querySelector if string
this.element = typeof element == 'string' ?
document.querySelector( element ) : element;
if ( jQuery ) {
this.$element = jQuery( this.element );
}
// options
this.options = extend( {}, this.constructor.defaults );
this.option( options );
this._create();
}
// inherit EventEmitter methods
extend( Draggabilly.prototype, Unidragger.prototype );
Draggabilly.defaults = {
};
/**
* set options
* @param {Object} opts
*/
Draggabilly.prototype.option = function( opts ) {
extend( this.options, opts );
};
Draggabilly.prototype._create = function() {
// properties
this.position = {};
this._getPosition();
this.startPoint = { x: 0, y: 0 };
this.dragPoint = { x: 0, y: 0 };
this.startPosition = extend( {}, this.position );
// set relative positioning
var style = getStyle( this.element );
if ( style.position != 'relative' && style.position != 'absolute' ) {
this.element.style.position = 'relative';
}
this.enable();
this.setHandles();
};
/**
* set this.handles and bind start events to 'em
*/
Draggabilly.prototype.setHandles = function() {
this.handles = this.options.handle ?
this.element.querySelectorAll( this.options.handle ) : [ this.element ];
this.bindHandles();
};
/**
* emits events via eventEmitter and jQuery events
* @param {String} type - name of event
* @param {Event} event - original event
* @param {Array} args - extra arguments
*/
Draggabilly.prototype.dispatchEvent = function( type, event, args ) {
var emitArgs = [ event ].concat( args );
this.emitEvent( type, emitArgs );
var jQuery = window.jQuery;
// trigger jQuery event
if ( jQuery && this.$element ) {
if ( event ) {
// create jQuery event
var $event = jQuery.Event( event );
$event.type = type;
this.$element.trigger( $event, args );
} else {
// just trigger with type if no event available
this.$element.trigger( type, args );
}
}
};
// -------------------------- position -------------------------- //
// get left/top position from style
Draggabilly.prototype._getPosition = function() {
// properties
var style = getStyle( this.element );
var x = parseInt( style.left, 10 );
var y = parseInt( style.top, 10 );
// clean up 'auto' or other non-integer values
this.position.x = isNaN( x ) ? 0 : x;
this.position.y = isNaN( y ) ? 0 : y;
this._addTransformPosition( style );
};
// add transform: translate( x, y ) to position
Draggabilly.prototype._addTransformPosition = function( style ) {
if ( !transformProperty ) {
return;
}
var transform = style[ transformProperty ];
// bail out if value is 'none'
if ( transform.indexOf('matrix') !== 0 ) {
return;
}
// split matrix(1, 0, 0, 1, x, y)
var matrixValues = transform.split(',');
// translate X value is in 12th or 4th position
var xIndex = transform.indexOf('matrix3d') === 0 ? 12 : 4;
var translateX = parseInt( matrixValues[ xIndex ], 10 );
// translate Y value is in 13th or 5th position
var translateY = parseInt( matrixValues[ xIndex + 1 ], 10 );
this.position.x += translateX;
this.position.y += translateY;
};
// -------------------------- events -------------------------- //
/**
* pointer start
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.pointerDown = function( event, pointer ) {
this._dragPointerDown( event, pointer );
// kludge to blur focused inputs in dragger
var focused = document.activeElement;
if ( focused && focused.blur ) {
focused.blur();
}
// bind move and end events
this._bindPostStartEvents( event );
classie.add( this.element, 'is-pointer-down' );
this.dispatchEvent( 'pointerDown', event, [ pointer ] );
};
/**
* drag move
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.pointerMove = function( event, pointer ) {
var moveVector = this._dragPointerMove( event, pointer );
this.dispatchEvent( 'pointerMove', event, [ pointer, moveVector ] );
this._dragMove( event, pointer, moveVector );
};
/**
* drag start
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.dragStart = function( event, pointer ) {
if ( !this.isEnabled ) {
return;
}
this._getPosition();
this.measureContainment();
// position _when_ drag began
this.startPosition.x = this.position.x;
this.startPosition.y = this.position.y;
// reset left/top style
this.setLeftTop();
this.dragPoint.x = 0;
this.dragPoint.y = 0;
// reset isDragging flag
this.isDragging = true;
classie.add( this.element, 'is-dragging' );
this.dispatchEvent( 'dragStart', event, [ pointer ] );
// start animation
this.animate();
};
Draggabilly.prototype.measureContainment = function() {
var containment = this.options.containment;
if ( !containment ) {
return;
}
this.size = getSize( this.element );
var elemRect = this.element.getBoundingClientRect();
// use element if element
var container = isElement( containment ) ? containment :
// fallback to querySelector if string
typeof containment == 'string' ? document.querySelector( containment ) :
// otherwise just `true`, use the parent
this.element.parentNode;
this.containerSize = getSize( container );
var containerRect = container.getBoundingClientRect();
this.relativeStartPosition = {
x: elemRect.left - containerRect.left,
y: elemRect.top - containerRect.top
};
};
// ----- move event ----- //
/**
* drag move
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.dragMove = function( event, pointer, moveVector ) {
var dragX = moveVector.x;
var dragY = moveVector.y;
var grid = this.options.grid;
var gridX = grid && grid[0];
var gridY = grid && grid[1];
dragX = applyGrid( dragX, gridX );
dragY = applyGrid( dragY, gridY );
dragX = this.containDrag( 'x', dragX, gridX );
dragY = this.containDrag( 'y', dragY, gridY );
// constrain to axis
dragX = this.options.axis == 'y' ? 0 : dragX;
dragY = this.options.axis == 'x' ? 0 : dragY;
this.position.x = this.startPosition.x + dragX;
this.position.y = this.startPosition.y + dragY;
// set dragPoint properties
this.dragPoint.x = dragX;
this.dragPoint.y = dragY;
this.dispatchEvent( 'dragMove', event, [ pointer, moveVector ] );
};
function applyGrid( value, grid, method ) {
method = method || 'round';
return grid ? Math[ method ]( value / grid ) * grid : value;
}
Draggabilly.prototype.containDrag = function( axis, drag, grid ) {
if ( !this.options.containment ) {
return drag;
}
var measure = axis == 'x' ? 'width' : 'height';
var rel = this.relativeStartPosition[ axis ];
var min = applyGrid( -rel, grid, 'ceil' );
var max = this.containerSize[ measure ] - rel - this.size[ measure ];
max = applyGrid( max, grid, 'floor' );
return Math.min( max, Math.max( min, drag ) );
};
// ----- end event ----- //
/**
* pointer up
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.pointerUp = function( event, pointer ) {
this.dispatchEvent( 'pointerUp', event, [ pointer ] );
this._dragPointerUp( event, pointer );
};
/**
* drag end
* @param {Event} event
* @param {Event or Touch} pointer
*/
Draggabilly.prototype.dragEnd = function( event, pointer ) {
this.isDragging = false;
// use top left position when complete
if ( transformProperty ) {
this.element.style[ transformProperty ] = '';
this.setLeftTop();
}
classie.remove( this.element, 'is-dragging' );
this.dispatchEvent( 'dragEnd', event, [ pointer ] );
};
// -------------------------- animation -------------------------- //
Draggabilly.prototype.animate = function() {
// only render and animate if dragging
if ( !this.isDragging ) {
return;
}
this.positionDrag();
var _this = this;
requestAnimationFrame( function animateFrame() {
_this.animate();
});
};
// transform translate function
var translate = is3d ?
function( x, y ) {
return 'translate3d( ' + x + 'px, ' + y + 'px, 0)';
} :
function( x, y ) {
return 'translate( ' + x + 'px, ' + y + 'px)';
};
// left/top positioning
Draggabilly.prototype.setLeftTop = function() {
this.element.style.left = this.position.x + 'px';
this.element.style.top = this.position.y + 'px';
};
Draggabilly.prototype.positionDrag = transformProperty ?
function() {
// position with transform
this.element.style[ transformProperty ] = translate( this.dragPoint.x, this.dragPoint.y );
} : Draggabilly.prototype.setLeftTop;
// ----- staticClick ----- //
Draggabilly.prototype.staticClick = function( event, pointer ) {
this.dispatchEvent( 'staticClick', event, [ pointer ] );
};
// ----- methods ----- //
Draggabilly.prototype.enable = function() {
this.isEnabled = true;
};
Draggabilly.prototype.disable = function() {
this.isEnabled = false;
if ( this.isDragging ) {
this.dragEnd();
}
};
Draggabilly.prototype.destroy = function() {
this.disable();
// reset styles
if ( transformProperty ) {
this.element.style[ transformProperty ] = '';
}
this.element.style.left = '';
this.element.style.top = '';
this.element.style.position = '';
// unbind handles
this.unbindHandles();
// remove jQuery data
if ( this.$element ) {
this.$element.removeData('draggabilly');
}
};
// ----- jQuery bridget ----- //
// required for jQuery bridget
Draggabilly.prototype._init = noop;
if ( jQuery && jQuery.bridget ) {
jQuery.bridget( 'draggabilly', Draggabilly );
}
// ----- ----- //
return Draggabilly;
}));
|
/*!
* FileInput Danish Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['da'] = {
fileSingle: 'fil',
filePlural: 'filer',
browseLabel: 'Browse …',
removeLabel: 'Fjern',
removeTitle: 'Fjern valgte filer',
cancelLabel: 'Fortryd',
cancelTitle: 'Afbryd nuværende upload',
uploadLabel: 'Upload',
uploadTitle: 'Upload valgte filer',
msgNo: 'Ingen',
msgNoFilesSelected: '',
msgCancelled: 'aflyst',
msgPlaceholder: 'Vælg {files}...',
msgZoomModalHeading: 'Detaljeret visning',
msgFileRequired: 'Du skal vælge en fil at uploade.',
msgSizeTooSmall: 'Fil "{name}" (<b>{size} KB</b>) er for lille og skal være større end <b>{minSize} KB</b>.',
msgSizeTooLarge: 'Fil "{name}" (<b>{size} KB</b>) er større end de tilladte <b>{maxSize} KB</b>.',
msgFilesTooLess: 'Du skal mindst vælge <b>{n}</b> {files} til upload.',
msgFilesTooMany: '<b>({n})</b> filer valgt til upload, men maks. <b>{m}</b> er tilladt.',
msgFileNotFound: 'Filen "{name}" blev ikke fundet!',
msgFileSecured: 'Sikkerhedsrestriktioner forhindrer læsning af "{name}".',
msgFileNotReadable: 'Filen "{name}" kan ikke indlæses.',
msgFilePreviewAborted: 'Filgennemsyn annulleret for "{name}".',
msgFilePreviewError: 'Der skete en fejl under læsningen af filen "{name}".',
msgInvalidFileName: 'Ugyldige eller ikke-understøttede tegn i filnavn "{name}".',
msgInvalidFileType: 'Ukendt type for filen "{name}". Kun "{types}" kan bruges.',
msgInvalidFileExtension: 'Ukendt filtype for filen "{name}". Kun "{extensions}" filer kan bruges.',
msgFileTypes: {
'image': 'image',
'html': 'HTML',
'text': 'text',
'video': 'video',
'audio': 'audio',
'flash': 'flash',
'pdf': 'PDF',
'object': 'object'
},
msgUploadAborted: 'Filupload annulleret',
msgUploadThreshold: 'Arbejder...',
msgUploadBegin: 'Initialiserer...',
msgUploadEnd: 'Udført',
msgUploadEmpty: 'Ingen gyldig data tilgængelig til upload.',
msgUploadError: 'Fejl',
msgValidationError: 'Valideringsfejl',
msgLoading: 'Henter fil {index} af {files} …',
msgProgress: 'Henter fil {index} af {files} - {name} - {percent}% færdiggjort.',
msgSelected: '{n} {files} valgt',
msgFoldersNotAllowed: 'Drag & drop kun filer! {n} mappe(r) sprunget over.',
msgImageWidthSmall: 'Bredden af billedet "{name}" skal være på mindst {size} px.',
msgImageHeightSmall: 'Højden af billedet "{name}" skal være på mindst {size} px.',
msgImageWidthLarge: 'Bredden af billedet "{name}" må ikke være over {size} px.',
msgImageHeightLarge: 'Højden af billedet "{name}" må ikke være over {size} px.',
msgImageResizeError: 'Kunne ikke få billedets dimensioner for at ændre størrelsen.',
msgImageResizeException: 'Fejl ved at ændre størrelsen på billedet.<pre>{errors}</pre>',
msgAjaxError: 'Noget gik galt med {operation} operationen. Forsøg venligst senere!',
msgAjaxProgressError: '{operation} fejlede',
ajaxOperations: {
deleteThumb: 'fil slet',
uploadThumb: 'fil upload',
uploadBatch: 'batchfil upload',
uploadExtra: 'form data upload'
},
dropZoneTitle: 'Drag & drop filer her …',
dropZoneClickTitle: '<br>(eller klik for at vælge {files})',
fileActionSettings: {
removeTitle: 'Fjern fil',
uploadTitle: 'Upload fil',
uploadRetryTitle: 'Forsåg upload igen',
downloadTitle: 'Download fil',
zoomTitle: 'Se detaljer',
dragTitle: 'Flyt / Omarranger',
indicatorNewTitle: 'Ikke uploadet endnu',
indicatorSuccessTitle: 'Uploadet',
indicatorErrorTitle: 'Upload fejl',
indicatorLoadingTitle: 'Uploader ...'
},
previewZoomButtonTitles: {
prev: 'Se forrige fil',
next: 'Se næste fil',
toggleheader: 'Skift header',
fullscreen: 'Skift fuld skærm',
borderless: 'Skift grænseløs mode',
close: 'Luk detaljeret visning'
}
};
})(window.jQuery);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.