code stringlengths 2 1.05M |
|---|
/* Copyright (c) 2014-2015 Richard Rodger, MIT License */
'use strict'
var Net = require('net')
var Code = require('code')
var Lab = require('lab')
var Seneca = require('..')
// Test shortcuts
var lab = exports.lab = Lab.script()
var describe = lab.describe
var it = lab.it
var expect = Code.expect
var internals = {}
internals.availablePort = function (callback) {
var server = Net.createServer()
server.listen(0, function () {
var port = server.address().port
server.close(function () {
callback(port)
})
})
}
describe('repl', function () {
lab.beforeEach(function (done) {
process.removeAllListeners('SIGHUP')
process.removeAllListeners('SIGTERM')
process.removeAllListeners('SIGINT')
process.removeAllListeners('SIGBREAK')
done()
})
it('accepts local connections and responds to commands', function (done) {
internals.availablePort(function (port) {
var seneca = Seneca({ repl: { port: port } })
seneca.repl()
setTimeout(function () {
var sock = Net.connect(port)
var state = 0
sock.on('readable', function () {
var buffer = sock.read()
if (!buffer) {
return
}
var result = buffer.toString('ascii')
if (state === 0) {
expect(result).to.contain('seneca')
sock.write('console.log(this)\n')
}
else if (state === 1) {
expect(result).to.contain('{')
sock.write('seneca.quit\n')
}
else if (state === 2) {
expect(result).to.contain('seneca')
done()
}
state++
}, 100)
})
})
})
})
|
var wymeditor_inputs = [];
var wymeditors_loaded = 0;
// supply custom_wymeditor_boot_options if you want to override anything here.
if (typeof(custom_wymeditor_boot_options) == "undefined") { custom_wymeditor_boot_options = {}; }
var wymeditor_boot_options = $.extend({
skin: 'refinery'
, basePath: "/javascripts/wymeditor/"
, wymPath: "/javascripts/wymeditor/jquery.refinery.wymeditor.js"
, cssSkinPath: "/stylesheets/wymeditor/skins/"
, jsSkinPath: "/javascripts/wymeditor/skins/"
, langPath: "/javascripts/wymeditor/lang/"
, iframeBasePath: '/'
, toolsItems: [
{'name': 'Bold', 'title': 'Bold', 'css': 'wym_tools_strong'}
,{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'}
,{'name': 'InsertOrderedList', 'title': 'Ordered_List', 'css': 'wym_tools_ordered_list'}
,{'name': 'InsertUnorderedList', 'title': 'Unordered_List', 'css': 'wym_tools_unordered_list'}
,{'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'}
,{'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'}
,{'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'}
,{'name': 'InsertTable', 'title': 'Table', 'css': 'wym_tools_table'}
,{'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'}
,{'name': 'Paste', 'title': 'Paste_From_Word', 'css': 'wym_tools_paste'}
]
,toolsHtml: "<ul class='wym_tools wym_section'>" + WYMeditor.TOOLS_ITEMS + WYMeditor.CLASSES + "</ul>"
,toolsItemHtml:
"<li class='" + WYMeditor.TOOL_CLASS + "'>"
+ "<a href='#' name='" + WYMeditor.TOOL_NAME + "' title='" + WYMeditor.TOOL_TITLE + "'>" + WYMeditor.TOOL_TITLE + "</a>"
+ "</li>"
//containersItems will be appended after tools in postInit.
, containersItems: [
{'name': 'h1', 'title':'Heading_1', 'css':'wym_containers_h1'}
,{'name': 'h2', 'title':'Heading_2', 'css':'wym_containers_h2'}
,{'name': 'h3', 'title':'Heading_3', 'css':'wym_containers_h3'}
,{'name': 'p', 'title':'Paragraph', 'css':'wym_containers_p'}
]
, classesHtml: "<li class='wym_tools_class'><a href='#' name='" + WYMeditor.APPLY_CLASS + "' title='"+ titleize(WYMeditor.APPLY_CLASS) +"'></a><ul class='wym_classes wym_classes_hidden'>" + WYMeditor.CLASSES_ITEMS + "</ul></li>"
, classesItemHtml: "<li><a href='#' name='"+ WYMeditor.CLASS_NAME + "'>"+ WYMeditor.CLASS_TITLE+ "</a></li>"
, classesItemHtmlMultiple: "<li class='wym_tools_class_multiple_rules'><span>" + WYMeditor.CLASS_TITLE + "</span><ul>{classesItemHtml}</ul></li>"
, classesItems: wymeditorClassesItems
, containersHtml: "<ul class='wym_containers wym_section'>" + WYMeditor.CONTAINERS_ITEMS + "</ul>"
, containersItemHtml:
"<li class='" + WYMeditor.CONTAINER_CLASS + "'>"
+ "<a href='#' name='" + WYMeditor.CONTAINER_NAME + "' title='" + WYMeditor.CONTAINER_TITLE + "'></a>"
+ "</li>"
, boxHtml:
"<div class='wym_box'>"
+ "<div class='wym_area_top'>"
+ WYMeditor.TOOLS
+ WYMeditor.CONTAINERS
+ "</div>"
+ "<div class='wym_area_main'>"
+ WYMeditor.HTML
+ WYMeditor.IFRAME
+ WYMeditor.STATUS
+ "</div>"
+ "</div>"
, iframeHtml:
"<div class='wym_iframe wym_section'>"
+ "<iframe id='WYMeditor_" + WYMeditor.INDEX + "' src='" + WYMeditor.IFRAME_BASE_PATH + "wymiframe' frameborder='0'"
+ " onload='this.contentWindow.parent.WYMeditor.INSTANCES[" + WYMeditor.INDEX + "].initIframe(this);'></iframe>"
+"</div>"
, dialogImageHtml: ""
, dialogLinkHtml: ""
, dialogTableHtml:
"<div class='wym_dialog wym_dialog_table'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='"+ WYMeditor.DIALOG_TABLE + "' />"
+ "<div class='field'>"
+ "<label for='wym_caption'>{Caption}</label>"
+ "<input type='text' id='wym_caption' class='wym_caption' value='' size='40' />"
+ "</div>"
+ "<div class='field'>"
+ "<label for='wym_rows'>{Number_Of_Rows}</label>"
+ "<input type='text' id='wym_rows' class='wym_rows' value='3' size='3' />"
+ "</div>"
+ "<div class='field'>"
+ "<label for='wym_cols'>{Number_Of_Cols}</label>"
+ "<input type='text' id='wym_cols' class='wym_cols' value='2' size='3' />"
+ "</div>"
+ "<div id='dialog-form-actions' class='form-actions'>"
+ "<input class='wym_submit' type='button' value='{Insert}' />"
+ " or "
+ "<a href='' class='wym_cancel close_dialog'>{Cancel}</a>"
+ "</div>"
+ "</form>"
+ "</div>"
, dialogPasteHtml:
"<div class='wym_dialog wym_dialog_paste'>"
+ "<form>"
+ "<input type='hidden' id='wym_dialog_type' class='wym_dialog_type' value='" + WYMeditor.DIALOG_PASTE + "' />"
+ "<div class='field'>"
+ "<label for='wym_text'>{Text_From_Word}</label"
+ "<textarea class='wym_text' rows='10' cols='50'></textarea>"
+ "</div>"
+ "<div id='dialog-form-actions' class='form-actions'>"
+ "<input class='wym_submit' type='button' value='{Insert}' />"
+ " or "
+ "<a href='' class='wym_cancel close_dialog'>{Cancel}</a>"
+ "</div>"
+ "</form>"
+ "</div>"
, dialogPath: "/admin/dialogs/"
, dialogFeatures: {
width: 958
, height: 570
, modal: true
, draggable: true
, resizable: false
, autoOpen: true
}
, dialogInlineFeatures: {
width: 600
, height: 530
, modal: true
, draggable: true
, resizable: false
, autoOpen: true
}
, dialogId: 'editor_dialog'
, dialogHtml:
"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>"
+ "<html dir='" + WYMeditor.DIRECTION + "'>"
+ "<head>"
+ "<link rel='stylesheet' type='text/css' media='screen' href='" + WYMeditor.CSS_PATH + "' />"
+ "<title>" + WYMeditor.DIALOG_TITLE + "</title>"
+ "<script type='text/javascript' src='" + WYMeditor.JQUERY_PATH + "'></script>"
+ "<script type='text/javascript' src='" + WYMeditor.WYM_PATH + "'></script>"
+ "</head>"
+ "<div id='page'>" + WYMeditor.DIALOG_BODY + "</div>"
+ "</html>"
, postInit: function(wym)
{
wym._iframe.style.height = wym._element.height() + "px";
wymeditors_loaded += 1;
if(WYMeditor.INSTANCES.length == wymeditors_loaded){
WYMeditor.loaded();
}
}
}, custom_wymeditor_boot_options);
// custom function added by us to hook into when all wymeditor instances on the page have finally loaded:
WYMeditor.loaded = function(){};
$(function()
{
wymeditor_inputs = $('.wymeditor');
wymeditor_inputs.hide();
wymeditor_inputs.wymeditor(wymeditor_boot_options);
$('.wym_iframe iframe').each(function(index, wym) {
// adjust for border width.
$(wym).css({'height':$(wym).parent().height()-2, 'width':$(wym).parent().width()-2});
});
}); |
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @RelayResolver
*
* @onType User
* @fieldName favorite_page
* @edgeTo Page
* @rootFragment myRootFragment
* @deprecated This one is not used any more
*/
|
var never = false;
it("should not crash on missing requires", function() {
if (never) {
require("./a");
require("./b");
require("./c");
require("./d");
require("./e");
require("./f");
require("./h");
require("./i");
require("./j");
require("./k");
require("./l");
require("./m");
require("./n");
require("./o");
}
});
|
/**
* MatchKeys.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
define(
'tinymce.core.keyboard.MatchKeys',
[
'ephox.katamari.api.Arr',
'ephox.katamari.api.Fun',
'ephox.katamari.api.Merger'
],
function (Arr, Fun, Merger) {
var defaultPatterns = function (patterns) {
return Arr.map(patterns, function (pattern) {
return Merger.merge({
shiftKey: false,
altKey: false,
ctrlKey: false,
metaKey: false,
keyCode: 0,
action: Fun.noop
}, pattern);
});
};
var matchesEvent = function (pattern, evt) {
return (
evt.keyCode === pattern.keyCode &&
evt.shiftKey === pattern.shiftKey &&
evt.altKey === pattern.altKey &&
evt.ctrlKey === pattern.ctrlKey &&
evt.metaKey === pattern.metaKey
);
};
var match = function (patterns, evt) {
return Arr.bind(defaultPatterns(patterns), function (pattern) {
return matchesEvent(pattern, evt) ? [pattern] : [ ];
});
};
var action = function (f) {
var args = Array.prototype.slice.call(arguments, 1);
return function () {
return f.apply(null, args);
};
};
var execute = function (patterns, evt) {
return Arr.find(match(patterns, evt), function (pattern) {
return pattern.action();
});
};
return {
match: match,
action: action,
execute: execute
};
}
); |
'use strict';
var assert = require('assert');
var ReactDOM= require('react-dom/server');
var jade = require('react-jade');
var test = /^\<div id\=\"container\".*\>Some Text\<\/div\>$/;
var templateA = jade`
#container Some Text
;
assert(test.test(ReactDOM.renderToString(templateA())));
var templateB = jade.compile('#container Some Text');
assert(test.test(ReactDOM.renderToString(templateB())));
|
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* Represents a command that can be executed on an editor instance.
*
* var command = new CKEDITOR.command( editor, {
* exec: function( editor ) {
* alert( editor.document.getBody().getHtml() );
* }
* } );
*
* @class
* @mixins CKEDITOR.event
* @constructor Creates a command class instance.
* @param {CKEDITOR.editor} editor The editor instance this command will be
* related to.
* @param {CKEDITOR.commandDefinition} commandDefinition The command
* definition.
*/
CKEDITOR.command = function( editor, commandDefinition ) {
/**
* Lists UI items that are associated to this command. This list can be
* used to interact with the UI on command execution (by the execution code
* itself, for example).
*
* alert( 'Number of UI items associated to this command: ' + command.uiItems.length );
*/
this.uiItems = [];
/**
* Executes the command.
*
* command.exec(); // The command gets executed.
*
* @param {Object} [data] Any data to pass to the command. Depends on the
* command implementation and requirements.
* @returns {Boolean} A boolean indicating that the command has been successfully executed.
*/
this.exec = function( data ) {
if ( this.state == CKEDITOR.TRISTATE_DISABLED || !this.checkAllowed() )
return false;
if ( this.editorFocus ) // Give editor focus if necessary (#4355).
editor.focus();
if ( this.fire( 'exec' ) === false )
return true;
return ( commandDefinition.exec.call( this, editor, data ) !== false );
};
/**
* Explicitly update the status of the command, by firing the {@link CKEDITOR.command#event-refresh} event,
* as well as invoke the {@link CKEDITOR.command#method-refresh} method if defined, this method
* is to allow different parts of the editor code to contribute in command status resolution.
*
* @todo
*/
this.refresh = function( editor, path ) {
// Do nothing is we're on read-only and this command doesn't support it.
// We don't need to disabled the command explicitely here, because this
// is already done by the "readOnly" event listener.
if ( !this.readOnly && editor.readOnly )
return true;
// Disable commands that are not allowed in the current selection path context.
if ( this.context && !path.isContextFor( this.context ) ) {
this.disable();
return true;
}
// Make the "enabled" state as basis.
this.enable();
if ( this.fire( 'refresh', { editor: editor, path: path } ) === false )
return true;
return ( commandDefinition.refresh && commandDefinition.refresh.apply( this, arguments ) !== false );
};
var allowed;
/**
* Checks whether this command is allowed by the allowed
* content filter ({@link CKEDITOR.filter}). This means
* that if command implements {@link CKEDITOR.feature} interface it will be tested
* by {@link CKEDITOR.filter#checkFeature}.
*
* @since 4.1
* @returns {Boolean} Whether this command is allowed.
*/
this.checkAllowed = function() {
if ( typeof allowed == 'boolean' )
return allowed;
return allowed = editor.filter.checkFeature( this );
};
CKEDITOR.tools.extend( this, commandDefinition, {
/**
* The editor modes within which the command can be executed. The
* execution will have no action if the current mode is not listed
* in this property.
*
* // Enable the command in both WYSIWYG and Source modes.
* command.modes = { wysiwyg:1,source:1 };
*
* // Enable the command in Source mode only.
* command.modes = { source:1 };
*
* @see CKEDITOR.editor#mode
*/
modes: { wysiwyg:1 },
/**
* Indicates that the editor will get the focus before executing
* the command.
*
* // Do not force the editor to have focus when executing the command.
* command.editorFocus = false;
*
* @property {Boolean} [=true]
*/
editorFocus: 1,
/**
* Indicates that this command is sensible to the selection context.
* If `true`, the {@link CKEDITOR.command#method-refresh} method will be
* called for this command on the {@link CKEDITOR.editor#event-selectionChange} event.
*
* @property {Boolean} [=false]
*/
contextSensitive: !!commandDefinition.context,
/**
* Indicates the editor state. Possible values are:
*
* * {@link CKEDITOR#TRISTATE_DISABLED}: the command is
* disabled. It's execution will have no effect. Same as {@link #disable}.
* * {@link CKEDITOR#TRISTATE_ON}: the command is enabled
* and currently active in the editor (for context sensitive commands, for example).
* * {@link CKEDITOR#TRISTATE_OFF}: the command is enabled
* and currently inactive in the editor (for context sensitive commands, for example).
*
* Do not set this property directly, using the {@link #setState} method instead.
*
* if ( command.state == CKEDITOR.TRISTATE_DISABLED )
* alert( 'This command is disabled' );
*
* @property {Number} [=CKEDITOR.TRISTATE_DISABLED]
*/
state: CKEDITOR.TRISTATE_DISABLED
});
// Call the CKEDITOR.event constructor to initialize this instance.
CKEDITOR.event.call( this );
};
CKEDITOR.command.prototype = {
/**
* Enables the command for execution. The command state (see
* {@link CKEDITOR.command#property-state}) available before disabling it is restored.
*
* command.enable();
* command.exec(); // Execute the command.
*/
enable: function() {
if ( this.state == CKEDITOR.TRISTATE_DISABLED && this.checkAllowed() )
this.setState( ( !this.preserveState || ( typeof this.previousState == 'undefined' ) ) ? CKEDITOR.TRISTATE_OFF : this.previousState );
},
/**
* Disables the command for execution. The command state (see
* {@link CKEDITOR.command#property-state}) will be set to {@link CKEDITOR#TRISTATE_DISABLED}.
*
* command.disable();
* command.exec(); // "false" - Nothing happens.
*/
disable: function() {
this.setState( CKEDITOR.TRISTATE_DISABLED );
},
/**
* Sets the command state.
*
* command.setState( CKEDITOR.TRISTATE_ON );
* command.exec(); // Execute the command.
* command.setState( CKEDITOR.TRISTATE_DISABLED );
* command.exec(); // 'false' - Nothing happens.
* command.setState( CKEDITOR.TRISTATE_OFF );
* command.exec(); // Execute the command.
*
* @param {Number} newState The new state. See {@link #property-state}.
* @returns {Boolean} Returns `true` if the command state changed.
*/
setState: function( newState ) {
// Do nothing if there is no state change.
if ( this.state == newState || !this.checkAllowed() )
return false;
this.previousState = this.state;
// Set the new state.
this.state = newState;
// Fire the "state" event, so other parts of the code can react to the
// change.
this.fire( 'state' );
return true;
},
/**
* Toggles the on/off (active/inactive) state of the command. This is
* mainly used internally by context sensitive commands.
*
* command.toggleState();
*/
toggleState: function() {
if ( this.state == CKEDITOR.TRISTATE_OFF )
this.setState( CKEDITOR.TRISTATE_ON );
else if ( this.state == CKEDITOR.TRISTATE_ON )
this.setState( CKEDITOR.TRISTATE_OFF );
}
};
CKEDITOR.event.implementOn( CKEDITOR.command.prototype );
/**
* Indicates the previous command state.
*
* alert( command.previousState );
*
* @property {Number} previousState
* @see #state
*/
/**
* Fired when the command state changes.
*
* command.on( 'state', function() {
* // Alerts the new state.
* alert( this.state );
* } );
*
* @event state
*/
/**
* @event refresh
* @todo
*/
|
var express = require('express');
var router = express.Router();
var devAccount = require("./../config").devAccount;
var endpoints = require("../bin/aerohive/api/main");
var Device = require("../bin/aerohive/models/device");
var Location = require("../bin/aerohive/models/location");
/*================================================================
COMMON FUNCTIONS
================================================================*/
function locationsFromQuery(req) {
// if the "locations" parameter exists, and is not null, will filter the request based on the locations selected by the user
// otherwise takes the "root" folder
if (req.query.locations && req.query.locations.length > 0) {
locations = req.query.locations;
if (locations.length == 0) locations = [req.session.locations.id];
} else locations = [req.session.locations.id];
if (typeof locations == "number" || typeof locations == "string") locations = [locations];
return locations;
}
/*================================================================
API
================================================================*/
// route called to get the data for the cards at the top of the dashboard
router.get('/cards/', function (req, res, next) {
var currentApi = req.session.xapi.owners[req.session.xapi.ownerIndex];
var locations = locationsFromQuery(req);
endpoints.monitor.device.getDevices(currentApi, devAccount, function (err, devices) {
if (err) res.status(500).send(err);
else {
// get the list of locationID based on the selection made by the user
var floorsFilter = Location.getFilteredFloorsId(req.session.locations, locations);
// get the counters about location and devices, filtered on the locations
var locationsCount = Location.countBuildings(req.session.locations, floorsFilter);
var devicesCount = Device.countDevices(devices, floorsFilter);
res.status(200).json({ locationsCount: locationsCount, devicesCount: devicesCount });
}
});
});
// route called to get the values for the charts on the dashboard
router.get('/widgets/', function (req, res, next) {
var currentApi = req.session.xapi.owners[req.session.xapi.ownerIndex];
var errors = [];
var startTime, endTime, locations, locNowDone, locWeekDone, locMonthDone, locYearDone,
startLastWeek, endLastWeek, startLastMonth, endLastMonth, startLastYear, endLastYear;
var dataNow = {
"uniqueClients": 0,
"engagedClients": 0,
"passersbyClients": 0,
"associatedClients": 0,
"unassociatedClients": 0,
"newClients": 0,
"returningClients": 0
};
var dataLastWeek = {
"uniqueClients": 0,
"engagedClients": 0,
"passersbyClients": 0,
"associatedClients": 0,
"unassociatedClients": 0,
"newClients": 0,
"returningClients": 0
};
var dataLastMonth = {
"uniqueClients": 0,
"engagedClients": 0,
"passersbyClients": 0,
"associatedClients": 0,
"unassociatedClients": 0,
"newClients": 0,
"returningClients": 0
};
var dataLastYear = {
"uniqueClients": 0,
"engagedClients": 0,
"passersbyClients": 0,
"associatedClients": 0,
"unassociatedClients": 0,
"newClients": 0,
"returningClients": 0
};
if (req.query.startTime && req.query.endTime) {
// retrieve the start time and end time from the POST method
startTime = new Date(req.query['startTime']);
endTime = new Date(req.query['endTime']);
var locations = locationsFromQuery(req);
locNowDone = 0;
locWeekDone = 0;
locMonthDone = 0;
locYearDone = 0;
// this "widgetReqId" is used to identify the calls to ACS API.
// It is needed because of the use of "Event Emitter" instead of the callback method
var widgetReqId = new Date().getTime();
locations.forEach(function (location) {
// get the values for the time range defined by the user
// once done, call the Event "dashboard widget now"
endpoints.clientlocation.clientcount.GET(
currentApi,
devAccount,
location,
startTime.toISOString(),
endTime.toISOString(),
function (err, data) {
// if there is an error, send the error message to the web browser
if (err) errors.push(err);
else {
// otherwise, add the values for the period of time defined by the user to the values for all the locations
dataNow['uniqueClients'] += data['uniqueClients'];
dataNow['engagedClients'] += data['engagedClients'];
dataNow['passersbyClients'] += data['passersbyClients'];
dataNow['associatedClients'] += data['associatedClients'];
dataNow['unassociatedClients'] += data['unassociatedClients'];
dataNow['newClients'] += data['newClients'];
dataNow['returningClients'] += data['returningClients'];
locNowDone++;
// call the last event to send back the data to the web browser (will check if all locations/periods are done)
end();
}
});
// if time range < 1 week, get the value for the previous week
// once done, call the Event "dashboard widget lastWeek"
if (endTime - startTime <= 604800000) {
// calculate the start/end dates for the previous week
startLastWeek = new Date(startTime);
startLastWeek.setDate(startLastWeek.getDate() - 7);
endLastWeek = new Date(endTime);
endLastWeek.setDate(endLastWeek.getDate() - 7);
endpoints.clientlocation.clientcount.GET(
currentApi,
devAccount,
location,
startLastWeek.toISOString(),
endLastWeek.toISOString(),
function (err, data) {
// if there is an error, send the error message to the web browser
if (err) errors.push(err);
else {
// otherwise, add the values for previous week to the values for all the locations
dataLastWeek['uniqueClients'] += data['uniqueClients'];
dataLastWeek['engagedClients'] += data['engagedClients'];
dataLastWeek['passersbyClients'] += data['passersbyClients'];
dataLastWeek['associatedClients'] += data['associatedClients'];
dataLastWeek['unassociatedClients'] += data['unassociatedClients'];
dataLastWeek['newClients'] += data['newClients'];
dataLastWeek['returningClients'] += data['returningClients'];
locWeekDone++;
// call the last event to send back the data to the web browser (will check if all locations/periods are done)
end();
}
});
// else, indicate that all the "weeks" are done
} else locWeekDone = locations.length;
// if time range < 1 month, get the value for the previous week
// once done, call the Event "dashboard widget lastMonth"
if (endTime - startTime <= 2678400000) {
// calculate the start/end dates for the previous month
startLastMonth = new Date(startTime);
startLastMonth.setMonth(startLastMonth.getMonth() - 1);
endLastMonth = new Date(endTime);
endLastMonth.setMonth(endLastMonth.getMonth() - 1);
endpoints.clientlocation.clientcount.GET(
currentApi,
devAccount,
location,
startLastMonth.toISOString(),
endLastMonth.toISOString(),
function (err, data) {
// if there is an error, send the error message to the web browser
if (err) errors.push(err);
else {
// otherwise, add the values for previous month to the values for all the locations
dataLastMonth['uniqueClients'] += data['uniqueClients'];
dataLastMonth['engagedClients'] += data['engagedClients'];
dataLastMonth['passersbyClients'] += data['passersbyClients'];
dataLastMonth['associatedClients'] += data['associatedClients'];
dataLastMonth['unassociatedClients'] += data['unassociatedClients'];
dataLastMonth['newClients'] += data['newClients'];
dataLastMonth['returningClients'] += data['returningClients'];
locMonthDone++;
// call the last event to send back the data to the web browser (will check if all locations/periods are done)
end();
}
});
// else, indicate that all the "months" are done
} else locMonthDone = locations.length;
// Get the value for the previous Year
// once done, call the Event "dashboard widget lastYear"
// calculate the start/end dates for the previous Year
startLastYear = new Date(startTime);
startLastYear.setFullYear(startLastYear.getFullYear() - 1);
endLastYear = new Date(endTime);
endLastYear.setFullYear(endLastYear.getFullYear() - 1);
endpoints.clientlocation.clientcount.GET(
currentApi,
devAccount,
location,
startLastYear.toISOString(),
endLastYear.toISOString(),
function (err, data) {
// if there is an error, send the error message to the web browser
if (err) errors.push(err);
else {
// otherwise, add the values for previous year to the values for all the locations
dataLastYear['uniqueClients'] += data['uniqueClients'];
dataLastYear['engagedClients'] += data['engagedClients'];
dataLastYear['passersbyClients'] += data['passersbyClients'];
dataLastYear['associatedClients'] += data['associatedClients'];
dataLastYear['unassociatedClients'] += data['unassociatedClients'];
dataLastYear['newClients'] += data['newClients'];
dataLastYear['returningClients'] += data['returningClients'];
locYearDone++;
// call the last event to send back the data to the web browser (will check if all locations/periods are done)
end();
}
});
});
} else res.status(400).json({ error: "missing parameters" });
function end() {
if (locNowDone == locations.length
&& locWeekDone == locations.length
&& locMonthDone == locations.length
&& locYearDone == locations.length) {
if (errors.length > 0) res.status(500).json({errors: errors});
// if all locations/periods are done, send back the response to the web browser
else res.status(200).json({
dataNow: dataNow,
dataLastWeek: dataLastWeek,
dataLastMonth: dataLastMonth,
dataLastYear: dataLastYear
})
}
}
});
//api call to get the values for the "Best locations by" charts
router.get("/widget-top/", function (req, res, next) {
var currentApi = req.session.xapi.owners[req.session.xapi.ownerIndex];
var errors = [];
var startTime, endTime, locDone, topLocations, locations, buildings;
if (req.query.startTime && req.query.endTime) {
// retrieve the start time and end time from the POST method
startTime = new Date(req.query.startTime);
endTime = new Date(req.query.endTime);
var locations = locationsFromQuery(req);
locDone = 0;
topLocations = {};
// get the list of buildings
buildings = Location.getFilteredFloorsId(req.session.locations, locations, "BUILDING");
buildings.forEach(function (location) {
// for each building, get the data from ACS
endpoints.clientlocation.clientcount.GET(
currentApi,
devAccount,
location,
startTime.toISOString(),
endTime.toISOString(),
function (err, data) {
if (err) errors.push(err);
else {
var storefront, name;
// calculate the storefront conversion
if (data['uniqueClients'] == 0) storefront = 0;
else storefront = ((data['engagedClients'] / data['uniqueClients']) * 100).toFixed(0);
// get the location name
name = Location.getLocationName(req.session.locations, this.location);
// add each locations to the "topLocations" dictionary
topLocations[this.location] = {
name: name,
uniqueClients: data['uniqueClients'],
engagedClients: data['engagedClients'],
passersbyClients: data['passersbyClients'],
associatedClients: data['associatedClients'],
unassociatedClients: data['unassociatedClients'],
newClients: data['newClients'],
returningClients: data['returningClients'],
storefront: parseInt(storefront)
};
locDone++;
// if all the locations are done, will send the response back to the web browser
if (locDone == buildings.length) {
if (errors.length > 0 ) res.status(500).json({errors: errors});
else res.status(200).json({ topLocations: topLocations })
}
}
}.bind({ location: location }));
});
} else res.status(400).json({ error: "missing parameters" });
});
module.exports = router;
|
var DOCUMENTER_CURRENT_VERSION = "v0.5.4";
|
import * as types from "./FeatureTypes";
const INITIAL_STATE = {};
// Replace with you own reducer
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case types.GET_DATA_RECEIVE:
return {
...state,
...action.payload
};
default:
return state;
}
};
|
var unidecode = require('unidecode'),
_ = require('lodash'),
utils,
getRandomInt;
/**
* Return a random int, used by `utils.uid()`
*
* @param {Number} min
* @param {Number} max
* @return {Number}
* @api private
*/
getRandomInt = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
utils = {
/**
* Timespans in seconds and milliseconds for better readability
*/
ONE_HOUR_S: 3600,
ONE_DAY_S: 86400,
ONE_MONTH_S: 2628000,
SIX_MONTH_S: 15768000,
ONE_YEAR_S: 31536000,
FIVE_MINUTES_MS: 300000,
ONE_HOUR_MS: 3600000,
ONE_DAY_MS: 86400000,
ONE_WEEK_MS: 604800000,
ONE_MONTH_MS: 2628000000,
SIX_MONTH_MS: 15768000000,
ONE_YEAR_MS: 31536000000,
/**
* Return a unique identifier with the given `len`.
*
* utils.uid(10);
* // => "FDaS435D2z"
*
* @param {Number} len
* @return {String}
* @api private
*/
uid: function (len) {
var buf = [],
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
charlen = chars.length,
i;
for (i = 0; i < len; i = i + 1) {
buf.push(chars[getRandomInt(0, charlen - 1)]);
}
return buf.join('');
},
safeString: function (string, options) {
options = options || {};
// Handle the £ symbol separately, since it needs to be removed before the unicode conversion.
string = string.replace(/£/g, '-');
// Remove non ascii characters
string = unidecode(string);
// Replace URL reserved chars: `@:/?#[]!$&()*+,;=` as well as `\%<>|^~£"{}` and \`
string = string.replace(/(\s|\.|@|:|\/|\?|#|\[|\]|!|\$|&|\(|\)|\*|\+|,|;|=|\\|%|<|>|\||\^|~|"|\{|\}|`|–|—)/g, '-')
// Remove apostrophes
.replace(/'/g, '')
// Make the whole thing lowercase
.toLowerCase();
// We do not need to make the following changes when importing data
if (!_.has(options, 'importing') || !options.importing) {
// Convert 2 or more dashes into a single dash
string = string.replace(/-+/g, '-')
// Remove trailing dash
.replace(/-$/, '')
// Remove any dashes at the beginning
.replace(/^-/, '');
}
// Handle whitespace at the beginning or end.
string = string.trim();
return string;
},
// The token is encoded URL safe by replacing '+' with '-', '\' with '_' and removing '='
// NOTE: the token is not encoded using valid base64 anymore
encodeBase64URLsafe: function (base64String) {
return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
},
// Decode url safe base64 encoding and add padding ('=')
decodeBase64URLsafe: function (base64String) {
base64String = base64String.replace(/-/g, '+').replace(/_/g, '/');
while (base64String.length % 4) {
base64String += '=';
}
return base64String;
},
redirect301: function redirect301(res, path) {
/*jslint unparam:true*/
res.set({'Cache-Control': 'public, max-age=' + utils.ONE_YEAR_S});
res.redirect(301, path);
},
readCSV: require('./read-csv'),
removeOpenRedirectFromUrl: require('./remove-open-redirect-from-url'),
zipFolder: require('./zip-folder'),
generateAssetHash: require('./asset-hash'),
url: require('./url'),
tokens: require('./tokens'),
sequence: require('./sequence'),
ghostVersion: require('./ghost-version'),
mobiledocConverter: require('./mobiledoc-converter')
};
module.exports = utils;
|
const {hsv2rgb} = require("../lib");
describe("hsv2rgb", () => {
it("should correctly convert valid hsv values to rgb", () => {
expect(hsv2rgb([0, 0, 1])).toEqual([255, 255, 255]);
expect(hsv2rgb([120, 1, 1])).toEqual([0, 255, 0]);
expect(hsv2rgb([300, 1, 0.5])).toEqual([128, 0, 128]);
expect(hsv2rgb([0, 0, 0])).toEqual([0, 0, 0]);
expect(hsv2rgb([69, 0.13, 0.37])).toEqual([93, 94, 82]);
});
});
|
module.exports = {
plugin: require('./events'),
setup: setup,
}
function setup(store) {
test('events', function() {
store.set('foo', 'bar')
var expectationNone = _createExpectation('expectNone', undefined)
store.watch('foo', function(){})
var expectation1 = _createExpectation('foo', 'bar')
var expectationOnce = _createExpectation('foo', 'bar', true)
store.watch('foo', function(){})
expectation1.add('bar2')
expectationOnce.add('bar2')
store.set('foo', 'bar2')
expectation1.add(undefined)
store.remove('foo')
expectation1.add('bar3')
store.set('foo', 'bar3')
var expectation2 = _createExpectation('foo', 'bar3')
expectation1.add(undefined)
expectation2.add(undefined)
store.clearAll() // Should fire for foo
store.clearAll() // Should not fire anything
expectation1.unwatch()
expectation2.add('bar4')
store.set('foo', 'bar4') // Should only fire for expectation2
expectation1.check()
expectationOnce.check()
expectation2.check()
expectationNone.check()
expectation2.unwatch()
})
function _createExpectation(key, firstOldVal, useOnce) {
var expectation = {
values: [firstOldVal],
count: 0,
add: function(value) {
this.values.push(value)
},
check: function() {
assert(expectation.count + 1 == expectation.values.length)
},
unwatch: function() {
store.unwatch(watchId)
}
}
var watchId = (useOnce
? store.once(key, callback)
: store.watch(key, callback)
)
function callback(val, oldVal) {
expectation.count += 1
assert(expectation.values[expectation.count] == val)
assert(expectation.values[expectation.count - 1] == oldVal)
}
return expectation
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:0c5a3b029fc98d5255cffc0bf6721373a9123eace933b55ebd03f5d5f85328fd
size 825
|
var fs = require("fs"), path = require("path");
var projectDir = path.resolve(__dirname, "..");
exports.resolve = function(pth) { return path.resolve(projectDir, pth); };
exports.ecma5 = JSON.parse(fs.readFileSync(exports.resolve("defs/ecma5.json")), "utf8");
exports.browser = JSON.parse(fs.readFileSync(exports.resolve("defs/browser.json")), "utf8");
exports.jquery = JSON.parse(fs.readFileSync(exports.resolve("defs/jquery.json")), "utf8");
var files = 0, tests = 0, failed = 0;
exports.addFile = function() { ++files; };
exports.addTest = function() { ++tests; };
exports.failure = function(message) {
console.log(message);
++failed;
};
process.on("exit", function() {
console.log("Ran " + tests + " tests from " + files + " files.");
console.log(failed ? failed + " failures!" : "All passed.");
});
|
!function(e){"function"==typeof define&&define.amd?define(["../widgets/datepicker"],e):e(jQuery.datepicker)}(function(e){return e.regional.lt={closeText:"U\u017edaryti",prevText:"<Atgal",nextText:"Pirmyn>",currentText:"\u0160iandien",monthNames:["Sausis","Vasaris","Kovas","Balandis","Gegu\u017e\u0117","Bir\u017eelis","Liepa","Rugpj\u016btis","Rugs\u0117jis","Spalis","Lapkritis","Gruodis"],monthNamesShort:["Sau","Vas","Kov","Bal","Geg","Bir","Lie","Rugp","Rugs","Spa","Lap","Gru"],dayNames:["sekmadienis","pirmadienis","antradienis","tre\u010diadienis","ketvirtadienis","penktadienis","\u0161e\u0161tadienis"],dayNamesShort:["sek","pir","ant","tre","ket","pen","\u0161e\u0161"],dayNamesMin:["Se","Pr","An","Tr","Ke","Pe","\u0160e"],weekHeader:"SAV",dateFormat:"yy-mm-dd",firstDay:1,isRTL:!1,showMonthAfterYear:!0,yearSuffix:""},e.setDefaults(e.regional.lt),e.regional.lt}); |
import React, { Component } from 'react';
import { Text, View } from 'react-native';
class Blink extends Component {
constructor(props) {
super(props);
this.state = { showText: true };
// 每1000毫秒对showText状态做一次取反操作
setInterval(() => {
this.setState({ showText: !this.state.showText });
}, 1000);
}
render() {
// 根据当前showText的值决定是否显示text内容
let display = this.state.showText ? this.props.text : ' ';
return (
<Text>{display}</Text>
);
}
}
export default Blink |
/*******************************************************
* task service implementation
* transitions document (server)
* Mike Amundsen (@mamund)
*******************************************************/
// holds the list of *all* possible state transitions for this service
// run on first load;
var trans = [];
trans = fillTrans();
module.exports = main;
function main(name) {
var rtn, i, x;
rtn = {};
for(i=0,x=trans.length;i<x;i++) {
if(trans[i].name===name) {
rtn = trans[i];
break;
}
}
return rtn;
}
// internal filling
function fillTrans() {
var trans;
trans = [];
// search transition
trans.push({
name : "searchLink",
type : "safe",
action: "read",
kind : "todo",
target : "list",
prompt : "Search ToDos"
});
trans.push({
name : "searchForm",
type : "safe",
action : "read",
kind : "todo",
target : "list",
prompt : "Search ToDos",
inputs : [
{name : "title", prompt : "Title", value : ""}
]
});
// self transition
trans.push({
name : "selfLink",
type : "safe",
action : "read",
kind : "self",
target : "self",
prompt : "Reload"
});
// home transitions
trans.push({
name : "homeLink",
type : "safe",
action : "read",
kind : "home",
target : "list",
prompt : "Home"
});
// todo transitions
trans.push({
name : "listAll",
type : "safe",
action : "read",
kind : "todo",
target : "list",
prompt : "All ToDo"
});
trans.push({
name : "listActive",
type : "safe",
action : "read",
kind : "todo",
target : "list",
prompt : "Active ToDos",
inputs : [
{name : "completed", prompt : "Complete", value : "false"}
]
});
trans.push({
name : "listCompleted",
type : "safe",
action : "read",
kind : "todo",
target : "list",
prompt : "Completed ToDos",
inputs : [
{name : "completed", prompt : "Complete", value : "true"}
]
});
trans.push({
name : "addLink",
type : "safe",
action : "read",
kind : "todo",
target : "list",
prompt : "Add ToDo"
});
// add email field here
trans.push({
name : "addForm",
type : "unsafe",
action : "append",
kind : "todo",
target : "list",
prompt : "Add ToDo",
inputs : [
{name : "title", prompt : "Title"},
{name : "completed", prompt : "Complete", value : "false"},
{name : "email", prompt : "Email"}
]
});
trans.push({
name : "editLink",
type : "safe",
action : "read",
kind : "todo",
target : "item",
prompt : "Edit ToDo"
});
// add email field here
trans.push({
name : "editForm",
type : "unsafe",
action : "replace",
kind : "todo",
prompt : "Edit ToDo",
inputs : [
{name : "id", prompt : "ID"},
{name : "title", prompt : "Title"},
{name : "completed", prompt : "Complete"},
{name : "email", prompt : "Email"}
]
});
trans.push({
name : "removeLink",
type : "safe",
action : "read",
kind : "todo",
target : "item",
prompt : "Remove ToDo"
});
trans.push({
name : "removeForm",
type : "unsafe",
action : "remove",
kind : "todo",
prompt : "Remove ToDo",
inputs : [
{name : "id", prompt : "ID"}
]
});
trans.push({
name : "completedLink",
type : "safe",
action : "read",
kind : "todo",
target : "item",
prompt : "Mark Completed"
});
trans.push({
name : "completedForm",
type : "unsafe",
action : "append",
kind : "todo",
prompt : "Mark Completed",
inputs : [
{name: "id", prompt:"ID"},
{name: "completed", prompt:"Complete Status", value:"true"}
]
});
trans.push({
name : "clearCompletedLink",
type : "safe",
action : "read",
kind : "todo",
target : "list",
prompt : "Clear Completed"
});
trans.push({
name : "clearCompletedForm",
type : "unsafe",
action : "append",
kind : "todo",
target : "list",
prompt : "Clear Completed",
inputs : [
{name: "completed", prompt:"Complete Status", value:"true"}
]
});
return trans;
}
|
/**
* Creator for tQuery.PoolBall
* @return {tQuery.Mesh} instance of
*/
tQuery.registerStatic('createPoolBall', function(opts){
// handle parameter polymorphism
if( typeof(opts) === 'string' ) opts = {ballDesc: opts};
// handle default options
opts = tQuery.extend(opts, {
ballDesc : '8',
stripped : true,
textureW : 1024
});
// build texture based on ballDesc
if( opts.ballDesc === 'cue' ){
// build the texture
var texture = tQuery.createPoolBall.ballTexture('', false, "#ffffff", opts.textureW);
}else if( opts.ballDesc === 'black' ){
// build the texture
var texture = tQuery.createPoolBall.ballTexture('', false, "#000000", opts.textureW);
}else{
var fillStylePerDesc = {
'1' : "#FDD017", // Yellow
'2' : "#2B65EC", // Blue
'3' : "#F62817", // Red
'4' : "#7A5DC7", // Purple
'5' : "#F87217", // Orange
'6' : "#348017", // Green
'7' : "#A52A2A", // Brown or burgundy (tan in some ball sets)
'8' : "#000000", // Black
'9' : "#FDD017", // Yellow
};
// sanity check
console.assert(Object.keys(fillStylePerDesc).indexOf(opts.ballDesc) !== -1);
// build the texture
var fillStyle = fillStylePerDesc[opts.ballDesc];
var texture = tQuery.createPoolBall.ballTexture(opts.ballDesc, opts.stripped,
fillStyle, opts.textureW);
}
// TODO it would be nice to cache the texture
// create the sphere and use texture
var object = tQuery.createSphere(0.5, 128,128)
.setPhongMaterial()
.map(texture)
.back()
// return the just created object
return object;
});
/**
* display the shaddow of the smiley in a texture
*
* @param {canvasElement} the canvas where we draw
*/
tQuery.createPoolBall.draw = function(canvas, textData, stripped, fillStyle){
var ctx = canvas.getContext( '2d' );
var xtx = tQuery.createPoolBall.xCanvas.create(ctx);
var w = canvas.width;
var h = canvas.height;
// base color is white
ctx.save();
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(0,0, w, h);
ctx.restore();
// do the strip/full
ctx.save();
ctx.translate(w/2, h/2)
var rectH = stripped ? h/2 : h;
ctx.fillStyle = fillStyle;
ctx.fillRect(-w/2,-rectH/2, w, rectH);
ctx.restore();
if( textData ){
// do white circle around textData
ctx.save();
ctx.translate(w/4, h/2)
ctx.fillStyle = "#FFFFFF";
var radiusW = 0.7 * w/4;
var radiusH = 1.2 * h/4;
xtx.fillEllipse(-radiusW/2, -radiusH/2, radiusW, radiusH);
ctx.restore();
// draw text data
ctx.save();
ctx.translate(w/4, h/2)
var textH = w/4;
ctx.font = "bolder "+textH+"px Arial";
ctx.fillStyle = "#000000";
var textW = ctx.measureText(textData).width;
ctx.fillText(textData, -textW/2, 0.8*textH/2);
ctx.restore();
}
}
tQuery.createPoolBall.ballTexture = function( textData, stripped, fillStyle, canvasW, mapping ){
canvasW = typeof canvasW !== 'undefined' ? canvasW : 512;
// create the canvas
var canvas = document.createElement('canvas');
canvas.width = canvas.height = canvasW;
// create the texture
var texture = new THREE.Texture(canvas, mapping);
texture.needsUpdate = true;
// draw in the texture
tQuery.createPoolBall.draw(canvas, textData, stripped, fillStyle);
// return the texture
return texture;
};
/**
* helper for the canvas2d API to draw circle and ellipse
* @type {Object}
*/
tQuery.createPoolBall.xCanvas = {
create : function(ctx){
var xCanvas = tQuery.createPoolBall.xCanvas;
return {
fillEllipse : function(aX, aY, aWidth, aHeight){
return xCanvas.fillEllipse(ctx, aX, aY, aWidth, aHeight)
}
}
},
// Andrea Giammarchi - Mit Style License
// Circle methods
circle : function(ctx, aX, aY, aDiameter){
this.ellipse(ctx, aX, aY, aDiameter, aDiameter);
},
fillCircle : function(ctx, aX, aY, aDiameter){
ctx.beginPath();
this.circle(ctx, aX, aY, aDiameter);
ctx.fill();
},
strokeCircle : function(ctx, aX, aY, aDiameter){
ctx.beginPath();
this.circle(ctx, aX, aY, aDiameter);
ctx.stroke();
},
// Ellipse methods
ellipse : function(ctx, aX, aY, aWidth, aHeight){
var hB = (aWidth / 2) * .5522848,
vB = (aHeight / 2) * .5522848,
eX = aX + aWidth,
eY = aY + aHeight,
mX = aX + aWidth / 2,
mY = aY + aHeight / 2;
ctx.moveTo(aX, mY);
ctx.bezierCurveTo(aX, mY - vB, mX - hB, aY, mX, aY);
ctx.bezierCurveTo(mX + hB, aY, eX, mY - vB, eX, mY);
ctx.bezierCurveTo(eX, mY + vB, mX + hB, eY, mX, eY);
ctx.bezierCurveTo(mX - hB, eY, aX, mY + vB, aX, mY);
ctx.closePath();
},
fillEllipse : function(ctx, aX, aY, aWidth, aHeight){
ctx.beginPath();
this.ellipse(ctx, aX, aY, aWidth, aHeight);
ctx.fill();
},
strokeEllipse:function(ctx, aX, aY, aWidth, aHeight){
ctx.beginPath();
this.ellipse(ctx, aX, aY, aWidth, aHeight);
ctx.stroke();
}
};
|
OVERRIDE(EXPORT_IMG_TYPE, function(origin) {
'use strict';
/**
* export img type. (fix for IE)
*/
global.EXPORT_IMG_TYPE = METHOD({
run : function(img, callback) {
//REQUIRED: img
//REQUIRED: callback
var
// image
image = new Image();
image.onload = function() {
callback(image.mimeType.toLowerCase().split(' ')[0]);
};
image.src = img.getSrc();
}
});
});
|
Package.describe({
name: "telescope:subscribe-to-posts",
summary: "Subscribe to posts to be notified when they get new comments",
version: "0.25.2",
git: "https://github.com/TelescopeJS/telescope-subscribe-to-posts.git"
});
Package.onUse(function (api) {
api.versionsFrom("METEOR@1.0");
// --------------------------- 1. Meteor packages dependencies ---------------------------
// automatic (let the package specify where it's needed)
api.use(['telescope:core@0.25.2']);
// ---------------------------------- 2. Files to include ----------------------------------
// i18n config (must come first)
api.addFiles([
'package-tap.i18n'
], ['client', 'server']);
// both
api.addFiles([
'lib/subscribe-to-posts.js',
], ['client', 'server']);
// client
api.addFiles([
'lib/client/templates/post_subscribe.html',
'lib/client/templates/post_subscribe.js',
'lib/client/templates/user_subscribed_posts.html',
'lib/client/templates/user_subscribed_posts.js'
], ['client']);
// server
api.addFiles([
'lib/server/publications.js'
], ['server']);
// i18n languages (must come last)
var languages = ["ar", "bg", "cs", "da", "de", "el", "en", "es", "et", "fr", "hu", "id", "it", "ja", "kk", "ko", "nl", "pl", "pt-BR", "ro", "ru", "sl", "sv", "th", "tr", "vi", "zh-CN"];
var languagesPaths = languages.map(function (language) {
return "i18n/"+language+".i18n.json";
});
api.addFiles(languagesPaths, ["client", "server"]);
api.export([
'subscribeItem',
'unsubscribeItem'
]);
});
|
/**
* Simple, lightweight, usable local autocomplete library for modern browsers
* Because there weren’t enough autocomplete scripts in the world? Because I’m completely insane and have NIH syndrome? Probably both. :P
* @author Lea Verou http://leaverou.github.io/awesomplete
* MIT license
*/
(function () {
var _ = function (input, o) {
var me = this;
// Setup
this.isOpened = false;
this.input = $(input);
this.input.setAttribute("autocomplete", "off");
this.input.setAttribute("aria-autocomplete", "list");
o = o || {};
configure(this, {
minChars: 2,
maxItems: 10,
autoFirst: false,
data: _.DATA,
filter: _.FILTER_CONTAINS,
sort: o.sort === false ? false : _.SORT_BYLENGTH,
item: _.ITEM,
replace: _.REPLACE
}, o);
this.index = -1;
// Create necessary elements
this.container = $.create("div", {
className: "awesomplete",
around: input
});
this.ul = $.create("ul", {
hidden: "hidden",
inside: this.container
});
this.status = $.create("span", {
className: "visually-hidden",
role: "status",
"aria-live": "assertive",
"aria-relevant": "additions",
inside: this.container
});
// Bind events
$.bind(this.input, {
"input": this.evaluate.bind(this),
"blur": this.close.bind(this, { reason: "blur" }),
"keydown": function(evt) {
var c = evt.keyCode;
// If the dropdown `ul` is in view, then act on keydown for the following keys:
// Enter / Esc / Up / Down
if(me.opened) {
if (c === 13 && me.selected) { // Enter
evt.preventDefault();
me.select();
}
else if (c === 27) { // Esc
me.close({ reason: "esc" });
}
else if (c === 38 || c === 40) { // Down/Up arrow
evt.preventDefault();
me[c === 38? "previous" : "next"]();
}
}
}
});
$.bind(this.input.form, {"submit": this.close.bind(this, { reason: "submit" })});
$.bind(this.ul, {"mousedown": function(evt) {
var li = evt.target;
if (li !== this) {
while (li && !/li/i.test(li.nodeName)) {
li = li.parentNode;
}
if (li && evt.button === 0) { // Only select on left click
evt.preventDefault();
me.select(li, evt.target);
}
}
}});
if (this.input.hasAttribute("list")) {
this.list = "#" + this.input.getAttribute("list");
this.input.removeAttribute("list");
}
else {
this.list = this.input.getAttribute("data-list") || o.list || [];
}
_.all.push(this);
};
_.prototype = {
set list(list) {
if (Array.isArray(list)) {
this._list = list;
}
else if (typeof list === "string" && list.indexOf(",") > -1) {
this._list = list.split(/\s*,\s*/);
}
else { // Element or CSS selector
list = $(list);
if (list && list.children) {
var items = [];
slice.apply(list.children).forEach(function (el) {
if (!el.disabled) {
var text = el.textContent.trim();
var value = el.value || text;
var label = el.label || text;
if (value !== "") {
items.push({ label: label, value: value });
}
}
});
this._list = items;
}
}
if (document.activeElement === this.input) {
this.evaluate();
}
},
get selected() {
return this.index > -1;
},
get opened() {
return this.isOpened;
},
close: function (o) {
if (!this.opened) {
return;
}
this.ul.setAttribute("hidden", "");
this.isOpened = false;
this.index = -1;
$.fire(this.input, "awesomplete-close", o || {});
},
open: function () {
this.ul.removeAttribute("hidden");
this.isOpened = true;
if (this.autoFirst && this.index === -1) {
this.goto(0);
}
$.fire(this.input, "awesomplete-open");
},
next: function () {
var count = this.ul.children.length;
this.goto(this.index < count - 1 ? this.index + 1 : (count ? 0 : -1) );
},
previous: function () {
var count = this.ul.children.length;
var pos = this.index - 1;
this.goto(this.selected && pos !== -1 ? pos : count - 1);
},
// Should not be used, highlights specific item without any checks!
goto: function (i) {
var lis = this.ul.children;
if (this.selected) {
lis[this.index].setAttribute("aria-selected", "false");
}
this.index = i;
if (i > -1 && lis.length > 0) {
lis[i].setAttribute("aria-selected", "true");
this.status.textContent = lis[i].textContent;
// scroll to highlighted element in case parent's height is fixed
this.ul.scrollTop = lis[i].offsetTop - this.ul.clientHeight + lis[i].clientHeight;
$.fire(this.input, "awesomplete-highlight", {
text: this.suggestions[this.index]
});
}
},
select: function (selected, origin) {
if (selected) {
this.index = $.siblingIndex(selected);
} else {
selected = this.ul.children[this.index];
}
if (selected) {
var suggestion = this.suggestions[this.index];
var allowed = $.fire(this.input, "awesomplete-select", {
text: suggestion,
origin: origin || selected
});
if (allowed) {
this.replace(suggestion);
this.close({ reason: "select" });
$.fire(this.input, "awesomplete-selectcomplete", {
text: suggestion
});
}
}
},
evaluate: function() {
var me = this;
var value = this.input.value;
if (value.length >= this.minChars && this._list.length > 0) {
this.index = -1;
// Populate list with options that match
this.ul.innerHTML = "";
this.suggestions = this._list
.map(function(item) {
return new Suggestion(me.data(item, value));
})
.filter(function(item) {
return me.filter(item, value);
});
if (this.sort !== false) {
this.suggestions = this.suggestions.sort(this.sort);
}
this.suggestions = this.suggestions.slice(0, this.maxItems);
this.suggestions.forEach(function(text) {
me.ul.appendChild(me.item(text, value));
});
if (this.ul.children.length === 0) {
this.close({ reason: "nomatches" });
} else {
this.open();
}
}
else {
this.close({ reason: "nomatches" });
}
}
};
// Static methods/properties
_.all = [];
_.FILTER_CONTAINS = function (text, input) {
return RegExp($.regExpEscape(input.trim()), "i").test(text);
};
_.FILTER_STARTSWITH = function (text, input) {
return RegExp("^" + $.regExpEscape(input.trim()), "i").test(text);
};
_.SORT_BYLENGTH = function (a, b) {
if (a.length !== b.length) {
return a.length - b.length;
}
return a < b? -1 : 1;
};
_.ITEM = function (text, input) {
var html = input.trim() === '' ? text : text.replace(RegExp($.regExpEscape(input.trim()), "gi"), "<mark>$&</mark>");
return $.create("li", {
innerHTML: html,
"aria-selected": "false"
});
};
_.REPLACE = function (text) {
this.input.value = text.value;
};
_.DATA = function (item/*, input*/) { return item; };
// Private functions
function Suggestion(data) {
var o = Array.isArray(data)
? { label: data[0], value: data[1] }
: typeof data === "object" && "label" in data && "value" in data ? data : { label: data, value: data };
this.label = o.label || o.value;
this.value = o.value;
}
Object.defineProperty(Suggestion.prototype = Object.create(String.prototype), "length", {
get: function() { return this.label.length; }
});
Suggestion.prototype.toString = Suggestion.prototype.valueOf = function () {
return "" + this.label;
};
function configure(instance, properties, o) {
for (var i in properties) {
var initial = properties[i],
attrValue = instance.input.getAttribute("data-" + i.toLowerCase());
if (typeof initial === "number") {
instance[i] = parseInt(attrValue);
}
else if (initial === false) { // Boolean options must be false by default anyway
instance[i] = attrValue !== null;
}
else if (initial instanceof Function) {
instance[i] = null;
}
else {
instance[i] = attrValue;
}
if (!instance[i] && instance[i] !== 0) {
instance[i] = (i in o)? o[i] : initial;
}
}
}
// Helpers
var slice = Array.prototype.slice;
function $(expr, con) {
return typeof expr === "string"? (con || document).querySelector(expr) : expr || null;
}
function $$(expr, con) {
return slice.call((con || document).querySelectorAll(expr));
}
$.create = function(tag, o) {
var element = document.createElement(tag);
for (var i in o) {
var val = o[i];
if (i === "inside") {
$(val).appendChild(element);
}
else if (i === "around") {
var ref = $(val);
ref.parentNode.insertBefore(element, ref);
element.appendChild(ref);
}
else if (i in element) {
element[i] = val;
}
else {
element.setAttribute(i, val);
}
}
return element;
};
$.bind = function(element, o) {
if (element) {
for (var event in o) {
var callback = o[event];
event.split(/\s+/).forEach(function (event) {
element.addEventListener(event, callback);
});
}
}
};
$.fire = function(target, type, properties) {
var evt = document.createEvent("HTMLEvents");
evt.initEvent(type, true, true );
for (var j in properties) {
evt[j] = properties[j];
}
return target.dispatchEvent(evt);
};
$.regExpEscape = function (s) {
return s.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&");
};
$.siblingIndex = function (el) {
/* eslint-disable no-cond-assign */
for (var i = 0; el = el.previousElementSibling; i++);
return i;
};
// Initialization
function init() {
$$("input.awesomplete").forEach(function (input) {
new _(input);
});
}
// Are we in a browser? Check for Document constructor
if (typeof Document !== "undefined") {
// DOM already loaded?
if (document.readyState !== "loading") {
init();
}
else {
// Wait for it
document.addEventListener("DOMContentLoaded", init);
}
}
_.$ = $;
_.$$ = $$;
// Make sure to export Awesomplete on self when in a browser
if (typeof self !== "undefined") {
self.Awesomplete = _;
}
// Expose Awesomplete as a CJS module
if (typeof module === "object" && module.exports) {
module.exports = _;
}
return _;
}());
|
import _curry3 from './internal/_curry3.js';
/**
* The `mapAccum` function behaves like a combination of map and reduce; it
* applies a function to each element of a list, passing an accumulating
* parameter from left to right, and returning a final value of this
* accumulator together with the new list.
*
* The iterator function receives two arguments, *acc* and *value*, and should
* return a tuple *[acc, value]*.
*
* @func
* @memberOf R
* @since v0.10.0
* @category List
* @sig ((acc, x) -> (acc, y)) -> acc -> [x] -> (acc, [y])
* @param {Function} fn The function to be called on every element of the input `list`.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.scan, R.addIndex, R.mapAccumRight
* @example
*
* const digits = ['1', '2', '3', '4'];
* const appender = (a, b) => [a + b, a + b];
*
* R.mapAccum(appender, 0, digits); //=> ['01234', ['01', '012', '0123', '01234']]
* @symb R.mapAccum(f, a, [b, c, d]) = [
* f(f(f(a, b)[0], c)[0], d)[0],
* [
* f(a, b)[1],
* f(f(a, b)[0], c)[1],
* f(f(f(a, b)[0], c)[0], d)[1]
* ]
* ]
*/
var mapAccum = _curry3(function mapAccum(fn, acc, list) {
var idx = 0;
var len = list.length;
var result = [];
var tuple = [acc];
while (idx < len) {
tuple = fn(tuple[0], list[idx]);
result[idx] = tuple[1];
idx += 1;
}
return [tuple[0], result];
});
export default mapAccum;
|
/**
* San
* Copyright 2016 Baidu Inc. All rights reserved.
*
* @file 主文件
* @author errorrik(errorrik@gmail.com)
* otakustay(otakustay@gmail.com)
* junmer(junmer@foxmail.com)
*/
(function (root) {
// 人工调整打包代码顺序,通过注释手工写一些依赖
// // require('./util/empty');
// // require('./util/extend');
// // require('./util/inherits');
// // require('./util/each');
// // require('./util/contains');
// // require('./util/bind');
// // require('./browser/on');
// // require('./browser/un');
// // require('./browser/svg-tags');
// // require('./browser/create-el');
// // require('./browser/remove-el');
// // require('./util/guid');
// // require('./util/next-tick');
// // require('./browser/ie');
// // require('./browser/ie-old-than-9');
// // require('./util/indexed-list');
// // require('./browser/auto-close-tags');
// // require('./util/data-types.js');
// // require('./util/create-data-types-checker.js');
// // require('./parser/walker');
// // require('./parser/create-a-node');
// // require('./parser/parse-template');
// // require('./runtime/change-expr-compare');
// // require('./runtime/data-change-type');
// // require('./runtime/data');
// // require('./runtime/escape-html');
// // require('./runtime/default-filters');
// // require('./runtime/binary-op');
// // require('./runtime/eval-expr');
// // require('./view/life-cycle');
// // require('./view/node-type');
// // require('./view/gen-stump-html');
// // require('./view/create-text');
// // require('./view/get-prop-handler');
// // require('./view/is-data-change-by-element');
// // require('./view/event-declaration-listener');
// // require('./view/gen-element-start-html');
// // require('./view/gen-element-end-html');
// // require('./view/gen-element-children-html');
// // require('./view/create-node');
// // require('./parser/parse-anode-from-el');
// // require('./view/from-el-init-children');
/**
* @file 空函数
* @author errorrik(errorrik@gmail.com)
*/
/**
* 啥都不干
*/
function empty() {}
// exports = module.exports = empty;
/**
* @file 属性拷贝
* @author errorrik(errorrik@gmail.com)
*/
/**
* 对象属性拷贝
*
* @param {Object} target 目标对象
* @param {Object} source 源对象
* @return {Object} 返回目标对象
*/
function extend(target, source) {
for (var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
return target;
}
// exports = module.exports = extend;
/**
* @file 构建类之间的继承关系
* @author errorrik(errorrik@gmail.com)
*/
// var extend = require('./extend');
/**
* 构建类之间的继承关系
*
* @param {Function} subClass 子类函数
* @param {Function} superClass 父类函数
*/
function inherits(subClass, superClass) {
/* jshint -W054 */
var subClassProto = subClass.prototype;
var F = new Function();
F.prototype = superClass.prototype;
subClass.prototype = new F();
subClass.prototype.constructor = subClass;
extend(subClass.prototype, subClassProto);
/* jshint +W054 */
}
// exports = module.exports = inherits;
/**
* @file bind函数
* @author errorrik(errorrik@gmail.com)
*/
/**
* Function.prototype.bind 方法的兼容性封装
*
* @param {Function} func 要bind的函数
* @param {Object} thisArg this指向对象
* @param {...*} args 预设的初始参数
* @return {Function}
*/
function bind(func, thisArg) {
var nativeBind = Function.prototype.bind;
var slice = Array.prototype.slice;
if (nativeBind && func.bind === nativeBind) {
return nativeBind.apply(func, slice.call(arguments, 1));
}
var args = slice.call(arguments, 2);
return function () {
return func.apply(thisArg, args.concat(slice.call(arguments)));
};
}
// exports = module.exports = bind;
/**
* @file 遍历数组
* @author errorrik(errorrik@gmail.com)
*/
// var bind = require('./bind');
/**
* 遍历数组集合
*
* @param {Array} array 数组源
* @param {function(Any,number):boolean} iterator 遍历函数
* @param {Object=} thisArg this指向对象
*/
function each(array, iterator, thisArg) {
if (array && array.length > 0) {
if (thisArg) {
iterator = bind(iterator, thisArg);
}
for (var i = 0, l = array.length; i < l; i++) {
if (iterator(array[i], i) === false) {
break;
}
}
}
}
// exports = module.exports = each;
/**
* @file 判断数组中是否包含某项
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('./each');
/**
* 判断数组中是否包含某项
*
* @param {Array} array 数组
* @param {*} value 包含的项
* @return {boolean}
*/
function contains(array, value) {
var result = false;
each(array, function (item) {
result = item === value;
return !result;
});
return result;
}
// exports = module.exports = contains;
/**
* @file DOM 事件挂载
* @author errorrik(errorrik@gmail.com)
*/
/**
* DOM 事件挂载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
* @param {Function} listener 监听函数
*/
function on(el, eventName, listener) {
if (el.addEventListener) {
el.addEventListener(eventName, listener, false);
}
else {
el.attachEvent('on' + eventName, listener);
}
}
// exports = module.exports = on;
/**
* @file DOM 事件卸载
* @author errorrik(errorrik@gmail.com)
*/
/**
* DOM 事件卸载
*
* @inner
* @param {HTMLElement} el DOM元素
* @param {string} eventName 事件名
* @param {Function} listener 监听函数
*/
function un(el, eventName, listener) {
if (el.addEventListener) {
el.removeEventListener(eventName, listener, false);
}
else {
el.detachEvent('on' + eventName, listener);
}
}
// exports = module.exports = un;
/**
* @file SVG标签表
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
/**
* svgTags
*
* @see https://www.w3.org/TR/SVG/svgdtd.html 只取常用
* @type {Object}
*/
var svgTags = {};
each((''
// structure
+ 'svg,g,defs,desc,metadata,symbol,use,'
// image & shape
+ 'image,path,rect,circle,line,ellipse,polyline,polygon,'
// text
+ 'text,tspan,tref,textpath,'
// other
+ 'marker,pattern,clippath,mask,filter,cursor,view,animate,'
// font
+ 'font,font-face,glyph,missing-glyph'
).split(','),
function (key) {
svgTags[key] = 1;
}
);
// exports = module.exports = svgTags;
/**
* @file DOM创建
* @author errorrik(errorrik@gmail.com)
*/
// var svgTags = require('./svg-tags');
/**
* 创建 DOM 元素
*
* @param {string} tagName tagName
* @return {HTMLElement}
*/
function createEl(tagName) {
if (svgTags[tagName]) {
return document.createElementNS('http://www.w3.org/2000/svg', tagName);
}
return document.createElement(tagName);
}
// exports = module.exports = createEl;
/**
* @file 移除DOM
* @author errorrik(errorrik@gmail.com)
*/
/**
* 将 DOM 从页面中移除
*
* @param {HTMLElement} el DOM元素
*/
function removeEl(el) {
if (el && el.parentNode) {
el.parentNode.removeChild(el);
}
}
// exports = module.exports = removeEl;
/**
* @file 生成唯一id
* @author errorrik(errorrik@gmail.com)
*/
/**
* 唯一id的起始值
*
* @inner
* @type {number}
*/
var guidIndex = 1;
/**
* 获取唯一id
*
* @inner
* @return {string} 唯一id
*/
function guid() {
return '_san_' + (guidIndex++);
}
// exports = module.exports = guid;
/**
* @file 在下一个时间周期运行任务
* @description
* @author errorrik(errorrik@gmail.com)
*/
// 该方法参照了vue2.5.0的实现,感谢vue团队
// SEE: https://github.com/vuejs/vue/blob/0948d999f2fddf9f90991956493f976273c5da1f/src/core/util/env.js#L68
// var bind = require('./bind');
// var each = require('./each');
/**
* 下一个周期要执行的任务列表
*
* @inner
* @type {Array}
*/
var nextTasks = [];
/**
* 执行下一个周期任务的函数
*
* @inner
* @type {Function}
*/
var nextHandler;
/**
* 浏览器是否支持原生Promise
* 对Promise做判断,是为了禁用一些不严谨的Promise的polyfill
*
* @inner
* @type {boolean}
*/
var isNativePromise = typeof Promise === 'function' && /native code/.test(Promise.toString());
/**
* 在下一个时间周期运行任务
*
* @inner
* @param {Function} fn 要运行的任务函数
* @param {Object=} thisArg this指向对象
*/
function nextTick(fn, thisArg) {
if (thisArg) {
fn = bind(fn, thisArg);
}
nextTasks.push(fn);
if (nextHandler) {
return;
}
nextHandler = function () {
var tasks = nextTasks.slice(0);
nextTasks = [];
nextHandler = null;
each(tasks, function (task) {
task();
});
};
// 非标准方法,但是此方法非常吻合要求。
if (typeof setImmediate === 'function') {
setImmediate(nextHandler);
}
// 用MessageChannel去做setImmediate的polyfill
// 原理是将新的message事件加入到原有的dom events之后
else if (typeof MessageChannel === 'function') {
var channel = new MessageChannel();
var port = channel.port2;
channel.port1.onmessage = nextHandler;
port.postMessage(1);
}
// for native app
else if (isNativePromise) {
Promise.resolve().then(nextHandler);
}
else {
setTimeout(nextHandler, 0);
}
}
// exports = module.exports = nextTick;
/**
* @file ie版本号
* @author errorrik(errorrik@gmail.com)
*/
/**
* 从userAgent中ie版本号的匹配信息
*
* @type {Array}
*/
var ieVersionMatch = typeof navigator !== 'undefined'
&& navigator.userAgent.match(/msie\s*([0-9]+)/i);
/**
* ie版本号,非ie时为0
*
* @type {number}
*/
var ie = ieVersionMatch ? ieVersionMatch[1] - 0 : 0;
// exports = module.exports = ie;
/**
* @file 是否 IE 并且小于 9
* @author errorrik(errorrik@gmail.com)
*/
// var ie = require('./ie');
// HACK: IE8下,设置innerHTML时如果以script开头,script会被自动滤掉
// 为了保证script的stump存在,前面加个零宽特殊字符
// IE8下,innerHTML还不支持custom element,所以需要用div替代,不用createElement
/**
* 是否 IE 并且小于 9
*/
var ieOldThan9 = ie && ie < 9;
// exports = module.exports = ieOldThan9;
/**
* @file 索引列表
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('./each');
/**
* 索引列表,能根据 item 中的 name 进行索引
*
* @class
*/
function IndexedList() {
this.raw = [];
this.index = {};
}
/**
* 在列表末尾添加 item
*
* @inner
* @param {Object} item 要添加的对象
*/
IndexedList.prototype.push = function (item) {
// #[begin] error
// if (!item.name) {
// throw new Error('[SAN ERROR] Miss "name" property');
// }
// #[end]
if (!this.index[item.name]) {
this.raw.push(item);
this.index[item.name] = item;
}
};
/**
* 根据 name 获取 item
*
* @inner
* @param {string} name name
* @return {Object}
*/
IndexedList.prototype.get = function (name) {
return this.index[name];
};
/**
* 遍历 items
*
* @inner
* @param {function(*,Number):boolean} iterator 遍历函数
* @param {Object} thisArg 遍历函数运行的this环境
*/
IndexedList.prototype.each = function (iterator, thisArg) {
each(this.raw, iterator, thisArg);
};
/**
* 根据 name 移除 item
*
* @inner
* @param {string} name name
*/
IndexedList.prototype.remove = function (name) {
this.index[name] = null;
var len = this.raw.length;
while (len--) {
if (this.raw[len].name === name) {
this.raw.splice(len, 1);
break;
}
}
};
/**
* 连接另外一个 IndexedList,返回一个新的 IndexedList
*
* @inner
* @param {IndexedList} other 要连接的IndexedList
* @return {IndexedList}
*/
IndexedList.prototype.concat = function (other) {
var result = new IndexedList();
each(this.raw.concat(other.raw), function (item) {
result.push(item);
});
return result;
};
// exports = module.exports = IndexedList;
/**
* @file 自闭合标签表
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
/**
* 自闭合标签列表
*
* @type {Object}
*/
var autoCloseTags = {};
each(
'area,base,br,col,embed,hr,img,input,keygen,param,source,track,wbr'.split(','),
function (key) {
autoCloseTags[key] = 1;
}
);
// exports = module.exports = autoCloseTags;
/**
* @file data types
* @author leon <ludafa@outlook.com>
*/
// var bind = require('./bind');
// var empty = require('./empty');
// var extend = require('./extend');
// #[begin] error
// var ANONYMOUS_CLASS_NAME = '<<anonymous>>';
//
// /**
// * 获取精确的类型
// *
// * @NOTE 如果 obj 是一个 DOMElement,我们会返回 `element`;
// *
// * @param {*} obj 目标
// * @return {string}
// */
// function getDataType(obj) {
//
// if (obj && obj.nodeType === 1) {
// return 'element';
// }
//
// return Object.prototype.toString
// .call(obj)
// .slice(8, -1)
// .toLowerCase();
// }
// #[end]
/**
* 创建链式的数据类型校验器
*
* @param {Function} validate 真正的校验器
* @return {Function}
*/
function createChainableChecker(validate) {
var chainedChecker = function () {};
chainedChecker.isRequired = empty;
// 只在 error 功能启用时才有实际上的 dataTypes 检测
// #[begin] error
// var checkType = function (isRequired, data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// componentName = componentName || ANONYMOUS_CLASS_NAME;
//
// // 如果是 null 或 undefined,那么要提前返回啦
// if (dataValue == null) {
// // 是 required 就报错
// if (isRequired) {
// throw new Error('[SAN ERROR] '
// + 'The `' + dataName + '` '
// + 'is marked as required in `' + componentName + '`, '
// + 'but its value is ' + dataType
// );
// }
// // 不是 required,那就是 ok 的
// return;
// }
//
// validate(data, dataName, componentName, fullDataName);
//
// };
//
// chainedChecker = bind(checkType, null, false);
// chainedChecker.isRequired = bind(checkType, null, true);
// #[end]
return chainedChecker;
}
// #[begin] error
// /**
// * 生成主要类型数据校验器
// *
// * @param {string} type 主类型
// * @return {Function}
// */
// function createPrimaryTypeChecker(type) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== type) {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected ' + type + ')'
// );
// }
//
// });
//
// }
//
//
//
// /**
// * 生成 arrayOf 校验器
// *
// * @param {Function} arrayItemChecker 数组中每项数据的校验器
// * @return {Function}
// */
// function createArrayOfChecker(arrayItemChecker) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (typeof arrayItemChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `arrayOf`, expected `function`'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected array)'
// );
// }
//
// for (var i = 0, len = dataValue.length; i < len; i++) {
// arrayItemChecker(dataValue, i, componentName, fullDataName + '[' + i + ']');
// }
//
// });
//
// }
//
// /**
// * 生成 instanceOf 检测器
// *
// * @param {Function|Class} expectedClass 期待的类
// * @return {Function}
// */
// function createInstanceOfChecker(expectedClass) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// var dataValue = data[dataName];
//
// if (dataValue instanceof expectedClass) {
// return;
// }
//
// var dataValueClassName = dataValue.constructor && dataValue.constructor.name
// ? dataValue.constructor.name
// : ANONYMOUS_CLASS_NAME;
//
// var expectedClassName = expectedClass.name || ANONYMOUS_CLASS_NAME;
//
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataValueClassName + ' supplied to ' + componentName + ', '
// + 'expected instance of ' + expectedClassName + ')'
// );
//
//
// });
//
// }
//
// /**
// * 生成 shape 校验器
// *
// * @param {Object} shapeTypes shape 校验规则
// * @return {Function}
// */
// function createShapeChecker(shapeTypes) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(shapeTypes) !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `shape`, expected `object`'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected object)'
// );
// }
//
// for (var shapeKeyName in shapeTypes) {
// if (shapeTypes.hasOwnProperty(shapeKeyName)) {
// var checker = shapeTypes[shapeKeyName];
// if (typeof checker === 'function') {
// checker(dataValue, shapeKeyName, componentName, fullDataName + '.' + shapeKeyName);
// }
// }
// }
//
// });
//
// }
//
// /**
// * 生成 oneOf 校验器
// *
// * @param {Array} expectedEnumValues 期待的枚举值
// * @return {Function}
// */
// function createOneOfChecker(expectedEnumValues) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(expectedEnumValues) !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `oneOf`, array is expected.'
// );
// }
//
// var dataValue = data[dataName];
//
// for (var i = 0, len = expectedEnumValues.length; i < len; i++) {
// if (dataValue === expectedEnumValues[i]) {
// return;
// }
// }
//
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + fullDataName + '` of value'
// + '(`' + dataValue + '` supplied to ' + componentName + ', '
// + 'expected one of ' + expectedEnumValues.join(',') + ')'
// );
//
// });
//
// }
//
// /**
// * 生成 oneOfType 校验器
// *
// * @param {Array<Function>} expectedEnumOfTypeValues 期待的枚举类型
// * @return {Function}
// */
// function createOneOfTypeChecker(expectedEnumOfTypeValues) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (getDataType(expectedEnumOfTypeValues) !== 'array') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `oneOf`, array is expected.'
// );
// }
//
// var dataValue = data[dataName];
//
// for (var i = 0, len = expectedEnumOfTypeValues.length; i < len; i++) {
//
// var checker = expectedEnumOfTypeValues[i];
//
// if (typeof checker !== 'function') {
// continue;
// }
//
// try {
// checker(data, dataName, componentName, fullDataName);
// // 如果 checker 完成校验没报错,那就返回了
// return;
// }
// catch (e) {
// // 如果有错误,那么应该把错误吞掉
// }
//
// }
//
// // 所有的可接受 type 都失败了,才丢一个异常
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + dataName + '` of value'
// + '(`' + dataValue + '` supplied to ' + componentName + ')'
// );
//
// });
//
// }
//
// /**
// * 生成 objectOf 校验器
// *
// * @param {Function} typeChecker 对象属性值校验器
// * @return {Function}
// */
// function createObjectOfChecker(typeChecker) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName) {
//
// if (typeof typeChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `objectOf`, expected function'
// );
// }
//
// var dataValue = data[dataName];
// var dataType = getDataType(dataValue);
//
// if (dataType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid ' + componentName + ' data `' + dataName + '` of type'
// + '(' + dataType + ' supplied to ' + componentName + ', '
// + 'expected object)'
// );
// }
//
// for (var dataKeyName in dataValue) {
// if (dataValue.hasOwnProperty(dataKeyName)) {
// typeChecker(
// dataValue,
// dataKeyName,
// componentName,
// fullDataName + '.' + dataKeyName
// );
// }
// }
//
//
// });
//
// }
//
// /**
// * 生成 exact 校验器
// *
// * @param {Object} shapeTypes object 形态定义
// * @return {Function}
// */
// function createExactChecker(shapeTypes) {
//
// return createChainableChecker(function (data, dataName, componentName, fullDataName, secret) {
//
// if (getDataType(shapeTypes) !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Data `' + dataName + '` of `' + componentName + '` has invalid '
// + 'DataType notation inside `exact`'
// );
// }
//
// var dataValue = data[dataName];
// var dataValueType = getDataType(dataValue);
//
// if (dataValueType !== 'object') {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` of type `' + dataValueType + '`'
// + '(supplied to ' + componentName + ', expected `object`)'
// );
// }
//
// var allKeys = {};
//
// // 先合入 shapeTypes
// extend(allKeys, shapeTypes);
// // 再合入 dataValue
// extend(allKeys, dataValue);
// // 保证 allKeys 的类型正确
//
// for (var key in allKeys) {
// if (allKeys.hasOwnProperty(key)) {
// var checker = shapeTypes[key];
//
// // dataValue 中有一个多余的数据项
// if (!checker) {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` key `' + key + '` '
// + 'supplied to `' + componentName + '`. '
// + '(`' + key + '` is not defined in `DataTypes.exact`)'
// );
// }
//
// if (!(key in dataValue)) {
// throw new Error('[SAN ERROR] '
// + 'Invalid data `' + fullDataName + '` key `' + key + '` '
// + 'supplied to `' + componentName + '`. '
// + '(`' + key + '` is marked `required` in `DataTypes.exact`)'
// );
// }
//
// checker(
// dataValue,
// key,
// componentName,
// fullDataName + '.' + key,
// secret
// );
//
// }
// }
//
// });
//
// }
// #[end]
/* eslint-disable fecs-valid-var-jsdoc */
var DataTypes = {
array: createChainableChecker(empty),
object: createChainableChecker(empty),
func: createChainableChecker(empty),
string: createChainableChecker(empty),
number: createChainableChecker(empty),
bool: createChainableChecker(empty),
symbol: createChainableChecker(empty),
any: createChainableChecker,
arrayOf: createChainableChecker,
instanceOf: createChainableChecker,
shape: createChainableChecker,
oneOf: createChainableChecker,
oneOfType: createChainableChecker,
objectOf: createChainableChecker,
exact: createChainableChecker
};
// #[begin] error
// DataTypes = {
//
// any: createChainableChecker(empty),
//
// // 类型检测
// array: createPrimaryTypeChecker('array'),
// object: createPrimaryTypeChecker('object'),
// func: createPrimaryTypeChecker('function'),
// string: createPrimaryTypeChecker('string'),
// number: createPrimaryTypeChecker('number'),
// bool: createPrimaryTypeChecker('boolean'),
// symbol: createPrimaryTypeChecker('symbol'),
//
// // 复合类型检测
// arrayOf: createArrayOfChecker,
// instanceOf: createInstanceOfChecker,
// shape: createShapeChecker,
// oneOf: createOneOfChecker,
// oneOfType: createOneOfTypeChecker,
// objectOf: createObjectOfChecker,
// exact: createExactChecker
//
// };
// /* eslint-enable fecs-valid-var-jsdoc */
// #[end]
// module.exports = DataTypes;
/**
* @file 创建数据检测函数
* @author leon<ludafa@outlook.com>
*/
// #[begin] error
//
// /**
// * 创建数据检测函数
// *
// * @param {Object} dataTypes 数据格式
// * @param {string} componentName 组件名
// * @return {Function}
// */
// function createDataTypesChecker(dataTypes, componentName) {
//
// /**
// * 校验 data 是否满足 data types 的格式
// *
// * @param {*} data 数据
// */
// return function (data) {
//
// for (var dataTypeName in dataTypes) {
//
// if (dataTypes.hasOwnProperty(dataTypeName)) {
//
// var dataTypeChecker = dataTypes[dataTypeName];
//
// if (typeof dataTypeChecker !== 'function') {
// throw new Error('[SAN ERROR] '
// + componentName + ':' + dataTypeName + ' is invalid; '
// + 'it must be a function, usually from san.DataTypes'
// );
// }
//
// dataTypeChecker(
// data,
// dataTypeName,
// componentName,
// dataTypeName
// );
//
//
// }
// }
//
// };
//
// }
//
// #[end]
// module.exports = createDataTypesChecker;
/**
* @file 字符串源码读取类
* @author errorrik(errorrik@gmail.com)
*/
/**
* 字符串源码读取类,用于模板字符串解析过程
*
* @class
* @param {string} source 要读取的字符串
*/
function Walker(source) {
this.source = source;
this.len = this.source.length;
this.index = 0;
}
/**
* 获取当前字符码
*
* @return {number}
*/
Walker.prototype.currentCode = function () {
return this.charCode(this.index);
};
/**
* 截取字符串片段
*
* @param {number} start 起始位置
* @param {number} end 结束位置
* @return {string}
*/
Walker.prototype.cut = function (start, end) {
return this.source.slice(start, end);
};
/**
* 向前读取字符
*
* @param {number} distance 读取字符数
*/
Walker.prototype.go = function (distance) {
this.index += distance;
};
/**
* 读取下一个字符,返回下一个字符的 code
*
* @return {number}
*/
Walker.prototype.nextCode = function () {
this.go(1);
return this.currentCode();
};
/**
* 获取相应位置字符的 code
*
* @param {number} index 字符位置
* @return {number}
*/
Walker.prototype.charCode = function (index) {
return this.source.charCodeAt(index);
};
/**
* 向前读取字符,直到遇到指定字符再停止
*
* @param {number=} charCode 指定字符的code
* @return {boolean} 当指定字符时,返回是否碰到指定的字符
*/
Walker.prototype.goUntil = function (charCode) {
var code;
while (this.index < this.len && (code = this.currentCode())) {
switch (code) {
case 32:
case 9:
this.index++;
break;
default:
if (code === charCode) {
this.index++;
return 1;
}
return;
}
}
};
/**
* 向前读取符合规则的字符片段,并返回规则匹配结果
*
* @param {RegExp} reg 字符片段的正则表达式
* @return {Array}
*/
Walker.prototype.match = function (reg) {
reg.lastIndex = this.index;
var match = reg.exec(this.source);
if (match) {
this.index = reg.lastIndex;
}
return match;
};
// exports = module.exports = Walker;
/**
* @file 表达式类型
* @author errorrik(errorrik@gmail.com)
*/
/**
* 表达式类型
*
* @const
* @type {Object}
*/
var ExprType = {
STRING: 1,
NUMBER: 2,
BOOL: 3,
ACCESSOR: 4,
INTERP: 5,
CALL: 6,
TEXT: 7,
BINARY: 8,
UNARY: 9,
TERTIARY: 10
};
// exports = module.exports = ExprType;
/**
* @file 读取字符串
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
/**
* 读取字符串
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readString(walker) {
var startCode = walker.currentCode();
var startIndex = walker.index;
var charCode;
walkLoop: while ((charCode = walker.nextCode())) {
switch (charCode) {
case 92: // \
walker.go(1);
break;
case startCode:
walker.go(1);
break walkLoop;
}
}
var literal = walker.cut(startIndex, walker.index);
return {
type: ExprType.STRING,
value: (new Function('return ' + literal))()
};
}
// exports = module.exports = readString;
/**
* @file 读取数字
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
/**
* 读取数字
*
* @inner
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readNumber(walker) {
var match = walker.match(/\s*(-?[0-9]+(.[0-9]+)?)/g);
return {
type: ExprType.NUMBER,
value: match[1] - 0
};
}
// exports = module.exports = readNumber;
/**
* @file 读取ident
* @author errorrik(errorrik@gmail.com)
*/
/**
* 读取ident
*
* @inner
* @param {Walker} walker 源码读取对象
* @return {string}
*/
function readIdent(walker) {
var match = walker.match(/\s*([\$0-9a-z_]+)/ig);
return match[1];
}
// exports = module.exports = readIdent;
/**
* @file 读取三元表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readLogicalORExpr = require('./read-logical-or-expr');
/**
* 读取三元表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readTertiaryExpr(walker) {
var conditional = readLogicalORExpr(walker);
walker.goUntil();
if (walker.currentCode() === 63) { // ?
walker.go(1);
var yesExpr = readTertiaryExpr(walker);
walker.goUntil();
if (walker.currentCode() === 58) { // :
walker.go(1);
return {
type: ExprType.TERTIARY,
segs: [
conditional,
yesExpr,
readTertiaryExpr(walker)
]
};
}
}
return conditional;
}
// exports = module.exports = readTertiaryExpr;
/**
* @file 读取访问表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readIdent = require('./read-ident');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取访问表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readAccessor(walker) {
var firstSeg = readIdent(walker);
switch (firstSeg) {
case 'true':
case 'false':
return {
type: ExprType.BOOL,
value: firstSeg === 'true'
};
}
var result = {
type: ExprType.ACCESSOR,
paths: [
{
type: ExprType.STRING,
value: firstSeg
}
]
};
/* eslint-disable no-constant-condition */
accessorLoop: while (1) {
/* eslint-enable no-constant-condition */
switch (walker.currentCode()) {
case 46: // .
walker.go(1);
// ident as string
result.paths.push({
type: ExprType.STRING,
value: readIdent(walker)
});
break;
case 91: // [
walker.go(1);
result.paths.push(readTertiaryExpr(walker));
walker.goUntil(93); // ]
break;
default:
break accessorLoop;
}
}
return result;
}
// exports = module.exports = readAccessor;
/**
* @file 读取括号表达式
* @author errorrik(errorrik@gmail.com)
*/
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取括号表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readParenthesizedExpr(walker) {
walker.go(1);
var expr = readTertiaryExpr(walker);
walker.goUntil(41); // )
return expr;
}
// exports = module.exports = readParenthesizedExpr;
/**
* @file 读取一元表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readString = require('./read-string');
// var readNumber = require('./read-number');
// var readAccessor = require('./read-accessor');
// var readParenthesizedExpr = require('./read-parenthesized-expr');
/**
* 读取一元表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readUnaryExpr(walker) {
walker.goUntil();
switch (walker.currentCode()) {
case 33: // !
walker.go(1);
return {
type: ExprType.UNARY,
expr: readUnaryExpr(walker)
};
case 34: // "
case 39: // '
return readString(walker);
case 45: // number
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
return readNumber(walker);
case 40: // (
return readParenthesizedExpr(walker);
}
return readAccessor(walker);
}
// exports = module.exports = readUnaryExpr;
/**
* @file 读取乘法表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readUnaryExpr = require('./read-unary-expr');
/**
* 读取乘法表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readMultiplicativeExpr(walker) {
var expr = readUnaryExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 37: // %
case 42: // *
case 47: // /
walker.go(1);
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readMultiplicativeExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readMultiplicativeExpr;
/**
* @file 读取加法表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readMultiplicativeExpr = require('./read-multiplicative-expr');
/**
* 读取加法表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readAdditiveExpr(walker) {
var expr = readMultiplicativeExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 43: // +
case 45: // -
walker.go(1);
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readAdditiveExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readAdditiveExpr;
/**
* @file 读取关系判断表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readAdditiveExpr = require('./read-additive-expr');
/**
* 读取关系判断表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readRelationalExpr(walker) {
var expr = readAdditiveExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 60: // <
case 62: // >
if (walker.nextCode() === 61) {
code += 61;
walker.go(1);
}
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readRelationalExpr(walker)]
};
}
return expr;
}
// exports = module.exports = readRelationalExpr;
/**
* @file 读取相等比对表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readRelationalExpr = require('./read-relational-expr');
/**
* 读取相等比对表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readEqualityExpr(walker) {
var expr = readRelationalExpr(walker);
walker.goUntil();
var code = walker.currentCode();
switch (code) {
case 61: // =
case 33: // !
if (walker.nextCode() === 61) {
code += 61;
if (walker.nextCode() === 61) {
code += 61;
walker.go(1);
}
return {
type: ExprType.BINARY,
operator: code,
segs: [expr, readEqualityExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readEqualityExpr;
/**
* @file 读取逻辑与表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readEqualityExpr = require('./read-equality-expr');
/**
* 读取逻辑与表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readLogicalANDExpr(walker) {
var expr = readEqualityExpr(walker);
walker.goUntil();
if (walker.currentCode() === 38) { // &
if (walker.nextCode() === 38) {
walker.go(1);
return {
type: ExprType.BINARY,
operator: 76,
segs: [expr, readLogicalANDExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readLogicalANDExpr;
/**
* @file 读取逻辑或表达式
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readLogicalANDExpr = require('./read-logical-and-expr');
/**
* 读取逻辑或表达式
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readLogicalORExpr(walker) {
var expr = readLogicalANDExpr(walker);
walker.goUntil();
if (walker.currentCode() === 124) { // |
if (walker.nextCode() === 124) {
walker.go(1);
return {
type: ExprType.BINARY,
operator: 248,
segs: [expr, readLogicalORExpr(walker)]
};
}
walker.go(-1);
}
return expr;
}
// exports = module.exports = readLogicalORExpr;
/**
* @file 读取调用
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('./expr-type');
// var readIdent = require('./read-ident');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 读取调用
*
* @param {Walker} walker 源码读取对象
* @return {Object}
*/
function readCall(walker) {
walker.goUntil();
var ident = readIdent(walker);
var args = [];
if (walker.goUntil(40)) { // (
while (!walker.goUntil(41)) { // )
args.push(readTertiaryExpr(walker));
walker.goUntil(44); // ,
}
}
return {
type: ExprType.CALL,
name: ident,
args: args
};
}
// exports = module.exports = readCall;
/**
* @file 解析插值替换
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var readTertiaryExpr = require('./read-tertiary-expr');
// var ExprType = require('./expr-type');
// var readCall = require('./read-call');
/**
* 解析插值替换
*
* @param {string} source 源码
* @return {Object}
*/
function parseInterp(source) {
var walker = new Walker(source);
var expr = readTertiaryExpr(walker);
var filters = [];
while (walker.goUntil(124)) { // |
filters.push(readCall(walker));
}
return {
type: ExprType.INTERP,
expr: expr,
filters: filters
};
}
// exports = module.exports = parseInterp;
/**
* @file 解析文本
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var ExprType = require('./expr-type');
// var parseInterp = require('./parse-interp');
/**
* 解析文本
*
* @param {string} source 源码
* @return {Object}
*/
function parseText(source) {
var exprStartReg = /\{\{\s*([\s\S]+?)\s*\}\}/ig;
var exprMatch;
var walker = new Walker(source);
var beforeIndex = 0;
var segs = [];
function pushStringToSeg(text) {
text && segs.push({
type: ExprType.STRING,
value: text
});
}
while ((exprMatch = walker.match(exprStartReg)) != null) {
pushStringToSeg(walker.cut(
beforeIndex,
walker.index - exprMatch[0].length
));
segs.push(parseInterp(exprMatch[1]));
beforeIndex = walker.index;
}
pushStringToSeg(walker.cut(beforeIndex));
var expr = {
type: ExprType.TEXT,
segs: segs,
raw: source
};
if (segs.length === 1 && segs[0].type === ExprType.STRING) {
expr.value = segs[0].value;
}
return expr;
}
// exports = module.exports = parseText;
/**
* @file 模板解析生成的抽象节点
* @author errorrik(errorrik@gmail.com)
*/
// var IndexedList = require('../util/indexed-list');
// var parseText = require('./parse-text');
/**
* 创建模板解析生成的抽象节点
*
* @class
* @param {Object=} options 节点参数
* @param {string=} options.tagName 标签名
* @param {ANode=} options.parent 父节点
* @param {boolean=} options.isText 是否文本节点
*/
function createANode(options) {
options = options || {};
if (options.isText) {
options.textExpr = parseText(options.text);
}
else {
options.directives = options.directives || new IndexedList();
options.props = options.props || new IndexedList();
options.events = options.events || [];
options.children = options.children || [];
}
return options;
}
// exports = module.exports = createANode;
/**
* @file 解析表达式
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var readTertiaryExpr = require('./read-tertiary-expr');
/**
* 解析表达式
*
* @param {string} source 源码
* @return {Object}
*/
function parseExpr(source) {
if (typeof source === 'object' && source.type) {
return source;
}
var expr = readTertiaryExpr(new Walker(source));
expr.raw = source;
return expr;
}
// exports = module.exports = parseExpr;
/**
* @file 解析调用
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var readCall = require('./read-call');
/**
* 解析调用
*
* @param {string} source 源码
* @return {Object}
*/
function parseCall(source) {
var expr = readCall(new Walker(source));
expr.raw = source;
return expr;
}
// exports = module.exports = parseCall;
/**
* @file 解析指令
* @author errorrik(errorrik@gmail.com)
*/
// var Walker = require('./walker');
// var parseExpr = require('./parse-expr');
// var parseText = require('./parse-text');
// var parseInterp = require('./parse-interp');
// var readAccessor = require('./read-accessor');
/**
* 指令解析器
*
* @inner
* @type {Object}
*/
var directiveParsers = {
'for': function (value) {
var walker = new Walker(value);
var match = walker.match(/^\s*([\$0-9a-z_]+)(\s*,\s*([\$0-9a-z_]+))?\s+in\s+/ig);
if (match) {
return {
item: parseExpr(match[1]),
index: parseExpr(match[3] || '$index'),
list: readAccessor(walker)
};
}
// #[begin] error
// throw new Error('[SAN FATAL] for syntax error: ' + value);
// #[end]
},
'ref': function (value) {
return {
value: parseText(value)
};
},
'if': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'elif': function (value) {
return {
value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
};
},
'else': function (value) {
return {
value: 1
};
},
'html': function (value) {
return {
value: parseInterp(value)
};
},
'transition': function (value) {
return {
value: value
};
}
};
/**
* 解析指令
*
* @param {ANode} aNode 抽象节点
* @param {string} name 指令名称
* @param {string} value 指令值
*/
function parseDirective(aNode, name, value) {
var parser = directiveParsers[name];
if (parser) {
var result = parser(value);
result.name = name;
result.raw = value;
aNode.directives.push(result);
}
}
// exports = module.exports = parseDirective;
/**
* @file 对属性信息进行处理
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('../parser/expr-type');
/**
* 对属性信息进行处理
* 对组件的 binds 或者特殊的属性(比如 input 的 checked)需要处理
*
* 扁平化:
* 当 text 解析只有一项时,要么就是 string,要么就是 interp
* interp 有可能是绑定到组件属性的表达式,不希望被 eval text 成 string
* 所以这里做个处理,只有一项时直接抽出来
*
* bool属性:
* 当绑定项没有值时,默认为true
*
* @param {Object} prop 属性对象
*/
function postProp(prop) {
var expr = prop.expr;
if (expr.type === ExprType.TEXT) {
switch (expr.segs.length) {
case 0:
prop.expr = {
type: ExprType.BOOL,
value: true
};
break;
case 1:
expr = prop.expr = expr.segs[0];
if (expr.type === ExprType.INTERP && expr.filters.length === 0) {
prop.expr = expr.expr;
}
}
}
}
// exports = module.exports = postProp;
/**
* @file 二元表达式操作函数
* @author errorrik(errorrik@gmail.com)
*/
/**
* 二元表达式操作函数
*
* @type {Object}
*/
var BinaryOp = {
/* eslint-disable */
37: function (a, b) {
return a % b;
},
43: function (a, b) {
return a + b;
},
45: function (a, b) {
return a - b;
},
42: function (a, b) {
return a * b;
},
47: function (a, b) {
return a / b;
},
60: function (a, b) {
return a < b;
},
62: function (a, b) {
return a > b;
},
76: function (a, b) {
return a && b;
},
94: function (a, b) {
return a != b;
},
121: function (a, b) {
return a <= b;
},
122: function (a, b) {
return a == b;
},
123: function (a, b) {
return a >= b;
},
155: function (a, b) {
return a !== b;
},
183: function (a, b) {
return a === b;
},
248: function (a, b) {
return a || b;
}
/* eslint-enable */
};
// exports = module.exports = BinaryOp;
/**
* @file HTML转义
* @author errorrik(errorrik@gmail.com)
*/
/**
* HTML Filter替换的字符实体表
*
* @const
* @inner
* @type {Object}
*/
var HTML_ENTITY = {
/* jshint ignore:start */
'&': '&',
'<': '<',
'>': '>',
'"': '"',
/* eslint-disable quotes */
"'": '''
/* eslint-enable quotes */
/* jshint ignore:end */
};
/**
* HTML Filter的替换函数
*
* @inner
* @param {string} c 替换字符
* @return {string} 替换后的HTML字符实体
*/
function htmlFilterReplacer(c) {
return HTML_ENTITY[c];
}
/**
* HTML转义
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
function escapeHTML(source) {
if (source == null) {
return '';
}
return ('' + source).replace(/[&<>"']/g, htmlFilterReplacer);
}
// exports = module.exports = escapeHTML;
/**
* @file 默认filter
* @author errorrik(errorrik@gmail.com)
*/
// var escapeHTML = require('./escape-html');
/* eslint-disable fecs-camelcase */
/* eslint-disable guard-for-in */
/**
* 默认filter
*
* @const
* @type {Object}
*/
var DEFAULT_FILTERS = {
/**
* HTML转义filter
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
html: escapeHTML,
/**
* URL编码filter
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
url: encodeURIComponent,
/**
* 源串filter,用于在默认开启HTML转义时获取源串,不进行转义
*
* @param {string} source 源串
* @return {string} 替换结果串
*/
raw: function (source) {
return source;
},
_class: function (source) {
if (source instanceof Array) {
return source.join(' ');
}
return source;
},
_style: function (source) {
if (typeof source === 'object') {
var result = '';
for (var key in source) {
result += key + ':' + source[key] + ';';
}
return result;
}
return source;
},
_sep: function (source, sep) {
return source ? sep + source : source;
}
};
/* eslint-enable fecs-camelcase */
// exports = module.exports = DEFAULT_FILTERS;
/**
* @file 表达式计算
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('../parser/expr-type');
// var BinaryOp = require('./binary-op');
// var DEFAULT_FILTERS = require('./default-filters');
// var escapeHTML = require('./escape-html');
// var each = require('../util/each');
/**
* 计算表达式的值
*
* @param {Object} expr 表达式对象
* @param {Data} data 数据容器对象
* @param {Component=} owner 所属组件环境
* @param {boolean?} escapeInterpHtml 是否对插值进行html转义
* @return {*}
*/
function evalExpr(expr, data, owner, escapeInterpHtml) {
if (expr.value != null) {
return expr.value;
}
switch (expr.type) {
case ExprType.UNARY:
return !evalExpr(expr.expr, data, owner);
case ExprType.BINARY:
var opHandler = BinaryOp[expr.operator];
if (typeof opHandler === 'function') {
return opHandler(
evalExpr(expr.segs[0], data, owner),
evalExpr(expr.segs[1], data, owner)
);
}
return;
case ExprType.TERTIARY:
return evalExpr(
expr.segs[evalExpr(expr.segs[0], data, owner) ? 1 : 2],
data,
owner
);
case ExprType.ACCESSOR:
return data.get(expr);
case ExprType.INTERP:
var value = evalExpr(expr.expr, data, owner);
owner && each(expr.filters, function (filter) {
var filterName = filter.name;
/* eslint-disable no-use-before-define */
var filterFn = owner.filters[filterName] || DEFAULT_FILTERS[filterName];
/* eslint-enable no-use-before-define */
if (typeof filterFn === 'function') {
var args = [value];
each(filter.args, function (arg) {
args.push(evalExpr(arg, data, owner));
});
value = filterFn.apply(owner, args);
}
});
if (value == null) {
value = '';
}
return value;
case ExprType.TEXT:
var buf = '';
each(expr.segs, function (seg) {
var segValue = evalExpr(seg, data, owner);
// escape html
if (escapeInterpHtml && seg.type === ExprType.INTERP && !seg.filters[0]) {
segValue = escapeHTML(segValue);
}
buf += segValue;
});
return buf;
}
}
// exports = module.exports = evalExpr;
/**
* @file 在节点环境执行表达式
* @author errorrik(errorrik@gmail.com)
*/
// var evalExpr = require('../runtime/eval-expr');
/**
* 在节点环境执行表达式
*
* @param {Object} node 节点对象
* @param {Object} expr 表达式对象
* @param {boolean} escapeInterpHtml 是否要对插值结果进行html转义
* @return {*}
*/
function nodeEvalExpr(node, expr, escapeInterpHtml) {
return evalExpr(expr, node.scope, node.owner, escapeInterpHtml);
}
// exports = module.exports = nodeEvalExpr;
/**
* @file 节点类型
* @author errorrik(errorrik@gmail.com)
*/
/**
* 节点类型
*
* @const
* @type {Object}
*/
var NodeType = {
TEXT: 1,
IF: 2,
FOR: 3,
ELEM: 4,
CMPT: 5,
SLOT: 6,
TPL: 7
};
// exports = module.exports = NodeType;
/**
* @file 判断一个node是否组件
* @author errorrik(errorrik@gmail.com)
*/
// var NodeType = require('./node-type');
/**
* 判断一个node是否组件
*
* @param {Node} node 节点实例
* @return {boolean}
*/
function isComponent(node) {
return node && node.nodeType === NodeType.CMPT;
}
// exports = module.exports = isComponent;
/**
* @file 获取属性处理对象
* @author errorrik(errorrik@gmail.com)
*/
// var contains = require('../util/contains');
// var empty = require('../util/empty');
// var svgTags = require('../browser/svg-tags');
// var evalExpr = require('../runtime/eval-expr');
// var nodeEvalExpr = require('./node-eval-expr');
// var isComponent = require('./is-component');
/**
* HTML 属性和 DOM 操作属性的对照表
*
* @inner
* @const
* @type {Object}
*/
var HTML_ATTR_PROP_MAP = {
'readonly': 'readOnly',
'cellpadding': 'cellPadding',
'cellspacing': 'cellSpacing',
'colspan': 'colSpan',
'rowspan': 'rowSpan',
'valign': 'vAlign',
'usemap': 'useMap',
'frameborder': 'frameBorder',
'for': 'htmlFor',
'class': 'className'
};
/**
* 默认的元素的属性设置的变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandler = {
attr: function (element, name, value) {
if (value != null) {
return ' ' + name + '="' + value + '"';
}
},
prop: function (element, name, value) {
var propName = HTML_ATTR_PROP_MAP[name] || name;
var el = element.el;
// input 的 type 是个特殊属性,其实也应该用 setAttribute
// 但是 type 不应该运行时动态改变,否则会有兼容性问题
// 所以这里直接就不管了
if (svgTags[element.tagName] || !(propName in el)) {
el.setAttribute(name, value);
}
else {
el[propName] = value == null ? '' : value;
}
// attribute 绑定的是 text,所以不会出现 null 的情况,这里无需处理
// 换句话来说,san 是做不到 attribute 时有时无的
// if (value == null) {
// el.removeAttribute(name);
// }
},
output: function (element, bindInfo, data) {
data.set(bindInfo.expr, element.el[bindInfo.name], {
target: {
id: element.id,
prop: bindInfo.name
}
});
}
};
/**
* 默认的属性设置变换方法
*
* @inner
* @type {Object}
*/
var defaultElementPropHandlers = {
style: {
attr: function (element, name, value) {
if (value != null) {
return ' style="' + value + '"';
}
},
prop: function (element, name, value) {
element.el.style.cssText = value;
}
},
draggable: genBoolPropHandler('draggable'),
readonly: genBoolPropHandler('readonly'),
disabled: genBoolPropHandler('disabled')
};
var checkedPropHandler = genBoolPropHandler('checked');
var analInputChecker = {
checkbox: contains,
radio: function (a, b) {
return a === b;
}
};
function analInputCheckedState(element, value, oper) {
var bindValue = element.props.get('value');
var bindType = element.props.get('type');
if (bindValue && bindType) {
var type = nodeEvalExpr(element, bindType.expr);
if (analInputChecker[type]) {
var bindChecked = element.props.get('checked');
if (!bindChecked.hintExpr) {
bindChecked.hintExpr = bindValue.expr;
}
var checkedState = analInputChecker[type](
value,
nodeEvalExpr(element, bindValue.expr)
);
switch (oper) {
case 'attr':
return checkedState ? ' checked="checked"' : '';
case 'prop':
element.el.checked = checkedState;
return;
}
}
}
return checkedPropHandler[oper](element, 'checked', value);
}
var elementPropHandlers = {
input: {
multiple: genBoolPropHandler('multiple'),
checked: {
attr: function (element, name, value) {
return analInputCheckedState(element, value, 'attr');
},
prop: function (element, name, value) {
analInputCheckedState(element, value, 'prop');
},
output: function (element, bindInfo, data) {
var el = element.el;
var bindValue = element.props.get('value');
var bindType = element.props.get('type') || {};
if (bindValue && bindType) {
switch (bindType.raw) {
case 'checkbox':
data[el.checked ? 'push' : 'remove'](bindInfo.expr, el.value);
return;
case 'radio':
el.checked && data.set(bindInfo.expr, el.value, {
target: {
id: element.id,
prop: bindInfo.name
}
});
return;
}
}
defaultElementPropHandler.output(element, bindInfo, data);
}
}
},
textarea: {
value: {
attr: empty,
prop: defaultElementPropHandler.prop,
output: defaultElementPropHandler.output
}
},
option: {
value: {
attr: function (element, name, value) {
var attrStr = ' value="' + (value || '') + '"';
var parentSelect = element.parent;
while (parentSelect) {
if (parentSelect.tagName === 'select') {
break;
}
parentSelect = parentSelect.parent;
}
if (parentSelect) {
var selectValue = null;
var prop;
var expr;
if ((prop = parentSelect.props.get('value'))
&& (expr = prop.expr)
) {
selectValue = isComponent(parentSelect)
? evalExpr(expr, parentSelect.data, parentSelect)
: nodeEvalExpr(parentSelect, expr)
|| '';
}
if (selectValue === value) {
attrStr += ' selected';
}
}
return attrStr;
},
prop: defaultElementPropHandler.prop
}
},
select: {
value: {
attr: empty,
prop: function (element, name, value) {
element.el.value = value || '';
},
output: defaultElementPropHandler.output
}
}
};
/**
* 生成 bool 类型属性绑定操作的变换方法
*
* @inner
* @param {string} attrName 属性名
* @return {Object}
*/
function genBoolPropHandler(attrName) {
return {
attr: function (element, name, value) {
// 因为元素的attr值必须经过html escape,否则可能有漏洞
// 所以这里直接对假值字符串形式进行处理
// NaN之类非主流的就先不考虑了
var prop = element.props.get(name);
if (prop && prop.raw === ''
|| value && value !== 'false' && value !== '0'
) {
return ' ' + attrName;
}
},
prop: function (element, name, value) {
var propName = HTML_ATTR_PROP_MAP[attrName] || attrName;
element.el[propName] = !!(value && value !== 'false' && value !== '0');
}
};
}
/**
* 获取属性处理对象
*
* @param {Element} element 元素实例
* @param {string} name 属性名
* @return {Object}
*/
function getPropHandler(element, name) {
var tagPropHandlers = elementPropHandlers[element.tagName];
if (!tagPropHandlers) {
tagPropHandlers = elementPropHandlers[element.tagName] = {};
}
var propHandler = tagPropHandlers[name];
if (!propHandler) {
propHandler = defaultElementPropHandlers[name] || defaultElementPropHandler;
tagPropHandlers[name] = propHandler;
}
return propHandler;
}
// exports = module.exports = getPropHandler;
/**
* @file 解析抽象节点属性
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var parseExpr = require('./parse-expr');
// var parseCall = require('./parse-call');
// var parseText = require('./parse-text');
// var parseDirective = require('./parse-directive');
// var ExprType = require('./expr-type');
// var postProp = require('./post-prop');
// var getPropHandler = require('../view/get-prop-handler');
/**
* 解析抽象节点属性
*
* @param {ANode} aNode 抽象节点
* @param {string} name 属性名称
* @param {string} value 属性值
* @param {boolean=} ignoreNormal 是否忽略无前缀的普通属性
*/
function integrateAttr(aNode, name, value, ignoreNormal) {
if (name === 'id') {
aNode.id = value;
return;
}
var prefixIndex = name.indexOf('-');
var realName;
var prefix;
if (prefixIndex > 0) {
prefix = name.slice(0, prefixIndex);
realName = name.slice(prefixIndex + 1);
}
switch (prefix) {
case 'on':
var event = {
name: realName
};
aNode.events.push(event);
var colonIndex = value.indexOf(':');
if (colonIndex > 0) {
var modifier = value.slice(0, colonIndex);
// eventHandler("dd:aa") 这种情况不能算modifier,需要辨识
if (/^[a-z]+$/i.test(modifier)) {
event.modifier = modifier;
value = value.slice(colonIndex + 1);
}
}
var expr = parseCall(value);
if (expr.args.length === 0) {
expr.args.push({
type: ExprType.ACCESSOR,
paths: [
{type: ExprType.STRING, value: '$event'}
]
});
}
event.expr = expr;
break;
case 'san':
case 's':
parseDirective(aNode, realName, value);
break;
case 'prop':
integrateProp(aNode, realName, value);
break;
case 'var':
if (!aNode.vars) {
aNode.vars = [];
}
aNode.vars.push({
name: realName,
expr: parseExpr(value.replace(/(^\{\{|\}\}$)/g, ''))
});
break;
default:
if (!ignoreNormal) {
integrateProp(aNode, name, value);
}
}
}
/**
* 解析抽象节点绑定属性
*
* @inner
* @param {ANode} aNode 抽象节点
* @param {string} name 属性名称
* @param {string} value 属性值
*/
function integrateProp(aNode, name, value) {
// parse two way binding, e.g. value="{=ident=}"
var xMatch = value.match(/^\{=\s*(.*?)\s*=\}$/);
if (xMatch) {
aNode.props.push({
name: name,
expr: parseExpr(xMatch[1]),
x: 1,
raw: value
});
return;
}
// parse normal prop
var prop = {
name: name,
expr: parseText(value),
raw: value
};
if (prop.expr.value != null && !/^(template|input|textarea|select|option)$/.test(aNode.tagName)) {
prop.attr = getPropHandler(aNode, name).attr(aNode, name, value);
}
if (name === 'checked' && aNode.tagName === 'input') {
postProp(prop);
}
// 这里不能把只有一个插值的属性抽取
// 因为插值里的值可能是html片段,容易被注入
// 组件的数据绑定在组件init时做抽取
switch (prop.name) {
case 'class':
case 'style':
each(prop.expr.segs, function (seg) {
if (seg.type === ExprType.INTERP) {
seg.filters.push({
type: ExprType.CALL,
name: '_' + prop.name,
args: []
});
}
});
break;
}
aNode.props.push(prop);
}
// exports = module.exports = integrateAttr;
/**
* @file 解析模板
* @author errorrik(errorrik@gmail.com)
*/
// var createANode = require('./create-a-node');
// var Walker = require('./walker');
// var integrateAttr = require('./integrate-attr');
// var autoCloseTags = require('../browser/auto-close-tags');
/* eslint-disable fecs-max-statements */
/**
* 解析 template
*
* @param {string} source template源码
* @param {Object?} options 解析参数
* @param {string?} options.trimWhitespace 空白文本的处理策略。none|blank|all
* @return {ANode}
*/
function parseTemplate(source, options) {
options = options || {};
options.trimWhitespace = options.trimWhitespace || 'none';
var rootNode = createANode();
if (typeof source !== 'string') {
return rootNode;
}
source = source.replace(/<!--([\s\S]*?)-->/mg, '').replace(/(^\s+|\s+$)/g, '');
var walker = new Walker(source);
var tagReg = /<(\/)?([a-z0-9-]+)\s*/ig;
var attrReg = /([-:0-9a-z\(\)\[\]]+)(=(['"])([^\3]*?)\3)?\s*/ig;
var tagMatch;
var currentNode = rootNode;
var stack = [rootNode];
var stackIndex = 0;
var beforeLastIndex = 0;
while ((tagMatch = walker.match(tagReg)) != null) {
var tagEnd = tagMatch[1];
var tagName = tagMatch[2].toLowerCase();
pushTextNode(source.slice(
beforeLastIndex,
walker.index - tagMatch[0].length
));
// 62: >
// 47: /
if (tagEnd && walker.currentCode() === 62) {
// 满足关闭标签的条件时,关闭标签
// 向上查找到对应标签,找不到时忽略关闭
var closeIndex = stackIndex;
while (closeIndex > 0 && stack[closeIndex].tagName !== tagName) {
closeIndex--;
}
if (closeIndex > 0) {
stack.length = closeIndex;
stackIndex = closeIndex - 1;
currentNode = stack[stackIndex];
}
walker.go(1);
}
else if (!tagEnd) {
var aElement = createANode({
tagName: tagName
});
var tagClose = autoCloseTags[tagName];
// 解析 attributes
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
var nextCharCode = walker.currentCode();
// 标签结束时跳出 attributes 读取
// 标签可能直接结束或闭合结束
if (nextCharCode === 62) {
walker.go(1);
break;
}
else if (nextCharCode === 47
&& walker.charCode(walker.index + 1) === 62
) {
walker.go(2);
tagClose = 1;
break;
}
// 读取 attribute
var attrMatch = walker.match(attrReg);
if (attrMatch) {
integrateAttr(
aElement,
attrMatch[1],
attrMatch[2] ? attrMatch[4] : ''
);
}
}
// match if directive for else/elif directive
var elseDirective = aElement.directives.get('else') || aElement.directives.get('elif');
if (elseDirective) {
var parentChildrenLen = currentNode.children.length;
while (parentChildrenLen--) {
var parentChild = currentNode.children[parentChildrenLen];
if (parentChild.isText) {
currentNode.children.splice(parentChildrenLen, 1);
continue;
}
// #[begin] error
// if (!parentChild.directives.get('if')) {
// throw new Error('[SAN FATEL] else not match if.');
// }
// #[end]
parentChild.elses = parentChild.elses || [];
parentChild.elses.push(aElement);
break;
}
}
else {
if (aElement.tagName === 'tr' && currentNode.tagName === 'table') {
var tbodyNode = createANode({
tagName: 'tbody'
});
currentNode.children.push(tbodyNode);
currentNode = tbodyNode;
stack[++stackIndex] = tbodyNode;
}
currentNode.children.push(aElement);
}
if (!tagClose) {
currentNode = aElement;
stack[++stackIndex] = aElement;
}
}
beforeLastIndex = walker.index;
}
pushTextNode(walker.cut(beforeLastIndex));
return rootNode;
/**
* 在读取栈中添加文本节点
*
* @inner
* @param {string} text 文本内容
*/
function pushTextNode(text) {
switch (options.trimWhitespace) {
case 'blank':
if (/^\s+$/.test(text)) {
text = null;
}
break;
case 'all':
text = text.replace(/(^\s+|\s+$)/g, '');
break;
}
if (text) {
currentNode.children.push(createANode({
isText: 1,
text: text
}));
}
}
}
/* eslint-enable fecs-max-statements */
// exports = module.exports = parseTemplate;
/**
* @file 比较变更表达式与目标表达式之间的关系
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('../parser/expr-type');
// var evalExpr = require('./eval-expr');
// var each = require('../util/each');
/**
* 判断变更表达式与多个表达式之间的关系,0为完全没关系,1为有关系
*
* @inner
* @param {Object} changeExpr 目标表达式
* @param {Array} exprs 多个源表达式
* @param {Data} data 表达式所属数据环境
* @return {number}
*/
function changeExprCompareExprs(changeExpr, exprs, data) {
var result;
each(exprs, function (expr) {
result = changeExprCompare(changeExpr, expr, data);
return !result;
});
return result ? 1 : 0;
}
/**
* 比较变更表达式与目标表达式之间的关系,用于视图更新判断
* 视图更新需要根据其关系,做出相应的更新行为
*
* 0: 完全没关系
* 1: 变更表达式是目标表达式的母项(如a与a.b) 或 表示需要完全变化
* 2: 变更表达式是目标表达式相等
* >2: 变更表达式是目标表达式的子项,如a.b.c与a.b
*
* @param {Object} changeExpr 变更表达式
* @param {Object} expr 要比较的目标表达式
* @param {Data} data 表达式所属数据环境
* @return {number}
*/
function changeExprCompare(changeExpr, expr, data) {
switch (expr.type) {
case ExprType.ACCESSOR:
var paths = expr.paths;
var len = paths.length;
var changePaths = changeExpr.paths;
var changeLen = changePaths.length;
var result = 1;
for (var i = 0; i < len; i++) {
var pathExpr = paths[i];
if (pathExpr.type === ExprType.ACCESSOR
&& changeExprCompare(changeExpr, pathExpr, data)
) {
return 1;
}
if (result && i < changeLen
/* eslint-disable eqeqeq */
&& evalExpr(pathExpr, data) != evalExpr(changePaths[i], data)
/* eslint-enable eqeqeq */
) {
result = 0;
}
}
if (result) {
result = Math.max(1, changeLen - len + 2);
}
return result;
case ExprType.UNARY:
return changeExprCompare(changeExpr, expr.expr, data) ? 1 : 0;
case ExprType.TEXT:
case ExprType.BINARY:
case ExprType.TERTIARY:
return changeExprCompareExprs(changeExpr, expr.segs, data);
case ExprType.INTERP:
if (!changeExprCompare(changeExpr, expr.expr, data)) {
var filterResult;
each(expr.filters, function (filter) {
filterResult = changeExprCompareExprs(changeExpr, filter.args, data);
return !filterResult;
});
return filterResult ? 1 : 0;
}
return 1;
}
return 0;
}
// exports = module.exports = changeExprCompare;
/**
* @file 数据变更类型枚举
* @author errorrik(errorrik@gmail.com)
*/
/**
* 数据变更类型枚举
*
* @const
* @type {Object}
*/
var DataChangeType = {
SET: 1,
SPLICE: 2
};
// exports = module.exports = DataChangeType;
/**
* @file 数据类
* @author errorrik(errorrik@gmail.com)
*/
// var ExprType = require('../parser/expr-type');
// var evalExpr = require('./eval-expr');
// var DataChangeType = require('./data-change-type');
// var parseExpr = require('../parser/parse-expr');
// var each = require('../util/each');
/**
* 数据类
*
* @class
* @param {Object?} data 初始数据
* @param {Model?} parent 父级数据容器
*/
function Data(data, parent) {
this.parent = parent;
this.raw = data || {};
this.listeners = [];
}
// #[begin] error
// // 以下两个函数只在开发模式下可用,在生产模式下不存在
// /**
// * DataTypes 检测
// */
// Data.prototype.checkDataTypes = function () {
// if (this.typeChecker) {
// this.typeChecker(this.raw);
// }
// };
//
// /**
// * 设置 type checker
// *
// * @param {Function} typeChecker 类型校验器
// */
// Data.prototype.setTypeChecker = function (typeChecker) {
// this.typeChecker = typeChecker;
// };
//
// #[end]
/**
* 添加数据变更的事件监听器
*
* @param {Function} listener 监听函数
*/
Data.prototype.listen = function (listener) {
if (typeof listener === 'function') {
this.listeners.push(listener);
}
};
/**
* 移除数据变更的事件监听器
*
* @param {Function} listener 监听函数
*/
Data.prototype.unlisten = function (listener) {
var len = this.listeners.length;
while (len--) {
if (!listener || this.listeners[len] === listener) {
this.listeners.splice(len, 1);
}
}
};
/**
* 触发数据变更
*
* @param {Object} change 变更信息对象
*/
Data.prototype.fire = function (change) {
each(this.listeners, function (listener) {
listener.call(this, change);
}, this);
};
/**
* 获取数据项
*
* @param {string|Object?} expr 数据项路径
* @return {*}
*/
Data.prototype.get = function (expr) {
var value = this.raw;
if (!expr) {
return value;
}
expr = parseExpr(expr);
var paths = expr.paths;
var start = 0;
var l = paths.length;
for (; start < l; start++) {
if (paths[start].value == null) {
break;
}
}
var i = 0;
for (; value != null && i < start; i++) {
value = value[paths[i].value];
}
if (value == null && this.parent) {
value = this.parent.get({
type: ExprType.ACCESSOR,
paths: paths.slice(0, start)
});
}
for (i = start; value != null && i < l; i++) {
value = value[evalExpr(paths[i], this)];
}
return value;
};
/**
* 数据对象变更操作
*
* @inner
* @param {Object|Array} source 要变更的源数据
* @param {Array} exprPaths 属性路径
* @param {*} value 变更属性值
* @param {Data} data 对应的Data对象
* @return {*} 变更后的新数据
*/
function immutableSet(source, exprPaths, value, data) {
if (exprPaths.length === 0) {
return value;
}
var prop = evalExpr(exprPaths[0], data);
var result;
if (source instanceof Array) {
var index = +prop;
result = source.slice(0);
result[isNaN(index) ? prop : index] = immutableSet(source[index], exprPaths.slice(1), value, data);
return result;
}
else if (typeof source === 'object') {
result = {};
for (var key in source) {
if (key !== prop) {
result[key] = source[key];
}
}
result[prop] = immutableSet(source[prop] || {}, exprPaths.slice(1), value, data);
return result;
}
return source;
}
/**
* 设置数据项
*
* @param {string|Object} expr 数据项路径
* @param {*} value 数据值
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
*/
Data.prototype.set = function (expr, value, option) {
option = option || {};
// #[begin] error
// var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
// if (expr.type !== ExprType.ACCESSOR) {
// throw new Error('[SAN ERROR] Invalid Expression in Data set: ' + exprRaw);
// }
// #[end]
if (this.get(expr) === value) {
return;
}
this.raw = immutableSet(this.raw, expr.paths, value, this);
!option.silence && this.fire({
type: DataChangeType.SET,
expr: expr,
value: value,
option: option
});
// #[begin] error
// this.checkDataTypes();
// #[end]
};
Data.prototype.splice = function (expr, args, option) {
option = option || {};
// #[begin] error
// var exprRaw = expr;
// #[end]
expr = parseExpr(expr);
// #[begin] error
// if (expr.type !== ExprType.ACCESSOR) {
// throw new Error('[SAN ERROR] Invalid Expression in Data splice: ' + exprRaw);
// }
// #[end]
var target = this.get(expr);
var returnValue = [];
if (target instanceof Array) {
var index = args[0];
if (index < 0 || index > target.length) {
return;
}
var newArray = target.slice(0);
returnValue = newArray.splice.apply(newArray, args);
this.raw = immutableSet(this.raw, expr.paths, newArray, this);
!option.silence && this.fire({
expr: expr,
type: DataChangeType.SPLICE,
index: index,
deleteCount: returnValue.length,
value: returnValue,
insertions: args.slice(2),
option: option
});
}
// #[begin] error
// this.checkDataTypes();
// #[end]
return returnValue;
};
/**
* 数组数据项push操作
*
* @param {string|Object} expr 数据项路径
* @param {*} item 要push的值
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
* @return {number} 新数组的length属性
*/
Data.prototype.push = function (expr, item, option) {
var target = this.get(expr);
if (target instanceof Array) {
this.splice(expr, [target.length, 0, item], option);
return target.length + 1;
}
};
/**
* 数组数据项pop操作
*
* @param {string|Object} expr 数据项路径
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
* @return {*}
*/
Data.prototype.pop = function (expr, option) {
var target = this.get(expr);
if (target instanceof Array) {
var len = target.length;
if (len) {
return this.splice(expr, [len - 1, 1], option)[0];
}
}
};
/**
* 数组数据项shift操作
*
* @param {string|Object} expr 数据项路径
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
* @return {*}
*/
Data.prototype.shift = function (expr, option) {
return this.splice(expr, [0, 1], option)[0];
};
/**
* 数组数据项unshift操作
*
* @param {string|Object} expr 数据项路径
* @param {*} item 要unshift的值
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
* @return {number} 新数组的length属性
*/
Data.prototype.unshift = function (expr, item, option) {
var target = this.get(expr);
if (target instanceof Array) {
this.splice(expr, [0, 0, item], option);
return target.length + 1;
}
};
/**
* 数组数据项移除操作
*
* @param {string|Object} expr 数据项路径
* @param {number} index 要移除项的索引
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
*/
Data.prototype.removeAt = function (expr, index, option) {
this.splice(expr, [index, 1], option);
};
/**
* 数组数据项移除操作
*
* @param {string|Object} expr 数据项路径
* @param {*} value 要移除的项
* @param {Object=} option 设置参数
* @param {boolean} option.silence 静默设置,不触发变更事件
*/
Data.prototype.remove = function (expr, value, option) {
var target = this.get(expr);
if (target instanceof Array) {
var len = target.length;
while (len--) {
if (target[len] === value) {
this.splice(expr, [len, 1], option);
break;
}
}
}
};
// exports = module.exports = Data;
/**
* @file 生命周期类
* @author errorrik(errorrik@gmail.com)
*/
function lifeCycleOwnIs(name) {
return this[name];
}
/* eslint-disable fecs-valid-var-jsdoc */
/**
* 节点生命周期信息
*
* @inner
* @type {Object}
*/
var LifeCycle = {
start: {},
compiled: {
is: lifeCycleOwnIs,
compiled: true
},
inited: {
is: lifeCycleOwnIs,
compiled: true,
inited: true
},
painting: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
painting: true
},
created: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true
},
attached: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
attached: true
},
leaving: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
attached: true,
leaving: true
},
detached: {
is: lifeCycleOwnIs,
compiled: true,
inited: true,
created: true,
detached: true
},
disposed: {
is: lifeCycleOwnIs,
disposed: true
}
};
/* eslint-enable fecs-valid-var-jsdoc */
// exports = module.exports = LifeCycle;
/**
* @file 字符串连接时是否使用老式的兼容方案
* @author errorrik(errorrik@gmail.com)
*/
// var ie = require('./ie');
/**
* 字符串连接时是否使用老式的兼容方案
*
* @inner
* @type {boolean}
*/
var isCompatStrJoin = ie && ie < 8;
// exports = module.exports = isCompatStrJoin;
/**
* @file 往字符串连接对象中添加字符串
* @author errorrik(errorrik@gmail.com)
*/
// var isCompatStrJoin = require('../browser/is-compat-str-join');
/**
* 往字符串连接对象中添加字符串
*
* @param {Object} buf 字符串连接对象
* @param {string} str 要添加的字符串
*/
var pushStrBuffer = isCompatStrJoin
? function (buf, str) {
buf.raw[buf.length++] = str;
}
: function (buf, str) {
buf.raw += str;
};
// exports = module.exports = pushStrBuffer;
/**
* @file 创建桩的html
* @author errorrik(errorrik@gmail.com)
*/
// var pushStrBuffer = require('../runtime/push-str-buffer');
/**
* 创建桩的html
*
* @param {Node} node 节点对象
* @param {Object} buf html串存储对象
*/
function genStumpHTML(node, buf) {
pushStrBuffer(buf, '<!--san:' + node.id + '-->');
}
// exports = module.exports = genStumpHTML;
/**
* @file 在 DOM 之前插入 HTML
* @author errorrik(errorrik@gmail.com)
*/
/**
* 在 DOM 之前插入 HTML
*
* @param {string} html 要插入的html
* @param {HTMLElement} parentEl 父元素
* @param {HTMLElement?} beforeEl 在此元素之前插入
*/
function insertHTMLBefore(html, parentEl, beforeEl) {
if (!beforeEl) {
parentEl.insertAdjacentHTML('beforeend', html);
}
else if (beforeEl.nodeType !== 1) {
var tempFlag = document.createElement('script');
parentEl.insertBefore(tempFlag, beforeEl);
tempFlag.insertAdjacentHTML('beforebegin', html);
parentEl.removeChild(tempFlag);
}
else {
beforeEl.insertAdjacentHTML('beforebegin', html);
}
}
// exports = module.exports = insertHTMLBefore;
/**
* @file 初始化节点
* @author errorrik(errorrik@gmail.com)
*/
// var guid = require('../util/guid');
// var isComponent = require('./is-component');
/**
* 初始化节点
*
* @param {Object} options 初始化参数
* @param {ANode} options.aNode 抽象信息节点对象
* @param {Component=} options.owner 所属的组件对象
* @param {Object?} node 节点对象,允许为空。空时将options作为节点对象,避免重复创建
* @return {Object}
*/
function nodeInit(options, node) {
node = node || options || {};
if (node !== options) {
node.owner = options.owner;
node.parent = options.parent;
node.scope = options.scope;
node.aNode = node.aNode || options.aNode;
node.el = options.el;
}
node.parentComponent = isComponent(options.parent)
? options.parent
: options.parent && options.parent.parentComponent,
node.id = (options.el && options.el.id)
|| (options.aNode && options.aNode.id)
|| guid();
return node;
}
// exports = module.exports = nodeInit;
/**
* @file 获取节点 stump 的 comment
* @author errorrik(errorrik@gmail.com)
*/
// #[begin] error
// /**
// * 获取节点 stump 的 comment
// *
// * @param {HTMLElement} el HTML元素
// */
// function warnSetHTML(el) {
// // dont warn if not in browser runtime
// if (!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document)) {
// return;
// }
//
// // some html elements cannot set innerHTML in old ie
// // see: https://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
// if (/^(col|colgroup|frameset|style|table|tbody|tfoot|thead|tr|select)$/i.test(el.tagName)) {
// var message = '[SAN WARNING] set html for element "' + el.tagName
// + '" may cause an error in old IE';
// /* eslint-disable no-console */
// if (typeof console === 'object' && console.warn) {
// console.warn(message);
// }
// else {
// throw new Error(message);
// }
// /* eslint-enable no-console */
// }
// }
// #[end]
// exports = module.exports = warnSetHTML;
/**
* @file 判断是否结束桩
* @author errorrik(errorrik@gmail.com)
*/
// #[begin] reverse
/**
* 判断是否结束桩
*
* @param {HTMLElement|HTMLComment} target 要判断的元素
* @param {string} type 桩类型
* @return {boolean}
*/
function isEndStump(target, type) {
return target.nodeType === 8 && target.data === '/s-' + type;
}
// #[end]
// exports = module.exports = isEndStump;
/**
* @file 创建 text 节点
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var removeEl = require('../browser/remove-el');
// var insertHTMLBefore = require('../browser/insert-html-before');
// var createANode = require('../parser/create-a-node');
// var ExprType = require('../parser/expr-type');
// var pushStrBuffer = require('../runtime/push-str-buffer');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var nodeInit = require('./node-init');
// var NodeType = require('./node-type');
// var nodeEvalExpr = require('./node-eval-expr');
// var warnSetHTML = require('./warn-set-html');
// var isEndStump = require('./is-end-stump');
/**
* 创建 text 节点
*
* @param {Object} options 初始化参数
* @param {ANode} options.aNode 抽象信息节点对象
* @param {Component=} options.owner 所属的组件对象
* @return {Object}
*/
function createText(options) {
var node = nodeInit(options);
node.nodeType = NodeType.TEXT;
node.attach = textOwnAttach;
node.dispose = textOwnDispose;
node._attachHTML = textOwnAttachHTML;
node._update = textOwnUpdate;
// #[begin] reverse
// from el
if (node.el) {
node.aNode = createANode({
isText: 1,
text: options.stumpText
});
node.parent._pushChildANode(node.aNode);
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
var next = options.elWalker.next;
if (isEndStump(next, 'text')) {
options.elWalker.goNext();
removeEl(next);
break;
}
options.elWalker.goNext();
}
removeEl(node.el);
node.el = null;
}
// #[end]
node._static = node.aNode.textExpr.value;
// 两种 update 模式
// 1. 单纯的 text node
// 2. 可能是复杂的 html 结构
node.updateMode = 1;
each(node.aNode.textExpr.segs, function (seg) {
if (seg.type === ExprType.INTERP) {
each(seg.filters, function (filter) {
switch (filter.name) {
case 'html':
case 'url':
return;
}
node.updateMode = 2;
return false;
});
}
return node.updateMode < 2;
});
return node;
}
/**
* 销毁 text 节点
*/
function textOwnDispose() {
this._prev = null;
this.el = null;
this.content = null;
}
/**
* attach text 节点的 html
*
* @param {Object} buf html串存储对象
*/
function textOwnAttachHTML(buf) {
this.content = nodeEvalExpr(this, this.aNode.textExpr, 1);
pushStrBuffer(buf, this.content);
}
/**
* 定位text节点在父元素中的位置
*
* @param {Object} node text节点元素
*/
function textLocatePrevNode(node) {
if (!node._located) {
var parentChildren = node.parent.children;
var len = parentChildren.length;
while (len--) {
if (node === parentChildren[len]) {
node._prev = parentChildren[len - 1];
}
}
node._located = 1;
}
}
/**
* 将text attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function textOwnAttach(parentEl, beforeEl) {
this.content = nodeEvalExpr(this, this.aNode.textExpr, 1);
insertHTMLBefore(this.content, parentEl, beforeEl);
}
/* eslint-disable max-depth */
/**
* 更新 text 节点的视图
*
* @param {Array} changes 数据变化信息
*/
function textOwnUpdate(changes) {
var me = this;
var len = changes ? changes.length : 0;
while (len--) {
if (changeExprCompare(changes[len].expr, this.aNode.textExpr, this.scope)) {
var text = nodeEvalExpr(this, this.aNode.textExpr, 1);
if (text !== this.content) {
this.content = text;
// 无 stump 元素,所以需要根据组件结构定位
textLocatePrevNode(me);
var parentEl = this.parent._getEl();
if (me.updateMode === 1) {
if (me.el) {
me.el[typeof me.el.textContent === 'string' ? 'textContent' : 'data'] = text;
}
else {
var el = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
if (el) {
switch (el.nodeType) {
case 3:
me.el = el;
me.el[typeof me.el.textContent === 'string' ? 'textContent' : 'data'] = text;
break;
case 1:
el.insertAdjacentHTML('beforebegin', text);
break;
default:
me.el = document.createTextNode(text);
parentEl.insertBefore(me.el, el);
}
}
else {
parentEl.insertAdjacentHTML('beforeend', text);
}
}
}
else {
var insertBeforeEl = me._prev && me._prev._getEl().nextSibling || parentEl.firstChild;
var startRemoveEl = insertBeforeEl;
while (startRemoveEl && !/^_san_/.test(startRemoveEl.id)) {
insertBeforeEl = startRemoveEl.nextSibling;
removeEl(startRemoveEl);
startRemoveEl = insertBeforeEl;
}
// #[begin] error
// warnSetHTML(parentEl);
// #[end]
insertHTMLBefore(text, parentEl, insertBeforeEl);
}
}
return;
}
}
}
/* eslint-enable max-depth */
// exports = module.exports = createText;
/**
* @file 判断变更是否来源于元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 判断变更是否来源于元素,来源于元素时,视图更新需要阻断
*
* @param {Object} change 变更对象
* @param {Element} element 元素
* @param {string?} propName 属性名,可选。需要精确判断是否来源于此属性时传入
* @return {boolean}
*/
function isDataChangeByElement(change, element, propName) {
var changeTarget = change.option.target;
return changeTarget && changeTarget.id === element.id
&& (!propName || changeTarget.prop === propName);
}
// exports = module.exports = isDataChangeByElement;
/**
* @file 声明式事件的监听函数
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var evalExpr = require('../runtime/eval-expr');
// var ExprType = require('../parser/expr-type');
/**
* 声明式事件的监听函数
*
* @param {Object} eventBind 绑定信息对象
* @param {boolean} isComponentEvent 是否组件自定义事件
* @param {Model} model 数据环境
* @param {Event} e 事件对象
*/
function eventDeclarationListener(eventBind, isComponentEvent, model, e) {
var args = [];
var expr = eventBind.expr;
each(expr.args, function (argExpr) {
args.push(argExpr.type === ExprType.ACCESSOR
&& argExpr.paths.length === 1
&& argExpr.paths[0].value === '$event'
? (isComponentEvent ? e : e || window.event)
: evalExpr(argExpr, model)
);
});
var method = this[expr.name];
if (typeof method === 'function') {
method.apply(this, args);
}
}
// exports = module.exports = eventDeclarationListener;
/**
* @file 生成元素标签起始的html
* @author errorrik(errorrik@gmail.com)
*/
// var evalExpr = require('../runtime/eval-expr');
// var pushStrBuffer = require('../runtime/push-str-buffer');
// var isComponent = require('./is-component');
// var getPropHandler = require('./get-prop-handler');
// var nodeEvalExpr = require('./node-eval-expr');
/**
* 生成元素标签起始的html
*
* @param {Element} element 元素
* @param {Object} buf html串存储对象
*/
function genElementStartHTML(element, buf) {
if (!element.tagName) {
return;
}
pushStrBuffer(buf, '<' + element.tagName + ' id="' + element.id + '"');
element.props.each(function (prop) {
var attr = prop.attr;
if (!attr) {
element.dynamicProps.push(prop);
var value = isComponent(element)
? evalExpr(prop.expr, element.data, element)
: nodeEvalExpr(element, prop.expr, 1);
attr = getPropHandler(element, prop.name).attr(element, prop.name, value);
}
pushStrBuffer(buf, attr || '');
});
pushStrBuffer(buf, '>');
}
// exports = module.exports = genElementStartHTML;
/**
* @file 生成元素标签结束的html
* @author errorrik(errorrik@gmail.com)
*/
// var autoCloseTags = require('../browser/auto-close-tags');
// var pushStrBuffer = require('../runtime/push-str-buffer');
/**
* 生成元素标签结束的html
*
* @inner
* @param {Element} element 元素
* @param {Object} buf html串存储对象
*/
function genElementEndHTML(element, buf) {
var tagName = element.tagName;
if (!autoCloseTags[tagName]) {
pushStrBuffer(buf, '</' + tagName + '>');
}
}
// exports = module.exports = genElementEndHTML;
/**
* @file attaching 的 element 和 component 池
完成 html fill 后执行 attached 操作,进行事件绑定等后续行为
* @author errorrik(errorrik@gmail.com)
*/
/**
* attaching 的 element 和 component 集合
*
* @inner
* @type {Array}
*/
var attachingNodes = [];
/**
* attaching 操作对象
*
* @type {Object}
*/
var attachings = {
/**
* 添加 attaching 的 element 或 component
*
* @param {Object|Component} node attaching的node
*/
add: function (node) {
attachingNodes.push(node);
},
/**
* 执行 attaching 完成行为
*/
done: function () {
var nodes = attachingNodes;
attachingNodes = [];
for (var i = 0, l = nodes.length; i < l; i++) {
nodes[i]._attached();
}
}
};
// exports = module.exports = attachings;
/**
* @file 解析元素自身的 ANode
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var createANode = require('./create-a-node');
// var integrateAttr = require('./integrate-attr');
// #[begin] reverse
/**
* 解析元素自身的 ANode
*
* @param {HTMLElement} el 页面元素
* @return {ANode}
*/
function parseANodeFromEl(el) {
var aNode = createANode();
aNode.tagName = el.tagName.toLowerCase();
each(
el.attributes,
function (attr) {
integrateAttr(aNode, attr.name, attr.value, 1);
}
);
return aNode;
}
// #[end]
// exports = module.exports = parseANodeFromEl;
/**
* @file 创建 element 节点
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var IndexedList = require('../util/indexed-list');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var attachings = require('./attachings');
// var parseANodeFromEl = require('../parser/parse-anode-from-el');
// var fromElInitChildren = require('./from-el-init-children');
// var isDataChangeByElement = require('./is-data-change-by-element');
// var nodeInit = require('./node-init');
// var nodeEvalExpr = require('./node-eval-expr');
// var elementUpdateChildren = require('./element-update-children');
// var elementOwnAttachHTML = require('./element-own-attach-html');
// var elementOwnCreate = require('./element-own-create');
// var elementOwnAttach = require('./element-own-attach');
// var elementOwnDetach = require('./element-own-detach');
// var elementOwnDispose = require('./element-own-dispose');
// var elementOwnGetEl = require('./element-own-get-el');
// var elementOwnOnEl = require('./element-own-on-el');
// var elementOwnToPhase = require('./element-own-to-phase');
// var elementAttached = require('./element-attached');
// var elementSetElProp = require('./element-set-el-prop');
// var elementInitProps = require('./element-init-props');
// var elementInitTagName = require('./element-init-tag-name');
// var elementOwnPushChildANode = require('./element-own-push-child-anode');
// var warnSetHTML = require('./warn-set-html');
/**
* 创建 element 节点
*
* @param {Object} options 初始化参数
* @param {ANode} options.aNode 抽象信息节点对象
* @param {Component=} options.owner 所属的组件对象
* @return {Object}
*/
function createElement(options) {
var node = nodeInit(options);
// init methods
node.attach = elementOwnAttach;
node.detach = elementOwnDetach;
node.dispose = elementOwnDispose;
node._attachHTML = elementOwnAttachHTML;
node._update = elementOwnUpdate;
node._create = elementOwnCreate;
node._attached = elementOwnAttached;
node._getEl = elementOwnGetEl;
node._toPhase = elementOwnToPhase;
node._onEl = elementOwnOnEl;
elementInitProps(node);
// #[begin] reverse
node._pushChildANode = elementOwnPushChildANode;
if (node.el) {
node.aNode = parseANodeFromEl(node.el);
node.parent && node.parent._pushChildANode(node.aNode);
node.tagName = node.aNode.tagName;
if (!node.aNode.directives.get('html')) {
fromElInitChildren(node);
}
node.el.id = node.id;
node.dynamicProps = new IndexedList();
node.aNode.props.each(function (prop) {
if (!prop.attr) {
node.dynamicProps.push(prop);
}
});
attachings.add(node);
}
// #[end]
elementInitTagName(node);
node.props = node.aNode.props;
node.binds = node.aNode.binds || node.aNode.props;
node._toPhase('inited');
return node;
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
function elementOwnUpdate(changes) {
this._getEl();
var me = this;
this.dynamicProps.each(function (prop) {
if (prop.expr.value) {
return;
}
each(changes, function (change) {
if (!isDataChangeByElement(change, me, prop.name)
&& (
changeExprCompare(change.expr, prop.expr, me.scope)
|| prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, me.scope)
)
) {
elementSetElProp(me, prop.name, nodeEvalExpr(me, prop.expr));
return false;
}
});
});
var htmlDirective = this.aNode.directives.get('html');
if (htmlDirective) {
each(changes, function (change) {
if (changeExprCompare(change.expr, htmlDirective.value, me.scope)) {
// #[begin] error
// warnSetHTML(me.el);
// #[end]
me.el.innerHTML = nodeEvalExpr(me, htmlDirective.value);
return false;
}
});
}
else {
elementUpdateChildren(this, changes);
}
}
/**
* 执行完成attached状态的行为
*/
function elementOwnAttached() {
elementAttached(this);
}
// exports = module.exports = createElement;
/**
* @file 创建节点的工厂方法
* @author errorrik(errorrik@gmail.com)
*/
// var isComponent = require('./is-component');
// var createText = require('./create-text');
// var createElement = require('./create-element');
// var createSlot = require('./create-slot');
// var createFor = require('./create-for');
// var createIf = require('./create-if');
// var createTemplate = require('./create-template');
/**
* 创建节点
*
* @param {ANode} aNode 抽象节点
* @param {Node} parent 父亲节点
* @param {Model=} scope 所属数据环境
* @return {Node}
*/
function createNode(aNode, parent, scope) {
var owner = isComponent(parent) ? parent : parent.owner;
scope = scope || (isComponent(parent) ? parent.data : parent.scope);
var options = {
aNode: aNode,
owner: owner,
scope: scope,
parent: parent
};
if (aNode.isText) {
return createText(options);
}
if (aNode.directives.get('if')) {
return createIf(options);
}
if (aNode.directives.get('for')) {
return createFor(options);
}
var ComponentType = owner.components[aNode.tagName];
if (ComponentType) {
options.subTag = aNode.tagName;
return new ComponentType(options);
}
switch (aNode.tagName) {
case 'slot':
return createSlot(options);
case 'template':
return createTemplate(options);
}
return createElement(options);
}
// exports = module.exports = createNode;
/**
* @file 通过存在的 el 创建节点的工厂方法
* @author errorrik(errorrik@gmail.com)
*/
// var parseANodeFromEl = require('../parser/parse-anode-from-el');
// var isComponent = require('./is-component');
// var createText = require('./create-text');
// var createElement = require('./create-element');
// var createIf = require('./create-if');
// var createFor = require('./create-for');
// var createSlot = require('./create-slot');
// var createTemplate = require('./create-template');
// #[begin] reverse
/**
* 通过存在的 el 创建节点
*
* @param {HTMLElement} el 页面中存在的元素
* @param {Node} parent 父亲节点
* @param {DOMChildrenWalker} elWalker 遍历元素的功能对象
* @param {Model=} scope 所属数据环境
* @return {Node}
*/
function createNodeByEl(el, parent, elWalker, scope) {
var owner = isComponent(parent) ? parent : parent.owner;
scope = scope || (isComponent(parent) ? parent.data : parent.scope);
var option = {
owner: owner,
scope: scope,
parent: parent,
el: el,
elWalker: elWalker
};
// comment as stump
if (el.nodeType === 8) {
var stumpMatch = el.data.match(/^\s*s-([a-z]+)(:[\s\S]+)?$/);
if (stumpMatch) {
option.stumpType = stumpMatch[1];
option.stumpText = stumpMatch[2] ? stumpMatch[2].slice(1) : '';
switch (option.stumpType) {
case 'text':
return createText(option);
case 'for':
return createFor(option);
case 'slot':
return createSlot(option);
case 'if':
return createIf(option);
case 'tpl':
return createTemplate(option);
case 'data':
// fill component data
var data = (new Function(
'return ' + option.stumpText.replace(/^[\s\n]*/, '')
))();
/* eslint-disable guard-for-in */
for (var key in data) {
owner.data.set(key, data[key]);
}
/* eslint-enable guard-for-in */
return;
}
}
return;
}
// element as anything
var tagName = el.tagName.toLowerCase();
var childANode = parseANodeFromEl(el);
option.aNode = childANode;
// find component class
var ComponentClass = null;
if (tagName.indexOf('-') > 0) {
ComponentClass = owner.components[tagName];
}
var componentName = el.getAttribute('s-component');
if (componentName) {
ComponentClass = owner.components[componentName];
childANode.tagName = componentName;
}
// as Component
if (ComponentClass) {
return new ComponentClass(option);
}
// as Element
return createElement(option);
}
// #[end]
// exports = module.exports = createNodeByEl;
/**
* @file 获取节点 stump 的父元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 获取节点 stump 的父元素
* if、for 节点的 el stump 是 comment node,在 IE 下还可能不存在
* 获取其父元素通常用于 el 的查找,以及视图变更的插入操作
*
* @param {Node} node 节点对象
* @return {HTMLElement}
*/
function getNodeStumpParent(node) {
if (node.el) {
return node.el.parentNode;
}
var parentNode = node.parent._getEl();
while (parentNode && parentNode.nodeType !== 1) {
parentNode = parentNode.parentNode;
}
return parentNode;
}
// exports = module.exports = getNodeStumpParent;
/**
* @file 更新元素的子元素视图
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
/**
* 更新元素的子元素视图
*
* @param {Object} element 要更新的元素
* @param {Array} changes 数据变化信息
*/
function elementUpdateChildren(element, changes) {
each(element.children, function (child) {
child._update(changes);
});
}
// exports = module.exports = elementUpdateChildren;
/**
* @file 销毁节点,清空节点上的无用成员
* @author errorrik(errorrik@gmail.com)
*/
/**
* 销毁节点
*
* @param {Object} node 节点对象
*/
function nodeDispose(node) {
node.el = null;
node.owner = null;
node.scope = null;
node.aNode = null;
node.parent = null;
node.parentComponent = null;
node.children = null;
if (node._toPhase) {
node._toPhase('disposed');
}
if (node._ondisposed) {
node._ondisposed();
}
}
// exports = module.exports = nodeDispose;
/**
* @file 销毁释放元素的子元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 销毁释放元素的子元素
*
* @param {Object} element 元素节点
* @param {Object} options 销毁节点的参数
*/
function elementDisposeChildren(element, options) {
var children = element.children;
if (children instanceof Array) {
var len = children.length;
while (len--) {
children[len].dispose(options);
}
children.length = 0;
}
}
// exports = module.exports = elementDisposeChildren;
/**
* @file 简单执行销毁节点的行为
* @author errorrik(errorrik@gmail.com)
*/
// var removeEl = require('../browser/remove-el');
// var nodeDispose = require('./node-dispose');
// var elementDisposeChildren = require('./element-dispose-children');
/**
* 简单执行销毁节点的行为
*
* @param {Object=} options dispose行为参数
*/
function nodeOwnSimpleDispose(options) {
elementDisposeChildren(this, options);
if (!options || !options.dontDetach) {
removeEl(this._getEl());
}
nodeDispose(this);
}
// exports = module.exports = nodeOwnSimpleDispose;
/**
* @file 获取节点 stump 的 comment
* @author errorrik(errorrik@gmail.com)
*/
// var getNodeStumpParent = require('./get-node-stump-parent');
/**
* 获取节点 stump 的 comment
*
* @param {Node} node 节点对象
* @return {Comment}
*/
function getNodeStump(node) {
if (typeof node.el === 'undefined') {
var parentNode = getNodeStumpParent(node);
var el = parentNode.firstChild;
while (el) {
if (el.nodeType === 8
&& el.data.indexOf('san:') === 0
&& el.data.replace('san:', '') === node.id
) {
break;
}
el = el.nextSibling;
}
node.el = el;
}
return node.el;
}
// exports = module.exports = getNodeStump;
/**
* @file 获取节点对应的 stump 主元素
* @author errorrik(errorrik@gmail.com)
*/
// var getNodeStump = require('./get-node-stump');
/**
* 获取节点对应的 stump 主元素
*
* @return {Comment}
*/
function nodeOwnGetStumpEl() {
return getNodeStump(this);
}
// exports = module.exports = nodeOwnGetStumpEl;
/**
* @file 创建 if 指令元素
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var empty = require('../util/empty');
// var IndexedList = require('../util/indexed-list');
// var parseTemplate = require('../parser/parse-template');
// var createANode = require('../parser/create-a-node');
// var removeEl = require('../browser/remove-el');
// var genStumpHTML = require('./gen-stump-html');
// var isEndStump = require('./is-end-stump');
// var nodeInit = require('./node-init');
// var NodeType = require('./node-type');
// var nodeEvalExpr = require('./node-eval-expr');
// var createNode = require('./create-node');
// var createNodeByEl = require('./create-node-by-el');
// var getNodeStumpParent = require('./get-node-stump-parent');
// var elementUpdateChildren = require('./element-update-children');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
// var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
/**
* 创建 if 指令元素
*
* @param {Object} options 初始化参数
* @return {Object}
*/
function createIf(options) {
var node = nodeInit(options);
node.children = [];
node.nodeType = NodeType.IF;
node.dispose = nodeOwnSimpleDispose;
node._getEl = nodeOwnGetStumpEl;
node._attachHTML = ifOwnAttachHTML;
node._update = ifOwnUpdate;
// #[begin] reverse
node._pushChildANode = empty;
// #[end]
// #[begin] reverse
if (options.el) {
var aNode = parseTemplate(options.stumpText).children[0];
node.aNode = aNode;
var next = options.elWalker.next;
if (next.nodeType === 8 && !isEndStump(next, 'if')) {
node.elseIndex = +next.data;
options.elWalker.goNext();
removeEl(next);
}
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
next = options.elWalker.next;
if (isEndStump(next, 'if')) {
options.elWalker.goNext();
removeEl(options.el);
node.el = next;
break;
}
options.elWalker.goNext();
var child = createNodeByEl(next, node, options.elWalker);
node.children[0] = child;
}
node.parent._pushChildANode(node.aNode);
}
// #[end]
node.cond = node.aNode.directives.get('if').value;
return node;
}
/**
* 创建 if 指令对应条件为 true 时对应的元素
*
* @inner
* @param {ANode} directiveANode 指令ANode
* @param {IfDirective} mainIf 主if元素
* @return {Element}
*/
function createIfDirectiveChild(directiveANode, mainIf) {
var childANode = createANode({
children: directiveANode.children,
props: directiveANode.props,
events: directiveANode.events,
tagName: directiveANode.tagName,
vars: directiveANode.vars,
directives: (new IndexedList()).concat(directiveANode.directives)
});
childANode.directives.remove('if');
childANode.directives.remove('else');
childANode.directives.remove('elif');
return createNode(childANode, mainIf);
}
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
*/
function ifOwnAttachHTML(buf) {
var me = this;
var elseIndex;
var child;
if (nodeEvalExpr(me, me.cond)) {
child = createIfDirectiveChild(me.aNode, me);
elseIndex = -1;
}
else {
each(me.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.get('elif');
if (!elif || elif && nodeEvalExpr(me, elif.value)) {
child = createIfDirectiveChild(elseANode, me);
elseIndex = index;
return false;
}
});
}
if (child) {
me.children[0] = child;
child._attachHTML(buf);
me.elseIndex = elseIndex;
}
genStumpHTML(this, buf);
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
function ifOwnUpdate(changes) {
var me = this;
var childANode = me.aNode;
var elseIndex;
if (nodeEvalExpr(this, this.cond)) {
elseIndex = -1;
}
else {
each(me.aNode.elses, function (elseANode, index) {
var elif = elseANode.directives.get('elif');
if (elif && nodeEvalExpr(me, elif.value) || !elif) {
elseIndex = index;
childANode = elseANode;
return false;
}
});
}
if (elseIndex === me.elseIndex) {
elementUpdateChildren(me, changes);
}
else {
var child = me.children[0];
me.children.length = 0;
if (child) {
child._ondisposed = newChild;
child.dispose();
}
else {
newChild();
}
me.elseIndex = elseIndex;
}
function newChild() {
if (typeof elseIndex !== 'undefined') {
var child = createIfDirectiveChild(childANode, me);
var parentEl = getNodeStumpParent(me);
child.attach(parentEl, me._getEl() || parentEl.firstChild);
me.children[0] = child;
}
}
}
// exports = module.exports = createIf;
/**
* @file 创建字符串连接对象,用于跨平台提高性能的字符串连接,万一不小心支持老式浏览器了呢
* @author errorrik(errorrik@gmail.com)
*/
// var isCompatStrJoin = require('../browser/is-compat-str-join');
/**
* 创建字符串连接对象
*
* @return {Object}
*/
function createStrBuffer() {
return {
raw: isCompatStrJoin ? [] : '',
length: 0
};
}
// exports = module.exports = createStrBuffer;
/**
* @file 字符串化字符串连接对象
* @author errorrik(errorrik@gmail.com)
*/
// var isCompatStrJoin = require('../browser/is-compat-str-join');
/**
* 字符串化字符串连接对象
*
* @param {Object} buf 字符串连接对象
* @return {string}
*/
var stringifyStrBuffer = isCompatStrJoin
? function (buf) {
return buf.raw.join('');
}
: function (buf) {
return buf.raw;
};
// exports = module.exports = stringifyStrBuffer;
/**
* @file 创建节点对应的 stump comment 元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 创建节点对应的 stump comment 主元素
*/
function nodeOwnCreateStump() {
this.el = this.el || document.createComment('san:' + this.id);
}
// exports = module.exports = nodeOwnCreateStump;
/**
* @file 创建 for 指令元素
* @author errorrik(errorrik@gmail.com)
*/
// var empty = require('../util/empty');
// var extend = require('../util/extend');
// var inherits = require('../util/inherits');
// var each = require('../util/each');
// var IndexedList = require('../util/indexed-list');
// var parseTemplate = require('../parser/parse-template');
// var createANode = require('../parser/create-a-node');
// var ExprType = require('../parser/expr-type');
// var parseExpr = require('../parser/parse-expr');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var createStrBuffer = require('../runtime/create-str-buffer');
// var stringifyStrBuffer = require('../runtime/stringify-str-buffer');
// var removeEl = require('../browser/remove-el');
// var insertHTMLBefore = require('../browser/insert-html-before');
// var LifeCycle = require('./life-cycle');
// var attachings = require('./attachings');
// var genStumpHTML = require('./gen-stump-html');
// var nodeInit = require('./node-init');
// var NodeType = require('./node-type');
// var nodeEvalExpr = require('./node-eval-expr');
// var createNode = require('./create-node');
// var createNodeByEl = require('./create-node-by-el');
// var isEndStump = require('./is-end-stump');
// var getNodeStumpParent = require('./get-node-stump-parent');
// var nodeOwnSimpleDispose = require('./node-own-simple-dispose');
// var nodeOwnCreateStump = require('./node-own-create-stump');
// var nodeOwnGetStumpEl = require('./node-own-get-stump-el');
// var elementDisposeChildren = require('./element-dispose-children');
// var warnSetHTML = require('./warn-set-html');
/**
* 循环项的数据容器类
*
* @inner
* @class
* @param {Object} forElement for元素对象
* @param {*} item 当前项的数据
* @param {number} index 当前项的索引
*/
function ForItemData(forElement, item, index) {
this.parent = forElement.scope;
this.raw = {};
this.listeners = [];
this.directive = forElement.aNode.directives.get('for');
this.raw[this.directive.item.raw] = item;
this.raw[this.directive.index.raw] = index;
}
/**
* 将数据操作的表达式,转换成为对parent数据操作的表达式
* 主要是对item和index进行处理
*
* @param {Object} expr 表达式
* @return {Object}
*/
ForItemData.prototype.exprResolve = function (expr) {
var directive = this.directive;
var me = this;
function resolveItem(expr) {
if (expr.type === ExprType.ACCESSOR
&& expr.paths[0].value === directive.item.paths[0].value
) {
return {
type: ExprType.ACCESSOR,
paths: directive.list.paths.concat(
{
type: ExprType.NUMBER,
value: me.get(directive.index)
},
expr.paths.slice(1)
)
};
}
return expr;
}
expr = resolveItem(expr);
var resolvedPaths = [];
each(expr.paths, function (item) {
resolvedPaths.push(
item.type === ExprType.ACCESSOR
&& item.paths[0].value === directive.index.paths[0].value
? {
type: ExprType.NUMBER,
value: me.get(directive.index)
}
: resolveItem(item)
);
});
return {
type: ExprType.ACCESSOR,
paths: resolvedPaths
};
};
// 代理数据操作方法
inherits(ForItemData, Data);
each(
['set', 'remove', 'unshift', 'shift', 'push', 'pop', 'splice'],
function (method) {
ForItemData.prototype[method] = function (expr) {
expr = this.exprResolve(parseExpr(expr));
this.parent[method].apply(
this.parent,
[expr].concat(Array.prototype.slice.call(arguments, 1))
);
};
}
);
/**
* 创建 for 指令元素的子元素
*
* @inner
* @param {ForDirective} forElement for 指令元素对象
* @param {*} item 子元素对应数据
* @param {number} index 子元素对应序号
* @return {Element}
*/
function createForDirectiveChild(forElement, item, index) {
var itemScope = new ForItemData(forElement, item, index);
return createNode(forElement.itemANode, forElement, itemScope);
}
/**
* 创建 for 指令元素
*
* @param {Object} options 初始化参数
* @return {Object}
*/
function createFor(options) {
var node = nodeInit(options);
node.children = [];
node.nodeType = NodeType.FOR;
node.attach = forOwnAttach;
node.detach = forOwnDetach;
node.dispose = nodeOwnSimpleDispose;
node._attachHTML = forOwnAttachHTML;
node._update = forOwnUpdate;
node._create = nodeOwnCreateStump;
node._getEl = nodeOwnGetStumpEl;
// #[begin] reverse
node._pushChildANode = empty;
// #[end]
var aNode = node.aNode;
// #[begin] reverse
if (options.el) {
aNode = parseTemplate(options.stumpText).children[0];
node.aNode = aNode;
var index = 0;
var directive = aNode.directives.get('for');
var listData = nodeEvalExpr(node, directive.list) || [];
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
var next = options.elWalker.next;
if (isEndStump(next, 'for')) {
options.elWalker.goNext();
removeEl(options.el);
node.el = next;
break;
}
options.elWalker.goNext();
var itemScope = new ForItemData(node, listData[index], index);
var child = createNodeByEl(next, node, options.elWalker, itemScope);
node.children.push(child);
index++;
}
node.parent._pushChildANode(node.aNode);
}
// #[end]
node.itemANode = createANode({
children: aNode.children,
props: aNode.props,
events: aNode.events,
tagName: aNode.tagName,
vars: aNode.vars,
directives: (new IndexedList()).concat(aNode.directives)
});
node.itemANode.directives.remove('for');
return node;
}
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
* @param {boolean} onlyChildren 是否只attach列表本身html,不包括stump部分
*/
function forOwnAttachHTML(buf, onlyChildren) {
var me = this;
each(
nodeEvalExpr(me, me.aNode.directives.get('for').list),
function (item, i) {
var child = createForDirectiveChild(me, item, i);
me.children.push(child);
child._attachHTML(buf);
}
);
if (!onlyChildren) {
genStumpHTML(me, buf);
}
}
/**
* 将元素attach到页面的行为
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function forOwnAttach(parentEl, beforeEl) {
this._create();
if (parentEl) {
if (beforeEl) {
parentEl.insertBefore(this.el, beforeEl);
}
else {
parentEl.appendChild(this.el);
}
}
// paint list
var el = this.el || parentEl.firstChild;
var prevEl = el && el.previousSibling;
var buf = createStrBuffer();
prev: while (prevEl) {
var nextPrev = prevEl.previousSibling;
switch (prevEl.nodeType) {
case 1:
break prev;
case 3:
if (!/^\s*$/.test(prevEl.textContent)) {
break prev;
}
removeEl(prevEl);
break;
}
prevEl = nextPrev;
}
if (!prevEl) {
this._attachHTML(buf, 1);
// #[begin] error
// warnSetHTML(parentEl);
// #[end]
parentEl.insertAdjacentHTML('afterbegin', stringifyStrBuffer(buf));
}
else if (prevEl.nodeType === 1) {
this._attachHTML(buf, 1);
// #[begin] error
// warnSetHTML(parentEl);
// #[end]
prevEl.insertAdjacentHTML('afterend', stringifyStrBuffer(buf));
}
else {
each(
nodeEvalExpr(this, this.aNode.directives.get('for').list),
function (item, i) {
var child = createForDirectiveChild(this, item, i);
this.children.push(child);
child.attach(parentEl, el);
},
this
);
}
attachings.done();
}
/**
* 将元素从页面上移除的行为
*/
function forOwnDetach() {
if (this.lifeCycle.attached) {
elementDisposeChildren(this, true);
removeEl(this._getEl());
this.lifeCycle = LifeCycle.detached;
}
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
function forOwnUpdate(changes) {
var me = this;
var childrenChanges = [];
var oldChildrenLen = this.children.length;
each(this.children, function () {
childrenChanges.push([]);
});
var disposeChildren = [];
var forDirective = this.aNode.directives.get('for');
this._getEl();
var parentEl = getNodeStumpParent(this);
var parentFirstChild = parentEl.firstChild;
var parentLastChild = parentEl.lastChild;
var isOnlyParentChild = oldChildrenLen > 0 // 有孩子时
&& parentFirstChild === this.children[0]._getEl()
&& (parentLastChild === this.el || parentLastChild === this.children[oldChildrenLen - 1]._getEl())
|| oldChildrenLen === 0 // 无孩子时
&& parentFirstChild === this.el
&& parentLastChild === this.el;
var isChildrenRebuild;
each(changes, function (change) {
var relation = changeExprCompare(change.expr, forDirective.list, this.scope);
if (!relation) {
// 无关时,直接传递给子元素更新,列表本身不需要动
each(childrenChanges, function (childChanges) {
childChanges.push(change);
});
}
else if (relation > 2) {
// 变更表达式是list绑定表达式的子项
// 只需要对相应的子项进行更新
var changePaths = change.expr.paths;
var forLen = forDirective.list.paths.length;
var changeIndex = +nodeEvalExpr(this, changePaths[forLen]);
if (isNaN(changeIndex)) {
each(childrenChanges, function (childChanges) {
childChanges.push(change);
});
}
else {
change = extend({}, change);
change.expr = {
type: ExprType.ACCESSOR,
paths: forDirective.item.paths.concat(changePaths.slice(forLen + 1))
};
childrenChanges[changeIndex].push(change);
switch (change.type) {
case DataChangeType.SET:
Data.prototype.set.call(
this.children[changeIndex].scope,
change.expr,
change.value,
{silence: 1}
);
break;
case DataChangeType.SPLICE:
Data.prototype.splice.call(
this.children[changeIndex].scope,
change.expr,
[].concat(change.index, change.deleteCount, change.insertions),
{silence: 1}
);
break;
}
}
}
else if (change.type === DataChangeType.SET) {
// 变更表达式是list绑定表达式本身或母项的重新设值
// 此时需要更新整个列表
var newList = nodeEvalExpr(this, forDirective.list);
var newLen = newList && newList.length || 0;
// 老的比新的多的部分,标记需要dispose
if (oldChildrenLen > newLen) {
disposeChildren = disposeChildren.concat(this.children.slice(newLen));
childrenChanges.length = newLen;
this.children.length = newLen;
}
// 整项变更
for (var i = 0; i < newLen; i++) {
childrenChanges[i] = childrenChanges[i] || [];
childrenChanges[i].push({
type: DataChangeType.SET,
option: change.option,
expr: {
type: ExprType.ACCESSOR,
paths: forDirective.item.paths.slice(0)
},
value: newList[i]
});
// 对list更上级数据的直接设置
if (relation < 2) {
childrenChanges[i].push(change);
}
if (this.children[i]) {
Data.prototype.set.call(
this.children[i].scope,
forDirective.item,
newList[i],
{silence: 1}
);
}
else {
this.children[i] = createForDirectiveChild(this, newList[i], i);
}
}
isChildrenRebuild = 1;
}
else if (relation === 2 && change.type === DataChangeType.SPLICE && !isChildrenRebuild) {
// 变更表达式是list绑定表达式本身数组的SPLICE操作
// 此时需要删除部分项,创建部分项
var changeStart = change.index;
var deleteCount = change.deleteCount;
var indexChange = {
type: DataChangeType.SET,
option: change.option,
expr: forDirective.index
};
var insertionsLen = change.insertions.length;
if (insertionsLen !== deleteCount) {
each(this.children, function (child, index) {
// update child index
if (index >= changeStart + deleteCount) {
childrenChanges[index].push(indexChange);
Data.prototype.set.call(
child.scope,
indexChange.expr,
index - deleteCount + insertionsLen,
{silence: 1}
);
}
}, this);
}
var spliceArgs = [changeStart, deleteCount];
var childrenChangesSpliceArgs = [changeStart, deleteCount];
each(change.insertions, function (insertion, index) {
spliceArgs.push(createForDirectiveChild(this, insertion, changeStart + index));
childrenChangesSpliceArgs.push([]);
}, this);
disposeChildren = disposeChildren.concat(this.children.splice.apply(this.children, spliceArgs));
childrenChanges.splice.apply(childrenChanges, childrenChangesSpliceArgs);
}
}, this);
var newChildrenLen = this.children.length;
// 标记 length 是否发生变化
if (newChildrenLen !== oldChildrenLen) {
var lengthChange = {
type: DataChangeType.SET,
option: {},
expr: {
type: ExprType.ACCESSOR,
paths: forDirective.list.paths.concat({
type: ExprType.STRING,
value: 'length'
})
}
};
each(childrenChanges, function (childChanges) {
childChanges.push(lengthChange);
});
}
// 清除应该干掉的 child
var violentClear = isOnlyParentChild && newChildrenLen === 0;
var disposeChildCount = disposeChildren.length;
var disposedChildCount = 0;
each(disposeChildren, function (child) {
child._ondisposed = childDisposed;
child.dispose({dontDetach: violentClear, noTransition: violentClear});
});
if (violentClear) {
parentEl.innerHTML = '';
this.el = document.createComment('san:' + this.id);
parentEl.appendChild(this.el);
}
if (disposeChildCount === 0) {
doCreateAndUpdate();
}
function childDisposed() {
disposedChildCount++;
if (disposedChildCount === disposeChildCount) {
doCreateAndUpdate();
}
}
function doCreateAndUpdate() {
if (violentClear) {
return;
}
// 对相应的项进行更新
if (oldChildrenLen === 0 && isOnlyParentChild) {
var buf = createStrBuffer();
each(
me.children,
function (child) {
child._attachHTML(buf);
}
);
parentEl.innerHTML = stringifyStrBuffer(buf);
me.el = document.createComment('san:' + me.id);
parentEl.appendChild(me.el);
}
else {
// 如果不attached则直接创建,如果存在则调用更新函数
// var attachStump = this;
// while (newChildrenLen--) {
// var child = me.children[newChildrenLen];
// if (child.lifeCycle.attached) {
// childrenChanges[newChildrenLen].length && child._update(childrenChanges[newChildrenLen]);
// }
// else {
// child.attach(parentEl, attachStump._getEl() || parentEl.firstChild);
// }
// attachStump = child;
// }
var newChildBuf;
for (var i = 0; i < newChildrenLen; i++) {
var child = me.children[i];
if (child.lifeCycle.attached) {
childrenChanges[i].length && child._update(childrenChanges[i]);
}
else {
newChildBuf = newChildBuf || createStrBuffer();
child._attachHTML(newChildBuf);
// flush new children html
var nextChild = me.children[i + 1];
if (!nextChild || nextChild.lifeCycle.attached) {
var beforeEl = nextChild && (nextChild._getEl() || nextChild.children[0]._getEl());
insertHTMLBefore(
stringifyStrBuffer(newChildBuf),
parentEl,
beforeEl || me.el || parentEl.firstChild
);
newChildBuf = null;
}
}
}
}
attachings.done();
}
}
// exports = module.exports = createFor;
/**
* @file 生成子元素html
* @author errorrik(errorrik@gmail.com)
*/
// var escapeHTML = require('../runtime/escape-html');
// var pushStrBuffer = require('../runtime/push-str-buffer');
// var each = require('../util/each');
// var createNode = require('./create-node');
// var nodeEvalExpr = require('./node-eval-expr');
/**
* 生成子元素html
*
* @param {Element} element 元素
* @param {Object} buf html串存储对象
* @param {Model=} scope 所属数据环境
*/
function genElementChildrenHTML(element, buf, scope) {
if (element.tagName === 'textarea') {
var valueProp = element.props.get('value');
if (valueProp) {
pushStrBuffer(buf, escapeHTML(nodeEvalExpr(element, valueProp.expr)));
}
}
else {
var htmlDirective = element.aNode.directives.get('html');
if (htmlDirective) {
pushStrBuffer(buf, nodeEvalExpr(element, htmlDirective.value));
}
else {
each(element.aNode.children, function (aNodeChild) {
var child = createNode(aNodeChild, element, scope);
if (!child._static) {
element.children.push(child);
}
child._attachHTML(buf);
});
}
}
}
// exports = module.exports = genElementChildrenHTML;
/**
* @file 使节点到达相应的生命周期
* @author errorrik(errorrik@gmail.com)
*/
// var LifeCycle = require('./life-cycle');
/**
* 使元素节点到达相应的生命周期
*
* @param {Object} element 元素节点
* @param {string} name 生命周期名称
* @return {boolean} 如果节点已经处于当前声明周期,返回false
*/
function elementToPhase(element, name) {
if (element.lifeCycle[name]) {
return;
}
element.lifeCycle = LifeCycle[name] || element.lifeCycle;
return true;
}
// exports = module.exports = elementToPhase;
/**
* @file 使元素节点到达相应的生命周期
* @author errorrik(errorrik@gmail.com)
*/
// var elementToPhase = require('./element-to-phase');
/**
* 使元素节点到达相应的生命周期
*
* @param {string} name 生命周期名称
*/
function elementOwnToPhase(name) {
elementToPhase(this, name);
}
// exports = module.exports = elementOwnToPhase;
/**
* @file 添加子节点的 ANode
* @author errorrik(errorrik@gmail.com)
*/
// #[begin] reverse
/**
* 添加子节点的 ANode
* 用于从 el 初始化时,需要将解析的元素抽象成 ANode,并向父级注册
*
* @param {ANode} aNode 抽象节点对象
*/
function elementOwnPushChildANode(aNode) {
this.aNode.children.push(aNode);
}
// #[end]
// exports = module.exports = elementOwnPushChildANode;
/**
* @file 执行完成attached状态的行为
* @author errorrik(errorrik@gmail.com)
*/
/**
* 执行完成attached状态的行为
*/
function nodeOwnSimpleAttached() {
this._toPhase('attached');
}
// exports = module.exports = nodeOwnSimpleAttached;
/**
* @file 将没有 root 只有 children 的元素 attach 到页面
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var createNode = require('./create-node');
// var attachings = require('./attachings');
/**
* 将没有 root 只有 children 的元素 attach 到页面
* 主要用于 slot 和 template
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function nodeOwnOnlyChildrenAttach(parentEl, beforeEl) {
var me = this;
each(this.aNode.children, function (aNodeChild) {
var child = createNode(aNodeChild, me);
if (!child._static) {
me.children.push(child);
}
child.attach(parentEl, beforeEl);
});
attachings.done();
}
// exports = module.exports = nodeOwnOnlyChildrenAttach;
/**
* @file 创建 slot 元素
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var createANode = require('../parser/create-a-node');
// var ExprType = require('../parser/expr-type');
// var parseTemplate = require('../parser/parse-template');
// var evalExpr = require('../runtime/eval-expr');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var removeEl = require('../browser/remove-el');
// var NodeType = require('./node-type');
// var attachings = require('./attachings');
// var isEndStump = require('./is-end-stump');
// var LifeCycle = require('./life-cycle');
// var isComponent = require('./is-component');
// var genElementChildrenHTML = require('./gen-element-children-html');
// var nodeInit = require('./node-init');
// var nodeDispose = require('./node-dispose');
// var createNodeByEl = require('./create-node-by-el');
// var elementDisposeChildren = require('./element-dispose-children');
// var elementUpdateChildren = require('./element-update-children');
// var elementOwnToPhase = require('./element-own-to-phase');
// var elementOwnPushChildANode = require('./element-own-push-child-anode');
// var nodeOwnSimpleAttached = require('./node-own-simple-attached');
// var nodeOwnOnlyChildrenAttach = require('./node-own-only-children-attach');
/**
* 创建 slot 元素
*
* @param {Object} options 初始化参数
* @return {Object}
*/
function createSlot(options) {
var literalOwner = options.owner;
var aNode = createANode();
// #[begin] reverse
if (options.el) {
if (options.stumpText.indexOf('!') !== 0) {
options.isInserted = true;
}
else {
options.stumpText = options.stumpText.slice(1);
}
aNode = parseTemplate(options.stumpText).children[0];
var nameBind = aNode.props.get('name');
options.name = nameBind ? nameBind.raw : '____';
}
else {
// #[end]
var nameBind = options.aNode.props.get('name');
options.name = nameBind ? nameBind.raw : '____';
var givenSlots = literalOwner.aNode.givenSlots;
var givenChildren = givenSlots && givenSlots[options.name];
aNode.children = givenChildren || options.aNode.children.slice(0);
if (givenChildren) {
options.isInserted = true;
}
aNode.vars = options.aNode.vars;
// #[begin] reverse
}
// #[end]
var initData = {};
each(aNode.vars, function (varItem) {
options.isScoped = true;
initData[varItem.name] = evalExpr(varItem.expr, options.scope, literalOwner);
});
if (options.isScoped) {
options.realScope = new Data(initData);
options.literalOwner = literalOwner;
}
if (options.isInserted) {
options.owner = literalOwner.owner;
!options.isScoped && (options.scope = literalOwner.scope);
}
options.aNode = aNode;
var node = nodeInit(options);
node.lifeCycle = LifeCycle.start;
node.children = [];
node.nodeType = NodeType.SLOT;
node.dispose = slotOwnDispose;
node.attach = nodeOwnOnlyChildrenAttach;
node._toPhase = elementOwnToPhase;
node._getEl = slotOwnGetEl;
node._attachHTML = slotOwnAttachHTML;
node._attached = nodeOwnSimpleAttached;
node._update = slotOwnUpdate;
// #[begin] reverse
node._pushChildANode = elementOwnPushChildANode;
// #[end]
if (options.isInserted && !options.isScoped) {
var parent = node.parent;
while (parent) {
if (isComponent(parent) && parent.owner === node.owner) {
parent.slotChildren.push(node);
break;
}
parent = parent.parent;
}
}
// #[begin] reverse
if (options.el) {
removeEl(options.el);
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
var next = options.elWalker.next;
if (!next || isEndStump(next, 'slot')) {
if (next) {
options.elWalker.goNext();
removeEl(next);
}
break;
}
options.elWalker.goNext();
var child = createNodeByEl(
next,
node,
options.elWalker,
node.realScope || node.scope
);
node.children.push(child);
}
if (literalOwner !== node.owner) {
literalOwner.aNode.givenSlots[node.name] = node.aNode;
}
}
// #[end]
return node;
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
* @param {boolean=} isFromOuter 变化信息是否来源于父组件之外的组件
*/
function slotOwnUpdate(changes, isFromOuter) {
var me = this;
if (me.isScoped) {
each(me.aNode.vars, function (varItem) {
me.realScope.set(varItem.name, evalExpr(varItem.expr, me.scope, me.literalOwner));
});
var scopedChanges = [];
each(changes, function (change) {
each(me.aNode.vars, function (varItem) {
var name = varItem.name;
var relation = changeExprCompare(change.expr, varItem.expr, me.scopeParent);
if (relation < 1) {
return;
}
if (change.type === DataChangeType.SET) {
scopedChanges.push({
type: DataChangeType.SET,
expr: {
type: ExprType.ACCESSOR,
paths: [
{type: ExprType.STRING, value: name}
]
},
value: me.realScope.get(name),
option: change.option
});
}
else if (relation === 2) {
scopedChanges.push({
expr: {
type: ExprType.ACCESSOR,
paths: [
{type: ExprType.STRING, value: name}
]
},
type: DataChangeType.SPLICE,
index: change.index,
deleteCount: change.deleteCount,
value: change.value,
insertions: change.insertions,
option: change.option
});
}
});
});
elementUpdateChildren(me, scopedChanges);
}
else if (me.isInserted && isFromOuter || !me.isInserted) {
elementUpdateChildren(me, changes);
}
}
/**
* attach元素的html
*
* @param {Object} buf html串存储对象
*/
function slotOwnAttachHTML(buf) {
genElementChildrenHTML(this, buf, this.realScope || this.scope);
attachings.add(this);
}
/**
* 获取 slot 对应的主元素
* slot 是片段的管理,没有主元素,所以直接返回爹的主元素,不持有引用
*
* @return {HTMLElement}
*/
function slotOwnGetEl() {
return this.parent._getEl();
}
/**
* 销毁释放 slot
*
* @param {Object=} options dispose行为参数
*/
function slotOwnDispose(options) {
this.realScope = null;
this.literalOwner = null;
elementDisposeChildren(this, options);
nodeDispose(this);
}
// exports = module.exports = createSlot;
/**
* @file 创建 template 元素
* @author errorrik(errorrik@gmail.com)
*/
// var empty = require('../util/empty');
// var createANode = require('../parser/create-a-node');
// var removeEl = require('../browser/remove-el');
// var NodeType = require('./node-type');
// var genElementChildrenHTML = require('./gen-element-children-html');
// var nodeInit = require('./node-init');
// var nodeDispose = require('./node-dispose');
// var isEndStump = require('./is-end-stump');
// var createNodeByEl = require('./create-node-by-el');
// var elementDisposeChildren = require('./element-dispose-children');
// var elementOwnToPhase = require('./element-own-to-phase');
// var elementOwnPushChildANode = require('./element-own-push-child-anode');
// var attachings = require('./attachings');
// var elementUpdateChildren = require('./element-update-children');
// var nodeOwnSimpleAttached = require('./node-own-simple-attached');
// var nodeOwnOnlyChildrenAttach = require('./node-own-only-children-attach');
// var LifeCycle = require('./life-cycle');
/**
* 创建 template 元素
*
* @param {Object} options 初始化参数
* @return {Object}
*/
function createTemplate(options) {
var node = nodeInit(options);
node.lifeCycle = LifeCycle.start;
node.children = [];
node.nodeType = NodeType.TPL;
node.attach = nodeOwnOnlyChildrenAttach;
node.dispose = templateOwnDispose;
node._toPhase = elementOwnToPhase;
node._getEl = empty;
node._attachHTML = templateOwnAttachHTML;
node._attached = nodeOwnSimpleAttached;
node._update = templateOwnUpdate;
// #[begin] reverse
node._pushChildANode = elementOwnPushChildANode;
// #[end]
node.aNode = node.aNode || createANode();
// #[begin] reverse
if (options.el) {
attachings.add(node);
removeEl(options.el);
options.el = null;
/* eslint-disable no-constant-condition */
while (1) {
/* eslint-enable no-constant-condition */
var next = options.elWalker.next;
if (isEndStump(next, 'tpl')) {
options.elWalker.goNext();
removeEl(next);
break;
}
options.elWalker.goNext();
var child = createNodeByEl(next, node, options.elWalker);
child && node.children.push(child);
}
node.parent._pushChildANode(node.aNode);
}
else {
// #[end]
var aNodeChildren = node.aNode.children;
var len = aNodeChildren.length;
if (len) {
if (aNodeChildren[--len].isText) {
aNodeChildren.length = len;
}
if (len && aNodeChildren[0].isText) {
aNodeChildren.splice(0, 1);
}
}
// #[begin] reverse
}
// #[end]
return node;
}
/**
* 视图更新函数
*
* @param {Array} changes 数据变化信息
*/
function templateOwnUpdate(changes) {
elementUpdateChildren(this, changes);
}
/**
* attach 元素的 html
*
* @param {Object} buf html串存储对象
*/
function templateOwnAttachHTML(buf) {
genElementChildrenHTML(this, buf);
attachings.add(this);
}
/**
* 销毁释放
*
* @param {Object=} options dispose行为参数
*/
function templateOwnDispose(options) {
elementDisposeChildren(this, options);
nodeDispose(this);
}
// exports = module.exports = createTemplate;
/**
* @file 遍历和编译已有元素的孩子
* @author errorrik(errorrik@gmail.com)
*/
// var createNodeByEl = require('./create-node-by-el');
// #[begin] reverse
/**
* 元素子节点遍历操作对象
*
* @inner
* @class
* @param {HTMLElement} el 要遍历的元素
*/
function DOMChildrenWalker(el) {
this.raw = [];
this.index = 0;
var child = el.firstChild;
while (child) {
switch (child.nodeType) {
case 1:
case 8:
this.raw.push(child);
}
child = child.nextSibling;
}
this.current = this.raw[this.index];
this.next = this.raw[this.index + 1];
}
/**
* 往下走一个元素
*/
DOMChildrenWalker.prototype.goNext = function () {
this.current = this.raw[++this.index];
this.next = this.raw[this.index + 1];
};
/**
* 遍历和编译已有元素的孩子
*
* @param {HTMLElement} element 已有元素
*/
function fromElInitChildren(element) {
var walker = new DOMChildrenWalker(element.el);
var current;
while ((current = walker.current)) {
var child = createNodeByEl(current, element, walker);
if (child && !child._static) {
element.children.push(child);
}
walker.goNext();
}
}
// #[end]
// exports = module.exports = fromElInitChildren;
/**
* @file attach 元素的 HTML
* @author errorrik(errorrik@gmail.com)
*/
// var genElementStartHTML = require('./gen-element-start-html');
// var genElementChildrenHTML = require('./gen-element-children-html');
// var genElementEndHTML = require('./gen-element-end-html');
// var attachings = require('./attachings');
// var LifeCycle = require('./life-cycle');
/**
* attach 元素的 HTML
*
* @param {Object} buf html串存储对象
*/
function elementOwnAttachHTML(buf) {
this.lifeCycle = LifeCycle.painting;
genElementStartHTML(this, buf);
genElementChildrenHTML(this, buf);
genElementEndHTML(this, buf);
attachings.add(this);
}
// exports = module.exports = elementOwnAttachHTML;
/**
* @file 设置元素属性
* @author errorrik(errorrik@gmail.com)
*/
// var getPropHandler = require('./get-prop-handler');
/**
* 设置元素属性
*
* @param {Object} element 元素
* @param {string} name 属性名
* @param {*} value 属性值
*/
function elementSetElProp(element, name, value) {
getPropHandler(element, name).prop(element, name, value);
}
// exports = module.exports = elementSetElProp;
/**
* @file 创建节点对应的 HTMLElement 主元素
* @author errorrik(errorrik@gmail.com)
*/
// var createEl = require('../browser/create-el');
// var evalExpr = require('../runtime/eval-expr');
// var nodeEvalExpr = require('./node-eval-expr');
// var isComponent = require('./is-component');
// var elementSetElProp = require('./element-set-el-prop');
// var LifeCycle = require('./life-cycle');
/**
* 创建节点对应的 HTMLElement 主元素
*
* @param {Object} element 元素节点
*/
function elementCreate(element) {
element.lifeCycle = LifeCycle.painting;
element.el = createEl(element.tagName);
element.el.id = element.id;
element.props.each(function (prop) {
var attr = prop.attr;
if (!attr) {
element.dynamicProps.push(prop);
}
var value = isComponent(element)
? evalExpr(prop.expr, element.data, element)
: nodeEvalExpr(element, prop.expr, 1);
elementSetElProp(element, prop.name, value);
});
}
// exports = module.exports = elementCreate;
/**
* @file 创建节点对应的 HTMLElement 主元素
* @author errorrik(errorrik@gmail.com)
*/
// var elementCreate = require('./element-create');
/**
* 创建节点对应的 HTMLElement 主元素
*/
function elementOwnCreate() {
if (!this.lifeCycle.created) {
elementCreate(this);
this._toPhase('created');
}
}
// exports = module.exports = elementOwnCreate;
/**
* @file 将元素attach到页面
* @author errorrik(errorrik@gmail.com)
*/
// var createStrBuffer = require('../runtime/create-str-buffer');
// var stringifyStrBuffer = require('../runtime/stringify-str-buffer');
// var genElementChildrenHTML = require('./gen-element-children-html');
// var warnSetHTML = require('./warn-set-html');
/**
* 将元素attach到页面
*
* @param {Object} element 元素节点
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function elementAttach(element, parentEl, beforeEl) {
element._create();
if (parentEl) {
if (beforeEl) {
parentEl.insertBefore(element.el, beforeEl);
}
else {
parentEl.appendChild(element.el);
}
}
if (!element._contentReady) {
var buf = createStrBuffer();
genElementChildrenHTML(element, buf);
// html 没内容就不要设置 innerHTML了
// 这里还能避免在 IE 下 component root 为 input 等元素时设置 innerHTML 报错的问题
var html = stringifyStrBuffer(buf);
if (html) {
// #[begin] error
// warnSetHTML(element.el);
// #[end]
element.el.innerHTML = html;
}
element._contentReady = 1;
}
}
// exports = module.exports = elementAttach;
/**
* @file 将元素attach到页面
* @author errorrik(errorrik@gmail.com)
*/
// var elementAttach = require('./element-attach');
// var attachings = require('./attachings');
/**
* 将元素attach到页面
*
* @param {HTMLElement} parentEl 要添加到的父元素
* @param {HTMLElement=} beforeEl 要添加到哪个元素之前
*/
function elementOwnAttach(parentEl, beforeEl) {
if (!this.lifeCycle.attached) {
elementAttach(this, parentEl, beforeEl);
attachings.add(this);
attachings.done();
this._toPhase('attached');
}
}
// exports = module.exports = elementOwnAttach;
/**
* @file 获取 element 的 transition 控制对象
* @author errorrik(errorrik@gmail.com)
*/
/**
* 获取 element 的 transition 控制对象
*
* @param {Object} element 元素
* @return {Object?}
*/
function elementGetTransition(element) {
var transitionDirective = element.aNode.directives.get('transition');
var transition = element.transition;
if (transitionDirective && element.owner) {
transition = element.owner[transitionDirective.value] || transition;
}
return transition;
}
// exports = module.exports = elementGetTransition;
/**
* @file 元素节点执行leave行为
* @author errorrik(errorrik@gmail.com)
*/
// var elementGetTransition = require('./element-get-transition');
/**
* 元素节点执行leave行为
*
* @param {Object} element 元素
* @param {Object=} options 到达目标状态的参数
*/
function elementLeave(element, options) {
var lifeCycle = element.lifeCycle;
if (lifeCycle.leaving || !lifeCycle.attached) {
return;
}
var noTransition = options && options.noTransition;
if (noTransition) {
element._doneLeave();
}
else {
var transition = elementGetTransition(element);
if (transition) {
element._toPhase('leaving');
transition.leave(element._getEl(), function () {
element._doneLeave();
});
}
else {
element._doneLeave();
}
}
}
// exports = module.exports = elementLeave;
/**
* @file 将元素从页面上移除
* @author errorrik(errorrik@gmail.com)
*/
// var removeEl = require('../browser/remove-el');
// var elementLeave = require('./element-leave');
/**
* 将元素从页面上移除
*/
function elementOwnDetach() {
var me = this;
me._doneLeave = me._doneLeave || function () {
if (me.lifeCycle.attached) {
removeEl(me._getEl());
me._toPhase('detached');
}
};
elementLeave(this);
}
// exports = module.exports = elementOwnDetach;
/**
* @file 销毁元素节点
* @author errorrik(errorrik@gmail.com)
*/
// var un = require('../browser/un');
// var removeEl = require('../browser/remove-el');
// var elementDisposeChildren = require('./element-dispose-children');
// var nodeDispose = require('./node-dispose');
/**
* 销毁元素节点
*
* @param {Object} element 要销毁的元素节点
* @param {Object=} options 销毁行为的参数
*/
function elementDispose(element, options) {
elementDisposeChildren(element, {dontDetach: true, noTransition: true});
/* eslint-disable guard-for-in */
// el 事件解绑
for (var key in element._elFns) {
var nameListeners = element._elFns[key];
var len = nameListeners && nameListeners.length;
while (len--) {
un(element._getEl(), key, nameListeners[len]);
}
}
element._elFns = null;
/* eslint-enable guard-for-in */
if (!options || !options.dontDetach || !element.parent) {
removeEl(element._getEl());
}
if (element._toPhase) {
element._toPhase('detached');
}
element.props = null;
element.dynamicProps = null;
element.binds = null;
element._propVals = null;
nodeDispose(element);
}
// exports = module.exports = elementDispose;
/**
* @file 销毁释放元素
* @author errorrik(errorrik@gmail.com)
*/
// var elementDispose = require('./element-dispose');
// var elementLeave = require('./element-leave');
/**
* 销毁释放元素
*
* @param {Object=} options dispose行为参数
*/
function elementOwnDispose(options) {
var me = this;
me._doneLeave = function () {
if (!me.lifeCycle.disposed) {
elementDispose(me, options);
}
};
elementLeave(this, options);
}
// exports = module.exports = elementOwnDispose;
/**
* @file 获取节点对应的主元素
* @author errorrik(errorrik@gmail.com)
*/
/**
* 获取节点对应的主元素
*
* @return {HTMLElement}
*/
function elementOwnGetEl() {
if (!this.el) {
this.el = document.getElementById(this.id);
}
return this.el;
}
// exports = module.exports = elementOwnGetEl;
/**
* @file 为元素的 el 绑定事件
* @author errorrik(errorrik@gmail.com)
*/
// var on = require('../browser/on');
/**
* 为元素的 el 绑定事件
*
* @param {string} name 事件名
* @param {Function} listener 监听器
*/
function elementOwnOnEl(name, listener) {
if (typeof listener === 'function') {
if (!this._elFns[name]) {
this._elFns[name] = [];
}
this._elFns[name].push(listener);
on(this._getEl(), name, listener);
}
}
// exports = module.exports = elementOwnOnEl;
/**
* @file 是否浏览器环境
* @author errorrik(errorrik@gmail.com)
*/
var isBrowser = typeof window !== 'undefined';
// exports = module.exports = isBrowser;
/**
* @file 事件绑定不存在的 warning
* @author varsha(wangshuonpu@gmail.com)
*/
// #[begin] error
// /**
// * 事件绑定不存在的 warning
// *
// * @param {string} name 事件名
// * @param {Component} owner 所属的组件对象
// * @param {string} listener 事件监听方法名
// */
// function warnEventListenMethod(name, owner, listener) {
// if (owner[listener] == null) {
// var message = '[SAN WARNING] ' + name + ' listen fail,"' + listener + '" not exist';
//
// /* eslint-disable no-console */
// if (typeof console === 'object' && console.warn) {
// console.warn(message);
// }
// else {
// throw new Error(message);
// }
// /* eslint-enable no-console */
// }
// }
// #[end]
// exports = module.exports = warnEventListenMethod;
/**
* @file 完成元素 attached 后的行为
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var bind = require('../util/bind');
// var empty = require('../util/empty');
// var isBrowser = require('../browser/is-browser');
// var elementGetTransition = require('./element-get-transition');
// var eventDeclarationListener = require('./event-declaration-listener');
// var isComponent = require('./is-component');
// var getPropHandler = require('./get-prop-handler');
// var warnEventListenMethod = require('./warn-event-listen-method');
/**
* 完成元素 attached 后的行为
*
* @param {Object} element 元素节点
*/
function elementAttached(element) {
element._toPhase('created');
var data = isComponent(element) ? element.data : element.scope;
// 处理自身变化时双向绑定的逻辑
var xBinds = isComponent(element) ? element.props : element.binds;
xBinds && xBinds.each(function (bindInfo) {
if (!bindInfo.x) {
return;
}
var el = element._getEl();
function outputer() {
getPropHandler(element, bindInfo.name).output(element, bindInfo, data);
}
switch (bindInfo.name) {
case 'value':
switch (element.tagName) {
case 'input':
case 'textarea':
if (isBrowser && window.CompositionEvent) {
element._onEl('compositionstart', function () {
this.composing = 1;
});
element._onEl('compositionend', function () {
this.composing = 0;
var event = document.createEvent('HTMLEvents');
event.initEvent('input', true, true);
this.dispatchEvent(event);
});
}
element._onEl(
('oninput' in el) ? 'input' : 'propertychange',
function (e) {
if (!this.composing) {
outputer(e);
}
}
);
break;
case 'select':
element._onEl('change', outputer);
break;
}
break;
case 'checked':
switch (element.tagName) {
case 'input':
switch (el.type) {
case 'checkbox':
case 'radio':
element._onEl('click', outputer);
}
}
break;
}
});
// bind events
each(element.aNode.events, function (eventBind) {
var owner = isComponent(element) ? element : element.owner;
// 判断是否是nativeEvent,下面的warn方法和事件绑定都需要
// 依此指定eventBind.expr.name位于owner还是owner.owner上
if (eventBind.modifier === 'native') {
owner = owner.owner;
}
// #[begin] error
// warnEventListenMethod(
// eventBind.name,
// owner,
// eventBind.expr.name
// );
// #[end]
element._onEl(
eventBind.name,
bind(
eventDeclarationListener,
owner,
eventBind,
0,
element.data || element.scope
)
);
});
element._toPhase('attached');
var transition = elementGetTransition(element);
if (transition) {
transition.enter(element._getEl(), empty);
}
}
// exports = module.exports = elementAttached;
/**
* @file 初始化 element 节点的必须属性
* @author errorrik(errorrik@gmail.com)
*/
// var LifeCycle = require('./life-cycle');
// var IndexedList = require('../util/indexed-list');
/**
* 初始化 element 节点的必须属性
*
* @param {Object} element 节点对象
*/
function elementInitProps(element) {
element.lifeCycle = LifeCycle.start;
element.children = [];
element._elFns = {};
element._propVals = {};
element.dynamicProps = new IndexedList();
}
// exports = module.exports = elementInitProps;
/**
* @file 初始化 element 节点的 tagName 处理
* @author errorrik(errorrik@gmail.com)
*/
// var ieOldThan9 = require('../browser/ie-old-than-9');
/**
* 初始化 element 节点的 tagName 处理
*
* @param {Object} node 节点对象
*/
function elementInitTagName(node) {
node.tagName = node.tagName || node.aNode.tagName || 'div';
// ie8- 不支持innerHTML输出自定义标签
if (ieOldThan9 && node.tagName.indexOf('-') > 0) {
node.tagName = 'div';
}
// ie 下,如果 option 没有 value 属性,select.value = xx 操作不会选中 option
// 所以没有设置 value 时,默认把 option 的内容作为 value
if (node.tagName === 'option'
&& !node.aNode.props.get('value')
&& node.aNode.children[0]
) {
node.aNode.props.push({
name: 'value',
expr: node.aNode.children[0].textExpr
});
}
}
// exports = module.exports = elementInitTagName;
/**
* @file 给 devtool 发通知消息
* @author errorrik(errorrik@gmail.com)
*/
// var isBrowser = require('../browser/is-browser');
// #[begin] devtool
// var san4devtool;
//
// /**
// * 给 devtool 发通知消息
// *
// * @param {string} name 消息名称
// * @param {*} arg 消息参数
// */
// function emitDevtool(name, arg) {
// if (isBrowser && san4devtool && san4devtool.debug && window.__san_devtool__) {
// window.__san_devtool__.emit(name, arg);
// }
// }
//
// emitDevtool.start = function (main) {
// san4devtool = main;
// emitDevtool('san', main);
// };
// #[end]
// exports = module.exports = emitDevtool;
/**
* @file 组件类
* @author errorrik(errorrik@gmail.com)
*/
// var bind = require('../util/bind');
// var each = require('../util/each');
// var extend = require('../util/extend');
// var nextTick = require('../util/next-tick');
// var emitDevtool = require('../util/emit-devtool');
// var ExprType = require('../parser/expr-type');
// var createANode = require('../parser/create-a-node');
// var parseExpr = require('../parser/parse-expr');
// var parseANodeFromEl = require('../parser/parse-anode-from-el');
// var Data = require('../runtime/data');
// var DataChangeType = require('../runtime/data-change-type');
// var evalExpr = require('../runtime/eval-expr');
// var changeExprCompare = require('../runtime/change-expr-compare');
// var compileComponent = require('./compile-component');
// var attachings = require('./attachings');
// var isComponent = require('./is-component');
// var isDataChangeByElement = require('./is-data-change-by-element');
// var eventDeclarationListener = require('./event-declaration-listener');
// var fromElInitChildren = require('./from-el-init-children');
// var postComponentBinds = require('./post-component-binds');
// var camelComponentBinds = require('./camel-component-binds');
// var nodeEvalExpr = require('./node-eval-expr');
// var NodeType = require('./node-type');
// var nodeInit = require('./node-init');
// var elementInitProps = require('./element-init-props');
// var elementInitTagName = require('./element-init-tag-name');
// var elementAttached = require('./element-attached');
// var elementDispose = require('./element-dispose');
// var elementUpdateChildren = require('./element-update-children');
// var elementSetElProp = require('./element-set-el-prop');
// var elementOwnGetEl = require('./element-own-get-el');
// var elementOwnOnEl = require('./element-own-on-el');
// var elementOwnCreate = require('./element-own-create');
// var elementOwnAttach = require('./element-own-attach');
// var elementOwnDetach = require('./element-own-detach');
// var elementOwnAttachHTML = require('./element-own-attach-html');
// var elementOwnPushChildANode = require('./element-own-push-child-anode');
// var warnEventListenMethod = require('./warn-event-listen-method');
// var elementLeave = require('./element-leave');
// var elementToPhase = require('./element-to-phase');
// var createDataTypesChecker = require('../util/create-data-types-checker');
/* eslint-disable guard-for-in */
/**
* 组件类
*
* @class
* @param {Object} options 初始化参数
*/
function Component(options) {
elementInitProps(this);
options = options || {};
this.listeners = {};
this.slotChildren = [];
this.filters = this.filters || this.constructor.filters || {};
this.computed = this.computed || this.constructor.computed || {};
this.messages = this.messages || this.constructor.messages || {};
this.subTag = options.subTag;
// compile
compileComponent(this.constructor);
var me = this;
var givenANode = options.aNode;
var protoANode = this.constructor.prototype.aNode;
if (givenANode) {
// 组件运行时传入的结构,做slot解析
var givenSlots = {};
// native事件数组
var nativeEvents = [];
each(givenANode.children, function (child) {
var slotName = '____';
var slotBind = !child.isText && child.props.get('slot');
if (slotBind) {
slotName = slotBind.raw;
}
if (!givenSlots[slotName]) {
givenSlots[slotName] = [];
}
givenSlots[slotName].push(child);
});
each(givenANode.events, function (eventBind) {
// 保存当前实例的native事件,下面创建aNode时候做合并
if (eventBind.modifier === 'native') {
nativeEvents.push(eventBind);
}
// #[begin] error
// warnEventListenMethod(eventBind.name, options.owner, eventBind.expr.name);
// #[end]
me.on(
eventBind.name,
bind(eventDeclarationListener, options.owner, eventBind, 1, options.scope),
eventBind
);
});
this.aNode = createANode({
tagName: protoANode.tagName || givenANode.tagName,
givenSlots: givenSlots,
// 组件的实际结构应为template编译的结构
children: protoANode.children,
// 合并运行时的一些绑定和事件声明
props: protoANode.props,
binds: camelComponentBinds(givenANode.props),
events: protoANode.events.concat(nativeEvents),
directives: givenANode.directives
});
}
this._toPhase('compiled');
// init data
this.data = new Data(
extend(
typeof this.initData === 'function' && this.initData() || {},
options.data
)
);
nodeInit(options, this);
// #[begin] reverse
if (this.el) {
this.aNode = parseANodeFromEl(this.el);
this.aNode.givenSlots = {};
this.aNode.binds = camelComponentBinds(this.aNode.props);
this.aNode.props = this.constructor.prototype.aNode.props;
this.parent && this.parent._pushChildANode(this.aNode);
this.tagName = this.aNode.tagName;
fromElInitChildren(this);
attachings.add(this);
}
// #[end]
elementInitTagName(this);
this.props = this.aNode.props;
this.binds = this.aNode.binds || this.aNode.props;
postComponentBinds(this.binds);
this.scope && this.binds.each(function (bind) {
me.data.set(bind.name, nodeEvalExpr(me, bind.expr));
});
// #[begin] error
// // 在初始化 + 数据绑定后,开始数据校验
// // NOTE: 只在开发版本中进行属性校验
// var dataTypes = this.dataTypes || this.constructor.dataTypes;
// if (dataTypes) {
// var dataTypeChecker = createDataTypesChecker(
// dataTypes,
// this.subTag || this.name || this.constructor.name
// );
// this.data.setTypeChecker(dataTypeChecker);
// this.data.checkDataTypes();
// }
// #[end]
this.computedDeps = {};
for (var expr in this.computed) {
if (!this.computedDeps[expr]) {
this._calcComputed(expr);
}
}
if (!this.dataChanger) {
this.dataChanger = bind(this._dataChanger, this);
this.data.listen(this.dataChanger);
}
this._toPhase('inited');
// #[begin] reverse
// 如果从el编译的,认为已经attach了,触发钩子
if (this.el) {
attachings.done();
}
// #[end]
}
/**
* 类型标识
*
* @type {string}
*/
Component.prototype.nodeType = NodeType.CMPT;
/**
* 在下一个更新周期运行函数
*
* @param {Function} fn 要运行的函数
*/
Component.prototype.nextTick = nextTick;
/* eslint-disable operator-linebreak */
/**
* 使节点到达相应的生命周期
*
* @protected
* @param {string} name 生命周期名称
*/
Component.prototype._callHook =
Component.prototype._toPhase = function (name) {
if (elementToPhase(this, name)) {
if (typeof this[name] === 'function') {
this[name]();
}
// 通知devtool
// #[begin] devtool
// emitDevtool('comp-' + name, this);
// #[end]
}
};
/* eslint-enable operator-linebreak */
/**
* 添加事件监听器
*
* @param {string} name 事件名
* @param {Function} listener 监听器
* @param {string?} declaration 声明式
*/
Component.prototype.on = function (name, listener, declaration) {
if (typeof listener === 'function') {
if (!this.listeners[name]) {
this.listeners[name] = [];
}
this.listeners[name].push({fn: listener, declaration: declaration});
}
};
/**
* 移除事件监听器
*
* @param {string} name 事件名
* @param {Function=} listener 监听器
*/
Component.prototype.un = function (name, listener) {
var nameListeners = this.listeners[name];
var len = nameListeners && nameListeners.length;
while (len--) {
if (!listener || listener === nameListeners[len].fn) {
nameListeners.splice(len, 1);
}
}
};
/**
* 派发事件
*
* @param {string} name 事件名
* @param {Object} event 事件对象
*/
Component.prototype.fire = function (name, event) {
each(this.listeners[name], function (listener) {
listener.fn.call(this, event);
}, this);
};
/**
* 计算 computed 属性的值
*
* @private
* @param {string} computedExpr computed表达式串
*/
Component.prototype._calcComputed = function (computedExpr) {
var computedDeps = this.computedDeps[computedExpr];
if (!computedDeps) {
computedDeps = this.computedDeps[computedExpr] = {};
}
this.data.set(computedExpr, this.computed[computedExpr].call({
data: {
get: bind(function (expr) {
// #[begin] error
// if (!expr) {
// throw new Error('[SAN ERROR] call get method in computed need argument');
// }
// #[end]
if (!computedDeps[expr]) {
computedDeps[expr] = 1;
if (this.computed[expr]) {
this._calcComputed(expr);
}
this.watch(expr, function () {
this._calcComputed(computedExpr);
});
}
return this.data.get(expr);
}, this)
}
}));
};
/**
* 派发消息
* 组件可以派发消息,消息将沿着组件树向上传递,直到遇上第一个处理消息的组件
*
* @param {string} name 消息名称
* @param {*?} value 消息值
*/
Component.prototype.dispatch = function (name, value) {
var parentComponent = this.parentComponent;
while (parentComponent) {
if (typeof parentComponent.messages[name] === 'function') {
parentComponent.messages[name].call(
parentComponent,
{target: this, value: value}
);
break;
}
parentComponent = parentComponent.parentComponent;
}
};
/**
* 获取组件内部的 slot
*
* @param {string=} name slot名称,空为default slot
* @return {Array}
*/
Component.prototype.slot = function (name) {
name = name || '____';
var result = [];
function childrenTraversal(children) {
each(children, function (child) {
if (child.nodeType === NodeType.SLOT) {
if (child.name === name) {
result.push(child);
}
}
else if (!isComponent(child)) {
childrenTraversal(child.children);
}
});
}
childrenTraversal(this.children);
return result;
};
/**
* 获取带有 san-ref 指令的子组件引用
*
* @param {string} name 子组件的引用名
* @return {Component}
*/
Component.prototype.ref = function (name) {
var refComponent;
var owner = this;
function childrenTraversal(children) {
each(children, function (child) {
elementTraversal(child);
return !refComponent;
});
}
function elementTraversal(element) {
if (isComponent(element)) {
var refDirective = element.aNode.directives.get('ref');
if (refDirective
&& evalExpr(refDirective.value, element.scope || owner.data, owner) === name
) {
refComponent = element;
}
!refComponent && childrenTraversal(element.slotChildren);
}
!refComponent && each(element.children, function (child) {
if (child.nodeType !== NodeType.TEXT) {
elementTraversal(child);
}
return !refComponent;
});
}
childrenTraversal(this.children);
return refComponent;
};
/**
* 视图更新函数
*
* @param {Array?} changes 数据变化信息
*/
Component.prototype._update = function (changes) {
if (this.lifeCycle.disposed) {
return;
}
var me = this;
each(changes, function (change) {
var changeExpr = change.expr;
me.binds.each(function (bindItem) {
var relation;
var setExpr = bindItem.name;
var updateExpr = bindItem.expr;
if (!isDataChangeByElement(change, me, setExpr)
&& (relation = changeExprCompare(changeExpr, updateExpr, me.scope))
) {
if (relation > 2) {
setExpr = {
type: ExprType.ACCESSOR,
paths: [{
type: ExprType.STRING,
value: setExpr
}].concat(changeExpr.paths.slice(updateExpr.paths.length))
};
updateExpr = changeExpr;
}
me.data.set(setExpr, nodeEvalExpr(me, updateExpr), {
target: {
id: me.owner.id
}
});
}
});
});
each(this.slotChildren, function (child) {
child._update(changes, 1);
});
var dataChanges = me.dataChanges;
if (dataChanges) {
me.dataChanges = null;
me.props.each(function (prop) {
each(dataChanges, function (change) {
if (changeExprCompare(change.expr, prop.expr, me.data)
|| prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, me.data)
) {
elementSetElProp(
me,
prop.name,
evalExpr(prop.expr, me.data, me)
);
return false;
}
});
});
elementUpdateChildren(this, dataChanges);
this._toPhase('updated');
if (me.owner) {
each(dataChanges, function (change) {
me.binds.each(function (bindItem) {
var changeExpr = change.expr;
if (bindItem.x
&& !isDataChangeByElement(change, me.owner)
&& changeExprCompare(changeExpr, parseExpr(bindItem.name), me.data)
) {
var updateScopeExpr = bindItem.expr;
if (changeExpr.paths.length > 1) {
updateScopeExpr = {
type: ExprType.ACCESSOR,
paths: bindItem.expr.paths.concat(changeExpr.paths.slice(1))
};
}
me.scope.set(
updateScopeExpr,
evalExpr(changeExpr, me.data, me),
{
target: {
id: me.id,
prop: bindItem.name
}
}
);
}
});
});
me.owner._update();
}
}
};
/**
* 组件内部监听数据变化的函数
*
* @private
* @param {Object} change 数据变化信息
*/
Component.prototype._dataChanger = function (change) {
if (this.lifeCycle.painting || this.lifeCycle.created) {
if (!this.dataChanges) {
nextTick(this._update, this);
this.dataChanges = [];
}
var len = this.dataChanges.length;
while (len--) {
switch (changeExprCompare(change.expr, this.dataChanges[len].expr)) {
case 1:
case 2:
if (change.type === DataChangeType.SET) {
this.dataChanges.splice(len, 1);
}
}
}
this.dataChanges.push(change);
}
};
/**
* 监听组件的数据变化
*
* @param {string} dataName 变化的数据项
* @param {Function} listener 监听函数
*/
Component.prototype.watch = function (dataName, listener) {
var dataExpr = parseExpr(dataName);
this.data.listen(bind(function (change) {
if (changeExprCompare(change.expr, dataExpr, this.data)) {
listener.call(this, evalExpr(dataExpr, this.data, this), change);
}
}, this));
};
/**
* 组件销毁的行为
*
* @param {Object} options 销毁行为的参数
*/
Component.prototype.dispose = function (options) {
var me = this;
me._doneLeave = function () {
if (!me.lifeCycle.disposed) {
// 这里不用挨个调用 dispose 了,因为 children 释放链会调用的
me.slotChildren = null;
me.data.unlisten();
me.dataChanger = null;
me.dataChanges = null;
elementDispose(me, options);
me.listeners = null;
}
};
elementLeave(this, options);
};
/**
* 完成组件 attached 后的行为
*
* @param {Object} element 元素节点
*/
Component.prototype._attached = function () {
this._getEl();
elementAttached(this);
};
Component.prototype.attach = elementOwnAttach;
Component.prototype.detach = elementOwnDetach;
Component.prototype._attachHTML = elementOwnAttachHTML;
Component.prototype._create = elementOwnCreate;
Component.prototype._getEl = elementOwnGetEl;
Component.prototype._onEl = elementOwnOnEl;
// #[begin] reverse
Component.prototype._pushChildANode = elementOwnPushChildANode;
// #[end]
// exports = module.exports = Component;
/**
* @file 创建组件类
* @author errorrik(errorrik@gmail.com)
*/
// var Component = require('./component');
// var inherits = require('../util/inherits');
/**
* 创建组件类
*
* @param {Object} proto 组件类的方法表
* @return {Function}
*/
function defineComponent(proto) {
// 如果传入一个不是 san component 的 constructor,直接返回不是组件构造函数
// 这种场景导致的错误 san 不予考虑
if (typeof proto === 'function') {
return proto;
}
// #[begin] error
// if (typeof proto !== 'object') {
// throw new Error('[SAN FATAL] param must be a plain object.');
// }
// #[end]
function ComponentClass(option) {
Component.call(this, option);
}
ComponentClass.prototype = proto;
inherits(ComponentClass, Component);
return ComponentClass;
}
// exports = module.exports = defineComponent;
/**
* @file 编译组件类
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var IndexedList = require('../util/indexed-list');
// var createANode = require('../parser/create-a-node');
// var parseTemplate = require('../parser/parse-template');
// var parseText = require('../parser/parse-text');
// var defineComponent = require('./define-component');
/* eslint-disable quotes */
var componentPropExtra = [
{name: 'class', expr: parseText("{{class | _class | _sep(' ')}}")},
{name: 'style', expr: parseText("{{style | _style | _sep(';')}}")}
];
/* eslint-enable quotes */
/**
* 编译组件类。预解析template和components
*
* @param {Function} ComponentClass 组件类
*/
function compileComponent(ComponentClass) {
var proto = ComponentClass.prototype;
// pre define components class
if (!proto.hasOwnProperty('_cmptReady')) {
proto.components = ComponentClass.components || proto.components || {};
var components = proto.components;
for (var key in components) {
var componentClass = components[key];
if (typeof componentClass === 'object') {
components[key] = defineComponent(componentClass);
}
else if (componentClass === 'self') {
components[key] = ComponentClass;
}
}
proto._cmptReady = 1;
}
// pre compile template
if (!proto.hasOwnProperty('aNode')) {
proto.aNode = createANode();
var tpl = ComponentClass.template || proto.template;
if (tpl) {
var aNode = parseTemplate(tpl, {
trimWhitespace: proto.trimWhitespace || ComponentClass.trimWhitespace
});
var firstChild = aNode.children[0];
// #[begin] error
// if (aNode.children.length !== 1 || firstChild.isText) {
// throw new Error('[SAN FATAL] template must have a root element.');
// }
// #[end]
proto.aNode = firstChild;
if (firstChild.tagName === 'template') {
firstChild.tagName = null;
}
firstChild.binds = new IndexedList();
each(componentPropExtra, function (extra) {
var prop = firstChild.props.get(extra.name);
if (prop) {
prop.expr.segs.push(extra.expr.segs[0]);
prop.expr.value = null;
prop.attr = null;
}
else {
firstChild.props.push({
name: extra.name,
expr: extra.expr
});
}
});
}
}
}
// exports = module.exports = compileComponent;
/**
* @file 将组件的绑定信息进行后处理
* @author errorrik(errorrik@gmail.com)
*/
// var postProp = require('../parser/post-prop');
/**
* 将组件的绑定信息进行后处理
*
* 扁平化:
* 当 text 解析只有一项时,要么就是 string,要么就是 interp
* interp 有可能是绑定到组件属性的表达式,不希望被 eval text 成 string
* 所以这里做个处理,只有一项时直接抽出来
*
* bool属性:
* 当绑定项没有值时,默认为true
*
* @param {IndexedList} binds 组件绑定信息集合对象
*/
function postComponentBinds(binds) {
binds.each(function (bind) {
postProp(bind);
});
}
// exports = module.exports = postComponentBinds;
/**
* @file 把 kebab case 字符串转换成 camel case
* @author errorrik(errorrik@gmail.com)
*/
/**
* 把 kebab case 字符串转换成 camel case
*
* @param {string} source 源字符串
* @return {string}
*/
function kebab2camel(source) {
return source.replace(/-([a-z])/g, function (match, alpha) {
return alpha.toUpperCase();
});
}
// exports = module.exports = kebab2camel;
/**
* @file 将 binds 的 name 从 kebabcase 转换成 camelcase
* @author errorrik(errorrik@gmail.com)
*/
// var kebab2camel = require('../util/kebab2camel');
// var IndexedList = require('../util/indexed-list');
/**
* 将 binds 的 name 从 kebabcase 转换成 camelcase
*
* @param {IndexedList} binds binds集合
* @return {IndexedList}
*/
function camelComponentBinds(binds) {
var result = new IndexedList();
binds.each(function (bind) {
result.push({
name: kebab2camel(bind.name),
expr: bind.expr,
x: bind.x,
raw: bind.raw
});
});
return result;
}
// exports = module.exports = camelComponentBinds;
/**
* @file 把 camel case 字符串转换成 kebab case
* @author errorrik(errorrik@gmail.com)
*/
// #[begin] ssr
// /**
// * 把 camel case 字符串转换成 kebab case
// *
// * @param {string} source 源字符串
// * @return {string}
// */
// function camel2kebab(source) {
// return source.replace(/[A-Z]/g, function (match) {
// return '-' + match.toLowerCase();
// });
// }
// #[end]
// exports = module.exports = camel2kebab;
/**
* @file 编译源码的 helper 方法集合
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var ExprType = require('../parser/expr-type');
// #[begin] ssr
//
// /**
// * 编译源码的 helper 方法集合对象
// */
// var compileExprSource = {
//
// /**
// * 字符串字面化
// *
// * @param {string} source 需要字面化的字符串
// * @return {string} 字符串字面化结果
// */
// stringLiteralize: function (source) {
// return '"'
// + source
// .replace(/\x5C/g, '\\\\')
// .replace(/"/g, '\\"')
// .replace(/\x0A/g, '\\n')
// .replace(/\x09/g, '\\t')
// .replace(/\x0D/g, '\\r')
// // .replace( /\x08/g, '\\b' )
// // .replace( /\x0C/g, '\\f' )
// + '"';
// },
//
// /**
// * 生成数据访问表达式代码
// *
// * @param {Object?} accessorExpr accessor表达式对象
// * @return {string}
// */
// dataAccess: function (accessorExpr) {
// var code = 'componentCtx.data';
// if (accessorExpr) {
// each(accessorExpr.paths, function (path) {
// if (path.type === ExprType.ACCESSOR) {
// code += '[' + compileExprSource.dataAccess(path) + ']';
// return;
// }
//
// switch (typeof path.value) {
// case 'string':
// code += '.' + path.value;
// break;
//
// case 'number':
// code += '[' + path.value + ']';
// break;
// }
// });
// }
//
// return code;
// },
//
// /**
// * 生成插值代码
// *
// * @param {Object} interpExpr 插值表达式对象
// * @return {string}
// */
// interp: function (interpExpr) {
// var code = compileExprSource.expr(interpExpr.expr);
//
// each(interpExpr.filters, function (filter) {
// code = 'componentCtx.callFilter("' + filter.name + '", [' + code;
// each(filter.args, function (arg) {
// code += ', ' + compileExprSource.expr(arg);
// });
// code += '])';
// });
//
// return code;
// },
//
// /**
// * 生成文本片段代码
// *
// * @param {Object} textExpr 文本片段表达式对象
// * @return {string}
// */
// text: function (textExpr) {
// if (textExpr.segs.length === 0) {
// return '""';
// }
//
// var code = '';
//
// each(textExpr.segs, function (seg) {
// if (seg.type === ExprType.INTERP && !seg.filters[0]) {
// seg = {
// type: ExprType.INTERP,
// expr: seg.expr,
// filters: [
// {
// type: ExprType.CALL,
// name: 'html',
// args: []
// }
// ]
// };
// }
//
// var segCode = compileExprSource.expr(seg);
// code += code ? ' + ' + segCode : segCode;
// });
//
// return code;
// },
//
// /**
// * 二元表达式操作符映射表
// *
// * @type {Object}
// */
// binaryOp: {
// /* eslint-disable */
// 43: '+',
// 45: '-',
// 42: '*',
// 47: '/',
// 60: '<',
// 62: '>',
// 76: '&&',
// 94: '!=',
// 121: '<=',
// 122: '==',
// 123: '>=',
// 155: '!==',
// 183: '===',
// 248: '||'
// /* eslint-enable */
// },
//
// /**
// * 生成表达式代码
// *
// * @param {Object} expr 表达式对象
// * @return {string}
// */
// expr: function (expr) {
// switch (expr.type) {
// case ExprType.UNARY:
// return '!' + compileExprSource.expr(expr.expr);
//
// case ExprType.BINARY:
// return compileExprSource.expr(expr.segs[0])
// + compileExprSource.binaryOp[expr.operator]
// + compileExprSource.expr(expr.segs[1]);
//
// case ExprType.TERTIARY:
// return compileExprSource.expr(expr.segs[0])
// + '?' + compileExprSource.expr(expr.segs[1])
// + ':' + compileExprSource.expr(expr.segs[2]);
//
// case ExprType.STRING:
// return compileExprSource.stringLiteralize(expr.value);
//
// case ExprType.NUMBER:
// return expr.value;
//
// case ExprType.BOOL:
// return expr.value ? 'true' : 'false';
//
// case ExprType.ACCESSOR:
// return compileExprSource.dataAccess(expr);
//
// case ExprType.INTERP:
// return compileExprSource.interp(expr);
//
// case ExprType.TEXT:
// return compileExprSource.text(expr);
// }
// }
// };
// #[end]
// exports = module.exports = compileExprSource;
/**
* @file 编译源码的中间buffer类
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var compileExprSource = require('./compile-expr-source');
// #[begin] ssr
// /**
// * 编译源码的中间buffer类
// *
// * @class
// */
// function CompileSourceBuffer() {
// this.segs = [];
// }
//
// /**
// * 添加原始代码,将原封不动输出
// *
// * @param {string} code 原始代码
// */
// CompileSourceBuffer.prototype.addRaw = function (code) {
// this.segs.push({
// type: 'RAW',
// code: code
// });
// };
//
// /**
// * 添加被拼接为html的原始代码
// *
// * @param {string} code 原始代码
// */
// CompileSourceBuffer.prototype.joinRaw = function (code) {
// this.segs.push({
// type: 'JOIN_RAW',
// code: code
// });
// };
//
// /**
// * 添加renderer方法的起始源码
// */
// CompileSourceBuffer.prototype.addRendererStart = function () {
// this.addRaw('function (data, parentCtx) {');
// this.addRaw('var html = "";');
// };
//
// /**
// * 添加renderer方法的结束源码
// */
// CompileSourceBuffer.prototype.addRendererEnd = function () {
// this.addRaw('return html;');
// this.addRaw('}');
// };
//
// /**
// * 添加被拼接为html的静态字符串
// *
// * @param {string} str 被拼接的字符串
// */
// CompileSourceBuffer.prototype.joinString = function (str) {
// this.segs.push({
// str: str,
// type: 'JOIN_STRING'
// });
// };
//
// /**
// * 添加被拼接为html的数据访问
// *
// * @param {Object?} accessor 数据访问表达式对象
// */
// CompileSourceBuffer.prototype.joinDataStringify = function () {
// this.segs.push({
// type: 'JOIN_DATA_STRINGIFY'
// });
// };
//
// /**
// * 添加被拼接为html的表达式
// *
// * @param {Object} expr 表达式对象
// */
// CompileSourceBuffer.prototype.joinExpr = function (expr) {
// this.segs.push({
// expr: expr,
// type: 'JOIN_EXPR'
// });
// };
//
// /**
// * 生成编译后代码
// *
// * @return {string}
// */
// CompileSourceBuffer.prototype.toCode = function () {
// var code = [];
// var temp = '';
//
// function genStrLiteral() {
// if (temp) {
// code.push('html += ' + compileExprSource.stringLiteralize(temp) + ';');
// }
//
// temp = '';
// }
//
// each(this.segs, function (seg) {
// if (seg.type === 'JOIN_STRING') {
// temp += seg.str;
// return;
// }
//
// genStrLiteral();
// switch (seg.type) {
// case 'JOIN_DATA_STRINGIFY':
// code.push('html += stringifier.any(' + compileExprSource.dataAccess() + ');');
// break;
//
// case 'JOIN_EXPR':
// code.push('html += ' + compileExprSource.expr(seg.expr) + ';');
// break;
//
// case 'JOIN_RAW':
// code.push('html += ' + seg.code + ';');
// break;
//
// case 'RAW':
// code.push(seg.code);
// break;
//
// }
// });
//
// genStrLiteral();
//
// return code.join('\n');
// };
//
// #[end]
// exports = module.exports = CompileSourceBuffer;
/**
* @file 序列化一个ANode
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var autoCloseTags = require('../browser/auto-close-tags');
// #[begin] ssr
// /**
// * 序列化一个ANode
// *
// * @param {ANode} aNode aNode对象
// * @return {string}
// */
// function serializeANode(aNode) {
// if (aNode.isText) {
// return aNode.text;
// }
//
// var tagName = aNode.tagName;
//
// // start tag
// var str = '<' + tagName;
//
// // for directives
// var hasElse;
// aNode.directives.each(function (directive) {
// if (directive.name === 'else' || directive.name === 'if' && directive.isElse) {
// if (!hasElse) {
// str += ' s-else';
// }
// hasElse = 1;
//
// return;
// }
//
// str += ' s-' + directive.name + '="' + directive.raw + '"';
// });
//
// // for events
// each(aNode.events, function (event) {
// str += ' on-' + event.name + '="' + event.expr.raw + '"';
// });
//
// // for props
// aNode.props.each(function (prop) {
// str += ' ' + prop.name + '="' + prop.raw + '"';
// });
//
// // for vars
// each(aNode.vars, function (varItem) {
// str += ' var-' + varItem.name + '="' + varItem.expr.raw + '"';
// });
//
// if (autoCloseTags[tagName]) {
// str += ' />';
// }
// else {
// str += '>';
//
// // for children
// each(aNode.children, function (child) {
// str += serializeANode(child);
// });
//
// // close tag
// str += '</' + tagName + '>';
// }
//
// if (aNode.directives.get('if')) {
// each(aNode.elses, function (elseANode) {
// str += serializeANode(elseANode);
// });
// }
//
// return str;
// }
// #[end]
// exports = module.exports = serializeANode;
/**
* @file 将组件编译成 render 方法的 js 源码
* @author errorrik(errorrik@gmail.com)
*/
// var each = require('../util/each');
// var camel2kebab = require('../util/camel2kebab');
// var IndexedList = require('../util/indexed-list');
// var guid = require('../util/guid');
// var parseExpr = require('../parser/parse-expr');
// var createANode = require('../parser/create-a-node');
// var autoCloseTags = require('../browser/auto-close-tags');
// var CompileSourceBuffer = require('./compile-source-buffer');
// var compileExprSource = require('./compile-expr-source');
// var postComponentBinds = require('./post-component-binds');
// var serializeANode = require('./serialize-a-node');
// #[begin] ssr
//
// /**
// * 生成序列化时起始桩的html
// *
// * @param {string} type 桩类型标识
// * @param {string?} content 桩内的内容
// * @return {string}
// */
// function serializeStump(type, content) {
// return '<!--s-' + type + (content ? ':' + content : '') + '-->';
// }
//
// /**
// * 生成序列化时结束桩的html
// *
// * @param {string} type 桩类型标识
// * @return {string}
// */
// function serializeStumpEnd(type) {
// return '<!--/s-' + type + '-->';
// }
//
// /**
// * element 的编译方法集合对象
// *
// * @inner
// */
// var elementSourceCompiler = {
//
// /* eslint-disable max-params */
// /**
// * 编译元素标签头
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {string} tagName 标签名
// * @param {IndexedList} props 属性列表
// * @param {IndexedList} binds 绑定信息列表
// * @param {Array} events 绑定事件列表
// * @param {Object} aNode 对应的抽象节点对象
// * @param {string?} extraProp 额外的属性串
// * @param {boolean?} isComponent 是否组件
// * @param {boolean?} isClose 是否闭合
// */
// tagStart: function (sourceBuffer, tagName, props, binds, events, aNode, extraProp, isComponent, isClose) {
// sourceBuffer.joinString('<' + tagName);
// sourceBuffer.joinString(extraProp || '');
//
// binds.each(function (bindInfo) {
// if (isComponent) {
// sourceBuffer.joinString(
// ' prop-' + camel2kebab(bindInfo.name)
// + (bindInfo.raw ? '="' + bindInfo.raw + '"' : '')
// );
// }
// else if (bindInfo.raw) {
// sourceBuffer.joinString(
// ' prop-' + camel2kebab(bindInfo.name) + '="' + bindInfo.raw + '"'
// );
// }
//
// });
//
// var htmlDirective = aNode.directives.get('html');
// if (htmlDirective) {
// sourceBuffer.joinString(' s-html="' + htmlDirective.raw + '"');
// }
//
// each(events, function (event) {
// sourceBuffer.joinString(' on-' + event.name + '="' + event.expr.raw + '"');
// });
//
// props.each(function (prop) {
// if (prop.name === 'value') {
// switch (tagName) {
// case 'textarea':
// return;
//
// case 'select':
// sourceBuffer.addRaw('$selectValue = '
// + compileExprSource.expr(prop.expr)
// + ' || "";'
// );
// return;
//
// case 'option':
// sourceBuffer.addRaw('$optionValue = '
// + compileExprSource.expr(prop.expr)
// + ';'
// );
// // value
// sourceBuffer.addRaw('if ($optionValue != null) {');
// sourceBuffer.joinRaw('" value=\\"" + $optionValue + "\\""');
// sourceBuffer.addRaw('}');
//
// // selected
// sourceBuffer.addRaw('if ($optionValue === $selectValue) {');
// sourceBuffer.joinString(' selected');
// sourceBuffer.addRaw('}');
// return;
// }
// }
//
// switch (prop.name) {
// case 'draggable':
// case 'readonly':
// case 'disabled':
// case 'multiple':
// if (prop.raw === '') {
// sourceBuffer.joinString(' ' + prop.name);
// }
// else {
// sourceBuffer.joinRaw('boolAttrFilter("' + prop.name + '", '
// + compileExprSource.expr(prop.expr)
// + ')'
// );
// }
// break;
//
// case 'checked':
// if (tagName === 'input') {
// var valueProp = props.get('value');
// var valueCode = compileExprSource.expr(valueProp.expr);
//
// if (valueProp) {
// switch (props.get('type').raw) {
// case 'checkbox':
// sourceBuffer.addRaw('if (contains('
// + compileExprSource.expr(prop.expr)
// + ', '
// + valueCode
// + ')) {'
// );
// sourceBuffer.joinString(' checked');
// sourceBuffer.addRaw('}');
// break;
//
// case 'radio':
// sourceBuffer.addRaw('if ('
// + compileExprSource.expr(prop.expr)
// + ' === '
// + valueCode
// + ') {'
// );
// sourceBuffer.joinString(' checked');
// sourceBuffer.addRaw('}');
// break;
// }
// }
// }
// break;
//
// default:
// if (prop.expr.value) {
// sourceBuffer.joinString(' ' + prop.name + '="' + prop.expr.value + '"');
// }
// else {
// sourceBuffer.joinRaw('attrFilter("' + prop.name + '", '
// + compileExprSource.expr(prop.expr)
// + ')'
// );
// }
// break;
// }
// });
//
// sourceBuffer.joinString(isClose ? '/>' : '>');
// },
// /* eslint-enable max-params */
//
// /**
// * 编译元素闭合
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {string} tagName 标签名
// */
// tagEnd: function (sourceBuffer, tagName) {
// if (!autoCloseTags[tagName]) {
// sourceBuffer.joinString('</' + tagName + '>');
// }
//
// if (tagName === 'select') {
// sourceBuffer.addRaw('$selectValue = null;');
// }
//
// if (tagName === 'option') {
// sourceBuffer.addRaw('$optionValue = null;');
// }
// },
//
// /**
// * 编译元素内容
// *
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {ANode} aNode 元素的抽象节点信息
// * @param {Component} owner 所属组件实例环境
// */
// inner: function (sourceBuffer, aNode, owner) {
// // inner content
// if (aNode.tagName === 'textarea') {
// var valueProp = aNode.props.get('value');
// if (valueProp) {
// sourceBuffer.joinRaw('escapeHTML('
// + compileExprSource.expr(valueProp.expr)
// + ')'
// );
// }
//
// return;
// }
//
// var htmlDirective = aNode.directives.get('html');
// if (htmlDirective) {
// sourceBuffer.joinExpr(htmlDirective.value);
// }
// else {
// /* eslint-disable no-use-before-define */
// each(aNode.children, function (aNodeChild) {
// sourceBuffer.addRaw(aNodeCompiler.compile(aNodeChild, sourceBuffer, owner));
// });
// /* eslint-enable no-use-before-define */
// }
// }
// };
//
// /**
// * ANode 的编译方法集合对象
// *
// * @inner
// */
// var aNodeCompiler = {
//
// /**
// * 编译节点
// *
// * @param {ANode} aNode 抽象节点
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// */
// compile: function (aNode, sourceBuffer, owner, extra) {
// extra = extra || {};
// var compileMethod = 'compileElement';
//
// if (aNode.isText) {
// compileMethod = 'compileText';
// }
// else if (aNode.directives.get('if')) {
// compileMethod = 'compileIf';
// }
// else if (aNode.directives.get('for')) {
// compileMethod = 'compileFor';
// }
// else if (aNode.tagName === 'slot') {
// compileMethod = 'compileSlot';
// }
// else if (aNode.tagName === 'template') {
// compileMethod = 'compileTemplate';
// }
// else {
// var ComponentType = owner.components[aNode.tagName];
// if (ComponentType) {
// compileMethod = 'compileComponent';
// extra.ComponentClass = ComponentType;
// }
// }
//
// aNodeCompiler[compileMethod](aNode, sourceBuffer, owner, extra);
// },
//
// /**
// * 编译文本节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// */
// compileText: function (aNode, sourceBuffer) {
// var value = aNode.textExpr.value;
//
// if (value == null) {
// sourceBuffer.joinString('<!--s-text:' + aNode.text + '-->');
// sourceBuffer.joinExpr(aNode.textExpr);
// sourceBuffer.joinString('<!--/s-text-->');
// }
// else {
// sourceBuffer.joinString(value);
// }
// },
//
// /**
// * 编译template节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileTemplate: function (aNode, sourceBuffer, owner) {
// sourceBuffer.joinString(serializeStump('tpl'));
// elementSourceCompiler.inner(sourceBuffer, aNode, owner);
// sourceBuffer.joinString(serializeStumpEnd('tpl'));
// },
//
// /**
// * 编译 if 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileIf: function (aNode, sourceBuffer, owner) {
// sourceBuffer.addRaw('(function () {');
//
// sourceBuffer.joinString(serializeStump('if', serializeANode(aNode)));
//
// sourceBuffer.addRaw('var ifIndex = null;');
//
// // for ifIndex
// var ifDirective = aNode.directives.get('if');
// sourceBuffer.addRaw('if (' + compileExprSource.expr(ifDirective.value) + ') {');
// sourceBuffer.addRaw(' ifIndex = -1;');
// sourceBuffer.addRaw('}');
// each(aNode.elses, function (elseANode, index) {
// var elifDirective = elseANode.directives.get('elif');
// if (elifDirective) {
// sourceBuffer.addRaw('else if (' + compileExprSource.expr(elifDirective.value) + ') {');
// }
// else {
// sourceBuffer.addRaw('else {');
// }
//
// sourceBuffer.addRaw(' ifIndex = ' + index + ';');
// sourceBuffer.addRaw('}');
// });
//
// sourceBuffer.addRaw('if (ifIndex != null) {');
// sourceBuffer.joinRaw('\"<!--\" + ifIndex + \"-->\"');
// sourceBuffer.addRaw('}');
//
// // for output main if html
// sourceBuffer.addRaw('if (ifIndex === -1) {');
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// rinseANode(aNode),
// sourceBuffer,
// owner
// )
// );
// sourceBuffer.addRaw('}');
//
// // for output else html
// each(aNode.elses, function (elseANode, index) {
// var elifDirective = elseANode.directives.get('elif');
// sourceBuffer.addRaw(elifDirective ? 'else if (ifIndex === ' + index + ') {' : 'else {');
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// rinseANode(elseANode),
// sourceBuffer,
// owner
// )
// );
// sourceBuffer.addRaw('}');
// });
//
// sourceBuffer.joinString(serializeStumpEnd('if'));
// sourceBuffer.addRaw('})();');
//
//
// /**
// * 清洗 if aNode,返回纯净无 if 指令的 aNode
// *
// * @param {ANode} ifANode 节点对象
// * @return {ANode}
// */
// function rinseANode(ifANode) {
// var result = createANode({
// children: ifANode.children,
// props: ifANode.props,
// events: ifANode.events,
// tagName: ifANode.tagName,
// directives: (new IndexedList()).concat(ifANode.directives)
// });
// result.directives.remove('if');
// result.directives.remove('elif');
// result.directives.remove('else');
//
// return result;
// }
// },
//
// /**
// * 编译 for 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileFor: function (aNode, sourceBuffer, owner) {
// var forElementANode = createANode({
// children: aNode.children,
// props: aNode.props,
// events: aNode.events,
// tagName: aNode.tagName,
// directives: (new IndexedList()).concat(aNode.directives)
// });
// forElementANode.directives.remove('for');
//
// var forDirective = aNode.directives.get('for');
// var itemName = forDirective.item.raw;
// var indexName = forDirective.index.raw;
// var listName = compileExprSource.dataAccess(forDirective.list);
//
// if (indexName === '$index') {
// indexName = guid();
// }
//
// // start stump
// sourceBuffer.joinString(serializeStump('for', serializeANode(aNode)));
//
// sourceBuffer.addRaw('for ('
// + 'var ' + indexName + ' = 0; '
// + indexName + ' < ' + listName + '.length; '
// + indexName + '++) {'
// );
// sourceBuffer.addRaw('componentCtx.data.' + indexName + '=' + indexName + ';');
// sourceBuffer.addRaw('componentCtx.data.' + itemName + '= ' + listName + '[' + indexName + '];');
// sourceBuffer.addRaw(
// aNodeCompiler.compile(
// forElementANode,
// sourceBuffer,
// owner
// )
// );
// sourceBuffer.addRaw('}');
//
// // stop stump
// sourceBuffer.joinString(serializeStumpEnd('for'));
// },
//
// /**
// * 编译 slot 节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// */
// compileSlot: function (aNode, sourceBuffer, owner) {
// var nameProp = aNode.props.get('name');
// var name = nameProp ? nameProp.raw : '____';
// var isInserted = 0;
// var children = aNode.children;
//
// if (owner.aNode.givenSlots[name]) {
// isInserted = 1;
// children = owner.aNode.givenSlots[name];
// owner = owner.owner;
// }
//
// var stumpText = (!isInserted ? '!' : '')
// + serializeANode({
// tagName: aNode.tagName,
// vars: aNode.vars,
// props: aNode.props,
// directives: aNode.directives
// });
//
//
//
// sourceBuffer.joinString(serializeStump('slot', stumpText));
//
// if (isInserted) {
// sourceBuffer.addRaw('var _slotCtx = componentCtx.owner;');
// }
// else {
// sourceBuffer.addRaw('var _slotCtx = componentCtx;');
// }
//
// if (aNode.vars) {
// sourceBuffer.addRaw('_slotCtx = {data: {}, filters: _slotCtx.filters, callFilter: _slotCtx.callFilter};');
// each(aNode.vars, function (varItem) {
// sourceBuffer.addRaw(
// '_slotCtx.data["' + varItem.name + '"] = '
// + compileExprSource.expr(varItem.expr)
// + ';'
// );
// });
// }
//
// sourceBuffer.addRaw('(function (componentCtx) {');
//
//
// each(children, function (aNodeChild) {
// sourceBuffer.addRaw(aNodeCompiler.compile(aNodeChild, sourceBuffer, owner));
// });
//
//
// sourceBuffer.addRaw('})(_slotCtx);');
// sourceBuffer.addRaw('_slotCtx = null;');
//
// sourceBuffer.joinString(serializeStumpEnd('slot'));
// },
//
// /**
// * 编译普通节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// */
// compileElement: function (aNode, sourceBuffer, owner, extra) {
// extra = extra || {};
// if (aNode.tagName === 'option'
// && !aNode.props.get('value')
// && aNode.children[0]
// ) {
// aNode.props.push({
// name: 'value',
// expr: aNode.children[0].textExpr
// });
// }
//
// elementSourceCompiler.tagStart(
// sourceBuffer,
// aNode.tagName,
// aNode.props,
// aNode.props,
// aNode.events,
// aNode,
// extra.prop
// );
//
// elementSourceCompiler.inner(sourceBuffer, aNode, owner);
// elementSourceCompiler.tagEnd(sourceBuffer, aNode.tagName);
// },
//
// /**
// * 编译组件节点
// *
// * @param {ANode} aNode 节点对象
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Component} owner 所属组件实例环境
// * @param {Object} extra 编译所需的一些额外信息
// * @param {Function} extra.ComponentClass 对应组件类
// */
// compileComponent: function (aNode, sourceBuffer, owner, extra) {
// var ComponentClass = extra.ComponentClass;
// var component = new ComponentClass({
// aNode: aNode,
// owner: owner,
// subTag: aNode.tagName
// });
//
// var givenData = [];
//
// postComponentBinds(aNode.props);
// component.binds.each(function (prop) {
// givenData.push(
// compileExprSource.stringLiteralize(prop.name)
// + ':'
// + compileExprSource.expr(prop.expr)
// );
// });
//
// sourceBuffer.addRaw('html += (');
// sourceBuffer.addRendererStart();
// compileComponentSource(sourceBuffer, component, extra && extra.prop);
// sourceBuffer.addRendererEnd();
// sourceBuffer.addRaw(')({' + givenData.join(',\n') + '}, componentCtx);');
// }
// };
//
// /* eslint-disable guard-for-in */
//
// /**
// * 生成组件 renderer 时 ctx 对象构建的代码
// *
// * @inner
// * @param {CompileSourceBuffer} sourceBuffer 编译源码的中间buffer
// * @param {Object} component 组件实例
// * @param {string?} extraProp 额外的属性串
// */
// function compileComponentSource(sourceBuffer, component, extraProp) {
// sourceBuffer.addRaw(genComponentContextCode(component));
// sourceBuffer.addRaw('componentCtx.owner = parentCtx;');
// sourceBuffer.addRaw('data = extend(componentCtx.data, data);');
// sourceBuffer.addRaw('for (var $i = 0; $i < componentCtx.computedNames.length; $i++) {');
// sourceBuffer.addRaw('var $computedName = componentCtx.computedNames[$i];');
// sourceBuffer.addRaw('data[$computedName] = componentCtx.computed[$computedName]();');
// sourceBuffer.addRaw('}');
//
// extraProp = extraProp || '';
// if (component.subTag) {
// extraProp += ' s-component="' + component.subTag + '"';
// }
//
// var refDirective = component.aNode.directives.get('ref');
// if (refDirective) {
// extraProp += ' s-ref="' + refDirective.value.raw + '"';
// }
//
// var eventDeclarations = [];
// for (var key in component.listeners) {
// each(component.listeners[key], function (listener) {
// if (listener.declaration) {
// eventDeclarations.push(listener.declaration);
// }
// });
// }
//
// elementSourceCompiler.tagStart(
// sourceBuffer,
// component.tagName,
// component.props,
// component.binds,
// eventDeclarations,
// component.aNode,
// extraProp,
// 1
// );
//
// if (!component.owner) {
// sourceBuffer.joinString('<!--s-data:');
// sourceBuffer.joinDataStringify();
// sourceBuffer.joinString('-->');
// }
//
// elementSourceCompiler.inner(sourceBuffer, component.aNode, component);
// elementSourceCompiler.tagEnd(sourceBuffer, component.tagName);
// }
//
// var stringifier = {
// obj: function (source) {
// var prefixComma;
// var result = '{';
//
// for (var key in source) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += compileExprSource.stringLiteralize(key) + ':' + stringifier.any(source[key]);
// }
//
// return result + '}';
// },
//
// arr: function (source) {
// var prefixComma;
// var result = '[';
//
// each(source, function (value) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringifier.any(value);
// });
//
// return result + ']';
// },
//
// str: function (source) {
// return compileExprSource.stringLiteralize(source);
// },
//
// date: function (source) {
// return 'new Date(' + source.getTime() + ')';
// },
//
// any: function (source) {
// switch (typeof source) {
// case 'string':
// return stringifier.str(source);
//
// case 'number':
// return '' + source;
//
// case 'boolean':
// return source ? 'true' : 'false';
//
// case 'object':
// if (!source) {
// return null;
// }
//
// if (source instanceof Array) {
// return stringifier.arr(source);
// }
//
// if (source instanceof Date) {
// return stringifier.date(source);
// }
//
// return stringifier.obj(source);
// }
//
// throw new Error('Cannot Stringify:' + source);
// }
// };
//
// /**
// * 生成组件 renderer 时 ctx 对象构建的代码
// *
// * @inner
// * @param {Object} component 组件实例
// * @return {string}
// */
// function genComponentContextCode(component) {
// var code = ['var componentCtx = {'];
//
// // filters
// code.push('filters: {');
// var filterCode = [];
// for (var key in component.filters) {
// var filter = component.filters[key];
//
// if (typeof filter === 'function') {
// filterCode.push(key + ': ' + filter.toString());
// }
// }
// code.push(filterCode.join(','));
// code.push('},');
//
// code.push(
// 'callFilter: function (name, args) {',
// ' var filter = this.filters[name] || DEFAULT_FILTERS[name];',
// ' if (typeof filter === "function") {',
// ' return filter.apply(this, args);',
// ' }',
// '},'
// );
//
// /* eslint-disable no-redeclare */
// // computed obj
// code.push('computed: {');
// var computedCode = [];
// for (var key in component.computed) {
// var computed = component.computed[key];
//
// if (typeof computed === 'function') {
// computedCode.push(key + ': '
// + computed.toString().replace(
// /this.data.get\(([^\)]+)\)/g,
// function (match, exprLiteral) {
// var exprStr = (new Function('return ' + exprLiteral))();
// var expr = parseExpr(exprStr);
//
// return compileExprSource.expr(expr);
// })
// );
// }
// }
// code.push(computedCode.join(','));
// code.push('},');
//
// // computed names
// code.push('computedNames: [');
// computedCode = [];
// for (var key in component.computed) {
// var computed = component.computed[key];
//
// if (typeof computed === 'function') {
// computedCode.push('"' + key + '"');
// }
// }
// code.push(computedCode.join(','));
// code.push('],');
// /* eslint-enable no-redeclare */
//
// // data
// code.push('data: ' + stringifier.any(component.data.get()) + ',');
//
// // tagName
// code.push('tagName: "' + component.tagName + '"');
// code.push('};');
//
// return code.join('\n');
// }
//
// /* eslint-enable guard-for-in */
//
// /* eslint-disable no-unused-vars */
// /* eslint-disable fecs-camelcase */
//
// /**
// * 组件编译的模板函数
// *
// * @inner
// */
// function componentCompilePreCode() {
// var $version = '3.3.0-beta.2';
//
// function extend(target, source) {
// if (source) {
// Object.keys(source).forEach(function (key) {
// target[key] = source[key];
// });
// }
//
// return target;
// }
//
// function each(array, iterator) {
// if (array && array.length > 0) {
// for (var i = 0, l = array.length; i < l; i++) {
// if (iterator(array[i], i) === false) {
// break;
// }
// }
// }
// }
//
// function contains(array, value) {
// var result;
// each(array, function (item) {
// result = item === value;
// return !result;
// });
//
// return result;
// }
//
// var HTML_ENTITY = {
// /* jshint ignore:start */
// '&': '&',
// '<': '<',
// '>': '>',
// '"': '"',
// /* eslint-disable quotes */
// "'": '''
// /* eslint-enable quotes */
// /* jshint ignore:end */
// };
//
// function htmlFilterReplacer(c) {
// return HTML_ENTITY[c];
// }
//
// function escapeHTML(source) {
// if (source == null) {
// return '';
// }
//
// return String(source).replace(/[&<>"']/g, htmlFilterReplacer);
// }
//
// var DEFAULT_FILTERS = {
// html: escapeHTML,
// url: encodeURIComponent,
// raw: function (source) {
// return source;
// },
// _class: function (source) {
// if (source instanceof Array) {
// return source.join(' ');
// }
//
// return source;
// },
// _style: function (source) {
// if (typeof source === 'object') {
// var result = '';
// if (source) {
// Object.keys(source).forEach(function (key) {
// result += key + ':' + source[key] + ';';
// });
// }
//
// return result;
// }
//
// return source || '';
// },
// _sep: function (source, sep) {
// return source ? sep + source : '';
// }
// };
//
// function attrFilter(name, value) {
// if (value) {
// return ' ' + name + '="' + value + '"';
// }
//
// return '';
// }
//
// function boolAttrFilter(name, value) {
// if (value && value !== 'false' && value !== '0') {
// return ' ' + name;
// }
//
// return '';
// }
//
// function stringLiteralize(source) {
// return '"'
// + source
// .replace(/\x5C/g, '\\\\')
// .replace(/"/g, '\\"')
// .replace(/\x0A/g, '\\n')
// .replace(/\x09/g, '\\t')
// .replace(/\x0D/g, '\\r')
// + '"';
// }
//
// var stringifier = {
// obj: function (source) {
// var prefixComma;
// var result = '{';
//
// Object.keys(source).forEach(function (key) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringLiteralize(key) + ':' + stringifier.any(source[key]);
// });
//
// return result + '}';
// },
//
// arr: function (source) {
// var prefixComma;
// var result = '[';
//
// each(source, function (value) {
// if (prefixComma) {
// result += ',';
// }
// prefixComma = 1;
//
// result += stringifier.any(value);
// });
//
// return result + ']';
// },
//
// str: function (source) {
// return stringLiteralize(source);
// },
//
// date: function (source) {
// return 'new Date(' + source.getTime() + ')';
// },
//
// any: function (source) {
// switch (typeof source) {
// case 'string':
// return stringifier.str(source);
//
// case 'number':
// return '' + source;
//
// case 'boolean':
// return source ? 'true' : 'false';
//
// case 'object':
// if (!source) {
// return null;
// }
//
// if (source instanceof Array) {
// return stringifier.arr(source);
// }
//
// if (source instanceof Date) {
// return stringifier.date(source);
// }
//
// return stringifier.obj(source);
// }
//
// throw new Error('Cannot Stringify:' + source);
// }
// };
// }
// /* eslint-enable no-unused-vars */
// /* eslint-enable fecs-camelcase */
//
// /**
// * 将组件编译成 render 方法的 js 源码
// *
// * @param {Function} ComponentClass 组件类
// * @return {string}
// */
// function compileJSSource(ComponentClass) {
// var sourceBuffer = new CompileSourceBuffer();
//
// sourceBuffer.addRendererStart();
// sourceBuffer.addRaw(
// componentCompilePreCode.toString()
// .split('\n')
// .slice(1)
// .join('\n')
// .replace(/\}\s*$/, '')
// );
//
// // 先初始化个实例,让模板编译成 ANode,并且能获得初始化数据
// var component = new ComponentClass();
//
// compileComponentSource(sourceBuffer, component);
// sourceBuffer.addRendererEnd();
// return sourceBuffer.toCode();
// }
// #[end]
// exports = module.exports = compileJSSource;
/* eslint-disable no-unused-vars */
// var nextTick = require('./util/next-tick');
// var inherits = require('./util/inherits');
// var parseTemplate = require('./parser/parse-template');
// var parseExpr = require('./parser/parse-expr');
// var ExprType = require('./parser/expr-type');
// var LifeCycle = require('./view/life-cycle');
// var NodeType = require('./view/node-type');
// var Component = require('./view/component');
// var compileComponent = require('./view/compile-component');
// var defineComponent = require('./view/define-component');
// var emitDevtool = require('./util/emit-devtool');
// var compileJSSource = require('./view/compile-js-source');
// var DataTypes = require('./util/data-types');
var san = {
/**
* san版本号
*
* @type {string}
*/
version: '3.3.0-beta.2',
// #[begin] devtool
// /**
// * 是否开启调试。开启调试时 devtool 会工作
// *
// * @type {boolean}
// */
// debug: true,
// #[end]
// #[begin] ssr
// /**
// * 将组件类编译成 renderer 方法
// *
// * @param {Function} ComponentClass 组件类
// * @return {function(Object):string}
// */
// compileToRenderer: function (ComponentClass) {
// var renderer = ComponentClass.__ssrRenderer;
//
// if (!renderer) {
// var code = compileJSSource(ComponentClass);
// renderer = (new Function('return ' + code))();
// ComponentClass.__ssrRenderer = renderer;
// }
//
// return renderer;
// },
//
// /**
// * 将组件类编译成 renderer 方法的源文件
// *
// * @param {Function} ComponentClass 组件类
// * @return {string}
// */
// compileToSource: compileJSSource,
// #[end]
/**
* 组件基类
*
* @type {Function}
*/
Component: Component,
/**
* 创建组件类
*
* @param {Object} proto 组件类的方法表
* @return {Function}
*/
defineComponent: defineComponent,
/**
* 编译组件类。预解析template和components
*
* @param {Function} ComponentClass 组件类
*/
compileComponent: compileComponent,
/**
* 解析 template
*
* @inner
* @param {string} source template 源码
* @return {ANode}
*/
parseTemplate: parseTemplate,
/**
* 解析表达式
*
* @param {string} source 源码
* @return {Object}
*/
parseExpr: parseExpr,
/**
* 表达式类型枚举
*
* @const
* @type {Object}
*/
ExprType: ExprType,
/**
* 生命周期
*/
LifeCycle: LifeCycle,
/**
* 节点类型
*
* @const
* @type {Object}
*/
NodeType: NodeType,
/**
* 在下一个更新周期运行函数
*
* @param {Function} fn 要运行的函数
*/
nextTick: nextTick,
/**
* 构建类之间的继承关系
*
* @param {Function} subClass 子类函数
* @param {Function} superClass 父类函数
*/
inherits: inherits,
/**
* DataTypes
*
* @type {Object}
*/
DataTypes: DataTypes
};
// export
if (typeof exports === 'object' && typeof module === 'object') {
// For CommonJS
exports = module.exports = san;
}
else if (typeof define === 'function' && define.amd) {
// For AMD
define('san', [], san);
}
else {
// For <script src="..."
root.san = san;
}
// #[begin] devtool
// emitDevtool.start(san);
// #[end]
})(this);
|
{
"AD" : "CE",
"Africa/Abidjan_Z_abbreviated" : "(CI)",
"Africa/Abidjan_Z_short" : "GMT",
"Africa/Accra_Z_abbreviated" : "(GH)",
"Africa/Accra_Z_short" : "GMT",
"Africa/Addis_Ababa_Z_abbreviated" : "(ET)",
"Africa/Addis_Ababa_Z_short" : "EAT",
"Africa/Algiers_Z_abbreviated" : "(DZ)",
"Africa/Algiers_Z_short" : "WET",
"Africa/Asmara_Z_abbreviated" : "(ER)",
"Africa/Asmara_Z_short" : "EAT",
"Africa/Bamako_Z_abbreviated" : "(ML)",
"Africa/Bamako_Z_short" : "GMT",
"Africa/Bangui_Z_abbreviated" : "(CF)",
"Africa/Bangui_Z_short" : "WAT",
"Africa/Banjul_Z_abbreviated" : "(GM)",
"Africa/Banjul_Z_short" : "GMT",
"Africa/Bissau_Z_abbreviated" : "(GW)",
"Africa/Bissau_Z_short" : "GMT-۰۱:۰۰",
"Africa/Blantyre_Z_abbreviated" : "(MW)",
"Africa/Blantyre_Z_short" : "CAT",
"Africa/Brazzaville_Z_abbreviated" : "(CG)",
"Africa/Brazzaville_Z_short" : "WAT",
"Africa/Bujumbura_Z_abbreviated" : "(BI)",
"Africa/Bujumbura_Z_short" : "CAT",
"Africa/Cairo_Z_abbreviated" : "(EG)",
"Africa/Cairo_Z_short" : "EET",
"Africa/Casablanca_Z_abbreviated" : "(MA)",
"Africa/Casablanca_Z_short" : "WET",
"Africa/Conakry_Z_abbreviated" : "(GN)",
"Africa/Conakry_Z_short" : "GMT",
"Africa/Dakar_Z_abbreviated" : "(SN)",
"Africa/Dakar_Z_short" : "GMT",
"Africa/Dar_es_Salaam_Z_abbreviated" : "(TZ)",
"Africa/Dar_es_Salaam_Z_short" : "EAT",
"Africa/Djibouti_Z_abbreviated" : "(DJ)",
"Africa/Djibouti_Z_short" : "EAT",
"Africa/Douala_Z_abbreviated" : "(CM)",
"Africa/Douala_Z_short" : "WAT",
"Africa/El_Aaiun_Z_abbreviated" : "(EH)",
"Africa/El_Aaiun_Z_short" : "GMT-۰۱:۰۰",
"Africa/Freetown_Z_abbreviated" : "(SL)",
"Africa/Freetown_Z_short" : "GMT",
"Africa/Gaborone_Z_abbreviated" : "(BW)",
"Africa/Gaborone_Z_short" : "CAT",
"Africa/Harare_Z_abbreviated" : "(ZW)",
"Africa/Harare_Z_short" : "CAT",
"Africa/Johannesburg_Z_abbreviated" : "(ZA)",
"Africa/Johannesburg_Z_short" : "SAST",
"Africa/Juba_Z_abbreviated" : "(SD)",
"Africa/Juba_Z_short" : "CAT",
"Africa/Kampala_Z_abbreviated" : "(UG)",
"Africa/Kampala_Z_short" : "EAT",
"Africa/Khartoum_Z_abbreviated" : "(SD)",
"Africa/Khartoum_Z_short" : "CAT",
"Africa/Kigali_Z_abbreviated" : "(RW)",
"Africa/Kigali_Z_short" : "CAT",
"Africa/Kinshasa_Z_abbreviated" : "CD (Kinshasa)",
"Africa/Kinshasa_Z_short" : "WAT",
"Africa/Lagos_Z_abbreviated" : "(NG)",
"Africa/Lagos_Z_short" : "WAT",
"Africa/Libreville_Z_abbreviated" : "(GA)",
"Africa/Libreville_Z_short" : "WAT",
"Africa/Lome_Z_abbreviated" : "(TG)",
"Africa/Lome_Z_short" : "GMT",
"Africa/Luanda_Z_abbreviated" : "(AO)",
"Africa/Luanda_Z_short" : "WAT",
"Africa/Lusaka_Z_abbreviated" : "(ZM)",
"Africa/Lusaka_Z_short" : "CAT",
"Africa/Malabo_Z_abbreviated" : "(GQ)",
"Africa/Malabo_Z_short" : "WAT",
"Africa/Maputo_Z_abbreviated" : "(MZ)",
"Africa/Maputo_Z_short" : "CAT",
"Africa/Maseru_Z_abbreviated" : "(LS)",
"Africa/Maseru_Z_short" : "SAST",
"Africa/Mbabane_Z_abbreviated" : "(SZ)",
"Africa/Mbabane_Z_short" : "SAST",
"Africa/Mogadishu_Z_abbreviated" : "(SO)",
"Africa/Mogadishu_Z_short" : "EAT",
"Africa/Monrovia_Z_abbreviated" : "(LR)",
"Africa/Monrovia_Z_short" : "GMT-۰۰:۴۴:۳۰",
"Africa/Nairobi_Z_abbreviated" : "(KE)",
"Africa/Nairobi_Z_short" : "EAT",
"Africa/Ndjamena_Z_abbreviated" : "(TD)",
"Africa/Ndjamena_Z_short" : "WAT",
"Africa/Niamey_Z_abbreviated" : "(NE)",
"Africa/Niamey_Z_short" : "WAT",
"Africa/Nouakchott_Z_abbreviated" : "(MR)",
"Africa/Nouakchott_Z_short" : "GMT",
"Africa/Ouagadougou_Z_abbreviated" : "(BF)",
"Africa/Ouagadougou_Z_short" : "GMT",
"Africa/Porto-Novo_Z_abbreviated" : "(BJ)",
"Africa/Porto-Novo_Z_short" : "WAT",
"Africa/Sao_Tome_Z_abbreviated" : "(ST)",
"Africa/Sao_Tome_Z_short" : "GMT",
"Africa/Tripoli_Z_abbreviated" : "(LY)",
"Africa/Tripoli_Z_short" : "EET",
"Africa/Tunis_Z_abbreviated" : "(TN)",
"Africa/Tunis_Z_short" : "CET",
"Africa/Windhoek_Z_abbreviated" : "(NA)",
"Africa/Windhoek_Z_short" : "SAST",
"America/Anguilla_Z_abbreviated" : "(AI)",
"America/Anguilla_Z_short" : "AST",
"America/Antigua_Z_abbreviated" : "(AG)",
"America/Antigua_Z_short" : "AST",
"America/Araguaina_Z_abbreviated" : "BR (Araguaina)",
"America/Araguaina_Z_short" : "BRT",
"America/Argentina/Buenos_Aires_Z_abbreviated" : "AR (Buenos Aires)",
"America/Argentina/Buenos_Aires_Z_short" : "ART",
"America/Argentina/Catamarca_Z_abbreviated" : "AR (Catamarca)",
"America/Argentina/Catamarca_Z_short" : "ART",
"America/Argentina/Cordoba_Z_abbreviated" : "AR (Cordoba)",
"America/Argentina/Cordoba_Z_short" : "ART",
"America/Argentina/Jujuy_Z_abbreviated" : "AR (Jujuy)",
"America/Argentina/Jujuy_Z_short" : "ART",
"America/Argentina/La_Rioja_Z_abbreviated" : "AR (La Rioja)",
"America/Argentina/La_Rioja_Z_short" : "ART",
"America/Argentina/Mendoza_Z_abbreviated" : "AR (Mendoza)",
"America/Argentina/Mendoza_Z_short" : "ART",
"America/Argentina/Rio_Gallegos_Z_abbreviated" : "AR (Rio Gallegos)",
"America/Argentina/Rio_Gallegos_Z_short" : "ART",
"America/Argentina/Salta_Z_abbreviated" : "AR (Salta)",
"America/Argentina/Salta_Z_short" : "ART",
"America/Argentina/San_Juan_Z_abbreviated" : "AR (San Juan)",
"America/Argentina/San_Juan_Z_short" : "ART",
"America/Argentina/San_Luis_Z_abbreviated" : "AR (San Luis)",
"America/Argentina/San_Luis_Z_short" : "ART",
"America/Argentina/Tucuman_Z_abbreviated" : "AR (Tucuman)",
"America/Argentina/Tucuman_Z_short" : "ART",
"America/Argentina/Ushuaia_Z_abbreviated" : "AR (Ushuaia)",
"America/Argentina/Ushuaia_Z_short" : "ART",
"America/Aruba_Z_abbreviated" : "(AW)",
"America/Aruba_Z_short" : "AST",
"America/Asuncion_Z_abbreviated" : "(PY)",
"America/Asuncion_Z_short" : "PYT",
"America/Bahia_Banderas_Z_abbreviated" : "MX (Bahia Banderas)",
"America/Bahia_Banderas_Z_short" : "PST",
"America/Bahia_Z_abbreviated" : "BR (Bahia)",
"America/Bahia_Z_short" : "BRT",
"America/Barbados_Z_abbreviated" : "(BB)",
"America/Barbados_Z_short" : "AST",
"America/Belem_Z_abbreviated" : "BR (Belem)",
"America/Belem_Z_short" : "BRT",
"America/Belize_Z_abbreviated" : "(BZ)",
"America/Belize_Z_short" : "CST",
"America/Blanc-Sablon_Z_abbreviated" : "CA (Blanc-Sablon)",
"America/Blanc-Sablon_Z_short" : "AST",
"America/Boa_Vista_Z_abbreviated" : "BR (Boa Vista)",
"America/Boa_Vista_Z_short" : "AMT",
"America/Bogota_Z_abbreviated" : "(CO)",
"America/Bogota_Z_short" : "COT",
"America/Boise_Z_abbreviated" : "US (Boise)",
"America/Boise_Z_short" : "MST",
"America/Cambridge_Bay_Z_abbreviated" : "CA (Cambridge Bay)",
"America/Cambridge_Bay_Z_short" : "MST",
"America/Campo_Grande_Z_abbreviated" : "BR (Campo Grande)",
"America/Campo_Grande_Z_short" : "AMT",
"America/Cancun_Z_abbreviated" : "MX (Cancun)",
"America/Cancun_Z_short" : "CST",
"America/Caracas_Z_abbreviated" : "(VE)",
"America/Caracas_Z_short" : "VET",
"America/Cayenne_Z_abbreviated" : "(GF)",
"America/Cayenne_Z_short" : "GFT",
"America/Cayman_Z_abbreviated" : "(KY)",
"America/Cayman_Z_short" : "EST",
"America/Chicago_Z_abbreviated" : "US (Chicago)",
"America/Chicago_Z_short" : "CST",
"America/Chihuahua_Z_abbreviated" : "MX (Chihuahua)",
"America/Chihuahua_Z_short" : "CST",
"America/Costa_Rica_Z_abbreviated" : "(CR)",
"America/Costa_Rica_Z_short" : "CST",
"America/Cuiaba_Z_abbreviated" : "BR (Cuiaba)",
"America/Cuiaba_Z_short" : "AMT",
"America/Curacao_Z_abbreviated" : "(AN)",
"America/Curacao_Z_short" : "AST",
"America/Danmarkshavn_Z_abbreviated" : "GL (Danmarkshavn)",
"America/Danmarkshavn_Z_short" : "WGT",
"America/Denver_Z_abbreviated" : "US (Denver)",
"America/Denver_Z_short" : "MST",
"America/Detroit_Z_abbreviated" : "US (Detroit)",
"America/Detroit_Z_short" : "EST",
"America/Dominica_Z_abbreviated" : "(DM)",
"America/Dominica_Z_short" : "AST",
"America/Edmonton_Z_abbreviated" : "CA (Edmonton)",
"America/Edmonton_Z_short" : "MST",
"America/Eirunepe_Z_abbreviated" : "BR (Eirunepe)",
"America/Eirunepe_Z_short" : "ACT (Acre)",
"America/El_Salvador_Z_abbreviated" : "(SV)",
"America/El_Salvador_Z_short" : "CST",
"America/Fortaleza_Z_abbreviated" : "BR (Fortaleza)",
"America/Fortaleza_Z_short" : "BRT",
"America/Goose_Bay_Z_abbreviated" : "CA (Goose Bay)",
"America/Goose_Bay_Z_short" : "AST",
"America/Grand_Turk_Z_abbreviated" : "(TC)",
"America/Grand_Turk_Z_short" : "EST",
"America/Grenada_Z_abbreviated" : "(GD)",
"America/Grenada_Z_short" : "AST",
"America/Guadeloupe_Z_abbreviated" : "(GP)",
"America/Guadeloupe_Z_short" : "AST",
"America/Guatemala_Z_abbreviated" : "(GT)",
"America/Guatemala_Z_short" : "CST",
"America/Guayaquil_Z_abbreviated" : "EC (Guayaquil)",
"America/Guayaquil_Z_short" : "ECT",
"America/Guyana_Z_abbreviated" : "(GY)",
"America/Guyana_Z_short" : "GYT",
"America/Halifax_Z_abbreviated" : "CA (Halifax)",
"America/Halifax_Z_short" : "AST",
"America/Havana_Z_abbreviated" : "(CU)",
"America/Havana_Z_short" : "CST (CU)",
"America/Hermosillo_Z_abbreviated" : "MX (Hermosillo)",
"America/Hermosillo_Z_short" : "PST",
"America/Indiana/Indianapolis_Z_abbreviated" : "US (Indianapolis)",
"America/Indiana/Indianapolis_Z_short" : "EST",
"America/Indiana/Knox_Z_abbreviated" : "US (Knox, Indiana)",
"America/Indiana/Knox_Z_short" : "CST",
"America/Indiana/Marengo_Z_abbreviated" : "US (Marengo, Indiana)",
"America/Indiana/Marengo_Z_short" : "EST",
"America/Indiana/Petersburg_Z_abbreviated" : "US (Petersburg, Indiana)",
"America/Indiana/Petersburg_Z_short" : "CST",
"America/Indiana/Tell_City_Z_abbreviated" : "US (Tell City, Indiana)",
"America/Indiana/Tell_City_Z_short" : "EST",
"America/Indiana/Vevay_Z_abbreviated" : "US (Vevay, Indiana)",
"America/Indiana/Vevay_Z_short" : "EST",
"America/Indiana/Vincennes_Z_abbreviated" : "US (Vincennes, Indiana)",
"America/Indiana/Vincennes_Z_short" : "EST",
"America/Indiana/Winamac_Z_abbreviated" : "US (Winamac, Indiana)",
"America/Indiana/Winamac_Z_short" : "EST",
"America/Iqaluit_Z_abbreviated" : "CA (Iqaluit)",
"America/Iqaluit_Z_short" : "EST",
"America/Jamaica_Z_abbreviated" : "(JM)",
"America/Jamaica_Z_short" : "EST",
"America/Juneau_Z_abbreviated" : "US (Juneau)",
"America/Juneau_Z_short" : "PST",
"America/Kentucky/Louisville_Z_abbreviated" : "US (Louisville)",
"America/Kentucky/Louisville_Z_short" : "EST",
"America/Kentucky/Monticello_Z_abbreviated" : "US (Monticello, Kentucky)",
"America/Kentucky/Monticello_Z_short" : "CST",
"America/La_Paz_Z_abbreviated" : "(BO)",
"America/La_Paz_Z_short" : "BOT",
"America/Lima_Z_abbreviated" : "(PE)",
"America/Lima_Z_short" : "PET",
"America/Los_Angeles_Z_abbreviated" : "US (Los Angeles)",
"America/Los_Angeles_Z_short" : "PST",
"America/Maceio_Z_abbreviated" : "BR (Maceio)",
"America/Maceio_Z_short" : "BRT",
"America/Managua_Z_abbreviated" : "(NI)",
"America/Managua_Z_short" : "CST",
"America/Manaus_Z_abbreviated" : "BR (Manaus)",
"America/Manaus_Z_short" : "AMT",
"America/Martinique_Z_abbreviated" : "(MQ)",
"America/Martinique_Z_short" : "AST",
"America/Matamoros_Z_abbreviated" : "MX (Matamoros)",
"America/Matamoros_Z_short" : "CST",
"America/Mazatlan_Z_abbreviated" : "MX (Mazatlan)",
"America/Mazatlan_Z_short" : "PST",
"America/Menominee_Z_abbreviated" : "US (Menominee)",
"America/Menominee_Z_short" : "EST",
"America/Merida_Z_abbreviated" : "MX (Merida)",
"America/Merida_Z_short" : "CST",
"America/Mexico_City_Z_abbreviated" : "MX (Mexico City)",
"America/Mexico_City_Z_short" : "CST",
"America/Miquelon_Z_abbreviated" : "(PM)",
"America/Miquelon_Z_short" : "AST",
"America/Moncton_Z_abbreviated" : "CA (Moncton)",
"America/Moncton_Z_short" : "AST",
"America/Monterrey_Z_abbreviated" : "MX (Monterrey)",
"America/Monterrey_Z_short" : "CST",
"America/Montevideo_Z_abbreviated" : "(UY)",
"America/Montevideo_Z_short" : "UYT",
"America/Montserrat_Z_abbreviated" : "(MS)",
"America/Montserrat_Z_short" : "AST",
"America/Nassau_Z_abbreviated" : "(BS)",
"America/Nassau_Z_short" : "EST",
"America/New_York_Z_abbreviated" : "US (New York)",
"America/New_York_Z_short" : "EST",
"America/Noronha_Z_abbreviated" : "BR (Noronha)",
"America/Noronha_Z_short" : "FNT",
"America/North_Dakota/Beulah_Z_abbreviated" : "US (Beulah)",
"America/North_Dakota/Beulah_Z_short" : "MST",
"America/North_Dakota/Center_Z_abbreviated" : "US (Center, North Dakota)",
"America/North_Dakota/Center_Z_short" : "MST",
"America/North_Dakota/New_Salem_Z_abbreviated" : "US (New Salem, North Dakota)",
"America/North_Dakota/New_Salem_Z_short" : "MST",
"America/Ojinaga_Z_abbreviated" : "MX (Ojinaga)",
"America/Ojinaga_Z_short" : "CST",
"America/Panama_Z_abbreviated" : "(PA)",
"America/Panama_Z_short" : "EST",
"America/Pangnirtung_Z_abbreviated" : "CA (Pangnirtung)",
"America/Pangnirtung_Z_short" : "AST",
"America/Paramaribo_Z_abbreviated" : "(SR)",
"America/Paramaribo_Z_short" : "NEGT",
"America/Phoenix_Z_abbreviated" : "US (Phoenix)",
"America/Phoenix_Z_short" : "MST",
"America/Port-au-Prince_Z_abbreviated" : "(HT)",
"America/Port-au-Prince_Z_short" : "EST",
"America/Port_of_Spain_Z_abbreviated" : "(TT)",
"America/Port_of_Spain_Z_short" : "AST",
"America/Porto_Velho_Z_abbreviated" : "BR (Porto Velho)",
"America/Porto_Velho_Z_short" : "AMT",
"America/Puerto_Rico_Z_abbreviated" : "(PR)",
"America/Puerto_Rico_Z_short" : "AST",
"America/Rankin_Inlet_Z_abbreviated" : "CA (Rankin Inlet)",
"America/Rankin_Inlet_Z_short" : "CST",
"America/Recife_Z_abbreviated" : "BR (Recife)",
"America/Recife_Z_short" : "BRT",
"America/Regina_Z_abbreviated" : "CA (Regina)",
"America/Regina_Z_short" : "CST",
"America/Resolute_Z_abbreviated" : "CA (Resolute)",
"America/Resolute_Z_short" : "CST",
"America/Rio_Branco_Z_abbreviated" : "BR (Rio Branco)",
"America/Rio_Branco_Z_short" : "ACT (Acre)",
"America/Santa_Isabel_Z_abbreviated" : "MX (Santa Isabel)",
"America/Santa_Isabel_Z_short" : "PST",
"America/Santarem_Z_abbreviated" : "BR (Santarem)",
"America/Santarem_Z_short" : "AMT",
"America/Santiago_Z_abbreviated" : "CL (Santiago)",
"America/Santiago_Z_short" : "CLST",
"America/Santo_Domingo_Z_abbreviated" : "(DO)",
"America/Santo_Domingo_Z_short" : "GMT-۰۴:۳۰",
"America/Sao_Paulo_Z_abbreviated" : "BR (Sao Paulo)",
"America/Sao_Paulo_Z_short" : "BRT",
"America/St_Johns_Z_abbreviated" : "CA (St. John's)",
"America/St_Johns_Z_short" : "NST",
"America/St_Kitts_Z_abbreviated" : "(KN)",
"America/St_Kitts_Z_short" : "AST",
"America/St_Lucia_Z_abbreviated" : "(LC)",
"America/St_Lucia_Z_short" : "AST",
"America/St_Thomas_Z_abbreviated" : "(VI)",
"America/St_Thomas_Z_short" : "AST",
"America/St_Vincent_Z_abbreviated" : "(VC)",
"America/St_Vincent_Z_short" : "AST",
"America/Tegucigalpa_Z_abbreviated" : "(HN)",
"America/Tegucigalpa_Z_short" : "CST",
"America/Tijuana_Z_abbreviated" : "MX (Tijuana)",
"America/Tijuana_Z_short" : "PST",
"America/Toronto_Z_abbreviated" : "CA (Toronto)",
"America/Toronto_Z_short" : "EST",
"America/Tortola_Z_abbreviated" : "(VG)",
"America/Tortola_Z_short" : "AST",
"America/Vancouver_Z_abbreviated" : "CA (Vancouver)",
"America/Vancouver_Z_short" : "PST",
"America/Winnipeg_Z_abbreviated" : "CA (Winnipeg)",
"America/Winnipeg_Z_short" : "CST",
"Antarctica/Casey_Z_abbreviated" : "AQ (Casey)",
"Antarctica/Casey_Z_short" : "AWST",
"Antarctica/Davis_Z_abbreviated" : "AQ (Davis)",
"Antarctica/Davis_Z_short" : "DAVT",
"Antarctica/DumontDUrville_Z_abbreviated" : "AQ (Dumont d'Urville)",
"Antarctica/DumontDUrville_Z_short" : "DDUT",
"Antarctica/Macquarie_Z_abbreviated" : "AQ (Macquarie)",
"Antarctica/Macquarie_Z_short" : "AEDT",
"Antarctica/McMurdo_Z_abbreviated" : "AQ (McMurdo)",
"Antarctica/McMurdo_Z_short" : "NZST",
"Antarctica/Palmer_Z_abbreviated" : "AQ (Palmer)",
"Antarctica/Palmer_Z_short" : "ART",
"Antarctica/Rothera_Z_abbreviated" : "AQ (Rothera)",
"Antarctica/Rothera_Z_short" : "ROTT",
"Antarctica/Syowa_Z_abbreviated" : "AQ (Syowa)",
"Antarctica/Syowa_Z_short" : "SYOT",
"Antarctica/Vostok_Z_abbreviated" : "AQ (Vostok)",
"Antarctica/Vostok_Z_short" : "VOST",
"Asia/Aden_Z_abbreviated" : "(YE)",
"Asia/Aden_Z_short" : "AST (SA)",
"Asia/Almaty_Z_abbreviated" : "KZ (Almaty)",
"Asia/Almaty_Z_short" : "ALMT",
"Asia/Amman_Z_abbreviated" : "(JO)",
"Asia/Amman_Z_short" : "EET",
"Asia/Anadyr_Z_abbreviated" : "RU (Anadyr)",
"Asia/Anadyr_Z_short" : "ANAT",
"Asia/Aqtau_Z_abbreviated" : "KZ (Aqtau)",
"Asia/Aqtau_Z_short" : "SHET",
"Asia/Aqtobe_Z_abbreviated" : "KZ (Aqtobe)",
"Asia/Aqtobe_Z_short" : "AKTT",
"Asia/Ashgabat_Z_abbreviated" : "(TM)",
"Asia/Ashgabat_Z_short" : "ASHT",
"Asia/Baghdad_Z_abbreviated" : "(IQ)",
"Asia/Baghdad_Z_short" : "AST (SA)",
"Asia/Bahrain_Z_abbreviated" : "(BH)",
"Asia/Bahrain_Z_short" : "GST",
"Asia/Baku_Z_abbreviated" : "(AZ)",
"Asia/Baku_Z_short" : "BAKT",
"Asia/Bangkok_Z_abbreviated" : "(TH)",
"Asia/Bangkok_Z_short" : "ICT",
"Asia/Beirut_Z_abbreviated" : "(LB)",
"Asia/Beirut_Z_short" : "EET",
"Asia/Bishkek_Z_abbreviated" : "(KG)",
"Asia/Bishkek_Z_short" : "FRUT",
"Asia/Brunei_Z_abbreviated" : "(BN)",
"Asia/Brunei_Z_short" : "BNT",
"Asia/Choibalsan_Z_abbreviated" : "MN (Choibalsan)",
"Asia/Choibalsan_Z_short" : "ULAT",
"Asia/Chongqing_Z_abbreviated" : "CN (Chongqing)",
"Asia/Chongqing_Z_short" : "LONT",
"Asia/Colombo_Z_abbreviated" : "(LK)",
"Asia/Colombo_Z_short" : "IST",
"Asia/Damascus_Z_abbreviated" : "(SY)",
"Asia/Damascus_Z_short" : "EET",
"Asia/Dhaka_Z_abbreviated" : "(BD)",
"Asia/Dhaka_Z_short" : "DACT",
"Asia/Dili_Z_abbreviated" : "(TL)",
"Asia/Dili_Z_short" : "TLT",
"Asia/Dubai_Z_abbreviated" : "(AE)",
"Asia/Dubai_Z_short" : "GST",
"Asia/Dushanbe_Z_abbreviated" : "(TJ)",
"Asia/Dushanbe_Z_short" : "DUST",
"Asia/Gaza_Z_abbreviated" : "(PS)",
"Asia/Gaza_Z_short" : "IST (IL)",
"Asia/Harbin_Z_abbreviated" : "CN (Harbin)",
"Asia/Harbin_Z_short" : "CHAT",
"Asia/Hebron_Z_abbreviated" : "(PS)",
"Asia/Hebron_Z_short" : "IST (IL)",
"Asia/Ho_Chi_Minh_Z_abbreviated" : "(VN)",
"Asia/Ho_Chi_Minh_Z_short" : "ICT",
"Asia/Hong_Kong_Z_abbreviated" : "(HK)",
"Asia/Hong_Kong_Z_short" : "HKT",
"Asia/Hovd_Z_abbreviated" : "MN (Hovd)",
"Asia/Hovd_Z_short" : "HOVT",
"Asia/Irkutsk_Z_abbreviated" : "RU (Irkutsk)",
"Asia/Irkutsk_Z_short" : "IRKT",
"Asia/Jakarta_Z_abbreviated" : "ID (Jakarta)",
"Asia/Jakarta_Z_short" : "WIT",
"Asia/Jerusalem_Z_abbreviated" : "(IL)",
"Asia/Jerusalem_Z_short" : "IST (IL)",
"Asia/Kabul_Z_abbreviated" : "(افغانستان)",
"Asia/Kabul_Z_short" : "AFT",
"Asia/Kamchatka_Z_abbreviated" : "RU (Kamchatka)",
"Asia/Kamchatka_Z_short" : "PETT",
"Asia/Karachi_Z_abbreviated" : "(PK)",
"Asia/Karachi_Z_short" : "KART",
"Asia/Kashgar_Z_abbreviated" : "CN (Kashgar)",
"Asia/Kashgar_Z_short" : "KAST",
"Asia/Kathmandu_Z_abbreviated" : "(NP)",
"Asia/Kathmandu_Z_short" : "NPT",
"Asia/Kolkata_Z_abbreviated" : "(IN)",
"Asia/Kolkata_Z_short" : "IST",
"Asia/Krasnoyarsk_Z_abbreviated" : "RU (Krasnoyarsk)",
"Asia/Krasnoyarsk_Z_short" : "KRAT",
"Asia/Kuala_Lumpur_Z_abbreviated" : "MY (Kuala Lumpur)",
"Asia/Kuala_Lumpur_Z_short" : "MALT",
"Asia/Kuching_Z_abbreviated" : "MY (Kuching)",
"Asia/Kuching_Z_short" : "BORT",
"Asia/Kuwait_Z_abbreviated" : "(KW)",
"Asia/Kuwait_Z_short" : "AST (SA)",
"Asia/Macau_Z_abbreviated" : "(MO)",
"Asia/Macau_Z_short" : "MOT",
"Asia/Magadan_Z_abbreviated" : "RU (Magadan)",
"Asia/Magadan_Z_short" : "MAGT",
"Asia/Manila_Z_abbreviated" : "(PH)",
"Asia/Manila_Z_short" : "PHT",
"Asia/Muscat_Z_abbreviated" : "(OM)",
"Asia/Muscat_Z_short" : "GST",
"Asia/Nicosia_Z_abbreviated" : "(CY)",
"Asia/Nicosia_Z_short" : "EET",
"Asia/Novokuznetsk_Z_abbreviated" : "RU (Novokuznetsk)",
"Asia/Novokuznetsk_Z_short" : "KRAT",
"Asia/Novosibirsk_Z_abbreviated" : "RU (Novosibirsk)",
"Asia/Novosibirsk_Z_short" : "NOVT",
"Asia/Omsk_Z_abbreviated" : "RU (Omsk)",
"Asia/Omsk_Z_short" : "OMST",
"Asia/Oral_Z_abbreviated" : "KZ (Oral)",
"Asia/Oral_Z_short" : "URAT",
"Asia/Phnom_Penh_Z_abbreviated" : "(KH)",
"Asia/Phnom_Penh_Z_short" : "ICT",
"Asia/Pontianak_Z_abbreviated" : "ID (Pontianak)",
"Asia/Pontianak_Z_short" : "CIT",
"Asia/Qatar_Z_abbreviated" : "(QA)",
"Asia/Qatar_Z_short" : "GST",
"Asia/Qyzylorda_Z_abbreviated" : "KZ (Qyzylorda)",
"Asia/Qyzylorda_Z_short" : "KIZT",
"Asia/Rangoon_Z_abbreviated" : "(MM)",
"Asia/Rangoon_Z_short" : "MMT",
"Asia/Riyadh87_Z_abbreviated" : "(Asia/Riyadh87)",
"Asia/Riyadh87_Z_short" : "GMT+۰۳:۰۷:۰۴",
"Asia/Riyadh88_Z_abbreviated" : "(Asia/Riyadh88)",
"Asia/Riyadh88_Z_short" : "GMT+۰۳:۰۷:۰۴",
"Asia/Riyadh89_Z_abbreviated" : "(Asia/Riyadh89)",
"Asia/Riyadh89_Z_short" : "GMT+۰۳:۰۷:۰۴",
"Asia/Riyadh_Z_abbreviated" : "(SA)",
"Asia/Riyadh_Z_short" : "AST (SA)",
"Asia/Sakhalin_Z_abbreviated" : "RU (Sakhalin)",
"Asia/Sakhalin_Z_short" : "SAKT",
"Asia/Samarkand_Z_abbreviated" : "Ўзбекистон (Samarkand)",
"Asia/Samarkand_Z_short" : "SAMT (Samarkand)",
"Asia/Seoul_Z_abbreviated" : "(KR)",
"Asia/Seoul_Z_short" : "KST",
"Asia/Shanghai_Z_abbreviated" : "CN (Shanghai)",
"Asia/Shanghai_Z_short" : "CST (CN)",
"Asia/Singapore_Z_abbreviated" : "(SG)",
"Asia/Singapore_Z_short" : "SGT",
"Asia/Taipei_Z_abbreviated" : "(TW)",
"Asia/Taipei_Z_short" : "CST (TW)",
"Asia/Tbilisi_Z_abbreviated" : "(GE)",
"Asia/Tbilisi_Z_short" : "TBIT",
"Asia/Tehran_Z_abbreviated" : "(IR)",
"Asia/Tehran_Z_short" : "IRST",
"Asia/Thimphu_Z_abbreviated" : "(BT)",
"Asia/Thimphu_Z_short" : "IST",
"Asia/Tokyo_Z_abbreviated" : "(JP)",
"Asia/Tokyo_Z_short" : "JST",
"Asia/Ulaanbaatar_Z_abbreviated" : "MN (Ulaanbaatar)",
"Asia/Ulaanbaatar_Z_short" : "ULAT",
"Asia/Urumqi_Z_abbreviated" : "CN (Urumqi)",
"Asia/Urumqi_Z_short" : "URUT",
"Asia/Vientiane_Z_abbreviated" : "(LA)",
"Asia/Vientiane_Z_short" : "ICT",
"Asia/Vladivostok_Z_abbreviated" : "RU (Vladivostok)",
"Asia/Vladivostok_Z_short" : "VLAT",
"Asia/Yakutsk_Z_abbreviated" : "RU (Yakutsk)",
"Asia/Yakutsk_Z_short" : "YAKT",
"Asia/Yekaterinburg_Z_abbreviated" : "RU (Yekaterinburg)",
"Asia/Yekaterinburg_Z_short" : "SVET",
"Asia/Yerevan_Z_abbreviated" : "(AM)",
"Asia/Yerevan_Z_short" : "YERT",
"Atlantic/Bermuda_Z_abbreviated" : "(BM)",
"Atlantic/Bermuda_Z_short" : "AST",
"Atlantic/Cape_Verde_Z_abbreviated" : "(CV)",
"Atlantic/Cape_Verde_Z_short" : "CVT",
"Atlantic/Reykjavik_Z_abbreviated" : "(IS)",
"Atlantic/Reykjavik_Z_short" : "GMT",
"Atlantic/South_Georgia_Z_abbreviated" : "(GS)",
"Atlantic/South_Georgia_Z_short" : "GST (GS)",
"Atlantic/St_Helena_Z_abbreviated" : "(SH)",
"Atlantic/St_Helena_Z_short" : "GMT",
"Atlantic/Stanley_Z_abbreviated" : "(FK)",
"Atlantic/Stanley_Z_short" : "FKT",
"Australia/Adelaide_Z_abbreviated" : "AU (Adelaide)",
"Australia/Adelaide_Z_short" : "ACST",
"Australia/Brisbane_Z_abbreviated" : "AU (Brisbane)",
"Australia/Brisbane_Z_short" : "AEST",
"Australia/Darwin_Z_abbreviated" : "AU (Darwin)",
"Australia/Darwin_Z_short" : "ACST",
"Australia/Hobart_Z_abbreviated" : "AU (Hobart)",
"Australia/Hobart_Z_short" : "AEDT",
"Australia/Lord_Howe_Z_abbreviated" : "AU (Lord Howe)",
"Australia/Lord_Howe_Z_short" : "AEST",
"Australia/Melbourne_Z_abbreviated" : "AU (Melbourne)",
"Australia/Melbourne_Z_short" : "AEST",
"Australia/Perth_Z_abbreviated" : "AU (Perth)",
"Australia/Perth_Z_short" : "AWST",
"Australia/Sydney_Z_abbreviated" : "AU (Sydney)",
"Australia/Sydney_Z_short" : "AEST",
"BC" : "BCE",
"DateTimeCombination" : "{1} {0}",
"DateTimeTimezoneCombination" : "{1} {0} {2}",
"DateTimezoneCombination" : "{1} {2}",
"EST_Z_abbreviated" : "GMT-۰۵:۰۰",
"EST_Z_short" : "GMT-۰۵:۰۰",
"Etc/GMT-14_Z_abbreviated" : "GMT+۱۴:۰۰",
"Etc/GMT-14_Z_short" : "GMT+۱۴:۰۰",
"Etc/GMT_Z_abbreviated" : "GMT+۰۰:۰۰",
"Etc/GMT_Z_short" : "GMT+۰۰:۰۰",
"Europe/Amsterdam_Z_abbreviated" : "(NL)",
"Europe/Amsterdam_Z_short" : "CET",
"Europe/Andorra_Z_abbreviated" : "(AD)",
"Europe/Andorra_Z_short" : "CET",
"Europe/Athens_Z_abbreviated" : "(GR)",
"Europe/Athens_Z_short" : "EET",
"Europe/Belgrade_Z_abbreviated" : "(RS)",
"Europe/Belgrade_Z_short" : "CET",
"Europe/Berlin_Z_abbreviated" : "(DE)",
"Europe/Berlin_Z_short" : "CET",
"Europe/Brussels_Z_abbreviated" : "(BE)",
"Europe/Brussels_Z_short" : "CET",
"Europe/Bucharest_Z_abbreviated" : "(RO)",
"Europe/Bucharest_Z_short" : "EET",
"Europe/Budapest_Z_abbreviated" : "(HU)",
"Europe/Budapest_Z_short" : "CET",
"Europe/Chisinau_Z_abbreviated" : "(MD)",
"Europe/Chisinau_Z_short" : "MSK",
"Europe/Copenhagen_Z_abbreviated" : "(DK)",
"Europe/Copenhagen_Z_short" : "CET",
"Europe/Gibraltar_Z_abbreviated" : "(GI)",
"Europe/Gibraltar_Z_short" : "CET",
"Europe/Helsinki_Z_abbreviated" : "(FI)",
"Europe/Helsinki_Z_short" : "EET",
"Europe/Istanbul_Z_abbreviated" : "(TR)",
"Europe/Istanbul_Z_short" : "EET",
"Europe/Kaliningrad_Z_abbreviated" : "RU (Kaliningrad)",
"Europe/Kaliningrad_Z_short" : "MSK",
"Europe/Kiev_Z_abbreviated" : "UA (Kiev)",
"Europe/Kiev_Z_short" : "MSK",
"Europe/Lisbon_Z_abbreviated" : "PT (Lisbon)",
"Europe/Lisbon_Z_short" : "CET",
"Europe/London_Z_abbreviated" : "(GB)",
"Europe/London_Z_short" : "GMT+۰۱:۰۰",
"Europe/Luxembourg_Z_abbreviated" : "(LU)",
"Europe/Luxembourg_Z_short" : "CET",
"Europe/Madrid_Z_abbreviated" : "ES (Madrid)",
"Europe/Madrid_Z_short" : "CET",
"Europe/Malta_Z_abbreviated" : "(MT)",
"Europe/Malta_Z_short" : "CET",
"Europe/Minsk_Z_abbreviated" : "(BY)",
"Europe/Minsk_Z_short" : "MSK",
"Europe/Monaco_Z_abbreviated" : "(MC)",
"Europe/Monaco_Z_short" : "CET",
"Europe/Moscow_Z_abbreviated" : "RU (Moscow)",
"Europe/Moscow_Z_short" : "MSK",
"Europe/Oslo_Z_abbreviated" : "(NO)",
"Europe/Oslo_Z_short" : "CET",
"Europe/Paris_Z_abbreviated" : "(FR)",
"Europe/Paris_Z_short" : "CET",
"Europe/Prague_Z_abbreviated" : "(CZ)",
"Europe/Prague_Z_short" : "CET",
"Europe/Riga_Z_abbreviated" : "(LV)",
"Europe/Riga_Z_short" : "MSK",
"Europe/Rome_Z_abbreviated" : "(IT)",
"Europe/Rome_Z_short" : "CET",
"Europe/Samara_Z_abbreviated" : "RU (Samara)",
"Europe/Samara_Z_short" : "KUYT",
"Europe/Simferopol_Z_abbreviated" : "UA (Simferopol)",
"Europe/Simferopol_Z_short" : "MSK",
"Europe/Sofia_Z_abbreviated" : "(BG)",
"Europe/Sofia_Z_short" : "EET",
"Europe/Stockholm_Z_abbreviated" : "(SE)",
"Europe/Stockholm_Z_short" : "CET",
"Europe/Tallinn_Z_abbreviated" : "(EE)",
"Europe/Tallinn_Z_short" : "MSK",
"Europe/Tirane_Z_abbreviated" : "(AL)",
"Europe/Tirane_Z_short" : "CET",
"Europe/Uzhgorod_Z_abbreviated" : "UA (Uzhgorod)",
"Europe/Uzhgorod_Z_short" : "MSK",
"Europe/Vaduz_Z_abbreviated" : "(LI)",
"Europe/Vaduz_Z_short" : "CET",
"Europe/Vienna_Z_abbreviated" : "(AT)",
"Europe/Vienna_Z_short" : "CET",
"Europe/Vilnius_Z_abbreviated" : "(LT)",
"Europe/Vilnius_Z_short" : "MSK",
"Europe/Volgograd_Z_abbreviated" : "RU (Volgograd)",
"Europe/Volgograd_Z_short" : "VOLT",
"Europe/Warsaw_Z_abbreviated" : "(PL)",
"Europe/Warsaw_Z_short" : "CET",
"Europe/Zaporozhye_Z_abbreviated" : "UA (Zaporozhye)",
"Europe/Zaporozhye_Z_short" : "MSK",
"Europe/Zurich_Z_abbreviated" : "(CH)",
"Europe/Zurich_Z_short" : "CET",
"HMS_long" : "{0} {1} {2}",
"HMS_short" : "{0}:{1}:{2}",
"HM_abbreviated" : "h:mm a",
"HM_short" : "h:mm a",
"H_abbreviated" : "h a",
"Indian/Antananarivo_Z_abbreviated" : "(MG)",
"Indian/Antananarivo_Z_short" : "EAT",
"Indian/Chagos_Z_abbreviated" : "(IO)",
"Indian/Chagos_Z_short" : "IOT",
"Indian/Christmas_Z_abbreviated" : "(CX)",
"Indian/Christmas_Z_short" : "CXT",
"Indian/Cocos_Z_abbreviated" : "(CC)",
"Indian/Cocos_Z_short" : "CCT",
"Indian/Comoro_Z_abbreviated" : "(KM)",
"Indian/Comoro_Z_short" : "EAT",
"Indian/Kerguelen_Z_abbreviated" : "(TF)",
"Indian/Kerguelen_Z_short" : "TFT",
"Indian/Mahe_Z_abbreviated" : "(SC)",
"Indian/Mahe_Z_short" : "SCT",
"Indian/Maldives_Z_abbreviated" : "(MV)",
"Indian/Maldives_Z_short" : "MVT",
"Indian/Mauritius_Z_abbreviated" : "(MU)",
"Indian/Mauritius_Z_short" : "MUT",
"Indian/Mayotte_Z_abbreviated" : "(YT)",
"Indian/Mayotte_Z_short" : "EAT",
"Indian/Reunion_Z_abbreviated" : "(RE)",
"Indian/Reunion_Z_short" : "RET",
"MD_abbreviated" : "MMM d",
"MD_long" : "MMMM d",
"MD_short" : "M-d",
"M_abbreviated" : "MMM",
"M_long" : "MMMM",
"Pacific/Apia_Z_abbreviated" : "(WS)",
"Pacific/Apia_Z_short" : "BST (Bering)",
"Pacific/Auckland_Z_abbreviated" : "NZ (Auckland)",
"Pacific/Auckland_Z_short" : "NZST",
"Pacific/Chuuk_Z_abbreviated" : "FM (Truk)",
"Pacific/Chuuk_Z_short" : "TRUT",
"Pacific/Efate_Z_abbreviated" : "(VU)",
"Pacific/Efate_Z_short" : "VUT",
"Pacific/Fakaofo_Z_abbreviated" : "(TK)",
"Pacific/Fakaofo_Z_short" : "TKT",
"Pacific/Fiji_Z_abbreviated" : "(FJ)",
"Pacific/Fiji_Z_short" : "FJT",
"Pacific/Funafuti_Z_abbreviated" : "(TV)",
"Pacific/Funafuti_Z_short" : "TVT",
"Pacific/Gambier_Z_abbreviated" : "PF (Gambier)",
"Pacific/Gambier_Z_short" : "GAMT",
"Pacific/Guadalcanal_Z_abbreviated" : "(SB)",
"Pacific/Guadalcanal_Z_short" : "SBT",
"Pacific/Guam_Z_abbreviated" : "(GU)",
"Pacific/Guam_Z_short" : "GST (GU)",
"Pacific/Honolulu_Z_abbreviated" : "US (Honolulu)",
"Pacific/Honolulu_Z_short" : "AHST",
"Pacific/Johnston_Z_abbreviated" : "UM (Johnston)",
"Pacific/Johnston_Z_short" : "AHST",
"Pacific/Majuro_Z_abbreviated" : "MH (Majuro)",
"Pacific/Majuro_Z_short" : "MHT",
"Pacific/Midway_Z_abbreviated" : "UM (Midway)",
"Pacific/Midway_Z_short" : "BST (Bering)",
"Pacific/Nauru_Z_abbreviated" : "(NR)",
"Pacific/Nauru_Z_short" : "NRT",
"Pacific/Niue_Z_abbreviated" : "(NU)",
"Pacific/Niue_Z_short" : "NUT",
"Pacific/Norfolk_Z_abbreviated" : "(NF)",
"Pacific/Norfolk_Z_short" : "NFT",
"Pacific/Noumea_Z_abbreviated" : "(NC)",
"Pacific/Noumea_Z_short" : "NCT",
"Pacific/Pago_Pago_Z_abbreviated" : "(AS)",
"Pacific/Pago_Pago_Z_short" : "BST (Bering)",
"Pacific/Palau_Z_abbreviated" : "(PW)",
"Pacific/Palau_Z_short" : "PWT",
"Pacific/Pitcairn_Z_abbreviated" : "(PN)",
"Pacific/Pitcairn_Z_short" : "PNT",
"Pacific/Port_Moresby_Z_abbreviated" : "(PG)",
"Pacific/Port_Moresby_Z_short" : "PGT",
"Pacific/Rarotonga_Z_abbreviated" : "(CK)",
"Pacific/Rarotonga_Z_short" : "CKT",
"Pacific/Saipan_Z_abbreviated" : "(MP)",
"Pacific/Saipan_Z_short" : "MPT",
"Pacific/Tarawa_Z_abbreviated" : "KI (Tarawa)",
"Pacific/Tarawa_Z_short" : "GILT",
"Pacific/Tongatapu_Z_abbreviated" : "(TO)",
"Pacific/Tongatapu_Z_short" : "TOT",
"Pacific/Wake_Z_abbreviated" : "UM (Wake)",
"Pacific/Wake_Z_short" : "WAKT",
"Pacific/Wallis_Z_abbreviated" : "(WF)",
"Pacific/Wallis_Z_short" : "WFT",
"RelativeTime/oneUnit" : "{0} ago",
"RelativeTime/twoUnits" : "{0} {1} ago",
"TimeTimezoneCombination" : "{0} {2}",
"WET_Z_abbreviated" : "GMT+۰۰:۰۰",
"WET_Z_short" : "GMT+۰۰:۰۰",
"WMD_abbreviated" : "E MMM d",
"WMD_long" : "EEEE, MMMM d",
"WMD_short" : "E, M-d",
"WYMD_abbreviated" : "EEE, y MMM d",
"WYMD_long" : "EEEE, y MMMM dd",
"WYMD_short" : "EEE, M/d/yy",
"W_abbreviated" : "EEE",
"W_long" : "EEEE",
"YMD_abbreviated" : "MMM d, y",
"YMD_full" : "yyyy-MM-dd",
"YMD_long" : "y MMMM d",
"YMD_short" : "yyyy-MM-dd",
"YM_long" : "y MMMM",
"currencyFormat" : "¤ #,##0.00",
"currencyPatternPlural" : "e u",
"currencyPatternSingular" : "{0} {1}",
"day" : "d",
"day_abbr" : "d",
"dayperiod" : "Dayperiod",
"days" : "d",
"days_abbr" : "d",
"decimalFormat" : "#,##0.###",
"decimalSeparator" : "٫",
"defaultCurrency" : "AFN",
"exponentialSymbol" : "×۱۰^",
"groupingSeparator" : "٬",
"hour" : "h",
"hour_abbr" : "h",
"hours" : "h",
"hours_abbr" : "h",
"infinitySign" : "∞",
"listPatternEnd" : "{0}, {1}",
"listPatternMiddle" : "{0}, {1}",
"listPatternStart" : "{0}, {1}",
"listPatternTwo" : "{0}, {1}",
"minusSign" : "−",
"minute" : "min",
"minute_abbr" : "min",
"minutes" : "min",
"minutes_abbr" : "min",
"month" : "m",
"monthAprLong" : "4",
"monthAprMedium" : "4",
"monthAugLong" : "8",
"monthAugMedium" : "8",
"monthDecLong" : "12",
"monthDecMedium" : "12",
"monthFebLong" : "2",
"monthFebMedium" : "2",
"monthJanLong" : "1",
"monthJanMedium" : "1",
"monthJulLong" : "7",
"monthJulMedium" : "7",
"monthJunLong" : "6",
"monthJunMedium" : "6",
"monthMarLong" : "3",
"monthMarMedium" : "3",
"monthMayLong" : "5",
"monthMayMedium" : "5",
"monthNovLong" : "11",
"monthNovMedium" : "11",
"monthOctLong" : "10",
"monthOctMedium" : "10",
"monthSepLong" : "9",
"monthSepMedium" : "9",
"month_abbr" : "m",
"months" : "m",
"months_abbr" : "m",
"nanSymbol" : "NaN",
"numberZero" : "۰",
"perMilleSign" : "‰",
"percentFormat" : "#,##0%",
"percentSign" : "٪",
"periodAm" : "Dayperiod",
"periodPm" : "Dayperiod",
"plusSign" : "+",
"scientificFormat" : "#E0",
"second" : "s",
"second_abbr" : "s",
"seconds" : "s",
"seconds_abbr" : "s",
"today" : "Today",
"tomorrow" : "Tomorrow",
"weekdayFriLong" : "6",
"weekdayFriMedium" : "6",
"weekdayMonLong" : "2",
"weekdayMonMedium" : "2",
"weekdaySatLong" : "7",
"weekdaySatMedium" : "7",
"weekdaySunLong" : "1",
"weekdaySunMedium" : "1",
"weekdayThuLong" : "5",
"weekdayThuMedium" : "5",
"weekdayTueLong" : "3",
"weekdayTueMedium" : "3",
"weekdayWedLong" : "4",
"weekdayWedMedium" : "4",
"year" : "y",
"year_abbr" : "y",
"years" : "y",
"years_abbr" : "y",
"yesterday" : "Yesterday"
}
|
/* *
*
* Copyright (c) 2019-2019 Highsoft AS
*
* Boost module: stripped-down renderer for higher performance
*
* License: highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../parts/Globals.js';
import '../../parts/Color.js';
var Color = H.Color;
// Register color names since GL can't render those directly.
// TODO: When supporting modern syntax, make this a const and a named export
var defaultHTMLColorMap = {
aliceblue: '#f0f8ff',
antiquewhite: '#faebd7',
aqua: '#00ffff',
aquamarine: '#7fffd4',
azure: '#f0ffff',
beige: '#f5f5dc',
bisque: '#ffe4c4',
black: '#000000',
blanchedalmond: '#ffebcd',
blue: '#0000ff',
blueviolet: '#8a2be2',
brown: '#a52a2a',
burlywood: '#deb887',
cadetblue: '#5f9ea0',
chartreuse: '#7fff00',
chocolate: '#d2691e',
coral: '#ff7f50',
cornflowerblue: '#6495ed',
cornsilk: '#fff8dc',
crimson: '#dc143c',
cyan: '#00ffff',
darkblue: '#00008b',
darkcyan: '#008b8b',
darkgoldenrod: '#b8860b',
darkgray: '#a9a9a9',
darkgreen: '#006400',
darkkhaki: '#bdb76b',
darkmagenta: '#8b008b',
darkolivegreen: '#556b2f',
darkorange: '#ff8c00',
darkorchid: '#9932cc',
darkred: '#8b0000',
darksalmon: '#e9967a',
darkseagreen: '#8fbc8f',
darkslateblue: '#483d8b',
darkslategray: '#2f4f4f',
darkturquoise: '#00ced1',
darkviolet: '#9400d3',
deeppink: '#ff1493',
deepskyblue: '#00bfff',
dimgray: '#696969',
dodgerblue: '#1e90ff',
feldspar: '#d19275',
firebrick: '#b22222',
floralwhite: '#fffaf0',
forestgreen: '#228b22',
fuchsia: '#ff00ff',
gainsboro: '#dcdcdc',
ghostwhite: '#f8f8ff',
gold: '#ffd700',
goldenrod: '#daa520',
gray: '#808080',
green: '#008000',
greenyellow: '#adff2f',
honeydew: '#f0fff0',
hotpink: '#ff69b4',
indianred: '#cd5c5c',
indigo: '#4b0082',
ivory: '#fffff0',
khaki: '#f0e68c',
lavender: '#e6e6fa',
lavenderblush: '#fff0f5',
lawngreen: '#7cfc00',
lemonchiffon: '#fffacd',
lightblue: '#add8e6',
lightcoral: '#f08080',
lightcyan: '#e0ffff',
lightgoldenrodyellow: '#fafad2',
lightgrey: '#d3d3d3',
lightgreen: '#90ee90',
lightpink: '#ffb6c1',
lightsalmon: '#ffa07a',
lightseagreen: '#20b2aa',
lightskyblue: '#87cefa',
lightslateblue: '#8470ff',
lightslategray: '#778899',
lightsteelblue: '#b0c4de',
lightyellow: '#ffffe0',
lime: '#00ff00',
limegreen: '#32cd32',
linen: '#faf0e6',
magenta: '#ff00ff',
maroon: '#800000',
mediumaquamarine: '#66cdaa',
mediumblue: '#0000cd',
mediumorchid: '#ba55d3',
mediumpurple: '#9370d8',
mediumseagreen: '#3cb371',
mediumslateblue: '#7b68ee',
mediumspringgreen: '#00fa9a',
mediumturquoise: '#48d1cc',
mediumvioletred: '#c71585',
midnightblue: '#191970',
mintcream: '#f5fffa',
mistyrose: '#ffe4e1',
moccasin: '#ffe4b5',
navajowhite: '#ffdead',
navy: '#000080',
oldlace: '#fdf5e6',
olive: '#808000',
olivedrab: '#6b8e23',
orange: '#ffa500',
orangered: '#ff4500',
orchid: '#da70d6',
palegoldenrod: '#eee8aa',
palegreen: '#98fb98',
paleturquoise: '#afeeee',
palevioletred: '#d87093',
papayawhip: '#ffefd5',
peachpuff: '#ffdab9',
peru: '#cd853f',
pink: '#ffc0cb',
plum: '#dda0dd',
powderblue: '#b0e0e6',
purple: '#800080',
red: '#ff0000',
rosybrown: '#bc8f8f',
royalblue: '#4169e1',
saddlebrown: '#8b4513',
salmon: '#fa8072',
sandybrown: '#f4a460',
seagreen: '#2e8b57',
seashell: '#fff5ee',
sienna: '#a0522d',
silver: '#c0c0c0',
skyblue: '#87ceeb',
slateblue: '#6a5acd',
slategray: '#708090',
snow: '#fffafa',
springgreen: '#00ff7f',
steelblue: '#4682b4',
tan: '#d2b48c',
teal: '#008080',
thistle: '#d8bfd8',
tomato: '#ff6347',
turquoise: '#40e0d0',
violet: '#ee82ee',
violetred: '#d02090',
wheat: '#f5deb3',
white: '#ffffff',
whitesmoke: '#f5f5f5',
yellow: '#ffff00',
yellowgreen: '#9acd32'
};
Color.prototype.names = defaultHTMLColorMap;
export default defaultHTMLColorMap;
|
/**
* Filemanager JS core
*
* filemanager.js
*
* @license MIT License
* @author Jason Huck - Core Five Labs
* @author Simon Georget <simon (at) linea21 (dot) com>
* @copyright Authors
*/
(function($) {
// function to retrieve GET params
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results)
return results[1];
else
return 0;
};
/*---------------------------------------------------------
Setup, Layout, and Status Functions
---------------------------------------------------------*/
// We retrieve config settings from filemanager.config.js
var loadConfigFile = function (type) {
var json = null;
type = (typeof type === "undefined") ? "user" : type;
if(type == 'user') {
var url = './scripts/filemanager.config.js';
} else {
var url = './scripts/filemanager.config.js.default'
}
$.ajax({
'async': false,
'url': url,
'dataType': "json",
cache: false,
'success': function (data) {
json = data;
}
});
return json;
};
// loading default configuration file
var configd = loadConfigFile('default');
// loading user configuration file
var config = loadConfigFile();
// we merge default config and user config file
var config = $.extend({}, configd, config);
// <head> included files collector
HEAD_included_files = new Array();
/**
* function to load a given css file into header
* if not already included
*/
loadCSS = function(href) {
// we check if already included
if($.inArray(href, HEAD_included_files) == -1) {
var cssLink = $("<link rel='stylesheet' type='text/css' href='" + href + "'>");
$("head").append(cssLink);
HEAD_included_files.push(href);
}
};
/**
* function to load a given js file into header
* if not already included
*/
loadJS = function(src) {
// we check if already included
if($.inArray(src, HEAD_included_files) == -1) {
var jsLink = $("<script type='text/javascript' src='" + src + "'>");
$("head").append(jsLink);
HEAD_included_files.push(src);
}
};
// Sets paths to connectors based on language selection.
// var fileConnector = config.options.fileConnector || 'connectors/' + config.options.lang + '/filemanager.' + config.options.lang;
var fileConnector = config.options.fileConnector || 'connectors';
// Read capabilities from config files if exists
// else apply default settings
var capabilities = config.options.capabilities || new Array('select', 'download', 'rename', 'move', 'delete', 'replace');
// Get localized messages from file
// through culture var or from URL
if($.urlParam('langCode') != 0 && file_exists ('scripts/languages/' + $.urlParam('langCode') + '.js')) config.options.culture = $.urlParam('langCode');
var lg = [];
$.ajax({
url: 'scripts/languages/' + config.options.culture + '.js',
async: false,
dataType: 'json',
success: function (json) {
lg = json;
}
});
// Options for alert, prompt, and confirm dialogues.
$.prompt.setDefaults({
overlayspeed: 'fast',
show: 'fadeIn',
opacity: 0.4,
persistent: false
});
// Forces columns to fill the layout vertically.
// Called on initial page load and on resize.
var setDimensions = function(){
var bheight = 20;
if(config.options.searchBox === true) bheight +=33;
if($.urlParam('CKEditorCleanUpFuncNum')) bheight +=60;
var newH = $(window).height() - $('#uploader').height() - bheight;
$('#splitter, #filetree, #fileinfo, .vsplitbar').height(newH);
var newW = $('#splitter').width() - 6 - $('#filetree').width();
$('#fileinfo').width(newW);
};
// Display Min Path
var displayPath = function(path, reduce) {
reduce = (typeof reduce === "undefined") ? true : false;
if(config.options.showFullPath == false) {
// if a "displayPathDecorator" function is defined, use it to decorate path
if('function' === typeof displayPathDecorator) {
return displayPathDecorator(path.replace(fileRoot, "/"));
} else {
path = path.replace(fileRoot, "/");
if(path.length > 50 && reduce === true) {
var n = path.split("/");
path = '/' + n[1] + '/' + n[2] + '/(...)/' + n[n.length-2] + '/';
}
return path;
}
} else {
return path;
}
};
// Set the view buttons state
var setViewButtonsFor = function(viewMode) {
if (viewMode == 'grid') {
$('#grid').addClass('ON');
$('#list').removeClass('ON');
}
else {
$('#list').addClass('ON');
$('#grid').removeClass('ON');
}
};
// Test if a given url exists
function file_exists (url) {
// http://kevin.vanzonneveld.net
// + original by: Enrique Gonzalez
// + input by: Jani Hartikainen
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// % note 1: This function uses XmlHttpRequest and cannot retrieve resource from different domain.
// % note 1: Synchronous so may lock up browser, mainly here for study purposes.
// * example 1: file_exists('http://kevin.vanzonneveld.net/pj_test_supportfile_1.htm');
// * returns 1: '123'
var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
if (!req) {
throw new Error('XMLHttpRequest not supported');
}
// HEAD Results are usually shorter (faster) than GET
req.open('HEAD', url, false);
req.send(null);
if (req.status == 200) {
return true;
}
return false;
}
// preg_replace
// Code from : http://xuxu.fr/2006/05/20/preg-replace-javascript/
var preg_replace = function(array_pattern, array_pattern_replace, str) {
var new_str = String (str);
for (i=0; i<array_pattern.length; i++) {
var reg_exp= RegExp(array_pattern[i], "g");
var val_to_replace = array_pattern_replace[i];
new_str = new_str.replace (reg_exp, val_to_replace);
}
return new_str;
};
// cleanString (), on the same model as server side (connector)
// cleanString
var cleanString = function(str) {
var cleaned = "";
var p_search = new Array("Š", "š", "Đ", "đ", "Ž", "ž", "Č", "č", "Ć", "ć", "À",
"Á", "Â", "Ã", "Ä", "Å", "Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
"Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "Ő", "Ø", "Ù", "Ú", "Û", "Ü", "Ý", "Þ", "ß",
"à", "á", "â", "ã", "ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í",
"î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "ő", "ø", "ù", "ú", "û", "ü",
"ý", "ý", "þ", "ÿ", "Ŕ", "ŕ", " ", "'", "/"
);
var p_replace = new Array("S", "s", "Dj", "dj", "Z", "z", "C", "c", "C", "c", "A",
"A", "A", "A", "A", "A", "A", "C", "E", "E", "E", "E", "I", "I", "I", "I",
"N", "O", "O", "O", "O", "O", "O", "O", "U", "U", "U", "U", "Y", "B", "Ss",
"a", "a", "a", "a", "a", "a", "a", "c", "e", "e", "e", "e", "i", "i",
"i", "i", "o", "n", "o", "o", "o", "o", "o", "o", "o", "u", "u", "u", "u",
"y", "y", "b", "y", "R", "r", "_", "_", ""
);
cleaned = preg_replace(p_search, p_replace, str);
// allow only latin alphabet
if(config.options.chars_only_latin) {
cleaned = cleaned.replace(/[^_a-zA-Z0-9]/g, "");
}
cleaned = cleaned.replace(/[_]+/g, "_");
return cleaned;
};
// nameFormat (), separate filename from extension before calling cleanString()
// nameFormat
var nameFormat = function(input) {
filename = '';
if(input.lastIndexOf('.') != -1) {
filename = cleanString(input.substr(0, input.lastIndexOf('.')));
filename += '.' + input.split('.').pop();
} else {
filename = cleanString(input);
}
return filename;
};
//Converts bytes to kb, mb, or gb as needed for display.
var formatBytes = function(bytes) {
var n = parseFloat(bytes);
var d = parseFloat(1024);
var c = 0;
var u = [lg.bytes,lg.kb,lg.mb,lg.gb];
while(true){
if(n < d){
n = Math.round(n * 100) / 100;
return n + u[c];
} else {
n /= d;
c += 1;
}
}
};
// Handle Error. Freeze interactive buttons and display
// error message. Also called when auth() function return false (Code == "-1")
var handleError = function(errMsg) {
$('#fileinfo').html('<h1>' + errMsg+ '</h1>');
$('#newfile').attr("disabled", "disabled");
$('#upload').attr("disabled", "disabled");
$('#newfolder').attr("disabled", "disabled");
};
// Test if Data structure has the 'cap' capability
// 'cap' is one of 'select', 'rename', 'delete', 'download', move
function has_capability(data, cap) {
if (data['File Type'] == 'dir' && (cap == 'download' || cap == 'replace')) return false;
if (typeof(data['Capabilities']) == "undefined") return true;
else return $.inArray(cap, data['Capabilities']) > -1;
}
// Test if file is authorized
var isAuthorizedFile = function(filename) {
var ext = getExtension(filename);
// no extension is allowed
if(ext == '' && config.security.allowNoExtension == true) return true;
if(config.security.uploadPolicy == 'DISALLOW_ALL') {
if($.inArray(ext, config.security.uploadRestrictions) != -1) return true;
}
if(config.security.uploadPolicy == 'ALLOW_ALL') {
if($.inArray(ext, config.security.uploadRestrictions) == -1) return true;
}
return false;
};
// from http://phpjs.org/functions/basename:360
var basename = function(path, suffix) {
var b = path.replace(/^.*[\/\\]/g, '');
if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
b = b.substr(0, b.length-suffix.length);
}
return b;
};
// return filename extension
var getExtension = function(filename) {
if(filename.split('.').length == 1) {
return "";
}
return filename.split('.').pop().toLowerCase();
};
// return filename without extension {
var getFilename = function(filename) {
if(filename.lastIndexOf('.') != -1) {
return filename.substring(0, filename.lastIndexOf('.'));
} else {
return filename;
}
};
//Test if is editable file
var isEditableFile = function(filename) {
if($.inArray(getExtension(filename), config.edit.editExt) != -1) {
return true;
} else {
return false;
}
};
// Test if is image file
var isImageFile = function(filename) {
if($.inArray(getExtension(filename), config.images.imagesExt) != -1) {
return true;
} else {
return false;
}
};
// Test if file is supported web video file
var isVideoFile = function(filename) {
if($.inArray(getExtension(filename), config.videos.videosExt) != -1) {
return true;
} else {
return false;
}
};
// Test if file is supported web audio file
var isAudioFile = function(filename) {
if($.inArray(getExtension(filename), config.audios.audiosExt) != -1) {
return true;
} else {
return false;
}
};
// Return HTML video player
var getVideoPlayer = function(data) {
var code = '<video width=' + config.videos.videosPlayerWidth + ' height=' + config.videos.videosPlayerHeight + ' src="' + data['Path'] + '" controls="controls">';
code += '<img src="' + data['Preview'] + '" />';
code += '</video>';
$("#fileinfo img").remove();
$('#fileinfo #preview h1').before(code);
};
//Return HTML audio player
var getAudioPlayer = function(data) {
var code = '<audio src="' + data['Path'] + '" controls="controls">';
code += '<img src="' + data['Preview'] + '" />';
code += '</audio>';
$("#fileinfo img").remove();
$('#fileinfo #preview h1').before(code);
};
// Display icons on list view
// retrieving them from filetree
// Called using SetInterval
var display_icons = function(timer) {
$('#fileinfo').find('td:first-child').each(function(){
var path = $(this).attr('data-path');
var treenode = $('#filetree').find('a[data-path="' + path + '"]').parent();
if (typeof treenode.css('background-image') !== "undefined") {
$(this).css('background-image', treenode.css('background-image'));
window.clearInterval(timer);
}
});
};
// Sets the folder status, upload, and new folder functions
// to the path specified. Called on initial page load and
// whenever a new directory is selected.
var setUploader = function(path) {
$('#currentpath').val(path);
$('#uploader h1').text(lg.current_folder + displayPath(path)).attr('title', displayPath(path, false)).attr('data-path', path);
$('#newfolder').unbind().click(function(){
var foldername = lg.default_foldername;
var msg = lg.prompt_foldername + ' : <input id="fname" name="fname" type="text" value="' + foldername + '" />';
var getFolderName = function(v, m){
if(v != 1) return false;
var fname = m.children('#fname').val();
if(fname != ''){
foldername = cleanString(fname);
var d = new Date(); // to prevent IE cache issues
$.getJSON(fileConnector + '?mode=addfolder&path=' + $('#currentpath').val() + '&name=' + foldername + '&time=' + d.getMilliseconds(), function(result){
if(result['Code'] == 0){
addFolder(result['Parent'], result['Name']);
getFolderInfo(result['Parent']);
// seems to be necessary when dealing w/ files located on s3 (need to look into a cleaner solution going forward)
$('#filetree').find('a[data-path="' + result['Parent'] +'/"]').click().click();
} else {
$.prompt(result['Error']);
}
});
} else {
$.prompt(lg.no_foldername);
}
};
var btns = {};
btns[lg.create_folder] = true;
btns[lg.cancel] = false;
$.prompt(msg, {
callback: getFolderName,
buttons: btns
});
});
};
// Binds specific actions to the toolbar in detail views.
// Called when detail views are loaded.
var bindToolbar = function(data) {
// this little bit is purely cosmetic
$( "#fileinfo button" ).each(function( index ) {
// check if span doesn't exist yet, when bindToolbar called from renameItem for example
if($(this).find('span').length == 0)
$(this).wrapInner('<span></span>');
});
if (!has_capability(data, 'select')) {
$('#fileinfo').find('button#select').hide();
} else {
$('#fileinfo').find('button#select').click(function () { selectItem(data); }).show();
if(window.opener || window.tinyMCEPopup) {
$('#preview img').attr('title', lg.select);
$('#preview img').click(function () { selectItem(data); }).css("cursor", "pointer");
}
}
if (!has_capability(data, 'rename')) {
$('#fileinfo').find('button#rename').hide();
} else {
$('#fileinfo').find('button#rename').click(function(){
var newName = renameItem(data);
if(newName.length) $('#fileinfo > h1').text(newName);
}).show();
}
if (!has_capability(data, 'move')) {
$('#fileinfo').find('button#move').hide();
} else {
$('#fileinfo').find('button#move').click(function(){
var newName = moveItem(data);
if(newName.length) $('#fileinfo > h1').text(newName);
}).show();
}
// @todo
if (!has_capability(data, 'replace')) {
$('#fileinfo').find('button#replace').hide();
} else {
$('#fileinfo').find('button#replace').click(function(){
replaceItem(data);
}).show();
}
if (!has_capability(data, 'delete')) {
$('#fileinfo').find('button#delete').hide();
} else {
$('#fileinfo').find('button#delete').click(function(){
if(deleteItem(data)) $('#fileinfo').html('<h1>' + lg.select_from_left + '</h1>');
}).show();
}
if (!has_capability(data, 'download')) {
$('#fileinfo').find('button#download').hide();
} else {
$('#fileinfo').find('button#download').click(function(){
window.location = fileConnector + '?mode=download&path=' + encodeURIComponent(data['Path']);
}).show();
}
};
//Create FileTree and bind elements
//called during initialization and also when adding a file
//directly in root folder (via addNode)
var createFileTree = function() {
// Creates file tree.
$('#filetree').fileTree({
root: fileRoot,
datafunc: populateFileTree,
multiFolder: false,
folderCallback: function(path){ getFolderInfo(path); },
expandedFolder: fullexpandedFolder,
after: function(data){
$('#filetree').find('li a').each(function() {
$(this).contextMenu(
{ menu: getContextMenuOptions($(this)) },
function(action, el, pos){
var path = $(el).attr('data-path');
setMenus(action, path);
}
);
});
//Search function
if(config.options.searchBox == true) {
$('#q').liveUpdate('#filetree ul').blur();
$('#search span.q-inactive').html(lg.search);
$('#search a.q-reset').attr('title', lg.search_reset);
}
}
}, function(file){
getFileInfo(file);
});
};
/*---------------------------------------------------------
Item Actions
---------------------------------------------------------*/
// Calls the SetUrl function for FCKEditor compatibility,
// passes file path, dimensions, and alt text back to the
// opening window. Triggered by clicking the "Select"
// button in detail views or choosing the "Select"
// contextual menu option in list views.
// NOTE: closes the window when finished.
var selectItem = function(data) {
if(config.options.relPath !== false ) {
var url = relPath + data['Path'].replace(fileRoot,"");
} else {
var url = relPath + data['Path'];
}
if(window.opener || window.tinyMCEPopup || $.urlParam('field_name') || $.urlParam('CKEditorCleanUpFuncNum') || $.urlParam('CKEditor')) {
if(window.tinyMCEPopup){
// use TinyMCE > 3.0 integration method
var win = tinyMCEPopup.getWindowArg("window");
win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = url;
if (typeof(win.ImageDialog) != "undefined") {
// Update image dimensions
if (win.ImageDialog.getImageData)
win.ImageDialog.getImageData();
// Preview if necessary
if (win.ImageDialog.showPreviewImage)
win.ImageDialog.showPreviewImage(url);
}
tinyMCEPopup.close();
return;
}
// tinymce 4 and colorbox
if($.urlParam('field_name')){
parent.document.getElementById($.urlParam('field_name')).value = url;
if(typeof parent.tinyMCE !== "undefined") {
parent.tinyMCE.activeEditor.windowManager.close();
}
if(typeof parent.$.fn.colorbox !== "undefined") {
parent.$.fn.colorbox.close();
}
}
else if($.urlParam('CKEditor')){
// use CKEditor 3.0 + integration method
if (window.opener) {
// Popup
window.opener.CKEDITOR.tools.callFunction($.urlParam('CKEditorFuncNum'), url);
} else {
// Modal (in iframe)
parent.CKEDITOR.tools.callFunction($.urlParam('CKEditorFuncNum'), url);
parent.CKEDITOR.tools.callFunction($.urlParam('CKEditorCleanUpFuncNum'));
}
} else {
// use FCKEditor 2.0 integration method
if(data['Properties']['Width'] != ''){
var p = url;
var w = data['Properties']['Width'];
var h = data['Properties']['Height'];
window.opener.SetUrl(p,w,h);
} else {
window.opener.SetUrl(url);
}
}
if (window.opener) {
window.close();
}
} else {
$.prompt(lg.fck_select_integration);
}
};
// Renames the current item and returns the new name.
// Called by clicking the "Rename" button in detail views
// or choosing the "Rename" contextual menu option in
// list views.
var renameItem = function(data) {
var finalName = '';
var fileName = config.security.allowChangeExtensions ? data['Filename'] : getFilename(data['Filename']);
var msg = lg.new_filename + ' : <input id="rname" name="rname" type="text" value="' + fileName + '" />';
var getNewName = function(v, m){
if(v != 1) return false;
rname = m.children('#rname').val();
if(rname != ''){
var givenName = rname;
if (! config.security.allowChangeExtensions) {
givenName = nameFormat(rname);
var suffix = getExtension(data['Filename']);
if(suffix.length > 0) {
givenName = givenName + '.' + suffix;
}
}
// File only - Check if file extension is allowed
if (data['Path'].charAt(data['Path'].length-1) != '/' && !isAuthorizedFile(givenName)) {
var str = '<p>' + lg.INVALID_FILE_TYPE + '</p>';
if(config.security.uploadPolicy == 'DISALLOW_ALL') {
str += '<p>' + lg.ALLOWED_FILE_TYPE + config.security.uploadRestrictions.join(', ') + '.</p>';
}
if(config.security.uploadPolicy == 'ALLOW_ALL') {
str += '<p>' + lg.DISALLOWED_FILE_TYPE + config.security.uploadRestrictions.join(', ') + '.</p>';
}
$("#filepath").val('');
$.prompt(str);
return false;
}
var oldPath = data['Path'];
var connectString = fileConnector + '?mode=rename&old=' + data['Path'] + '&new=' + givenName;
$.ajax({
type: 'GET',
url: connectString,
dataType: 'json',
async: false,
success: function(result){
if(result['Code'] == 0){
var newPath = result['New Path'];
var newName = result['New Name'];
updateNode(oldPath, newPath, newName);
var title = $("#preview h1").attr("title");
if (typeof title !="undefined" && title == oldPath) {
$('#preview h1').text(newName);
}
if($('#fileinfo').data('view') == 'grid'){
$('#fileinfo img[data-path="' + oldPath + '"]').parent().next('p').text(newName);
$('#fileinfo img[data-path="' + oldPath + '"]').attr('data-path', newPath);
} else {
$('#fileinfo td[data-path="' + oldPath + '"]').text(newName);
$('#fileinfo td[data-path="' + oldPath + '"]').attr('data-path', newPath);
}
$("#preview h1").html(newName);
// actualized data for binding
data['Path']=newPath;
data['Filename']=newName;
// Bind toolbar functions.
$('#fileinfo').find('button#rename, button#delete, button#download').unbind();
bindToolbar(data);
if(config.options.showConfirmation) $.prompt(lg.successful_rename);
} else {
$.prompt(result['Error']);
}
finalName = result['New Name'];
}
});
}
};
var btns = {};
btns[lg.rename] = true;
btns[lg.cancel] = false;
$.prompt(msg, {
callback: getNewName,
buttons: btns
});
return finalName;
};
// Replace the current file and keep the same name.
// Called by clicking the "Replace" button in detail views
// or choosing the "Replace" contextual menu option in
// list views.
var replaceItem = function(data) {
// remove dynamic form if already exists
//$('#file-replacement').remove();
// we create a dynamic form with input File
// $form = $('<form id="file-replacement" method="post">');
// $form.append('<input id="fileR" name="fileR" type="file" />');
// $form.append('<input id="mode" name="mode" type="hidden" value="replace" /> ');
// $form.append('<input id="newfilepath" name="newfilepath" type="hidden" value="' + data["Path"] + '" />');
// $('body').prepend($form);
// we auto-submit form when user filled it up
$('#fileR').bind('change', function () {
$(this).closest("form#toolbar").submit();
});
// we set the connector to send data to
$('#toolbar').attr('action', fileConnector);
$('#toolbar').attr('method', 'post');
// submission script
$('#toolbar').ajaxForm({
target: '#uploadresponse',
beforeSubmit: function (arr, form, options) {
var newFile = $('#fileR', form).val();
// Test if a value is given
if (newFile == '') {
return false;
}
// Check if file extension is matching with the original
if (getExtension(newFile) != data["File Type"]) {
$.prompt(lg.ERROR_REPLACING_FILE + " ." + getExtension(data["Filename"]));
return false;
}
$('#replace').attr('disabled', true);
$('#upload span').addClass('loading').text(lg.loading_data);
// if config.upload.fileSizeLimit == auto we delegate size test to connector
if (typeof FileReader !== "undefined" && typeof config.upload.fileSizeLimit != "auto") {
// Check file size using html5 FileReader API
var size = $('#fileR', form).get(0).files[0].size;
if (size > config.upload.fileSizeLimit * 1024 * 1024) {
$.prompt("<p>" + lg.file_too_big + "</p><p>" + lg.file_size_limit + config.upload.fileSizeLimit + " " + lg.mb + ".</p>");
$('#upload').removeAttr('disabled').find("span").removeClass('loading').text(lg.upload);
return false;
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('#upload').removeAttr('disabled').find("span").removeClass('loading').text(lg.upload);
$.prompt(lg.ERROR_UPLOADING_FILE);
},
success: function (result) {
var data = jQuery.parseJSON($('#uploadresponse').find('textarea').text());
if (data['Code'] == 0) {
var fullpath = data["Path"] + '/' + data["Name"];
// Reloading file info
getFileInfo(fullpath);
// Visual effects for user to see action is successful
$('#preview').find('img').hide().fadeIn('slow'); // on right panel
$('ul.jqueryFileTree').find('li a[data-path="' + fullpath + '"]').parent().hide().fadeIn('slow'); // on fileTree
if (config.options.showConfirmation) $.prompt(lg.successful_replace);
} else {
$.prompt(data['Error']);
}
$('#replace').removeAttr('disabled');
$('#upload span').removeClass('loading').text(lg.upload);
}
});
// we pass data path value - original file
$('#newfilepath').val(data["Path"]);
// we open the input file dialog window
$('#fileR').click();
};
// Move the current item to specified dir and returns the new name.
// Called by clicking the "Move" button in detail views
// or choosing the "Move" contextual menu option in
// list views.
var moveItem = function(data) {
var finalName = '';
var msg = lg.move + ' : <input id="rname" name="rname" type="text" value="" />';
var doMove = function(v, m){
if(v != 1) return false;
rname = m.children('#rname').val();
if(rname != ''){
var givenName = rname;
var oldPath = data['Path'];
var connectString = fileConnector + '?mode=move&old=' + encodeURIComponent(data['Path']) + '&new=' + encodeURIComponent(givenName) + '&root=' + encodeURIComponent(fileRoot);
$.ajax({
type: 'GET',
url: connectString,
dataType: 'json',
async: false,
success: function(result){
if(result['Code'] == 0){
var newPath = result['New Path'];
var newName = result['New Name'];
// we set fullexpandedFolder value to automatically open file in
// filetree when calling createFileTree() function
fullexpandedFolder = newPath;
createFileTree();
getFolderInfo(newPath); // update list in main window
if(config.options.showConfirmation) $.prompt(lg.successful_moved);
} else {
$.prompt(result['Error']);
}
finalName = newPath + newName;
}
});
}
};
var btns = {};
btns[lg.move] = true;
btns[lg.cancel] = false;
$.prompt(msg, {
callback: doMove,
buttons: btns
});
return finalName;
};
// Prompts for confirmation, then deletes the current item.
// Called by clicking the "Delete" button in detail views
// or choosing the "Delete contextual menu item in list views.
var deleteItem = function(data) {
var isDeleted = false;
var msg = lg.confirmation_delete;
var doDelete = function(v, m){
if(v != 1) return false;
var d = new Date(); // to prevent IE cache issues
var connectString = fileConnector + '?mode=delete&path=' + encodeURIComponent(data['Path']) + '&time=' + d.getMilliseconds(),
parent = data['Path'].split('/').reverse().slice(1).reverse().join('/') + '/';
$.ajax({
type: 'GET',
url: connectString,
dataType: 'json',
async: false,
success: function(result){
if(result['Code'] == 0){
removeNode(result['Path']);
var rootpath = result['Path'].substring(0, result['Path'].length-1); // removing the last slash
rootpath = rootpath.substr(0, rootpath.lastIndexOf('/') + 1);
$('#uploader h1').text(lg.current_folder + displayPath(rootpath)).attr("title", displayPath(rootpath, false)).attr('data-path', rootpath);
isDeleted = true;
if(config.options.showConfirmation) $.prompt(lg.successful_delete);
// seems to be necessary when dealing w/ files located on s3 (need to look into a cleaner solution going forward)
$('#filetree').find('a[data-path="' + parent +'/"]').click().click();
} else {
isDeleted = false;
$.prompt(result['Error']);
}
}
});
};
var btns = {};
btns[lg.yes] = true;
btns[lg.no] = false;
$.prompt(msg, {
callback: doDelete,
buttons: btns
});
return isDeleted;
};
// Display an 'edit' link for editable files
// Then let user change the content of the file
// Save action is handled by the method using ajax
var editItem = function(data) {
isEdited = false;
$('#fileinfo').find('h1').append(' <a id="edit-file" href="#" title="' + lg.edit + '"><span>' + lg.edit + '</span></a>');
$('#edit-file').click(function() {
$(this).hide(); // hiding Edit link
var d = new Date(); // to prevent IE cache issues
var connectString = fileConnector + '?mode=editfile&path=' + encodeURIComponent(data['Path']) + '&time=' + d.getMilliseconds();
$.ajax({
type : 'GET',
url : connectString,
dataType : 'json',
async : false,
success : function(result) {
if (result['Code'] == 0) {
var content = '<form id="edit-form">';
content += '<textarea id="edit-content" name="content">' + result['Content'] + '</textarea>';
content += '<input type="hidden" name="mode" value="savefile" />';
content += '<input type="hidden" name="_token" value="'+ $("input[name='_token']").val() +'" />';
content += '<input type="hidden" name="path" value="' + data['Path'] + '" />';
content += '<button id="edit-cancel" class="edition" type="button">' + lg.quit_editor + '</button>';
content += '<button id="edit-save" class="edition" type="button">' + lg.save + '</button>';
content += '</form>';
$('#preview').find('img').hide();
$('#preview').prepend(content).hide().fadeIn();
// Cancel Button Behavior
$('#edit-cancel').click(function() {
$('#preview').find('form#edit-form').hide();
$('#preview').find('img').fadeIn();
$('#edit-file').show();
});
// Save Button Behavior
$('#edit-save').click(function() {
// we get new textarea content
var newcontent = codeMirrorEditor.getValue();
$("textarea#edit-content").val(newcontent);
var postData = $('#edit-form').serializeArray();
$.ajax({
type: 'POST',
url: fileConnector,
dataType: 'json',
data : postData,
async: false,
success: function(result){
if(result['Code'] == 0){
isEdited = true;
// if (config.options.showConfirmation) $.prompt(lg.successful_edit);
$.prompt(lg.successful_edit);
} else {
isEdited = false;
$.prompt(result['Error']);
}
}
});
});
// we instantiate codeMirror according to config options
codeMirrorEditor = instantiateCodeMirror(getExtension(data['Path']), config);
} else {
isEdited = false;
$.prompt(result['Error']);
$(this).show(); // hiding Edit link
}
}
});
});
return isEdited;
};
/*---------------------------------------------------------
Functions to Update the File Tree
---------------------------------------------------------*/
// Adds a new node as the first item beneath the specified
// parent node. Called after a successful file upload.
var addNode = function(path, name) {
var ext = getExtension(name);
var thisNode = $('#filetree').find('a[data-path="' + path + '"]');
var parentNode = thisNode.parent();
var newNode = '<li class="file ext_' + ext + '"><a data-path="' + path + name + '" href="#" class="">' + name + '</a></li>';
// if is root folder
// TODO optimize
if(!parentNode.find('ul').size()) {
parentNode = $('#filetree').find('ul.jqueryFileTree');
parentNode.prepend(newNode);
createFileTree();
} else {
parentNode.find('ul').prepend(newNode);
thisNode.click().click();
}
getFolderInfo(path); // update list in main window
if(config.options.showConfirmation) $.prompt(lg.successful_added_file);
};
// Updates the specified node with a new name. Called after
// a successful rename operation.
var updateNode = function(oldPath, newPath, newName){
var thisNode = $('#filetree').find('a[data-path="' + oldPath + '"]');
var parentNode = thisNode.parent().parent().prev('a');
thisNode.attr('data-path', newPath).text(newName);
// we work directly on root folder
// TODO optimize by binding only the renamed element
if(parentNode.length == 0) {
createFileTree();
} else {
parentNode.click().click();
}
};
// Removes the specified node. Called after a successful
// delete operation.
var removeNode = function(path) {
$('#filetree')
.find('a[data-path="' + path + '"]')
.parent()
.fadeOut('slow', function(){
$(this).remove();
});
// if the actual view is the deleted folder, we display parent folder
if($('#uploader h1').attr('data-path') == path) {
var a = path.split('/');
var parent = a.slice(0, length - 2).join('/') + '/';
getFolderInfo(parent);
}
// grid case
if($('#fileinfo').data('view') == 'grid'){
$('#contents img[data-path="' + path + '"]').parent().parent()
.fadeOut('slow', function(){
$(this).remove();
});
}
// list case
else {
$('table#contents')
.find('td[data-path="' + path + '"]')
.parent()
.fadeOut('slow', function(){
$(this).remove();
});
}
// remove fileinfo when item to remove is currently selected
if ($('#preview').length) {
getFolderInfo(path.substr(0, path.lastIndexOf('/') + 1));
}
};
// Adds a new folder as the first item beneath the
// specified parent node. Called after a new folder is
// successfully created.
var addFolder = function(parent, name) {
var newNode = '<li class="directory collapsed"><a data-path="' + parent + name + '/" href="#">' + name + '</a><ul class="jqueryFileTree" style="display: block;"></ul></li>';
var parentNode = $('#filetree').find('a[data-path="' + parent + '"]');
if(parent != fileRoot){
parentNode.next('ul').prepend(newNode).prev('a').click().click();
} else {
$('#filetree > ul').prepend(newNode);
$('#filetree').find('li a[data-path="' + parent + name + '/"]').attr('class', 'cap_rename cap_delete').click(function(){
getFolderInfo(parent + name + '/');
}).each(function() {
$(this).contextMenu(
{ menu: getContextMenuOptions($(this)) },
function(action, el, pos){
var path = $(el).attr('data-path');
setMenus(action, path);
});
}
);
}
if(config.options.showConfirmation) $.prompt(lg.successful_added_folder);
};
/*---------------------------------------------------------
Functions to Retrieve File and Folder Details
---------------------------------------------------------*/
// Decides whether to retrieve file or folder info based on
// the path provided.
var getDetailView = function(path) {
if(path.lastIndexOf('/') == path.length - 1){
getFolderInfo(path);
$('#filetree').find('a[data-path="' + path + '"]').click();
} else {
getFileInfo(path);
}
};
function getContextMenuOptions(elem) {
var optionsID = elem.attr('class').replace(/ /g, '_');
if (optionsID == "") return 'itemOptions';
if (!($('#' + optionsID).length)) {
// Create a clone to itemOptions with menus specific to this element
var newOptions = $('#itemOptions').clone().attr('id', optionsID);
if (!elem.hasClass('cap_select')) $('.select', newOptions).remove();
if (!elem.hasClass('cap_download')) $('.download', newOptions).remove();
if (!elem.hasClass('cap_rename')) $('.rename', newOptions).remove();
if (!elem.hasClass('cap_move')) $('.move', newOptions).remove();
$('.replace', newOptions).remove(); // we remove replace since it is not implemented on Opera + Chrome and works only if #preview panel is on on FF
if (!elem.hasClass('cap_delete')) $('.delete', newOptions).remove();
$('#itemOptions').after(newOptions);
}
return optionsID;
}
// Binds contextual menus to items in list and grid views.
var setMenus = function(action, path) {
var d = new Date(); // to prevent IE cache issues
$.getJSON(fileConnector + '?mode=getinfo&path=' + path + '&time=' + d.getMilliseconds(), function(data){
if($('#fileinfo').data('view') == 'grid'){
var item = $('#fileinfo').find('img[data-path="' + data['Path'] + '"]').parent();
} else {
var item = $('#fileinfo').find('td[data-path="' + data['Path'] + '"]').parent();
}
switch(action){
case 'select':
selectItem(data);
break;
case 'download': // todo implement javascript method to test if exstension is correct
window.location = fileConnector + '?mode=download&path=' + data['Path'] + '&time=' + d.getMilliseconds();
break;
case 'rename':
var newName = renameItem(data);
break;
case 'replace':
replaceItem(data);
break;
case 'move':
var newName = moveItem(data);
break;
case 'delete':
deleteItem(data);
break;
}
});
};
// Retrieves information about the specified file as a JSON
// object and uses that data to populate a template for
// detail views. Binds the toolbar for that detail view to
// enable specific actions. Called whenever an item is
// clicked in the file tree or list views.
var getFileInfo = function(file) {
// Update location for status, upload, & new folder functions.
var currentpath = file.substr(0, file.lastIndexOf('/') + 1);
setUploader(currentpath);
// Include the template.
var template = '<div id="preview"><img /><h1></h1><dl></dl></div>';
template += '<form id="toolbar">';
template += '<button id="parentfolder">' + lg.parentfolder + '</button>';
if($.inArray('select', capabilities) != -1 && ($.urlParam('CKEditor') || window.opener || window.tinyMCEPopup || $.urlParam('field_name'))) template += '<button id="select" name="select" type="button" value="Select">' + lg.select + '</button>';
if($.inArray('download', capabilities) != -1) template += '<button id="download" name="download" type="button" value="Download">' + lg.download + '</button>';
if($.inArray('rename', capabilities) != -1 && config.options.browseOnly != true) template += '<button id="rename" name="rename" type="button" value="Rename">' + lg.rename + '</button>';
if($.inArray('move', capabilities) != -1 && config.options.browseOnly != true) template += '<button id="move" name="move" type="button" value="Move">' + lg.move + '</button>';
if($.inArray('delete', capabilities) != -1 && config.options.browseOnly != true) template += '<button id="delete" name="delete" type="button" value="Delete">' + lg.del + '</button>';
if($.inArray('replace', capabilities) != -1 && config.options.browseOnly != true) {
template += '<button id="replace" name="replace" type="button" value="Replace">' + lg.replace + '</button>';
template += '<div class="hidden-file-input"><input id="fileR" name="fileR" type="file" /></div>';
template += '<input id="mode" name="mode" type="hidden" value="replace" /> ';
template += '<input name="_token" type="hidden" value="'+ $("input[name='_token']").val() +'" /> ';
template += '<input id="newfilepath" name="newfilepath" type="hidden" />';
}
template += '</form>';
$('#fileinfo').html(template);
$('#parentfolder').click(function() {getFolderInfo(currentpath);});
// Retrieve the data & populate the template.
var d = new Date(); // to prevent IE cache issues
$.getJSON(fileConnector + '?mode=getinfo&path=' + encodeURIComponent(file) + '&time=' + d.getMilliseconds(), function(data){
if(data['Code'] == 0){
$('#fileinfo').find('h1').text(data['Filename']).attr('title', file);
$('#fileinfo').find('img').attr('src',data['Preview']);
if(isVideoFile(data['Filename']) && config.videos.showVideoPlayer == true) {
getVideoPlayer(data);
}
if(isAudioFile(data['Filename']) && config.audios.showAudioPlayer == true) {
getAudioPlayer(data);
}
if(isEditableFile(data['Filename']) && config.edit.enabled == true) {
editItem(data);
}
var properties = '';
if(data['Properties']['Width'] && data['Properties']['Width'] != '') properties += '<dt>' + lg.dimensions + '</dt><dd>' + data['Properties']['Width'] + 'x' + data['Properties']['Height'] + '</dd>';
if(data['Properties']['Date Created'] && data['Properties']['Date Created'] != '') properties += '<dt>' + lg.created + '</dt><dd>' + data['Properties']['Date Created'] + '</dd>';
if(data['Properties']['Date Modified'] && data['Properties']['Date Modified'] != '') properties += '<dt>' + lg.modified + '</dt><dd>' + data['Properties']['Date Modified'] + '</dd>';
if(data['Properties']['Size'] || parseInt(data['Properties']['Size'])==0) properties += '<dt>' + lg.size + '</dt><dd>' + formatBytes(data['Properties']['Size']) + '</dd>';
$('#fileinfo').find('dl').html(properties);
// Bind toolbar functions.
bindToolbar(data);
} else {
$.prompt(data['Error']);
}
});
};
// Retrieves data for all items within the given folder and
// creates a list view. Binds contextual menu options.
// TODO: consider stylesheet switching to switch between grid
// and list views with sorting options.
var getFolderInfo = function(path) {
// Update location for status, upload, & new folder functions.
setUploader(path);
// Display an activity indicator.
$('#fileinfo').html('<img id="activity" src="images/wait30trans.gif" width="30" height="30" />');
// Retrieve the data and generate the markup.
var d = new Date(); // to prevent IE cache issues
var url = fileConnector + '?path=' + encodeURIComponent(path) + '&mode=getfolder&showThumbs=' + config.options.showThumbs + '&time=' + d.getMilliseconds();
if ($.urlParam('type')) url += '&type=' + $.urlParam('type');
$.getJSON(url, function(data){
var result = '';
// Is there any error or user is unauthorized?
if(data.Code=='-1') {
handleError(data.Error);
return;
};
if(data){
if($('#fileinfo').data('view') == 'grid'){
result += '<ul id="contents" class="grid">';
for(key in data){
var props = data[key]['Properties'];
var cap_classes = "";
for (cap in capabilities) {
if (has_capability(data[key], capabilities[cap])) {
cap_classes += " cap_" + capabilities[cap];
}
}
var scaledWidth = 64;
var actualWidth = props['Width'];
if(actualWidth > 1 && actualWidth < scaledWidth) scaledWidth = actualWidth;
config.options.showTitleAttr ? title = ' title="' + data[key]['Path'] + '"' : title = '';
result += '<li class="' + cap_classes + '"' + title + '"><div class="clip"><img src="' + data[key]['Preview'] + '" width="' + scaledWidth + '" alt="' + data[key]['Path'] + '" data-path="' + data[key]['Path'] + '" /></div><p>' + data[key]['Filename'] + '</p>';
if(props['Width'] && props['Width'] != '') result += '<span class="meta dimensions">' + props['Width'] + 'x' + props['Height'] + '</span>';
if(props['Size'] && props['Size'] != '') result += '<span class="meta size">' + props['Size'] + '</span>';
if(props['Date Created'] && props['Date Created'] != '') result += '<span class="meta created">' + props['Date Created'] + '</span>';
if(props['Date Modified'] && props['Date Modified'] != '') result += '<span class="meta modified">' + props['Date Modified'] + '</span>';
result += '</li>';
}
result += '</ul>';
} else {
result += '<table id="contents" class="list">';
result += '<thead><tr><th class="headerSortDown"><span>' + lg.name + '</span></th><th><span>' + lg.dimensions + '</span></th><th><span>' + lg.size + '</span></th><th><span>' + lg.modified + '</span></th></tr></thead>';
result += '<tbody>';
for(key in data){
var path = data[key]['Path'];
var props = data[key]['Properties'];
var cap_classes = "";
config.options.showTitleAttr ? title = ' title="' + data[key]['Path'] + '"' : title = '';
for (cap in capabilities) {
if (has_capability(data[key], capabilities[cap])) {
cap_classes += " cap_" + capabilities[cap];
}
}
result += '<tr class="' + cap_classes + '">';
result += '<td data-path="' + data[key]['Path'] + '"' + title + '">' + data[key]['Filename'] + '</td>';
if(props['Width'] && props['Width'] != ''){
result += ('<td>' + props['Width'] + 'x' + props['Height'] + '</td>');
} else {
result += '<td></td>';
}
if(props['Size'] && props['Size'] != ''){
result += '<td><abbr title="' + props['Size'] + '">' + formatBytes(props['Size']) + '</abbr></td>';
} else {
result += '<td></td>';
}
if(props['Date Modified'] && props['Date Modified'] != ''){
result += '<td>' + props['Date Modified'] + '</td>';
} else {
result += '<td></td>';
}
result += '</tr>';
}
result += '</tbody>';
result += '</table>';
}
} else {
result += '<h1>' + lg.could_not_retrieve_folder + '</h1>';
}
// Add the new markup to the DOM.
$('#fileinfo').html(result);
// Bind click events to create detail views and add
// contextual menu options.
if($('#fileinfo').data('view') == 'grid') {
$('#fileinfo').find('#contents li').click(function(){
var path = $(this).find('img').attr('data-path');
getDetailView(path);
}).each(function() {
$(this).contextMenu(
{ menu: getContextMenuOptions($(this)) },
function(action, el, pos){
var path = $(el).find('img').attr('data-path');
setMenus(action, path);
}
);
});
} else {
$('#fileinfo tbody tr').click(function(){
var path = $('td:first-child', this).attr('data-path');
getDetailView(path);
}).each(function() {
$(this).contextMenu(
{ menu: getContextMenuOptions($(this)) },
function(action, el, pos){
var path = $('td:first-child', el).attr('data-path');
setMenus(action, path);
}
);
});
$('#fileinfo').find('table').tablesorter({
textExtraction: function(node){
if($(node).find('abbr').size()){
return $(node).find('abbr').attr('title');
} else {
return node.innerHTML;
}
}
});
// Calling display_icons() function
// to get icons from filteree
// Necessary to fix bug #170
// https://github.com/simogeo/Filemanager/issues/170
var timer = setInterval(function() {display_icons(timer)}, 300);
}
});
};
// Retrieve data (file/folder listing) for jqueryFileTree and pass the data back
// to the callback function in jqueryFileTree
var populateFileTree = function(path, callback) {
var d = new Date(); // to prevent IE cache issues
var url = fileConnector + '?path=' + encodeURIComponent(path) + '&mode=getfolder&showThumbs=' + config.options.showThumbs + '&time=' + d.getMilliseconds();
if ($.urlParam('type')) url += '&type=' + $.urlParam('type');
$.getJSON(url, function(data) {
var result = '';
// Is there any error or user is unauthorized?
if(data.Code=='-1') {
handleError(data.Error);
return;
};
if(data) {
result += "<ul class=\"jqueryFileTree\" style=\"display: none;\">";
for(key in data) {
var cap_classes = "";
for (cap in capabilities) {
if (has_capability(data[key], capabilities[cap])) {
cap_classes += " cap_" + capabilities[cap];
}
}
if (data[key]['File Type'] == 'dir') {
result += "<li class=\"directory collapsed\"><a href=\"#\" class=\"" + cap_classes + "\" data-path=\"" + data[key]['Path'] + "\">" + data[key]['Filename'] + "</a></li>";
} else {
if(config.options.listFiles) {
result += "<li class=\"file ext_" + data[key]['File Type'].toLowerCase() + "\"><a href=\"#\" class=\"" + cap_classes + "\" data-path=\"" + data[key]['Path'] + "\">" + data[key]['Filename'] + "</a></li>";
}
}
}
result += "</ul>";
} else {
result += '<h1>' + lg.could_not_retrieve_folder + '</h1>';
}
callback(result);
});
};
/*---------------------------------------------------------
Initialization
---------------------------------------------------------*/
$(function(){
if(config.extras.extra_js) {
for(var i=0; i< config.extras.extra_js.length; i++) {
$.ajax({
url: config.extras.extra_js[i],
dataType: "script",
async: config.extras.extra_js_async
});
}
}
// Loading CodeMirror if enabled for online edition
if(config.edit.enabled) {
loadCSS('./scripts/CodeMirror/lib/codemirror.css');
loadCSS('./scripts/CodeMirror/theme/' + config.edit.theme + '.css');
loadJS('./scripts/CodeMirror/lib/codemirror.js');
loadJS('./scripts/CodeMirror/addon/selection/active-line.js');
loadJS('./scripts/CodeMirror/dynamic-mode.js');
}
if(!config.options.fileRoot) {
fileRoot = '/' + document.location.pathname.substring(1, document.location.pathname.lastIndexOf('/') + 1) + 'userfiles/';
} else {
if(!config.options.serverRoot) {
fileRoot = config.options.fileRoot;
} else {
fileRoot = '/' + config.options.fileRoot;
}
// we remove double slashes - can happen when using PHP SetFileRoot() function with fileRoot = '/' value
fileRoot = fileRoot.replace(/\/\//g, '\/');
}
if(config.options.relPath === false) {
relPath = window.location.protocol + "//" + window.location.host;
} else {
relPath = config.options.relPath;
}
if($.urlParam('exclusiveFolder') != 0) {
fileRoot += $.urlParam('exclusiveFolder');
if(fileRoot.charAt(fileRoot.length-1) != '/' ) fileRoot += '/'; // add last '/' if needed
fileRoot = fileRoot.replace(/\/\//g, '\/');
}
if($.urlParam('expandedFolder') != 0) {
expandedFolder = $.urlParam('expandedFolder');
fullexpandedFolder = fileRoot + expandedFolder;
} else {
expandedFolder = '';
fullexpandedFolder = null;
}
// we finalize the FileManager UI initialization
// with localized text if necessary
if(config.options.autoload == true) {
$('#upload').append(lg.upload);
$('#newfolder').append(lg.new_folder);
$('#grid').attr('title', lg.grid_view);
$('#list').attr('title', lg.list_view);
$('#fileinfo h1').append(lg.select_from_left);
$('#itemOptions a[href$="#select"]').append(lg.select);
$('#itemOptions a[href$="#download"]').append(lg.download);
$('#itemOptions a[href$="#rename"]').append(lg.rename);
$('#itemOptions a[href$="#move"]').append(lg.move);
$('#itemOptions a[href$="#replace"]').append(lg.replace);
$('#itemOptions a[href$="#delete"]').append(lg.del);
}
/** Adding a close button triggering callback function if CKEditorCleanUpFuncNum passed */
if($.urlParam('CKEditorCleanUpFuncNum')) {
$("body").append('<button id="close-btn" type="button">' + lg.close + '</button>');
$('#close-btn').click(function () {
parent.CKEDITOR.tools.callFunction($.urlParam('CKEditorCleanUpFuncNum'));
});
}
/** Input file Replacement */
$('#browse').append('+');
$('#browse').attr('title', lg.browse);
$("#newfile").change(function() {
$("#filepath").val($(this).val().replace(/.+[\\\/]/, ""));
});
/** load searchbox */
if(config.options.searchBox === true) {
loadJS("./scripts/filemanager.liveSearch.min.js");
} else {
$('#search').remove();
}
// cosmetic tweak for buttons
$('button').wrapInner('<span></span>');
// Set initial view state.
$('#fileinfo').data('view', config.options.defaultViewMode);
setViewButtonsFor(config.options.defaultViewMode);
$('#home').click(function() {
var currentViewMode = $('#fileinfo').data('view');
$('#fileinfo').data('view', currentViewMode);
$('#filetree>ul>li.expanded>a').trigger('click');
getFolderInfo(fileRoot);
});
// Set buttons to switch between grid and list views.
$('#grid').click(function() {
setViewButtonsFor('grid');
$('#fileinfo').data('view', 'grid');
getFolderInfo($('#currentpath').val());
});
$('#list').click(function() {
setViewButtonsFor('list');
$('#fileinfo').data('view', 'list');
getFolderInfo($('#currentpath').val());
});
// Provide initial values for upload form, status, etc.
setUploader(fileRoot);
$('#uploader').attr('action', fileConnector);
$('#uploader').ajaxForm({
target: '#uploadresponse',
beforeSubmit: function (arr, form, options) {
// Test if a value is given
if($('#newfile', form).val()=='') {
return false;
}
// Check if file extension is allowed
if (!isAuthorizedFile($('#newfile', form).val())) {
var str = '<p>' + lg.INVALID_FILE_TYPE + '</p>';
if(config.security.uploadPolicy == 'DISALLOW_ALL') {
str += '<p>' + lg.ALLOWED_FILE_TYPE + config.security.uploadRestrictions.join(', ') + '.</p>';
}
if(config.security.uploadPolicy == 'ALLOW_ALL') {
str += '<p>' + lg.DISALLOWED_FILE_TYPE + config.security.uploadRestrictions.join(', ') + '.</p>';
}
$("#filepath").val('');
$.prompt(str);
return false;
}
$('#upload').attr('disabled', true);
$('#upload span').addClass('loading').text(lg.loading_data);
if ($.urlParam('type').toString().toLowerCase() == 'images') {
// Test if uploaded file extension is in valid image extensions
var newfileSplitted = $('#newfile', form).val().toLowerCase().split('.');
var found = false;
for (key in config.images.imagesExt) {
if (config.images.imagesExt[key] == newfileSplitted[newfileSplitted.length - 1]) {
found = true;
}
}
if (found === false) {
$.prompt(lg.UPLOAD_IMAGES_ONLY);
$('#upload').removeAttr('disabled').find("span").removeClass('loading').text(lg.upload);
return false;
}
}
// if config.upload.fileSizeLimit == auto we delegate size test to connector
if (typeof FileReader !== "undefined" && typeof config.upload.fileSizeLimit != "auto") {
// Check file size using html5 FileReader API
var size = $('#newfile', form).get(0).files[0].size;
if (size > config.upload.fileSizeLimit * 1024 * 1024) {
$.prompt("<p>" + lg.file_too_big + "</p><p>" + lg.file_size_limit + config.upload.fileSizeLimit + " " + lg.mb + ".</p>");
$('#upload').removeAttr('disabled').find("span").removeClass('loading').text(lg.upload);
return false;
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('#upload').removeAttr('disabled').find("span").removeClass('loading').text(lg.upload);
$.prompt(lg.ERROR_UPLOADING_FILE);
},
success: function (result) {
var data = jQuery.parseJSON($('#uploadresponse').find('textarea').text());
if (data['Code'] == 0) {
addNode(data['Path'], data['Name']);
$("#filepath, #newfile").val('');
// IE can not empty input='file'. A fix consist to replace the element (see github issue #215)
if($.browser.msie) $("#newfile").replaceWith($("#newfile").clone(true));
// seems to be necessary when dealing w/ files located on s3 (need to look into a cleaner solution going forward)
$('#filetree').find('a[data-path="' + data['Path'] + '/"]').click().click();
} else {
$.prompt(data['Error']);
}
$('#upload').removeAttr('disabled');
$('#upload span').removeClass('loading').text(lg.upload);
$("#filepath").val('');
}
});
// Creates file tree.
createFileTree();
// Disable select function if no window.opener
if(! (window.opener || window.tinyMCEPopup || $.urlParam('field_name')) ) $('#itemOptions a[href$="#select"]').remove();
// Keep only browseOnly features if needed
if(config.options.browseOnly == true) {
$('#file-input-container').remove();
$('#upload').remove();
$('#newfolder').remove();
$('#toolbar').remove('#rename');
$('.contextMenu .rename').remove();
$('.contextMenu .move').remove();
$('.contextMenu .replace').remove();
$('.contextMenu .delete').remove();
}
// Adjust layout.
setDimensions();
$(window).resize(setDimensions);
// Provides support for adjustible columns.
$('#splitter').splitter({
sizeLeft: 200
});
getDetailView(fileRoot + expandedFolder);
});
// add useragent string to html element for IE 10/11 detection
var doc = document.documentElement;
doc.setAttribute('data-useragent', navigator.userAgent);
})(jQuery);
|
import { actionLinks } from './lib/actionLinks';
import './actionLinkHandler';
export {
actionLinks,
};
|
import React, { cloneElement, Component, PropTypes } from "react";
import Radium from "radium";
@Radium
export default class Overview extends Component {
_renderSlides() {
const slide = this.props.slide;
return this.props.slides.map((child, index) => {
if (index < slide - 3 || slide + 3 < index) { return false; }
const left = `${(50 + 30.6667 * (index - slide))}%`;
const style = {
position: "absolute",
width: "25%",
height: "25%",
top: "50%",
left,
transform: " translate(-50%,-50%)",
border: "1px solid #FFF",
opacity: index === slide ? 1 : 0.5
};
const el = cloneElement(child, {
key: index,
slideIndex: index,
transition: [],
transitionDuration: 0,
appearOff: true
});
return (
<div key={index} style={[style]}>
{el}
</div>
);
});
}
render() {
const styles = {
overview: {
height: "100%",
width: "100%"
}
};
return (
<div className="spectacle-overview" style={[styles.overview]}>
{this._renderSlides()}
</div>
);
}
}
Overview.propTypes = {
slides: PropTypes.array,
slide: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};
Overview.contextTypes = {
styles: PropTypes.object
};
|
/*global requirejs*/
/*jshint browser:true*/
(function (files, callback) {
'use strict';
var file, match, tests = [], libs = {};
for (file in files) {
if (files.hasOwnProperty(file)) {
// collect tests
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
// collect test framework's libs
match = file.match(/TestFrameworkBundle\/Karma\/lib\/(?:[\w\W]+\/)*([\w\-\.]+)\.js$/);
if (match && match[1] !== 'require-config') {
libs[match[1]] = file.slice(0, -3);
}
}
}
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base/web/bundles',
paths: libs,
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: callback
});
}(window.__karma__.files, window.__karma__.start));
|
/**
* Durandal 2.0.0-pre Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved.
* Available via the MIT license.
* see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details.
*/
/**
* The viewLocator module collaborates with the viewEngine module to provide views (literally dom sub-trees) to other parts of the framework as needed. The primary consumer of the viewLocator is the composition module.
* @module viewModelBinder
* @requires system
* @requires knockout
*/
define(['durandal/system', 'knockout'], function (system, ko) {
var viewModelBinder,
insufficientInfoMessage = 'Insufficient Information to Bind',
unexpectedViewMessage = 'Unexpected View Type',
bindingInstructionKey = 'durandal-binding-instruction',
koBindingContextKey = '__ko_bindingContext__';
function normalizeBindingInstruction(result){
if(result === undefined){
return { applyBindings: true };
}
if(system.isBoolean(result)){
return { applyBindings:result };
}
if(result.applyBindings === undefined){
result.applyBindings = true;
}
return result;
}
function doBind(obj, view, bindingTarget, data){
if (!view || !bindingTarget) {
if (viewModelBinder.throwOnErrors) {
system.error(insufficientInfoMessage);
} else {
system.log(insufficientInfoMessage, view, data);
}
return;
}
if (!view.getAttribute) {
if (viewModelBinder.throwOnErrors) {
system.error(unexpectedViewMessage);
} else {
system.log(unexpectedViewMessage, view, data);
}
return;
}
var viewName = view.getAttribute('data-view');
try {
var instruction;
if (obj && obj.binding) {
instruction = obj.binding(view);
}
instruction = normalizeBindingInstruction(instruction);
viewModelBinder.beforeBind(data, view, instruction);
if(instruction.applyBindings){
system.log('Binding', viewName, data);
ko.applyBindings(bindingTarget, view);
}else if(obj){
ko.utils.domData.set(view, koBindingContextKey, { $data:obj });
}
viewModelBinder.afterBind(data, view, instruction);
if (obj && obj.bindingComplete) {
obj.bindingComplete(view);
}
ko.utils.domData.set(view, bindingInstructionKey, instruction);
return instruction;
} catch (e) {
e.message = e.message + ';\nView: ' + viewName + ";\nModuleId: " + system.getModuleId(data);
if (viewModelBinder.throwOnErrors) {
system.error(e);
} else {
system.log(e.message);
}
}
}
/**
* @class ViewModelBinderModule
* @static
*/
return viewModelBinder = {
/**
* Called before every binding operation. Does nothing by default.
* @method beforeBind
* @param {object} data The data that is about to be bound.
* @param {DOMElement} view The view that is about to be bound.
* @param {object} instruction The object that carries the binding instructions.
*/
beforeBind: system.noop,
/**
* Called after every binding operation. Does nothing by default.
* @method afterBind
* @param {object} data The data that has just been bound.
* @param {DOMElement} view The view that has just been bound.
* @param {object} instruction The object that carries the binding instructions.
*/
afterBind: system.noop,
/**
* Indicates whether or not the binding system should throw errors or not.
* @property {boolean} throwOnErrors
* @default false The binding system will not throw errors by default. Instead it will log them.
*/
throwOnErrors: false,
/**
* Gets the binding instruction that was associated with a view when it was bound.
* @method getBindingInstruction
* @param {DOMElement} view The view that was previously bound.
* @return {object} The object that carries the binding instructions.
*/
getBindingInstruction:function(view){
return ko.utils.domData.get(view, bindingInstructionKey);
},
/**
* Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context.
* @method bindContext
* @param {KnockoutBindingContext} bindingContext The current binding context.
* @param {DOMElement} view The view to bind.
* @param {object} [obj] The data to bind to, causing the creation of a child binding context if present.
*/
bindContext: function(bindingContext, view, obj) {
if (obj) {
bindingContext = bindingContext.createChildContext(obj);
}
return doBind(obj, view, bindingContext, obj || bindingContext.$data);
},
/**
* Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context.
* @method bind
* @param {object} obj The data to bind to.
* @param {DOMElement} view The view to bind.
*/
bind: function(obj, view) {
return doBind(obj, view, obj, obj);
}
};
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:cab88156472b93cebbadd6957f297f7780ba4d97520d742440049174bf3a39fb
size 10187
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods.
*
* @class Phaser.Physics.Arcade
* @constructor
* @param {Phaser.Game} game - reference to the current game instance.
*/
Phaser.Physics.Arcade = function (game) {
/**
* @property {Phaser.Game} game - Local reference to game.
*/
this.game = game;
/**
* @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity.
*/
this.gravity = new Phaser.Point();
/**
* @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
*/
this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
/**
* Which edges of the World bounds Bodies can collide against when `collideWorldBounds` is `true`.
* For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom.
* @property {object} checkCollision - An object containing allowed collision flags (up, down, left, right).
*/
this.checkCollision = { up: true, down: true, left: true, right: true };
/**
* @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
*/
this.maxObjects = 10;
/**
* @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
*/
this.maxLevels = 4;
/**
* @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks.
*/
this.OVERLAP_BIAS = 4;
/**
* @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first.
*/
this.forceX = false;
/**
* @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT.
* @default
*/
this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT;
/**
* @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`.
*/
this.skipQuadTree = true;
/**
* @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies.
*/
this.isPaused = false;
/**
* @property {Phaser.QuadTree} quadTree - The world QuadTree.
*/
this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
/**
* @property {number} _total - Internal cache var.
* @private
*/
this._total = 0;
// By default we want the bounds the same size as the world bounds
this.setBoundsToWorld();
};
Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade;
/**
* A constant used for the sortDirection value.
* Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups.
* @constant
* @type {number}
*/
Phaser.Physics.Arcade.SORT_NONE = 0;
/**
* A constant used for the sortDirection value.
* Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario)
* @constant
* @type {number}
*/
Phaser.Physics.Arcade.LEFT_RIGHT = 1;
/**
* A constant used for the sortDirection value.
* Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards)
* @constant
* @type {number}
*/
Phaser.Physics.Arcade.RIGHT_LEFT = 2;
/**
* A constant used for the sortDirection value.
* Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug)
* @constant
* @type {number}
*/
Phaser.Physics.Arcade.TOP_BOTTOM = 3;
/**
* A constant used for the sortDirection value.
* Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up)
* @constant
* @type {number}
*/
Phaser.Physics.Arcade.BOTTOM_TOP = 4;
Phaser.Physics.Arcade.prototype = {
/**
* Updates the size of this physics world.
*
* @method Phaser.Physics.Arcade#setBounds
* @param {number} x - Top left most corner of the world.
* @param {number} y - Top left most corner of the world.
* @param {number} width - New width of the world. Can never be smaller than the Game.width.
* @param {number} height - New height of the world. Can never be smaller than the Game.height.
*/
setBounds: function (x, y, width, height) {
this.bounds.setTo(x, y, width, height);
},
/**
* Updates the size of this physics world to match the size of the game world.
*
* @method Phaser.Physics.Arcade#setBoundsToWorld
*/
setBoundsToWorld: function () {
this.bounds.copyFrom(this.game.world.bounds);
},
/**
* This will create an Arcade Physics body on the given game object or array of game objects.
* A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
*
* @method Phaser.Physics.Arcade#enable
* @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
* @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
*/
enable: function (object, children) {
if (children === undefined) { children = true; }
var i = 1;
if (Array.isArray(object))
{
i = object.length;
while (i--)
{
if (object[i] instanceof Phaser.Group)
{
// If it's a Group then we do it on the children regardless
this.enable(object[i].children, children);
}
else
{
this.enableBody(object[i]);
if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
{
this.enable(object[i], true);
}
}
}
}
else
{
if (object instanceof Phaser.Group)
{
// If it's a Group then we do it on the children regardless
this.enable(object.children, children);
}
else
{
this.enableBody(object);
if (children && object.hasOwnProperty('children') && object.children.length > 0)
{
this.enable(object.children, true);
}
}
}
},
/**
* Creates an Arcade Physics body on the given game object.
*
* A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
*
* When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array.
*
* @method Phaser.Physics.Arcade#enableBody
* @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
*/
enableBody: function (object) {
if (object.hasOwnProperty('body') && object.body === null)
{
object.body = new Phaser.Physics.Arcade.Body(object);
if (object.parent && object.parent instanceof Phaser.Group)
{
object.parent.addToHash(object);
}
}
},
/**
* Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`.
*
* @method Phaser.Physics.Arcade#updateMotion
* @param {Phaser.Physics.Arcade.Body} The Body object to be updated.
*/
updateMotion: function (body) {
var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity;
body.angularVelocity += velocityDelta;
body.rotation += (body.angularVelocity * this.game.time.physicsElapsed);
body.velocity.x = this.computeVelocity(1, body, body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x);
body.velocity.y = this.computeVelocity(2, body, body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y);
},
/**
* A tween-like function that takes a starting velocity and some other factors and returns an altered velocity.
* Based on a function in Flixel by @ADAMATOMIC
*
* @method Phaser.Physics.Arcade#computeVelocity
* @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical.
* @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated.
* @param {number} velocity - Any component of velocity (e.g. 20).
* @param {number} acceleration - Rate at which the velocity is changing.
* @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set.
* @param {number} [max=10000] - An absolute value cap for the velocity.
* @return {number} The altered Velocity value.
*/
computeVelocity: function (axis, body, velocity, acceleration, drag, max) {
if (max === undefined) { max = 10000; }
if (axis === 1 && body.allowGravity)
{
velocity += (this.gravity.x + body.gravity.x) * this.game.time.physicsElapsed;
}
else if (axis === 2 && body.allowGravity)
{
velocity += (this.gravity.y + body.gravity.y) * this.game.time.physicsElapsed;
}
if (acceleration)
{
velocity += acceleration * this.game.time.physicsElapsed;
}
else if (drag)
{
drag *= this.game.time.physicsElapsed;
if (velocity - drag > 0)
{
velocity -= drag;
}
else if (velocity + drag < 0)
{
velocity += drag;
}
else
{
velocity = 0;
}
}
if (velocity > max)
{
velocity = max;
}
else if (velocity < -max)
{
velocity = -max;
}
return velocity;
},
/**
* Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
* You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
* Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
* Both the first and second parameter can be arrays of objects, of differing types.
* If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter.
* NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups within Groups).
*
* @method Phaser.Physics.Arcade#overlap
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
* @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`.
* @param {object} [callbackContext] - The context in which to run the callbacks.
* @return {boolean} True if an overlap occurred otherwise false.
*/
overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
overlapCallback = overlapCallback || null;
processCallback = processCallback || null;
callbackContext = callbackContext || overlapCallback;
this._total = 0;
if (!Array.isArray(object1) && Array.isArray(object2))
{
for (var i = 0; i < object2.length; i++)
{
this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
}
}
else if (Array.isArray(object1) && !Array.isArray(object2))
{
for (var i = 0; i < object1.length; i++)
{
this.collideHandler(object1[i], object2, overlapCallback, processCallback, callbackContext, true);
}
}
else if (Array.isArray(object1) && Array.isArray(object2))
{
for (var i = 0; i < object1.length; i++)
{
for (var j = 0; j < object2.length; j++)
{
this.collideHandler(object1[i], object2[j], overlapCallback, processCallback, callbackContext, true);
}
}
}
else
{
this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
}
return (this._total > 0);
},
/**
* Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
* Both the first and second parameter can be arrays of objects, of differing types.
* If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter.
* The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
* An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place,
* giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped.
* The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called.
* NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups).
*
* @method Phaser.Physics.Arcade#collide
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer.
* @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter.
* @param {object} [callbackContext] - The context in which to run the callbacks.
* @return {boolean} True if a collision occurred otherwise false.
*/
collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
collideCallback = collideCallback || null;
processCallback = processCallback || null;
callbackContext = callbackContext || collideCallback;
this._total = 0;
if (!Array.isArray(object1) && Array.isArray(object2))
{
for (var i = 0; i < object2.length; i++)
{
this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
}
}
else if (Array.isArray(object1) && !Array.isArray(object2))
{
for (var i = 0; i < object1.length; i++)
{
this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, false);
}
}
else if (Array.isArray(object1) && Array.isArray(object2))
{
for (var i = 0; i < object1.length; i++)
{
for (var j = 0; j < object2.length; j++)
{
this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, false);
}
}
}
else
{
this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
}
return (this._total > 0);
},
/**
* A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction.
*
* This is called automatically by World.sort
*
* @method Phaser.Physics.Arcade#sortLeftRight
* @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
* @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
* @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
*/
sortLeftRight: function (a, b) {
if (!a.body || !b.body)
{
return 0;
}
return a.body.x - b.body.x;
},
/**
* A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction.
*
* This is called automatically by World.sort
*
* @method Phaser.Physics.Arcade#sortRightLeft
* @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
* @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
* @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
*/
sortRightLeft: function (a, b) {
if (!a.body || !b.body)
{
return 0;
}
return b.body.x - a.body.x;
},
/**
* A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction.
*
* This is called automatically by World.sort
*
* @method Phaser.Physics.Arcade#sortTopBottom
* @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
* @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
* @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
*/
sortTopBottom: function (a, b) {
if (!a.body || !b.body)
{
return 0;
}
return a.body.y - b.body.y;
},
/**
* A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction.
*
* This is called automatically by World.sort
*
* @method Phaser.Physics.Arcade#sortBottomTop
* @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
* @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
* @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
*/
sortBottomTop: function (a, b) {
if (!a.body || !b.body)
{
return 0;
}
return b.body.y - a.body.y;
},
/**
* This method will sort a Groups hash array.
*
* If the Group has `physicsSortDirection` set it will use the sort direction defined.
*
* Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection.
*
* By changing Group.physicsSortDirection you can customise each Group to sort in a different order.
*
* @method Phaser.Physics.Arcade#sort
* @param {Phaser.Group} group - The Group to sort.
* @param {integer} [sortDirection] - The sort direction used to sort this Group.
*/
sort: function (group, sortDirection) {
if (group.physicsSortDirection !== null)
{
sortDirection = group.physicsSortDirection;
}
else
{
if (sortDirection === undefined) { sortDirection = this.sortDirection; }
}
if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
{
// Game world is say 2000x600 and you start at 0
group.hash.sort(this.sortLeftRight);
}
else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
{
// Game world is say 2000x600 and you start at 2000
group.hash.sort(this.sortRightLeft);
}
else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
{
// Game world is say 800x2000 and you start at 0
group.hash.sort(this.sortTopBottom);
}
else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
{
// Game world is say 800x2000 and you start at 2000
group.hash.sort(this.sortBottomTop);
}
},
/**
* Internal collision handler.
*
* @method Phaser.Physics.Arcade#collideHandler
* @private
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
* @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check.
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} callbackContext - The context in which to run the callbacks.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
*/
collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
// Only collide valid objects
if (object2 === undefined && object1.physicsType === Phaser.GROUP)
{
this.sort(object1);
this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
return;
}
// If neither of the objects are set or exist then bail out
if (!object1 || !object2 || !object1.exists || !object2.exists)
{
return;
}
// Groups? Sort them
if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE)
{
if (object1.physicsType === Phaser.GROUP)
{
this.sort(object1);
}
if (object2.physicsType === Phaser.GROUP)
{
this.sort(object2);
}
}
// SPRITES
if (object1.physicsType === Phaser.SPRITE)
{
if (object2.physicsType === Phaser.SPRITE)
{
this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.physicsType === Phaser.GROUP)
{
this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.physicsType === Phaser.TILEMAPLAYER)
{
this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
// GROUPS
else if (object1.physicsType === Phaser.GROUP)
{
if (object2.physicsType === Phaser.SPRITE)
{
this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.physicsType === Phaser.GROUP)
{
this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.physicsType === Phaser.TILEMAPLAYER)
{
this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
// TILEMAP LAYERS
else if (object1.physicsType === Phaser.TILEMAPLAYER)
{
if (object2.physicsType === Phaser.SPRITE)
{
this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
else if (object2.physicsType === Phaser.GROUP)
{
this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideSpriteVsSprite
* @private
* @param {Phaser.Sprite} sprite1 - The first sprite to check.
* @param {Phaser.Sprite} sprite2 - The second sprite to check.
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} callbackContext - The context in which to run the callbacks.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
* @return {boolean} True if there was a collision, otherwise false.
*/
collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
if (!sprite1.body || !sprite2.body)
{
return false;
}
if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
{
if (collideCallback)
{
collideCallback.call(callbackContext, sprite1, sprite2);
}
this._total++;
}
return true;
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideSpriteVsGroup
* @private
* @param {Phaser.Sprite} sprite - The sprite to check.
* @param {Phaser.Group} group - The Group to check.
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} callbackContext - The context in which to run the callbacks.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
*/
collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group.length === 0 || !sprite.body)
{
return;
}
if (this.skipQuadTree || sprite.body.skipQuadTree)
{
var bounds = {};
for (var i = 0; i < group.hash.length; i++)
{
var object1 = group.hash[i];
// Skip duff entries - we can't check a non-existent sprite or one with no body
if (!object1 || !object1.exists || !object1.body)
{
continue;
}
// Inject the Body bounds data into the bounds object
bounds = object1.body.getBounds(bounds);
// Skip items either side of the sprite
if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
{
if (sprite.body.right < bounds.x)
{
break;
}
else if (bounds.right < sprite.body.x)
{
continue;
}
}
else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
{
if (sprite.body.x > bounds.right)
{
break;
}
else if (bounds.x > sprite.body.right)
{
continue;
}
}
else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
{
if (sprite.body.bottom < bounds.y)
{
break;
}
else if (bounds.bottom < sprite.body.y)
{
continue;
}
}
else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
{
if (sprite.body.y > bounds.bottom)
{
break;
}
else if (bounds.y > sprite.body.bottom)
{
continue;
}
}
this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
else
{
// What is the sprite colliding with in the quadtree?
this.quadTree.clear();
this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
this.quadTree.populate(group);
var items = this.quadTree.retrieve(sprite);
for (var i = 0; i < items.length; i++)
{
// We have our potential suspects, are they in this group?
if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly))
{
if (collideCallback)
{
collideCallback.call(callbackContext, sprite, items[i].sprite);
}
this._total++;
}
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideGroupVsSelf
* @private
* @param {Phaser.Group} group - The Group to check.
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} callbackContext - The context in which to run the callbacks.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
* @return {boolean} True if there was a collision, otherwise false.
*/
collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group.length === 0)
{
return;
}
for (var i = 0; i < group.hash.length; i++)
{
var bounds1 = {};
var object1 = group.hash[i];
// Skip duff entries - we can't check a non-existent sprite or one with no body
if (!object1 || !object1.exists || !object1.body)
{
continue;
}
// Inject the Body bounds data into the bounds1 object
bounds1 = object1.body.getBounds(bounds1);
for (var j = i + 1; j < group.hash.length; j++)
{
var bounds2 = {};
var object2 = group.hash[j];
// Skip duff entries - we can't check a non-existent sprite or one with no body
if (!object2 || !object2.exists || !object2.body)
{
continue;
}
// Inject the Body bounds data into the bounds2 object
bounds2 = object2.body.getBounds(bounds2);
// Skip items either side of the sprite
if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
{
if (bounds1.right < bounds2.x)
{
break;
}
else if (bounds2.right < bounds1.x)
{
continue;
}
}
else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
{
if (bounds1.x > bounds2.right)
{
continue;
}
else if (bounds2.x > bounds1.right)
{
break;
}
}
else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
{
if (bounds1.bottom < bounds2.y)
{
continue;
}
else if (bounds2.bottom < bounds1.y)
{
break;
}
}
else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
{
if (bounds1.y > bounds2.bottom)
{
continue;
}
else if (bounds2.y > object1.body.bottom)
{
break;
}
}
this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
},
/**
* An internal function. Use Phaser.Physics.Arcade.collide instead.
*
* @method Phaser.Physics.Arcade#collideGroupVsGroup
* @private
* @param {Phaser.Group} group1 - The first Group to check.
* @param {Phaser.Group} group2 - The second Group to check.
* @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
* @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
* @param {object} callbackContext - The context in which to run the callbacks.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
*/
collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
if (group1.length === 0 || group2.length === 0)
{
return;
}
for (var i = 0; i < group1.children.length; i++)
{
if (group1.children[i].exists)
{
if (group1.children[i].physicsType === Phaser.GROUP)
{
this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
}
else
{
this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
}
}
}
},
/**
* The core separation function to separate two physics bodies.
*
* @private
* @method Phaser.Physics.Arcade#separate
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate.
* @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true.
* @param {object} [callbackContext] - The context in which to run the process callback.
* @param {boolean} overlapOnly - Just run an overlap or a full collision.
* @return {boolean} Returns true if the bodies collided, otherwise false.
*/
separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
if (
!body1.enable ||
!body2.enable ||
body1.checkCollision.none ||
body2.checkCollision.none ||
!this.intersects(body1, body2))
{
return false;
}
// They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false)
{
return false;
}
// Circle vs. Circle quick bail out
if (body1.isCircle && body2.isCircle)
{
return this.separateCircle(body1, body2, overlapOnly);
}
// We define the behavior of bodies in a collision circle and rectangle
// If a collision occurs in the corner points of the rectangle, the body behave like circles
// Either body1 or body2 is a circle
if (body1.isCircle !== body2.isCircle)
{
var bodyRect = (body1.isCircle) ? body2 : body1;
var bodyCircle = (body1.isCircle) ? body1 : body2;
var rect = {
x: bodyRect.x,
y: bodyRect.y,
right: bodyRect.right,
bottom: bodyRect.bottom
};
var circle = {
x: bodyCircle.x + bodyCircle.radius,
y: bodyCircle.y + bodyCircle.radius
};
if (circle.y < rect.y || circle.y > rect.bottom)
{
if (circle.x < rect.x || circle.x > rect.right)
{
return this.separateCircle(body1, body2, overlapOnly);
}
}
}
var resultX = false;
var resultY = false;
// Do we separate on x or y first?
if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x))
{
resultX = this.separateX(body1, body2, overlapOnly);
// Are they still intersecting? Let's do the other axis then
if (this.intersects(body1, body2))
{
resultY = this.separateY(body1, body2, overlapOnly);
}
}
else
{
resultY = this.separateY(body1, body2, overlapOnly);
// Are they still intersecting? Let's do the other axis then
if (this.intersects(body1, body2))
{
resultX = this.separateX(body1, body2, overlapOnly);
}
}
var result = (resultX || resultY);
if (result)
{
if (overlapOnly)
{
if (body1.onOverlap)
{
body1.onOverlap.dispatch(body1.sprite, body2.sprite);
}
if (body2.onOverlap)
{
body2.onOverlap.dispatch(body2.sprite, body1.sprite);
}
}
else
{
if (body1.onCollide)
{
body1.onCollide.dispatch(body1.sprite, body2.sprite);
}
if (body2.onCollide)
{
body2.onCollide.dispatch(body2.sprite, body1.sprite);
}
}
}
return result;
},
/**
* Check for intersection against two bodies.
*
* @method Phaser.Physics.Arcade#intersects
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check.
* @return {boolean} True if they intersect, otherwise false.
*/
intersects: function (body1, body2) {
if (body1 === body2)
{
return false;
}
if (body1.isCircle)
{
if (body2.isCircle)
{
// Circle vs. Circle
return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.radius + body2.radius);
}
else
{
// Circle vs. Rect
return this.circleBodyIntersects(body1, body2);
}
}
else
{
if (body2.isCircle)
{
// Rect vs. Circle
return this.circleBodyIntersects(body2, body1);
}
else
{
// Rect vs. Rect
if (body1.right <= body2.position.x)
{
return false;
}
if (body1.bottom <= body2.position.y)
{
return false;
}
if (body1.position.x >= body2.right)
{
return false;
}
if (body1.position.y >= body2.bottom)
{
return false;
}
return true;
}
}
},
/**
* Checks to see if a circular Body intersects with a Rectangular Body.
*
* @method Phaser.Physics.Arcade#circleBodyIntersects
* @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set.
* @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape)
* @return {boolean} Returns true if the bodies intersect, otherwise false.
*/
circleBodyIntersects: function (circle, body) {
var x = Phaser.Math.clamp(circle.center.x, body.left, body.right);
var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom);
var dx = (circle.center.x - x) * (circle.center.x - x);
var dy = (circle.center.y - y) * (circle.center.y - y);
return (dx + dy) <= (circle.radius * circle.radius);
},
/**
* The core separation function to separate two circular physics bodies.
*
* @method Phaser.Physics.Arcade#separateCircle
* @private
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`.
* @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
* @return {boolean} Returns true if the bodies were separated or overlap, otherwise false.
*/
separateCircle: function (body1, body2, overlapOnly) {
// Set the bounding box overlap values
this.getOverlapX(body1, body2);
this.getOverlapY(body1, body2);
var dx = body2.center.x - body1.center.x;
var dy = body2.center.y - body1.center.y;
var angleCollision = Math.atan2(dy, dx);
var overlap = 0;
if (body1.isCircle !== body2.isCircle)
{
var rect = {
x: (body2.isCircle) ? body1.position.x : body2.position.x,
y: (body2.isCircle) ? body1.position.y : body2.position.y,
right: (body2.isCircle) ? body1.right : body2.right,
bottom: (body2.isCircle) ? body1.bottom : body2.bottom
};
var circle = {
x: (body1.isCircle) ? (body1.position.x + body1.radius) : (body2.position.x + body2.radius),
y: (body1.isCircle) ? (body1.position.y + body1.radius) : (body2.position.y + body2.radius),
radius: (body1.isCircle) ? body1.radius : body2.radius
};
if (circle.y < rect.y)
{
if (circle.x < rect.x)
{
overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius;
}
else if (circle.x > rect.right)
{
overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius;
}
}
else if (circle.y > rect.bottom)
{
if (circle.x < rect.x)
{
overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius;
}
else if (circle.x > rect.right)
{
overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius;
}
}
overlap *= -1;
}
else
{
overlap = (body1.radius + body2.radius) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y);
}
// Can't separate two immovable bodies, or a body with its own custom separation logic
if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX)
{
if (overlap !== 0)
{
if (body1.onOverlap)
{
body1.onOverlap.dispatch(body1.sprite, body2.sprite);
}
if (body2.onOverlap)
{
body2.onOverlap.dispatch(body2.sprite, body1.sprite);
}
}
// return true if there was some overlap, otherwise false
return (overlap !== 0);
}
// Transform the velocity vector to the coordinate system oriented along the direction of impact.
// This is done to eliminate the vertical component of the velocity
var v1 = {
x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision),
y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision)
};
var v2 = {
x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision),
y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision)
};
// We expect the new velocity after impact
var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass);
var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass);
// We convert the vector to the original coordinate system and multiplied by factor of rebound
if (!body1.immovable)
{
body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x;
body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y;
}
if (!body2.immovable)
{
body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x;
body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y;
}
// When the collision angle is almost perpendicular to the total initial velocity vector
// (collision on a tangent) vector direction can be determined incorrectly.
// This code fixes the problem
if (Math.abs(angleCollision) < Math.PI / 2)
{
if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x))
{
body1.velocity.x *= -1;
}
else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x))
{
body2.velocity.x *= -1;
}
else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y))
{
body1.velocity.y *= -1;
}
else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y))
{
body2.velocity.y *= -1;
}
}
else if (Math.abs(angleCollision) > Math.PI / 2)
{
if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x))
{
body1.velocity.x *= -1;
}
else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x))
{
body2.velocity.x *= -1;
}
else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y))
{
body1.velocity.y *= -1;
}
else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y))
{
body2.velocity.y *= -1;
}
}
if (!body1.immovable)
{
body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision);
body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision);
}
if (!body2.immovable)
{
body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision);
body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision);
}
if (body1.onCollide)
{
body1.onCollide.dispatch(body1.sprite, body2.sprite);
}
if (body2.onCollide)
{
body2.onCollide.dispatch(body2.sprite, body1.sprite);
}
return true;
},
/**
* Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including:
* `touching.left`, `touching.right` and `overlapX`.
*
* @method Phaser.Physics.Arcade#getOverlapX
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
* @param {boolean} overlapOnly - Is this an overlap only check, or part of separation?
* @return {float} Returns the amount of horizontal overlap between the two bodies.
*/
getOverlapX: function (body1, body2, overlapOnly) {
var overlap = 0;
var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS;
if (body1.deltaX() === 0 && body2.deltaX() === 0)
{
// They overlap but neither of them are moving
body1.embedded = true;
body2.embedded = true;
}
else if (body1.deltaX() > body2.deltaX())
{
// Body1 is moving right and / or Body2 is moving left
overlap = body1.right - body2.x;
if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false)
{
overlap = 0;
}
else
{
body1.touching.none = false;
body1.touching.right = true;
body2.touching.none = false;
body2.touching.left = true;
}
}
else if (body1.deltaX() < body2.deltaX())
{
// Body1 is moving left and/or Body2 is moving right
overlap = body1.x - body2.width - body2.x;
if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false)
{
overlap = 0;
}
else
{
body1.touching.none = false;
body1.touching.left = true;
body2.touching.none = false;
body2.touching.right = true;
}
}
// Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is
body1.overlapX = overlap;
body2.overlapX = overlap;
return overlap;
},
/**
* Calculates the vertical overlap between two Bodies and sets their properties accordingly, including:
* `touching.up`, `touching.down` and `overlapY`.
*
* @method Phaser.Physics.Arcade#getOverlapY
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
* @param {boolean} overlapOnly - Is this an overlap only check, or part of separation?
* @return {float} Returns the amount of vertical overlap between the two bodies.
*/
getOverlapY: function (body1, body2, overlapOnly) {
var overlap = 0;
var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS;
if (body1.deltaY() === 0 && body2.deltaY() === 0)
{
// They overlap but neither of them are moving
body1.embedded = true;
body2.embedded = true;
}
else if (body1.deltaY() > body2.deltaY())
{
// Body1 is moving down and/or Body2 is moving up
overlap = body1.bottom - body2.y;
if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false)
{
overlap = 0;
}
else
{
body1.touching.none = false;
body1.touching.down = true;
body2.touching.none = false;
body2.touching.up = true;
}
}
else if (body1.deltaY() < body2.deltaY())
{
// Body1 is moving up and/or Body2 is moving down
overlap = body1.y - body2.bottom;
if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false)
{
overlap = 0;
}
else
{
body1.touching.none = false;
body1.touching.up = true;
body2.touching.none = false;
body2.touching.down = true;
}
}
// Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is
body1.overlapY = overlap;
body2.overlapY = overlap;
return overlap;
},
/**
* The core separation function to separate two physics bodies on the x axis.
*
* @method Phaser.Physics.Arcade#separateX
* @private
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
* @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
* @return {boolean} Returns true if the bodies were separated or overlap, otherwise false.
*/
separateX: function (body1, body2, overlapOnly) {
var overlap = this.getOverlapX(body1, body2, overlapOnly);
// Can't separate two immovable bodies, or a body with its own custom separation logic
if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX)
{
// return true if there was some overlap, otherwise false
return (overlap !== 0) || (body1.embedded && body2.embedded);
}
// Adjust their positions and velocities accordingly (if there was any overlap)
var v1 = body1.velocity.x;
var v2 = body2.velocity.x;
if (!body1.immovable && !body2.immovable)
{
overlap *= 0.5;
body1.x -= overlap;
body2.x += overlap;
var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
var avg = (nv1 + nv2) * 0.5;
nv1 -= avg;
nv2 -= avg;
body1.velocity.x = avg + nv1 * body1.bounce.x;
body2.velocity.x = avg + nv2 * body2.bounce.x;
}
else if (!body1.immovable)
{
body1.x -= overlap;
body1.velocity.x = v2 - v1 * body1.bounce.x;
// This is special case code that handles things like vertically moving platforms you can ride
if (body2.moves)
{
body1.y += (body2.y - body2.prev.y) * body2.friction.y;
}
}
else
{
body2.x += overlap;
body2.velocity.x = v1 - v2 * body2.bounce.x;
// This is special case code that handles things like vertically moving platforms you can ride
if (body1.moves)
{
body2.y += (body1.y - body1.prev.y) * body1.friction.y;
}
}
// If we got this far then there WAS overlap, and separation is complete, so return true
return true;
},
/**
* The core separation function to separate two physics bodies on the y axis.
*
* @private
* @method Phaser.Physics.Arcade#separateY
* @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
* @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
* @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
* @return {boolean} Returns true if the bodies were separated or overlap, otherwise false.
*/
separateY: function (body1, body2, overlapOnly) {
var overlap = this.getOverlapY(body1, body2, overlapOnly);
// Can't separate two immovable bodies, or a body with its own custom separation logic
if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY)
{
// return true if there was some overlap, otherwise false
return (overlap !== 0) || (body1.embedded && body2.embedded);
}
// Adjust their positions and velocities accordingly (if there was any overlap)
var v1 = body1.velocity.y;
var v2 = body2.velocity.y;
if (!body1.immovable && !body2.immovable)
{
overlap *= 0.5;
body1.y -= overlap;
body2.y += overlap;
var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
var avg = (nv1 + nv2) * 0.5;
nv1 -= avg;
nv2 -= avg;
body1.velocity.y = avg + nv1 * body1.bounce.y;
body2.velocity.y = avg + nv2 * body2.bounce.y;
}
else if (!body1.immovable)
{
body1.y -= overlap;
body1.velocity.y = v2 - v1 * body1.bounce.y;
// This is special case code that handles things like horizontal moving platforms you can ride
if (body2.moves)
{
body1.x += (body2.x - body2.prev.x) * body2.friction.x;
}
}
else
{
body2.y += overlap;
body2.velocity.y = v1 - v2 * body2.bounce.y;
// This is special case code that handles things like horizontal moving platforms you can ride
if (body1.moves)
{
body2.x += (body1.x - body1.prev.x) * body1.friction.x;
}
}
// If we got this far then there WAS overlap, and separation is complete, so return true
return true;
},
/**
* Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates.
* Each child will be sent to the given callback for further processing.
* Note that the children are not checked for depth order, but simply if they overlap the Pointer or not.
*
* @method Phaser.Physics.Arcade#getObjectsUnderPointer
* @param {Phaser.Pointer} pointer - The Pointer to check.
* @param {Phaser.Group} group - The Group to check.
* @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it.
* @param {object} [callbackContext] - The context in which to run the callback.
* @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates.
*/
getObjectsUnderPointer: function (pointer, group, callback, callbackContext) {
if (group.length === 0 || !pointer.exists)
{
return;
}
return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer);
},
/**
* Given a Group and a location this will check to see which Group children overlap with the coordinates.
* Each child will be sent to the given callback for further processing.
* Note that the children are not checked for depth order, but simply if they overlap the coordinate or not.
*
* @method Phaser.Physics.Arcade#getObjectsAtLocation
* @param {number} x - The x coordinate to check.
* @param {number} y - The y coordinate to check.
* @param {Phaser.Group} group - The Group to check.
* @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location.
* @param {object} [callbackContext] - The context in which to run the callback.
* @param {object} [callbackArg] - An argument to pass to the callback.
* @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates.
*/
getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) {
this.quadTree.clear();
this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
this.quadTree.populate(group);
var rect = new Phaser.Rectangle(x, y, 1, 1);
var output = [];
var items = this.quadTree.retrieve(rect);
for (var i = 0; i < items.length; i++)
{
if (items[i].hitTest(x, y))
{
if (callback)
{
callback.call(callbackContext, callbackArg, items[i].sprite);
}
output.push(items[i].sprite);
}
}
return output;
},
/**
* Move the given display object towards the destination object at a steady velocity.
* If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds.
* Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
* Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
*
* @method Phaser.Physics.Arcade#moveToObject
* @param {any} displayObject - The display object to move.
* @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
* @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
*/
moveToObject: function (displayObject, destination, speed, maxTime) {
if (speed === undefined) { speed = 60; }
if (maxTime === undefined) { maxTime = 0; }
var angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x);
if (maxTime > 0)
{
// We know how many pixels we need to move, but how fast?
speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000);
}
displayObject.body.velocity.x = Math.cos(angle) * speed;
displayObject.body.velocity.y = Math.sin(angle) * speed;
return angle;
},
/**
* Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer.
* If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
* Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
*
* @method Phaser.Physics.Arcade#moveToPointer
* @param {any} displayObject - The display object to move.
* @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
* @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
*/
moveToPointer: function (displayObject, speed, pointer, maxTime) {
if (speed === undefined) { speed = 60; }
pointer = pointer || this.game.input.activePointer;
if (maxTime === undefined) { maxTime = 0; }
var angle = this.angleToPointer(displayObject, pointer);
if (maxTime > 0)
{
// We know how many pixels we need to move, but how fast?
speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000);
}
displayObject.body.velocity.x = Math.cos(angle) * speed;
displayObject.body.velocity.y = Math.sin(angle) * speed;
return angle;
},
/**
* Move the given display object towards the x/y coordinates at a steady velocity.
* If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
* Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
* Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
*
* @method Phaser.Physics.Arcade#moveToXY
* @param {any} displayObject - The display object to move.
* @param {number} x - The x coordinate to move towards.
* @param {number} y - The y coordinate to move towards.
* @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
* @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
*/
moveToXY: function (displayObject, x, y, speed, maxTime) {
if (speed === undefined) { speed = 60; }
if (maxTime === undefined) { maxTime = 0; }
var angle = Math.atan2(y - displayObject.y, x - displayObject.x);
if (maxTime > 0)
{
// We know how many pixels we need to move, but how fast?
speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000);
}
displayObject.body.velocity.x = Math.cos(angle) * speed;
displayObject.body.velocity.y = Math.sin(angle) * speed;
return angle;
},
/**
* Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
* One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
*
* @method Phaser.Physics.Arcade#velocityFromAngle
* @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
* @param {number} [speed=60] - The speed it will move, in pixels per second sq.
* @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
* @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
*/
velocityFromAngle: function (angle, speed, point) {
if (speed === undefined) { speed = 60; }
point = point || new Phaser.Point();
return point.setTo((Math.cos(Phaser.Math.degToRad(angle)) * speed), (Math.sin(Phaser.Math.degToRad(angle)) * speed));
},
/**
* Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
* One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
*
* @method Phaser.Physics.Arcade#velocityFromRotation
* @param {number} rotation - The angle in radians.
* @param {number} [speed=60] - The speed it will move, in pixels per second sq.
* @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
* @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
*/
velocityFromRotation: function (rotation, speed, point) {
if (speed === undefined) { speed = 60; }
point = point || new Phaser.Point();
return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
},
/**
* Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object.
* One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object.
*
* @method Phaser.Physics.Arcade#accelerationFromRotation
* @param {number} rotation - The angle in radians.
* @param {number} [speed=60] - The speed it will move, in pixels per second sq.
* @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration.
* @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value.
*/
accelerationFromRotation: function (rotation, speed, point) {
if (speed === undefined) { speed = 60; }
point = point || new Phaser.Point();
return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
},
/**
* Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
* You must give a maximum speed value, beyond which the display object won't go any faster.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
*
* @method Phaser.Physics.Arcade#accelerateToObject
* @param {any} displayObject - The display object to move.
* @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
* @param {number} [speed=60] - The speed it will accelerate in pixels per second.
* @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
* @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
*/
accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) {
if (speed === undefined) { speed = 60; }
if (xSpeedMax === undefined) { xSpeedMax = 1000; }
if (ySpeedMax === undefined) { ySpeedMax = 1000; }
var angle = this.angleBetween(displayObject, destination);
displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
return angle;
},
/**
* Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
* You must give a maximum speed value, beyond which the display object won't go any faster.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
*
* @method Phaser.Physics.Arcade#accelerateToPointer
* @param {any} displayObject - The display object to move.
* @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
* @param {number} [speed=60] - The speed it will accelerate in pixels per second.
* @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
* @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
*/
accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) {
if (speed === undefined) { speed = 60; }
if (pointer === undefined) { pointer = this.game.input.activePointer; }
if (xSpeedMax === undefined) { xSpeedMax = 1000; }
if (ySpeedMax === undefined) { ySpeedMax = 1000; }
var angle = this.angleToPointer(displayObject, pointer);
displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
return angle;
},
/**
* Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.)
* You must give a maximum speed value, beyond which the display object won't go any faster.
* Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
* Note: The display object doesn't stop moving once it reaches the destination coordinates.
*
* @method Phaser.Physics.Arcade#accelerateToXY
* @param {any} displayObject - The display object to move.
* @param {number} x - The x coordinate to accelerate towards.
* @param {number} y - The y coordinate to accelerate towards.
* @param {number} [speed=60] - The speed it will accelerate in pixels per second.
* @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
* @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
* @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
*/
accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) {
if (speed === undefined) { speed = 60; }
if (xSpeedMax === undefined) { xSpeedMax = 1000; }
if (ySpeedMax === undefined) { ySpeedMax = 1000; }
var angle = this.angleToXY(displayObject, x, y);
displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
return angle;
},
/**
* Find the distance between two display objects (like Sprites).
*
* The optional `world` argument allows you to return the result based on the Game Objects `world` property,
* instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
* or parent Game Object.
*
* @method Phaser.Physics.Arcade#distanceBetween
* @param {any} source - The Display Object to test from.
* @param {any} target - The Display Object to test to.
* @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default)
* @return {number} The distance between the source and target objects.
*/
distanceBetween: function (source, target, world) {
if (world === undefined) { world = false; }
var dx = (world) ? source.world.x - target.world.x : source.x - target.x;
var dy = (world) ? source.world.y - target.world.y : source.y - target.y;
return Math.sqrt(dx * dx + dy * dy);
},
/**
* Find the distance between a display object (like a Sprite) and the given x/y coordinates.
* The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
* If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
*
* The optional `world` argument allows you to return the result based on the Game Objects `world` property,
* instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
* or parent Game Object.
*
* @method Phaser.Physics.Arcade#distanceToXY
* @param {any} displayObject - The Display Object to test from.
* @param {number} x - The x coordinate to move towards.
* @param {number} y - The y coordinate to move towards.
* @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default)
* @return {number} The distance between the object and the x/y coordinates.
*/
distanceToXY: function (displayObject, x, y, world) {
if (world === undefined) { world = false; }
var dx = (world) ? displayObject.world.x - x : displayObject.x - x;
var dy = (world) ? displayObject.world.y - y : displayObject.y - y;
return Math.sqrt(dx * dx + dy * dy);
},
/**
* Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used.
* The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
* If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
*
* The optional `world` argument allows you to return the result based on the Game Objects `world` property,
* instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
* or parent Game Object.
*
* @method Phaser.Physics.Arcade#distanceToPointer
* @param {any} displayObject - The Display Object to test from.
* @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
* @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default)
* @return {number} The distance between the object and the Pointer.
*/
distanceToPointer: function (displayObject, pointer, world) {
if (pointer === undefined) { pointer = this.game.input.activePointer; }
if (world === undefined) { world = false; }
var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX;
var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY;
return Math.sqrt(dx * dx + dy * dy);
},
/**
* Find the angle in radians between two display objects (like Sprites).
*
* The optional `world` argument allows you to return the result based on the Game Objects `world` property,
* instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
* or parent Game Object.
*
* @method Phaser.Physics.Arcade#angleBetween
* @param {any} source - The Display Object to test from.
* @param {any} target - The Display Object to test to.
* @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default)
* @return {number} The angle in radians between the source and target display objects.
*/
angleBetween: function (source, target, world) {
if (world === undefined) { world = false; }
if (world)
{
return Math.atan2(target.world.y - source.world.y, target.world.x - source.world.x);
}
else
{
return Math.atan2(target.y - source.y, target.x - source.x);
}
},
/**
* Find the angle in radians between centers of two display objects (like Sprites).
*
* @method Phaser.Physics.Arcade#angleBetweenCenters
* @param {any} source - The Display Object to test from.
* @param {any} target - The Display Object to test to.
* @return {number} The angle in radians between the source and target display objects.
*/
angleBetweenCenters: function (source, target) {
var dx = target.centerX - source.centerX;
var dy = target.centerY - source.centerY;
return Math.atan2(dy, dx);
},
/**
* Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate.
*
* The optional `world` argument allows you to return the result based on the Game Objects `world` property,
* instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
* or parent Game Object.
*
* @method Phaser.Physics.Arcade#angleToXY
* @param {any} displayObject - The Display Object to test from.
* @param {number} x - The x coordinate to get the angle to.
* @param {number} y - The y coordinate to get the angle to.
* @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default)
* @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
*/
angleToXY: function (displayObject, x, y, world) {
if (world === undefined) { world = false; }
if (world)
{
return Math.atan2(y - displayObject.world.y, x - displayObject.world.x);
}
else
{
return Math.atan2(y - displayObject.y, x - displayObject.x);
}
},
/**
* Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account.
*
* The optional `world` argument allows you to return the result based on the Game Objects `world` property,
* instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
* or parent Game Object.
*
* @method Phaser.Physics.Arcade#angleToPointer
* @param {any} displayObject - The Display Object to test from.
* @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
* @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default)
* @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
*/
angleToPointer: function (displayObject, pointer, world) {
if (pointer === undefined) { pointer = this.game.input.activePointer; }
if (world === undefined) { world = false; }
if (world)
{
return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x);
}
else
{
return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x);
}
},
/**
* Find the angle in radians between a display object (like a Sprite) and a Pointer,
* taking their x/y and center into account relative to the world.
*
* @method Phaser.Physics.Arcade#worldAngleToPointer
* @param {any} displayObject - The DisplayObjerct to test from.
* @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
* @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY
*/
worldAngleToPointer: function (displayObject, pointer) {
return this.angleToPointer(displayObject, pointer, true);
}
};
|
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.VBox}
* @param {!WebInspector.NetworkRequest} request
* @param {!WebInspector.NetworkTimeCalculator} calculator
*/
WebInspector.RequestTimingView = function(request, calculator)
{
WebInspector.VBox.call(this);
this.element.classList.add("resource-timing-view");
this._request = request;
this._calculator = calculator;
}
WebInspector.RequestTimingView.prototype = {
wasShown: function()
{
this._request.addEventListener(WebInspector.NetworkRequest.Events.TimingChanged, this._refresh, this);
this._request.addEventListener(WebInspector.NetworkRequest.Events.FinishedLoading, this._refresh, this);
this._calculator.addEventListener(WebInspector.NetworkTimeCalculator.Events.BoundariesChanged, this._refresh, this);
this._refresh();
},
willHide: function()
{
this._request.removeEventListener(WebInspector.NetworkRequest.Events.TimingChanged, this._refresh, this);
this._request.removeEventListener(WebInspector.NetworkRequest.Events.FinishedLoading, this._refresh, this);
this._calculator.removeEventListener(WebInspector.NetworkTimeCalculator.Events.BoundariesChanged, this._refresh, this);
},
_refresh: function()
{
if (this._tableElement)
this._tableElement.remove();
this._tableElement = WebInspector.RequestTimingView.createTimingTable(this._request, this._calculator.minimumBoundary());
this.element.appendChild(this._tableElement);
},
__proto__: WebInspector.VBox.prototype
}
/** @enum {string} */
WebInspector.RequestTimeRangeNames = {
Blocking: "blocking",
Connecting: "connecting",
DNS: "dns",
Proxy: "proxy",
Receiving: "receiving",
Sending: "sending",
ServiceWorker: "serviceworker",
ServiceWorkerPreparation: "serviceworker-preparation",
SSL: "ssl",
Total: "total",
Waiting: "waiting"
};
/** @typedef {{name: !WebInspector.RequestTimeRangeNames, start: number, end: number}} */
WebInspector.RequestTimeRange;
/**
* @param {!WebInspector.RequestTimeRangeNames} name
* @return {string}
*/
WebInspector.RequestTimingView._timeRangeTitle = function(name)
{
switch (name) {
case WebInspector.RequestTimeRangeNames.Blocking: return WebInspector.UIString("Stalled");
case WebInspector.RequestTimeRangeNames.Connecting: return WebInspector.UIString("Initial connection");
case WebInspector.RequestTimeRangeNames.DNS: return WebInspector.UIString("DNS Lookup");
case WebInspector.RequestTimeRangeNames.Proxy: return WebInspector.UIString("Proxy negotiation");
case WebInspector.RequestTimeRangeNames.Receiving: return WebInspector.UIString("Content Download");
case WebInspector.RequestTimeRangeNames.Sending: return WebInspector.UIString("Request sent");
case WebInspector.RequestTimeRangeNames.ServiceWorker: return WebInspector.UIString("Request to ServiceWorker");
case WebInspector.RequestTimeRangeNames.ServiceWorkerPreparation: return WebInspector.UIString("ServiceWorker Preparation");
case WebInspector.RequestTimeRangeNames.SSL: return WebInspector.UIString("SSL");
case WebInspector.RequestTimeRangeNames.Total: return WebInspector.UIString("Total");
case WebInspector.RequestTimeRangeNames.Waiting: return WebInspector.UIString("Waiting (TTFB)");
default: return WebInspector.UIString(name);
}
}
/**
* @param {!WebInspector.NetworkRequest} request
* @return {!Array.<!WebInspector.RequestTimeRange>}
*/
WebInspector.RequestTimingView.calculateRequestTimeRanges = function(request)
{
var result = [];
/**
* @param {!WebInspector.RequestTimeRangeNames} name
* @param {number} start
* @param {number} end
*/
function addRange(name, start, end)
{
if (start < end)
result.push({name: name, start: start, end: end});
}
/**
* @param {!Array.<number>} numbers
* @return {number|undefined}
*/
function firstPositive(numbers)
{
for (var i = 0; i < numbers.length; ++i) {
if (numbers[i] > 0)
return numbers[i];
}
return undefined;
}
/**
* @param {!WebInspector.RequestTimeRangeNames} name
* @param {number} start
* @param {number} end
*/
function addOffsetRange(name, start, end)
{
if (start >= 0 && end >= 0)
addRange(name, startTime + (start / 1000), startTime + (end / 1000));
}
var timing = request.timing;
if (!timing) {
var start = request.issueTime() !== -1 ? request.issueTime() : request.startTime !== -1 ? request.startTime : 0;
var middle = (request.responseReceivedTime === -1) ? Number.MAX_VALUE : request.responseReceivedTime;
var end = (request.endTime === -1) ? Number.MAX_VALUE : request.endTime;
addRange(WebInspector.RequestTimeRangeNames.Total, start, end);
addRange(WebInspector.RequestTimeRangeNames.Blocking, start, middle);
addRange(WebInspector.RequestTimeRangeNames.Receiving, middle, end);
return result;
}
var issueTime = request.issueTime();
var startTime = timing.requestTime;
var endTime = firstPositive([request.endTime, request.responseReceivedTime]) || startTime;
addRange(WebInspector.RequestTimeRangeNames.Total, issueTime < startTime ? issueTime : startTime, endTime);
if (request.fetchedViaServiceWorker) {
addOffsetRange(WebInspector.RequestTimeRangeNames.Blocking, 0, timing.serviceWorkerFetchStart);
addOffsetRange(WebInspector.RequestTimeRangeNames.ServiceWorker, timing.serviceWorkerFetchStart, timing.serviceWorkerFetchEnd);
addOffsetRange(WebInspector.RequestTimeRangeNames.ServiceWorkerPreparation, timing.serviceWorkerFetchStart, timing.serviceWorkerFetchReady);
addOffsetRange(WebInspector.RequestTimeRangeNames.Waiting, timing.serviceWorkerFetchEnd, timing.receiveHeadersEnd);
} else {
var blocking = firstPositive([timing.dnsStart, timing.connectStart, timing.sendStart]) || 0;
addOffsetRange(WebInspector.RequestTimeRangeNames.Blocking, 0, blocking);
addOffsetRange(WebInspector.RequestTimeRangeNames.Proxy, timing.proxyStart, timing.proxyEnd);
addOffsetRange(WebInspector.RequestTimeRangeNames.DNS, timing.dnsStart, timing.dnsEnd);
addOffsetRange(WebInspector.RequestTimeRangeNames.Connecting, timing.connectStart, timing.connectEnd);
addOffsetRange(WebInspector.RequestTimeRangeNames.SSL, timing.sslStart, timing.sslEnd);
addOffsetRange(WebInspector.RequestTimeRangeNames.Sending, timing.sendStart, timing.sendEnd);
addOffsetRange(WebInspector.RequestTimeRangeNames.Waiting, timing.sendEnd, timing.receiveHeadersEnd);
}
if (request.endTime !== -1)
addRange(WebInspector.RequestTimeRangeNames.Receiving, request.responseReceivedTime, endTime);
return result;
}
/**
* @param {!WebInspector.NetworkRequest} request
* @param {number} navigationStart
* @return {!Element}
*/
WebInspector.RequestTimingView.createTimingTable = function(request, navigationStart)
{
var tableElement = createElementWithClass("table", "network-timing-table");
tableElement.createChild("colgroup").createChild("col", "labels");
var timeRanges = WebInspector.RequestTimingView.calculateRequestTimeRanges(request);
var startTime = timeRanges[0].start;
var endTime = timeRanges[0].end;
var scale = 100 / (endTime - startTime);
var globalTimeInfo = tableElement.createChild("tr").createChild("td");
globalTimeInfo.colSpan = 2;
globalTimeInfo.createTextChild("Started at " + Number.secondsToString(timeRanges[0].start - navigationStart));
for (var i = 0; i < timeRanges.length; ++i) {
var range = timeRanges[i];
var rangeName = range.name;
var left = (scale * (range.start - startTime));
var right = (scale * (endTime - range.end));
var duration = range.end - range.start;
var tr = tableElement.createChild("tr");
tr.createChild("td").createTextChild(WebInspector.RequestTimingView._timeRangeTitle(rangeName));
var row = tr.createChild("td").createChild("div", "network-timing-row");
var bar = row.createChild("span", "network-timing-bar " + rangeName);
bar.style.left = left + "%";
bar.style.right = right + "%";
bar.textContent = "\u200B"; // Important for 0-time items to have 0 width.
var label = row.createChild("span", "network-timing-bar-title");
if (right < left)
label.style.right = right + "%";
else
label.style.left = left + "%";
label.textContent = Number.secondsToString(duration, true);
}
if (!request.finished) {
var cell = tableElement.createChild("tr").createChild("td", "caution");
cell.colSpan = 2;
cell.createTextChild(WebInspector.UIString("CAUTION: request is not finished yet!"));
}
var note = tableElement.createChild("tr").createChild("td", "footnote");
note.colSpan = 2;
note.appendChild(WebInspector.createDocumentationAnchor("network#resource-network-timing", WebInspector.UIString("Explanation of resource timing")));
return tableElement;
}
|
var name = "Sparkle Buddy";
var collection_type = 0;
var is_secret = 0;
var desc = "Made seven players extra-happy at the same time with Sparkle Powder";
var status_text = "Waytago! A regular life of the party you are, making all those nice people happy with your Sparkle Powder. You deserve the coveted Sparkle Buddy badge.";
var last_published = 1316303737;
var is_shareworthy = 0;
var url = "sparkle-buddy";
var category = "alchemy";
var url_swf = "\/c2.glitch.bz\/achievements\/2011-05-09\/sparkle_buddy_1304984077.swf";
var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-05-09\/sparkle_buddy_1304984077_180.png";
var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-05-09\/sparkle_buddy_1304984077_60.png";
var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-05-09\/sparkle_buddy_1304984077_40.png";
function on_apply(pc){
}
var conditions = {
230 : {
type : "counter",
group : "powders",
label : "sparkle_buddy",
value : "1"
},
};
function onComplete(pc){ // generated from rewards
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_achievement_modifier();
if (/completist/i.exec(this.name)) {
var level = pc.stats_get_level();
if (level > 4) {
multiplier *= (pc.stats_get_level()/4);
}
}
pc.stats_add_xp(round_to_5(100 * multiplier), true);
pc.stats_add_favor_points("friendly", round_to_5(15 * multiplier));
if(pc.buffs_has('gift_of_gab')) {
pc.buffs_remove('gift_of_gab');
}
else if(pc.buffs_has('silvertongue')) {
pc.buffs_remove('silvertongue');
}
}
var rewards = {
"xp" : 100,
"favor" : {
"giant" : "friendly",
"points" : 15
}
};
// generated ok (NO DATE)
|
'use strict';
/**
* The `kss/generator` module loads the {@link KssGenerator} class constructor.
* ```
* var KssGenerator = require('kss/generator');
* ```
* @module kss/generator
*/
/* **************************************************************
See kss_example_generator.js for how to implement a generator.
************************************************************** */
var Kss = require('../lib/kss.js'),
wrench = require('wrench');
var KssGenerator;
/**
* Create a KssGenerator object.
*
* This is the base object used by all kss-node generators. Implementations of
* KssGenerator MUST pass the version parameter. kss-node will use this to
* ensure that only compatible generators are used.
*
* ```
* var KssGenerator = require('kss/generator');
* var customGenerator = new KssGenerator('2.0');
* ```
*
* @constructor
* @alias KssGenerator
* @param {string} version The generator API version implemented.
* @param {object} options The Yargs options this generator has.
* See https://github.com/bcoe/yargs/blob/master/README.md#optionskey-opt
*/
module.exports = KssGenerator = function(version, options) {
if (!(this instanceof KssGenerator)) {
return new KssGenerator();
}
// Tell generators which generator API version is currently running.
this.API = '2.0';
// Store the version of the generator API that the generator instance is
// expecting; we will verify this in checkGenerator().
this.instanceAPI = typeof version === 'undefined' ? 'undefined' : version;
// Tell kss-node which Yargs options this generator has.
this.options = options || {};
};
/**
* Checks the generator configuration.
*
* An instance of KssGenerator MUST NOT override this method. A process
* controlling the generator should call this method to verify the
* specified generator has been configured correctly.
*
* @alias KssGenerator.prototype.checkGenerator
*/
KssGenerator.prototype.checkGenerator = function() {
if (!(this instanceof KssGenerator)) {
throw new Error('The loaded generator is not a KssGenerator object.');
}
if (this.instanceAPI === 'undefined') {
throw new Error('This generator is incompatible with KssGenerator API ' + this.API + ': "' + this.instanceAPI + '"');
}
};
/**
* Clone a template's files.
*
* This method is fairly simple; it copies one directory to the specified
* location. An instance of KssGenerator does not need to override this method,
* but it can if it needs to do something more complicated.
*
* @alias KssGenerator.prototype.clone
* @param {string} templatePath Path to the template to clone.
* @param {string} destinationPath Path to the destination of the newly cloned
* template.
*/
KssGenerator.prototype.clone = function(templatePath, destinationPath) {
try {
var error = wrench.copyDirSyncRecursive(
templatePath,
destinationPath,
{
forceDelete: false,
excludeHiddenUnix: true
}
);
if (error) {
throw error;
}
} catch (e) {
throw new Error('Error! This folder already exists: ' + destinationPath);
}
};
/**
* Initialize the style guide creation process.
*
* This method is given a configuration JSON object with the details of the
* requested style guide generation. The generator can use this information for
* any necessary tasks before the KSS parsing of the source files.
*
* @alias KssGenerator.prototype.init
* @param {Array} config Array of configuration for the requested generation.
*/
KssGenerator.prototype.init = function(config) {
// At the very least, generators MUST save the configuration parameters.
this.config = config;
};
/**
* Parse the source files for KSS comments and create a KssStyleguide object.
*
* When finished, it passes the completed KssStyleguide to the given callback.
*
* @alias KssGenerator.prototype.parse
* @param {function} callback Function that takes a KssStyleguide and generates
* the HTML files of the style guide.
*/
KssGenerator.prototype.parse = function(callback) {
if (this.config.verbose) {
console.log('...Parsing your style guide:');
}
/* eslint-disable key-spacing */
// The default parse() method looks at the paths to the source folders and
// uses KSS' traverse method to load, read and parse the source files. Other
// generators may want to use KSS' parse method if they have already loaded
// the source files through some other mechanism.
Kss.traverse(this.config.source, {
multiline: true,
markdown: true,
markup: true,
mask: this.config.mask,
custom: this.config.custom
}, function(err, styleguide) {
if (err) {
throw err;
}
callback(styleguide);
});
/* eslint-enable key-spacing */
};
/* eslint-disable no-unused-vars */
/**
* Generate the HTML files of the style guide given a KssStyleguide object.
*
* This the callback function passed to the parse() method. The callback is
* wrapped in a closure so that it has access to "this" object (the methods and
* properties of KssExampleGenerator.)
*
* @alias KssGenerator.prototype.generate
* @param {KssStyleguide} styleguide The KSS style guide in object format.
*/
KssGenerator.prototype.generate = function(styleguide) {
};
/* eslint-enable no-unused-vars */
|
'use strict';
/* jshint -W030 */
/* jshint -W110 */
var chai = require('chai')
, Sequelize = require('../../index')
, expect = chai.expect
, Support = require(__dirname + '/support')
, sinon = require('sinon')
, _ = require('lodash')
, moment = require('moment')
, current = Support.sequelize
, uuid = require('node-uuid')
, DataTypes = require('../../lib/data-types')
, dialect = Support.getTestDialect();
describe(Support.getTestDialectTeaser('DataTypes'), function() {
afterEach(function () {
// Restore some sanity by resetting all parsers
switch (dialect) {
case 'postgres':
var types = require('../../node_modules/pg/node_modules/pg-types');
_.each(DataTypes, function (dataType) {
if (dataType.types && dataType.types.postgres) {
dataType.types.postgres.oids.forEach(function (oid) {
types.setTypeParser(oid, _.identity);
});
}
});
require('../../node_modules/pg/node_modules/pg-types/lib/binaryParsers').init(function (oid, converter) {
types.setTypeParser(oid, 'binary', converter);
});
require('../../node_modules/pg/node_modules/pg-types/lib/textParsers').init(function (oid, converter) {
types.setTypeParser(oid, 'text', converter);
});
break;
default:
this.sequelize.connectionManager.$clearTypeParser();
}
this.sequelize.connectionManager.refreshTypeParser(DataTypes[dialect]); // Reload custom parsers
});
it('allows me to return values from a custom parse function', function () {
var parse = Sequelize.DATE.parse = sinon.spy(function (value) {
return moment(value, 'YYYY-MM-DD HH:mm:ss Z');
});
var stringify = Sequelize.DATE.prototype.stringify = sinon.spy(function (value, options) {
if (!moment.isMoment(value)) {
value = this.$applyTimezone(value, options);
}
return value.format('YYYY-MM-DD HH:mm:ss Z');
});
current.refreshTypes();
var User = current.define('user', {
dateField: Sequelize.DATE
}, {
timestamps: false
});
return current.sync({ force: true }).then(function () {
return User.create({
dateField: moment("2011 10 31", 'YYYY MM DD')
});
}).then(function () {
return User.findAll().get(0);
}).then(function (user) {
expect(parse).to.have.been.called;
expect(stringify).to.have.been.called;
expect(moment.isMoment(user.dateField)).to.be.ok;
delete Sequelize.DATE.parse;
});
});
var testSuccess = function (Type, value) {
var parse = Type.constructor.parse = sinon.spy(function (value) {
return value;
});
var stringify = Type.constructor.prototype.stringify = sinon.spy(function (value) {
return Sequelize.ABSTRACT.prototype.stringify.apply(this, arguments);
});
current.refreshTypes();
var User = current.define('user', {
field: Type
}, {
timestamps: false
});
return current.sync({ force: true }).then(function () {
return User.create({
field: value
});
}).then(function () {
return User.findAll().get(0);
}).then(function (user) {
expect(parse).to.have.been.called;
expect(stringify).to.have.been.called;
delete Type.constructor.parse;
delete Type.constructor.prototype.stringify;
});
};
var testFailure = function (Type, value) {
Type.constructor.parse = _.noop();
expect(function () {
current.refreshTypes();
}).to.throw('Parse function not supported for type ' + Type.key + ' in dialect ' + dialect);
delete Type.constructor.parse;
};
if (dialect === 'postgres') {
it('calls parse and stringify for JSON', function () {
var Type = new Sequelize.JSON();
return testSuccess(Type, { test: 42, nested: { foo: 'bar' }});
});
it('calls parse and stringify for JSONB', function () {
var Type = new Sequelize.JSONB();
return testSuccess(Type, { test: 42, nested: { foo: 'bar' }});
});
it('calls parse and stringify for HSTORE', function () {
var Type = new Sequelize.HSTORE();
return testSuccess(Type, { test: 42, nested: false });
});
it('calls parse and stringify for RANGE', function () {
var Type = new Sequelize.RANGE(new Sequelize.INTEGER());
return testSuccess(Type, [1, 2]);
});
}
it('calls parse and stringify for DATE', function () {
var Type = new Sequelize.DATE();
return testSuccess(Type, new Date());
});
it('calls parse and stringify for DATEONLY', function () {
var Type = new Sequelize.DATEONLY();
return testSuccess(Type, new Date());
});
it('calls parse and stringify for TIME', function () {
var Type = new Sequelize.TIME();
return testSuccess(Type, new Date());
});
it('calls parse and stringify for BLOB', function () {
var Type = new Sequelize.BLOB();
return testSuccess(Type, 'foobar');
});
it('calls parse and stringify for CHAR', function () {
var Type = new Sequelize.CHAR();
return testSuccess(Type, 'foobar');
});
it('calls parse and stringify for STRING', function () {
var Type = new Sequelize.STRING();
return testSuccess(Type, 'foobar');
});
it('calls parse and stringify for TEXT', function () {
var Type = new Sequelize.TEXT();
if (dialect === 'mssql') {
// Text uses nvarchar, same type as string
testFailure(Type);
} else {
return testSuccess(Type, 'foobar');
}
});
it('calls parse and stringify for BOOLEAN', function () {
var Type = new Sequelize.BOOLEAN();
return testSuccess(Type, true);
});
it('calls parse and stringify for INTEGER', function () {
var Type = new Sequelize.INTEGER();
return testSuccess(Type, 1);
});
it('calls parse and stringify for DECIMAL', function () {
var Type = new Sequelize.DECIMAL();
return testSuccess(Type, 1.5);
});
it('calls parse and stringify for BIGINT', function () {
var Type = new Sequelize.BIGINT();
if (dialect === 'mssql') {
// Same type as integer
testFailure(Type);
} else {
return testSuccess(Type, 1);
}
});
it('calls parse and stringify for DOUBLE', function () {
var Type = new Sequelize.DOUBLE();
return testSuccess(Type, 1.5);
});
it('calls parse and stringify for FLOAT', function () {
var Type = new Sequelize.FLOAT();
if (dialect === 'postgres') {
// Postgres doesn't have float, maps to either decimal or double
testFailure(Type);
} else {
return testSuccess(Type, 1.5);
}
});
it('calls parse and stringify for REAL', function () {
var Type = new Sequelize.REAL();
return testSuccess(Type, 1.5);
});
it('calls parse and stringify for GEOMETRY', function () {
var Type = new Sequelize.GEOMETRY();
if (['postgres', 'mysql', 'mariadb'].indexOf(dialect) !== -1) {
return testSuccess(Type, { type: "Point", coordinates: [125.6, 10.1] });
} else {
// Not implemented yet
testFailure(Type);
}
});
it('calls parse and stringify for UUID', function () {
var Type = new Sequelize.UUID();
if (['postgres', 'sqlite'].indexOf(dialect) !== -1) {
return testSuccess(Type, uuid.v4());
} else {
// No native uuid type
testFailure(Type);
}
});
it('calls parse and stringify for ENUM', function () {
var Type = new Sequelize.ENUM('hat', 'cat');
// No dialects actually allow us to identify that we get an enum back..
testFailure(Type);
});
it('should parse an empty GEOMETRY field', function () {
var Type = new Sequelize.GEOMETRY();
if (current.dialect.supports.GEOMETRY) {
current.refreshTypes();
var User = current.define('user', { field: Type }, { timestamps: false });
var point = { type: "Point", coordinates: [] };
return current.sync({ force: true }).then(function () {
return User.create({
//insert a null GEOMETRY type
field: point
});
}).then(function () {
//This case throw unhandled exception
return User.findAll();
}).then(function(users){
if (Support.dialectIsMySQL()) {
// MySQL will return NULL, becuase they lack EMPTY geometry data support.
expect(users[0].field).to.be.eql(null);
} else if (dialect === 'postgres' || dialect === 'postgres-native') {
//Empty Geometry data [0,0] as per https://trac.osgeo.org/postgis/ticket/1996
expect(users[0].field).to.be.deep.eql({ type: "Point", coordinates: [0,0] });
} else {
expect(users[0].field).to.be.deep.eql(point);
}
});
}
});
if (dialect === 'postgres' || dialect === 'sqlite') {
// postgres actively supports IEEE floating point literals, and sqlite doesn't care what we throw at it
it('should store and parse IEEE floating point literals (NaN and Infinity', function () {
var Model = this.sequelize.define('model', {
float: Sequelize.FLOAT,
double: Sequelize.DOUBLE,
real: Sequelize.REAL
});
return Model.sync({ force: true }).then(function () {
return Model.create({
id: 1,
float: NaN,
double: Infinity,
real: -Infinity
});
}).then(function () {
return Model.find({id: 1});
}).then(function (user) {
expect(user.get('float')).to.be.NaN;
expect(user.get('double')).to.eq(Infinity);
expect(user.get('real')).to.eq(-Infinity);
});
});
}
});
|
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
plugins: [
'@typescript-eslint',
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
};
|
import { run } from '@ember/runloop';
import { Component, getTemplate, setTemplates, hasTemplate, setTemplate } from 'ember-glimmer';
import bootstrap from '../../lib/system/bootstrap';
import {
runAppend,
runDestroy,
buildOwner,
moduleFor,
AbstractTestCase,
} from 'internal-test-helpers';
let component, fixture;
function checkTemplate(templateName, assert) {
run(() => bootstrap({ context: fixture, hasTemplate, setTemplate }));
let template = getTemplate(templateName);
let qunitFixture = document.querySelector('#qunit-fixture');
assert.ok(template, 'template is available on Ember.TEMPLATES');
assert.notOk(qunitFixture.querySelector('script'), 'script removed');
let owner = buildOwner();
owner.register('template:-top-level', template);
owner.register(
'component:-top-level',
Component.extend({
layoutName: '-top-level',
firstName: 'Tobias',
drug: 'teamocil',
})
);
component = owner.lookup('component:-top-level');
runAppend(component);
assert.equal(qunitFixture.textContent.trim(), 'Tobias takes teamocil', 'template works');
runDestroy(owner);
}
moduleFor(
'ember-templates: bootstrap',
class extends AbstractTestCase {
constructor() {
super();
fixture = document.getElementById('qunit-fixture');
}
teardown() {
setTemplates({});
fixture = component = null;
}
['@test template with data-template-name should add a new template to Ember.TEMPLATES'](
assert
) {
fixture.innerHTML =
'<script type="text/x-handlebars" data-template-name="funkyTemplate">{{firstName}} takes {{drug}}</script>';
checkTemplate('funkyTemplate', assert);
}
['@test template with id instead of data-template-name should add a new template to Ember.TEMPLATES'](
assert
) {
fixture.innerHTML =
'<script type="text/x-handlebars" id="funkyTemplate" >{{firstName}} takes {{drug}}</script>';
checkTemplate('funkyTemplate', assert);
}
['@test template without data-template-name or id should default to application'](assert) {
fixture.innerHTML = '<script type="text/x-handlebars">{{firstName}} takes {{drug}}</script>';
checkTemplate('application', assert);
}
// Add this test case, only for typeof Handlebars === 'object';
[`${
typeof Handlebars === 'object' ? '@test' : '@skip'
} template with type text/x-raw-handlebars should be parsed`](assert) {
fixture.innerHTML =
'<script type="text/x-raw-handlebars" data-template-name="funkyTemplate">{{name}}</script>';
run(() => bootstrap({ context: fixture, hasTemplate, setTemplate }));
let template = getTemplate('funkyTemplate');
assert.ok(template, 'template with name funkyTemplate available');
// This won't even work with Ember templates
assert.equal(template({ name: 'Tobias' }).trim(), 'Tobias');
}
['@test duplicated default application templates should throw exception'](assert) {
fixture.innerHTML =
'<script type="text/x-handlebars">first</script><script type="text/x-handlebars">second</script>';
assert.throws(
() => bootstrap({ context: fixture, hasTemplate, setTemplate }),
/Template named "[^"]+" already exists\./,
'duplicate templates should not be allowed'
);
}
['@test default default application template and id application template present should throw exception'](
assert
) {
fixture.innerHTML =
'<script type="text/x-handlebars">first</script><script type="text/x-handlebars" id="application">second</script>';
assert.throws(
() => bootstrap({ context: fixture, hasTemplate, setTemplate }),
/Template named "[^"]+" already exists\./,
'duplicate templates should not be allowed'
);
}
['@test default application template and data-template-name application template present should throw exception'](
assert
) {
fixture.innerHTML =
'<script type="text/x-handlebars">first</script><script type="text/x-handlebars" data-template-name="application">second</script>';
assert.throws(
() => bootstrap({ context: fixture, hasTemplate, setTemplate }),
/Template named "[^"]+" already exists\./,
'duplicate templates should not be allowed'
);
}
['@test duplicated template id should throw exception'](assert) {
fixture.innerHTML =
'<script type="text/x-handlebars" id="funkyTemplate">first</script><script type="text/x-handlebars" id="funkyTemplate">second</script>';
assert.throws(
() => bootstrap({ context: fixture, hasTemplate, setTemplate }),
/Template named "[^"]+" already exists\./,
'duplicate templates should not be allowed'
);
}
['@test duplicated template data-template-name should throw exception'](assert) {
fixture.innerHTML =
'<script type="text/x-handlebars" data-template-name="funkyTemplate">first</script><script type="text/x-handlebars" data-template-name="funkyTemplate">second</script>';
assert.throws(
() => bootstrap({ context: fixture, hasTemplate, setTemplate }),
/Template named "[^"]+" already exists\./,
'duplicate templates should not be allowed'
);
}
}
);
|
// Vex Base Libraries.
// Mohit Muthanna Cheppudira <mohit@muthanna.com>
//
// Copyright Mohit Muthanna Cheppudira 2010
/* global window: false */
/* global document: false */
function Vex() {}
/**
* Enable debug mode for special-case code.
*
* @define {boolean}
*/
Vex.Debug = true;
/**
* Logging levels available to this application.
* @enum {number}
*/
Vex.LogLevels = {
DEBUG: 5,
INFO: 4,
WARN: 3,
ERROR: 2,
FATAL: 1
};
/**
* Set the debuglevel for this application.
*
* @define {number}
*/
Vex.LogLevel = 5;
/**
* Logs a message to the console.
*
* @param {Vex.LogLevels} level A logging level.
* @param {string|number|!Object} A log message (or object to dump).
*/
Vex.LogMessage = function(level, message) {
if ((level <= Vex.LogLevel) && window.console) {
var log_message = message;
if (typeof(message) == 'object') {
log_message = {
level: level,
message: message
};
} else {
log_message = "VexLog: [" + level + "] " + log_message;
}
window.console.log(log_message);
}
};
/**
* Logging shortcuts.
*/
Vex.LogDebug = function(message) {
Vex.LogMessage(Vex.LogLevels.DEBUG, message); };
Vex.LogInfo = function(message) {
Vex.LogMessage(Vex.LogLevels.INFO, message); };
Vex.LogWarn = function(message) {
Vex.LogMessage(Vex.LogLevels.WARN, message); };
Vex.LogError = function(message) {
Vex.LogMessage(Vex.LogLevels.ERROR, message); };
Vex.LogFatal = function(message, exception) {
Vex.LogMessage(Vex.LogLevels.FATAL, message);
if (exception) throw exception; else throw "VexFatalError";
};
Vex.Log = Vex.LogDebug;
Vex.L = Vex.LogDebug;
/**
* Simple assertion checks.
*/
/**
* An exception for assertions.
*
* @constructor
* @param {string} message The message to display.
*/
Vex.AssertException = function(message) { this.message = message; };
Vex.AssertException.prototype.toString = function() {
return "AssertException: " + this.message;
};
Vex.Assert = function(exp, message) {
if (Vex.Debug && !exp) {
if (!message) message = "Assertion failed.";
throw new Vex.AssertException(message);
}
};
/**
* An generic runtime exception. For example:
*
* throw new Vex.RuntimeError("BadNoteError", "Bad note: " + note);
*
* @constructor
* @param {string} message The exception message.
*/
Vex.RuntimeError = function(code, message) {
this.code = code;
this.message = message;
};
Vex.RuntimeError.prototype.toString = function() {
return "RuntimeError: " + this.message;
};
Vex.RERR = Vex.RuntimeError;
/**
* Merge "destination" hash with "source" hash, overwriting like keys
* in "source" if necessary.
*/
Vex.Merge = function(destination, source) {
for (var property in source)
destination[property] = source[property];
return destination;
};
/**
* Min / Max: If you don't know what this does, you should be ashamed of yourself.
*/
Vex.Min = function(a, b) {
return (a > b) ? b : a;
};
Vex.Max = function(a, b) {
return (a > b) ? a : b;
};
// Round number to nearest fractional value (.5, .25, etc.)
Vex.RoundN = function(x, n) {
return (x % n) >= (n/2) ?
parseInt(x / n, 10) * n + n : parseInt(x / n, 10) * n;
};
// Locate the mid point between stave lines. Returns a fractional line if a space
Vex.MidLine = function(a, b) {
var mid_line = b + (a - b) / 2;
if (mid_line % 2 > 0) {
mid_line = Vex.RoundN(mid_line * 10, 5) / 10;
}
return mid_line;
};
/**
* Take 'arr' and return a new list consisting of the sorted, unique,
* contents of arr.
*/
Vex.SortAndUnique = function(arr, cmp, eq) {
if (arr.length > 1) {
var newArr = [];
var last;
arr.sort(cmp);
for (var i = 0; i < arr.length; ++i) {
if (i === 0 || !eq(arr[i], last)) {
newArr.push(arr[i]);
}
last = arr[i];
}
return newArr;
} else {
return arr;
}
};
/**
* Check if array "a" contains "obj"
*/
Vex.Contains = function(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
};
/**
* @param {string} canvas_sel The selector id for the canvas.
* @return {!Object} A 2D canvas context.
*/
Vex.getCanvasContext = function(canvas_sel) {
if (!canvas_sel)
throw new Vex.RERR("BadArgument", "Invalid canvas selector: " + canvas_sel);
var canvas = document.getElementById(canvas_sel);
if (!(canvas && canvas.getContext)) {
throw new Vex.RERR("UnsupportedBrowserError",
"This browser does not support HTML5 Canvas");
}
return canvas.getContext('2d');
};
/**
* Draw a tiny marker on the specified canvas. A great debugging aid.
*
* @param {!Object} ctx Canvas context.
* @param {number} x X position for dot.
* @param {number} y Y position for dot.
*/
Vex.drawDot = function(ctx, x, y, color) {
var c = color || "#f55";
ctx.save();
ctx.fillStyle = c;
//draw a circle
ctx.beginPath();
ctx.arc(x, y, 3, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.restore();
};
Vex.BM = function(s, f) {
var start_time = new Date().getTime();
f();
var elapsed = new Date().getTime() - start_time;
Vex.L(s + elapsed + "ms");
};
/**
* Basic classical inheritance helper. Usage:
*
* Vex.Inherit(Child, Parent, {
* getName: function() {return this.name;},
* setName: function(name) {this.name = name}
* });
*
* Returns Child.
*/
Vex.Inherit = (function () {
var F = function () {};
return function (C, P, O) {
F.prototype = P.prototype;
C.prototype = new F();
C.superclass = P.prototype;
C.prototype.constructor = C;
Vex.Merge(C.prototype, O);
return C;
};
}()); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var message_constants_1 = require("../../binary-protocol/src/message-constants");
var constants_1 = require("../../src/constants");
var Listener = /** @class */ (function () {
function Listener(topic, services) {
this.topic = topic;
this.services = services;
this.listeners = new Map();
this.stopCallbacks = new Map();
if (topic === message_constants_1.TOPIC.RECORD) {
this.actions = message_constants_1.RECORD_ACTIONS;
}
else if (topic === message_constants_1.TOPIC.EVENT) {
this.actions = message_constants_1.EVENT_ACTIONS;
}
this.services.connection.onLost(this.onConnectionLost.bind(this));
this.services.connection.onReestablished(this.onConnectionReestablished.bind(this));
}
Listener.prototype.listen = function (pattern, callback) {
if (typeof pattern !== 'string' || pattern.length === 0) {
throw new Error('invalid argument pattern');
}
if (typeof callback !== 'function') {
throw new Error('invalid argument callback');
}
if (this.listeners.has(pattern)) {
this.services.logger.warn({
topic: this.topic,
action: constants_1.EVENT.LISTENER_EXISTS,
name: pattern
});
return;
}
this.listeners.set(pattern, callback);
this.sendListen(pattern);
};
Listener.prototype.unlisten = function (pattern) {
if (typeof pattern !== 'string' || pattern.length === 0) {
throw new Error('invalid argument pattern');
}
if (!this.listeners.has(pattern)) {
this.services.logger.warn({
topic: this.topic,
action: constants_1.EVENT.NOT_LISTENING,
name: pattern
});
return;
}
this.listeners.delete(pattern);
this.sendUnlisten(pattern);
};
/*
* Accepting a listener request informs deepstream that the current provider is willing to
* provide the record or event matching the subscriptionName . This will establish the current
* provider as the only publisher for the actual subscription with the deepstream cluster.
* Either accept or reject needs to be called by the listener
*/
Listener.prototype.accept = function (pattern, subscription) {
this.services.connection.sendMessage({
topic: this.topic,
action: this.actions.LISTEN_ACCEPT,
name: pattern,
subscription: subscription
});
};
/*
* Rejecting a listener request informs deepstream that the current provider is not willing
* to provide the record or event matching the subscriptionName . This will result in deepstream
* requesting another provider to do so instead. If no other provider accepts or exists, the
* resource will remain unprovided.
* Either accept or reject needs to be called by the listener
*/
Listener.prototype.reject = function (pattern, subscription) {
this.services.connection.sendMessage({
topic: this.topic,
action: this.actions.LISTEN_REJECT,
name: pattern,
subscription: subscription
});
};
Listener.prototype.stop = function (subscription, callback) {
this.stopCallbacks.set(subscription, callback);
};
Listener.prototype.handle = function (message) {
if (message.isAck) {
this.services.timeoutRegistry.remove(message);
return;
}
if (message.action === this.actions.SUBSCRIPTION_FOR_PATTERN_FOUND) {
var listener = this.listeners.get(message.name);
if (listener) {
listener(message.subscription, {
accept: this.accept.bind(this, message.name, message.subscription),
reject: this.reject.bind(this, message.name, message.subscription),
onStop: this.stop.bind(this, message.subscription)
});
}
return;
}
if (message.action === this.actions.SUBSCRIPTION_FOR_PATTERN_REMOVED) {
var stopCallback = this.stopCallbacks.get(message.subscription);
if (stopCallback) {
stopCallback(message.subscription);
this.stopCallbacks.delete(message.subscription);
}
return;
}
this.services.logger.error(message, constants_1.EVENT.UNSOLICITED_MESSAGE);
};
Listener.prototype.onConnectionLost = function () {
this.stopCallbacks.forEach(function (callback, subscription) {
callback(subscription);
});
this.stopCallbacks.clear();
};
Listener.prototype.onConnectionReestablished = function () {
var _this = this;
this.listeners.forEach(function (callback, pattern) {
_this.sendListen(pattern);
});
};
/*
* Sends a C.ACTIONS.LISTEN to deepstream.
*/
Listener.prototype.sendListen = function (pattern) {
var message = {
topic: this.topic,
action: this.actions.LISTEN,
name: pattern
};
this.services.timeoutRegistry.add({ message: message });
this.services.connection.sendMessage(message);
};
Listener.prototype.sendUnlisten = function (pattern) {
var message = {
topic: this.topic,
action: this.actions.UNLISTEN,
name: pattern
};
this.services.timeoutRegistry.add({ message: message });
this.services.connection.sendMessage(message);
};
return Listener;
}());
exports.Listener = Listener;
|
/*!
* bindings/inputmask.binding.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.1-beta.37
*/
!function(a){"function"==typeof define&&define.amd?define(["jquery","../inputmask","../global/document"],a):"object"==typeof exports?module.exports=a(require("jquery"),require("../inputmask"),require("../global/document")):a(jQuery,window.Inputmask,document)}(function(i,e,a){i(a).ajaxComplete(function(a,t,n){-1!==i.inArray("html",n.dataTypes)&&i(".inputmask, [data-inputmask], [data-inputmask-mask], [data-inputmask-alias]").each(function(a,t){void 0===t.inputmask&&e().mask(t)})}).ready(function(){i(".inputmask, [data-inputmask], [data-inputmask-mask], [data-inputmask-alias]").each(function(a,t){void 0===t.inputmask&&e().mask(t)})})}); |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.7.4.2_A2_T06;
* @section: 15.7.4.2;
* @assertion: toString: If radix is an integer from 2 to 36, but not 10,
* the result is a string, the choice of which is implementation-dependent;
* @description: radix is 7;
*/
//CHECK#1
if(Number.prototype.toString(7) !== "0"){
$ERROR('#1: Number.prototype.toString(7) === "0"');
}
//CHECK#2
if((new Number()).toString(7) !== "0"){
$ERROR('#2: (new Number()).toString(7) === "0"');
}
//CHECK#3
if((new Number(0)).toString(7) !== "0"){
$ERROR('#3: (new Number(0)).toString(7) === "0"');
}
//CHECK#4
if((new Number(-1)).toString(7) !== "-1"){
$ERROR('#4: (new Number(-1)).toString(7) === "-1"');
}
//CHECK#5
if((new Number(1)).toString(7) !== "1"){
$ERROR('#5: (new Number(1)).toString(7) === "1"');
}
//CHECK#6
if((new Number(Number.NaN)).toString(7) !== "NaN"){
$ERROR('#6: (new Number(Number.NaN)).toString(7) === "NaN"');
}
//CHECK#7
if((new Number(Number.POSITIVE_INFINITY)).toString(7) !== "Infinity"){
$ERROR('#7: (new Number(Number.POSITIVE_INFINITY)).toString(7) === "Infinity"');
}
//CHECK#8
if((new Number(Number.NEGATIVE_INFINITY)).toString(7) !== "-Infinity"){
$ERROR('#8: (new Number(Number.NEGATIVE_INFINITY)).toString(7) === "-Infinity"');
}
|
module.exports = function(config){
config.set({
basePath : '../',
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/js/**/*.js',
'test/unit/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
const BaseChecker = require('./../base-checker')
const { severityDescription } = require('../../doc/utils')
const DEFAULT_SEVERITY = 'warn'
const DEFAULT_IGNORE_CONSTRUCTORS = false
const DEFAULT_OPTION = { ignoreConstructors: DEFAULT_IGNORE_CONSTRUCTORS }
const ruleId = 'func-visibility'
const meta = {
type: 'security',
docs: {
description: `Explicitly mark visibility in function.`,
category: 'Security Rules',
options: [
{
description: severityDescription,
default: DEFAULT_SEVERITY
},
{
description:
'A JSON object with a single property "ignoreConstructors" specifying if the rule should ignore constructors. (**Note: This is required to be true for Solidity >=0.7.0 and false for <0.7.0**)',
default: JSON.stringify(DEFAULT_OPTION)
}
],
examples: {
good: [
{
description: 'Functions explicitly marked with visibility',
code: require('../../../test/fixtures/security/functions-with-visibility').join('\n')
}
],
bad: [
{
description: 'Functions without explicitly marked visibility',
code: require('../../../test/fixtures/security/functions-without-visibility').join('\n')
}
]
}
},
isDefault: false,
recommended: true,
defaultSetup: [DEFAULT_SEVERITY, DEFAULT_OPTION],
schema: {
type: 'object',
properties: {
ignoreConstructors: {
type: 'boolean'
}
}
}
}
class FuncVisibilityChecker extends BaseChecker {
constructor(reporter, config) {
super(reporter, ruleId, meta)
this.ignoreConstructors =
config && config.getObjectPropertyBoolean(ruleId, 'ignoreConstructors', false)
}
FunctionDefinition(node) {
if (node.isConstructor && this.ignoreConstructors) {
return
}
if (node.visibility === 'default') {
this.warn(
node,
node.isConstructor
? 'Explicitly mark visibility in function (Set ignoreConstructors to true if using solidity >=0.7.0)'
: 'Explicitly mark visibility in function'
)
}
}
}
module.exports = FuncVisibilityChecker
|
'use strict';
var memwatch = require('memwatch');
var dbServerName = '192.168.13.190';
var dbPort = 1433;
var dbName = 'test';
var dbUserId = 'test';
var dbPassword = 'test';
var dbConnectString = 'jdbc:sqlserver://' + dbServerName + ':' + dbPort + ';databaseName=' + dbName + ';selectMethod=direct;responseBuffering=adaptive;packetSize=0;programName=nodeJavaTest;hostProcess=nodeJavaTest;sendStringParametersAsUnicode=false;';
var dbConnectionClass = 'com.microsoft.sqlserver.jdbc.SQLServerDriver';
//var dbUserId = 'test';
//var dbPassword = 'test';
//var dbConnectString = "jdbc:mysql://localhost/test";
//var dbConnectionClass = 'com.mysql.jdbc.Driver';
var util = require('util');
var path = require('path');
var java = require('../../');
java.classpath.push(path.join(__dirname, 'sqljdbc4.jar'));
java.classpath.push(path.join(__dirname, 'mysql-connector-java-5.1.22-bin.jar'));
var DriverManager = java.import('java.sql.DriverManager');
setTimeout(function() {
console.log('start heap diff');
var hd = new memwatch.HeapDiff();
var loopStart = new Date();
for (var loopCount = 0; loopCount < 500000; loopCount++) {
console.log('loopCount:', loopCount);
doLoop();
}
var loopEnd = new Date();
console.log('end loop', loopEnd - loopStart);
memwatch.gc();
var diff = hd.end();
console.log(util.inspect(diff.change, false, 10, true));
console.log("done... waiting 30seconds");
setTimeout(function() {
console.log("really done");
}, 30 * 1000);
}, 1);
function doLoop() {
java.findClassSync(dbConnectionClass);
var conn = DriverManager.getConnectionSync(dbConnectString, dbUserId, dbPassword);
//console.log("connected");
var statement = conn.createStatementSync();
var queryString = "select * from Person";
var rs = statement.executeQuerySync(queryString);
var metaData = rs.getMetaDataSync();
var columnCount = metaData.getColumnCountSync();
while (rs.nextSync()) {
for (var i = 1; i <= columnCount; i++) {
var obj = rs.getObjectSync(i);
if (obj) {
if (obj.hasOwnProperty('getClassSync')) {
if (obj.getClassSync().toString() == 'class java.math.BigDecimal') {
//console.log(obj.doubleValueSync());
continue;
}
if (obj.getClassSync().toString() == 'class java.sql.Timestamp') {
//console.log(obj.getTimeSync());
continue;
}
//console.log("class:", obj.getClassSync().toString());
}
//console.log(obj);
}
}
}
conn.closeSync();
} |
//////////////////////////////////////////////////////////////////////////
// //
// 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. //
// //
//////////////////////////////////////////////////////////////////////////
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var _ = Package.underscore._;
var EJSON = Package.ejson.EJSON;
/* Package-scope variables */
var check, Match;
(function(){
////////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/check/match.js //
// //
////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// XXX docs // 1
// 2
// Things we explicitly do NOT support: // 3
// - heterogenous arrays // 4
// 5
var currentArgumentChecker = new Meteor.EnvironmentVariable; // 6
// 7
/** // 8
* @summary Check that a value matches a [pattern](#matchpatterns). // 9
* If the value does not match the pattern, throw a `Match.Error`. // 10
* // 11
* Particularly useful to assert that arguments to a function have the right // 12
* types and structure. // 13
* @locus Anywhere // 14
* @param {Any} value The value to check // 15
* @param {MatchPattern} pattern The pattern to match // 16
* `value` against // 17
*/ // 18
check = function (value, pattern) { // 19
// Record that check got called, if somebody cared. // 20
// // 21
// We use getOrNullIfOutsideFiber so that it's OK to call check() // 22
// from non-Fiber server contexts; the downside is that if you forget to // 23
// bindEnvironment on some random callback in your method/publisher, // 24
// it might not find the argumentChecker and you'll get an error about // 25
// not checking an argument that it looks like you're checking (instead // 26
// of just getting a "Node code must run in a Fiber" error). // 27
var argChecker = currentArgumentChecker.getOrNullIfOutsideFiber(); // 28
if (argChecker) // 29
argChecker.checking(value); // 30
var result = testSubtree(value, pattern); // 31
if (result) { // 32
var err = new Match.Error(result.message); // 33
if (result.path) { // 34
err.message += " in field " + result.path; // 35
err.path = result.path; // 36
} // 37
throw err; // 38
} // 39
}; // 40
// 41
/** // 42
* @namespace Match // 43
* @summary The namespace for all Match types and methods. // 44
*/ // 45
Match = { // 46
Optional: function (pattern) { // 47
return new Optional(pattern); // 48
}, // 49
OneOf: function (/*arguments*/) { // 50
return new OneOf(_.toArray(arguments)); // 51
}, // 52
Any: ['__any__'], // 53
Where: function (condition) { // 54
return new Where(condition); // 55
}, // 56
ObjectIncluding: function (pattern) { // 57
return new ObjectIncluding(pattern); // 58
}, // 59
ObjectWithValues: function (pattern) { // 60
return new ObjectWithValues(pattern); // 61
}, // 62
// Matches only signed 32-bit integers // 63
Integer: ['__integer__'], // 64
// 65
// XXX matchers should know how to describe themselves for errors // 66
Error: Meteor.makeErrorType("Match.Error", function (msg) { // 67
this.message = "Match error: " + msg; // 68
// The path of the value that failed to match. Initially empty, this gets // 69
// populated by catching and rethrowing the exception as it goes back up the // 70
// stack. // 71
// E.g.: "vals[3].entity.created" // 72
this.path = ""; // 73
// If this gets sent over DDP, don't give full internal details but at least // 74
// provide something better than 500 Internal server error. // 75
this.sanitizedError = new Meteor.Error(400, "Match failed"); // 76
}), // 77
// 78
// Tests to see if value matches pattern. Unlike check, it merely returns true // 79
// or false (unless an error other than Match.Error was thrown). It does not // 80
// interact with _failIfArgumentsAreNotAllChecked. // 81
// XXX maybe also implement a Match.match which returns more information about // 82
// failures but without using exception handling or doing what check() // 83
// does with _failIfArgumentsAreNotAllChecked and Meteor.Error conversion // 84
// 85
/** // 86
* @summary Returns true if the value matches the pattern. // 87
* @locus Anywhere // 88
* @param {Any} value The value to check // 89
* @param {MatchPattern} pattern The pattern to match `value` against // 90
*/ // 91
test: function (value, pattern) { // 92
return !testSubtree(value, pattern); // 93
}, // 94
// 95
// Runs `f.apply(context, args)`. If check() is not called on every element of // 96
// `args` (either directly or in the first level of an array), throws an error // 97
// (using `description` in the message). // 98
// // 99
_failIfArgumentsAreNotAllChecked: function (f, context, args, description) { // 100
var argChecker = new ArgumentChecker(args, description); // 101
var result = currentArgumentChecker.withValue(argChecker, function () { // 102
return f.apply(context, args); // 103
}); // 104
// If f didn't itself throw, make sure it checked all of its arguments. // 105
argChecker.throwUnlessAllArgumentsHaveBeenChecked(); // 106
return result; // 107
} // 108
}; // 109
// 110
var Optional = function (pattern) { // 111
this.pattern = pattern; // 112
}; // 113
// 114
var OneOf = function (choices) { // 115
if (_.isEmpty(choices)) // 116
throw new Error("Must provide at least one choice to Match.OneOf"); // 117
this.choices = choices; // 118
}; // 119
// 120
var Where = function (condition) { // 121
this.condition = condition; // 122
}; // 123
// 124
var ObjectIncluding = function (pattern) { // 125
this.pattern = pattern; // 126
}; // 127
// 128
var ObjectWithValues = function (pattern) { // 129
this.pattern = pattern; // 130
}; // 131
// 132
var typeofChecks = [ // 133
[String, "string"], // 134
[Number, "number"], // 135
[Boolean, "boolean"], // 136
// While we don't allow undefined in EJSON, this is good for optional // 137
// arguments with OneOf. // 138
[undefined, "undefined"] // 139
]; // 140
// 141
// Return `false` if it matches. Otherwise, return an object with a `message` and a `path` field. // 142
var testSubtree = function (value, pattern) { // 143
// Match anything! // 144
if (pattern === Match.Any) // 145
return false; // 146
// 147
// Basic atomic types. // 148
// Do not match boxed objects (e.g. String, Boolean) // 149
for (var i = 0; i < typeofChecks.length; ++i) { // 150
if (pattern === typeofChecks[i][0]) { // 151
if (typeof value === typeofChecks[i][1]) // 152
return false; // 153
return { // 154
message: "Expected " + typeofChecks[i][1] + ", got " + typeof value, // 155
path: "" // 156
}; // 157
} // 158
} // 159
if (pattern === null) { // 160
if (value === null) // 161
return false; // 162
return { // 163
message: "Expected null, got " + EJSON.stringify(value), // 164
path: "" // 165
}; // 166
} // 167
// 168
// Strings, numbers, and booleans match literally. Goes well with Match.OneOf. // 169
if (typeof pattern === "string" || typeof pattern === "number" || typeof pattern === "boolean") { // 170
if (value === pattern) // 171
return false; // 172
return { // 173
message: "Expected " + pattern + ", got " + EJSON.stringify(value), // 174
path: "" // 175
}; // 176
} // 177
// 178
// Match.Integer is special type encoded with array // 179
if (pattern === Match.Integer) { // 180
// There is no consistent and reliable way to check if variable is a 64-bit // 181
// integer. One of the popular solutions is to get reminder of division by 1 // 182
// but this method fails on really large floats with big precision. // 183
// E.g.: 1.348192308491824e+23 % 1 === 0 in V8 // 184
// Bitwise operators work consistantly but always cast variable to 32-bit // 185
// signed integer according to JavaScript specs. // 186
if (typeof value === "number" && (value | 0) === value) // 187
return false; // 188
return { // 189
message: "Expected Integer, got " + (value instanceof Object ? EJSON.stringify(value) : value),
path: "" // 191
}; // 192
} // 193
// 194
// "Object" is shorthand for Match.ObjectIncluding({}); // 195
if (pattern === Object) // 196
pattern = Match.ObjectIncluding({}); // 197
// 198
// Array (checked AFTER Any, which is implemented as an Array). // 199
if (pattern instanceof Array) { // 200
if (pattern.length !== 1) { // 201
return { // 202
message: "Bad pattern: arrays must have one type element" + EJSON.stringify(pattern), // 203
path: "" // 204
}; // 205
} // 206
if (!_.isArray(value) && !_.isArguments(value)) { // 207
return { // 208
message: "Expected array, got " + EJSON.stringify(value), // 209
path: "" // 210
}; // 211
} // 212
// 213
for (var i = 0, length = value.length; i < length; i++) { // 214
var result = testSubtree(value[i], pattern[0]); // 215
if (result) { // 216
result.path = _prependPath(i, result.path); // 217
return result; // 218
} // 219
} // 220
return false; // 221
} // 222
// 223
// Arbitrary validation checks. The condition can return false or throw a // 224
// Match.Error (ie, it can internally use check()) to fail. // 225
if (pattern instanceof Where) { // 226
var result; // 227
try { // 228
result = pattern.condition(value); // 229
} catch (err) { // 230
if (!(err instanceof Match.Error)) // 231
throw err; // 232
return { // 233
message: err.message, // 234
path: err.path // 235
}; // 236
} // 237
if (pattern.condition(value)) // 238
return false; // 239
// XXX this error is terrible // 240
return { // 241
message: "Failed Match.Where validation", // 242
path: "" // 243
}; // 244
} // 245
// 246
// 247
if (pattern instanceof Optional) // 248
pattern = Match.OneOf(undefined, pattern.pattern); // 249
// 250
if (pattern instanceof OneOf) { // 251
for (var i = 0; i < pattern.choices.length; ++i) { // 252
var result = testSubtree(value, pattern.choices[i]); // 253
if (!result) { // 254
// No error? Yay, return. // 255
return false; // 256
} // 257
// Match errors just mean try another choice. // 258
} // 259
// XXX this error is terrible // 260
return { // 261
message: "Failed Match.OneOf or Match.Optional validation", // 262
path: "" // 263
}; // 264
} // 265
// 266
// A function that isn't something we special-case is assumed to be a // 267
// constructor. // 268
if (pattern instanceof Function) { // 269
if (value instanceof pattern) // 270
return false; // 271
return { // 272
message: "Expected " + (pattern.name ||"particular constructor"), // 273
path: "" // 274
}; // 275
} // 276
// 277
var unknownKeysAllowed = false; // 278
var unknownKeyPattern; // 279
if (pattern instanceof ObjectIncluding) { // 280
unknownKeysAllowed = true; // 281
pattern = pattern.pattern; // 282
} // 283
if (pattern instanceof ObjectWithValues) { // 284
unknownKeysAllowed = true; // 285
unknownKeyPattern = [pattern.pattern]; // 286
pattern = {}; // no required keys // 287
} // 288
// 289
if (typeof pattern !== "object") { // 290
return { // 291
message: "Bad pattern: unknown pattern type", // 292
path: "" // 293
}; // 294
} // 295
// 296
// An object, with required and optional keys. Note that this does NOT do // 297
// structural matches against objects of special types that happen to match // 298
// the pattern: this really needs to be a plain old {Object}! // 299
if (typeof value !== 'object') { // 300
return { // 301
message: "Expected object, got " + typeof value, // 302
path: "" // 303
}; // 304
} // 305
if (value === null) { // 306
return { // 307
message: "Expected object, got null", // 308
path: "" // 309
}; // 310
} // 311
if (value.constructor !== Object) { // 312
return { // 313
message: "Expected plain object", // 314
path: "" // 315
}; // 316
} // 317
// 318
var requiredPatterns = {}; // 319
var optionalPatterns = {}; // 320
_.each(pattern, function (subPattern, key) { // 321
if (subPattern instanceof Optional) // 322
optionalPatterns[key] = subPattern.pattern; // 323
else // 324
requiredPatterns[key] = subPattern; // 325
}); // 326
// 327
for (var keys = _.keys(value), i = 0, length = keys.length; i < length; i++) { // 328
var key = keys[i]; // 329
var subValue = value[key]; // 330
if (_.has(requiredPatterns, key)) { // 331
var result = testSubtree(subValue, requiredPatterns[key]); // 332
if (result) { // 333
result.path = _prependPath(key, result.path); // 334
return result; // 335
} // 336
delete requiredPatterns[key]; // 337
} else if (_.has(optionalPatterns, key)) { // 338
var result = testSubtree(subValue, optionalPatterns[key]); // 339
if (result) { // 340
result.path = _prependPath(key, result.path); // 341
return result; // 342
} // 343
} else { // 344
if (!unknownKeysAllowed) { // 345
return { // 346
message: "Unknown key", // 347
path: key // 348
}; // 349
} // 350
if (unknownKeyPattern) { // 351
var result = testSubtree(subValue, unknownKeyPattern[0]); // 352
if (result) { // 353
result.path = _prependPath(key, result.path); // 354
return result; // 355
} // 356
} // 357
} // 358
} // 359
// 360
var keys = _.keys(requiredPatterns); // 361
if (keys.length) { // 362
return { // 363
message: "Missing key '" + keys[0] + "'", // 364
path: "" // 365
}; // 366
} // 367
}; // 368
// 369
var ArgumentChecker = function (args, description) { // 370
var self = this; // 371
// Make a SHALLOW copy of the arguments. (We'll be doing identity checks // 372
// against its contents.) // 373
self.args = _.clone(args); // 374
// Since the common case will be to check arguments in order, and we splice // 375
// out arguments when we check them, make it so we splice out from the end // 376
// rather than the beginning. // 377
self.args.reverse(); // 378
self.description = description; // 379
}; // 380
// 381
_.extend(ArgumentChecker.prototype, { // 382
checking: function (value) { // 383
var self = this; // 384
if (self._checkingOneValue(value)) // 385
return; // 386
// Allow check(arguments, [String]) or check(arguments.slice(1), [String]) // 387
// or check([foo, bar], [String]) to count... but only if value wasn't // 388
// itself an argument. // 389
if (_.isArray(value) || _.isArguments(value)) { // 390
_.each(value, _.bind(self._checkingOneValue, self)); // 391
} // 392
}, // 393
_checkingOneValue: function (value) { // 394
var self = this; // 395
for (var i = 0; i < self.args.length; ++i) { // 396
// Is this value one of the arguments? (This can have a false positive if // 397
// the argument is an interned primitive, but it's still a good enough // 398
// check.) // 399
// (NaN is not === to itself, so we have to check specially.) // 400
if (value === self.args[i] || (_.isNaN(value) && _.isNaN(self.args[i]))) { // 401
self.args.splice(i, 1); // 402
return true; // 403
} // 404
} // 405
return false; // 406
}, // 407
throwUnlessAllArgumentsHaveBeenChecked: function () { // 408
var self = this; // 409
if (!_.isEmpty(self.args)) // 410
throw new Error("Did not check() all arguments during " + // 411
self.description); // 412
} // 413
}); // 414
// 415
var _jsKeywords = ["do", "if", "in", "for", "let", "new", "try", "var", "case", // 416
"else", "enum", "eval", "false", "null", "this", "true", "void", "with", // 417
"break", "catch", "class", "const", "super", "throw", "while", "yield", // 418
"delete", "export", "import", "public", "return", "static", "switch", // 419
"typeof", "default", "extends", "finally", "package", "private", "continue", // 420
"debugger", "function", "arguments", "interface", "protected", "implements", // 421
"instanceof"]; // 422
// 423
// Assumes the base of path is already escaped properly // 424
// returns key + base // 425
var _prependPath = function (key, base) { // 426
if ((typeof key) === "number" || key.match(/^[0-9]+$/)) // 427
key = "[" + key + "]"; // 428
else if (!key.match(/^[a-z_$][0-9a-z_$]*$/i) || _.contains(_jsKeywords, key)) // 429
key = JSON.stringify([key]); // 430
// 431
if (base && base[0] !== "[") // 432
return key + '.' + base; // 433
return key + base; // 434
}; // 435
// 436
// 437
////////////////////////////////////////////////////////////////////////////////////////////////////////
}).call(this);
/* Exports */
if (typeof Package === 'undefined') Package = {};
Package.check = {
check: check,
Match: Match
};
})();
|
;(function() {
"use strict";
$script.ready('validation', function()
{
$script(validationMethodsJs);
});
$script.ready('app_editor', function()
{
$script(indexJs,'index');
});
$script.ready(['config','index'], function()
{
Index.init({
DataTable: {
datatableIsResponsive: datatableIsResponsive,
groupActionSupport: groupActionSupport,
rowDetailSupport: rowDetailSupport,
datatableFilterSupport: datatableFilterSupport
}
});
});
})(); |
/**
* Example of micromono server.
*/
// setup express app
var app = require('express')();
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
// Get a micromono instance.
var micromono = require('micromono')();
// Boot the service(s) with express server
// do stuff in the promise callback.
micromono.runServer(app).then(function() {
console.log('server booted');
app.listen(3000);
});
|
/*************************************************************
*
* MathJax/localization/bg/HelpDialog.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("bg","HelpDialog",{
version: "2.7.0",
isLoaded: true,
strings: {
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/bg/HelpDialog.js");
|
/* @flow */
import { decode } from 'he'
import { parseHTML } from './html-parser'
import { parseText } from './text-parser'
import { parseFilters } from './filter-parser'
import { cached, no, camelize } from 'shared/util'
import { isIE, isServerRendering } from 'core/util/env'
import {
pluckModuleFunction,
getAndRemoveAttr,
addProp,
addAttr,
addHandler,
addDirective,
getBindingAttr,
baseWarn
} from '../helpers'
export const dirRE = /^v-|^@|^:/
export const forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/
export const forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/
const bindRE = /^:|^v-bind:/
const onRE = /^@|^v-on:/
const argRE = /:(.*)$/
const modifierRE = /\.[^.]+/g
const decodeHTMLCached = cached(decode)
// configurable state
let warn
let platformGetTagNamespace
let platformMustUseProp
let platformIsPreTag
let preTransforms
let transforms
let postTransforms
let delimiters
/**
* Convert HTML string to AST.
*/
export function parse (
template: string,
options: CompilerOptions
): ASTElement | void {
warn = options.warn || baseWarn
platformGetTagNamespace = options.getTagNamespace || no
platformMustUseProp = options.mustUseProp || no
platformIsPreTag = options.isPreTag || no
preTransforms = pluckModuleFunction(options.modules, 'preTransformNode')
transforms = pluckModuleFunction(options.modules, 'transformNode')
postTransforms = pluckModuleFunction(options.modules, 'postTransformNode')
delimiters = options.delimiters
const stack = []
const preserveWhitespace = options.preserveWhitespace !== false
let root
let currentParent
let inVPre = false
let inPre = false
let warned = false
parseHTML(template, {
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag)
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs)
}
const element: ASTElement = {
type: 1,
tag,
attrsList: attrs,
attrsMap: makeAttrsMap(attrs),
parent: currentParent,
children: []
}
if (ns) {
element.ns = ns
}
if (isForbiddenTag(element) && !isServerRendering()) {
element.forbidden = true
process.env.NODE_ENV !== 'production' && warn(
'Templates should only be responsible for mapping the state to the ' +
'UI. Avoid placing tags with side-effects in your templates, such as ' +
`<${tag}>` + ', as they will not be parsed.'
)
}
// apply pre-transforms
for (let i = 0; i < preTransforms.length; i++) {
preTransforms[i](element, options)
}
if (!inVPre) {
processPre(element)
if (element.pre) {
inVPre = true
}
}
if (platformIsPreTag(element.tag)) {
inPre = true
}
if (inVPre) {
processRawAttrs(element)
} else {
processFor(element)
processIf(element)
processOnce(element)
processKey(element)
// determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !attrs.length
processRef(element)
processSlot(element)
processComponent(element)
for (let i = 0; i < transforms.length; i++) {
transforms[i](element, options)
}
processAttrs(element)
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production' && !warned) {
if (el.tag === 'slot' || el.tag === 'template') {
warned = true
warn(
`Cannot use <${el.tag}> as component root element because it may ` +
'contain multiple nodes:\n' + template
)
}
if (el.attrsMap.hasOwnProperty('v-for')) {
warned = true
warn(
'Cannot use v-for on stateful component root element because ' +
'it renders multiple elements:\n' + template
)
}
}
}
// tree management
if (!root) {
root = element
checkRootConstraints(root)
} else if (!stack.length) {
// allow root elements with v-if, v-else-if and v-else
if (root.if && (element.elseif || element.else)) {
checkRootConstraints(element)
addIfCondition(root, {
exp: element.elseif,
block: element
})
} else if (process.env.NODE_ENV !== 'production' && !warned) {
warned = true
warn(
`Component template should contain exactly one root element:` +
`\n\n${template}\n\n` +
`If you are using v-if on multiple elements, ` +
`use v-else-if to chain them instead.`
)
}
}
if (currentParent && !element.forbidden) {
if (element.elseif || element.else) {
processIfConditions(element, currentParent)
} else if (element.slotScope) { // scoped slot
currentParent.plain = false
const name = element.slotTarget || 'default'
;(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element
} else {
currentParent.children.push(element)
element.parent = currentParent
}
}
if (!unary) {
currentParent = element
stack.push(element)
}
// apply post-transforms
for (let i = 0; i < postTransforms.length; i++) {
postTransforms[i](element, options)
}
},
end () {
// remove trailing whitespace
const element = stack[stack.length - 1]
const lastNode = element.children[element.children.length - 1]
if (lastNode && lastNode.type === 3 && lastNode.text === ' ') {
element.children.pop()
}
// pop stack
stack.length -= 1
currentParent = stack[stack.length - 1]
// check pre state
if (element.pre) {
inVPre = false
}
if (platformIsPreTag(element.tag)) {
inPre = false
}
},
chars (text: string) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production' && !warned && text === template) {
warned = true
warn(
'Component template requires a root element, rather than just text:\n\n' + template
)
}
return
}
// IE textarea placeholder bug
/* istanbul ignore if */
if (isIE &&
currentParent.tag === 'textarea' &&
currentParent.attrsMap.placeholder === text) {
return
}
const children = currentParent.children
text = inPre || text.trim()
? decodeHTMLCached(text)
// only preserve whitespace if its not right after a starting tag
: preserveWhitespace && children.length ? ' ' : ''
if (text) {
let expression
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression,
text
})
} else if (text !== ' ' || children[children.length - 1].text !== ' ') {
currentParent.children.push({
type: 3,
text
})
}
}
}
})
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true
}
}
function processRawAttrs (el) {
const l = el.attrsList.length
if (l) {
const attrs = el.attrs = new Array(l)
for (let i = 0; i < l; i++) {
attrs[i] = {
name: el.attrsList[i].name,
value: JSON.stringify(el.attrsList[i].value)
}
}
} else if (!el.pre) {
// non root node in pre blocks with no attributes
el.plain = true
}
}
function processKey (el) {
const exp = getBindingAttr(el, 'key')
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn(`<template> cannot be keyed. Place the key on real elements instead.`)
}
el.key = exp
}
}
function processRef (el) {
const ref = getBindingAttr(el, 'ref')
if (ref) {
el.ref = ref
el.refInFor = checkInFor(el)
}
}
function processFor (el) {
let exp
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
const inMatch = exp.match(forAliasRE)
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn(
`Invalid v-for expression: ${exp}`
)
return
}
el.for = inMatch[2].trim()
const alias = inMatch[1].trim()
const iteratorMatch = alias.match(forIteratorRE)
if (iteratorMatch) {
el.alias = iteratorMatch[1].trim()
el.iterator1 = iteratorMatch[2].trim()
if (iteratorMatch[3]) {
el.iterator2 = iteratorMatch[3].trim()
}
} else {
el.alias = alias
}
}
}
function processIf (el) {
const exp = getAndRemoveAttr(el, 'v-if')
if (exp) {
el.if = exp
addIfCondition(el, {
exp: exp,
block: el
})
} else {
if (getAndRemoveAttr(el, 'v-else') != null) {
el.else = true
}
const elseif = getAndRemoveAttr(el, 'v-else-if')
if (elseif) {
el.elseif = elseif
}
}
}
function processIfConditions (el, parent) {
const prev = findPrevElement(parent.children)
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
})
} else if (process.env.NODE_ENV !== 'production') {
warn(
`v-${el.elseif ? ('else-if="' + el.elseif + '"') : 'else'} ` +
`used on element <${el.tag}> without corresponding v-if.`
)
}
}
function findPrevElement (children: Array<any>): ASTElement | void {
let i = children.length
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn(
`text "${children[i].text.trim()}" between v-if and v-else(-if) ` +
`will be ignored.`
)
}
children.pop()
}
}
}
function addIfCondition (el, condition) {
if (!el.ifConditions) {
el.ifConditions = []
}
el.ifConditions.push(condition)
}
function processOnce (el) {
const once = getAndRemoveAttr(el, 'v-once')
if (once != null) {
el.once = true
}
}
function processSlot (el) {
if (el.tag === 'slot') {
el.slotName = getBindingAttr(el, 'name')
if (process.env.NODE_ENV !== 'production' && el.key) {
warn(
`\`key\` does not work on <slot> because slots are abstract outlets ` +
`and can possibly expand into multiple elements. ` +
`Use the key on a wrapping element instead.`
)
}
} else {
const slotTarget = getBindingAttr(el, 'slot')
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope')
}
}
}
function processComponent (el) {
let binding
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true
}
}
function processAttrs (el) {
const list = el.attrsList
let i, l, name, rawName, value, arg, modifiers, isProp
for (i = 0, l = list.length; i < l; i++) {
name = rawName = list[i].name
value = list[i].value
if (dirRE.test(name)) {
// mark element as dynamic
el.hasBindings = true
// modifiers
modifiers = parseModifiers(name)
if (modifiers) {
name = name.replace(modifierRE, '')
}
if (bindRE.test(name)) { // v-bind
name = name.replace(bindRE, '')
value = parseFilters(value)
isProp = false
if (modifiers) {
if (modifiers.prop) {
isProp = true
name = camelize(name)
if (name === 'innerHtml') name = 'innerHTML'
}
if (modifiers.camel) {
name = camelize(name)
}
}
if (isProp || platformMustUseProp(el.tag, name)) {
addProp(el, name, value)
} else {
addAttr(el, name, value)
}
} else if (onRE.test(name)) { // v-on
name = name.replace(onRE, '')
addHandler(el, name, value, modifiers)
} else { // normal directives
name = name.replace(dirRE, '')
// parse arg
const argMatch = name.match(argRE)
if (argMatch && (arg = argMatch[1])) {
name = name.slice(0, -(arg.length + 1))
}
addDirective(el, name, rawName, value, arg, modifiers)
if (process.env.NODE_ENV !== 'production' && name === 'model') {
checkForAliasModel(el, value)
}
}
} else {
// literal attribute
if (process.env.NODE_ENV !== 'production') {
const expression = parseText(value, delimiters)
if (expression) {
warn(
`${name}="${value}": ` +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div id="{{ val }}">, use <div :id="val">.'
)
}
}
addAttr(el, name, JSON.stringify(value))
// #4530 also bind special attributes as props even if they are static
// so that patches between dynamic/static are consistent
if (platformMustUseProp(el.tag, name)) {
if (name === 'value') {
addProp(el, name, JSON.stringify(value))
} else {
addProp(el, name, 'true')
}
}
}
}
}
function checkInFor (el: ASTElement): boolean {
let parent = el
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent
}
return false
}
function parseModifiers (name: string): Object | void {
const match = name.match(modifierRE)
if (match) {
const ret = {}
match.forEach(m => { ret[m.slice(1)] = true })
return ret
}
}
function makeAttrsMap (attrs: Array<Object>): Object {
const map = {}
for (let i = 0, l = attrs.length; i < l; i++) {
if (process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE) {
warn('duplicate attribute: ' + attrs[i].name)
}
map[attrs[i].name] = attrs[i].value
}
return map
}
function isForbiddenTag (el): boolean {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
const ieNSBug = /^xmlns:NS\d+/
const ieNSPrefix = /^NS\d+:/
/* istanbul ignore next */
function guardIESVGBug (attrs) {
const res = []
for (let i = 0; i < attrs.length; i++) {
const attr = attrs[i]
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '')
res.push(attr)
}
}
return res
}
function checkForAliasModel (el, value) {
let _el = el
while (_el) {
if (_el.for && _el.alias === value) {
warn(
`<${el.tag} v-model="${value}">: ` +
`You are binding v-model directly to a v-for iteration alias. ` +
`This will not be able to modify the v-for source array because ` +
`writing to the alias is like modifying a function local variable. ` +
`Consider using an array of objects and use v-model on an object property instead.`
)
}
_el = _el.parent
}
}
|
/* global google, jQuery */
jQuery( function ( $ ) {
'use strict';
/**
* Callback function for Google Maps Lazy Load library to display map
*
* @return void
*/
function displayMap() {
var $container = $( this ),
options = $container.data( 'map_options' );
var mapOptions = options.js_options,
center = new google.maps.LatLng( options.latitude, options.longitude ),
map;
switch ( mapOptions.mapTypeId ) {
case 'ROADMAP':
mapOptions.mapTypeId = google.maps.MapTypeId.ROADMAP;
break;
case 'SATELLITE':
mapOptions.mapTypeId = google.maps.MapTypeId.SATELLITE;
break;
case 'HYBRID':
mapOptions.mapTypeId = google.maps.MapTypeId.HYBRID;
break;
case 'TERRAIN':
mapOptions.mapTypeId = google.maps.MapTypeId.TERRAIN;
break;
}
mapOptions.center = center;
// Typcast zoom to a number
mapOptions.zoom *= 1;
map = new google.maps.Map( this, mapOptions );
// Set marker
if ( options.marker ) {
var marker = new google.maps.Marker( {
position: center,
map: map
} );
// Set marker title
if ( options.marker_title ) {
marker.setTitle( options.marker_title );
}
// Set marker icon
if ( options.marker_icon ) {
marker.setIcon( options.marker_icon );
}
}
// Set info window
if ( options.info_window ) {
var infoWindow = new google.maps.InfoWindow( {
content: options.info_window,
minWidth: 200
} );
google.maps.event.addListener( marker, 'click', function () {
infoWindow.open( map, marker );
} );
}
}
// Loop through all map instances and display them
$( '.rwmb-map-canvas' ).each( displayMap );
} );
|
///
/// Remote methods and access control.
///
const hasOwn = Object.prototype.hasOwnProperty;
// Restrict default mutators on collection. allow() and deny() take the
// same options:
//
// options.insert {Function(userId, doc)}
// return true to allow/deny adding this document
//
// options.update {Function(userId, docs, fields, modifier)}
// return true to allow/deny updating these documents.
// `fields` is passed as an array of fields that are to be modified
//
// options.remove {Function(userId, docs)}
// return true to allow/deny removing these documents
//
// options.fetch {Array}
// Fields to fetch for these validators. If any call to allow or deny
// does not have this option then all fields are loaded.
//
// allow and deny can be called multiple times. The validators are
// evaluated as follows:
// - If neither deny() nor allow() has been called on the collection,
// then the request is allowed if and only if the "insecure" smart
// package is in use.
// - Otherwise, if any deny() function returns true, the request is denied.
// - Otherwise, if any allow() function returns true, the request is allowed.
// - Otherwise, the request is denied.
//
// Meteor may call your deny() and allow() functions in any order, and may not
// call all of them if it is able to make a decision without calling them all
// (so don't include side effects).
AllowDeny = {
CollectionPrototype: {}
};
// In the `mongo` package, we will extend Mongo.Collection.prototype with these
// methods
const CollectionPrototype = AllowDeny.CollectionPrototype;
/**
* @summary Allow users to write directly to this collection from client code, subject to limitations you define.
* @locus Server
* @method allow
* @memberOf Mongo.Collection
* @instance
* @param {Object} options
* @param {Function} options.insert,update,remove Functions that look at a proposed modification to the database and return true if it should be allowed.
* @param {String[]} options.fetch Optional performance enhancement. Limits the fields that will be fetched from the database for inspection by your `update` and `remove` functions.
* @param {Function} options.transform Overrides `transform` on the [`Collection`](#collections). Pass `null` to disable transformation.
*/
CollectionPrototype.allow = function(options) {
addValidator(this, 'allow', options);
};
/**
* @summary Override `allow` rules.
* @locus Server
* @method deny
* @memberOf Mongo.Collection
* @instance
* @param {Object} options
* @param {Function} options.insert,update,remove Functions that look at a proposed modification to the database and return true if it should be denied, even if an [allow](#allow) rule says otherwise.
* @param {String[]} options.fetch Optional performance enhancement. Limits the fields that will be fetched from the database for inspection by your `update` and `remove` functions.
* @param {Function} options.transform Overrides `transform` on the [`Collection`](#collections). Pass `null` to disable transformation.
*/
CollectionPrototype.deny = function(options) {
addValidator(this, 'deny', options);
};
CollectionPrototype._defineMutationMethods = function(options) {
const self = this;
options = options || {};
// set to true once we call any allow or deny methods. If true, use
// allow/deny semantics. If false, use insecure mode semantics.
self._restricted = false;
// Insecure mode (default to allowing writes). Defaults to 'undefined' which
// means insecure iff the insecure package is loaded. This property can be
// overriden by tests or packages wishing to change insecure mode behavior of
// their collections.
self._insecure = undefined;
self._validators = {
insert: {allow: [], deny: []},
update: {allow: [], deny: []},
remove: {allow: [], deny: []},
upsert: {allow: [], deny: []}, // dummy arrays; can't set these!
fetch: [],
fetchAllFields: false
};
if (!self._name)
return; // anonymous collection
// XXX Think about method namespacing. Maybe methods should be
// "Meteor:Mongo:insert/NAME"?
self._prefix = '/' + self._name + '/';
// Mutation Methods
// Minimongo on the server gets no stubs; instead, by default
// it wait()s until its result is ready, yielding.
// This matches the behavior of macromongo on the server better.
// XXX see #MeteorServerNull
if (self._connection && (self._connection === Meteor.server || Meteor.isClient)) {
const m = {};
['insert', 'update', 'remove'].forEach((method) => {
const methodName = self._prefix + method;
if (options.useExisting) {
const handlerPropName = Meteor.isClient ? '_methodHandlers' : 'method_handlers';
// Do not try to create additional methods if this has already been called.
// (Otherwise the .methods() call below will throw an error.)
if (self._connection[handlerPropName] &&
typeof self._connection[handlerPropName][methodName] === 'function') return;
}
m[methodName] = function (/* ... */) {
// All the methods do their own validation, instead of using check().
check(arguments, [Match.Any]);
const args = Array.from(arguments);
try {
// For an insert, if the client didn't specify an _id, generate one
// now; because this uses DDP.randomStream, it will be consistent with
// what the client generated. We generate it now rather than later so
// that if (eg) an allow/deny rule does an insert to the same
// collection (not that it really should), the generated _id will
// still be the first use of the stream and will be consistent.
//
// However, we don't actually stick the _id onto the document yet,
// because we want allow/deny rules to be able to differentiate
// between arbitrary client-specified _id fields and merely
// client-controlled-via-randomSeed fields.
let generatedId = null;
if (method === "insert" && !hasOwn.call(args[0], '_id')) {
generatedId = self._makeNewID();
}
if (this.isSimulation) {
// In a client simulation, you can do any mutation (even with a
// complex selector).
if (generatedId !== null)
args[0]._id = generatedId;
return self._collection[method].apply(
self._collection, args);
}
// This is the server receiving a method call from the client.
// We don't allow arbitrary selectors in mutations from the client: only
// single-ID selectors.
if (method !== 'insert')
throwIfSelectorIsNotId(args[0], method);
if (self._restricted) {
// short circuit if there is no way it will pass.
if (self._validators[method].allow.length === 0) {
throw new Meteor.Error(
403, "Access denied. No allow validators set on restricted " +
"collection for method '" + method + "'.");
}
const validatedMethodName =
'_validated' + method.charAt(0).toUpperCase() + method.slice(1);
args.unshift(this.userId);
method === 'insert' && args.push(generatedId);
return self[validatedMethodName].apply(self, args);
} else if (self._isInsecure()) {
if (generatedId !== null)
args[0]._id = generatedId;
// In insecure mode, allow any mutation (with a simple selector).
// XXX This is kind of bogus. Instead of blindly passing whatever
// we get from the network to this function, we should actually
// know the correct arguments for the function and pass just
// them. For example, if you have an extraneous extra null
// argument and this is Mongo on the server, the .wrapAsync'd
// functions like update will get confused and pass the
// "fut.resolver()" in the wrong slot, where _update will never
// invoke it. Bam, broken DDP connection. Probably should just
// take this whole method and write it three times, invoking
// helpers for the common code.
return self._collection[method].apply(self._collection, args);
} else {
// In secure mode, if we haven't called allow or deny, then nothing
// is permitted.
throw new Meteor.Error(403, "Access denied");
}
} catch (e) {
if (
e.name === 'MongoError' ||
e.name === 'BulkWriteError' ||
e.name === 'MinimongoError'
) {
throw new Meteor.Error(409, e.toString());
} else {
throw e;
}
}
};
});
self._connection.methods(m);
}
};
CollectionPrototype._updateFetch = function (fields) {
const self = this;
if (!self._validators.fetchAllFields) {
if (fields) {
const union = Object.create(null);
const add = names => names && names.forEach(name => union[name] = 1);
add(self._validators.fetch);
add(fields);
self._validators.fetch = Object.keys(union);
} else {
self._validators.fetchAllFields = true;
// clear fetch just to make sure we don't accidentally read it
self._validators.fetch = null;
}
}
};
CollectionPrototype._isInsecure = function () {
const self = this;
if (self._insecure === undefined)
return !!Package.insecure;
return self._insecure;
};
CollectionPrototype._validatedInsert = function (userId, doc,
generatedId) {
const self = this;
// call user validators.
// Any deny returns true means denied.
if (self._validators.insert.deny.some((validator) => {
return validator(userId, docToValidate(validator, doc, generatedId));
})) {
throw new Meteor.Error(403, "Access denied");
}
// Any allow returns true means proceed. Throw error if they all fail.
if (self._validators.insert.allow.every((validator) => {
return !validator(userId, docToValidate(validator, doc, generatedId));
})) {
throw new Meteor.Error(403, "Access denied");
}
// If we generated an ID above, insert it now: after the validation, but
// before actually inserting.
if (generatedId !== null)
doc._id = generatedId;
self._collection.insert.call(self._collection, doc);
};
// Simulate a mongo `update` operation while validating that the access
// control rules set by calls to `allow/deny` are satisfied. If all
// pass, rewrite the mongo operation to use $in to set the list of
// document ids to change ##ValidatedChange
CollectionPrototype._validatedUpdate = function(
userId, selector, mutator, options) {
const self = this;
check(mutator, Object);
options = Object.assign(Object.create(null), options);
if (!LocalCollection._selectorIsIdPerhapsAsObject(selector))
throw new Error("validated update should be of a single ID");
// We don't support upserts because they don't fit nicely into allow/deny
// rules.
if (options.upsert)
throw new Meteor.Error(403, "Access denied. Upserts not " +
"allowed in a restricted collection.");
const noReplaceError = "Access denied. In a restricted collection you can only" +
" update documents, not replace them. Use a Mongo update operator, such " +
"as '$set'.";
const mutatorKeys = Object.keys(mutator);
// compute modified fields
const modifiedFields = {};
if (mutatorKeys.length === 0) {
throw new Meteor.Error(403, noReplaceError);
}
mutatorKeys.forEach((op) => {
const params = mutator[op];
if (op.charAt(0) !== '$') {
throw new Meteor.Error(403, noReplaceError);
} else if (!hasOwn.call(ALLOWED_UPDATE_OPERATIONS, op)) {
throw new Meteor.Error(
403, "Access denied. Operator " + op + " not allowed in a restricted collection.");
} else {
Object.keys(params).forEach((field) => {
// treat dotted fields as if they are replacing their
// top-level part
if (field.indexOf('.') !== -1)
field = field.substring(0, field.indexOf('.'));
// record the field we are trying to change
modifiedFields[field] = true;
});
}
});
const fields = Object.keys(modifiedFields);
const findOptions = {transform: null};
if (!self._validators.fetchAllFields) {
findOptions.fields = {};
self._validators.fetch.forEach((fieldName) => {
findOptions.fields[fieldName] = 1;
});
}
const doc = self._collection.findOne(selector, findOptions);
if (!doc) // none satisfied!
return 0;
// call user validators.
// Any deny returns true means denied.
if (self._validators.update.deny.some((validator) => {
const factoriedDoc = transformDoc(validator, doc);
return validator(userId,
factoriedDoc,
fields,
mutator);
})) {
throw new Meteor.Error(403, "Access denied");
}
// Any allow returns true means proceed. Throw error if they all fail.
if (self._validators.update.allow.every((validator) => {
const factoriedDoc = transformDoc(validator, doc);
return !validator(userId,
factoriedDoc,
fields,
mutator);
})) {
throw new Meteor.Error(403, "Access denied");
}
options._forbidReplace = true;
// Back when we supported arbitrary client-provided selectors, we actually
// rewrote the selector to include an _id clause before passing to Mongo to
// avoid races, but since selector is guaranteed to already just be an ID, we
// don't have to any more.
return self._collection.update.call(
self._collection, selector, mutator, options);
};
// Only allow these operations in validated updates. Specifically
// whitelist operations, rather than blacklist, so new complex
// operations that are added aren't automatically allowed. A complex
// operation is one that does more than just modify its target
// field. For now this contains all update operations except '$rename'.
// http://docs.mongodb.org/manual/reference/operators/#update
const ALLOWED_UPDATE_OPERATIONS = {
$inc:1, $set:1, $unset:1, $addToSet:1, $pop:1, $pullAll:1, $pull:1,
$pushAll:1, $push:1, $bit:1
};
// Simulate a mongo `remove` operation while validating access control
// rules. See #ValidatedChange
CollectionPrototype._validatedRemove = function(userId, selector) {
const self = this;
const findOptions = {transform: null};
if (!self._validators.fetchAllFields) {
findOptions.fields = {};
self._validators.fetch.forEach((fieldName) => {
findOptions.fields[fieldName] = 1;
});
}
const doc = self._collection.findOne(selector, findOptions);
if (!doc)
return 0;
// call user validators.
// Any deny returns true means denied.
if (self._validators.remove.deny.some((validator) => {
return validator(userId, transformDoc(validator, doc));
})) {
throw new Meteor.Error(403, "Access denied");
}
// Any allow returns true means proceed. Throw error if they all fail.
if (self._validators.remove.allow.every((validator) => {
return !validator(userId, transformDoc(validator, doc));
})) {
throw new Meteor.Error(403, "Access denied");
}
// Back when we supported arbitrary client-provided selectors, we actually
// rewrote the selector to {_id: {$in: [ids that we found]}} before passing to
// Mongo to avoid races, but since selector is guaranteed to already just be
// an ID, we don't have to any more.
return self._collection.remove.call(self._collection, selector);
};
CollectionPrototype._callMutatorMethod = function _callMutatorMethod(name, args, callback) {
if (Meteor.isClient && !callback && !alreadyInSimulation()) {
// Client can't block, so it can't report errors by exception,
// only by callback. If they forget the callback, give them a
// default one that logs the error, so they aren't totally
// baffled if their writes don't work because their database is
// down.
// Don't give a default callback in simulation, because inside stubs we
// want to return the results from the local collection immediately and
// not force a callback.
callback = function (err) {
if (err)
Meteor._debug(name + " failed", err);
};
}
// For two out of three mutator methods, the first argument is a selector
const firstArgIsSelector = name === "update" || name === "remove";
if (firstArgIsSelector && !alreadyInSimulation()) {
// If we're about to actually send an RPC, we should throw an error if
// this is a non-ID selector, because the mutation methods only allow
// single-ID selectors. (If we don't throw here, we'll see flicker.)
throwIfSelectorIsNotId(args[0], name);
}
const mutatorMethodName = this._prefix + name;
return this._connection.apply(
mutatorMethodName, args, { returnStubValue: true }, callback);
}
function transformDoc(validator, doc) {
if (validator.transform)
return validator.transform(doc);
return doc;
}
function docToValidate(validator, doc, generatedId) {
let ret = doc;
if (validator.transform) {
ret = EJSON.clone(doc);
// If you set a server-side transform on your collection, then you don't get
// to tell the difference between "client specified the ID" and "server
// generated the ID", because transforms expect to get _id. If you want to
// do that check, you can do it with a specific
// `C.allow({insert: f, transform: null})` validator.
if (generatedId !== null) {
ret._id = generatedId;
}
ret = validator.transform(ret);
}
return ret;
}
function addValidator(collection, allowOrDeny, options) {
// validate keys
const validKeysRegEx = /^(?:insert|update|remove|fetch|transform)$/;
Object.keys(options).forEach((key) => {
if (!validKeysRegEx.test(key))
throw new Error(allowOrDeny + ": Invalid key: " + key);
});
collection._restricted = true;
['insert', 'update', 'remove'].forEach((name) => {
if (hasOwn.call(options, name)) {
if (!(options[name] instanceof Function)) {
throw new Error(allowOrDeny + ": Value for `" + name + "` must be a function");
}
// If the transform is specified at all (including as 'null') in this
// call, then take that; otherwise, take the transform from the
// collection.
if (options.transform === undefined) {
options[name].transform = collection._transform; // already wrapped
} else {
options[name].transform = LocalCollection.wrapTransform(
options.transform);
}
collection._validators[name][allowOrDeny].push(options[name]);
}
});
// Only update the fetch fields if we're passed things that affect
// fetching. This way allow({}) and allow({insert: f}) don't result in
// setting fetchAllFields
if (options.update || options.remove || options.fetch) {
if (options.fetch && !(options.fetch instanceof Array)) {
throw new Error(allowOrDeny + ": Value for `fetch` must be an array");
}
collection._updateFetch(options.fetch);
}
}
function throwIfSelectorIsNotId(selector, methodName) {
if (!LocalCollection._selectorIsIdPerhapsAsObject(selector)) {
throw new Meteor.Error(
403, "Not permitted. Untrusted code may only " + methodName +
" documents by ID.");
}
};
// Determine if we are in a DDP method simulation
function alreadyInSimulation() {
var CurrentInvocation =
DDP._CurrentMethodInvocation ||
// For backwards compatibility, as explained in this issue:
// https://github.com/meteor/meteor/issues/8947
DDP._CurrentInvocation;
const enclosing = CurrentInvocation.get();
return enclosing && enclosing.isSimulation;
}
|
/**
* @author oosmoxiecode
* based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
*/
THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
THREE.Geometry.call( this );
var scope = this;
this.radius = radius || 200;
this.tube = tube || 40;
this.segmentsR = segmentsR || 64;
this.segmentsT = segmentsT || 8;
this.p = p || 2;
this.q = q || 3;
this.heightScale = heightScale || 1;
this.grid = new Array(this.segmentsR);
var tang = new THREE.Vector3();
var n = new THREE.Vector3();
var bitan = new THREE.Vector3();
for ( var i = 0; i < this.segmentsR; ++ i ) {
this.grid[ i ] = new Array( this.segmentsT );
for ( var j = 0; j < this.segmentsT; ++ j ) {
var u = i / this.segmentsR * 2 * this.p * Math.PI;
var v = j / this.segmentsT * 2 * Math.PI;
var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
var cx, cy;
tang.sub( p2, p1 );
n.add( p2, p1 );
bitan.cross( tang, n );
n.cross( bitan, tang );
bitan.normalize();
n.normalize();
cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
cy = this.tube * Math.sin( v );
p1.x += cx * n.x + cy * bitan.x;
p1.y += cx * n.y + cy * bitan.y;
p1.z += cx * n.z + cy * bitan.z;
this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
}
}
for ( var i = 0; i < this.segmentsR; ++ i ) {
for ( var j = 0; j < this.segmentsT; ++ j ) {
var ip = ( i + 1 ) % this.segmentsR;
var jp = ( j + 1 ) % this.segmentsT;
var a = this.grid[ i ][ j ];
var b = this.grid[ ip ][ j ];
var c = this.grid[ ip ][ jp ];
var d = this.grid[ i ][ jp ];
var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
this.faces.push( new THREE.Face4( a, b, c, d ) );
this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
}
}
this.computeCentroids();
this.computeFaceNormals();
this.computeVertexNormals();
function vert( x, y, z ) {
return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
}
function getPos( u, v, in_q, in_p, radius, heightScale ) {
var cu = Math.cos( u );
var cv = Math.cos( v );
var su = Math.sin( u );
var quOverP = in_q / in_p * u;
var cs = Math.cos( quOverP );
var tx = radius * ( 2 + cs ) * 0.5 * cu;
var ty = radius * ( 2 + cs ) * su * 0.5;
var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
return new THREE.Vector3( tx, ty, tz );
}
};
THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
|
'use strict';
module.exports = {
TXHEX: [
[ // From Mainnet Block 100014
// From: http://btc.blockr.io/api/v1/tx/raw/652b0aa4cf4f17bdb31f7a1d308331bba91f3b3cbf8f39c9cb5e19d4015b9f01
"0100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000"
],
],
HEX: [
// Mainnet Block 100014
"01000000" + // Version
"82bb869cf3a793432a66e826e05a6fc37469f8efb7421dc88067010000000000" + // prevHash
"7f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d97287" + // MerkleRoot
"76381b4d" + // Time
"4c86041b" + // Bits
"554b8529" + // Nonce
"07000000" + // Transaction Count
"04" + // Hash Count
"3612262624047ee87660be1a707519a443b1c1ce3d248cbfc6c15870f6c5daa2" + // Hash1
"019f5b01d4195ecbc9398fbf3c3b1fa9bb3183301d7a1fb3bd174fcfa40a2b65" + // Hash2
"41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068" + // Hash3
"20d2a7bc994987302e5b1ac80fc425fe25f8b63169ea78e68fbaaefa59379bbf" + // Hash4
"01" + // Num Flag Bytes
"1d" // Flags
],
JSON: [
{ // Mainnet Block 100014
header: {
version: 1,
prevHash: "0000000000016780c81d42b7eff86974c36f5ae026e8662a4393a7f39c86bb82",
merkleRoot: "8772d9d0fdf8c1303c7b1167e3c73b095fd970e33c799c6563d98b2e96c5167f",
time: 1293629558,
bits: 453281356,
nonce: 151839121
},
numTransactions: 7,
hashes: [
"3612262624047ee87660be1a707519a443b1c1ce3d248cbfc6c15870f6c5daa2",
"019f5b01d4195ecbc9398fbf3c3b1fa9bb3183301d7a1fb3bd174fcfa40a2b65",
"41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068",
"20d2a7bc994987302e5b1ac80fc425fe25f8b63169ea78e68fbaaefa59379bbf"
],
flags: [ 29 ]
},
{ // Mainnet Block 12363
header: {
version: 1,
prevHash: "00000000acc3e6a055e05edc7cd0cfac6187cd73adc3c06d408d05c95edaaef8",
merkleRoot: "67313e7a73b62faffe9380578a1a96727c1f0af62e61eb8aa050064007a008d0",
time: 1240800408,
nonce: 2506812214,
bits: 486604799,
},
numTransactions: 1,
hashes: [
"d008a007400650a08aeb612ef60a1f7c72961a8a578093feaf2fb6737a3e3167"
],
flags: [ 0 ]
},
{ // Mainnet Block 280472
flags : [
255, 85, 218, 225, 90, 173, 229, 43, 183, 195, 213, 229, 43, 108, 43,
219, 226, 215, 217, 226, 61, 92, 253, 92, 237, 134, 215, 170, 174, 182,
170, 237, 220, 251, 106, 235, 109, 109, 253, 219, 58, 159, 182, 221,
190, 189, 181, 126, 251, 223, 223, 254, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 15
],
numTransactions : 1159,
hashes : [
"ad6c32eef89f29f29d43d14500dcb0ac35cba42626244a4dbded64e27d3cdbe4",
"31878bc4a8004d4d2457f7c93571a927de9f22fcacca0356f96fbed5500e1a93",
"252931be626437e48a264aac1f7d178e1ffe8e1c94812e4970f7ab19dfadf074",
"53bd172839306e615ee24552b3ff3c8e2ce2e5a9a6d0c9d1160f1c4bcd73cfde",
"21f3e6be36f0c770938b63505ee2a6065cf9ba5b3ba0d9e115ef9081fb386554",
"7b5bff18588f2f82c130ef92351b289d4a2e6a79dfd2c969ab626fe41d5f3341",
"4672cdcffcd1f3eb4ece0e6558d3d6cef9f42a142df6d46fa6daa4efe5e25a4c",
"f2ba2db60d57f29734fcf98099391a1404c5c1399eb87a6c00f8df9974d1e85d",
"25f5dea2941e8ff493ac7810a4e11cc2846720633469479e8ae29eecee0b2cd2",
"08c71bc1ea3583602db17a5681189f346472447df48bb0254eca8bcdc0e7f2fe",
"42ccdd6e22c0f9da824c6d036f02fe0e5d33368bfa701567bab3fb49acbd9d12",
"971b294ae8678ccc2b1e16c22eb44ded5ef1738dc85d509998982c8d6d742ac5",
"0332bacb6ca645b25682cda96b72c990729e2cf58b0845dc1364cf9785cd09de",
"26ea9fe5be9baddfa879b2e756d71f446779efceef157de30bf799bb632996d0",
"7abcc87284e324bb22d9f2f3365a1745dc9af5e525b659ed60f62d948883f4f5",
"cbcd1f8f2b6dab1253e74d15d1f04c95955e485e5fe462064291d88f84180578",
"fb703bcbdb66148eedb309291609b4e881e94bb9ec8dde1372fa11756ca2e7c5",
"8bd19b733b82e2d02801a55bfd59e262066704c5b09799391224c70862fabfa6",
"ceaeaa83b77263ca910511d385392613695c4882c7fb018c9d37a246b56132e8",
"8c1003d7a5086e57dbd29667668140c1624cc96e96ca97c60f5deb94f15e9a57",
"85945287f9867b8402a287571ea9849fdd5b381873bfc0a6ddd823ef6058f6a5",
"b8d9bb4aea6db726f91cc37040723de9b69048dc725cd0316f7ec7dc10c6d276",
"be9338992c7d0ec10a6364ab8afcde1cf42d45360cc1707208b8d29315742b84",
"7d8b1015509a837ca028c3ec40cddb8e59a96c036e30d18ce84922b8f34e0d1f",
"e9e502636caaa0aa6b978571e3facd5f7a25d25df889583c54e959331051810d",
"489a38d2430ebd638f945bbbc3117345dd2bda666be09bcf454b09272fcc6754",
"b0fe9b242568bbfdbd90932db48dfc42beb4ebdba110b4d7e98b198dfdca4a20",
"0518e5cec967cfdd27d3b3791202bc2e0520cce858f632da776caba97828cdc8",
"97f60954c04de156ceec938437b0eacacf9105bfbb9ea604852eb6454cbbb24d",
"946e2b6387d87d49c151ac2969877410a8f1d65fecc5a99071ec751a6fd7fe6f",
"34d717eb07d2845d9dc1aa0cd620e3ea8d7bd2f25daacc8a058eb9c6a393a896",
"5993d871822b19dfdaa04b7911a790327297132d063f0ce2112323a938904e1c",
"b46666bf125488c07d62af75af71661edc7ef83f17df71bde09c3ceaa574521f",
"6bb9ebc3d94a4d3d528afec8d79f13c5179248cc474d13a3d6f9d279afce0fd8",
"52da5e469bacd7282e515a65a6ca6599bcc8b5e56f7293121b8db41c22483133",
"d2d511a18e5e1a7c2fe485fcd6b3263cec624b1a4e182c8987404adf6434b652",
"9b2fe6183ee437f4c7ce0e368df73256d684b71f48f8f308f62b856604360581",
"30e3e6b952ccd05c32a6c5efefe908fab145a9d7676366c699bd521edd57424c",
"b60c41d49f1c8bb492449c76f63b64a42130579083d5dbfea8377a4a968aa5f1",
"731889fdb1d00f8bd5035071552ee432a0752822d6aca4c35d8f7f14d98b415c",
"b8b7fe24a3b116caab6bc686fb4dd9013027aa349e6e14cdd229c01e9a785444",
"26a8870eaa040d6e0489ee5028d1474d3a895e049f336c7e9ba531e24400393b",
"2a65c6d121dbc11d1c9e58ceedbeee70ff7f6f4c8cfaf5515b9e41c335ea9f03",
"c3724ee9b9c2897fda1c56ce9135ce95eacbb7f9e45a46882e082f2b50b7c19a",
"3168e28ac53cafe312eb0e8bdf454ec77e34390787eab7d78bfd8dfe33640804",
"b461a62a62d6ca50a10b32f09dda4a8f7c18073a86a048634f4331c8c54b4545",
"e9902fd47c94ee0eb0bc3e11836820e1763df3dd5dd0e5da978cbedffa04fbe4",
"01a1d6550ae60519fc796320703a6c3c72e133049845ee6cab9e3850ae6a4274",
"aac3276405f3cadc64a23a1007d85a203135ecb0a656cca11ba7f68ec1d7d8ba",
"cf0a4c57afb757c2a0cbb2d1fd39a10600063bf74695f13a4440fb6e5ade526b",
"feae17a192599d2647adf0218b39ef0e660742349d2395a0b106f6eb2d664796",
"503fc34490ad5de912e86bdb62ccd678d0b9d401cef010d48c935d455364744e",
"fd605fd1f8a121442d09748d3276dd5739a193256c318bce07f29b73e5e2797f",
"270ffccd7a0a1959e1a07d0c2d04cb5b0b1aeaea5abe5b56234c0295718c4269",
"7e7c89a24303966a0b3ec1afa006dec7abc0e46539beb74268534d5721590605",
"2f088d956302164764e6cdcacbcd3ff6545f150fcb2866107c4b4a22dff4444b",
"aa18717fbb5575f3c25195cd59e74c6f096e5622402294900eab58c86ef1f3f9",
"b125a208eb149e923cc70d29248d13549f46f9c353ae99b8818c54f1160efe81",
"d751efaacc03f71d0a306b08b11782d1a002e4211b6905c4524455fd9362bf5f",
"5d67344da8d35bcb0c099e90e9aec2a708a68b6ad9f6b7939cfe1d2eb872a14d",
"ff13ea7bc835d1046c39f50de61e229b154f5b9354e21afdb8202032928c03f9",
"568c957db832e8daa663afb3ebe50f9bc07a546c142a3b8dd8e3ae23c4f3e61b",
"c681f6304af1d4d636ffcc9a511534629f1116dc2209ca33f47aaf0a6a7a38ce",
"822063a0f81c69a738c4596d125847d8d174d33c73d89e5bb10d10e4c8657579",
"bdf5b3f862edd508694af8d64d8eb6dc980de6987f9a5f4012379de6827f4516",
"531177870b5efef4a0985dd48afa13fea0b8e6be87c658d147c2d84e48826e59",
"e523b181cb1aa4d3fcb1f424b609de93bd0a6388cf17a24dcfb76fccc60ecd0c",
"a11e5210eceef1a5dca92d15f08f106061799de1880a84ddd739ad7c162b7023",
"ed61b91c7439b7364820abaffb094bedeb859de42100ceb7a72b098a050fadb6",
"f089c202de5553fc4246fa0d6be72cf54506d7608a153e55806ca1dddfc42764",
"28c3e63756f72b27ae32d07b280bcf1edc13df039361617cb0f29eb17e8559ed",
"a9a1b2b3157d78e642e4b8f534bd1a97a9039ecde41baa1ab0953d7ca527b7d1",
"eece909a9ffaf785c96a29fd2f027048e767d03ca30acfa9813dd99ee3882608",
"fb56466712c8584cb48a5936da28c71773212b9fd2af4c378ccdd498aeefc789",
"4adaa4526cc5f25fd2be1874103da8ce75506d9c05cfadfef3aa684dc9ebc5bc",
"5db5c19d1836da8d44dfcf6a32a9884a39d9b24c1745b7ad07ee90edd165e7ba",
"a85d0a2d898ef48ca6ab120a86c6f58b11091b7f7c4f6faa931d0594db4ea695",
"3514809d3cd2cfc96f5c79e9d08533a7a7238d7ea29d07b6a66be8cdbb3b159c",
"3987a7cff18d70cfa10342c4bc714cd540d5eadcf553af4a93a431209ae0f4f2",
"288bc3cb0fdec441494ca970901cb84e807f522743eb9e53fb7a6b171b1f00df",
"356de5250f43bb8a97a079912fb6be18df2f50e928bff2c37121c01ebcf88c9d",
"dbd2daea97a3a335afc5a2c7207ca176cf01ba40caff06a823e646736d71f2a5",
"6be37d83809273e581a2b373a1778471e33599b695fdf3b7791f65030ef1b38a",
"c7c339fd0998e022c606b02b421031d25a319682b3fd7ff41a48d630b1b8bc9c",
"eeee90adecccafff27ec24f264399190afef7e4b78e6f2f92f0c2c7c47aabe3e",
"79cf1aed207b3603b197630c9d282a8b36de4a92ddb96c1d3ca61efa1c4b7021",
"5553b7a0fcb823ec9e5252c194fe5d8df716cef98bada8a50819f89989a00931",
"a7c060926f5b3219a7b7e131ab6547bd64809cf75b24053952a87e324addc8ac",
"e7649498c748a4cd00221ae6f729e16e29e4fd27d9c28d5ed95bcc6f00377872",
"998a4ead843602e37a210823c221b9755a7a21a7d5283e5db54bac51df16c3ac",
"3fbce6ff59cbb982e3df5ce2917274ca87828f811083eab4b41534d34472dec7",
"b9b417bd9a55634ca616edc371c9e8c09cb0611626b84ce3acfeeb32a1f2627f",
"c303c7dc74f66c512cc2d165ef89d57cee257359b3ee0e00edb3737348f88068",
"07aa9856735c0110c2f8190d3be1aab49f6c6edf4bf231c94428b5ca7509b91d",
"cd59eb7e808f543925e6ab47f794f0bcfc9d91fcb7758b7fa1df3abfbc3c3e9b",
"c549035e1d22855eb6c2bf371b2ac5846e0bef1d0f4700a5192ddc88de27a97a",
"0ac1249b989f412d714daf732137498f9b4bed4d790aae420e9b9b5b6022d6fc",
"83f5604c6f2c8fe5bfbd274f51ba754610b565fa93dd558771787728d1e17d19",
"b106d7fdeab23c1886978f7de80ef1ee2395177cbf26fa5940173369fa42b2dc",
"44a95badbd41ec197043f6907b32d759d935c3fe68af3d5080672cfcfad11d98",
"79843495d689579abe43332a2d0c265abe42dbe8fa94f822d2e6702af0e0a0a9",
"80ea7ea2beefedf6abf2c085a9c2f89ff9ae0da7f42bc1d1478ff641d449181a",
"67657bb03abea359ffc6166e12589162ecb30a5c37a0886e14b20d481652bdae",
"e2095adc5a1dfbf89b28dea1b3cf2d726984fa5343943513dba7b66c347321d6",
"24fa9fa1f60cda5b002b453c79600c458bc513f4f7ea31f2ee40af9a5b0c5533",
"3eeecf1563fc3cee96fc92dac5eba03fc95a7de585f402ef1c6125988393f8d4",
"e64d7d4bf18f87ac4c638b821bab5615fcfca45cfa2470d3e12693b5413618d8",
"2828ce70f254c1f8e18d92c4f28206fd9f2b42f3be1d67405df64d96324939b9",
"f2b24eed42be177653d2f95ec1885d78f3ef1ce32a0088bc4fa2671976156e4c",
"0946f3d99392b7161cd29c0e84acbabbcd7f5f9d58d3288b21151f8170239cf1",
"31290c1047285ab1a97728ad4e51896f890c18452a4fef561023b1aa58d8d197",
"82e79c4ef466cad39b3e08d4b3d05cfba17ea58a5ad4c2d2e0539114bcba88f1",
"8c35a97de4a9831eb2415be5a9883e3477cdf1cd19ed6a24984fa1b45d7e9f90",
"99d0d7783bcb87cd7e976fa6fdc28fd58dd688b087142d9767e432c1f298a261",
"5218233bba9cbc0527e131a3d9d5ea290821ddf58eb8c9b52918f5654804a0a5",
"f4fe4e1a4c22ad8d9725c8cf04b0b509a0ada3458da3ff3c12cbaa389cf8638f",
"ce133d2fa135f4f102b368cfd5ce02078dec518c9b170f4dbcc3ae823b16680f",
"8276e57b19b15fa200e0bf2cc3f221793a14e41b5a8eb3d5155be747747565f1",
"e08977c0b9b3b6d1c9f0dd33e075e9565b1ea67fdfb968a297d643ea56ede5a4",
"34df12dc797251aedb4196d1ed2a67e5febee79f89b35c503ceefabbfba43544",
"336454288c2a05f22211a3e7522624ba70fc3ad381ad43aa227185077be4806c",
"51975d2024c1eeae7d2b44a12a1af2891d234dcee2d0ff500ae03d341b57880b",
"02bba57b27d557180e9edf91a09950cd2340e8fb44a5cb787c5d0f3011a542f3",
"908420fed38c9785eebccf1204e07e3f9d4434ab299342ba489daec0cbf686d7",
"d187e9b16d142e22522ec7098c3412b61fecdf98f1cca554ab4c1a1d2ab489e1",
"7249f156f19b30541f6c816b5387a26cb803a63b41930f08ba3f0107e31208f6",
"497faeb327567a9af6056ec1a7fdbc8154dff2ebb9896df855a5090eaba2a03d",
"eb51ce48cf06179e1ad3135f8e3c8e6c21d3b856690b8a34f063bd348bcc77f7",
"17e156c54f3efa435e8a2fe19b9b6700dee338090a97599f23810aaf0db00d2a",
"f230f52bb22cc4af6373065cb15fc91ca1f6c74eaac3ccc6c1b88553aed581b2",
"bf2c9b5a78e3b1ef95c0fcb8efd85d6f3a3cb594f03b7917ac192023d0c7da30",
"ed438001c7fbd49ea89d1b6116e8ce8da19810631cb045d7093d2ef43ba8a486",
"f99e2575f6d7532e0dd296d126768942e5820a99428023959cd1505e239224fe",
"7147f6dd56c363a1f32cfe475c0a612b65d359154b93866fe516880537990f4e",
"0af258f3304e644b31abfd08b6fcc21159a7729712ed8d2e0856d368f54a4269",
"77608ddabf1f39cec2b3f9cb4cc4d36fd1b04f00a5765c779ee342e4d3c6e5ae",
"e74c05c43ecfb8e7182a334823ee134da43e2e1ab4f92e9c6f3e5e813f30e6d3",
"2b952ea819ab78b34136e4d3d698ca41a58d00e558675cffed4206a93a5f5ef9",
"8e82ae850e62ed480e4a55512dedbd065fb553a419214c87790420d8d2e1b3c8",
"8c560c3b6047002cef9654937b2c8e98fbf741b36e423bce5ff1ede18c7b43d2",
"99a9daa989002fed2ad6819b3c95fe0b04fd9ae0164eafe6f84c7dde3dac66d5",
"a599224017b1f90d4d94180a2cb782f95ca75b65b946522b52c035b13a5d518a",
"692186550a90b67eb0d057f95ca2e194c32222737a44e7ff64b840f7ef2f9ec6",
"3a1532b43af74c7ff2deceee0aea597d63b058fa9af5f491206886060adbbdd9",
"3b744e52f07254f53b70e85389e484c570eb476bea247e1e706ca3b357ccb113",
"7f9d11ef6cb1d0d78aa151aa4c0c6faf8a0cd7543751a4c6da40d9d6dd0e9e89",
"fd82c6589a3df264abce32d31578d46551d1c067c6b9316e47c041c303fa24ec",
"94943dd079fb25b56c6d28c00d3d87ba207ff957ea3328c05e53f95eeac4f16c",
"7519a0ea3b65c23d88d30f5cd84a552259e99ae2322a3cfba3314e9987583bb1",
"be599f62b04f2f77d5c844590b7ca1efd8677fc483f4455e7de901d315d56b5b",
"3bc6500d77b4b5e2882e810610ceac4280e87e6171baf242c890b157b1c3020d",
"3251411ad79102964f144282c1a71fa4e953f6afc8897c9622e14746e9c1a476",
"a79e5d72f0ae70cf43d6988742fe75abd45356ae8d42f2c93c933b0608b9ae70",
"c0eb798ad1cccd38bc8bcca1b1d9a03c394f11e513ac77afc16759ad688b847c",
"9dd585798374b2fd53f2ce173399cdd80c482cb432ac78d7b000aaa6e941ef42",
"7de291dacd196f97b4a031cd553082061cf16cb9b4c8544cfbb16cae7bdfb5d9",
"a923a968585828bf9e2d8874e7eb2165968cb4fcd309e383482e5f6c74bdb45c",
"f856c43a55434ed1727ffac57906f44d6ce73c0896a8f28b961dc0a75fa9b394",
"9e00caae373307a3070eafa659bcd614333dc56a834e81e042523f0419decc67",
"b7c1be14d0824b183ec39184a5b7eda29383796b3dea8d38daccfdfc6ae311c6",
"99640304779e8b265f8d8ae495d5bcd4f82927b623cc57cbb347a5c5c27b682d",
"43a8149510152a2967f5d2b16064312d4cb488d1b6866d5258e877b22e2a1f40",
"c0d28c084fc8188e512995263431561e8c1eb4b7842f1ea11a3cb8485151195e",
"3eba131992984494ba739e8dbecfda6c2fdbec127b094dd43d583a7fbaf6378c",
"8932c9acdec6135447870fd3c0ce74f1345f72dbc38942a42bf418045964b34c",
"e35943cb6de6851111b62d722456f589c2619531adf8268e5332da1afe544282",
"4a310270a3ceb81cc8af14e6d6c9e617d66d361e7d8960558f5cae2a061331b4",
"0d4306cf7404111bf247576a15fe0a66cef0417c47d1fd9e576c09650961c2f2",
"1e846b2677d149da1c012b055fe001c279535acdb83dfba6253b21b625d559ec",
"6dd565d87f2a6fd6c4944f38e9a240696454df79f5ea58e9887676fd74cea688",
"f07f97b58b5d4224b0c11e8ee2f3f9314209958c5da578e7db949b0f6542738e",
"14f5c29aae9fc1d709962dea0fee3070e0ac8eaede64d940d2f43a584a23cf5a",
"00268073af8e1f2f82d742be9d13076ca08173f6bcec3d89c96de3d7823a2f03",
"ef583223b4d2bd42387968c349d928a6f329f6f79912261730b52f90f7960bcc",
"23aea669fd0edf1439db8c121847775336b40340d5743d7ce73e3be8fe184a26",
"fbabfb448b25bfb43fb9df1091127e6c15ea3b6662eb714eaf0a167aa67415a8",
"0ebfc4c6fe4ea2b7700ae9132509253166bb215b8800e86a7633295b140c8ac7",
"778dae382d063c92dda40744b1af2063d0ab77ef46bbeebd5ab57686bb87c959",
"982800d89a84ecfc5a01b8d9a96b69448433a920d4713313f59726174f36a8d7",
"9e9dbdfb7f6198dd07e75ed2665130a941baf1b73601f777cafdfbfa59ee176c",
"e3090a666d5af8611fd8ddc7dd9f0290a5e0d0e40f440c1ed6713d41645465e5",
"b5a78ab61b943ebcdb1dc4e0533b68e0310c9bb37ed23f1c4773409c392f214a",
"bb73f7729212748081ac45731c15630ecd89652ad3b2a563de5aa6795ac0494f",
"a12a2ce969ee1d6261eb7be74cbeafdafcc867767e76b3f9433272681cae3939",
"9e9852c0087dcd88f1fac2383e884894611ec3fd19760316da106ab7b4594f17",
"6182ece2e1b252d838e81d52b2000aab1eef0c8b3efc51df77167929dc495a57",
"ae59c591c044e6f24c54662ae1b64b1e75e20510d2229f6b68bbd4547cf13326",
"4ebb82be6043b5122a86cb6b51434fc23082d2197b5eaff824b52e0295e54d80",
"33f559a179624c63ffe1b3739a5fd5825e117a1fd59003a168f9f892d1de3aa0",
"aac18754690516f5ce0e6c8a8974b0f9db560c6abcd943a09bcf3f3818e4a1ba",
"f73ecb180fe4f4107c6c8f4f3f81bdffa3909db577450ad8a10b7e61029b3e11",
"0fd732521ede730dc8bfb58ec1313f370a5887ec67f395dc048e132681a4cb07",
"bdcc038ebf3c3176dcbbd8b6b7bd8c7737ae279caba99e81f569dbeb29857a42",
"46e287c04d6662f4612f8ba3f88e9a129088b21ad83e8847401f9edfe4ab18ba",
"8d70e5307862c2c60c221a3acd586c9169ae54dbe1f2a108328cf84946007fab",
"8e0de399cb79028aceaa634392b64705cf97864e37f8e488effb2fc6f4a46531",
"57c5e60a4f2b3e82d95f9e78bf70d6a3c27d98873a10aa9eab7e2f279af22a38",
"b5f1729e763fb6f4dbf168fe0d20d03e1c39a9378a045891f0764bb800d6d32c",
"6dddabd46c2167fd89f0bb942a4e1405828b400bb3763a542013dadb3f7307ef",
"54fe8d2f742a0b59a33281aa38a2f1803acf36d538702d693f14099654c94551",
"30a2b9320396248bc3ca27e6976a06336f6ed55be72a2fec222ca8925b36ddee",
"2c13bb82bd5236bd32b087a3bfe291fc4829d0f09f2e701113859abd3ea1cc8c",
"67d852403b6ee6b8146c6a52c33d5585a0377fbb240e841fd30f3fe73f5bd165",
"4a863fa1f3602e380ced5b710b0c77c9f69fc7eda0f137c3b48732758c2e1386",
"30e84049ab91ea6716204a27139fcbc57fceea8ecab28e04bbf690e24f558bbd",
"9aa2e2dd7a770399718421f20fe27b2dc9923e9f6b57d1fa5add3617d24bfeab",
"1e31d7c86bf694f8856cb1c869c665baa452d445c9305bf4a709c37fd2665e82",
"61af97100797147e99daee9fd3b867847970b8fd7d95ef1d3bdfc1c7fa8bc949",
"ac049081dcde776e22911e892e05d1069b7795b7bd332cd88f208fbb72960886",
"8683457c0e857617c0ec755f448d306a2fdc1144de8698f1e33c1dda9d8bb964",
"3dff8d5494fa343f49be420f8d4876446a114ddd3475959c6ac26c51b9b01906",
"c41e7a4e855d7df1ea78e713dc1aa6218de3077a42db5662d80db125011d8620",
"baf74f03d301c85890748a90b06addc4bf4d5d008ec0fde0ae07b9bb8f9dd4a1",
"4185ae388931e194b63dc8ef22e51d4f449b759156a1453a387b6dd40447c00c",
"982021842949f144b1317d0b4961a0f2b40e181fa225a4ad87649f4144d2c880",
"b56c39853ee20c6223032e08507e8eb8cb690441e863bb69f6768afd660052b1",
"1a0f05b6165cfa23f19627024f0b37ca549edc203505b41dde07a9b88bbd7535",
"430cfc29ce4b35ad3b8835b12c688d60bd2bc7df1200074b3c539b7da5eb585e",
"774371f57e9ae885e19294de121a520c3001229e106fc596f2940e3ea1ff0ef3",
"47bc2e2bb4a810348ef348e26ac813d6d5a54baa3433f2abd1612b717d3da015",
"4b72a447be4322ba818576dab8a3ba31a9cefc20421770388fd4829ee934f028",
"6fc3d154fe6e2c509113a13f9e969f20499972b826cd15ac33dc1eb6baf7bfd2",
"2d48e4d127a962377c01058c26c61cd87b5345b6f2818463b5e41c711000caf2",
"a2282c6f0cb806627a207ee1d912c66333f9bc33e92127a278c720a4b0a0ad9e",
"9bce3752dc7a13fad93acc8ac931e764ce6c6909ad22bb087ef0b66beb0bb732",
"705436abdbcaa17582fabd4a86d4d2c2dbab89a07b2ec813b2d71a3e21ecfd27",
"3dbfd8fc113f4ac6524f55266cfa9970118bba6c468c15f4e1afde5041fb2fe4",
"7a6558e365bb9b1532cea9883c5560be5d1df01c4ee21f39ef26e85347a07c76",
"cd7bd7b7115b9973f0560584422296992dd5dee7016d5c3e49c88d9635ee4547",
"a48c74a64066aa0013d5cb76ba25ca73bb4f9ad2017214d566cccd71d2ad8f49",
"5a703dd802e7b0cd8660dcd1cdb4cbeca7ddce66ee89648538f1cec7f0e4ae16",
"c2dab8adf040a2fbcbad196d50b2357fb35432f9a4fe09377adc0ef71e0b9f7d",
"02dc0a4d4b25d732c7455547a555067181924632f99b5693397dc636b28423bf",
"6cfc763f0b00b2d469529582b38b6b9608e9406f0b6fb2e2aa2de4197eb16c5a",
"8828a15c1d52c1e3967fd652db870c8cc1a6aad787418c307f415611da3fcf0e",
"7f53dc6e2fdc3a61e5e296e75c2697da21f8f92bc346388f6a17c25ef7686ed6",
"becbaba75af9ace5c4899513cdbb1eca3b016c4c2968154eb0ec3bc5facf6e71",
"3f7859a6b06d096d20bc644889a226eaa5d747d860b9fa0d0cded49bdcbf8fe0",
"cd9250c8c2eb6c28ca2aaabf41d91b18f75edad3e9df82aad70272702fe2feae",
"d56bfb137e6d4150095d242cd0e63fc6cde099a3e670ce9a5d8f2e6ffba77a07",
"b3bd7ec83a8057aa609bb485c4e247e67e4cb923d4764765862db65b6af15307",
"1942bdf5f85eef33c1c64ad92469bf78bf7fac628a22feaf193d86adc62e8b93",
"cd313479b8467c29655be09d63d4c1208fbbd6607a19c9a13f6bf094d28812a4",
"0d31559805703d361e04e48283e62ed21dacebf8104fa7ccbcb5e59d468f70e1",
"ac1e224a387d2d9a6d6ef7c19451af3efa599753b9fe44b4e737b6d2e37fb551",
"9116da1e18ba243f3ed29a76197fa8e2d957d6f11169cc1275709e6cdc4a8756",
"b1ef2f49b0b26ec4ce558f5dec98416cf8bcabb9a8702784f3cdf00a5d676587",
"797aaaa86ab5d64bcc4e34d92eff8f63551e579b8fd66b7f01b662d218740e5f",
"c4e31b52cc3bc49bcaf2c632b9597c8e4f5f066b2bc8692ded5663c756b48387",
"2e4b5491eb23250e5e855acb6417b59da3da9ccdc1217e34cd04ca40030eb464",
"900c4d49c267c2d251768442f29fbc1c2aaef0cdf8f8855a9b68be9d7367f046",
"5f940e3736a9ca25f61c16230165594983a5bb1426789aafa2e24f7b7a127f3c",
"a372e58ff796ed4bc28a27aa04393b17060f97b9fea62272446ef389d534e727",
"799eeb62f4e6d0b192a6b8811913b6781043093853f4ad3dfd80ad40dc13cdf6",
"c5da9d51154df4a5904bb2b582bdbd1111cf720e6f03ef5f97f95423df58e147",
"92b302bc860da5db46234ee558fb1aff62ca70bc2b18f142eb5200131e14bc8a",
"aebf6338cb63544de46b9f45311918232722ca625bee66278ecd2f180b0be5ae",
"9a907c10d6033bc91fb1847766307267b8d029379b9859d9c80c209a7cf082a0",
"de28f5c0d46ad54b57c465d8a9e416b849bfd41472ee7d250a360e4d439b3251",
"f651d87f4cbd99f72a7459cf77d8425031627de145041a1689955adcacc88b60",
"4f8641f49563c14b43285257c71df4c60621a5320b8a0bb575bcdb85c1bc131b",
"0810ddc592b81998e465024698f3898c104ed8d13e9f675497c824a81111a28f",
"49050203987cc982c7ebb2620de5fde348a751e00c05ed358fc6b91ce0067baf",
"37694a5c185d87fab218d8b37c39c094fbe00098e3da83d1986a8e12123b8f72",
"9e6aa46a83ce984bf5fcf16fcc535335e3757c8f06774fa467b1c024140c30af",
"0b259dcf3bbd58a9a1369259cef787ea352a1c0ede4fbef2b7d1c785e9f44a02",
"74dfb52467dc994e6007d2e57900630f2d0e8e4ecc57c9097bf0c0cbd908575f",
"94d44a100ca284444dfb0106efcaf04107908975f2b301aa9bb3dd0b437380c6",
"47b11267b2c7be15ee78e744f2dd90ffd5e7a3c21bd3cf8a52df0e553ccdf9a8",
"8f15cdf786ed0c6df1489e8cd28031d1a3fae8f006ac30602ca9a0ec5725d410",
"110a9949642519b08293304865bf19a95f9590db6db8c0d677491715d7decefd",
"918e80b22117f5e587840cd3f6da607312a8792c4e8194f1a191bcd2f550b16b",
"85f9ac70add31496aa4b4bcc4443bc8c15d377e90af375fffc001b4380a2309c",
"5e57b6a99301201ea691dbfacfd7105c940c0374eabd14150ef09875cf5e5468",
"712093cbd1ad05d632da00dad2306d7aa09e48fe651021ecaf13c1e0122d3609",
"93758b69bbc55048f3f64ab02ba05b748a2301ba8fdabda5ad31c5132f3b17f7",
"6fa9a1fd4ec39f4691555ba3064cac5afaa9ee90604bc9c24b6b4c452b5dbd66",
"d062b6b04643123071223138c91a28e50e89ffd48f676c187a647c9ca2637c07",
"53e011f498d01672e4f15ac8c41e44f7aac84c7eb55f37e6d98e50e072133236",
"a29db89a18a11505801ca8146b38e596cda6a53ceb57e6bf05014f62b03a708b",
"0673a9faf5ab50c4c0d16d3d1c9493fd1c6972790f9da84c24b4316bac674d7d",
"fddae5c3c65653c5058ed34da5645b3889bf54bba81c7ab5acbe4d534eb7297a",
"3a87acd3df6a48b023f261a8b316e6b51ccab88bbc5f05ea2aa686e53eb75926",
"a640148dcb71dd66cae73f98727b204e6f8f7ac43132858c81313aa8e2162700",
"d06710316f1ae7ce8234e6ab9800c5a2eb9a62d758090eea1744e7bc7b0d5a07",
"4002aba5e583c3ca558def1aebcc2d01967cc32703fd28f27b79c35275c17e82",
"e33205319a12141ce884fa1802fb5d14806fa02993b6cab412563104ba2875f6",
"984036f284a988ba0b19eec68e485b8f86a592725c9bfa3d2c887f076d4dc669",
"5a6df37a1c8b1056d84940dd1c6352d93483dbfc0960d33ee23a58ccc9f50ed1",
"92b59222427a0caf431ada26da149218d7ed2fea050b11df2cb0a118dda11087",
"5ddf4869c2578c1ccfa3a17c4f728ac6cd9d8bb5b19def13335a8fffb3947e2a",
"3cffff6af9917186588a5291bd997f900ebbd997205a8597ed86b32c313d15f9",
"26212b92d9e7073dbfaf31e501d603f2a4a0a72e6d51eeba003f6c4769e199b9",
"8b9a2208d6e17986f28ce6df7e3f1d2e15cf25225b7852dadbf6771ee21a391d",
"b9ba75b8bc86ae75dff2b9cba3521f9158596bfc4471813688f5a2a471a94a7e",
"51431dbfbde822ef6ccde33a7d7988f34e5042a1ba0cca9b9ba6eb86e797b67e",
"19b8b5c3dc7427d3b4fbe20fc117fe2ffa0ea2101f60701cda8fe4de0b0af495",
"3ed134a30673821c38cced4cc3affec64de7ac890ef88c0f98fb72e59ebe7cdc",
"27bfdd5fd4cab4cccfdf4a2af342958f40d1f82f792896b461b35fc968b3dfd6",
"d4395b2c014b8d988cbe25ad50d02ab03a8fa47875d3ea28a4e37bdf48965530",
"0092d15bfd929deaa455dfe5be976707cbcc761eea63ce216b2457e0d70ad1ad",
"5b6934565705b73e362e79108a153375a6b43fb706b2480ceb0bd75673e8817f",
"122618aa4adf9ec938c48da1c586e059d2847d3d249df5fe613921d6cf4d1117",
"34106ad21d6c03450bd922cb2cd82f8087f4e0e78cc33b678552f96da0ccab6a",
"a46b6cb6e14305fcd0bc642e0930bdaef7c04b6bf3014e138b153ef24a9b3213",
"f71d42a86c0f3a9edd76158f1a1d0ae4a7f34ad836e5521ffd287cc00bfa430f",
"08541a74d5a6d7bcdcdfb04f932b35592ae31e860dea533ae75388ee4973e7d5",
"fe396de692968efa4617b7401edfaf4f75ba296e3321017adf3ccc9ac811b9a2",
"ad94d80fd601ba309e56b6195099794360f8091c8e77db843c113141aaaa9592",
"708744f24ca16598075fbf661c64ec10e735bd3154193fd3a8064d415ed2be20",
"cd7f5f414e2bbe5e05092d727505a2baea0058c9ed4d98f1bc69f60224d7683f",
"fa1045fcedf7041863cf6a2f3ff8dead976c01f3968e9fc0ab94dc14cc392377",
"3d88497ed93e4989b734e47a0a1e285901577ca3f0ab5c54d322dca6818f8dfc",
"ae739e369f8a632b8ef1cf4d98effc0a9154b091f23797f4f8624f34551752dc",
"d40cc8fb2938db8a0351c79d41fae7d3c7d8668a0c32ed4cd956c4cdc770b93f",
"b93950b8f2eccb0a713d3e96e4c9218d1993b9af8a7e8621dbebce519e6b6ad6",
"4f54da34c556e2a0e36d2fd0afed57b391998ccf54517bf6701c64167d3ab6b8",
"97beb30f09514b58013365ef00196667c79a82cf188f8f2417b2d06bbb610b0e",
"e37a52762caddcca8b095f782bbeff5fa20e04b123fd0f9658753b7e2a9943e6",
"9f171cc54a54340c757c468cf608af52a5e56e6a7da6813675520d32fa0272b6",
"777b198faf560d71bf276e7e98acf63d2ee0556b7ab8edf7c8547fb2c4d66e50",
"73cfc9e8632891d77c12e184f27478c19c3c49e78b92caf0bb07596277fca003",
"086ce6966f0ee6f8baaf00d5e3ef95314cca0a717f6596d4462b770d381d1427",
"4a43d62b2764e121390416a339232e6281dfc51b5b4a33c08fcf55f114e0f17e",
"d665b4bfe9fdbd04fc1bccefa1c56cd7634664277a1117e936e78ca5595462b6",
"6c7c0f93dab33466e3ba8b88a7e040081c1ca6d0804c715c2fcc225774bc8e89",
"41c740f4009bae19d4903f2b8a0ac687a9d13079c86ff3d9d532ed5f57f58987",
"535a8f16b8ede6a96cfb53799f1cc99add60b3fa8fcdd90cdf75df6132f6f637",
"0da3a7ac204385a5aa5128ad7d1060e25f13914fd0ffd243de1badd36d2f8dc5",
"ccfc0881c0d34e67d405ce8fbe9b9cd6b52e901312c3018e5b86f55bbc7ecc2e",
"2ad0c7bfcfc937c40ce40587aa420081dfac80c415bbd77f000a2bff22332bd0",
"6327f17b88e3ca7a0d76b2a2b149174159636cbee049ef8fd74ee838c586e12b",
"af47446bea26a8475dc65e1b4e311277a64df12f83ff48a7ad18eecc3e3766fb",
"5d9a44a90439991093e7303a776c495d318b5012cff8217c8623b4b3d44d9cd8",
"440f7e994a260ca4293745a431276c9c87e9cfccec2e7bd8e3d1492fc56a3e8e",
"0186122f88baad1fc4294795dca301240a6ef4d34999e59387e095a2ffbda869",
"411cd7fd695dd595e671afece2bfaadd9e34477fa66858c9643276e81dd16598",
"0b3d09cd01d2bbe2a24398c812eafcfff85e15a9debbab1f7af88eaf618ba2e5",
"3ebb9d27bd068459f386ea4966709b963cd38c828ae35ca4c0085f86dc9ba941",
"6df6a782e21c1f51844b6a01d334a75cbc5557679eb0d3ed24d403da431d21b3",
"b7a5eb26ea3373ef1e5eff05f0acbe8e633cda2d22216d7a1476768437b52027",
"f090be97792dce7e57ac104229b40b10ad306e7f16faec89705997e43b4e0ec4",
"6226b38f52683080de6ea3b0d49a2be57e46d8b38df20e4eba377d89e7555b43",
"595605106e9cd66abb02eb4389a922f26f4981672a9c814074d5f85176c2ce52",
"9bed6bb275376acbd52c871423858452c76f1e098f6b4c3bb0f581c43b1b78af",
"5a5d91cc51f19b2d053f70e68ed7f7809caec0ccc135a368b88e739af7498d21",
"37d0445b8ef3357db5b68226f16270505af0ca8d926d85c66f28b4683bb9f3ca",
"99e5fb26ba2d82674a216b1de505f0d137f3bff7094d70869afe75f1d305c9ac",
"88bc0a7fca01ab1e96b2dabd211605a6212bb5d45f59d7afa3eed9f7bc8cee2d",
"10871ee43797f3ecb4848dc419147c536466edbaca83bfff9c09ef47d2152eeb",
"86fa8cf2806d39a4bcf2a94ccf104d2b54fd72baab034fdbd6fbe7e0ea0dfb37",
"ea7ca070c12582f44c4b083d94aa3fc050bcbe5ce45f4b0d8f47437d223b8d38",
"c4861ea926ca6b8d17c35052c5dd11383583ea686ba3355910364dc6e1e771a6",
"0221bbe4da98b60cd39c2d4787893d5bf1f70e303e7d7fe6fd9dde6528541ddb",
"22a2206974c27030f99f35f259c44ffa64ef11b8e6330a3fcd1a68a8f686ffcd",
"089fe5d906bbf100a911891eac4dea621bf33d0ca79e63856918c0f14598fd48",
"be38f160ef5db2bc51789e67907f5b7955dbf6226b917507eedfd61d15e1b07a",
"ae727ffcd38a5c26ee1a1af45b9ac07a2c9b21550714b15edf909a6b5622ee78",
"4f6cc96186ec9524363c36dbf2caddc3a059d5210694fcd35f3ad3bf831290dc",
"8a0ad15c6a35e1b677adb1151d9b6df49b11fd2f7921b331b5135844ce8a2e5a",
"e4a7addaf81a40e00d9fb3967188ffeffdec0d7b61778dbc12f7f342fca79e5d",
"564acc06212018c0ee33d6109bd062433161a501d0e4a3eee423dafafb21a33f",
"f6332c5c8debbe2e49a1e431b1cfed8b0790943eecc9c3708a2f52204bc997c1",
"b06cfd8e8e17b9afa585ea76f5647b4d54b64f4ad1b41780075f4982daaa68bd",
"1f596a1cee4760ab7b507b18e4f7418e6230de72b9d619cc8f6ac0df5ffa88f4",
"2738eb6f6f0a436e43f04b3fedda30cea5c3b8e36eb94fd3a73b7841ea6e3a6a",
"b84fa9e606a6fd6ee381e2831f1b80a14a1626032fdc3678b121954c5d0ce98a",
"4c4acf3cefd0b466d418d3b7f58f9b41681f803a81878e6fad8409f430e8bf04",
"6fdceb9e02428d9175acbe04590b693a5c644eb8cae672f4c4d06d145ea8ab1a",
"823486c19fd887d93dc2d1478edf5773ba381f13f0ae6f287c1038e7c81aef1c",
"036bf6944a47791471e9a2cb86615de837f3aa234a7d1cd024026b3e1daee79e"
],
header : {
prevHash : "000000000000000124f6ce137a43bb288d63cc84f9847033cb84595ead05f9de",
merkleRoot : "792f40129c95aec653d2838ef4b031bf541f11c764ca6c3ecc2e20b396ce83cb",
time : 1389715824,
version : 2,
nonce : 322045839,
bits : 419587686,
}
}
]
};
|
//See: https://github.com/pablojim/highcharts-ng
$(function () {
var myapp = angular.module('myapp', ["highcharts-ng"]);
myapp.controller('myctrl', function ($scope) {
$scope.addPoints = function () {
var seriesArray = $scope.chartConfig.series;
var rndIdx = Math.floor(Math.random() * seriesArray.length);
seriesArray[rndIdx].data = seriesArray[rndIdx].data.concat([1, 10, 20]);
};
var series = 0;
$scope.addSeries = function () {
var rnd = [];
for (var i = 0; i < 10; i++) {
rnd.push(Math.floor(Math.random() * 20) + 1);
}
$scope.chartConfig.series.push({
data: rnd,
id: 'series_' + series++
});
}
$scope.removeRandomSeries = function () {
var seriesArray = $scope.chartConfig.series
var rndIdx = Math.floor(Math.random() * seriesArray.length);
seriesArray.splice(rndIdx, 1);
}
$scope.chartConfig = {
chart: {
type: 'line'
},
series: [{
data: [10, 15, 12, 8, 7],
id: 'series1'
}],
title: {
text: 'Hello'
},
xAxis: [{
type: 'datetime'
}],
yAxis: [{ // Primary yAxis
title: {
text: 'number of notification',
}
}, { // Secondary yAxis
title: {
text: 'usage time',
},
opposite: true
}],
};
});
})
|
'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
let battle;
describe('Pledge moves', function () {
afterEach(function () {
battle.destroy();
});
it(`should work`, function () {
battle = common.createBattle({gameType: 'doubles'});
battle.setPlayer('p1', {team: [
{species: 'Ninjask', ability: 'noability', moves: ['waterpledge']},
{species: 'Incineroar', ability: 'noability', moves: ['grasspledge']},
]});
battle.setPlayer('p2', {team: [
{species: 'Garchomp', ability: 'noability', moves: ['waterpledge']},
{species: 'Mew', ability: 'noability', moves: ['firepledge']},
]});
battle.makeChoices('move 1 1, move 1 1', 'move 1 1, move 1 2');
// Incineroar should start Grass Pledge first, then faint to Water Pledge
assert(battle.p2.sideConditions['waterpledge']);
assert(battle.p2.sideConditions['grasspledge']);
assert.fainted(battle.p1.active[1]);
});
});
|
/*
* jquery.collision
* https://github.com/ducksboard/gridster.js
*
* Copyright (c) 2012 ducksboard
* Licensed under the MIT licenses.
*/
;(function($, window, document, undefined){
var defaults = {
colliders_context: document.body,
overlapping_region: 'C'
// ,on_overlap: function(collider_data){},
// on_overlap_start : function(collider_data){},
// on_overlap_stop : function(collider_data){}
};
/**
* Detects collisions between a DOM element against other DOM elements or
* Coords objects.
*
* @class Collision
* @uses Coords
* @param {HTMLElement} el The jQuery wrapped HTMLElement.
* @param {HTMLElement|Array} colliders Can be a jQuery collection
* of HTMLElements or an Array of Coords instances.
* @param {Object} [options] An Object with all options you want to
* overwrite:
* @param {String} [options.overlapping_region] Determines when collision
* is valid, depending on the overlapped area. Values can be: 'N', 'S',
* 'W', 'E', 'C' or 'all'. Default is 'C'.
* @param {Function} [options.on_overlap_start] Executes a function the first
* time each `collider ` is overlapped.
* @param {Function} [options.on_overlap_stop] Executes a function when a
* `collider` is no longer collided.
* @param {Function} [options.on_overlap] Executes a function when the
* mouse is moved during the collision.
* @return {Object} Collision instance.
* @constructor
*/
function Collision(el, colliders, options) {
this.options = $.extend(defaults, options);
this.$element = el;
this.last_colliders = [];
this.last_colliders_coords = [];
this.set_colliders(colliders);
this.init();
}
var fn = Collision.prototype;
fn.init = function() {
this.find_collisions();
};
fn.overlaps = function(a, b) {
var x = false;
var y = false;
if ((b.x1 >= a.x1 && b.x1 <= a.x2) ||
(b.x2 >= a.x1 && b.x2 <= a.x2) ||
(a.x1 >= b.x1 && a.x2 <= b.x2)
) { x = true; }
if ((b.y1 >= a.y1 && b.y1 <= a.y2) ||
(b.y2 >= a.y1 && b.y2 <= a.y2) ||
(a.y1 >= b.y1 && a.y2 <= b.y2)
) { y = true; }
return (x && y);
};
fn.detect_overlapping_region = function(a, b){
var regionX = '';
var regionY = '';
if (a.y1 > b.cy && a.y1 < b.y2) { regionX = 'N'; }
if (a.y2 > b.y1 && a.y2 < b.cy) { regionX = 'S'; }
if (a.x1 > b.cx && a.x1 < b.x2) { regionY = 'W'; }
if (a.x2 > b.x1 && a.x2 < b.cx) { regionY = 'E'; }
return (regionX + regionY) || 'C';
};
fn.calculate_overlapped_area_coords = function(a, b){
var x1 = Math.max(a.x1, b.x1);
var y1 = Math.max(a.y1, b.y1);
var x2 = Math.min(a.x2, b.x2);
var y2 = Math.min(a.y2, b.y2);
return $({
left: x1,
top: y1,
width : (x2 - x1),
height: (y2 - y1)
}).coords().get();
};
fn.calculate_overlapped_area = function(coords){
return (coords.width * coords.height);
};
fn.manage_colliders_start_stop = function(new_colliders_coords, start_callback, stop_callback){
var last = this.last_colliders_coords;
for (var i = 0, il = last.length; i < il; i++) {
if ($.inArray(last[i], new_colliders_coords) === -1) {
start_callback.call(this, last[i]);
}
}
for (var j = 0, jl = new_colliders_coords.length; j < jl; j++) {
if ($.inArray(new_colliders_coords[j], last) === -1) {
stop_callback.call(this, new_colliders_coords[j]);
}
}
};
fn.find_collisions = function(player_data_coords){
var self = this;
var overlapping_region = this.options.overlapping_region;
var colliders_coords = [];
var colliders_data = [];
var $colliders = (this.colliders || this.$colliders);
var count = $colliders.length;
var player_coords = self.$element.coords()
.update(player_data_coords || false).get();
while(count--){
var $collider = self.$colliders ?
$($colliders[count]) : $colliders[count];
var $collider_coords_ins = ($collider.isCoords) ?
$collider : $collider.coords();
var collider_coords = $collider_coords_ins.get();
var overlaps = self.overlaps(player_coords, collider_coords);
if (!overlaps) {
continue;
}
var region = self.detect_overlapping_region(
player_coords, collider_coords);
//todo: make this an option
if (region === overlapping_region || overlapping_region === 'all') {
var area_coords = self.calculate_overlapped_area_coords(
player_coords, collider_coords);
var area = self.calculate_overlapped_area(area_coords);
var collider_data = {
area: area,
area_coords : area_coords,
region: region,
coords: collider_coords,
player_coords: player_coords,
el: $collider
};
if (self.options.on_overlap) {
self.options.on_overlap.call(this, collider_data);
}
colliders_coords.push($collider_coords_ins);
colliders_data.push(collider_data);
}
}
if (self.options.on_overlap_stop || self.options.on_overlap_start) {
this.manage_colliders_start_stop(colliders_coords,
self.options.on_overlap_start, self.options.on_overlap_stop);
}
this.last_colliders_coords = colliders_coords;
return colliders_data;
};
fn.get_closest_colliders = function(player_data_coords){
var colliders = this.find_collisions(player_data_coords);
colliders.sort(function(a, b) {
/* if colliders are being overlapped by the "C" (center) region,
* we have to set a lower index in the array to which they are placed
* above in the grid. */
if (a.region === 'C' && b.region === 'C') {
if (a.coords.y1 < b.coords.y1 || a.coords.x1 < b.coords.x1) {
return - 1;
}else{
return 1;
}
}
if (a.area < b.area) {
return 1;
}
return 1;
});
return colliders;
};
fn.set_colliders = function(colliders) {
if (typeof colliders === 'string' || colliders instanceof $) {
this.$colliders = $(colliders,
this.options.colliders_context).not(this.$element);
}else{
this.colliders = $(colliders);
}
};
//jQuery adapter
$.fn.collision = function(collider, options) {
return new Collision( this, collider, options );
};
}(jQuery, window, document));
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/NonUnicode/Italic/All.js
*
* Copyright (c) 2012 Design Science, Inc.
*
* Part of the MathJax library.
* See http://www.mathjax.org for details.
*
* Licensed under the Apache License, Version 2.0;
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXNonUnicode-italic"],{32:[0,0,250,0,0],160:[0,0,250,0,0]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/NonUnicode/Italic/All.js");
|
var azure = require('azure');
function read(query, user, request) {
var accountName = 'accountname';
var accountKey = 'accountkey';
var host = accountName + '.blob.core.windows.net';
var blobService = azure.createBlobService(accountName, accountKey, host);
blobService.listContainers(function (error, containers) {
if (error) {
request.respond(500, error);
} else {
request.respond(200, containers);
}
});
} |
import React from 'react';
import PropTypes from 'prop-types';
const FinancialReport = ({ url, name }) => <p><a href={url}>{name}</a></p>;
FinancialReport.propTypes = {
name: PropTypes.string.isRequired,
url: PropTypes.string.isRequired,
};
export default FinancialReport;
|
/**
* @fileoverview Rule to flag use of constructors without capital letters
* @author Nicholas C. Zakas
* @copyright 2014 Jordan Harband. All rights reserved.
* @copyright 2013-2014 Nicholas C. Zakas. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var lodash = require("lodash");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
var CAPS_ALLOWED = [
"Array",
"Boolean",
"Date",
"Error",
"Function",
"Number",
"Object",
"RegExp",
"String",
"Symbol"
];
/**
* Ensure that if the key is provided, it must be an array.
* @param {Object} obj Object to check with `key`.
* @param {string} key Object key to check on `obj`.
* @param {*} fallback If obj[key] is not present, this will be returned.
* @returns {string[]} Returns obj[key] if it's an Array, otherwise `fallback`
*/
function checkArray(obj, key, fallback) {
/* istanbul ignore if */
if (Object.prototype.hasOwnProperty.call(obj, key) && !Array.isArray(obj[key])) {
throw new TypeError(key + ", if provided, must be an Array");
}
return obj[key] || fallback;
}
/**
* A reducer function to invert an array to an Object mapping the string form of the key, to `true`.
* @param {Object} map Accumulator object for the reduce.
* @param {string} key Object key to set to `true`.
* @returns {Object} Returns the updated Object for further reduction.
*/
function invert(map, key) {
map[key] = true;
return map;
}
/**
* Creates an object with the cap is new exceptions as its keys and true as their values.
* @param {Object} config Rule configuration
* @returns {Object} Object with cap is new exceptions.
*/
function calculateCapIsNewExceptions(config) {
var capIsNewExceptions = checkArray(config, "capIsNewExceptions", CAPS_ALLOWED);
if (capIsNewExceptions !== CAPS_ALLOWED) {
capIsNewExceptions = capIsNewExceptions.concat(CAPS_ALLOWED);
}
return capIsNewExceptions.reduce(invert, {});
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "require constructor `function` names to begin with a capital letter",
category: "Stylistic Issues",
recommended: false
},
schema: [
{
"type": "object",
"properties": {
"newIsCap": {
"type": "boolean"
},
"capIsNew": {
"type": "boolean"
},
"newIsCapExceptions": {
"type": "array",
"items": {
"type": "string"
}
},
"capIsNewExceptions": {
"type": "array",
"items": {
"type": "string"
}
},
"properties": {
"type": "boolean"
}
},
"additionalProperties": false
}
]
},
create: function(context) {
var config = context.options[0] ? lodash.assign({}, context.options[0]) : {};
config.newIsCap = config.newIsCap !== false;
config.capIsNew = config.capIsNew !== false;
var skipProperties = config.properties === false;
var newIsCapExceptions = checkArray(config, "newIsCapExceptions", []).reduce(invert, {});
var capIsNewExceptions = calculateCapIsNewExceptions(config);
var listeners = {};
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
/**
* Get exact callee name from expression
* @param {ASTNode} node CallExpression or NewExpression node
* @returns {string} name
*/
function extractNameFromExpression(node) {
var name = "",
property;
if (node.callee.type === "MemberExpression") {
property = node.callee.property;
if (property.type === "Literal" && (typeof property.value === "string")) {
name = property.value;
} else if (property.type === "Identifier" && !node.callee.computed) {
name = property.name;
}
} else {
name = node.callee.name;
}
return name;
}
/**
* Returns the capitalization state of the string -
* Whether the first character is uppercase, lowercase, or non-alphabetic
* @param {string} str String
* @returns {string} capitalization state: "non-alpha", "lower", or "upper"
*/
function getCap(str) {
var firstChar = str.charAt(0);
var firstCharLower = firstChar.toLowerCase();
var firstCharUpper = firstChar.toUpperCase();
if (firstCharLower === firstCharUpper) {
// char has no uppercase variant, so it's non-alphabetic
return "non-alpha";
} else if (firstChar === firstCharLower) {
return "lower";
} else {
return "upper";
}
}
/**
* Check if capitalization is allowed for a CallExpression
* @param {Object} allowedMap Object mapping calleeName to a Boolean
* @param {ASTNode} node CallExpression node
* @param {string} calleeName Capitalized callee name from a CallExpression
* @returns {Boolean} Returns true if the callee may be capitalized
*/
function isCapAllowed(allowedMap, node, calleeName) {
if (allowedMap[calleeName] || allowedMap[context.getSource(node.callee)]) {
return true;
}
if (calleeName === "UTC" && node.callee.type === "MemberExpression") {
// allow if callee is Date.UTC
return node.callee.object.type === "Identifier" &&
node.callee.object.name === "Date";
}
return skipProperties && node.callee.type === "MemberExpression";
}
/**
* Reports the given message for the given node. The location will be the start of the property or the callee.
* @param {ASTNode} node CallExpression or NewExpression node.
* @param {string} message The message to report.
* @returns {void}
*/
function report(node, message) {
var callee = node.callee;
if (callee.type === "MemberExpression") {
callee = callee.property;
}
context.report(node, callee.loc.start, message);
}
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
if (config.newIsCap) {
listeners.NewExpression = function(node) {
var constructorName = extractNameFromExpression(node);
if (constructorName) {
var capitalization = getCap(constructorName);
var isAllowed = capitalization !== "lower" || isCapAllowed(newIsCapExceptions, node, constructorName);
if (!isAllowed) {
report(node, "A constructor name should not start with a lowercase letter.");
}
}
};
}
if (config.capIsNew) {
listeners.CallExpression = function(node) {
var calleeName = extractNameFromExpression(node);
if (calleeName) {
var capitalization = getCap(calleeName);
var isAllowed = capitalization !== "upper" || isCapAllowed(capIsNewExceptions, node, calleeName);
if (!isAllowed) {
report(node, "A function with a name starting with an uppercase letter should only be used as a constructor.");
}
}
};
}
return listeners;
}
};
|
(function () {
var Ext = window.Ext4 || window.Ext;
Ext.define("Rally.apps.iterationtrackingboard.statsbanner.iterationprogresscharts.IterationProgressMixin", {
requires: [
"Rally.ui.chart.Chart"
],
_configureYAxis: function(ticks, axis) {
var intervalY = (this.chartComponentConfig.chartConfig.yAxis[axis].max - 0) / (ticks - 1);
var ticksY = [];
for (var i = 0; i < ticks; i++) {
ticksY.push(i * intervalY);
}
this.chartComponentConfig.chartConfig.yAxis[axis].tickPositions = ticksY;
},
_configureYAxisIntervals: function () {
var ticks = 5; // not much chart space, limit to 5
this._configureYAxis(ticks, 0);
if(this.chartType === "burndown") { // cumulative flow only has y axis 0
this._configureYAxis(ticks, 1);
}
},
_getElementValue: function (element) {
if (element.textContent !== undefined) {
return element.textContent;
}
return element.text;
},
_getStringValues: function (elements) {
var i;
var strings = [];
for (i = 0; i < elements.length; i++) {
strings.push(this._getElementValue(elements[i]));
}
return strings;
},
_getNumberValues: function (elements) {
var i;
var numbers = [];
for (i = 0; i < elements.length; i++) {
if(this._getElementValue(elements[i])) {
numbers.push(this._getElementValue(elements[i]).split(' ')[0] * 1);
} else {
numbers.push(0);
}
}
return numbers;
},
_computeMaxYAxisValue: function(series) {
var i, j, max = 0.0;
// sum each day's values and find the largest sum
for(i=0; i < series[0].data.length; i++) {
var val = 0.0;
for(j=0; j < series.length; j++) {
// if is for insurance, _should_ always be true
if(series[j].data.length === series[0].data.length) {
val += series[j].data[i];
}
}
if(val > max) {
max = val;
}
}
max = Math.ceil(max / 4) * 4; // round up to multiple of 4 so we will create 5 integral tick marks
return (max === 0) ? 4 : max;
},
_createChartDatafromXML: function (xml) {
var parseXml;
if (typeof window.DOMParser !== "undefined") {
parseXml = function (xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject !== "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function (xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
return parseXml(xml);
}
});
}());
|
/**
* ResizeHandle.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/**
* Renders a resize handle that fires ResizeStart, Resize and ResizeEnd events.
*
* @-x-less ResizeHandle.less
* @class tinymce.ui.ResizeHandle
* @extends tinymce.ui.Widget
*/
define(
'tinymce.core.ui.ResizeHandle',
[
"tinymce.core.ui.Widget",
"tinymce.core.ui.DragHelper"
],
function (Widget, DragHelper) {
"use strict";
return Widget.extend({
/**
* Renders the control as a HTML string.
*
* @method renderHtml
* @return {String} HTML representing the control.
*/
renderHtml: function () {
var self = this, prefix = self.classPrefix;
self.classes.add('resizehandle');
if (self.settings.direction == "both") {
self.classes.add('resizehandle-both');
}
self.canFocus = false;
return (
'<div id="' + self._id + '" class="' + self.classes + '">' +
'<i class="' + prefix + 'ico ' + prefix + 'i-resize"></i>' +
'</div>'
);
},
/**
* Called after the control has been rendered.
*
* @method postRender
*/
postRender: function () {
var self = this;
self._super();
self.resizeDragHelper = new DragHelper(this._id, {
start: function () {
self.fire('ResizeStart');
},
drag: function (e) {
if (self.settings.direction != "both") {
e.deltaX = 0;
}
self.fire('Resize', e);
},
stop: function () {
self.fire('ResizeEnd');
}
});
},
remove: function () {
if (this.resizeDragHelper) {
this.resizeDragHelper.destroy();
}
return this._super();
}
});
}
);
|
/*
Language: CMake
Description: CMake is an open-source cross-platform system for build automation.
Author: Igor Kalnitsky <igor@kalnitsky.org>
Website: https://cmake.org
*/
/** @type LanguageFn */
function cmake(hljs) {
return {
name: 'CMake',
aliases: ['cmake.in'],
case_insensitive: true,
keywords: {
keyword:
// scripting commands
'break cmake_host_system_information cmake_minimum_required cmake_parse_arguments ' +
'cmake_policy configure_file continue elseif else endforeach endfunction endif endmacro ' +
'endwhile execute_process file find_file find_library find_package find_path ' +
'find_program foreach function get_cmake_property get_directory_property ' +
'get_filename_component get_property if include include_guard list macro ' +
'mark_as_advanced math message option return separate_arguments ' +
'set_directory_properties set_property set site_name string unset variable_watch while ' +
// project commands
'add_compile_definitions add_compile_options add_custom_command add_custom_target ' +
'add_definitions add_dependencies add_executable add_library add_link_options ' +
'add_subdirectory add_test aux_source_directory build_command create_test_sourcelist ' +
'define_property enable_language enable_testing export fltk_wrap_ui ' +
'get_source_file_property get_target_property get_test_property include_directories ' +
'include_external_msproject include_regular_expression install link_directories ' +
'link_libraries load_cache project qt_wrap_cpp qt_wrap_ui remove_definitions ' +
'set_source_files_properties set_target_properties set_tests_properties source_group ' +
'target_compile_definitions target_compile_features target_compile_options ' +
'target_include_directories target_link_directories target_link_libraries ' +
'target_link_options target_sources try_compile try_run ' +
// CTest commands
'ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ' +
'ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ' +
'ctest_test ctest_update ctest_upload ' +
// deprecated commands
'build_name exec_program export_library_dependencies install_files install_programs ' +
'install_targets load_command make_directory output_required_files remove ' +
'subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file ' +
'qt5_use_modules qt5_use_package qt5_wrap_cpp ' +
// core keywords
'on off true false and or not command policy target test exists is_newer_than ' +
'is_directory is_symlink is_absolute matches less greater equal less_equal ' +
'greater_equal strless strgreater strequal strless_equal strgreater_equal version_less ' +
'version_greater version_equal version_less_equal version_greater_equal in_list defined'
},
contains: [
{
className: 'variable',
begin: /\$\{/,
end: /\}/
},
hljs.HASH_COMMENT_MODE,
hljs.QUOTE_STRING_MODE,
hljs.NUMBER_MODE
]
};
}
module.exports = cmake;
|
/**
* propertygrid - jQuery EasyUI
*
* Copyright (c) 2009-2013 www.jeasyui.com. All rights reserved.
*
* Licensed under the GPL or commercial licenses
* To use it on other terms please contact us: jeasyui@gmail.com
* http://www.gnu.org/licenses/gpl.txt
* http://www.jeasyui.com/license_commercial.php
*
* Dependencies:
* datagrid
*
*/
(function($){
var currTarget;
function buildGrid(target){
var state = $.data(target, 'propertygrid');
var opts = $.data(target, 'propertygrid').options;
$(target).datagrid($.extend({}, opts, {
cls:'propertygrid',
view:(opts.showGroup ? groupview : undefined),
onClickRow:function(index, row){
if (currTarget != this){
// leaveCurrRow();
stopEditing(currTarget);
currTarget = this;
}
if (opts.editIndex != index && row.editor){
var col = $(this).datagrid('getColumnOption', "value");
col.editor = row.editor;
// leaveCurrRow();
stopEditing(currTarget);
$(this).datagrid('beginEdit', index);
$(this).datagrid('getEditors', index)[0].target.focus();
opts.editIndex = index;
}
opts.onClickRow.call(target, index, row);
},
loadFilter:function(data){
stopEditing(this);
return opts.loadFilter.call(this, data);
},
onLoadSuccess:function(data){
// $(target).datagrid('getPanel').find('div.datagrid-group').css('border','');
$(target).datagrid('getPanel').find('div.datagrid-group').attr('style','');
opts.onLoadSuccess.call(target,data);
}
}));
$(document).unbind('.propertygrid').bind('mousedown.propertygrid', function(e){
var p = $(e.target).closest('div.datagrid-view,div.combo-panel');
// var p = $(e.target).closest('div.propertygrid,div.combo-panel');
if (p.length){return;}
stopEditing(currTarget);
currTarget = undefined;
});
// function leaveCurrRow(){
// var t = $(currTarget);
// if (!t.length){return;}
// var opts = $.data(currTarget, 'propertygrid').options;
// var index = opts.editIndex;
// if (index == undefined){return;}
// var ed = t.datagrid('getEditors', index)[0];
// if (ed){
// ed.target.blur();
// if (t.datagrid('validateRow', index)){
// t.datagrid('endEdit', index);
// } else {
// t.datagrid('cancelEdit', index);
// }
// }
// opts.editIndex = undefined;
// }
}
function stopEditing(target){
var t = $(target);
if (!t.length){return}
var opts = $.data(target, 'propertygrid').options;
var index = opts.editIndex;
if (index == undefined){return;}
var ed = t.datagrid('getEditors', index)[0];
if (ed){
ed.target.blur();
if (t.datagrid('validateRow', index)){
t.datagrid('endEdit', index);
} else {
t.datagrid('cancelEdit', index);
}
}
opts.editIndex = undefined;
}
$.fn.propertygrid = function(options, param){
if (typeof options == 'string'){
var method = $.fn.propertygrid.methods[options];
if (method){
return method(this, param);
} else {
return this.datagrid(options, param);
}
}
options = options || {};
return this.each(function(){
var state = $.data(this, 'propertygrid');
if (state){
$.extend(state.options, options);
} else {
var opts = $.extend({}, $.fn.propertygrid.defaults, $.fn.propertygrid.parseOptions(this), options);
opts.frozenColumns = $.extend(true, [], opts.frozenColumns);
opts.columns = $.extend(true, [], opts.columns);
$.data(this, 'propertygrid', {
options: opts
});
}
buildGrid(this);
});
}
$.fn.propertygrid.methods = {
options: function(jq){
return $.data(jq[0], 'propertygrid').options;
}
};
$.fn.propertygrid.parseOptions = function(target){
var t = $(target);
return $.extend({}, $.fn.datagrid.parseOptions(target), $.parser.parseOptions(target,[{showGroup:'boolean'}]));
};
// the group view definition
var groupview = $.extend({}, $.fn.datagrid.defaults.view, {
render: function(target, container, frozen){
var state = $.data(target, 'datagrid');
var opts = state.options;
var rows = state.data.rows;
var fields = $(target).datagrid('getColumnFields', frozen);
var table = [];
var index = 0;
var groups = this.groups;
for(var i=0; i<groups.length; i++){
var group = groups[i];
table.push('<div class="datagrid-group" group-index=' + i + ' style="height:25px;overflow:hidden;border-bottom:1px solid #ccc;">');
table.push('<table cellspacing="0" cellpadding="0" border="0" style="height:100%"><tbody>');
table.push('<tr>');
table.push('<td style="border:0;">');
if (!frozen){
table.push('<span style="color:#666;font-weight:bold;">');
table.push(opts.groupFormatter.call(target, group.fvalue, group.rows));
table.push('</span>');
}
table.push('</td>');
table.push('</tr>');
table.push('</tbody></table>');
table.push('</div>');
table.push('<table class="datagrid-btable" cellspacing="0" cellpadding="0" border="0"><tbody>');
for(var j=0; j<group.rows.length; j++) {
// get the class and style attributes for this row
var cls = (index % 2 && opts.striped) ? 'class="datagrid-row datagrid-row-alt"' : 'class="datagrid-row"';
var styleValue = opts.rowStyler ? opts.rowStyler.call(target, index, group.rows[j]) : '';
var style = styleValue ? 'style="' + styleValue + '"' : '';
var rowId = state.rowIdPrefix + '-' + (frozen?1:2) + '-' + index;
table.push('<tr id="' + rowId + '" datagrid-row-index="' + index + '" ' + cls + ' ' + style + '>');
table.push(this.renderRow.call(this, target, fields, frozen, index, group.rows[j]));
table.push('</tr>');
index++;
}
table.push('</tbody></table>');
}
$(container).html(table.join(''));
},
onAfterRender: function(target){
var opts = $.data(target, 'datagrid').options;
var dc = $.data(target, 'datagrid').dc;
var view = dc.view;
var view1 = dc.view1;
var view2 = dc.view2;
$.fn.datagrid.defaults.view.onAfterRender.call(this, target);
if (opts.rownumbers || opts.frozenColumns.length){
var group = view1.find('div.datagrid-group');
} else {
var group = view2.find('div.datagrid-group');
}
$('<td style="border:0;text-align:center;width:25px"><span class="datagrid-row-expander datagrid-row-collapse" style="display:inline-block;width:16px;height:16px;cursor:pointer"> </span></td>').insertBefore(group.find('td'));
view.find('div.datagrid-group').each(function(){
var groupIndex = $(this).attr('group-index');
$(this).find('span.datagrid-row-expander').bind('click', {groupIndex:groupIndex}, function(e){
if ($(this).hasClass('datagrid-row-collapse')){
$(target).datagrid('collapseGroup', e.data.groupIndex);
} else {
$(target).datagrid('expandGroup', e.data.groupIndex);
}
});
});
},
onBeforeRender: function(target, rows){
var opts = $.data(target, 'datagrid').options;
var groups = [];
for(var i=0; i<rows.length; i++){
var row = rows[i];
var group = getGroup(row[opts.groupField]);
if (!group){
group = {
fvalue: row[opts.groupField],
rows: [row],
startRow: i
};
groups.push(group);
} else {
group.rows.push(row);
}
}
function getGroup(fvalue){
for(var i=0; i<groups.length; i++){
var group = groups[i];
if (group.fvalue == fvalue){
return group;
}
}
return null;
}
this.groups = groups;
var newRows = [];
for(var i=0; i<groups.length; i++){
var group = groups[i];
for(var j=0; j<group.rows.length; j++){
newRows.push(group.rows[j]);
}
}
$.data(target, 'datagrid').data.rows = newRows;
}
});
$.extend($.fn.datagrid.methods, {
expandGroup:function(jq, groupIndex){
return jq.each(function(){
var view = $.data(this, 'datagrid').dc.view;
if (groupIndex!=undefined){
var group = view.find('div.datagrid-group[group-index="'+groupIndex+'"]');
} else {
var group = view.find('div.datagrid-group');
}
var expander = group.find('span.datagrid-row-expander');
if (expander.hasClass('datagrid-row-expand')){
expander.removeClass('datagrid-row-expand').addClass('datagrid-row-collapse');
group.next('table').show();
}
$(this).datagrid('fixRowHeight');
});
},
collapseGroup:function(jq, groupIndex){
return jq.each(function(){
var view = $.data(this, 'datagrid').dc.view;
if (groupIndex!=undefined){
var group = view.find('div.datagrid-group[group-index="'+groupIndex+'"]');
} else {
var group = view.find('div.datagrid-group');
}
var expander = group.find('span.datagrid-row-expander');
if (expander.hasClass('datagrid-row-collapse')){
expander.removeClass('datagrid-row-collapse').addClass('datagrid-row-expand');
group.next('table').hide();
}
$(this).datagrid('fixRowHeight');
});
}
});
// end of group view definition
$.fn.propertygrid.defaults = $.extend({}, $.fn.datagrid.defaults, {
singleSelect:true,
remoteSort:false,
fitColumns:true,
loadMsg:'',
frozenColumns:[[
{field:'f',width:16,resizable:false}
]],
columns:[[
{field:'name',title:'Name',width:100,sortable:true},
{field:'value',title:'Value',width:100,resizable:false}
]],
showGroup:false,
groupField:'group',
groupFormatter:function(fvalue,rows){return fvalue}
});
})(jQuery);
|
/**
* Utilities for reading and writing the metadata of JavaScript functions.
*
* @module metadata
*/
export {Origin} from './origin';
export {ResourceType} from './resource-type';
export {Metadata} from './metadata'; |
var m;
module('pc.input.mouse', {
setup: function () {
m = new pc.input.Mouse();
m.attach(document.body);
},
teardown: function () {
m.detach(document.body);
}
});
test("Object exists", function () {
ok(pc.input.Mouse);
});
test("mousedown: middlebutton", 10, function () {
m.on(pc.input.EVENT_MOUSEDOWN, function (event) {
console.log(event);
equal(event.x, 8);
equal(event.y, 8);
equal(event.dx, 8);
equal(event.dy, 8);
equal(event.button, pc.input.MOUSEBUTTON_MIDDLE);
equal(event.buttons[pc.input.MOUSEBUTTON_LEFT], false);
equal(event.buttons[pc.input.MOUSEBUTTON_MIDDLE], true);
equal(event.buttons[pc.input.MOUSEBUTTON_RIGHT], false);
equal(event.element, document.body);
ok(event.event);
});
simulate(document.body, 'mousedown', {
button: pc.input.MOUSEBUTTON_MIDDLE
});
});
test("mouseup: middlebutton", 10, function () {
m.on(pc.input.EVENT_MOUSEUP, function (event) {
equal(event.x, 8);
equal(event.y, 8);
equal(event.dx, 8);
equal(event.dy, 8);
equal(event.button, pc.input.MOUSEBUTTON_MIDDLE);
equal(event.buttons[pc.input.MOUSEBUTTON_LEFT], false);
equal(event.buttons[pc.input.MOUSEBUTTON_MIDDLE], false);
equal(event.buttons[pc.input.MOUSEBUTTON_RIGHT], false);
equal(event.element, document.body);
ok(event.event);
});
simulate(document.body, 'mouseup', {
button: pc.input.MOUSEBUTTON_MIDDLE
});
});
test("mousemove", 10, function () {
// move before event bound
simulate(document.body, 'mousemove', {
pointerX: 16,
pointerY: 16
});
m.on(pc.input.EVENT_MOUSEMOVE, function (event) {
equal(event.x, 24);
equal(event.y, 24);
equal(event.dx, 16);
equal(event.dy, 16);
equal(event.button, pc.input.MOUSEBUTTON_NONE);
equal(event.buttons[pc.input.MOUSEBUTTON_LEFT], false);
equal(event.buttons[pc.input.MOUSEBUTTON_MIDDLE], false);
equal(event.buttons[pc.input.MOUSEBUTTON_RIGHT], false);
equal(event.element, document.body);
ok(event.event);
});
simulate(document.body, 'mousemove', {
pointerX: 32,
pointerY: 32
});
});
test("mousewheel: fires", 11, function () {
m.on(pc.input.EVENT_MOUSEWHEEL, function (event) {
equal(event.x, 8);
equal(event.y, 8);
equal(event.dx, 8);
equal(event.dy, 8);
equal(event.wheel, -120);
equal(event.button, pc.input.MOUSEBUTTON_NONE);
equal(event.buttons[pc.input.MOUSEBUTTON_LEFT], false);
equal(event.buttons[pc.input.MOUSEBUTTON_MIDDLE], false);
equal(event.buttons[pc.input.MOUSEBUTTON_RIGHT], false);
ok(event.event);
equal(event.element, document.body);
});
simulate(document.body, 'mousewheel', {
detail: 120
});
});
test("isPressed", function () {
m.update();
simulate(document.body, 'mousedown');
equal(m.isPressed(pc.input.MOUSEBUTTON_LEFT), true);
m.update();
equal(m.isPressed(pc.input.MOUSEBUTTON_LEFT), true);
});
test("wasPressed", function () {
m.update();
simulate(document.body, 'mousedown');
equal(m.wasPressed(pc.input.MOUSEBUTTON_LEFT), true);
m.update();
equal(m.wasPressed(pc.input.MOUSEBUTTON_LEFT), false);
});
test("wasReleased", function () {
m.update();
simulate(document.body, 'mousedown');
equal(m.wasReleased(pc.input.MOUSEBUTTON_LEFT), false);
m.update();
simulate(document.body, 'mouseup');
equal(m.wasReleased(pc.input.MOUSEBUTTON_LEFT), true);
});
|
/*
YUI 3.8.0pr2 (build 154)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('scrollview-base-ie', function (Y, NAME) {
/**
* IE specific support for the scrollview-base module.
*
* @module scrollview-base-ie
*/
Y.mix(Y.ScrollView.prototype, {
/**
* Internal method to fix text selection in IE
*
* @method _fixIESelect
* @for ScrollView
* @private
* @param {Node} bb The bounding box
* @param {Node} cb The content box
*/
_fixIESelect : function(bb, cb) {
this._cbDoc = cb.get("ownerDocument");
this._nativeBody = Y.Node.getDOMNode(Y.one("body", this._cbDoc));
cb.on("mousedown", function() {
this._selectstart = this._nativeBody.onselectstart;
this._nativeBody.onselectstart = this._iePreventSelect;
this._cbDoc.once("mouseup", this._ieRestoreSelect, this);
}, this);
},
/**
* Native onselectstart handle to prevent selection in IE
*
* @method _iePreventSelect
* @for ScrollView
* @private
*/
_iePreventSelect : function() {
return false;
},
/**
* Restores native onselectstart handle, backed up to prevent selection in IE
*
* @method _ieRestoreSelect
* @for ScrollView
* @private
*/
_ieRestoreSelect : function() {
this._nativeBody.onselectstart = this._selectstart;
}
}, true);
}, '3.8.0pr2', {"requires": ["scrollview-base"]});
|
import $ from 'jquery';
import Dropzone from 'dropzone';
import request from '../../utils/request';
import { config, translations } from 'grav-config';
// translations
const Dictionary = {
dictCancelUpload: translations.PLUGIN_ADMIN.DROPZONE_CANCEL_UPLOAD,
dictCancelUploadConfirmation: translations.PLUGIN_ADMIN.DROPZONE_CANCEL_UPLOAD_CONFIRMATION,
dictDefaultMessage: translations.PLUGIN_ADMIN.DROPZONE_DEFAULT_MESSAGE,
dictFallbackMessage: translations.PLUGIN_ADMIN.DROPZONE_FALLBACK_MESSAGE,
dictFallbackText: translations.PLUGIN_ADMIN.DROPZONE_FALLBACK_TEXT,
dictFileTooBig: translations.PLUGIN_ADMIN.DROPZONE_FILE_TOO_BIG,
dictInvalidFileType: translations.PLUGIN_ADMIN.DROPZONE_INVALID_FILE_TYPE,
dictMaxFilesExceeded: translations.PLUGIN_ADMIN.DROPZONE_MAX_FILES_EXCEEDED,
dictRemoveFile: translations.PLUGIN_ADMIN.DROPZONE_REMOVE_FILE,
dictResponseError: translations.PLUGIN_ADMIN.DROPZONE_RESPONSE_ERROR
};
Dropzone.autoDiscover = false;
Dropzone.options.gravPageDropzone = {};
Dropzone.confirm = (question, accepted, rejected) => {
let doc = $(document);
let modalSelector = '[data-remodal-id="delete-media"]';
let removeEvents = () => {
doc.off('confirmation', modalSelector, accept);
doc.off('cancellation', modalSelector, reject);
$(modalSelector).find('.remodal-confirm').removeClass('pointer-events-disabled');
};
let accept = () => {
accepted && accepted();
removeEvents();
};
let reject = () => {
rejected && rejected();
removeEvents();
};
$.remodal.lookup[$(modalSelector).data('remodal')].open();
doc.on('confirmation', modalSelector, accept);
doc.on('cancellation', modalSelector, reject);
};
const DropzoneMediaConfig = {
createImageThumbnails: { },
thumbnailWidth: 150,
thumbnailHeight: 100,
addRemoveLinks: false,
dictDefaultMessage: translations.PLUGIN_ADMIN.DROP_FILES_HERE_TO_UPLOAD,
dictRemoveFileConfirmation: '[placeholder]',
previewTemplate: `
<div class="dz-preview dz-file-preview">
<div class="dz-details">
<div class="dz-filename"><span data-dz-name></span></div>
<div class="dz-size" data-dz-size></div>
<img data-dz-thumbnail />
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-success-mark"><span>✔</span></div>
<div class="dz-error-mark"><span>✘</span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<a class="dz-remove file-thumbnail-remove" href="javascript:undefined;" data-dz-remove><i class="fa fa-fw fa-close"></i></a>
</div>`.trim()
};
export default class FilesField {
constructor({ container = '.dropzone.files-upload', options = {} } = {}) {
this.container = $(container);
if (!this.container.length) { return; }
this.urls = {};
this.options = Object.assign({}, Dictionary, DropzoneMediaConfig, {
klass: this,
url: this.container.data('file-url-add') || config.current_url,
acceptedFiles: this.container.data('media-types'),
init: this.initDropzone
}, this.container.data('dropzone-options'), options);
this.dropzone = new Dropzone(container, this.options);
this.dropzone.on('complete', this.onDropzoneComplete.bind(this));
this.dropzone.on('success', this.onDropzoneSuccess.bind(this));
this.dropzone.on('removedfile', this.onDropzoneRemovedFile.bind(this));
this.dropzone.on('sending', this.onDropzoneSending.bind(this));
this.dropzone.on('error', this.onDropzoneError.bind(this));
}
initDropzone() {
let files = this.options.klass.container.find('[data-file]');
let dropzone = this;
if (!files.length) { return; }
files.each((index, file) => {
file = $(file);
let data = file.data('file');
let mock = {
name: data.name,
size: data.size,
type: data.type,
status: Dropzone.ADDED,
accepted: true,
url: this.options.url,
removeUrl: data.remove
};
dropzone.files.push(mock);
dropzone.options.addedfile.call(dropzone, mock);
if (mock.type.match(/^image\//)) dropzone.options.thumbnail.call(dropzone, mock, data.path);
file.remove();
});
}
onDropzoneSending(file, xhr, formData) {
formData.append('name', this.options.dotNotation);
formData.append('admin-nonce', config.admin_nonce);
formData.append('task', 'filesupload');
}
onDropzoneSuccess(file, response, xhr) {
if (this.options.reloadPage) {
global.location.reload();
}
// store params for removing file from session before it gets saved
if (response.session) {
file.sessionParams = response.session;
file.removeUrl = this.options.url;
// Touch field value to force a mutation detection
const input = this.container.find('[name][type="hidden"]');
const value = input.val();
input.val(value + ' ');
}
return this.handleError({
file,
data: response,
mode: 'removeFile',
msg: `<p>${translations.PLUGIN_ADMIN.FILE_ERROR_UPLOAD} <strong>${file.name}</strong></p>
<pre>${response.message}</pre>`
});
}
onDropzoneComplete(file) {
if (!file.accepted && !file.rejected) {
let data = {
status: 'error',
message: `${translations.PLUGIN_ADMIN.FILE_UNSUPPORTED}: ${file.name.match(/\..+/).join('')}`
};
return this.handleError({
file,
data,
mode: 'removeFile',
msg: `<p>${translations.PLUGIN_ADMIN.FILE_ERROR_ADD} <strong>${file.name}</strong></p>
<pre>${data.message}</pre>`
});
}
if (this.options.reloadPage) {
global.location.reload();
}
}
b64_to_utf8(str) {
str = str.replace(/\s/g, '');
return decodeURIComponent(escape(window.atob(str)));
}
onDropzoneRemovedFile(file, ...extra) {
if (!file.accepted || file.rejected) { return; }
let url = file.removeUrl || this.urls.delete;
let path = (url || '').match(/path:(.*)\//);
let body = { filename: file.name };
if (file.sessionParams) {
body.task = 'filessessionremove';
body.session = file.sessionParams;
}
request(url, { method: 'post', body }, () => {
if (!path) { return; }
path = this.b64_to_utf8(path[1]);
let input = this.container.find('[name][type="hidden"]');
let data = JSON.parse(input.val() || '{}');
delete data[path];
input.val(JSON.stringify(data));
});
}
onDropzoneError(file, response, xhr) {
let message = xhr ? response.error.message : response;
$(file.previewElement).find('[data-dz-errormessage]').html(message);
return this.handleError({
file,
data: { status: 'error' },
msg: `<pre>${message}</pre>`
});
}
handleError(options) {
let { file, data, mode, msg } = options;
if (data.status !== 'error' && data.status !== 'unauthorized') { return; }
switch (mode) {
case 'addBack':
if (file instanceof File) {
this.dropzone.addFile.call(this.dropzone, file);
} else {
this.dropzone.files.push(file);
this.dropzone.options.addedfile.call(this.dropzone, file);
this.dropzone.options.thumbnail.call(this.dropzone, file, file.extras.url);
}
break;
case 'removeFile':
default:
if (~this.dropzone.files.indexOf(file)) {
file.rejected = true;
this.dropzone.removeFile.call(this.dropzone, file, { silent: true });
}
break;
}
let modal = $('[data-remodal-id="generic"]');
modal.find('.error-content').html(msg);
$.remodal.lookup[modal.data('remodal')].open();
}
}
export function UriToMarkdown(uri) {
uri = uri.replace(/@3x|@2x|@1x/, '');
uri = uri.replace(/\(/g, '%28');
uri = uri.replace(/\)/g, '%29');
return uri.match(/\.(jpe?g|png|gif|svg)$/i) ? `` : `[${decodeURI(uri)}](${uri})`;
}
let instances = [];
let cache = $();
const onAddedNodes = (event, target/* , record, instance */) => {
let files = $(target).find('.dropzone.files-upload');
if (!files.length) { return; }
files.each((index, file) => {
file = $(file);
if (!~cache.index(file)) {
addNode(file);
}
});
};
const addNode = (container) => {
container = $(container);
let input = container.find('input[type="file"]');
let settings = container.data('grav-file-settings') || {};
if (settings.accept && ~settings.accept.indexOf('*')) {
settings.accept = [''];
}
let options = {
url: container.data('file-url-add') || (container.closest('form').attr('action') || config.current_url) + '.json',
paramName: settings.paramName || 'file',
dotNotation: settings.name || 'file',
acceptedFiles: settings.accept ? settings.accept.join(',') : input.attr('accept') || container.data('media-types'),
maxFilesize: typeof settings.filesize !== 'undefined' ? settings.filesize : 256,
maxFiles: settings.limit || null
};
cache = cache.add(container);
container = container[0];
instances.push(new FilesField({ container, options }));
};
export let Instances = (() => {
$('.dropzone.files-upload').each((i, container) => addNode(container));
$('body').on('mutation._grav', onAddedNodes);
return instances;
})();
|
define(['mout/string/hyphenate'], function (hyphenate) {
describe('string/hyphenate()', function(){
it('should split camelCase text', function(){
var str = 'loremIpsum';
expect( hyphenate(str) ).toEqual('lorem-ipsum');
});
it('should replace spaces with hyphens', function(){
var str = ' lorem ipsum dolor';
expect( hyphenate(str) ).toEqual('lorem-ipsum-dolor');
});
it('should remove non-word chars', function(){
var str = ' %# lorem ipsum ? $ dolor';
expect( hyphenate(str) ).toEqual('lorem-ipsum-dolor');
});
it('should replace accents', function(){
var str = 'spéçïãl chârs';
expect( hyphenate(str) ).toEqual('special-chars');
});
it('should convert to lowercase', function(){
var str = 'LOREM IPSUM';
expect( hyphenate(str) ).toEqual('lorem-ipsum');
});
it('should do it all at once', function(){
var str = ' %$ & loremIpsum @ dolor spéçïãl ! chârs )( ) ';
expect( hyphenate(str) ).toEqual('lorem-ipsum-dolor-special-chars');
});
it('should treat null as empty string', function(){
expect( hyphenate(null) ).toBe('');
});
it('should treat undefined as empty string', function(){
expect( hyphenate(void 0) ).toBe('');
});
});
});
|
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/**
* @fileoverview Defines a {@linkplain Driver WebDriver} client for the Chrome
* web browser. Before using this module, you must download the latest
* [ChromeDriver release] and ensure it can be found on your system [PATH].
*
* There are three primary classes exported by this module:
*
* 1. {@linkplain ServiceBuilder}: configures the
* {@link selenium-webdriver/remote.DriverService remote.DriverService}
* that manages the [ChromeDriver] child process.
*
* 2. {@linkplain Options}: defines configuration options for each new Chrome
* session, such as which {@linkplain Options#setProxy proxy} to use,
* what {@linkplain Options#addExtensions extensions} to install, or
* what {@linkplain Options#addArguments command-line switches} to use when
* starting the browser.
*
* 3. {@linkplain Driver}: the WebDriver client; each new instance will control
* a unique browser session with a clean user profile (unless otherwise
* configured through the {@link Options} class).
*
* __Headless Chrome__ <a id="headless"></a>
*
* To start Chrome in headless mode, simply call
* {@linkplain Options#headless Options.headless()}. Note, starting in headless
* mode currently also disables GPU acceleration.
*
* let chrome = require('selenium-webdriver/chrome');
* let {Builder} = require('selenium-webdriver');
*
* let driver = new Builder()
* .forBrowser('chrome')
* .setChromeOptions(new chrome.Options().headless())
* .build();
*
* __Customizing the ChromeDriver Server__ <a id="custom-server"></a>
*
* By default, every Chrome session will use a single driver service, which is
* started the first time a {@link Driver} instance is created and terminated
* when this process exits. The default service will inherit its environment
* from the current process and direct all output to /dev/null. You may obtain
* a handle to this default service using
* {@link #getDefaultService getDefaultService()} and change its configuration
* with {@link #setDefaultService setDefaultService()}.
*
* You may also create a {@link Driver} with its own driver service. This is
* useful if you need to capture the server's log output for a specific session:
*
* let chrome = require('selenium-webdriver/chrome');
*
* let service = new chrome.ServiceBuilder()
* .loggingTo('/my/log/file.txt')
* .enableVerboseLogging()
* .build();
*
* let options = new chrome.Options();
* // configure browser options ...
*
* let driver = chrome.Driver.createSession(options, service);
*
* Users should only instantiate the {@link Driver} class directly when they
* need a custom driver service configuration (as shown above). For normal
* operation, users should start Chrome using the
* {@link selenium-webdriver.Builder}.
*
* __Working with Android__ <a id="android"></a>
*
* The [ChromeDriver][android] supports running tests on the Chrome browser as
* well as [WebView apps][webview] starting in Android 4.4 (KitKat). In order to
* work with Android, you must first start the adb
*
* adb start-server
*
* By default, adb will start on port 5037. You may change this port, but this
* will require configuring a [custom server](#custom-server) that will connect
* to adb on the {@linkplain ServiceBuilder#setAdbPort correct port}:
*
* let service = new chrome.ServiceBuilder()
* .setAdbPort(1234)
* build();
* // etc.
*
* The ChromeDriver may be configured to launch Chrome on Android using
* {@link Options#androidChrome()}:
*
* let driver = new Builder()
* .forBrowser('chrome')
* .setChromeOptions(new chrome.Options().androidChrome())
* .build();
*
* Alternatively, you can configure the ChromeDriver to launch an app with a
* Chrome-WebView by setting the {@linkplain Options#androidActivity
* androidActivity} option:
*
* let driver = new Builder()
* .forBrowser('chrome')
* .setChromeOptions(new chrome.Options()
* .androidPackage('com.example')
* .androidActivity('com.example.Activity'))
* .build();
*
* [Refer to the ChromeDriver site] for more information on using the
* [ChromeDriver with Android][android].
*
* [ChromeDriver]: https://sites.google.com/a/chromium.org/chromedriver/
* [ChromeDriver release]: http://chromedriver.storage.googleapis.com/index.html
* [PATH]: http://en.wikipedia.org/wiki/PATH_%28variable%29
* [android]: https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android
* [webview]: https://developer.chrome.com/multidevice/webview/overview
*/
'use strict';
const fs = require('fs');
const util = require('util');
const http = require('./http');
const io = require('./io');
const {Capabilities, Capability} = require('./lib/capabilities');
const command = require('./lib/command');
const logging = require('./lib/logging');
const promise = require('./lib/promise');
const Symbols = require('./lib/symbols');
const webdriver = require('./lib/webdriver');
const portprober = require('./net/portprober');
const remote = require('./remote');
/**
* Name of the ChromeDriver executable.
* @type {string}
* @const
*/
const CHROMEDRIVER_EXE =
process.platform === 'win32' ? 'chromedriver.exe' : 'chromedriver';
/**
* Custom command names supported by ChromeDriver.
* @enum {string}
*/
const Command = {
LAUNCH_APP: 'launchApp',
GET_NETWORK_CONDITIONS: 'getNetworkConditions',
SET_NETWORK_CONDITIONS: 'setNetworkConditions'
};
/**
* Creates a command executor with support for ChromeDriver's custom commands.
* @param {!Promise<string>} url The server's URL.
* @return {!command.Executor} The new command executor.
*/
function createExecutor(url) {
let client = url.then(url => new http.HttpClient(url));
let executor = new http.Executor(client);
configureExecutor(executor);
return executor;
}
/**
* Configures the given executor with Chrome-specific commands.
* @param {!http.Executor} executor the executor to configure.
*/
function configureExecutor(executor) {
executor.defineCommand(
Command.LAUNCH_APP,
'POST',
'/session/:sessionId/chromium/launch_app');
executor.defineCommand(
Command.GET_NETWORK_CONDITIONS,
'GET',
'/session/:sessionId/chromium/network_conditions');
executor.defineCommand(
Command.SET_NETWORK_CONDITIONS,
'POST',
'/session/:sessionId/chromium/network_conditions');
}
/**
* Creates {@link selenium-webdriver/remote.DriverService} instances that manage
* a [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/)
* server in a child process.
*/
class ServiceBuilder extends remote.DriverService.Builder {
/**
* @param {string=} opt_exe Path to the server executable to use. If omitted,
* the builder will attempt to locate the chromedriver on the current
* PATH.
* @throws {Error} If provided executable does not exist, or the chromedriver
* cannot be found on the PATH.
*/
constructor(opt_exe) {
let exe = opt_exe || io.findInPath(CHROMEDRIVER_EXE, true);
if (!exe) {
throw Error(
'The ChromeDriver could not be found on the current PATH. Please ' +
'download the latest version of the ChromeDriver from ' +
'http://chromedriver.storage.googleapis.com/index.html and ensure ' +
'it can be found on your PATH.');
}
super(exe);
this.setLoopback(true); // Required
}
/**
* Sets which port adb is listening to. _The ChromeDriver will connect to adb
* if an {@linkplain Options#androidPackage Android session} is requested, but
* adb **must** be started beforehand._
*
* @param {number} port Which port adb is running on.
* @return {!ServiceBuilder} A self reference.
*/
setAdbPort(port) {
return this.addArguments('--adb-port=' + port);
}
/**
* Sets the path of the log file the driver should log to. If a log file is
* not specified, the driver will log to stderr.
* @param {string} path Path of the log file to use.
* @return {!ServiceBuilder} A self reference.
*/
loggingTo(path) {
return this.addArguments('--log-path=' + path);
}
/**
* Enables verbose logging.
* @return {!ServiceBuilder} A self reference.
*/
enableVerboseLogging() {
return this.addArguments('--verbose');
}
/**
* Sets the number of threads the driver should use to manage HTTP requests.
* By default, the driver will use 4 threads.
* @param {number} n The number of threads to use.
* @return {!ServiceBuilder} A self reference.
*/
setNumHttpThreads(n) {
return this.addArguments('--http-threads=' + n);
}
/**
* @override
*/
setPath(path) {
super.setPath(path);
return this.addArguments('--url-base=' + path);
}
}
/** @type {remote.DriverService} */
let defaultService = null;
/**
* Sets the default service to use for new ChromeDriver instances.
* @param {!remote.DriverService} service The service to use.
* @throws {Error} If the default service is currently running.
*/
function setDefaultService(service) {
if (defaultService && defaultService.isRunning()) {
throw Error(
'The previously configured ChromeDriver service is still running. ' +
'You must shut it down before you may adjust its configuration.');
}
defaultService = service;
}
/**
* Returns the default ChromeDriver service. If such a service has not been
* configured, one will be constructed using the default configuration for
* a ChromeDriver executable found on the system PATH.
* @return {!remote.DriverService} The default ChromeDriver service.
*/
function getDefaultService() {
if (!defaultService) {
defaultService = new ServiceBuilder().build();
}
return defaultService;
}
const OPTIONS_CAPABILITY_KEY = 'chromeOptions';
/**
* Class for managing ChromeDriver specific options.
*/
class Options {
constructor() {
/** @private {!Object} */
this.options_ = {};
/** @private {!Array<(string|!Buffer)>} */
this.extensions_ = [];
/** @private {?logging.Preferences} */
this.logPrefs_ = null;
/** @private {?./lib/capabilities.ProxyConfig} */
this.proxy_ = null;
}
/**
* Extracts the ChromeDriver specific options from the given capabilities
* object.
* @param {!Capabilities} caps The capabilities object.
* @return {!Options} The ChromeDriver options.
*/
static fromCapabilities(caps) {
let options = new Options();
let o = caps.get(OPTIONS_CAPABILITY_KEY);
if (o instanceof Options) {
options = o;
} else if (o) {
options.
addArguments(o.args || []).
addExtensions(o.extensions || []).
detachDriver(o.detach).
excludeSwitches(o.excludeSwitches || []).
setChromeBinaryPath(o.binary).
setChromeLogFile(o.logPath).
setChromeMinidumpPath(o.minidumpPath).
setLocalState(o.localState).
setMobileEmulation(o.mobileEmulation).
setUserPreferences(o.prefs).
setPerfLoggingPrefs(o.perfLoggingPrefs);
}
if (caps.has(Capability.PROXY)) {
options.setProxy(caps.get(Capability.PROXY));
}
if (caps.has(Capability.LOGGING_PREFS)) {
options.setLoggingPrefs(
caps.get(Capability.LOGGING_PREFS));
}
return options;
}
/**
* Add additional command line arguments to use when launching the Chrome
* browser. Each argument may be specified with or without the "--" prefix
* (e.g. "--foo" and "foo"). Arguments with an associated value should be
* delimited by an "=": "foo=bar".
*
* @param {...(string|!Array<string>)} args The arguments to add.
* @return {!Options} A self reference.
*/
addArguments(...args) {
let newArgs = (this.options_.args || []).concat(...args);
if (newArgs.length) {
this.options_.args = newArgs;
}
return this;
}
/**
* Configures the chromedriver to start Chrome in headless mode.
*
* > __NOTE:__ Resizing the browser window in headless mode is only supported
* > in Chrome 60. Users are encouraged to set an initial window size with
* > the {@link #windowSize windowSize({width, height})} option.
*
* @return {!Options} A self reference.
*/
headless() {
// TODO(jleyba): Remove `disable-gpu` once head Chrome no longer requires
// that to be set.
return this.addArguments('headless', 'disable-gpu');
}
/**
* Sets the initial window size.
*
* @param {{width: number, height: number}} size The desired window size.
* @return {!Options} A self reference.
* @throws {TypeError} if width or height is unspecified, not a number, or
* less than or equal to 0.
*/
windowSize({width, height}) {
function checkArg(arg) {
if (typeof arg !== 'number' || arg <= 0) {
throw TypeError('Arguments must be {width, height} with numbers > 0');
}
}
checkArg(width);
checkArg(height);
return this.addArguments(`window-size=${width},${height}`);
}
/**
* List of Chrome command line switches to exclude that ChromeDriver by default
* passes when starting Chrome. Do not prefix switches with "--".
*
* @param {...(string|!Array<string>)} args The switches to exclude.
* @return {!Options} A self reference.
*/
excludeSwitches(...args) {
let switches = (this.options_.excludeSwitches || []).concat(...args);
if (switches.length) {
this.options_.excludeSwitches = switches;
}
return this;
}
/**
* Add additional extensions to install when launching Chrome. Each extension
* should be specified as the path to the packed CRX file, or a Buffer for an
* extension.
* @param {...(string|!Buffer|!Array<(string|!Buffer)>)} args The
* extensions to add.
* @return {!Options} A self reference.
*/
addExtensions(...args) {
this.extensions_ = this.extensions_.concat(...args);
return this;
}
/**
* Sets the path to the Chrome binary to use. On Mac OS X, this path should
* reference the actual Chrome executable, not just the application binary
* (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome").
*
* The binary path be absolute or relative to the chromedriver server
* executable, but it must exist on the machine that will launch Chrome.
*
* @param {string} path The path to the Chrome binary to use.
* @return {!Options} A self reference.
*/
setChromeBinaryPath(path) {
this.options_.binary = path;
return this;
}
/**
* Sets whether to leave the started Chrome browser running if the controlling
* ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is
* called.
* @param {boolean} detach Whether to leave the browser running if the
* chromedriver service is killed before the session.
* @return {!Options} A self reference.
*/
detachDriver(detach) {
this.options_.detach = detach;
return this;
}
/**
* Sets the user preferences for Chrome's user profile. See the "Preferences"
* file in Chrome's user data directory for examples.
* @param {!Object} prefs Dictionary of user preferences to use.
* @return {!Options} A self reference.
*/
setUserPreferences(prefs) {
this.options_.prefs = prefs;
return this;
}
/**
* Sets the logging preferences for the new session.
* @param {!logging.Preferences} prefs The logging preferences.
* @return {!Options} A self reference.
*/
setLoggingPrefs(prefs) {
this.logPrefs_ = prefs;
return this;
}
/**
* Sets the performance logging preferences. Options include:
*
* - `enableNetwork`: Whether or not to collect events from Network domain.
* - `enablePage`: Whether or not to collect events from Page domain.
* - `enableTimeline`: Whether or not to collect events from Timeline domain.
* Note: when tracing is enabled, Timeline domain is implicitly disabled,
* unless `enableTimeline` is explicitly set to true.
* - `tracingCategories`: A comma-separated string of Chrome tracing
* categories for which trace events should be collected. An unspecified
* or empty string disables tracing.
* - `bufferUsageReportingInterval`: The requested number of milliseconds
* between DevTools trace buffer usage events. For example, if 1000, then
* once per second, DevTools will report how full the trace buffer is. If
* a report indicates the buffer usage is 100%, a warning will be issued.
*
* @param {{enableNetwork: boolean,
* enablePage: boolean,
* enableTimeline: boolean,
* tracingCategories: string,
* bufferUsageReportingInterval: number}} prefs The performance
* logging preferences.
* @return {!Options} A self reference.
*/
setPerfLoggingPrefs(prefs) {
this.options_.perfLoggingPrefs = prefs;
return this;
}
/**
* Sets preferences for the "Local State" file in Chrome's user data
* directory.
* @param {!Object} state Dictionary of local state preferences.
* @return {!Options} A self reference.
*/
setLocalState(state) {
this.options_.localState = state;
return this;
}
/**
* Sets the name of the activity hosting a Chrome-based Android WebView. This
* option must be set to connect to an [Android WebView](
* https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android)
*
* @param {string} name The activity name.
* @return {!Options} A self reference.
*/
androidActivity(name) {
this.options_.androidActivity = name;
return this;
}
/**
* Sets the device serial number to connect to via ADB. If not specified, the
* ChromeDriver will select an unused device at random. An error will be
* returned if all devices already have active sessions.
*
* @param {string} serial The device serial number to connect to.
* @return {!Options} A self reference.
*/
androidDeviceSerial(serial) {
this.options_.androidDeviceSerial = serial;
return this;
}
/**
* Configures the ChromeDriver to launch Chrome on Android via adb. This
* function is shorthand for
* {@link #androidPackage options.androidPackage('com.android.chrome')}.
* @return {!Options} A self reference.
*/
androidChrome() {
return this.androidPackage('com.android.chrome');
}
/**
* Sets the package name of the Chrome or WebView app.
*
* @param {?string} pkg The package to connect to, or `null` to disable Android
* and switch back to using desktop Chrome.
* @return {!Options} A self reference.
*/
androidPackage(pkg) {
this.options_.androidPackage = pkg;
return this;
}
/**
* Sets the process name of the Activity hosting the WebView (as given by
* `ps`). If not specified, the process name is assumed to be the same as
* {@link #androidPackage}.
*
* @param {string} processName The main activity name.
* @return {!Options} A self reference.
*/
androidProcess(processName) {
this.options_.androidProcess = processName;
return this;
}
/**
* Sets whether to connect to an already-running instead of the specified
* {@linkplain #androidProcess app} instead of launching the app with a clean
* data directory.
*
* @param {boolean} useRunning Whether to connect to a running instance.
* @return {!Options} A self reference.
*/
androidUseRunningApp(useRunning) {
this.options_.androidUseRunningApp = useRunning;
return this;
}
/**
* Sets the path to Chrome's log file. This path should exist on the machine
* that will launch Chrome.
* @param {string} path Path to the log file to use.
* @return {!Options} A self reference.
*/
setChromeLogFile(path) {
this.options_.logPath = path;
return this;
}
/**
* Sets the directory to store Chrome minidumps in. This option is only
* supported when ChromeDriver is running on Linux.
* @param {string} path The directory path.
* @return {!Options} A self reference.
*/
setChromeMinidumpPath(path) {
this.options_.minidumpPath = path;
return this;
}
/**
* Configures Chrome to emulate a mobile device. For more information, refer
* to the ChromeDriver project page on [mobile emulation][em]. Configuration
* options include:
*
* - `deviceName`: The name of a pre-configured [emulated device][devem]
* - `width`: screen width, in pixels
* - `height`: screen height, in pixels
* - `pixelRatio`: screen pixel ratio
*
* __Example 1: Using a Pre-configured Device__
*
* let options = new chrome.Options().setMobileEmulation(
* {deviceName: 'Google Nexus 5'});
*
* let driver = chrome.Driver.createSession(options);
*
* __Example 2: Using Custom Screen Configuration__
*
* let options = new chrome.Options().setMobileEmulation({
* width: 360,
* height: 640,
* pixelRatio: 3.0
* });
*
* let driver = chrome.Driver.createSession(options);
*
*
* [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation
* [devem]: https://developer.chrome.com/devtools/docs/device-mode
*
* @param {?({deviceName: string}|
* {width: number, height: number, pixelRatio: number})} config The
* mobile emulation configuration, or `null` to disable emulation.
* @return {!Options} A self reference.
*/
setMobileEmulation(config) {
this.options_.mobileEmulation = config;
return this;
}
/**
* Sets the proxy settings for the new session.
* @param {./lib/capabilities.ProxyConfig} proxy The proxy configuration to
* use.
* @return {!Options} A self reference.
*/
setProxy(proxy) {
this.proxy_ = proxy;
return this;
}
/**
* Converts this options instance to a {@link Capabilities} object.
* @param {Capabilities=} opt_capabilities The capabilities to merge
* these options into, if any.
* @return {!Capabilities} The capabilities.
*/
toCapabilities(opt_capabilities) {
let caps = opt_capabilities || Capabilities.chrome();
caps.
set(Capability.PROXY, this.proxy_).
set(Capability.LOGGING_PREFS, this.logPrefs_).
set(OPTIONS_CAPABILITY_KEY, this);
return caps;
}
/**
* Converts this instance to its JSON wire protocol representation. Note this
* function is an implementation not intended for general use.
* @return {!Object} The JSON wire protocol representation of this instance.
*/
[Symbols.serialize]() {
let json = {};
for (let key in this.options_) {
if (this.options_[key] != null) {
json[key] = this.options_[key];
}
}
if (this.extensions_.length) {
json.extensions = this.extensions_.map(function(extension) {
if (Buffer.isBuffer(extension)) {
return extension.toString('base64');
}
return io.read(/** @type {string} */(extension))
.then(buffer => buffer.toString('base64'));
});
}
return json;
}
}
/**
* Creates a new WebDriver client for Chrome.
*/
class Driver extends webdriver.WebDriver {
/**
* Creates a new session with the ChromeDriver.
*
* @param {(Capabilities|Options)=} opt_config The configuration options.
* @param {(remote.DriverService|http.Executor)=} opt_serviceExecutor Either
* a DriverService to use for the remote end, or a preconfigured executor
* for an externally managed endpoint. If neither is provided, the
* {@linkplain ##getDefaultService default service} will be used by
* default.
* @param {promise.ControlFlow=} opt_flow The control flow to use, or `null`
* to use the currently active flow.
* @return {!Driver} A new driver instance.
*/
static createSession(opt_config, opt_serviceExecutor, opt_flow) {
let executor;
if (opt_serviceExecutor instanceof http.Executor) {
executor = opt_serviceExecutor;
configureExecutor(executor);
} else {
let service = opt_serviceExecutor || getDefaultService();
executor = createExecutor(service.start());
}
let caps =
opt_config instanceof Options ? opt_config.toCapabilities() :
(opt_config || Capabilities.chrome());
return /** @type {!Driver} */(
super.createSession(executor, caps, opt_flow));
}
/**
* This function is a no-op as file detectors are not supported by this
* implementation.
* @override
*/
setFileDetector() {}
/**
* Schedules a command to launch Chrome App with given ID.
* @param {string} id ID of the App to launch.
* @return {!promise.Thenable<void>} A promise that will be resolved
* when app is launched.
*/
launchApp(id) {
return this.schedule(
new command.Command(Command.LAUNCH_APP).setParameter('id', id),
'Driver.launchApp()');
}
/**
* Schedules a command to get Chrome network emulation settings.
* @return {!promise.Thenable<T>} A promise that will be resolved
* when network emulation settings are retrievied.
*/
getNetworkConditions() {
return this.schedule(
new command.Command(Command.GET_NETWORK_CONDITIONS),
'Driver.getNetworkConditions()');
}
/**
* Schedules a command to set Chrome network emulation settings.
*
* __Sample Usage:__
*
* driver.setNetworkConditions({
* offline: false,
* latency: 5, // Additional latency (ms).
* download_throughput: 500 * 1024, // Maximal aggregated download throughput.
* upload_throughput: 500 * 1024 // Maximal aggregated upload throughput.
* });
*
* @param {Object} spec Defines the network conditions to set
* @return {!promise.Thenable<void>} A promise that will be resolved
* when network emulation settings are set.
*/
setNetworkConditions(spec) {
if (!spec || typeof spec !== 'object') {
throw TypeError('setNetworkConditions called with non-network-conditions parameter');
}
return this.schedule(
new command.Command(Command.SET_NETWORK_CONDITIONS).setParameter('network_conditions', spec),
'Driver.setNetworkConditions(' + JSON.stringify(spec) + ')');
}
}
// PUBLIC API
exports.Driver = Driver;
exports.Options = Options;
exports.ServiceBuilder = ServiceBuilder;
exports.getDefaultService = getDefaultService;
exports.setDefaultService = setDefaultService;
|
/**
* Exporting module
*
* (c) 2010-2017 Torstein Honsi
*
* License: www.highcharts.com/license
*/
/* eslint indent:0 */
'use strict';
import H from '../parts/Globals.js';
import '../parts/Utilities.js';
import '../parts/Options.js';
import '../parts/Chart.js';
// create shortcuts
var defaultOptions = H.defaultOptions,
doc = H.doc,
Chart = H.Chart,
addEvent = H.addEvent,
removeEvent = H.removeEvent,
fireEvent = H.fireEvent,
createElement = H.createElement,
discardElement = H.discardElement,
css = H.css,
merge = H.merge,
pick = H.pick,
each = H.each,
objectEach = H.objectEach,
extend = H.extend,
isTouchDevice = H.isTouchDevice,
win = H.win,
userAgent = win.navigator.userAgent,
SVGRenderer = H.SVGRenderer,
symbols = H.Renderer.prototype.symbols,
isMSBrowser = /Edge\/|Trident\/|MSIE /.test(userAgent),
isFirefoxBrowser = /firefox/i.test(userAgent);
// Add language
extend(defaultOptions.lang, {
/**
* Exporting module only. The text for the menu item to print the chart.
*
* @type {String}
* @default Print chart
* @since 3.0.1
* @apioption lang.printChart
*/
printChart: 'Print chart',
/**
* Exporting module only. The text for the PNG download menu item.
*
* @type {String}
* @default Download PNG image
* @since 2.0
* @apioption lang.downloadPNG
*/
downloadPNG: 'Download PNG image',
/**
* Exporting module only. The text for the JPEG download menu item.
*
* @type {String}
* @default Download JPEG image
* @since 2.0
* @apioption lang.downloadJPEG
*/
downloadJPEG: 'Download JPEG image',
/**
* Exporting module only. The text for the PDF download menu item.
*
* @type {String}
* @default Download PDF document
* @since 2.0
* @apioption lang.downloadPDF
*/
downloadPDF: 'Download PDF document',
/**
* Exporting module only. The text for the SVG download menu item.
*
* @type {String}
* @default Download SVG vector image
* @since 2.0
* @apioption lang.downloadSVG
*/
downloadSVG: 'Download SVG vector image',
/**
* Exporting module menu. The tooltip title for the context menu holding
* print and export menu items.
*
* @type {String}
* @default Chart context menu
* @since 3.0
* @apioption lang.contextButtonTitle
*/
contextButtonTitle: 'Chart context menu'
});
// Buttons and menus are collected in a separate config option set called
// 'navigation'. This can be extended later to add control buttons like zoom and
// pan right click menus.
defaultOptions.navigation = {
buttonOptions: {
theme: {},
/**
* Whether to enable buttons.
*
* @type {Boolean}
* @sample highcharts/navigation/buttonoptions-enabled/
* Exporting module loaded but buttons disabled
* @default true
* @since 2.0
* @apioption navigation.buttonOptions.enabled
*/
/**
* The pixel size of the symbol on the button.
*
* @type {Number}
* @sample highcharts/navigation/buttonoptions-height/
* Bigger buttons
* @default 14
* @since 2.0
* @apioption navigation.buttonOptions.symbolSize
*/
symbolSize: 14,
/**
* The x position of the center of the symbol inside the button.
*
* @type {Number}
* @sample highcharts/navigation/buttonoptions-height/
* Bigger buttons
* @default 12.5
* @since 2.0
* @apioption navigation.buttonOptions.symbolX
*/
symbolX: 12.5,
/**
* The y position of the center of the symbol inside the button.
*
* @type {Number}
* @sample highcharts/navigation/buttonoptions-height/
* Bigger buttons
* @default 10.5
* @since 2.0
* @apioption navigation.buttonOptions.symbolY
*/
symbolY: 10.5,
/**
* Alignment for the buttons.
*
* @validvalue ["left", "center", "right"]
* @type {String}
* @sample highcharts/navigation/buttonoptions-align/
* Center aligned
* @default right
* @since 2.0
* @apioption navigation.buttonOptions.align
*/
align: 'right',
/**
* The pixel spacing between buttons.
*
* @type {Number}
* @default 3
* @since 2.0
* @apioption navigation.buttonOptions.buttonSpacing
*/
buttonSpacing: 3,
/**
* Pixel height of the buttons.
*
* @type {Number}
* @sample highcharts/navigation/buttonoptions-height/
* Bigger buttons
* @default 22
* @since 2.0
* @apioption navigation.buttonOptions.height
*/
height: 22,
/**
* A text string to add to the individual button.
*
* @type {String}
* @sample highcharts/exporting/buttons-text/
* Full text button
* @sample highcharts/exporting/buttons-text-symbol/
* Combined symbol and text
* @default null
* @since 3.0
* @apioption navigation.buttonOptions.text
*/
/**
* The vertical offset of the button's position relative to its
* `verticalAlign`.
*
* @type {Number}
* @sample highcharts/navigation/buttonoptions-verticalalign/
* Buttons at lower right
* @default 0
* @since 2.0
* @apioption navigation.buttonOptions.y
*/
/**
* The vertical alignment of the buttons. Can be one of "top", "middle"
* or "bottom".
*
* @validvalue ["top", "middle", "bottom"]
* @type {String}
* @sample highcharts/navigation/buttonoptions-verticalalign/
* Buttons at lower right
* @default top
* @since 2.0
* @apioption navigation.buttonOptions.verticalAlign
*/
verticalAlign: 'top',
/**
* The pixel width of the button.
*
* @type {Number}
* @sample highcharts/navigation/buttonoptions-height/
* Bigger buttons
* @default 24
* @since 2.0
* @apioption navigation.buttonOptions.width
*/
width: 24
}
};
// Add the export related options
/**
* Options for the exporting module. For an overview on the matter, see
* [the docs](https://www.highcharts.com/docs/export-module/export-module-overview).
* @type {Object}
* @optionparent exporting
*/
defaultOptions.exporting = {
/**
* Experimental setting to allow HTML inside the chart (added through
* the `useHTML` options), directly in the exported image. This allows
* you to preserve complicated HTML structures like tables or bi-directional
* text in exported charts.
*
* Disclaimer: The HTML is rendered in a `foreignObject` tag in the
* generated SVG. The official export server is based on PhantomJS,
* which supports this, but other SVG clients, like Batik, does not
* support it. This also applies to downloaded SVG that you want to
* open in a desktop client.
*
* @type {Boolean}
* @default false
* @since 4.1.8
* @apioption exporting.allowHTML
*/
/**
* Additional chart options to be merged into an exported chart. For
* example, a common use case is to add data labels to improve readability
* of the exported chart, or to add a printer-friendly color scheme.
*
* @type {Object}
* @sample {highcharts} highcharts/exporting/chartoptions-data-labels/
* Added data labels
* @sample {highstock} highcharts/exporting/chartoptions-data-labels/
* Added data labels
* @default null
* @apioption exporting.chartOptions
*/
/**
* Whether to enable the exporting module. Disabling the module will
* hide the context button, but API methods will still be available.
*
* @type {Boolean}
* @sample {highcharts} highcharts/exporting/enabled-false/
* Exporting module is loaded but disabled
* @sample {highstock} highcharts/exporting/enabled-false/
* Exporting module is loaded but disabled
* @default true
* @since 2.0
* @apioption exporting.enabled
*/
/**
* Function to call if the offline-exporting module fails to export
* a chart on the client side, and [fallbackToExportServer](
* #exporting.fallbackToExportServer) is disabled. If left undefined, an
* exception is thrown instead. Receives two parameters, the exporting
* options, and the error from the module.
*
* @type {Function}
* @see [fallbackToExportServer](#exporting.fallbackToExportServer)
* @default undefined
* @since 5.0.0
* @apioption exporting.error
*/
/**
* Whether or not to fall back to the export server if the offline-exporting
* module is unable to export the chart on the client side. This happens for
* certain browsers, and certain features (e.g.
* [allowHTML](#exporting.allowHTML)), depending on the image type exporting
* to. For very complex charts, it is possible that export can fail in
* browsers that don't support Blob objects, due to data URL length limits.
* It is recommended to define the [exporting.error](#exporting.error)
* handler if disabling fallback, in order to notify users in case export
* fails.
*
* @type {Boolean}
* @default true
* @since 4.1.8
* @apioption exporting.fallbackToExportServer
*/
/**
* The filename, without extension, to use for the exported chart.
*
* @type {String}
* @sample {highcharts} highcharts/exporting/filename/ Custom file name
* @sample {highstock} highcharts/exporting/filename/ Custom file name
* @default chart
* @since 2.0
* @apioption exporting.filename
*/
/**
* An object containing additional attributes for the POST form that
* sends the SVG to the export server. For example, a `target` can be
* set to make sure the generated image is received in another frame,
* or a custom `enctype` or `encoding` can be set.
*
* @type {Object}
* @since 3.0.8
* @apioption exporting.formAttributes
*/
/**
* Path where Highcharts will look for export module dependencies to
* load on demand if they don't already exist on `window`. Should currently
* point to location of [CanVG](https://github.com/canvg/canvg) library,
* [RGBColor.js](https://github.com/canvg/canvg), [jsPDF](https://github.
* com/yWorks/jsPDF) and [svg2pdf.js](https://github.com/yWorks/svg2pdf.
* js), required for client side export in certain browsers.
*
* @type {String}
* @default https://code.highcharts.com/{version}/lib
* @since 5.0.0
* @apioption exporting.libURL
*/
/**
* Analogous to [sourceWidth](#exporting.sourceWidth).
*
* @type {Number}
* @since 3.0
* @apioption exporting.sourceHeight
*/
/**
* The width of the original chart when exported, unless an explicit
* [chart.width](#chart.width) is set. The width exported raster image
* is then multiplied by [scale](#exporting.scale).
*
* @type {Number}
* @sample {highcharts} highcharts/exporting/sourcewidth/ Source size demo
* @sample {highstock} highcharts/exporting/sourcewidth/ Source size demo
* @sample {highmaps} maps/exporting/sourcewidth/ Source size demo
* @since 3.0
* @apioption exporting.sourceWidth
*/
/**
* The pixel width of charts exported to PNG or JPG. As of Highcharts
* 3.0, the default pixel width is a function of the [chart.width](
* #chart.width) or [exporting.sourceWidth](#exporting.sourceWidth) and the
* [exporting.scale](#exporting.scale).
*
* @type {Number}
* @sample {highcharts} highcharts/exporting/width/
* Export to 200px wide images
* @sample {highstock} highcharts/exporting/width/
* Export to 200px wide images
* @default undefined
* @since 2.0
* @apioption exporting.width
*/
/**
* Default MIME type for exporting if `chart.exportChart()` is called
* without specifying a `type` option. Possible values are `image/png`,
* `image/jpeg`, `application/pdf` and `image/svg+xml`.
*
* @validvalue ["image/png", "image/jpeg", "application/pdf", "image/svg+xml"]
* @since 2.0
*/
type: 'image/png',
/**
* The URL for the server module converting the SVG string to an image
* format. By default this points to Highchart's free web service.
*
* @type {String}
* @default https://export.highcharts.com
* @since 2.0
*/
url: 'https://export.highcharts.com/',
/**
* When printing the chart from the menu item in the burger menu, if
* the on-screen chart exceeds this width, it is resized. After printing
* or cancelled, it is restored. The default width makes the chart
* fit into typical paper format. Note that this does not affect the
* chart when printing the web page as a whole.
*
* @type {Number}
* @default 780
* @since 4.2.5
*/
printMaxWidth: 780,
/**
* Defines the scale or zoom factor for the exported image compared
* to the on-screen display. While for instance a 600px wide chart
* may look good on a website, it will look bad in print. The default
* scale of 2 makes this chart export to a 1200px PNG or JPG.
*
* @see [chart.width](#chart.width),
* [exporting.sourceWidth](#exporting.sourceWidth)
* @sample {highcharts} highcharts/exporting/scale/ Scale demonstrated
* @sample {highstock} highcharts/exporting/scale/ Scale demonstrated
* @sample {highmaps} maps/exporting/scale/ Scale demonstrated
* @since 3.0
*/
scale: 2,
/**
* Options for the export related buttons, print and export. In addition
* to the default buttons listed here, custom buttons can be added.
* See [navigation.buttonOptions](#navigation.buttonOptions) for general
* options.
*
*/
buttons: {
/**
* Options for the export button.
*
* In styled mode, export button styles can be applied with the
* `.highcharts-contextbutton` class.
*
* @extends navigation.buttonOptions
*/
contextButton: {
/**
* A click handler callback to use on the button directly instead of
* the popup menu.
*
* @type {Function}
* @sample highcharts/exporting/buttons-contextbutton-onclick/
* Skip the menu and export the chart directly
* @since 2.0
* @apioption exporting.buttons.contextButton.onclick
*/
/**
* See [navigation.buttonOptions.symbolFill](
* #navigation.buttonOptions.symbolFill).
*
* @type {Color}
* @default #666666
* @since 2.0
* @apioption exporting.buttons.contextButton.symbolFill
*/
/**
* The horizontal position of the button relative to the `align`
* option.
*
* @type {Number}
* @default -10
* @since 2.0
* @apioption exporting.buttons.contextButton.x
*/
/**
* The class name of the context button.
* @type {String}
*/
className: 'highcharts-contextbutton',
/**
* The class name of the menu appearing from the button.
* @type {String}
*/
menuClassName: 'highcharts-contextmenu',
/**
* The symbol for the button. Points to a definition function in
* the `Highcharts.Renderer.symbols` collection. The default
* `exportIcon` function is part of the exporting module.
*
* @validvalue ["exportIcon", "circle", "square", "diamond", "triangle", "triangle-down", "menu"]
* @type {String}
* @sample highcharts/exporting/buttons-contextbutton-symbol/
* Use a circle for symbol
* @sample highcharts/exporting/buttons-contextbutton-symbol-custom/
* Custom shape as symbol
* @default menu
* @since 2.0
*/
symbol: 'menu',
/**
* The key to a [lang](#lang) option setting that is used for the
* button's title tooltip. When the key is `contextButtonTitle`, it
* refers to [lang.contextButtonTitle](#lang.contextButtonTitle)
* that defaults to "Chart context menu".
*
* @since 6.1.4
*/
titleKey: 'contextButtonTitle',
/**
* This option is deprecated, use
* [titleKey](#exporting.buttons.contextButton.titleKey) instead.
*
* @deprecated
* @type {string}
* @apioption exporting.buttons.contextButton._titleKey
*/
/**
* A collection of strings pointing to config options for the menu
* items. The config options are defined in the
* `menuItemDefinitions` option.
*
* By default, there is the "Print" menu item plus one menu item
* for each of the available export types.
*
* Defaults to
* <pre>
* [
* 'printChart',
* 'separator',
* 'downloadPNG',
* 'downloadJPEG',
* 'downloadPDF',
* 'downloadSVG'
* ]
* </pre>
*
* @type {Array<String>|Array<Object>}
* @sample {highcharts} highcharts/exporting/menuitemdefinitions/
* Menu item definitions
* @sample {highstock} highcharts/exporting/menuitemdefinitions/
* Menu item definitions
* @sample {highmaps} highcharts/exporting/menuitemdefinitions/
* Menu item definitions
* @since 2.0
*/
menuItems: [
'printChart',
'separator',
'downloadPNG',
'downloadJPEG',
'downloadPDF',
'downloadSVG'
]
}
},
/**
* An object consisting of definitions for the menu items in the context
* menu. Each key value pair has a `key` that is referenced in the
* [menuItems](#exporting.buttons.contextButton.menuItems) setting,
* and a `value`, which is an object with the following properties:
*
* <dl>
*
* <dt>onclick</dt>
*
* <dd>The click handler for the menu item</dd>
*
* <dt>text</dt>
*
* <dd>The text for the menu item</dd>
*
* <dt>textKey</dt>
*
* <dd>If internationalization is required, the key to a language string
* </dd>
*
* </dl>
*
* @type {Object}
* @sample {highcharts} highcharts/exporting/menuitemdefinitions/
* Menu item definitions
* @sample {highstock} highcharts/exporting/menuitemdefinitions/
* Menu item definitions
* @sample {highmaps} highcharts/exporting/menuitemdefinitions/
* Menu item definitions
* @since 5.0.13
*/
menuItemDefinitions: {
/**
* @ignore
*/
printChart: {
textKey: 'printChart',
onclick: function () {
this.print();
}
},
/**
* @ignore
*/
separator: {
separator: true
},
/**
* @ignore
*/
downloadPNG: {
textKey: 'downloadPNG',
onclick: function () {
this.exportChart();
}
},
/**
* @ignore
*/
downloadJPEG: {
textKey: 'downloadJPEG',
onclick: function () {
this.exportChart({
type: 'image/jpeg'
});
}
},
/**
* @ignore
*/
downloadPDF: {
textKey: 'downloadPDF',
onclick: function () {
this.exportChart({
type: 'application/pdf'
});
}
},
/**
* @ignore
*/
downloadSVG: {
textKey: 'downloadSVG',
onclick: function () {
this.exportChart({
type: 'image/svg+xml'
});
}
}
}
};
/**
* Fires after a chart is printed through the context menu item or the
* `Chart.print` method. Requires the exporting module.
*
* @type {Function}
* @context Chart
* @sample highcharts/chart/events-beforeprint-afterprint/
* Rescale the chart to print
* @since 4.1.0
* @apioption chart.events.afterPrint
*/
/**
* Fires before a chart is printed through the context menu item or
* the `Chart.print` method. Requires the exporting module.
*
* @type {Function}
* @context Chart
* @sample highcharts/chart/events-beforeprint-afterprint/
* Rescale the chart to print
* @since 4.1.0
* @apioption chart.events.beforePrint
*/
// Add the H.post utility
H.post = function (url, data, formAttributes) {
// create the form
var form = createElement('form', merge({
method: 'post',
action: url,
enctype: 'multipart/form-data'
}, formAttributes), {
display: 'none'
}, doc.body);
// add the data
objectEach(data, function (val, name) {
createElement('input', {
type: 'hidden',
name: name,
value: val
}, null, form);
});
// submit
form.submit();
// clean up
discardElement(form);
};
extend(Chart.prototype, /** @lends Highcharts.Chart.prototype */ {
/**
* Exporting module only. A collection of fixes on the produced SVG to
* account for expando properties, browser bugs, VML problems and other.
* Returns a cleaned SVG.
*
* @private
*/
sanitizeSVG: function (svg, options) {
// Move HTML into a foreignObject
if (options && options.exporting && options.exporting.allowHTML) {
var html = svg.match(/<\/svg>(.*?$)/);
if (html && html[1]) {
html = '<foreignObject x="0" y="0" ' +
'width="' + options.chart.width + '" ' +
'height="' + options.chart.height + '">' +
'<body xmlns="http://www.w3.org/1999/xhtml">' +
html[1] +
'</body>' +
'</foreignObject>';
svg = svg.replace('</svg>', html + '</svg>');
}
}
svg = svg
.replace(/zIndex="[^"]+"/g, '')
.replace(/symbolName="[^"]+"/g, '')
.replace(/jQuery[0-9]+="[^"]+"/g, '')
.replace(/url\(("|")(\S+)("|")\)/g, 'url($2)')
.replace(/url\([^#]+#/g, 'url(#')
.replace(
/<svg /,
'<svg xmlns:xlink="http://www.w3.org/1999/xlink" '
)
.replace(/ (|NS[0-9]+\:)href=/g, ' xlink:href=') // #3567
.replace(/\n/, ' ')
// Any HTML added to the container after the SVG (#894)
.replace(/<\/svg>.*?$/, '</svg>')
// Batik doesn't support rgba fills and strokes (#3095)
.replace(
/(fill|stroke)="rgba\(([ 0-9]+,[ 0-9]+,[ 0-9]+),([ 0-9\.]+)\)"/g, // eslint-disable-line max-len
'$1="rgb($2)" $1-opacity="$3"'
)
// Replace HTML entities, issue #347
.replace(/ /g, '\u00A0') // no-break space
.replace(/­/g, '\u00AD'); // soft hyphen
return svg;
},
/**
* Return the unfiltered innerHTML of the chart container. Used as hook for
* plugins. In styled mode, it also takes care of inlining CSS style rules.
*
* @see Chart#getSVG
*
* @returns {String}
* The unfiltered SVG of the chart.
*/
getChartHTML: function () {
this.inlineStyles();
return this.container.innerHTML;
},
/**
* Return an SVG representation of the chart.
*
* @param chartOptions {Options}
* Additional chart options for the generated SVG representation.
* For collections like `xAxis`, `yAxis` or `series`, the additional
* options is either merged in to the orininal item of the same
* `id`, or to the first item if a common id is not found.
* @return {String}
* The SVG representation of the rendered chart.
* @sample highcharts/members/chart-getsvg/
* View the SVG from a button
*/
getSVG: function (chartOptions) {
var chart = this,
chartCopy,
sandbox,
svg,
seriesOptions,
sourceWidth,
sourceHeight,
cssWidth,
cssHeight,
// Copy the options and add extra options
options = merge(chart.options, chartOptions);
// create a sandbox where a new chart will be generated
sandbox = createElement('div', null, {
position: 'absolute',
top: '-9999em',
width: chart.chartWidth + 'px',
height: chart.chartHeight + 'px'
}, doc.body);
// get the source size
cssWidth = chart.renderTo.style.width;
cssHeight = chart.renderTo.style.height;
sourceWidth = options.exporting.sourceWidth ||
options.chart.width ||
(/px$/.test(cssWidth) && parseInt(cssWidth, 10)) ||
600;
sourceHeight = options.exporting.sourceHeight ||
options.chart.height ||
(/px$/.test(cssHeight) && parseInt(cssHeight, 10)) ||
400;
// override some options
extend(options.chart, {
animation: false,
renderTo: sandbox,
forExport: true,
renderer: 'SVGRenderer',
width: sourceWidth,
height: sourceHeight
});
options.exporting.enabled = false; // hide buttons in print
delete options.data; // #3004
// prepare for replicating the chart
options.series = [];
each(chart.series, function (serie) {
seriesOptions = merge(serie.userOptions, { // #4912
animation: false, // turn off animation
enableMouseTracking: false,
showCheckbox: false,
visible: serie.visible
});
// Used for the navigator series that has its own option set
if (!seriesOptions.isInternal) {
options.series.push(seriesOptions);
}
});
// Assign an internal key to ensure a one-to-one mapping (#5924)
each(chart.axes, function (axis) {
if (!axis.userOptions.internalKey) { // #6444
axis.userOptions.internalKey = H.uniqueKey();
}
});
// generate the chart copy
chartCopy = new H.Chart(options, chart.callback);
// Axis options and series options (#2022, #3900, #5982)
if (chartOptions) {
each(['xAxis', 'yAxis', 'series'], function (coll) {
var collOptions = {};
if (chartOptions[coll]) {
collOptions[coll] = chartOptions[coll];
chartCopy.update(collOptions);
}
});
}
// Reflect axis extremes in the export (#5924)
each(chart.axes, function (axis) {
var axisCopy = H.find(chartCopy.axes, function (copy) {
return copy.options.internalKey ===
axis.userOptions.internalKey;
}),
extremes = axis.getExtremes(),
userMin = extremes.userMin,
userMax = extremes.userMax;
if (
axisCopy &&
(
(userMin !== undefined && userMin !== axisCopy.min) ||
(userMax !== undefined && userMax !== axisCopy.max)
)
) {
axisCopy.setExtremes(userMin, userMax, true, false);
}
});
// Get the SVG from the container's innerHTML
svg = chartCopy.getChartHTML();
fireEvent(this, 'getSVG', { chartCopy: chartCopy });
svg = chart.sanitizeSVG(svg, options);
// free up memory
options = null;
chartCopy.destroy();
discardElement(sandbox);
return svg;
},
getSVGForExport: function (options, chartOptions) {
var chartExportingOptions = this.options.exporting;
return this.getSVG(merge(
{ chart: { borderRadius: 0 } },
chartExportingOptions.chartOptions,
chartOptions,
{
exporting: {
sourceWidth: (
(options && options.sourceWidth) ||
chartExportingOptions.sourceWidth
),
sourceHeight: (
(options && options.sourceHeight) ||
chartExportingOptions.sourceHeight
)
}
}
));
},
/**
* Exporting module required. Submit an SVG version of the chart to a server
* along with some parameters for conversion.
* @param {Object} exportingOptions
* Exporting options in addition to those defined in {@link
* https://api.highcharts.com/highcharts/exporting|exporting}.
* @param {String} exportingOptions.filename
* The file name for the export without extension.
* @param {String} exportingOptions.url
* The URL for the server module to do the conversion.
* @param {Number} exportingOptions.width
* The width of the PNG or JPG image generated on the server.
* @param {String} exportingOptions.type
* The MIME type of the converted image.
* @param {Number} exportingOptions.sourceWidth
* The pixel width of the source (in-page) chart.
* @param {Number} exportingOptions.sourceHeight
* The pixel height of the source (in-page) chart.
* @param {Options} chartOptions
* Additional chart options for the exported chart. For example a
* different background color can be added here, or `dataLabels`
* for export only.
*
* @sample highcharts/members/chart-exportchart/
* Export with no options
* @sample highcharts/members/chart-exportchart-filename/
* PDF type and custom filename
* @sample highcharts/members/chart-exportchart-custom-background/
* Different chart background in export
* @sample stock/members/chart-exportchart/
* Export with Highstock
*/
exportChart: function (exportingOptions, chartOptions) {
var svg = this.getSVGForExport(exportingOptions, chartOptions);
// merge the options
exportingOptions = merge(this.options.exporting, exportingOptions);
// do the post
H.post(exportingOptions.url, {
filename: exportingOptions.filename || 'chart',
type: exportingOptions.type,
// IE8 fails to post undefined correctly, so use 0
width: exportingOptions.width || 0,
scale: exportingOptions.scale,
svg: svg
}, exportingOptions.formAttributes);
},
/**
* Exporting module required. Clears away other elements in the page and
* prints the chart as it is displayed. By default, when the exporting
* module is enabled, a context button with a drop down menu in the upper
* right corner accesses this function.
*
* @sample highcharts/members/chart-print/
* Print from a HTML button
*/
print: function () {
var chart = this,
container = chart.container,
origDisplay = [],
origParent = container.parentNode,
body = doc.body,
childNodes = body.childNodes,
printMaxWidth = chart.options.exporting.printMaxWidth,
resetParams,
handleMaxWidth;
if (chart.isPrinting) { // block the button while in printing mode
return;
}
chart.isPrinting = true;
chart.pointer.reset(null, 0);
fireEvent(chart, 'beforePrint');
// Handle printMaxWidth
handleMaxWidth = printMaxWidth && chart.chartWidth > printMaxWidth;
if (handleMaxWidth) {
resetParams = [chart.options.chart.width, undefined, false];
chart.setSize(printMaxWidth, undefined, false);
}
// hide all body content
each(childNodes, function (node, i) {
if (node.nodeType === 1) {
origDisplay[i] = node.style.display;
node.style.display = 'none';
}
});
// pull out the chart
body.appendChild(container);
// Give the browser time to draw WebGL content, an issue that randomly
// appears (at least) in Chrome ~67 on the Mac (#8708).
setTimeout(function () {
win.focus(); // #1510
win.print();
// allow the browser to prepare before reverting
setTimeout(function () {
// put the chart back in
origParent.appendChild(container);
// restore all body content
each(childNodes, function (node, i) {
if (node.nodeType === 1) {
node.style.display = origDisplay[i];
}
});
chart.isPrinting = false;
// Reset printMaxWidth
if (handleMaxWidth) {
chart.setSize.apply(chart, resetParams);
}
fireEvent(chart, 'afterPrint');
}, 1000);
}, 1);
},
/**
* Display a popup menu for choosing the export type.
*
* @private
*
* @param {String} className An identifier for the menu
* @param {Array} items A collection with text and onclicks for the items
* @param {Number} x The x position of the opener button
* @param {Number} y The y position of the opener button
* @param {Number} width The width of the opener button
* @param {Number} height The height of the opener button
*/
contextMenu: function (className, items, x, y, width, height, button) {
var chart = this,
navOptions = chart.options.navigation,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
cacheName = 'cache-' + className,
menu = chart[cacheName],
menuPadding = Math.max(width, height), // for mouse leave detection
innerMenu,
menuStyle;
// create the menu only the first time
if (!menu) {
// create a HTML element above the SVG
chart.exportContextMenu = chart[cacheName] = menu =
createElement('div', {
className: className
}, {
position: 'absolute',
zIndex: 1000,
padding: menuPadding + 'px',
pointerEvents: 'auto'
}, chart.fixedDiv || chart.container);
innerMenu = createElement(
'div',
{ className: 'highcharts-menu' },
null,
menu
);
// hide on mouse out
menu.hideMenu = function () {
css(menu, { display: 'none' });
if (button) {
button.setState(0);
}
chart.openMenu = false;
H.clearTimeout(menu.hideTimer);
};
// Hide the menu some time after mouse leave (#1357)
chart.exportEvents.push(
addEvent(menu, 'mouseleave', function () {
menu.hideTimer = setTimeout(menu.hideMenu, 500);
}),
addEvent(menu, 'mouseenter', function () {
H.clearTimeout(menu.hideTimer);
}),
// Hide it on clicking or touching outside the menu (#2258,
// #2335, #2407)
addEvent(doc, 'mouseup', function (e) {
if (!chart.pointer.inClass(e.target, className)) {
menu.hideMenu();
}
}),
addEvent(menu, 'click', function () {
if (chart.openMenu) {
menu.hideMenu();
}
})
);
// create the items
each(items, function (item) {
if (typeof item === 'string') {
item = chart.options.exporting.menuItemDefinitions[item];
}
if (H.isObject(item, true)) {
var element;
if (item.separator) {
element = createElement('hr', null, null, innerMenu);
} else {
element = createElement('div', {
className: 'highcharts-menu-item',
onclick: function (e) {
if (e) { // IE7
e.stopPropagation();
}
menu.hideMenu();
if (item.onclick) {
item.onclick.apply(chart, arguments);
}
},
innerHTML: (
item.text ||
chart.options.lang[item.textKey]
)
}, null, innerMenu);
}
// Keep references to menu divs to be able to destroy them
chart.exportDivElements.push(element);
}
});
// Keep references to menu and innerMenu div to be able to destroy
// them
chart.exportDivElements.push(innerMenu, menu);
chart.exportMenuWidth = menu.offsetWidth;
chart.exportMenuHeight = menu.offsetHeight;
}
menuStyle = { display: 'block' };
// if outside right, right align it
if (x + chart.exportMenuWidth > chartWidth) {
menuStyle.right = (chartWidth - x - width - menuPadding) + 'px';
} else {
menuStyle.left = (x - menuPadding) + 'px';
}
// if outside bottom, bottom align it
if (
y + height + chart.exportMenuHeight > chartHeight &&
button.alignOptions.verticalAlign !== 'top'
) {
menuStyle.bottom = (chartHeight - y - menuPadding) + 'px';
} else {
menuStyle.top = (y + height - menuPadding) + 'px';
}
css(menu, menuStyle);
chart.openMenu = true;
},
/**
* Add the export button to the chart, with options.
*
* @private
*/
addButton: function (options) {
var chart = this,
renderer = chart.renderer,
btnOptions = merge(chart.options.navigation.buttonOptions, options),
onclick = btnOptions.onclick,
menuItems = btnOptions.menuItems,
symbol,
button,
symbolSize = btnOptions.symbolSize || 12;
if (!chart.btnCount) {
chart.btnCount = 0;
}
// Keeps references to the button elements
if (!chart.exportDivElements) {
chart.exportDivElements = [];
chart.exportSVGElements = [];
}
if (btnOptions.enabled === false) {
return;
}
var attr = btnOptions.theme,
states = attr.states,
hover = states && states.hover,
select = states && states.select,
callback;
delete attr.states;
if (onclick) {
callback = function (e) {
if (e) {
e.stopPropagation();
}
onclick.call(chart, e);
};
} else if (menuItems) {
callback = function (e) {
// consistent with onclick call (#3495)
if (e) {
e.stopPropagation();
}
chart.contextMenu(
button.menuClassName,
menuItems,
button.translateX,
button.translateY,
button.width,
button.height,
button
);
button.setState(2);
};
}
if (btnOptions.text && btnOptions.symbol) {
attr.paddingLeft = pick(attr.paddingLeft, 25);
} else if (!btnOptions.text) {
extend(attr, {
width: btnOptions.width,
height: btnOptions.height,
padding: 0
});
}
button = renderer
.button(btnOptions.text, 0, 0, callback, attr, hover, select)
.addClass(options.className)
.attr({
title: pick(
chart.options.lang[
btnOptions._titleKey || btnOptions.titleKey
],
''
)
});
button.menuClassName = (
options.menuClassName ||
'highcharts-menu-' + chart.btnCount++
);
if (btnOptions.symbol) {
symbol = renderer.symbol(
btnOptions.symbol,
btnOptions.symbolX - (symbolSize / 2),
btnOptions.symbolY - (symbolSize / 2),
symbolSize,
symbolSize,
// If symbol is an image, scale it (#7957)
{
width: symbolSize,
height: symbolSize
}
)
.addClass('highcharts-button-symbol')
.attr({
zIndex: 1
}).add(button);
}
button.add(chart.exportingGroup)
.align(extend(btnOptions, {
width: button.width,
x: pick(btnOptions.x, chart.buttonOffset) // #1654
}), true, 'spacingBox');
chart.buttonOffset += (
(button.width + btnOptions.buttonSpacing) *
(btnOptions.align === 'right' ? -1 : 1)
);
chart.exportSVGElements.push(button, symbol);
},
/**
* Destroy the export buttons.
*
* @private
*/
destroyExport: function (e) {
var chart = e ? e.target : this,
exportSVGElements = chart.exportSVGElements,
exportDivElements = chart.exportDivElements,
exportEvents = chart.exportEvents,
cacheName;
// Destroy the extra buttons added
if (exportSVGElements) {
each(exportSVGElements, function (elem, i) {
// Destroy and null the svg elements
if (elem) { // #1822
elem.onclick = elem.ontouchstart = null;
cacheName = 'cache-' + elem.menuClassName;
if (chart[cacheName]) {
delete chart[cacheName];
}
chart.exportSVGElements[i] = elem.destroy();
}
});
exportSVGElements.length = 0;
}
// Destroy the exporting group
if (chart.exportingGroup) {
chart.exportingGroup.destroy();
delete chart.exportingGroup;
}
// Destroy the divs for the menu
if (exportDivElements) {
each(exportDivElements, function (elem, i) {
// Remove the event handler
H.clearTimeout(elem.hideTimer); // #5427
removeEvent(elem, 'mouseleave');
// Remove inline events
chart.exportDivElements[i] =
elem.onmouseout =
elem.onmouseover =
elem.ontouchstart =
elem.onclick = null;
// Destroy the div by moving to garbage bin
discardElement(elem);
});
exportDivElements.length = 0;
}
if (exportEvents) {
each(exportEvents, function (unbind) {
unbind();
});
exportEvents.length = 0;
}
}
});
// These ones are translated to attributes rather than styles
SVGRenderer.prototype.inlineToAttributes = [
'fill',
'stroke',
'strokeLinecap',
'strokeLinejoin',
'strokeWidth',
'textAnchor',
'x',
'y'
];
// These CSS properties are not inlined. Remember camelCase.
SVGRenderer.prototype.inlineBlacklist = [
/-/, // In Firefox, both hyphened and camelCased names are listed
/^(clipPath|cssText|d|height|width)$/, // Full words
/^font$/, // more specific props are set
/[lL]ogical(Width|Height)$/,
/perspective/,
/TapHighlightColor/,
/^transition/,
/^length$/ // #7700
// /^text (border|color|cursor|height|webkitBorder)/
];
SVGRenderer.prototype.unstyledElements = [
'clipPath',
'defs',
'desc'
];
/**
* Analyze inherited styles from stylesheets and add them inline
*
* @todo: What are the border styles for text about? In general, text has a lot
* of properties.
* @todo: Make it work with IE9 and IE10.
*/
Chart.prototype.inlineStyles = function () {
var renderer = this.renderer,
inlineToAttributes = renderer.inlineToAttributes,
blacklist = renderer.inlineBlacklist,
whitelist = renderer.inlineWhitelist, // For IE
unstyledElements = renderer.unstyledElements,
defaultStyles = {},
dummySVG,
iframe,
iframeDoc;
// Create an iframe where we read default styles without pollution from this
// body
iframe = doc.createElement('iframe');
css(iframe, {
width: '1px',
height: '1px',
visibility: 'hidden'
});
doc.body.appendChild(iframe);
iframeDoc = iframe.contentWindow.document;
iframeDoc.open();
iframeDoc.write('<svg xmlns="http://www.w3.org/2000/svg"></svg>');
iframeDoc.close();
/**
* Make hyphenated property names out of camelCase
*/
function hyphenate(prop) {
return prop.replace(
/([A-Z])/g,
function (a, b) {
return '-' + b.toLowerCase();
}
);
}
/**
* Call this on all elements and recurse to children
*/
function recurse(node) {
var styles,
parentStyles,
cssText = '',
dummy,
styleAttr,
blacklisted,
whitelisted,
i;
// Check computed styles and whether they are in the white/blacklist for
// styles or atttributes
function filterStyles(val, prop) {
// Check against whitelist & blacklist
blacklisted = whitelisted = false;
if (whitelist) {
// Styled mode in IE has a whitelist instead.
// Exclude all props not in this list.
i = whitelist.length;
while (i-- && !whitelisted) {
whitelisted = whitelist[i].test(prop);
}
blacklisted = !whitelisted;
}
// Explicitly remove empty transforms
if (prop === 'transform' && val === 'none') {
blacklisted = true;
}
i = blacklist.length;
while (i-- && !blacklisted) {
blacklisted = (
blacklist[i].test(prop) ||
typeof val === 'function'
);
}
if (!blacklisted) {
// If parent node has the same style, it gets inherited, no need
// to inline it. Top-level props should be diffed against parent
// (#7687).
if (
(parentStyles[prop] !== val || node.nodeName === 'svg') &&
defaultStyles[node.nodeName][prop] !== val
) {
// Attributes
if (inlineToAttributes.indexOf(prop) !== -1) {
node.setAttribute(hyphenate(prop), val);
// Styles
} else {
cssText += hyphenate(prop) + ':' + val + ';';
}
}
}
}
if (
node.nodeType === 1 &&
unstyledElements.indexOf(node.nodeName) === -1
) {
styles = win.getComputedStyle(node, null);
parentStyles = node.nodeName === 'svg' ?
{} :
win.getComputedStyle(node.parentNode, null);
// Get default styles from the browser so that we don't have to add
// these
if (!defaultStyles[node.nodeName]) {
/*
if (!dummySVG) {
dummySVG = doc.createElementNS(H.SVG_NS, 'svg');
dummySVG.setAttribute('version', '1.1');
doc.body.appendChild(dummySVG);
}
*/
dummySVG = iframeDoc.getElementsByTagName('svg')[0];
dummy = iframeDoc.createElementNS(
node.namespaceURI,
node.nodeName
);
dummySVG.appendChild(dummy);
// Copy, so we can remove the node
defaultStyles[node.nodeName] = merge(
win.getComputedStyle(dummy, null)
);
// Remove default fill, otherwise text disappears when exported
if (node.nodeName === 'text') {
delete defaultStyles.text.fill;
}
dummySVG.removeChild(dummy);
}
// Loop through all styles and add them inline if they are ok
if (isFirefoxBrowser || isMSBrowser) {
// Some browsers put lots of styles on the prototype
for (var p in styles) {
filterStyles(styles[p], p);
}
} else {
objectEach(styles, filterStyles);
}
// Apply styles
if (cssText) {
styleAttr = node.getAttribute('style');
node.setAttribute(
'style',
(styleAttr ? styleAttr + ';' : '') + cssText
);
}
// Set default stroke width (needed at least for IE)
if (node.nodeName === 'svg') {
node.setAttribute('stroke-width', '1px');
}
if (node.nodeName === 'text') {
return;
}
// Recurse
each(node.children || node.childNodes, recurse);
}
}
/**
* Remove the dummy objects used to get defaults
*/
function tearDown() {
dummySVG.parentNode.removeChild(dummySVG);
}
recurse(this.container.querySelector('svg'));
tearDown();
};
symbols.menu = function (x, y, width, height) {
var arr = [
'M', x, y + 2.5,
'L', x + width, y + 2.5,
'M', x, y + height / 2 + 0.5,
'L', x + width, y + height / 2 + 0.5,
'M', x, y + height - 1.5,
'L', x + width, y + height - 1.5
];
return arr;
};
// Add the buttons on chart load
Chart.prototype.renderExporting = function () {
var chart = this,
exportingOptions = chart.options.exporting,
buttons = exportingOptions.buttons,
isDirty = chart.isDirtyExporting || !chart.exportSVGElements;
chart.buttonOffset = 0;
if (chart.isDirtyExporting) {
chart.destroyExport();
}
if (isDirty && exportingOptions.enabled !== false) {
chart.exportEvents = [];
chart.exportingGroup = chart.exportingGroup ||
chart.renderer.g('exporting-group').attr({
zIndex: 3 // #4955, // #8392
}).add();
objectEach(buttons, function (button) {
chart.addButton(button);
});
chart.isDirtyExporting = false;
}
// Destroy the export elements at chart destroy
addEvent(chart, 'destroy', chart.destroyExport);
};
// Add update methods to handle chart.update and chart.exporting.update and
// chart.navigation.update. These must be added to the chart instance rather
// than the Chart prototype in order to use the chart instance inside the update
// function.
addEvent(Chart, 'init', function () {
var chart = this;
function update(prop, options, redraw) {
chart.isDirtyExporting = true;
merge(true, chart.options[prop], options);
if (pick(redraw, true)) {
chart.redraw();
}
}
each(['exporting', 'navigation'], function (prop) {
chart[prop] = {
update: function (options, redraw) {
update(prop, options, redraw);
}
};
});
});
Chart.prototype.callbacks.push(function (chart) {
chart.renderExporting();
addEvent(chart, 'redraw', chart.renderExporting);
// Uncomment this to see a button directly below the chart, for quick
// testing of export
/*
var button, viewImage, viewSource;
if (!chart.renderer.forExport) {
viewImage = function () {
var div = doc.createElement('div');
div.innerHTML = chart.getSVGForExport();
chart.renderTo.parentNode.appendChild(div);
};
viewSource = function () {
var pre = doc.createElement('pre');
pre.innerHTML = chart.getSVGForExport()
.replace(/</g, '\n<')
.replace(/>/g, '>');
chart.renderTo.parentNode.appendChild(pre);
};
viewImage();
// View SVG Image
button = doc.createElement('button');
button.innerHTML = 'View SVG Image';
chart.renderTo.parentNode.appendChild(button);
button.onclick = viewImage;
// View SVG Source
button = doc.createElement('button');
button.innerHTML = 'View SVG Source';
chart.renderTo.parentNode.appendChild(button);
button.onclick = viewSource;
}
//*/
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:dc8631c89d8afb852678d770bac42c3b4e487fbe60893c1e69298224db5747d6
size 720
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
switch (arguments.length) {
case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
}
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from 'angular2/src/core/di';
import { AnimationBuilder } from 'angular2/src/animate/animation_builder';
import { CssAnimationBuilder } from 'angular2/src/animate/css_animation_builder';
import { Animation } from 'angular2/src/animate/animation';
import { BrowserDetails } from 'angular2/src/animate/browser_details';
export let MockAnimationBuilder = class extends AnimationBuilder {
constructor() {
super(null);
}
css() { return new MockCssAnimationBuilder(); }
};
MockAnimationBuilder = __decorate([
Injectable(),
__metadata('design:paramtypes', [])
], MockAnimationBuilder);
class MockCssAnimationBuilder extends CssAnimationBuilder {
constructor() {
super(null);
}
start(element) { return new MockAnimation(element, this.data); }
}
class MockBrowserAbstraction extends BrowserDetails {
doesElapsedTimeIncludesDelay() { this.elapsedTimeIncludesDelay = false; }
}
class MockAnimation extends Animation {
constructor(element, data) {
super(element, data, new MockBrowserAbstraction());
}
wait(callback) { this._callback = callback; }
flush() {
this._callback(0);
this._callback = null;
}
}
//# sourceMappingURL=animation_builder_mock.js.map |
/** @license React v16.3.0-alpha.1
* react-dom-test-utils.production.min.js
*
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';(function(m,p){"object"===typeof exports&&"undefined"!==typeof module?module.exports=p(require("react"),require("react-dom")):"function"===typeof define&&define.amd?define(["react","react-dom"],p):m.ReactTestUtils=p(m.React,m.ReactDOM)})(this,function(m,p){function k(a){for(var b=arguments.length-1,c="Minified React error #"+a+"; visit http://facebook.github.io/react/docs/error-decoder.html?invariant\x3d"+a,f=0;f<b;f++)c+="\x26args[]\x3d"+encodeURIComponent(arguments[f+1]);b=Error(c+
" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.");b.name="Invariant Violation";b.framesToPop=1;throw b;}function v(a){return function(){return a}}function A(a){var b=a;if(a.alternate)for(;b["return"];)b=b["return"];else{if(0!==(b.effectTag&2))return 1;for(;b["return"];)if(b=b["return"],0!==(b.effectTag&2))return 1}return 3===b.tag?2:3}function B(a){2!==A(a)?k("188"):void 0}function J(a){var b=a.alternate;if(!b)return b=A(a),3===b?k("188"):
void 0,1===b?null:a;for(var c=a,f=b;;){var g=c["return"],e=g?g.alternate:null;if(!g||!e)break;if(g.child===e.child){for(var d=g.child;d;){if(d===c)return B(g),a;if(d===f)return B(g),b;d=d.sibling}k("188")}if(c["return"]!==f["return"])c=g,f=e;else{d=!1;for(var l=g.child;l;){if(l===c){d=!0;c=g;f=e;break}if(l===f){d=!0;f=g;c=e;break}l=l.sibling}if(!d){for(l=e.child;l;){if(l===c){d=!0;c=e;f=g;break}if(l===f){d=!0;f=e;c=g;break}l=l.sibling}d?void 0:k("189")}}c.alternate!==f?k("190"):void 0}3!==c.tag?k("188"):
void 0;return c.stateNode.current===c?a:b}function r(a,b,c,f){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var d in a)a.hasOwnProperty(d)&&((b=a[d])?this[d]=b(c):"target"===d?this.target=f:this[d]=c[d]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?n.thatReturnsTrue:n.thatReturnsFalse;this.isPropagationStopped=n.thatReturnsFalse;return this}function K(a,b,c,f){if(this.eventPool.length){var d=this.eventPool.pop();
this.call(d,a,b,c,f);return d}return new this(a,b,c,f)}function L(a){a instanceof this?void 0:k("223");a.destructor();10>this.eventPool.length&&this.eventPool.push(a)}function C(a){a.eventPool=[];a.getPooled=K;a.release=L}function w(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;c["ms"+a]="MS"+b;c["O"+a]="o"+b.toLowerCase();return c}function x(a){if(y[a])return y[a];if(!h[a])return a;var b=h[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in D)return y[a]=b[c];
return a}function E(a){}function M(a,b){if(!a)return[];a=J(a);if(!a)return[];for(var c=a,d=[];;){if(5===c.tag||6===c.tag||2===c.tag||1===c.tag){var e=c.stateNode;b(e)&&d.push(e)}if(c.child)c.child["return"]=c,c=c.child;else{if(c===a)return d;for(;!c.sibling;){if(!c["return"]||c["return"]===a)return d;c=c["return"]}c.sibling["return"]=c["return"];c=c.sibling}}}function N(a){return function(b,c){m.isValidElement(b)?k("228"):void 0;e.isCompositeComponent(b)?k("229"):void 0;var d=F.eventNameDispatchConfigs[a],
g=new E;g.target=b;g.type=a.toLowerCase();var n=O.getInstanceFromNode(b),h=new r(d,n,g,b);h.persist();t(h,c);d.phasedRegistrationNames?G.accumulateTwoPhaseDispatches(h):G.accumulateDirectDispatches(h);p.unstable_batchedUpdates(function(){H.enqueueStateRestore(b);u.runEventsInBatch(h,!0)});H.restoreStateIfNeeded()}}function z(){e.Simulate={};var a=void 0;for(a in F.eventNameDispatchConfigs)e.Simulate[a]=N(a)}function P(a){return function(b,c){var d=new E(a);t(d,c);e.isDOMComponent(b)?e.simulateNativeEventOnDOMComponent(a,
b,d):b.tagName&&e.simulateNativeEventOnNode(a,b,d)}}var t=m.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.assign,d=function(){};d.thatReturns=v;d.thatReturnsFalse=v(!1);d.thatReturnsTrue=v(!0);d.thatReturnsNull=v(null);d.thatReturnsThis=function(){return this};d.thatReturnsArgument=function(a){return a};var n=d,I="dispatchConfig _targetInst nativeEvent isDefaultPrevented isPropagationStopped _dispatchListeners _dispatchInstances".split(" ");d={type:null,target:null,currentTarget:n.thatReturnsNull,
eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};t(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=n.thatReturnsTrue)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=
!0),this.isPropagationStopped=n.thatReturnsTrue)},persist:function(){this.isPersistent=n.thatReturnsTrue},isPersistent:n.thatReturnsFalse,destructor:function(){var a=this.constructor.Interface,b;for(b in a)this[b]=null;for(a=0;a<I.length;a++)this[I[a]]=null}});r.Interface=d;r.extend=function(a){function b(){return c.apply(this,arguments)}var c=this,d=function(){};d.prototype=c.prototype;d=new d;t(d,b.prototype);b.prototype=d;b.prototype.constructor=b;b.Interface=t({},c.Interface,a);b.extend=c.extend;
C(b);return b};C(r);d=!("undefined"===typeof window||!window.document||!window.document.createElement);var h={animationend:w("Animation","AnimationEnd"),animationiteration:w("Animation","AnimationIteration"),animationstart:w("Animation","AnimationStart"),transitionend:w("Transition","TransitionEnd")},y={},D={};d&&(D=document.createElement("div").style,"AnimationEvent"in window||(delete h.animationend.animation,delete h.animationiteration.animation,delete h.animationstart.animation),"TransitionEvent"in
window||delete h.transitionend.transition);d={topAnimationEnd:x("animationend"),topAnimationIteration:x("animationiteration"),topAnimationStart:x("animationstart"),topBlur:"blur",topCancel:"cancel",topChange:"change",topClick:"click",topClose:"close",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",
topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoad:"load",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topToggle:"toggle",topTouchCancel:"touchcancel",
topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topTransitionEnd:x("transitionend"),topWheel:"wheel"};var Q=p.findDOMNode,q=p.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,u=q.EventPluginHub,F=q.EventPluginRegistry,G=q.EventPropagators,H=q.ReactControlledComponent,O=q.ReactDOMComponentTree,R=q.ReactDOMEventListener,e={renderIntoDocument:function(a){var b=document.createElement("div");return p.render(a,b)},isElement:function(a){return m.isValidElement(a)},isElementOfType:function(a,
b){return m.isValidElement(a)&&a.type===b},isDOMComponent:function(a){return!(!a||1!==a.nodeType||!a.tagName)},isDOMComponentElement:function(a){return!!(a&&m.isValidElement(a)&&a.tagName)},isCompositeComponent:function(a){return e.isDOMComponent(a)?!1:null!=a&&"function"===typeof a.render&&"function"===typeof a.setState},isCompositeComponentWithType:function(a,b){return e.isCompositeComponent(a)?a._reactInternalFiber.type===b:!1},findAllInRenderedTree:function(a,b){if(!a)return[];e.isCompositeComponent(a)?
void 0:k("10");return M(a._reactInternalFiber,b)},scryRenderedDOMComponentsWithClass:function(a,b){return e.findAllInRenderedTree(a,function(a){if(e.isDOMComponent(a)){var c=a.className;"string"!==typeof c&&(c=a.getAttribute("class")||"");var d=c.split(/\s+/);Array.isArray(b)||(void 0===b?k("11"):void 0,b=b.split(/\s+/));return b.every(function(a){return-1!==d.indexOf(a)})}return!1})},findRenderedDOMComponentWithClass:function(a,b){a=e.scryRenderedDOMComponentsWithClass(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+
a.length+") for class:"+b);return a[0]},scryRenderedDOMComponentsWithTag:function(a,b){return e.findAllInRenderedTree(a,function(a){return e.isDOMComponent(a)&&a.tagName.toUpperCase()===b.toUpperCase()})},findRenderedDOMComponentWithTag:function(a,b){a=e.scryRenderedDOMComponentsWithTag(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+a.length+") for tag:"+b);return a[0]},scryRenderedComponentsWithType:function(a,b){return e.findAllInRenderedTree(a,function(a){return e.isCompositeComponentWithType(a,
b)})},findRenderedComponentWithType:function(a,b){a=e.scryRenderedComponentsWithType(a,b);if(1!==a.length)throw Error("Did not find exactly one match (found: "+a.length+") for componentType:"+b);return a[0]},mockComponent:function(a,b){b=b||a.mockTagName||"div";a.prototype.render.mockImplementation(function(){return m.createElement(b,null,this.props.children)});return this},simulateNativeEventOnNode:function(a,b,c){c.target=b;R.dispatchEvent(a,c)},simulateNativeEventOnDOMComponent:function(a,b,c){e.simulateNativeEventOnNode(a,
Q(b),c)},nativeTouchData:function(a,b){return{touches:[{pageX:a,pageY:b}]}},Simulate:null,SimulateNative:{}},S=u.injection.injectEventPluginOrder;u.injection.injectEventPluginOrder=function(){S.apply(this,arguments);z()};var T=u.injection.injectEventPluginsByName;u.injection.injectEventPluginsByName=function(){T.apply(this,arguments);z()};z();[].concat(Object.keys(d),Object.keys({topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",
topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"})).forEach(function(a){var b=0===a.indexOf("top")?a.charAt(3).toLowerCase()+a.substr(4):a;e.SimulateNative[b]=
P(a)});d=(d=Object.freeze({default:e}))&&e||d;return d["default"]?d["default"]:d});
|
module.exports={A:{A:{"1":"B A","2":"J C G E VB"},B:{"1":"D Y g H L"},C:{"1":"0 1 3 4 5 6 L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s x y u t","2":"TB z RB QB","33":"I J C G E B A D Y g H","164":"F"},D:{"1":"0 1 3 4 5 6 V W X v Z a b c d e f K h i j k l m n o p q r s x y u t FB AB CB UB DB","33":"F I J C G E B A D Y g H L M N O P Q R S T U"},E:{"1":"C G E B A HB IB JB KB LB","33":"J GB","164":"9 F I EB"},F:{"1":"H L M N O P Q R S T U V W X v Z a b c d e f K h i j k l m n o p q r s w","2":"E MB NB","33":"D","164":"7 8 A OB PB SB"},G:{"1":"G A YB ZB aB bB cB dB","33":"XB","164":"2 9 BB WB"},H:{"2":"eB"},I:{"1":"t jB kB","33":"2 z F fB gB hB iB"},J:{"1":"B","33":"C"},K:{"1":"K w","33":"D","164":"7 8 B A"},L:{"1":"AB"},M:{"1":"u"},N:{"1":"B A"},O:{"1":"lB"},P:{"1":"F I"},Q:{"1":"mB"},R:{"1":"nB"}},B:5,C:"CSS3 Transitions"};
|
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Copyright 2009 Google Inc.
// All Rights Reserved
/**
* @fileoverview File #2 of module A.
*/
goog.require('goog.module.ModuleManager');
goog.module.ModuleManager.getInstance().setLoaded('modA');
|
(function($, QUnit){
'use strict';
QUnit.module('utility');
var util = $.smoothStateUtility;
/**
* Checks to see if the url is external
*/
QUnit.test( 'isExternal', function( assert ) {
var externalUrls = [
'http://www.google.com',
'//www.google.com',
'//google.com',
'//google.com#hash'
],
internalUrls = [
'index.html',
'/index.html',
'/index.html#hash',
'#hash'
],
i, y;
// Is external
for (i = externalUrls.length - 1; i >= 0; i--) {
assert.ok( util.isExternal(externalUrls[i]) === true, 'External: ' + externalUrls[i] );
}
// Is not external
for ( y = internalUrls.length - 1; y >= 0; y--) {
assert.ok( util.isExternal(internalUrls[y]) === false, 'Internal: ' + internalUrls[y] );
}
});
/**
* Checks to see if the url is a hash to the same page
*/
QUnit.test( 'stripHash', function( assert ) {
var hashes = [
'/index.html#hash',
'/index.html'
];
assert.equal( util.stripHash(hashes[0]), hashes[1], 'Stripped the hash from a url' );
assert.equal( util.stripHash(hashes[1]), hashes[1], 'Url that had no hash stayed the same' );
});
/**
* Checks to see if the url is a hash to the same page
*/
QUnit.test( 'isHash', function( assert ) {
var hashes = [
$('<a href="#foo" />').prop('href'),
$('<a href="' + window.location.href + '#foo" />').prop('href')
],
nonHashes = [
$('<a href="/other/page.html" />').prop('href'),
$('<a href="/other/page.html#foo" />').prop('href'),
$('<a href="/other/page.html#bar" />').prop('href')
],
i, y;
// Is external
for (i = hashes.length - 1; i >= 0; i--) {
assert.ok( util.isHash(hashes[i]) === true, 'Hash: ' + hashes[i] );
}
// Is not external
for ( y = nonHashes.length - 1; y >= 0; y--) {
assert.ok( util.isHash(nonHashes[y]) === false, 'Non hash: ' + nonHashes[y] );
}
// Passing in current href
assert.ok( util.isHash(nonHashes[1], nonHashes[0]) === true, 'Passed in current href' );
// After having clicked on a previous hash
assert.ok( util.isHash(nonHashes[1], nonHashes[2]) === true, 'Clicked on a hash when a hash is in the current url' );
});
/**
* Translates a url string into a $.ajax settings obj
*/
QUnit.test( 'translate', function( assert ) {
var expectedObject = JSON.stringify({
dataType: 'html',
type: 'GET',
url: 'hello.html'
});
assert.equal( JSON.stringify(util.translate('hello.html')), expectedObject, 'Turned string into request object' );
assert.equal( JSON.stringify(util.translate({ url: 'hello.html' })), expectedObject, 'Maintained original request object' );
assert.notEqual( JSON.stringify(util.translate({ url: 'hello.html', type: 'POST' })), expectedObject, 'Does not override set params' );
});
/**
* Checks to see if we should be loading this URL
*/
QUnit.test( 'shouldLoadAnchor', function( assert ) {
var blacklist = '.no-smoothState, [target]',
badAnchors = [
$('<a href="intex.html" class="no-smoothState"/>'),
$('<a href="index.html" target="_blank" />'),
$('<a href="//google.com" />'),
$('<a href="#hash" />'),
$('<a href="' + window.location.href + '#hash" />')
],
goodAnchors = [
$('<a href="index.html" />'),
$('<a href="/index.html#foo" />'),
$('<a href="/index.html" />')
],
i, y;
// Invalid anchors
for (i = badAnchors.length - 1; i >= 0; i--) {
assert.ok( util.shouldLoadAnchor(badAnchors[i], blacklist) === false, 'Bad: ' + $('<div/>').append(badAnchors[i]).html() );
}
// Valid anchors
for ( y = goodAnchors.length - 1; y >= 0; y--) {
assert.ok( util.shouldLoadAnchor(goodAnchors[y], blacklist) === true, 'Good: ' + $('<div/>').append(goodAnchors[y]).html() );
}
});
/**
* Resets an object if it has too many properties
*/
QUnit.test( 'clearIfOverCapacity', function( assert ) {
var capacity = 2,
objOver = util.clearIfOverCapacity({ '1':1, '2':2, '3':3 }, capacity),
objEq = util.clearIfOverCapacity({ '1':1, '2':2 }, capacity),
objUnder = util.clearIfOverCapacity({ '1':1 }, capacity);
assert.ok( Object.keys(objOver).length === 0, 'Is a blank object' );
assert.ok( Object.keys(objEq).length === 2, 'Returns the same object' );
assert.ok( Object.keys(objUnder).length === 1, 'Returns the same object' );
});
/**
* Stores html content as jquery object in given object
*/
QUnit.test( 'storePageIn', function( assert ) {
var url = window.location.href,
title = 'Test title ' + Math.random(),
$html = '<!doctype html> <html> <head> <title>' + title + '</title> </head> <body id="main"> <div> Content <svg><title>svg title</title></svg></div> </body> </html>',
cache = {};
util.storePageIn(cache, url, $html);
assert.ok( cache.hasOwnProperty(url), 'Correct entry was made' );
assert.ok( cache[url].title === title, 'Title was stored properly' );
assert.ok( cache[url].status === 'loaded', 'Status was set to "loaded"' );
assert.ok( cache[url].html instanceof jQuery, 'Html is a jquery object' );
});
/**
* Triggers an 'allanimationend' event when all animations are complete
*/
QUnit.test( 'triggerAllAnimationEndEvent', function( assert ) {
var $elem = $('<div/>'),
triggered = false;
$elem.on('allanimationend', function(){
triggered = true;
});
util.triggerAllAnimationEndEvent($elem);
$elem.trigger('animationstart').trigger('animationend');
assert.ok( triggered, 'allanimationend fired' );
});
})(jQuery, QUnit);
|
#!/usr/bin/env node
'use strict';
const {exec, spawn} = require('child-process-promise');
const {join} = require('path');
const {readFileSync} = require('fs');
const theme = require('./theme');
const {logPromise, printDiff} = require('./utils');
const cwd = join(__dirname, '..', '..');
const CIRCLE_CI_BUILD = 12707;
const COMMIT = 'b3d1a81a9';
const VERSION = '1.2.3';
const run = async () => {
const defaultOptions = {
cwd,
env: process.env,
};
try {
// Start with a known build/revision:
// https://circleci.com/gh/facebook/react/12707
let promise = spawn(
'node',
[
'./scripts/release/prepare-release-from-ci.js',
`--build=${CIRCLE_CI_BUILD}`,
],
defaultOptions
);
logPromise(
promise,
theme`Checking out "next" build {version ${CIRCLE_CI_BUILD}}`
);
await promise;
// Upgrade the above build top a known React version.
// Note that using the --local flag skips NPM checkout.
// This isn't totally necessary but is useful if we want to test an unpublished "next" build.
promise = spawn(
'node',
[
'./scripts/release/prepare-release-from-npm.js',
`--version=0.0.0-${COMMIT}`,
'--local',
],
defaultOptions
);
promise.childProcess.stdin.setEncoding('utf-8');
promise.childProcess.stdout.setEncoding('utf-8');
promise.childProcess.stdout.on('data', data => {
if (data.includes('✓ Version for')) {
// Update all packages to a stable version
promise.childProcess.stdin.write(VERSION);
} else if (data.includes('(y/N)')) {
// Accept all of the confirmation prompts
promise.childProcess.stdin.write('y');
}
});
logPromise(promise, theme`Preparing stable release {version ${VERSION}}`);
await promise;
const beforeContents = readFileSync(
join(cwd, 'scripts/release/snapshot-test.snapshot'),
'utf-8'
);
await exec('cp build/temp.diff scripts/release/snapshot-test.snapshot', {
cwd,
});
const afterContents = readFileSync(
join(cwd, 'scripts/release/snapshot-test.snapshot'),
'utf-8'
);
if (beforeContents === afterContents) {
console.log(theme.header`Snapshot test passed.`);
} else {
printDiff(
'scripts/release/snapshot-test.snapshot',
beforeContents,
afterContents
);
console.log();
console.error(theme.error('Snapshot test failed!'));
console.log();
console.log(
'If this failure was expected, please update the contents of the snapshot file:'
);
console.log(
theme` {command git add} {path scripts/release/snapshot-test.snapshot}`
);
console.log(
theme` {command git commit -m "Updating release script snapshot file."}`
);
process.exit(1);
}
} catch (error) {
console.error(theme.error(error));
process.exit(1);
}
};
run();
|
ace.define("ace/ext/searchbox",["require","exports","module","ace/lib/dom","ace/lib/lang","ace/lib/event","ace/keyboard/hash_handler","ace/lib/keys"], function(acequire, exports, module) {
"use strict";
var dom = acequire("../lib/dom");
var lang = acequire("../lib/lang");
var event = acequire("../lib/event");
var searchboxCss = "\
.ace_search {\
background-color: #ddd;\
border: 1px solid #cbcbcb;\
border-top: 0 none;\
max-width: 325px;\
overflow: hidden;\
margin: 0;\
padding: 4px;\
padding-right: 6px;\
padding-bottom: 0;\
position: absolute;\
top: 0px;\
z-index: 99;\
white-space: normal;\
}\
.ace_search.left {\
border-left: 0 none;\
border-radius: 0px 0px 5px 0px;\
left: 0;\
}\
.ace_search.right {\
border-radius: 0px 0px 0px 5px;\
border-right: 0 none;\
right: 0;\
}\
.ace_search_form, .ace_replace_form {\
border-radius: 3px;\
border: 1px solid #cbcbcb;\
float: left;\
margin-bottom: 4px;\
overflow: hidden;\
}\
.ace_search_form.ace_nomatch {\
outline: 1px solid red;\
}\
.ace_search_field {\
background-color: white;\
border-right: 1px solid #cbcbcb;\
border: 0 none;\
-webkit-box-sizing: border-box;\
-moz-box-sizing: border-box;\
box-sizing: border-box;\
float: left;\
height: 22px;\
outline: 0;\
padding: 0 7px;\
width: 214px;\
margin: 0;\
}\
.ace_searchbtn,\
.ace_replacebtn {\
background: #fff;\
border: 0 none;\
border-left: 1px solid #dcdcdc;\
cursor: pointer;\
float: left;\
height: 22px;\
margin: 0;\
padding: 0;\
position: relative;\
}\
.ace_searchbtn:last-child,\
.ace_replacebtn:last-child {\
border-top-right-radius: 3px;\
border-bottom-right-radius: 3px;\
}\
.ace_searchbtn:disabled {\
background: none;\
cursor: default;\
}\
.ace_searchbtn {\
background-position: 50% 50%;\
background-repeat: no-repeat;\
width: 27px;\
}\
.ace_searchbtn.prev {\
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADFJREFUeNpiSU1NZUAC/6E0I0yACYskCpsJiySKIiY0SUZk40FyTEgCjGgKwTRAgAEAQJUIPCE+qfkAAAAASUVORK5CYII=); \
}\
.ace_searchbtn.next {\
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAFCAYAAAB4ka1VAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAADRJREFUeNpiTE1NZQCC/0DMyIAKwGJMUAYDEo3M/s+EpvM/mkKwCQxYjIeLMaELoLMBAgwAU7UJObTKsvAAAAAASUVORK5CYII=); \
}\
.ace_searchbtn_close {\
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAcCAYAAABRVo5BAAAAZ0lEQVR42u2SUQrAMAhDvazn8OjZBilCkYVVxiis8H4CT0VrAJb4WHT3C5xU2a2IQZXJjiQIRMdkEoJ5Q2yMqpfDIo+XY4k6h+YXOyKqTIj5REaxloNAd0xiKmAtsTHqW8sR2W5f7gCu5nWFUpVjZwAAAABJRU5ErkJggg==) no-repeat 50% 0;\
border-radius: 50%;\
border: 0 none;\
color: #656565;\
cursor: pointer;\
float: right;\
font: 16px/16px Arial;\
height: 14px;\
margin: 5px 1px 9px 5px;\
padding: 0;\
text-align: center;\
width: 14px;\
}\
.ace_searchbtn_close:hover {\
background-color: #656565;\
background-position: 50% 100%;\
color: white;\
}\
.ace_replacebtn.prev {\
width: 54px\
}\
.ace_replacebtn.next {\
width: 27px\
}\
.ace_button {\
margin-left: 2px;\
cursor: pointer;\
-webkit-user-select: none;\
-moz-user-select: none;\
-o-user-select: none;\
-ms-user-select: none;\
user-select: none;\
overflow: hidden;\
opacity: 0.7;\
border: 1px solid rgba(100,100,100,0.23);\
padding: 1px;\
-moz-box-sizing: border-box;\
box-sizing: border-box;\
color: black;\
}\
.ace_button:hover {\
background-color: #eee;\
opacity:1;\
}\
.ace_button:active {\
background-color: #ddd;\
}\
.ace_button.checked {\
border-color: #3399ff;\
opacity:1;\
}\
.ace_search_options{\
margin-bottom: 3px;\
text-align: right;\
-webkit-user-select: none;\
-moz-user-select: none;\
-o-user-select: none;\
-ms-user-select: none;\
user-select: none;\
}";
var HashHandler = acequire("../keyboard/hash_handler").HashHandler;
var keyUtil = acequire("../lib/keys");
dom.importCssString(searchboxCss, "ace_searchbox");
var html = '<div class="ace_search right">\
<button type="button" action="hide" class="ace_searchbtn_close"></button>\
<div class="ace_search_form">\
<input class="ace_search_field" placeholder="Search for" spellcheck="false"></input>\
<button type="button" action="findNext" class="ace_searchbtn next"></button>\
<button type="button" action="findPrev" class="ace_searchbtn prev"></button>\
<button type="button" action="findAll" class="ace_searchbtn" title="Alt-Enter">All</button>\
</div>\
<div class="ace_replace_form">\
<input class="ace_search_field" placeholder="Replace with" spellcheck="false"></input>\
<button type="button" action="replaceAndFindNext" class="ace_replacebtn">Replace</button>\
<button type="button" action="replaceAll" class="ace_replacebtn">All</button>\
</div>\
<div class="ace_search_options">\
<span action="toggleRegexpMode" class="ace_button" title="RegExp Search">.*</span>\
<span action="toggleCaseSensitive" class="ace_button" title="CaseSensitive Search">Aa</span>\
<span action="toggleWholeWords" class="ace_button" title="Whole Word Search">\\b</span>\
</div>\
</div>'.replace(/>\s+/g, ">");
var SearchBox = function(editor, range, showReplaceForm) {
var div = dom.createElement("div");
div.innerHTML = html;
this.element = div.firstChild;
this.$init();
this.setEditor(editor);
};
(function() {
this.setEditor = function(editor) {
editor.searchBox = this;
editor.container.appendChild(this.element);
this.editor = editor;
};
this.$initElements = function(sb) {
this.searchBox = sb.querySelector(".ace_search_form");
this.replaceBox = sb.querySelector(".ace_replace_form");
this.searchOptions = sb.querySelector(".ace_search_options");
this.regExpOption = sb.querySelector("[action=toggleRegexpMode]");
this.caseSensitiveOption = sb.querySelector("[action=toggleCaseSensitive]");
this.wholeWordOption = sb.querySelector("[action=toggleWholeWords]");
this.searchInput = this.searchBox.querySelector(".ace_search_field");
this.replaceInput = this.replaceBox.querySelector(".ace_search_field");
};
this.$init = function() {
var sb = this.element;
this.$initElements(sb);
var _this = this;
event.addListener(sb, "mousedown", function(e) {
setTimeout(function(){
_this.activeInput.focus();
}, 0);
event.stopPropagation(e);
});
event.addListener(sb, "click", function(e) {
var t = e.target || e.srcElement;
var action = t.getAttribute("action");
if (action && _this[action])
_this[action]();
else if (_this.$searchBarKb.commands[action])
_this.$searchBarKb.commands[action].exec(_this);
event.stopPropagation(e);
});
event.addCommandKeyListener(sb, function(e, hashId, keyCode) {
var keyString = keyUtil.keyCodeToString(keyCode);
var command = _this.$searchBarKb.findKeyCommand(hashId, keyString);
if (command && command.exec) {
command.exec(_this);
event.stopEvent(e);
}
});
this.$onChange = lang.delayedCall(function() {
_this.find(false, false);
});
event.addListener(this.searchInput, "input", function() {
_this.$onChange.schedule(20);
});
event.addListener(this.searchInput, "focus", function() {
_this.activeInput = _this.searchInput;
_this.searchInput.value && _this.highlight();
});
event.addListener(this.replaceInput, "focus", function() {
_this.activeInput = _this.replaceInput;
_this.searchInput.value && _this.highlight();
});
};
this.$closeSearchBarKb = new HashHandler([{
bindKey: "Esc",
name: "closeSearchBar",
exec: function(editor) {
editor.searchBox.hide();
}
}]);
this.$searchBarKb = new HashHandler();
this.$searchBarKb.bindKeys({
"Ctrl-f|Command-f|Ctrl-H|Command-Option-F": function(sb) {
var isReplace = sb.isReplace = !sb.isReplace;
sb.replaceBox.style.display = isReplace ? "" : "none";
sb[isReplace ? "replaceInput" : "searchInput"].focus();
},
"Ctrl-G|Command-G": function(sb) {
sb.findNext();
},
"Ctrl-Shift-G|Command-Shift-G": function(sb) {
sb.findPrev();
},
"esc": function(sb) {
setTimeout(function() { sb.hide();});
},
"Return": function(sb) {
if (sb.activeInput == sb.replaceInput)
sb.replace();
sb.findNext();
},
"Shift-Return": function(sb) {
if (sb.activeInput == sb.replaceInput)
sb.replace();
sb.findPrev();
},
"Alt-Return": function(sb) {
if (sb.activeInput == sb.replaceInput)
sb.replaceAll();
sb.findAll();
},
"Tab": function(sb) {
(sb.activeInput == sb.replaceInput ? sb.searchInput : sb.replaceInput).focus();
}
});
this.$searchBarKb.addCommands([{
name: "toggleRegexpMode",
bindKey: {win: "Alt-R|Alt-/", mac: "Ctrl-Alt-R|Ctrl-Alt-/"},
exec: function(sb) {
sb.regExpOption.checked = !sb.regExpOption.checked;
sb.$syncOptions();
}
}, {
name: "toggleCaseSensitive",
bindKey: {win: "Alt-C|Alt-I", mac: "Ctrl-Alt-R|Ctrl-Alt-I"},
exec: function(sb) {
sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked;
sb.$syncOptions();
}
}, {
name: "toggleWholeWords",
bindKey: {win: "Alt-B|Alt-W", mac: "Ctrl-Alt-B|Ctrl-Alt-W"},
exec: function(sb) {
sb.wholeWordOption.checked = !sb.wholeWordOption.checked;
sb.$syncOptions();
}
}]);
this.$syncOptions = function() {
dom.setCssClass(this.regExpOption, "checked", this.regExpOption.checked);
dom.setCssClass(this.wholeWordOption, "checked", this.wholeWordOption.checked);
dom.setCssClass(this.caseSensitiveOption, "checked", this.caseSensitiveOption.checked);
this.find(false, false);
};
this.highlight = function(re) {
this.editor.session.highlight(re || this.editor.$search.$options.re);
this.editor.renderer.updateBackMarkers()
};
this.find = function(skipCurrent, backwards) {
var range = this.editor.find(this.searchInput.value, {
skipCurrent: skipCurrent,
backwards: backwards,
wrap: true,
regExp: this.regExpOption.checked,
caseSensitive: this.caseSensitiveOption.checked,
wholeWord: this.wholeWordOption.checked
});
var noMatch = !range && this.searchInput.value;
dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
this.editor._emit("findSearchBox", { match: !noMatch });
this.highlight();
};
this.findNext = function() {
this.find(true, false);
};
this.findPrev = function() {
this.find(true, true);
};
this.findAll = function(){
var range = this.editor.findAll(this.searchInput.value, {
regExp: this.regExpOption.checked,
caseSensitive: this.caseSensitiveOption.checked,
wholeWord: this.wholeWordOption.checked
});
var noMatch = !range && this.searchInput.value;
dom.setCssClass(this.searchBox, "ace_nomatch", noMatch);
this.editor._emit("findSearchBox", { match: !noMatch });
this.highlight();
this.hide();
};
this.replace = function() {
if (!this.editor.getReadOnly())
this.editor.replace(this.replaceInput.value);
};
this.replaceAndFindNext = function() {
if (!this.editor.getReadOnly()) {
this.editor.replace(this.replaceInput.value);
this.findNext()
}
};
this.replaceAll = function() {
if (!this.editor.getReadOnly())
this.editor.replaceAll(this.replaceInput.value);
};
this.hide = function() {
this.element.style.display = "none";
this.editor.keyBinding.removeKeyboardHandler(this.$closeSearchBarKb);
this.editor.focus();
};
this.show = function(value, isReplace) {
this.element.style.display = "";
this.replaceBox.style.display = isReplace ? "" : "none";
this.isReplace = isReplace;
if (value)
this.searchInput.value = value;
this.searchInput.focus();
this.searchInput.select();
this.editor.keyBinding.addKeyboardHandler(this.$closeSearchBarKb);
};
this.isFocused = function() {
var el = document.activeElement;
return el == this.searchInput || el == this.replaceInput;
}
}).call(SearchBox.prototype);
exports.SearchBox = SearchBox;
exports.Search = function(editor, isReplace) {
var sb = editor.searchBox || new SearchBox(editor);
sb.show(editor.session.getTextRange(), isReplace);
};
});
ace.define("ace/ext/old_ie",["require","exports","module","ace/lib/useragent","ace/tokenizer","ace/ext/searchbox","ace/mode/text"], function(acequire, exports, module) {
"use strict";
var MAX_TOKEN_COUNT = 1000;
var useragent = acequire("../lib/useragent");
var TokenizerModule = acequire("../tokenizer");
function patch(obj, name, regexp, replacement) {
eval("obj['" + name + "']=" + obj[name].toString().replace(
regexp, replacement
));
}
if (useragent.isIE && useragent.isIE < 10 && window.top.document.compatMode === "BackCompat")
useragent.isOldIE = true;
if (typeof document != "undefined" && !document.documentElement.querySelector) {
useragent.isOldIE = true;
var qs = function(el, selector) {
if (selector.charAt(0) == ".") {
var classNeme = selector.slice(1);
} else {
var m = selector.match(/(\w+)=(\w+)/);
var attr = m && m[1];
var attrVal = m && m[2];
}
for (var i = 0; i < el.all.length; i++) {
var ch = el.all[i];
if (classNeme) {
if (ch.className.indexOf(classNeme) != -1)
return ch;
} else if (attr) {
if (ch.getAttribute(attr) == attrVal)
return ch;
}
}
};
var sb = acequire("./searchbox").SearchBox.prototype;
patch(
sb, "$initElements",
/([^\s=]*).querySelector\((".*?")\)/g,
"qs($1, $2)"
);
}
var compliantExecNpcg = /()??/.exec("")[1] === undefined;
if (compliantExecNpcg)
return;
var proto = TokenizerModule.Tokenizer.prototype;
TokenizerModule.Tokenizer_orig = TokenizerModule.Tokenizer;
proto.getLineTokens_orig = proto.getLineTokens;
patch(
TokenizerModule, "Tokenizer",
"ruleRegExps.push(adjustedregex);\n",
function(m) {
return m + '\
if (state[i].next && RegExp(adjustedregex).test(""))\n\
rule._qre = RegExp(adjustedregex, "g");\n\
';
}
);
TokenizerModule.Tokenizer.prototype = proto;
patch(
proto, "getLineTokens",
/if \(match\[i \+ 1\] === undefined\)\s*continue;/,
"if (!match[i + 1]) {\n\
if (value)continue;\n\
var qre = state[mapping[i]]._qre;\n\
if (!qre) continue;\n\
qre.lastIndex = lastIndex;\n\
if (!qre.exec(line) || qre.lastIndex != lastIndex)\n\
continue;\n\
}"
);
patch(
acequire("../mode/text").Mode.prototype, "getTokenizer",
/Tokenizer/,
"TokenizerModule.Tokenizer"
);
useragent.isOldIE = true;
});
(function() {
ace.acequire(["ace/ext/old_ie"], function() {});
})();
|
dojo.provide("dojo.testsDOH._base._loader.hostenv_rhino"),tests.register("testsDOH._base._loader.hostenv_rhino",[function(e){var t=dojo.moduleUrl("testsDOH._base._loader","getText.txt"),t=(t=new String(readText(t))).replace(/[\r\n]+$/,"");e.assertEqual("dojo._getText() test data",t)}]); |
define("ace/snippets/apache_conf",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText = "";
exports.scope = "apache_conf";
});
(function() {
window.require(["ace/snippets/apache_conf"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
module.exports={A:{A:{"1":"C G E B A","2":"UB","8":"J"},B:{"1":"D X g H L"},C:{"1":"0 1 2 4 5 SB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s QB PB"},D:{"1":"0 1 4 5 8 F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s EB BB TB CB"},E:{"1":"9 F I J C G E B A DB FB GB HB IB JB KB"},F:{"1":"6 7 E A D H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r LB MB NB OB RB y"},G:{"1":"G A YB ZB aB bB cB","2":"3 9 AB","132":"VB WB XB"},H:{"2":"dB"},I:{"1":"2 s iB jB","260":"eB fB gB","513":"3 F hB"},J:{"1":"C B"},K:{"1":"6 7 B A D K y"},L:{"1":"8"},M:{"1":"t"},N:{"1":"B A"},O:{"1":"kB"},P:{"1":"F I"},Q:{"1":"lB"},R:{"1":"mB"}},B:2,C:"CSS position:fixed"};
|
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _postcss = require("postcss");
var _postcss2 = _interopRequireDefault(_postcss);
var _caniuseApi = require("caniuse-api");
var _features = require("./features");
var _features2 = _interopRequireDefault(_features);
var _featuresActivationMap = require("./features-activation-map");
var _featuresActivationMap2 = _interopRequireDefault(_featuresActivationMap);
var _warnForDuplicates = require("./warn-for-duplicates");
var _warnForDuplicates2 = _interopRequireDefault(_warnForDuplicates);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var plugin = _postcss2.default.plugin("postcss-cssnext", function (options) {
options = _extends({
console: console,
warnForDuplicates: true,
features: {}
}, options);
var features = options.features;
// propagate browsers option to plugins that supports it
var pluginsToPropagateBrowserOption = ["autoprefixer", "rem"];
pluginsToPropagateBrowserOption.forEach(function (name) {
var feature = features[name];
if (feature !== false) {
features[name] = _extends({
browsers: feature && feature.browsers ? feature.browsers : options.browsers
}, feature || {});
}
});
// autoprefixer doesn't like an "undefined" value. Related to coffee ?
if (features.autoprefixer && features.autoprefixer.browsers === undefined) {
delete features.autoprefixer.browsers;
}
var processor = (0, _postcss2.default)();
// features
Object.keys(_features2.default).forEach(function (key) {
// feature is auto enabled if: not disable && (enabled || no data yet ||
// !supported yet)
if (
// feature is not disabled
features[key] !== false && (
// feature is enabled
features[key] === true ||
// feature don't have any browsers data (yet)
_featuresActivationMap2.default[key] === undefined ||
// feature is not yet supported by the browsers scope
_featuresActivationMap2.default[key] && _featuresActivationMap2.default[key][0] && !(0, _caniuseApi.isSupported)(_featuresActivationMap2.default[key][0], options.browsers))) {
var _plugin = _features2.default[key](_typeof(features[key]) === "object" ? _extends({}, features[key]) : undefined);
processor.use(_plugin);
}
});
if (options.warnForDuplicates) {
processor.use((0, _warnForDuplicates2.default)({
keys: Object.keys(_features2.default),
console: options.console
}));
}
return processor;
});
// es5/6 support
plugin.features = _features2.default;
module.exports = plugin; |
/*!
* reveal.js 2.0 r19
* http://lab.hakim.se/reveal-js
* MIT licensed
*
* Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se
*/
var Reveal = (function(){
var HORIZONTAL_SLIDES_SELECTOR = '.reveal .slides>section',
VERTICAL_SLIDES_SELECTOR = '.reveal .slides>section.present>section',
IS_TOUCH_DEVICE = !!( 'ontouchstart' in window ),
// Configurations defaults, can be overridden at initialization time
config = {
// Display controls in the bottom right corner
controls: true,
// Display a presentation progress bar
progress: true,
// Push each slide change to the browser history
history: false,
// Enable keyboard shortcuts for navigation
keyboard: true,
// Loop the presentation
loop: false,
// Number of milliseconds between automatically proceeding to the
// next slide, disabled when set to 0
autoSlide: 0,
// Enable slide navigation via mouse wheel
mouseWheel: true,
// Apply a 3D roll to links on hover
rollingLinks: true,
// Transition style
transition: 'default', // default/cube/page/concave/linear(2d),
// Script dependencies to load
dependencies: []
},
// The horizontal and verical index of the currently active slide
indexh = 0,
indexv = 0,
// The previous and current slide HTML elements
previousSlide,
currentSlide,
// Slides may hold a data-state attribute which we pick up and apply
// as a class to the body. This list contains the combined state of
// all current slides.
state = [],
// Cached references to DOM elements
dom = {},
// Detect support for CSS 3D transforms
supports3DTransforms = 'WebkitPerspective' in document.body.style ||
'MozPerspective' in document.body.style ||
'msPerspective' in document.body.style ||
'OPerspective' in document.body.style ||
'perspective' in document.body.style,
supports2DTransforms = 'WebkitTransform' in document.body.style ||
'MozTransform' in document.body.style ||
'msTransform' in document.body.style ||
'OTransform' in document.body.style ||
'transform' in document.body.style,
// Throttles mouse wheel navigation
mouseWheelTimeout = 0,
// An interval used to automatically move on to the next slide
autoSlideTimeout = 0,
// Delays updates to the URL due to a Chrome thumbnailer bug
writeURLTimeout = 0,
// Holds information about the currently ongoing touch input
touch = {
startX: 0,
startY: 0,
startSpan: 0,
startCount: 0,
handled: false,
threshold: 40
};
/**
* Starts up the presentation if the client is capable.
*/
function initialize( options ) {
if( ( !supports2DTransforms && !supports3DTransforms ) ) {
document.body.setAttribute( 'class', 'no-transforms' );
// If the browser doesn't support core features we won't be
// using JavaScript to control the presentation
return;
}
// Copy options over to our config object
extend( config, options );
// Cache references to DOM elements
dom.wrapper = document.querySelector( '.reveal' );
dom.progress = document.querySelector( '.reveal .progress' );
dom.progressbar = document.querySelector( '.reveal .progress span' );
if ( config.controls ) {
dom.controls = document.querySelector( '.reveal .controls' );
dom.controlsLeft = document.querySelector( '.reveal .controls .left' );
dom.controlsRight = document.querySelector( '.reveal .controls .right' );
dom.controlsUp = document.querySelector( '.reveal .controls .up' );
dom.controlsDown = document.querySelector( '.reveal .controls .down' );
}
// Loads the dependencies and continues to #start() once done
load();
// Set up hiding of the browser address bar
if( navigator.userAgent.match( /(iphone|ipod|android)/i ) ) {
// Give the page some scrollable overflow
document.documentElement.style.overflow = 'scroll';
document.body.style.height = '120%';
// Events that should trigger the address bar to hide
window.addEventListener( 'load', removeAddressBar, false );
window.addEventListener( 'orientationchange', removeAddressBar, false );
}
}
/**
* Loads the dependencies of reveal.js. Dependencies are
* defined via the configuration option 'dependencies'
* and will be loaded prior to starting/binding reveal.js.
* Some dependencies may have an 'async' flag, if so they
* will load after reveal.js has been started up.
*/
function load() {
var scripts = [],
scriptsAsync = [];
for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
var s = config.dependencies[i];
// Load if there's no condition or the condition is truthy
if( !s.condition || s.condition() ) {
if( s.async ) {
scriptsAsync.push( s.src );
}
else {
scripts.push( s.src );
}
// Extension may contain callback functions
if( typeof s.callback === 'function' ) {
head.ready( s.src.match( /([\w\d_-]*)\.?[^\\\/]*$/i )[0], s.callback );
}
}
}
// Called once synchronous scritps finish loading
function proceed() {
// Load asynchronous scripts
head.js.apply( null, scriptsAsync );
start();
}
if( scripts.length ) {
head.ready( proceed );
// Load synchronous scripts
head.js.apply( null, scripts );
}
else {
proceed();
}
}
/**
* Starts up reveal.js by binding input events and navigating
* to the current URL deeplink if there is one.
*/
function start() {
// Subscribe to input
addEventListeners();
// Updates the presentation to match the current configuration values
configure();
// Read the initial hash
readURL();
// Start auto-sliding if it's enabled
cueAutoSlide();
}
/**
* Applies the configuration settings from the config object.
*/
function configure() {
if( supports3DTransforms === false ) {
config.transition = 'linear';
}
if( config.controls && dom.controls ) {
dom.controls.style.display = 'block';
}
if( config.progress && dom.progress ) {
dom.progress.style.display = 'block';
}
if( config.transition !== 'default' ) {
dom.wrapper.classList.add( config.transition );
}
if( config.mouseWheel ) {
document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
}
if( config.rollingLinks ) {
// Add some 3D magic to our anchors
linkify();
}
}
function addEventListeners() {
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
document.addEventListener( 'touchend', onDocumentTouchEnd, false );
window.addEventListener( 'hashchange', onWindowHashChange, false );
if( config.keyboard ) {
document.addEventListener( 'keydown', onDocumentKeyDown, false );
}
if ( config.controls && dom.controls ) {
dom.controlsLeft.addEventListener( 'click', preventAndForward( navigateLeft ), false );
dom.controlsRight.addEventListener( 'click', preventAndForward( navigateRight ), false );
dom.controlsUp.addEventListener( 'click', preventAndForward( navigateUp ), false );
dom.controlsDown.addEventListener( 'click', preventAndForward( navigateDown ), false );
}
}
function removeEventListeners() {
document.removeEventListener( 'keydown', onDocumentKeyDown, false );
document.removeEventListener( 'touchstart', onDocumentTouchStart, false );
document.removeEventListener( 'touchmove', onDocumentTouchMove, false );
document.removeEventListener( 'touchend', onDocumentTouchEnd, false );
window.removeEventListener( 'hashchange', onWindowHashChange, false );
if ( config.controls && dom.controls ) {
dom.controlsLeft.removeEventListener( 'click', preventAndForward( navigateLeft ), false );
dom.controlsRight.removeEventListener( 'click', preventAndForward( navigateRight ), false );
dom.controlsUp.removeEventListener( 'click', preventAndForward( navigateUp ), false );
dom.controlsDown.removeEventListener( 'click', preventAndForward( navigateDown ), false );
}
}
/**
* Extend object a with the properties of object b.
* If there's a conflict, object b takes precedence.
*/
function extend( a, b ) {
for( var i in b ) {
a[ i ] = b[ i ];
}
}
/**
* Measures the distance in pixels between point a
* and point b.
*
* @param {Object} a point with x/y properties
* @param {Object} b point with x/y properties
*/
function distanceBetween( a, b ) {
var dx = a.x - b.x,
dy = a.y - b.y;
return Math.sqrt( dx*dx + dy*dy );
}
/**
* Prevents an events defaults behavior calls the
* specified delegate.
*
* @param {Function} delegate The method to call
* after the wrapper has been executed
*/
function preventAndForward( delegate ) {
return function( event ) {
event.preventDefault();
delegate.call();
}
}
/**
* Causes the address bar to hide on mobile devices,
* more vertical space ftw.
*/
function removeAddressBar() {
setTimeout( function() {
window.scrollTo( 0, 1 );
}, 0 );
}
/**
* Handler for the document level 'keydown' event.
*
* @param {Object} event
*/
function onDocumentKeyDown( event ) {
// FFT: Use document.querySelector( ':focus' ) === null
// instead of checking contentEditable?
// Disregard the event if the target is editable or a
// modifier is present
if ( event.target.contentEditable != 'inherit' || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;
var triggered = false;
switch( event.keyCode ) {
// p, page up
case 80: case 33: navigatePrev(); triggered = true; break;
// n, page down
case 78: case 34: navigateNext(); triggered = true; break;
// h, left
case 72: case 37: navigateLeft(); triggered = true; break;
// l, right
case 76: case 39: navigateRight(); triggered = true; break;
// k, up
case 75: case 38: navigateUp(); triggered = true; break;
// j, down
case 74: case 40: navigateDown(); triggered = true; break;
// home
case 36: navigateTo( 0 ); triggered = true; break;
// end
case 35: navigateTo( Number.MAX_VALUE ); triggered = true; break;
// space
case 32: overviewIsActive() ? deactivateOverview() : navigateNext(); triggered = true; break;
// return
case 13: if( overviewIsActive() ) { deactivateOverview(); triggered = true; } break;
}
// If the input resulted in a triggered action we should prevent
// the browsers default behavior
if( triggered ) {
event.preventDefault();
}
else if ( event.keyCode === 27 && supports3DTransforms ) {
toggleOverview();
event.preventDefault();
}
// If auto-sliding is enabled we need to cue up
// another timeout
cueAutoSlide();
}
/**
* Handler for the document level 'touchstart' event,
* enables support for swipe and pinch gestures.
*/
function onDocumentTouchStart( event ) {
touch.startX = event.touches[0].clientX;
touch.startY = event.touches[0].clientY;
touch.startCount = event.touches.length;
// If there's two touches we need to memorize the distance
// between those two points to detect pinching
if( event.touches.length === 2 ) {
touch.startSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
}
}
/**
* Handler for the document level 'touchmove' event.
*/
function onDocumentTouchMove( event ) {
// Each touch should only trigger one action
if( !touch.handled ) {
var currentX = event.touches[0].clientX;
var currentY = event.touches[0].clientY;
// If the touch started off with two points and still has
// two active touches; test for the pinch gesture
if( event.touches.length === 2 && touch.startCount === 2 ) {
// The current distance in pixels between the two touch points
var currentSpan = distanceBetween( {
x: event.touches[1].clientX,
y: event.touches[1].clientY
}, {
x: touch.startX,
y: touch.startY
} );
// If the span is larger than the desire amount we've got
// ourselves a pinch
if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
touch.handled = true;
if( currentSpan < touch.startSpan ) {
activateOverview();
}
else {
deactivateOverview();
}
}
}
// There was only one touch point, look for a swipe
else if( event.touches.length === 1 ) {
var deltaX = currentX - touch.startX,
deltaY = currentY - touch.startY;
if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.handled = true;
navigateLeft();
}
else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
touch.handled = true;
navigateRight();
}
else if( deltaY > touch.threshold ) {
touch.handled = true;
navigateUp();
}
else if( deltaY < -touch.threshold ) {
touch.handled = true;
navigateDown();
}
}
event.preventDefault();
}
}
/**
* Handler for the document level 'touchend' event.
*/
function onDocumentTouchEnd( event ) {
touch.handled = false;
}
/**
* Handles mouse wheel scrolling, throttled to avoid
* skipping multiple slides.
*/
function onDocumentMouseScroll( event ){
clearTimeout( mouseWheelTimeout );
mouseWheelTimeout = setTimeout( function() {
var delta = event.detail || -event.wheelDelta;
if( delta > 0 ) {
navigateNext();
}
else {
navigatePrev();
}
}, 100 );
}
/**
* Handler for the window level 'hashchange' event.
*
* @param {Object} event
*/
function onWindowHashChange( event ) {
readURL();
}
/**
* Wrap all links in 3D goodness.
*/
function linkify() {
if( supports3DTransforms && !( 'msPerspective' in document.body.style ) ) {
var nodes = document.querySelectorAll( '.reveal .slides section a:not(.image)' );
for( var i = 0, len = nodes.length; i < len; i++ ) {
var node = nodes[i];
if( node.textContent && !node.querySelector( 'img' ) && ( !node.className || !node.classList.contains( node, 'roll' ) ) ) {
node.classList.add( 'roll' );
node.innerHTML = '<span data-title="'+ node.text +'">' + node.innerHTML + '</span>';
}
};
}
}
/**
* Displays the overview of slides (quick nav) by
* scaling down and arranging all slide elements.
*
* Experimental feature, might be dropped if perf
* can't be improved.
*/
function activateOverview() {
dom.wrapper.classList.add( 'overview' );
var horizontalSlides = Array.prototype.slice.call( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
var hslide = horizontalSlides[i],
htransform = 'translateZ(-2500px) translate(' + ( ( i - indexh ) * 105 ) + '%, 0%)';
hslide.setAttribute( 'data-index-h', i );
hslide.style.display = 'block';
hslide.style.WebkitTransform = htransform;
hslide.style.MozTransform = htransform;
hslide.style.msTransform = htransform;
hslide.style.OTransform = htransform;
hslide.style.transform = htransform;
if( !hslide.classList.contains( 'stack' ) ) {
// Navigate to this slide on click
hslide.addEventListener( 'click', onOverviewSlideClicked, true );
}
var verticalSlides = Array.prototype.slice.call( hslide.querySelectorAll( 'section' ) );
for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
var vslide = verticalSlides[j],
vtransform = 'translate(0%, ' + ( ( j - ( i === indexh ? indexv : 0 ) ) * 105 ) + '%)';
vslide.setAttribute( 'data-index-h', i );
vslide.setAttribute( 'data-index-v', j );
vslide.style.display = 'block';
vslide.style.WebkitTransform = vtransform;
vslide.style.MozTransform = vtransform;
vslide.style.msTransform = vtransform;
vslide.style.OTransform = vtransform;
vslide.style.transform = vtransform;
// Navigate to this slide on click
vslide.addEventListener( 'click', onOverviewSlideClicked, true );
}
}
}
/**
* Exits the slide overview and enters the currently
* active slide.
*/
function deactivateOverview() {
dom.wrapper.classList.remove( 'overview' );
var slides = Array.prototype.slice.call( document.querySelectorAll( '.reveal .slides section' ) );
for( var i = 0, len = slides.length; i < len; i++ ) {
var element = slides[i];
// Resets all transforms to use the external styles
element.style.WebkitTransform = '';
element.style.MozTransform = '';
element.style.msTransform = '';
element.style.OTransform = '';
element.style.transform = '';
element.removeEventListener( 'click', onOverviewSlideClicked );
}
slide();
}
/**
* Checks if the overview is currently active.
*
* @return {Boolean} true if the overview is active,
* false otherwise
*/
function overviewIsActive() {
return dom.wrapper.classList.contains( 'overview' );
}
/**
* Invoked when a slide is and we're in the overview.
*/
function onOverviewSlideClicked( event ) {
// TODO There's a bug here where the event listeners are not
// removed after deactivating the overview.
if( overviewIsActive() ) {
event.preventDefault();
deactivateOverview();
indexh = this.getAttribute( 'data-index-h' );
indexv = this.getAttribute( 'data-index-v' );
slide();
}
}
/**
* Updates one dimension of slides by showing the slide
* with the specified index.
*
* @param {String} selector A CSS selector that will fetch
* the group of slides we are working with
* @param {Number} index The index of the slide that should be
* shown
*
* @return {Number} The index of the slide that is now shown,
* might differ from the passed in index if it was out of
* bounds.
*/
function updateSlides( selector, index ) {
// Select all slides and convert the NodeList result to
// an array
var slides = Array.prototype.slice.call( document.querySelectorAll( selector ) ),
slidesLength = slides.length;
if( slidesLength ) {
// Should the index loop?
if( config.loop ) {
index %= slidesLength;
if( index < 0 ) {
index = slidesLength + index;
}
}
// Enforce max and minimum index bounds
index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
for( var i = 0; i < slidesLength; i++ ) {
var slide = slides[i];
// Optimization; hide all slides that are three or more steps
// away from the present slide
if( overviewIsActive() === false ) {
// The distance loops so that it measures 1 between the first
// and last slides
var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
slide.style.display = distance > 3 ? 'none' : 'block';
}
slides[i].classList.remove( 'past' );
slides[i].classList.remove( 'present' );
slides[i].classList.remove( 'future' );
if( i < index ) {
// Any element previous to index is given the 'past' class
slides[i].classList.add( 'past' );
}
else if( i > index ) {
// Any element subsequent to index is given the 'future' class
slides[i].classList.add( 'future' );
}
// If this element contains vertical slides
if( slide.querySelector( 'section' ) ) {
slides[i].classList.add( 'stack' );
}
}
// Mark the current slide as present
slides[index].classList.add( 'present' );
// If this slide has a state associated with it, add it
// onto the current state of the deck
var slideState = slides[index].getAttribute( 'data-state' );
if( slideState ) {
state = state.concat( slideState.split( ' ' ) );
}
}
else {
// Since there are no slides we can't be anywhere beyond the
// zeroth index
index = 0;
}
return index;
}
/**
* Updates the visual slides to represent the currently
* set indices.
*/
function slide( h, v ) {
// Remember where we were at before
previousSlide = currentSlide;
// Remember the state before this slide
var stateBefore = state.concat();
// Reset the state array
state.length = 0;
var indexhBefore = indexh,
indexvBefore = indexv;
// Activate and transition to the new slide
indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
// Apply the new state
stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
// Check if this state existed on the previous slide. If it
// did, we will avoid adding it repeatedly.
for( var j = 0; j < stateBefore.length; j++ ) {
if( stateBefore[j] === state[i] ) {
stateBefore.splice( j, 1 );
continue stateLoop;
}
}
document.documentElement.classList.add( state[i] );
// Dispatch custom event matching the state's name
dispatchEvent( state[i] );
}
// Clean up the remaints of the previous state
while( stateBefore.length ) {
document.documentElement.classList.remove( stateBefore.pop() );
}
// Update progress if enabled
if( config.progress && dom.progress ) {
dom.progressbar.style.width = ( indexh / ( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ).length - 1 ) ) * window.innerWidth + 'px';
}
// Close the overview if it's active
if( overviewIsActive() ) {
activateOverview();
}
updateControls();
clearTimeout( writeURLTimeout );
writeURLTimeout = setTimeout( writeURL, 1500 );
// Query all horizontal slides in the deck
var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
// Find the current horizontal slide and any possible vertical slides
// within it
var currentHorizontalSlide = horizontalSlides[ indexh ],
currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
// Store references to the previous and current slides
currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
// Dispatch an event if the slide changed
if( indexh !== indexhBefore || indexv !== indexvBefore ) {
dispatchEvent( 'slidechanged', {
'indexh': indexh,
'indexv': indexv,
'previousSlide': previousSlide,
'currentSlide': currentSlide
} );
}
else {
// Ensure that the previous slide is never the same as the current
previousSlide = null;
}
// Solves an edge case where the previous slide maintains the
// 'present' class when navigating between adjacent vertical
// stacks
if( previousSlide ) {
previousSlide.classList.remove( 'present' );
}
}
/**
* Updates the state and link pointers of the controls.
*/
function updateControls() {
if ( !config.controls || !dom.controls ) {
return;
}
var routes = availableRoutes();
// Remove the 'enabled' class from all directions
[ dom.controlsLeft, dom.controlsRight, dom.controlsUp, dom.controlsDown ].forEach( function( node ) {
node.classList.remove( 'enabled' );
} )
if( routes.left ) dom.controlsLeft.classList.add( 'enabled' );
if( routes.right ) dom.controlsRight.classList.add( 'enabled' );
if( routes.up ) dom.controlsUp.classList.add( 'enabled' );
if( routes.down ) dom.controlsDown.classList.add( 'enabled' );
}
/**
* Determine what available routes there are for navigation.
*
* @return {Object} containing four booleans: left/right/up/down
*/
function availableRoutes() {
var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
var verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
return {
left: indexh > 0,
right: indexh < horizontalSlides.length - 1,
up: indexv > 0,
down: indexv < verticalSlides.length - 1
};
}
/**
* Reads the current URL (hash) and navigates accordingly.
*/
function readURL() {
// Break the hash down to separate components
var bits = window.location.hash.slice(2).split('/');
// Read the index components of the hash
var h = parseInt( bits[0] ) || 0 ;
var v = parseInt( bits[1] ) || 0 ;
navigateTo( h, v );
}
/**
* Updates the page URL (hash) to reflect the current
* state.
*/
function writeURL() {
if( config.history ) {
var url = '/';
// Only include the minimum possible number of components in
// the URL
if( indexh > 0 || indexv > 0 ) url += indexh;
if( indexv > 0 ) url += '/' + indexv;
window.location.hash = url;
}
}
/**
* Dispatches an event of the specified type from the
* reveal DOM element.
*/
function dispatchEvent( type, properties ) {
var event = document.createEvent( "HTMLEvents", 1, 2 );
event.initEvent( type, true, true );
extend( event, properties );
dom.wrapper.dispatchEvent( event );
}
/**
* Navigate to the next slide fragment.
*
* @return {Boolean} true if there was a next fragment,
* false otherwise
*/
function nextFragment() {
// Vertical slides:
if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
if( verticalFragments.length ) {
verticalFragments[0].classList.add( 'visible' );
// Notify subscribers of the change
dispatchEvent( 'fragmentshown', { fragment: verticalFragments[0] } );
return true;
}
}
// Horizontal slides:
else {
var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
if( horizontalFragments.length ) {
horizontalFragments[0].classList.add( 'visible' );
// Notify subscribers of the change
dispatchEvent( 'fragmentshown', { fragment: horizontalFragments[0] } );
return true;
}
}
return false;
}
/**
* Navigate to the previous slide fragment.
*
* @return {Boolean} true if there was a previous fragment,
* false otherwise
*/
function previousFragment() {
// Vertical slides:
if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment.visible' );
if( verticalFragments.length ) {
verticalFragments[ verticalFragments.length - 1 ].classList.remove( 'visible' );
// Notify subscribers of the change
dispatchEvent( 'fragmenthidden', { fragment: verticalFragments[ verticalFragments.length - 1 ] } );
return true;
}
}
// Horizontal slides:
else {
var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment.visible' );
if( horizontalFragments.length ) {
horizontalFragments[ horizontalFragments.length - 1 ].classList.remove( 'visible' );
// Notify subscribers of the change
dispatchEvent( 'fragmenthidden', { fragment: horizontalFragments[ horizontalFragments.length - 1 ] } );
return true;
}
}
return false;
}
function cueAutoSlide() {
clearTimeout( autoSlideTimeout );
// Cue the next auto-slide if enabled
if( config.autoSlide ) {
autoSlideTimeout = setTimeout( navigateNext, config.autoSlide );
}
}
/**
* Triggers a navigation to the specified indices.
*
* @param {Number} h The horizontal index of the slide to show
* @param {Number} v The vertical index of the slide to show
*/
function navigateTo( h, v ) {
slide( h, v );
}
function navigateLeft() {
// Prioritize hiding fragments
if( overviewIsActive() || previousFragment() === false ) {
slide( indexh - 1, 0 );
}
}
function navigateRight() {
// Prioritize revealing fragments
if( overviewIsActive() || nextFragment() === false ) {
slide( indexh + 1, 0 );
}
}
function navigateUp() {
// Prioritize hiding fragments
if( overviewIsActive() || previousFragment() === false ) {
slide( indexh, indexv - 1 );
}
}
function navigateDown() {
// Prioritize revealing fragments
if( overviewIsActive() || nextFragment() === false ) {
slide( indexh, indexv + 1 );
}
}
/**
* Navigates backwards, prioritized in the following order:
* 1) Previous fragment
* 2) Previous vertical slide
* 3) Previous horizontal slide
*/
function navigatePrev() {
// Prioritize revealing fragments
if( previousFragment() === false ) {
if( availableRoutes().up ) {
navigateUp();
}
else {
// Fetch the previous horizontal slide, if there is one
var previousSlide = document.querySelector( '.reveal .slides>section.past:nth-child(' + indexh + ')' );
if( previousSlide ) {
indexv = ( previousSlide.querySelectorAll('section').length + 1 ) || 0;
indexh --;
slide();
}
}
}
}
/**
* Same as #navigatePrev() but navigates forwards.
*/
function navigateNext() {
// Prioritize revealing fragments
if( nextFragment() === false ) {
availableRoutes().down ? navigateDown() : navigateRight();
}
// If auto-sliding is enabled we need to cue up
// another timeout
cueAutoSlide();
}
/**
* Toggles the slide overview mode on and off.
*/
function toggleOverview() {
if( overviewIsActive() ) {
deactivateOverview();
}
else {
activateOverview();
}
}
// Expose some methods publicly
return {
initialize: initialize,
navigateTo: navigateTo,
navigateLeft: navigateLeft,
navigateRight: navigateRight,
navigateUp: navigateUp,
navigateDown: navigateDown,
navigatePrev: navigatePrev,
navigateNext: navigateNext,
toggleOverview: toggleOverview,
// Adds or removes all internal event listeners (such as keyboard)
addEventListeners: addEventListeners,
removeEventListeners: removeEventListeners,
// Returns the indices of the current slide
getIndices: function() {
return {
h: indexh,
v: indexv
};
},
// Returns the previous slide element, may be null
getPreviousSlide: function() {
return previousSlide
},
// Returns the current slide element
getCurrentSlide: function() {
return currentSlide
},
// Helper method, retrieves query string as a key/value hash
getQueryHash: function() {
var query = {};
location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
} );
return query;
},
// Forward event binding to the reveal DOM element
addEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
}
},
removeEventListener: function( type, listener, useCapture ) {
if( 'addEventListener' in window ) {
( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
}
}
};
})();
|
describe('Documents', function(){
beforeEach(function(){
setFixtures(sandbox({id: 'something'}));
appendSetFixtures('<a id="revisions-anchor" href="#">Revisions</a><div id="revisions" style="display:none"><br/>This is <b>first</b> revision</div>');
reloadScript('documents.js');
WebsiteOne.Documents.init();
jQuery.fx.off = true;
});
it('prevents refreshing the page after link gets clicked', function() {
var submitSpy = jasmine.createSpy('submitSpy')
$(document).on('submit', submitSpy);
$('#revisions-anchor').trigger('click');
expect(submitSpy).not.toHaveBeenCalled();
});
it('shows revisions div after Revisions link is clicked', function(){
$('#revisions-anchor').trigger('click');
expect($('#revisions')).toBeVisible();
});
it('hides revisions div after Revisions is clicked twice', function(){
$('#revisions-anchor').trigger('click');
$('#revisions-anchor').trigger('click');
expect($('#revisions')).toBeHidden();
jQuery.fx.off = false
});
});
|
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import thunk from 'redux-thunk'
import reducers from './reducers'
export default (initialState = {}, history) => {
let middleware = applyMiddleware(thunk, routerMiddleware(history))
// Use DevTools chrome extension in development
if (__DEBUG__) {
const devToolsExtension = window.devToolsExtension
if (typeof devToolsExtension === 'function') {
middleware = compose(middleware, devToolsExtension())
}
}
const store = createStore(reducers(), initialState, middleware)
store.asyncReducers = {}
if (module.hot) {
module.hot.accept('./reducers', () => {
const reducers = require('./reducers').default
store.replaceReducer(reducers)
})
}
return store
}
|
import { hooks } from '../utils/hooks';
import hasOwnProp from '../utils/has-own-prop';
import getParsingFlags from '../create/parsing-flags';
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var momentProperties = hooks.momentProperties = [];
export function copyConfig(to, from) {
var i, prop, val;
if (typeof from._isAMomentObject !== 'undefined') {
to._isAMomentObject = from._isAMomentObject;
}
if (typeof from._i !== 'undefined') {
to._i = from._i;
}
if (typeof from._f !== 'undefined') {
to._f = from._f;
}
if (typeof from._l !== 'undefined') {
to._l = from._l;
}
if (typeof from._strict !== 'undefined') {
to._strict = from._strict;
}
if (typeof from._tzm !== 'undefined') {
to._tzm = from._tzm;
}
if (typeof from._isUTC !== 'undefined') {
to._isUTC = from._isUTC;
}
if (typeof from._offset !== 'undefined') {
to._offset = from._offset;
}
if (typeof from._pf !== 'undefined') {
to._pf = getParsingFlags(from);
}
if (typeof from._locale !== 'undefined') {
to._locale = from._locale;
}
if (momentProperties.length > 0) {
for (i in momentProperties) {
prop = momentProperties[i];
val = from[prop];
if (typeof val !== 'undefined') {
to[prop] = val;
}
}
}
return to;
}
var updateInProgress = false;
// Moment prototype object
export function Moment(config) {
copyConfig(this, config);
this._d = new Date(config._d.getTime());
// Prevent infinite loop in case updateOffset creates new moment
// objects.
if (updateInProgress === false) {
updateInProgress = true;
hooks.updateOffset(this);
updateInProgress = false;
}
}
export function isMoment (obj) {
return obj instanceof Moment || (obj != null && obj._isAMomentObject != null);
}
|
/**
* @author Hamza Waqas <hamzawaqas@live.com>
* @since 2/9/14
*/
var linkedin = require('../../')('75gyccfxufrozz', 'HKwSAPg0z7oGYfh5')
token = process.env.IN_TOKEN;
jasmine.getEnv().defaultTimeoutInterval = 20000;
linkedin = linkedin.init(token);
describe('API: People Test Suite', function() {
it('should retrieve profile of current user', function(done) {
linkedin.people.me(function(err, data) {
done();
});
});
it('should invite someone to connect', function(done) {
linkedin.people.invite({
"recipients": {
"values": [{
"person": {
"_path": "/people/email=glavin.wiechert@gmail.com",
"first-name": "Glavin",
"last-name": "Wiechert"
}
}]
},
"subject": "Invitation to connect.",
"body": "Say yes!",
"item-content": {
"invitation-request": {
"connect-type": "friend"
}
}
}, function(err, data) {
done();
});
});
it('should share some data on the wall', function(done){
linkedin.people.share({
"comment": "Check out the LinkedIn Share API!",
"content": {
"title": " LinkedIn Developers Documentation On Using the Share API ",
"description": " Leverage the Share API to maximize engagement on user-generated content on LinkedIn",
"submitted-url": " https://developer.linkedin.com/documents/share-api ",
"submitted-image-url": " https://m3.licdn.com/media/p/3/000/124/1a6/089a29a.png"
},
"visibility": { "code": "anyone" }
}, function(err, data){
done();
});
});
});
|
/*!
* Ext JS Library 3.2.1
* Copyright(c) 2006-2010 Ext JS, Inc.
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.data.DataProxy
* @extends Ext.util.Observable
* <p>Abstract base class for implementations which provide retrieval of unformatted data objects.
* This class is intended to be extended and should not be created directly. For existing implementations,
* see {@link Ext.data.DirectProxy}, {@link Ext.data.HttpProxy}, {@link Ext.data.ScriptTagProxy} and
* {@link Ext.data.MemoryProxy}.</p>
* <p>DataProxy implementations are usually used in conjunction with an implementation of {@link Ext.data.DataReader}
* (of the appropriate type which knows how to parse the data object) to provide a block of
* {@link Ext.data.Records} to an {@link Ext.data.Store}.</p>
* <p>The parameter to a DataProxy constructor may be an {@link Ext.data.Connection} or can also be the
* config object to an {@link Ext.data.Connection}.</p>
* <p>Custom implementations must implement either the <code><b>doRequest</b></code> method (preferred) or the
* <code>load</code> method (deprecated). See
* {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#doRequest doRequest} or
* {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#load load} for additional details.</p>
* <p><b><u>Example 1</u></b></p>
* <pre><code>
proxy: new Ext.data.ScriptTagProxy({
{@link Ext.data.Connection#url url}: 'http://extjs.com/forum/topics-remote.php'
}),
* </code></pre>
* <p><b><u>Example 2</u></b></p>
* <pre><code>
proxy : new Ext.data.HttpProxy({
{@link Ext.data.Connection#method method}: 'GET',
{@link Ext.data.HttpProxy#prettyUrls prettyUrls}: false,
{@link Ext.data.Connection#url url}: 'local/default.php', // see options parameter for {@link Ext.Ajax#request}
{@link #api}: {
// all actions except the following will use above url
create : 'local/new.php',
update : 'local/update.php'
}
}),
* </code></pre>
* <p>And <b>new in Ext version 3</b>, attach centralized event-listeners upon the DataProxy class itself! This is a great place
* to implement a <i>messaging system</i> to centralize your application's user-feedback and error-handling.</p>
* <pre><code>
// Listen to all "beforewrite" event fired by all proxies.
Ext.data.DataProxy.on('beforewrite', function(proxy, action) {
console.log('beforewrite: ', action);
});
// Listen to "write" event fired by all proxies
Ext.data.DataProxy.on('write', function(proxy, action, data, res, rs) {
console.info('write: ', action);
});
// Listen to "exception" event fired by all proxies
Ext.data.DataProxy.on('exception', function(proxy, type, action) {
console.error(type + action + ' exception);
});
* </code></pre>
* <b>Note:</b> These three events are all fired with the signature of the corresponding <i>DataProxy instance</i> event {@link #beforewrite beforewrite}, {@link #write write} and {@link #exception exception}.
*/
Ext.data.DataProxy = function(conn){
// make sure we have a config object here to support ux proxies.
// All proxies should now send config into superclass constructor.
conn = conn || {};
// This line caused a bug when people use custom Connection object having its own request method.
// http://extjs.com/forum/showthread.php?t=67194. Have to set DataProxy config
//Ext.applyIf(this, conn);
this.api = conn.api;
this.url = conn.url;
this.restful = conn.restful;
this.listeners = conn.listeners;
// deprecated
this.prettyUrls = conn.prettyUrls;
/**
* @cfg {Object} api
* Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".
* Defaults to:<pre><code>
api: {
read : undefined,
create : undefined,
update : undefined,
destroy : undefined
}
* </code></pre>
* <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>
* using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the
* configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>
* <p>For example:</p>
* <pre><code>
api: {
load : '/controller/load',
create : '/controller/new', // Server MUST return idProperty of new record
save : '/controller/update',
destroy : '/controller/destroy_action'
}
// Alternatively, one can use the object-form to specify each API-action
api: {
load: {url: 'read.php', method: 'GET'},
create: 'create.php',
destroy: 'destroy.php',
save: 'update.php'
}
* </code></pre>
* <p>If the specific URL for a given CRUD action is undefined, the CRUD action request
* will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>
* <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API
* property should be modified before the action is requested using the corresponding before
* action event. For example to modify the URL associated with the load action:
* <pre><code>
// modify the url for the action
myStore.on({
beforeload: {
fn: function (store, options) {
// use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.
store.proxy.setUrl('changed1.php');
// set optional second parameter to true to make this URL change
// permanent, applying this URL for all subsequent requests.
store.proxy.setUrl('changed1.php', true);
// Altering the proxy API should be done using the public
// method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt>.
store.proxy.setApi('read', 'changed2.php');
// Or set the entire API with a config-object.
// When using the config-object option, you must redefine the <b>entire</b>
// API -- not just a specific action of it.
store.proxy.setApi({
read : 'changed_read.php',
create : 'changed_create.php',
update : 'changed_update.php',
destroy : 'changed_destroy.php'
});
}
}
});
* </code></pre>
* </p>
*/
this.addEvents(
/**
* @event exception
* <p>Fires if an exception occurs in the Proxy during a remote request. This event is relayed
* through a corresponding {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},
* so any Store instance may observe this event.</p>
* <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
* through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of exception events from <b>all</b>
* DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
* <p>This event can be fired for one of two reasons:</p>
* <div class="mdetail-params"><ul>
* <li>remote-request <b>failed</b> : <div class="sub-desc">
* The server did not return status === 200.
* </div></li>
* <li>remote-request <b>succeeded</b> : <div class="sub-desc">
* The remote-request succeeded but the reader could not read the response.
* This means the server returned data, but the configured Reader threw an
* error while reading the response. In this case, this event will be
* raised and the caught error will be passed along into this event.
* </div></li>
* </ul></div>
* <br><p>This event fires with two different contexts based upon the 2nd
* parameter <tt>type [remote|response]</tt>. The first four parameters
* are identical between the two contexts -- only the final two parameters
* differ.</p>
* @param {DataProxy} this The proxy that sent the request
* @param {String} type
* <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>
* <div class="mdetail-params"><ul>
* <li><b><tt>'response'</tt></b> : <div class="sub-desc">
* <p>An <b>invalid</b> response from the server was returned: either 404,
* 500 or the response meta-data does not match that defined in the DataReader
* (e.g.: root, idProperty, successProperty).</p>
* </div></li>
* <li><b><tt>'remote'</tt></b> : <div class="sub-desc">
* <p>A <b>valid</b> response was returned from the server having
* successProperty === false. This response might contain an error-message
* sent from the server. For example, the user may have failed
* authentication/authorization or a database validation error occurred.</p>
* </div></li>
* </ul></div>
* @param {String} action Name of the action (see {@link Ext.data.Api#actions}.
* @param {Object} options The options for the action that were specified in the {@link #request}.
* @param {Object} response
* <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>
* <div class="mdetail-params"><ul>
* <li><b><tt>'response'</tt></b> : <div class="sub-desc">
* <p>The raw browser response object (e.g.: XMLHttpRequest)</p>
* </div></li>
* <li><b><tt>'remote'</tt></b> : <div class="sub-desc">
* <p>The decoded response object sent from the server.</p>
* </div></li>
* </ul></div>
* @param {Mixed} arg
* <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>
* <div class="mdetail-params"><ul>
* <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">
* <p>The JavaScript Error object caught if the configured Reader could not read the data.
* If the remote request returns success===false, this parameter will be null.</p>
* </div></li>
* <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">
* <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action
* (Ext.data.Api.actions.create|update|destroy).</p>
* </div></li>
* </ul></div>
*/
'exception',
/**
* @event beforeload
* Fires before a request to retrieve a data object.
* @param {DataProxy} this The proxy for the request
* @param {Object} params The params object passed to the {@link #request} function
*/
'beforeload',
/**
* @event load
* Fires before the load method's callback is called.
* @param {DataProxy} this The proxy for the request
* @param {Object} o The request transaction object
* @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function
*/
'load',
/**
* @event loadexception
* <p>This event is <b>deprecated</b>. The signature of the loadexception event
* varies depending on the proxy, use the catch-all {@link #exception} event instead.
* This event will fire in addition to the {@link #exception} event.</p>
* @param {misc} misc See {@link #exception}.
* @deprecated
*/
'loadexception',
/**
* @event beforewrite
* <p>Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy</p>
* <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
* through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of beforewrite events from <b>all</b>
* DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
* @param {DataProxy} this The proxy for the request
* @param {String} action [Ext.data.Api.actions.create|update|destroy]
* @param {Record/Record[]} rs The Record(s) to create|update|destroy.
* @param {Object} params The request <code>params</code> object. Edit <code>params</code> to add parameters to the request.
*/
'beforewrite',
/**
* @event write
* <p>Fires before the request-callback is called</p>
* <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
* through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of write events from <b>all</b>
* DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
* @param {DataProxy} this The proxy that sent the request
* @param {String} action [Ext.data.Api.actions.create|upate|destroy]
* @param {Object} data The data object extracted from the server-response
* @param {Object} response The decoded response from server
* @param {Record/Record[]} rs The Record(s) from Store
* @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function
*/
'write'
);
Ext.data.DataProxy.superclass.constructor.call(this);
// Prepare the proxy api. Ensures all API-actions are defined with the Object-form.
try {
Ext.data.Api.prepare(this);
} catch (e) {
if (e instanceof Ext.data.Api.Error) {
e.toConsole();
}
}
// relay each proxy's events onto Ext.data.DataProxy class for centralized Proxy-listening
Ext.data.DataProxy.relayEvents(this, ['beforewrite', 'write', 'exception']);
};
Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {
/**
* @cfg {Boolean} restful
* <p>Defaults to <tt>false</tt>. Set to <tt>true</tt> to operate in a RESTful manner.</p>
* <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the
* {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the
* Store is RESTful, there is no need to set this option on the proxy.</p>
* <br><p>RESTful implementations enable the serverside framework to automatically route
* actions sent to one url based upon the HTTP method, for example:
* <pre><code>
store: new Ext.data.Store({
restful: true,
proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users
...
)}
* </code></pre>
* If there is no <code>{@link #api}</code> specified in the configuration of the proxy,
* all requests will be marshalled to a single RESTful url (/users) so the serverside
* framework can inspect the HTTP Method and act accordingly:
* <pre>
<u>Method</u> <u>url</u> <u>action</u>
POST /users create
GET /users read
PUT /users/23 update
DESTROY /users/23 delete
* </pre></p>
* <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's
* {@link Ext.data.Record#id id} will be appended to the url. Some MVC (e.g., Ruby on Rails,
* Merb and Django) support segment based urls where the segments in the URL follow the
* Model-View-Controller approach:<pre><code>
* someSite.com/controller/action/id
* </code></pre>
* Where the segments in the url are typically:<div class="mdetail-params"><ul>
* <li>The first segment : represents the controller class that should be invoked.</li>
* <li>The second segment : represents the class function, or method, that should be called.</li>
* <li>The third segment : represents the ID (a variable typically passed to the method).</li>
* </ul></div></p>
* <br><p>Refer to <code>{@link Ext.data.DataProxy#api}</code> for additional information.</p>
*/
restful: false,
/**
* <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>
* <p>If called with an object as the only parameter, the object should redefine the <b>entire</b> API, e.g.:</p><pre><code>
proxy.setApi({
read : '/users/read',
create : '/users/create',
update : '/users/update',
destroy : '/users/destroy'
});
</code></pre>
* <p>If called with two parameters, the first parameter should be a string specifying the API action to
* redefine and the second parameter should be the URL (or function if using DirectProxy) to call for that action, e.g.:</p><pre><code>
proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');
</code></pre>
* @param {String/Object} api An API specification object, or the name of an action.
* @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.
*/
setApi : function() {
if (arguments.length == 1) {
var valid = Ext.data.Api.isValid(arguments[0]);
if (valid === true) {
this.api = arguments[0];
}
else {
throw new Ext.data.Api.Error('invalid', valid);
}
}
else if (arguments.length == 2) {
if (!Ext.data.Api.isAction(arguments[0])) {
throw new Ext.data.Api.Error('invalid', arguments[0]);
}
this.api[arguments[0]] = arguments[1];
}
Ext.data.Api.prepare(this);
},
/**
* Returns true if the specified action is defined as a unique action in the api-config.
* request. If all API-actions are routed to unique urls, the xaction parameter is unecessary. However, if no api is defined
* and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to
* the corresponding code for CRUD action.
* @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action
* @return {Boolean}
*/
isApiAction : function(action) {
return (this.api[action]) ? true : false;
},
/**
* All proxy actions are executed through this method. Automatically fires the "before" + action event
* @param {String} action Name of the action
* @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'
* @param {Object} params
* @param {Ext.data.DataReader} reader
* @param {Function} callback
* @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the Proxy object.
* @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.
*/
request : function(action, rs, params, reader, callback, scope, options) {
if (!this.api[action] && !this.load) {
throw new Ext.data.DataProxy.Error('action-undefined', action);
}
params = params || {};
if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {
this.doRequest.apply(this, arguments);
}
else {
callback.call(scope || this, null, options, false);
}
},
/**
* <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.
* @deprecated
* @param {Object} params
* @param {Object} reader
* @param {Object} callback
* @param {Object} scope
* @param {Object} arg
*/
load : null,
/**
* @cfg {Function} doRequest Abstract method that should be implemented in all subclasses. <b>Note:</b> Should only be used by custom-proxy developers.
* (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},
* {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).
*/
doRequest : function(action, rs, params, reader, callback, scope, options) {
// default implementation of doRequest for backwards compatibility with 2.0 proxies.
// If we're executing here, the action is probably "load".
// Call with the pre-3.0 method signature.
this.load(params, reader, callback, scope, options);
},
/**
* @cfg {Function} onRead Abstract method that should be implemented in all subclasses. <b>Note:</b> Should only be used by custom-proxy developers. Callback for read {@link Ext.data.Api#actions action}.
* @param {String} action Action name as per {@link Ext.data.Api.actions#read}.
* @param {Object} o The request transaction object
* @param {Object} res The server response
* @fires loadexception (deprecated)
* @fires exception
* @fires load
* @protected
*/
onRead : Ext.emptyFn,
/**
* @cfg {Function} onWrite Abstract method that should be implemented in all subclasses. <b>Note:</b> Should only be used by custom-proxy developers. Callback for <i>create, update and destroy</i> {@link Ext.data.Api#actions actions}.
* @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
* @param {Object} trans The request transaction object
* @param {Object} res The server response
* @fires exception
* @fires write
* @protected
*/
onWrite : Ext.emptyFn,
/**
* buildUrl
* Sets the appropriate url based upon the action being executed. If restful is true, and only a single record is being acted upon,
* url will be built Rails-style, as in "/controller/action/32". restful will aply iff the supplied record is an
* instance of Ext.data.Record rather than an Array of them.
* @param {String} action The api action being executed [read|create|update|destroy]
* @param {Ext.data.Record/Ext.data.Record[]} record The record or Array of Records being acted upon.
* @return {String} url
* @private
*/
buildUrl : function(action, record) {
record = record || null;
// conn.url gets nullified after each request. If it's NOT null here, that means the user must have intervened with a call
// to DataProxy#setUrl or DataProxy#setApi and changed it before the request was executed. If that's the case, use conn.url,
// otherwise, build the url from the api or this.url.
var url = (this.conn && this.conn.url) ? this.conn.url : (this.api[action]) ? this.api[action].url : this.url;
if (!url) {
throw new Ext.data.Api.Error('invalid-url', action);
}
// look for urls having "provides" suffix used in some MVC frameworks like Rails/Merb and others. The provides suffice informs
// the server what data-format the client is dealing with and returns data in the same format (eg: application/json, application/xml, etc)
// e.g.: /users.json, /users.xml, etc.
// with restful routes, we need urls like:
// PUT /users/1.json
// DELETE /users/1.json
var provides = null;
var m = url.match(/(.*)(\.json|\.xml|\.html)$/);
if (m) {
provides = m[2]; // eg ".json"
url = m[1]; // eg: "/users"
}
// prettyUrls is deprectated in favor of restful-config
if ((this.restful === true || this.prettyUrls === true) && record instanceof Ext.data.Record && !record.phantom) {
url += '/' + record.id;
}
return (provides === null) ? url : url + provides;
},
/**
* Destroys the proxy by purging any event listeners and cancelling any active requests.
*/
destroy: function(){
this.purgeListeners();
}
});
// Apply the Observable prototype to the DataProxy class so that proxy instances can relay their
// events to the class. Allows for centralized listening of all proxy instances upon the DataProxy class.
Ext.apply(Ext.data.DataProxy, Ext.util.Observable.prototype);
Ext.util.Observable.call(Ext.data.DataProxy);
/**
* @class Ext.data.DataProxy.Error
* @extends Ext.Error
* DataProxy Error extension.
* constructor
* @param {String} message Message describing the error.
* @param {Record/Record[]} arg
*/
Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {
constructor : function(message, arg) {
this.arg = arg;
Ext.Error.call(this, message);
},
name: 'Ext.data.DataProxy'
});
Ext.apply(Ext.data.DataProxy.Error.prototype, {
lang: {
'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function. Please review your Proxy url/api-configuration.",
'api-invalid': 'Recieved an invalid API-configuration. Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'
}
});
|
/*global describe, it, before, after */
/*jshint expr:true*/
var testUtils = require('../../../utils'),
should = require('should'),
supertest = require('supertest'),
express = require('express'),
ghost = require('../../../../../core'),
httpServer,
request;
describe('Tag API', function () {
var accesstoken = '';
before(function (done) {
var app = express();
// starting ghost automatically populates the db
// TODO: prevent db init, and manage bringing up the DB with fixtures ourselves
ghost({app: app}).then(function (_httpServer) {
httpServer = _httpServer;
request = supertest.agent(app);
}).then(function () {
return testUtils.doAuth(request, 'posts');
}).then(function (token) {
accesstoken = token;
done();
}).catch(function (e) {
console.log('Ghost Error: ', e);
console.log(e.stack);
});
});
after(function (done) {
testUtils.clearData().then(function () {
httpServer.close();
done();
});
});
it('can retrieve all tags', function (done) {
request.get(testUtils.API.getApiQuery('tags/'))
.set('Authorization', 'Bearer ' + accesstoken)
.expect('Content-Type', /json/)
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
should.not.exist(res.headers['x-cache-invalidate']);
var jsonResponse = res.body;
jsonResponse.should.exist;
jsonResponse.tags.should.exist;
jsonResponse.tags.should.have.length(6);
testUtils.API.checkResponse(jsonResponse.tags[0], 'tag');
testUtils.API.isISO8601(jsonResponse.tags[0].created_at).should.be.true;
done();
});
});
}); |
/*
* Serve JSON to our AngularJS client
*/
exports.name = function (req, res) {
res.json({
name: 'Bob'
});
}; |
import demoTest from '../../../tests/shared/demoTest';
demoTest('tag');
|
'use strict';
module.exports = {
db: 'mongodb://localhost/northwindnode-dev',
app: {
title: 'NorthwindNode - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
// ==UserScript==
// @id iitc-plugin-basemap-kartverket@sollie
// @name IITC plugin: Kartverket.no map tiles
// @category Map Tiles
// @version 0.1.0.@@DATETIMEVERSION@@
// @namespace https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL @@UPDATEURL@@
// @downloadURL @@DOWNLOADURL@@
// @description [@@BUILDNAME@@-@@BUILDDATE@@] Add the color and grayscale map tiles from Kartverket.no as an optional layer.
// @include https://*.ingress.com/intel*
// @include http://*.ingress.com/intel*
// @match https://*.ingress.com/intel*
// @match http://*.ingress.com/intel*
// @include https://*.ingress.com/mission/*
// @include http://*.ingress.com/mission/*
// @match https://*.ingress.com/mission/*
// @match http://*.ingress.com/mission/*
// @grant none
// ==/UserScript==
@@PLUGINSTART@@
// PLUGIN START ////////////////////////////////////////////////////////
// use own namespace for plugin
window.plugin.mapTileKartverketMap = function() {};
window.plugin.mapTileKartverketMap.addLayer = function() {
// Map data from Kartverket (http://statkart.no/en/)
kartverketAttribution = 'Map data © Kartverket';
var kartverketOpt = {attribution: kartverketAttribution, maxNativeZoom: 18, maxZoom: 21, subdomains: ['opencache', 'opencache2', 'opencache3']};
var kartverketTopo2 = new L.TileLayer('http://{s}.statkart.no/gatekeeper/gk/gk.open_gmaps?layers=topo2&zoom={z}&x={x}&y={y}', kartverketOpt);
var kartverketTopo2Grayscale = new L.TileLayer('http://{s}.statkart.no/gatekeeper/gk/gk.open_gmaps?layers=topo2graatone&zoom={z}&x={x}&y={y}', kartverketOpt);
layerChooser.addBaseLayer(kartverketTopo2, "Norway Topo");
layerChooser.addBaseLayer(kartverketTopo2Grayscale, "Norway Topo Grayscale");
};
var setup = window.plugin.mapTileKartverketMap.addLayer;
// PLUGIN END //////////////////////////////////////////////////////////
@@PLUGINEND@@
|
var objectAssign = require('object-assign');
var webpack = require('webpack');
var path = require('path');
var webpackConfig = require('./webpack.config.js');
module.exports = webpackConfig.map(function(config) {
return objectAssign({}, config, {
output: {
path: root("dist"),
filename: "[name].min.js",
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin()
]
});
});
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
|
'use strict';
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
ecmaFeatures: {
legacyDecorators: true
}
},
plugins: [
'ember'
],
extends: [
'eslint:recommended',
'plugin:ember/recommended'
],
env: {
browser: true
},
rules: {},
overrides: [
// node files
{
files: [
'.eslintrc.js',
'.template-lintrc.js',
'ember-cli-build.js',
'index.js',
'testem.js',
'blueprints/*/index.js',
'config/**/*.js',
'tests/dummy/config/**/*.js'
],
excludedFiles: [
'addon/**',
'addon-test-support/**',
'app/**',
'tests/dummy/app/**'
],
parserOptions: {
sourceType: 'script'
},
env: {
browser: false,
node: true
},
plugins: ['node'],
extends: ['plugin:node/recommended']
}
]
};
|
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2013, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file, and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying, or distributing this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*
*/
/**
* @fileOverview Defines the {@link CKFinder.lang} object for the Norwegian
* Nynorsk language.
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKFinder.lang['nn'] =
{
appTitle : 'CKFinder',
// Common messages and labels.
common :
{
// Put the voice-only part of the label in the span.
unavailable : '%1<span class="cke_accessibility">, utilgjenglig</span>',
confirmCancel : 'Noen av valgene har blitt endret. Er du sikker på at du vil lukke dialogen?',
ok : 'OK',
cancel : 'Avbryt',
confirmationTitle : 'Bekreftelse',
messageTitle : 'Informasjon',
inputTitle : 'Spørsmål',
undo : 'Angre',
redo : 'Gjør om',
skip : 'Hopp over',
skipAll : 'Hopp over alle',
makeDecision : 'Hvilken handling skal utføres?',
rememberDecision: 'Husk mitt valg'
},
// Language direction, 'ltr' or 'rtl'.
dir : 'ltr',
HelpLang : 'en',
LangCode : 'nn',
// Date Format
// d : Day
// dd : Day (padding zero)
// m : Month
// mm : Month (padding zero)
// yy : Year (two digits)
// yyyy : Year (four digits)
// h : Hour (12 hour clock)
// hh : Hour (12 hour clock, padding zero)
// H : Hour (24 hour clock)
// HH : Hour (24 hour clock, padding zero)
// M : Minute
// MM : Minute (padding zero)
// a : Firt char of AM/PM
// aa : AM/PM
DateTime : 'dd/mm/yyyy HH:MM',
DateAmPm : ['AM', 'PM'],
// Folders
FoldersTitle : 'Mapper',
FolderLoading : 'Laster...',
FolderNew : 'Skriv inn det nye mappenavnet: ',
FolderRename : 'Skriv inn det nye mappenavnet: ',
FolderDelete : 'Er du sikker på at du vil slette mappen "%1"?',
FolderRenaming : ' (Endrer mappenavn...)',
FolderDeleting : ' (Sletter...)',
DestinationFolder : 'Destination Folder', // MISSING
// Files
FileRename : 'Skriv inn det nye filnavnet: ',
FileRenameExt : 'Er du sikker på at du vil endre filtypen? Filen kan bli ubrukelig.',
FileRenaming : 'Endrer filnavn...',
FileDelete : 'Er du sikker på at du vil slette denne filen "%1"?',
FilesDelete : 'Are you sure you want to delete %1 files?', // MISSING
FilesLoading : 'Laster...',
FilesEmpty : 'Denne katalogen er tom.',
DestinationFile : 'Destination File', // MISSING
SkippedFiles : 'List of skipped files:', // MISSING
// Basket
BasketFolder : 'Kurv',
BasketClear : 'Tøm kurv',
BasketRemove : 'Fjern fra kurv',
BasketOpenFolder : 'Åpne foreldremappen',
BasketTruncateConfirm : 'Vil du virkelig fjerne alle filer fra kurven?',
BasketRemoveConfirm : 'Vil du virkelig fjerne filen "%1" fra kurven?',
BasketRemoveConfirmMultiple : 'Do you really want to remove %1 files from the basket?', // MISSING
BasketEmpty : 'Ingen filer i kurven, dra og slipp noen.',
BasketCopyFilesHere : 'Kopier filer fra kurven',
BasketMoveFilesHere : 'Flytt filer fra kurven',
// Global messages
OperationCompletedSuccess : 'Operation completed successfully.', // MISSING
OperationCompletedErrors : 'Operation completed with errors.', // MISSING
FileError : '%s: %e', // MISSING
// Move and Copy files
MovedFilesNumber : 'Number of files moved: %s.', // MISSING
CopiedFilesNumber : 'Number of files copied: %s.', // MISSING
MoveFailedList : 'The following files could not be moved:<br />%s', // MISSING
CopyFailedList : 'The following files could not be copied:<br />%s', // MISSING
// Toolbar Buttons (some used elsewhere)
Upload : 'Last opp',
UploadTip : 'Last opp en ny fil',
Refresh : 'Oppdater',
Settings : 'Innstillinger',
Help : 'Hjelp',
HelpTip : 'Hjelp finnes kun på engelsk',
// Context Menus
Select : 'Velg',
SelectThumbnail : 'Velg miniatyr',
View : 'Vis fullversjon',
Download : 'Last ned',
NewSubFolder : 'Ny undermappe',
Rename : 'Endre navn',
Delete : 'Slett',
DeleteFiles : 'Delete Files', // MISSING
CopyDragDrop : 'Kopier hit',
MoveDragDrop : 'Flytt hit',
// Dialogs
RenameDlgTitle : 'Gi nytt navn',
NewNameDlgTitle : 'Nytt navn',
FileExistsDlgTitle : 'Filen finnes allerede',
SysErrorDlgTitle : 'Systemfeil',
FileOverwrite : 'Overskriv',
FileAutorename : 'Gi nytt navn automatisk',
ManuallyRename : 'Manually rename', // MISSING
// Generic
OkBtn : 'OK',
CancelBtn : 'Avbryt',
CloseBtn : 'Lukk',
// Upload Panel
UploadTitle : 'Last opp ny fil',
UploadSelectLbl : 'Velg filen du vil laste opp',
UploadProgressLbl : '(Laster opp filen, vennligst vent...)',
UploadBtn : 'Last opp valgt fil',
UploadBtnCancel : 'Avbryt',
UploadNoFileMsg : 'Du må velge en fil fra din datamaskin',
UploadNoFolder : 'Vennligst velg en mappe før du laster opp.',
UploadNoPerms : 'Filopplastning er ikke tillatt.',
UploadUnknError : 'Feil ved sending av fil.',
UploadExtIncorrect : 'Filtypen er ikke tillatt i denne mappen.',
// Flash Uploads
UploadLabel : 'Filer for opplastning',
UploadTotalFiles : 'Totalt antall filer:',
UploadTotalSize : 'Total størrelse:',
UploadSend : 'Last opp',
UploadAddFiles : 'Legg til filer',
UploadClearFiles : 'Tøm filer',
UploadCancel : 'Avbryt opplastning',
UploadRemove : 'Fjern',
UploadRemoveTip : 'Fjern !f',
UploadUploaded : 'Lastet opp !n%',
UploadProcessing : 'Behandler...',
// Settings Panel
SetTitle : 'Innstillinger',
SetView : 'Filvisning:',
SetViewThumb : 'Miniatyrbilder',
SetViewList : 'Liste',
SetDisplay : 'Vis:',
SetDisplayName : 'Filnavn',
SetDisplayDate : 'Dato',
SetDisplaySize : 'Filstørrelse',
SetSort : 'Sorter etter:',
SetSortName : 'Filnavn',
SetSortDate : 'Dato',
SetSortSize : 'Størrelse',
SetSortExtension : 'Filetternavn',
// Status Bar
FilesCountEmpty : '<Tom Mappe>',
FilesCountOne : '1 fil',
FilesCountMany : '%1 filer',
// Size and Speed
Kb : '%1 KB',
Mb : '%1 MB',
Gb : '%1 GB',
SizePerSecond : '%1/s',
// Connector Error Messages.
ErrorUnknown : 'Det var ikke mulig å utføre forespørselen. (Feil %1)',
Errors :
{
10 : 'Ugyldig kommando.',
11 : 'Ressurstypen ble ikke spesifisert i forepørselen.',
12 : 'Ugyldig ressurstype.',
102 : 'Ugyldig fil- eller mappenavn.',
103 : 'Kunne ikke utføre forespørselen pga manglende autorisasjon.',
104 : 'Kunne ikke utføre forespørselen pga manglende tilgang til filsystemet.',
105 : 'Ugyldig filtype.',
109 : 'Ugyldig forespørsel.',
110 : 'Ukjent feil.',
111 : 'It was not possible to complete the request due to resulting file size.', // MISSING
115 : 'Det finnes allerede en fil eller mappe med dette navnet.',
116 : 'Kunne ikke finne mappen. Oppdater vinduet og prøv igjen.',
117 : 'Kunne ikke finne filen. Oppdater vinduet og prøv igjen.',
118 : 'Kilde- og mål-bane er like.',
201 : 'Det fantes allerede en fil med dette navnet. Den opplastede filens navn har blitt endret til "%1".',
202 : 'Ugyldig fil.',
203 : 'Ugyldig fil. Filen er for stor.',
204 : 'Den opplastede filen er korrupt.',
205 : 'Det finnes ingen midlertidig mappe for filopplastinger.',
206 : 'Opplastingen ble avbrutt av sikkerhetshensyn. Filen inneholder HTML-aktig data.',
207 : 'Den opplastede filens navn har blitt endret til "%1".',
300 : 'Klarte ikke å flytte fil(er).',
301 : 'Klarte ikke å kopiere fil(er).',
500 : 'Filvelgeren ikke tilgjengelig av sikkerhetshensyn. Kontakt systemansvarlig og be han sjekke CKFinder\'s konfigurasjonsfil.',
501 : 'Funksjon for minityrbilder er skrudd av.'
},
// Other Error Messages.
ErrorMsg :
{
FileEmpty : 'Filnavnet kan ikke være tomt.',
FileExists : 'Filen %s finnes alt.',
FolderEmpty : 'Mappenavnet kan ikke være tomt.',
FolderExists : 'Folder %s already exists.', // MISSING
FolderNameExists : 'Folder already exists.', // MISSING
FileInvChar : 'Filnavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
FolderInvChar : 'Mappenavnet kan ikke inneholde følgende tegn: \n\\ / : * ? " < > |',
PopupBlockView : 'Du må skru av popup-blockeren for å se bildet i nytt vindu.',
XmlError : 'Det var ikke mulig å laste XML-dataene i svaret fra serveren.',
XmlEmpty : 'Det var ikke mulig å laste XML-dataene fra serverne, svaret var tomt.',
XmlRawResponse : 'Rått datasvar fra serveren: %s'
},
// Imageresize plugin
Imageresize :
{
dialogTitle : 'Endre størrelse %s',
sizeTooBig : 'Kan ikke sette høyde og bredde til større enn orginalstørrelse (%size).',
resizeSuccess : 'Endring av bildestørrelse var vellykket.',
thumbnailNew : 'Lag ett nytt miniatyrbilde',
thumbnailSmall : 'Liten (%s)',
thumbnailMedium : 'Medium (%s)',
thumbnailLarge : 'Stor (%s)',
newSize : 'Sett en ny størrelse',
width : 'Bredde',
height : 'Høyde',
invalidHeight : 'Ugyldig høyde.',
invalidWidth : 'Ugyldig bredde.',
invalidName : 'Ugyldig filnavn.',
newImage : 'Lag ett nytt bilde',
noExtensionChange : 'Filendelsen kan ikke endres.',
imageSmall : 'Kildebildet er for lite.',
contextMenuName : 'Endre størrelse',
lockRatio : 'Lås forhold',
resetSize : 'Tilbakestill størrelse'
},
// Fileeditor plugin
Fileeditor :
{
save : 'Lagre',
fileOpenError : 'Klarte ikke å åpne filen.',
fileSaveSuccess : 'Fillagring var vellykket.',
contextMenuName : 'Rediger',
loadingFile : 'Laster fil, vennligst vent...'
},
Maximize :
{
maximize : 'Maksimer',
minimize : 'Minimer'
},
Gallery :
{
current : 'Bilde {current} av {total}'
},
Zip :
{
extractHereLabel : 'Extract here', // MISSING
extractToLabel : 'Extract to...', // MISSING
downloadZipLabel : 'Download as zip', // MISSING
compressZipLabel : 'Compress to zip', // MISSING
removeAndExtract : 'Remove existing and extract', // MISSING
extractAndOverwrite : 'Extract overwriting existing files', // MISSING
extractSuccess : 'File extracted successfully.' // MISSING
},
Search :
{
searchPlaceholder : 'Søk'
}
};
|
/*
Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/**
* @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
* Backing buffer: ArrayBuffer, Accessor: Uint8Array
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/bytebuffer.js for details
*/
(function(global, factory) {
/* AMD */ if (typeof define === 'function' && define["amd"])
define(["long"], factory);
/* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
module['exports'] = (function() {
var Long; try { Long = require("long"); } catch (e) {}
return factory(Long);
})();
/* Global */ else
(global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
})(this, function(Long) {
"use strict";
/**
* Constructs a new ByteBuffer.
* @class The swiss army knife for binary data in JavaScript.
* @exports ByteBuffer
* @constructor
* @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
* {@link ByteBuffer.DEFAULT_NOASSERT}.
* @expose
*/
var ByteBuffer = function(capacity, littleEndian, noAssert) {
if (typeof capacity === 'undefined')
capacity = ByteBuffer.DEFAULT_CAPACITY;
if (typeof littleEndian === 'undefined')
littleEndian = ByteBuffer.DEFAULT_ENDIAN;
if (typeof noAssert === 'undefined')
noAssert = ByteBuffer.DEFAULT_NOASSERT;
if (!noAssert) {
capacity = capacity | 0;
if (capacity < 0)
throw RangeError("Illegal capacity");
littleEndian = !!littleEndian;
noAssert = !!noAssert;
}
/**
* Backing ArrayBuffer.
* @type {!ArrayBuffer}
* @expose
*/
this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
/**
* Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
* @type {?Uint8Array}
* @expose
*/
this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
/**
* Absolute read/write offset.
* @type {number}
* @expose
* @see ByteBuffer#flip
* @see ByteBuffer#clear
*/
this.offset = 0;
/**
* Marked offset.
* @type {number}
* @expose
* @see ByteBuffer#mark
* @see ByteBuffer#reset
*/
this.markedOffset = -1;
/**
* Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
* @type {number}
* @expose
* @see ByteBuffer#flip
* @see ByteBuffer#clear
*/
this.limit = capacity;
/**
* Whether to use little endian byte order, defaults to `false` for big endian.
* @type {boolean}
* @expose
*/
this.littleEndian = littleEndian;
/**
* Whether to skip assertions of offsets and values, defaults to `false`.
* @type {boolean}
* @expose
*/
this.noAssert = noAssert;
};
/**
* ByteBuffer version.
* @type {string}
* @const
* @expose
*/
ByteBuffer.VERSION = "5.0.1";
/**
* Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
* @type {boolean}
* @const
* @expose
*/
ByteBuffer.LITTLE_ENDIAN = true;
/**
* Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
* @type {boolean}
* @const
* @expose
*/
ByteBuffer.BIG_ENDIAN = false;
/**
* Default initial capacity of `16`.
* @type {number}
* @expose
*/
ByteBuffer.DEFAULT_CAPACITY = 16;
/**
* Default endianess of `false` for big endian.
* @type {boolean}
* @expose
*/
ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
/**
* Default no assertions flag of `false`.
* @type {boolean}
* @expose
*/
ByteBuffer.DEFAULT_NOASSERT = false;
/**
* A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
* and int64 support is not available.
* @type {?Long}
* @const
* @see https://github.com/dcodeIO/long.js
* @expose
*/
ByteBuffer.Long = Long || null;
/**
* @alias ByteBuffer.prototype
* @inner
*/
var ByteBufferPrototype = ByteBuffer.prototype;
/**
* An indicator used to reliably determine if an object is a ByteBuffer or not.
* @type {boolean}
* @const
* @expose
* @private
*/
ByteBufferPrototype.__isByteBuffer__;
Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
value: true,
enumerable: false,
configurable: false
});
// helpers
/**
* @type {!ArrayBuffer}
* @inner
*/
var EMPTY_BUFFER = new ArrayBuffer(0);
/**
* String.fromCharCode reference for compile-time renaming.
* @type {function(...number):string}
* @inner
*/
var stringFromCharCode = String.fromCharCode;
/**
* Creates a source function for a string.
* @param {string} s String to read from
* @returns {function():number|null} Source function returning the next char code respectively `null` if there are
* no more characters left.
* @throws {TypeError} If the argument is invalid
* @inner
*/
function stringSource(s) {
var i=0; return function() {
return i < s.length ? s.charCodeAt(i++) : null;
};
}
/**
* Creates a destination function for a string.
* @returns {function(number=):undefined|string} Destination function successively called with the next char code.
* Returns the final string when called without arguments.
* @inner
*/
function stringDestination() {
var cs = [], ps = []; return function() {
if (arguments.length === 0)
return ps.join('')+stringFromCharCode.apply(String, cs);
if (cs.length + arguments.length > 1024)
ps.push(stringFromCharCode.apply(String, cs)),
cs.length = 0;
Array.prototype.push.apply(cs, arguments);
};
}
/**
* Gets the accessor type.
* @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
* @expose
*/
ByteBuffer.accessor = function() {
return Uint8Array;
};
/**
* Allocates a new ByteBuffer backed by a buffer of the specified capacity.
* @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
* {@link ByteBuffer.DEFAULT_NOASSERT}.
* @returns {!ByteBuffer}
* @expose
*/
ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
return new ByteBuffer(capacity, littleEndian, noAssert);
};
/**
* Concatenates multiple ByteBuffers into one.
* @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
* @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
* defaults to "utf8")
* @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
* to {@link ByteBuffer.DEFAULT_ENDIAN}.
* @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
* {@link ByteBuffer.DEFAULT_NOASSERT}.
* @returns {!ByteBuffer} Concatenated ByteBuffer
* @expose
*/
ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
noAssert = littleEndian;
littleEndian = encoding;
encoding = undefined;
}
var capacity = 0;
for (var i=0, k=buffers.length, length; i<k; ++i) {
if (!ByteBuffer.isByteBuffer(buffers[i]))
buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
length = buffers[i].limit - buffers[i].offset;
if (length > 0) capacity += length;
}
if (capacity === 0)
return new ByteBuffer(0, littleEndian, noAssert);
var bb = new ByteBuffer(capacity, littleEndian, noAssert),
bi;
i=0; while (i<k) {
bi = buffers[i++];
length = bi.limit - bi.offset;
if (length <= 0) continue;
bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
bb.offset += length;
}
bb.limit = bb.offset;
bb.offset = 0;
return bb;
};
/**
* Tests if the specified type is a ByteBuffer.
* @param {*} bb ByteBuffer to test
* @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
* @expose
*/
ByteBuffer.isByteBuffer = function(bb) {
return (bb && bb["__isByteBuffer__"]) === true;
};
/**
* Gets the backing buffer type.
* @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
* @expose
*/
ByteBuffer.type = function() {
return ArrayBuffer;
};
/**
* Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
* {@link ByteBuffer#limit} to the length of the wrapped data.
* @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
* @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
* "utf8")
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
* {@link ByteBuffer.DEFAULT_NOASSERT}.
* @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
* @expose
*/
ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
if (typeof encoding !== 'string') {
noAssert = littleEndian;
littleEndian = encoding;
encoding = undefined;
}
if (typeof buffer === 'string') {
if (typeof encoding === 'undefined')
encoding = "utf8";
switch (encoding) {
case "base64":
return ByteBuffer.fromBase64(buffer, littleEndian);
case "hex":
return ByteBuffer.fromHex(buffer, littleEndian);
case "binary":
return ByteBuffer.fromBinary(buffer, littleEndian);
case "utf8":
return ByteBuffer.fromUTF8(buffer, littleEndian);
case "debug":
return ByteBuffer.fromDebug(buffer, littleEndian);
default:
throw Error("Unsupported encoding: "+encoding);
}
}
if (buffer === null || typeof buffer !== 'object')
throw TypeError("Illegal buffer");
var bb;
if (ByteBuffer.isByteBuffer(buffer)) {
bb = ByteBufferPrototype.clone.call(buffer);
bb.markedOffset = -1;
return bb;
}
if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
bb = new ByteBuffer(0, littleEndian, noAssert);
if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
bb.buffer = buffer.buffer;
bb.offset = buffer.byteOffset;
bb.limit = buffer.byteOffset + buffer.byteLength;
bb.view = new Uint8Array(buffer.buffer);
}
} else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
bb = new ByteBuffer(0, littleEndian, noAssert);
if (buffer.byteLength > 0) {
bb.buffer = buffer;
bb.offset = 0;
bb.limit = buffer.byteLength;
bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
}
} else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
bb.limit = buffer.length;
for (var i=0; i<buffer.length; ++i)
bb.view[i] = buffer[i];
} else
throw TypeError("Illegal buffer"); // Otherwise fail
return bb;
};
/**
* Writes the array as a bitset.
* @param {Array<boolean>} value Array of booleans to write
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
* @returns {!ByteBuffer}
* @expose
*/
ByteBufferPrototype.writeBitSet = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (!(value instanceof Array))
throw TypeError("Illegal BitSet: Not an array");
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
var start = offset,
bits = value.length,
bytes = (bits >> 3),
bit = 0,
k;
offset += this.writeVarint32(bits,offset);
while(bytes--) {
k = (!!value[bit++] & 1) |
((!!value[bit++] & 1) << 1) |
((!!value[bit++] & 1) << 2) |
((!!value[bit++] & 1) << 3) |
((!!value[bit++] & 1) << 4) |
((!!value[bit++] & 1) << 5) |
((!!value[bit++] & 1) << 6) |
((!!value[bit++] & 1) << 7);
this.writeByte(k,offset++);
}
if(bit < bits) {
var m = 0; k = 0;
while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
this.writeByte(k,offset++);
}
if (relative) {
this.offset = offset;
return this;
}
return offset - start;
}
/**
* Reads a BitSet as an array of booleans.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
* @returns {Array<boolean>
* @expose
*/
ByteBufferPrototype.readBitSet = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
var ret = this.readVarint32(offset),
bits = ret.value,
bytes = (bits >> 3),
bit = 0,
value = [],
k;
offset += ret.length;
while(bytes--) {
k = this.readByte(offset++);
value[bit++] = !!(k & 0x01);
value[bit++] = !!(k & 0x02);
value[bit++] = !!(k & 0x04);
value[bit++] = !!(k & 0x08);
value[bit++] = !!(k & 0x10);
value[bit++] = !!(k & 0x20);
value[bit++] = !!(k & 0x40);
value[bit++] = !!(k & 0x80);
}
if(bit < bits) {
var m = 0;
k = this.readByte(offset++);
while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
}
if (relative) {
this.offset = offset;
}
return value;
}
/**
* Reads the specified number of bytes.
* @param {number} length Number of bytes to read
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
* @returns {!ByteBuffer}
* @expose
*/
ByteBufferPrototype.readBytes = function(length, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + length > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
}
var slice = this.slice(offset, offset + length);
if (relative) this.offset += length;
return slice;
};
/**
* Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
* @function
* @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
* will be modified according to the performed read operation.
* @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
// types/ints/int8
/**
* Writes an 8bit signed integer.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeInt8 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number' || value % 1 !== 0)
throw TypeError("Illegal value: "+value+" (not an integer)");
value |= 0;
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
offset += 1;
var capacity0 = this.buffer.byteLength;
if (offset > capacity0)
this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
offset -= 1;
this.view[offset] = value;
if (relative) this.offset += 1;
return this;
};
/**
* Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
* @function
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
/**
* Reads an 8bit signed integer.
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
* @returns {number} Value read
* @expose
*/
ByteBufferPrototype.readInt8 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 1 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
}
var value = this.view[offset];
if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
if (relative) this.offset += 1;
return value;
};
/**
* Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
* @function
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
* @returns {number} Value read
* @expose
*/
ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
/**
* Writes an 8bit unsigned integer.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeUint8 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number' || value % 1 !== 0)
throw TypeError("Illegal value: "+value+" (not an integer)");
value >>>= 0;
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
offset += 1;
var capacity1 = this.buffer.byteLength;
if (offset > capacity1)
this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
offset -= 1;
this.view[offset] = value;
if (relative) this.offset += 1;
return this;
};
/**
* Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
* @function
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
/**
* Reads an 8bit unsigned integer.
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
* @returns {number} Value read
* @expose
*/
ByteBufferPrototype.readUint8 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 1 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
}
var value = this.view[offset];
if (relative) this.offset += 1;
return value;
};
/**
* Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
* @function
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
* @returns {number} Value read
* @expose
*/
ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
// types/ints/int16
/**
* Writes a 16bit signed integer.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
* @throws {TypeError} If `offset` or `value` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @expose
*/
ByteBufferPrototype.writeInt16 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number' || value % 1 !== 0)
throw TypeError("Illegal value: "+value+" (not an integer)");
value |= 0;
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
offset += 2;
var capacity2 = this.buffer.byteLength;
if (offset > capacity2)
this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
offset -= 2;
if (this.littleEndian) {
this.view[offset+1] = (value & 0xFF00) >>> 8;
this.view[offset ] = value & 0x00FF;
} else {
this.view[offset] = (value & 0xFF00) >>> 8;
this.view[offset+1] = value & 0x00FF;
}
if (relative) this.offset += 2;
return this;
};
/**
* Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
* @function
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
* @throws {TypeError} If `offset` or `value` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @expose
*/
ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
/**
* Reads a 16bit signed integer.
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
* @returns {number} Value read
* @throws {TypeError} If `offset` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @expose
*/
ByteBufferPrototype.readInt16 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 2 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
}
var value = 0;
if (this.littleEndian) {
value = this.view[offset ];
value |= this.view[offset+1] << 8;
} else {
value = this.view[offset ] << 8;
value |= this.view[offset+1];
}
if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
if (relative) this.offset += 2;
return value;
};
/**
* Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
* @function
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
* @returns {number} Value read
* @throws {TypeError} If `offset` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @expose
*/
ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
/**
* Writes a 16bit unsigned integer.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
* @throws {TypeError} If `offset` or `value` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @expose
*/
ByteBufferPrototype.writeUint16 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number' || value % 1 !== 0)
throw TypeError("Illegal value: "+value+" (not an integer)");
value >>>= 0;
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
offset += 2;
var capacity3 = this.buffer.byteLength;
if (offset > capacity3)
this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
offset -= 2;
if (this.littleEndian) {
this.view[offset+1] = (value & 0xFF00) >>> 8;
this.view[offset ] = value & 0x00FF;
} else {
this.view[offset] = (value & 0xFF00) >>> 8;
this.view[offset+1] = value & 0x00FF;
}
if (relative) this.offset += 2;
return this;
};
/**
* Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
* @function
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
* @throws {TypeError} If `offset` or `value` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @expose
*/
ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
/**
* Reads a 16bit unsigned integer.
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
* @returns {number} Value read
* @throws {TypeError} If `offset` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @expose
*/
ByteBufferPrototype.readUint16 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 2 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
}
var value = 0;
if (this.littleEndian) {
value = this.view[offset ];
value |= this.view[offset+1] << 8;
} else {
value = this.view[offset ] << 8;
value |= this.view[offset+1];
}
if (relative) this.offset += 2;
return value;
};
/**
* Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
* @function
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
* @returns {number} Value read
* @throws {TypeError} If `offset` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @expose
*/
ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
// types/ints/int32
/**
* Writes a 32bit signed integer.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @expose
*/
ByteBufferPrototype.writeInt32 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number' || value % 1 !== 0)
throw TypeError("Illegal value: "+value+" (not an integer)");
value |= 0;
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
offset += 4;
var capacity4 = this.buffer.byteLength;
if (offset > capacity4)
this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
offset -= 4;
if (this.littleEndian) {
this.view[offset+3] = (value >>> 24) & 0xFF;
this.view[offset+2] = (value >>> 16) & 0xFF;
this.view[offset+1] = (value >>> 8) & 0xFF;
this.view[offset ] = value & 0xFF;
} else {
this.view[offset ] = (value >>> 24) & 0xFF;
this.view[offset+1] = (value >>> 16) & 0xFF;
this.view[offset+2] = (value >>> 8) & 0xFF;
this.view[offset+3] = value & 0xFF;
}
if (relative) this.offset += 4;
return this;
};
/**
* Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @expose
*/
ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
/**
* Reads a 32bit signed integer.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @returns {number} Value read
* @expose
*/
ByteBufferPrototype.readInt32 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 4 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
}
var value = 0;
if (this.littleEndian) {
value = this.view[offset+2] << 16;
value |= this.view[offset+1] << 8;
value |= this.view[offset ];
value += this.view[offset+3] << 24 >>> 0;
} else {
value = this.view[offset+1] << 16;
value |= this.view[offset+2] << 8;
value |= this.view[offset+3];
value += this.view[offset ] << 24 >>> 0;
}
value |= 0; // Cast to signed
if (relative) this.offset += 4;
return value;
};
/**
* Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
* @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
* @returns {number} Value read
* @expose
*/
ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
/**
* Writes a 32bit unsigned integer.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @expose
*/
ByteBufferPrototype.writeUint32 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number' || value % 1 !== 0)
throw TypeError("Illegal value: "+value+" (not an integer)");
value >>>= 0;
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
offset += 4;
var capacity5 = this.buffer.byteLength;
if (offset > capacity5)
this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
offset -= 4;
if (this.littleEndian) {
this.view[offset+3] = (value >>> 24) & 0xFF;
this.view[offset+2] = (value >>> 16) & 0xFF;
this.view[offset+1] = (value >>> 8) & 0xFF;
this.view[offset ] = value & 0xFF;
} else {
this.view[offset ] = (value >>> 24) & 0xFF;
this.view[offset+1] = (value >>> 16) & 0xFF;
this.view[offset+2] = (value >>> 8) & 0xFF;
this.view[offset+3] = value & 0xFF;
}
if (relative) this.offset += 4;
return this;
};
/**
* Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
* @function
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @expose
*/
ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
/**
* Reads a 32bit unsigned integer.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @returns {number} Value read
* @expose
*/
ByteBufferPrototype.readUint32 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 4 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
}
var value = 0;
if (this.littleEndian) {
value = this.view[offset+2] << 16;
value |= this.view[offset+1] << 8;
value |= this.view[offset ];
value += this.view[offset+3] << 24 >>> 0;
} else {
value = this.view[offset+1] << 16;
value |= this.view[offset+2] << 8;
value |= this.view[offset+3];
value += this.view[offset ] << 24 >>> 0;
}
if (relative) this.offset += 4;
return value;
};
/**
* Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
* @function
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @returns {number} Value read
* @expose
*/
ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
// types/ints/int64
if (Long) {
/**
* Writes a 64bit signed integer.
* @param {number|!Long} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeInt64 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value === 'number')
value = Long.fromNumber(value);
else if (typeof value === 'string')
value = Long.fromString(value);
else if (!(value && value instanceof Long))
throw TypeError("Illegal value: "+value+" (not an integer or Long)");
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
if (typeof value === 'number')
value = Long.fromNumber(value);
else if (typeof value === 'string')
value = Long.fromString(value);
offset += 8;
var capacity6 = this.buffer.byteLength;
if (offset > capacity6)
this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
offset -= 8;
var lo = value.low,
hi = value.high;
if (this.littleEndian) {
this.view[offset+3] = (lo >>> 24) & 0xFF;
this.view[offset+2] = (lo >>> 16) & 0xFF;
this.view[offset+1] = (lo >>> 8) & 0xFF;
this.view[offset ] = lo & 0xFF;
offset += 4;
this.view[offset+3] = (hi >>> 24) & 0xFF;
this.view[offset+2] = (hi >>> 16) & 0xFF;
this.view[offset+1] = (hi >>> 8) & 0xFF;
this.view[offset ] = hi & 0xFF;
} else {
this.view[offset ] = (hi >>> 24) & 0xFF;
this.view[offset+1] = (hi >>> 16) & 0xFF;
this.view[offset+2] = (hi >>> 8) & 0xFF;
this.view[offset+3] = hi & 0xFF;
offset += 4;
this.view[offset ] = (lo >>> 24) & 0xFF;
this.view[offset+1] = (lo >>> 16) & 0xFF;
this.view[offset+2] = (lo >>> 8) & 0xFF;
this.view[offset+3] = lo & 0xFF;
}
if (relative) this.offset += 8;
return this;
};
/**
* Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
* @param {number|!Long} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
/**
* Reads a 64bit signed integer.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!Long}
* @expose
*/
ByteBufferPrototype.readInt64 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 8 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
}
var lo = 0,
hi = 0;
if (this.littleEndian) {
lo = this.view[offset+2] << 16;
lo |= this.view[offset+1] << 8;
lo |= this.view[offset ];
lo += this.view[offset+3] << 24 >>> 0;
offset += 4;
hi = this.view[offset+2] << 16;
hi |= this.view[offset+1] << 8;
hi |= this.view[offset ];
hi += this.view[offset+3] << 24 >>> 0;
} else {
hi = this.view[offset+1] << 16;
hi |= this.view[offset+2] << 8;
hi |= this.view[offset+3];
hi += this.view[offset ] << 24 >>> 0;
offset += 4;
lo = this.view[offset+1] << 16;
lo |= this.view[offset+2] << 8;
lo |= this.view[offset+3];
lo += this.view[offset ] << 24 >>> 0;
}
var value = new Long(lo, hi, false);
if (relative) this.offset += 8;
return value;
};
/**
* Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!Long}
* @expose
*/
ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
/**
* Writes a 64bit unsigned integer.
* @param {number|!Long} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeUint64 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value === 'number')
value = Long.fromNumber(value);
else if (typeof value === 'string')
value = Long.fromString(value);
else if (!(value && value instanceof Long))
throw TypeError("Illegal value: "+value+" (not an integer or Long)");
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
if (typeof value === 'number')
value = Long.fromNumber(value);
else if (typeof value === 'string')
value = Long.fromString(value);
offset += 8;
var capacity7 = this.buffer.byteLength;
if (offset > capacity7)
this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
offset -= 8;
var lo = value.low,
hi = value.high;
if (this.littleEndian) {
this.view[offset+3] = (lo >>> 24) & 0xFF;
this.view[offset+2] = (lo >>> 16) & 0xFF;
this.view[offset+1] = (lo >>> 8) & 0xFF;
this.view[offset ] = lo & 0xFF;
offset += 4;
this.view[offset+3] = (hi >>> 24) & 0xFF;
this.view[offset+2] = (hi >>> 16) & 0xFF;
this.view[offset+1] = (hi >>> 8) & 0xFF;
this.view[offset ] = hi & 0xFF;
} else {
this.view[offset ] = (hi >>> 24) & 0xFF;
this.view[offset+1] = (hi >>> 16) & 0xFF;
this.view[offset+2] = (hi >>> 8) & 0xFF;
this.view[offset+3] = hi & 0xFF;
offset += 4;
this.view[offset ] = (lo >>> 24) & 0xFF;
this.view[offset+1] = (lo >>> 16) & 0xFF;
this.view[offset+2] = (lo >>> 8) & 0xFF;
this.view[offset+3] = lo & 0xFF;
}
if (relative) this.offset += 8;
return this;
};
/**
* Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
* @function
* @param {number|!Long} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
/**
* Reads a 64bit unsigned integer.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!Long}
* @expose
*/
ByteBufferPrototype.readUint64 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 8 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
}
var lo = 0,
hi = 0;
if (this.littleEndian) {
lo = this.view[offset+2] << 16;
lo |= this.view[offset+1] << 8;
lo |= this.view[offset ];
lo += this.view[offset+3] << 24 >>> 0;
offset += 4;
hi = this.view[offset+2] << 16;
hi |= this.view[offset+1] << 8;
hi |= this.view[offset ];
hi += this.view[offset+3] << 24 >>> 0;
} else {
hi = this.view[offset+1] << 16;
hi |= this.view[offset+2] << 8;
hi |= this.view[offset+3];
hi += this.view[offset ] << 24 >>> 0;
offset += 4;
lo = this.view[offset+1] << 16;
lo |= this.view[offset+2] << 8;
lo |= this.view[offset+3];
lo += this.view[offset ] << 24 >>> 0;
}
var value = new Long(lo, hi, true);
if (relative) this.offset += 8;
return value;
};
/**
* Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
* @function
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!Long}
* @expose
*/
ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
} // Long
// types/floats/float32
/*
ieee754 - https://github.com/feross/ieee754
The MIT License (MIT)
Copyright (c) Feross Aboukhadijeh
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.
*/
/**
* Reads an IEEE754 float from a byte array.
* @param {!Array} buffer
* @param {number} offset
* @param {boolean} isLE
* @param {number} mLen
* @param {number} nBytes
* @returns {number}
* @inner
*/
function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
var e, m,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
nBits = -7,
i = isLE ? (nBytes - 1) : 0,
d = isLE ? -1 : 1,
s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity);
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
}
/**
* Writes an IEEE754 float to a byte array.
* @param {!Array} buffer
* @param {number} value
* @param {number} offset
* @param {boolean} isLE
* @param {number} mLen
* @param {number} nBytes
* @inner
*/
function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c,
eLen = nBytes * 8 - mLen - 1,
eMax = (1 << eLen) - 1,
eBias = eMax >> 1,
rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
i = isLE ? 0 : (nBytes - 1),
d = isLE ? 1 : -1,
s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128;
}
/**
* Writes a 32bit float.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeFloat32 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number')
throw TypeError("Illegal value: "+value+" (not a number)");
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
offset += 4;
var capacity8 = this.buffer.byteLength;
if (offset > capacity8)
this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
offset -= 4;
ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
if (relative) this.offset += 4;
return this;
};
/**
* Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
* @function
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
/**
* Reads a 32bit float.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @returns {number}
* @expose
*/
ByteBufferPrototype.readFloat32 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 4 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
}
var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
if (relative) this.offset += 4;
return value;
};
/**
* Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
* @function
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
* @returns {number}
* @expose
*/
ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
// types/floats/float64
/**
* Writes a 64bit float.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeFloat64 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number')
throw TypeError("Illegal value: "+value+" (not a number)");
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
offset += 8;
var capacity9 = this.buffer.byteLength;
if (offset > capacity9)
this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
offset -= 8;
ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
if (relative) this.offset += 8;
return this;
};
/**
* Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
* @function
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
/**
* Reads a 64bit float.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {number}
* @expose
*/
ByteBufferPrototype.readFloat64 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 8 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
}
var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
if (relative) this.offset += 8;
return value;
};
/**
* Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
* @function
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
* @returns {number}
* @expose
*/
ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
// types/varints/varint32
/**
* Maximum number of bytes required to store a 32bit base 128 variable-length integer.
* @type {number}
* @const
* @expose
*/
ByteBuffer.MAX_VARINT32_BYTES = 5;
/**
* Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
* @param {number} value Value to encode
* @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
* @expose
*/
ByteBuffer.calculateVarint32 = function(value) {
// ref: src/google/protobuf/io/coded_stream.cc
value = value >>> 0;
if (value < 1 << 7 ) return 1;
else if (value < 1 << 14) return 2;
else if (value < 1 << 21) return 3;
else if (value < 1 << 28) return 4;
else return 5;
};
/**
* Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
* @param {number} n Signed 32bit integer
* @returns {number} Unsigned zigzag encoded 32bit integer
* @expose
*/
ByteBuffer.zigZagEncode32 = function(n) {
return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
};
/**
* Decodes a zigzag encoded signed 32bit integer.
* @param {number} n Unsigned zigzag encoded 32bit integer
* @returns {number} Signed 32bit integer
* @expose
*/
ByteBuffer.zigZagDecode32 = function(n) {
return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
};
/**
* Writes a 32bit base 128 variable-length integer.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
* @expose
*/
ByteBufferPrototype.writeVarint32 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value !== 'number' || value % 1 !== 0)
throw TypeError("Illegal value: "+value+" (not an integer)");
value |= 0;
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
var size = ByteBuffer.calculateVarint32(value),
b;
offset += size;
var capacity10 = this.buffer.byteLength;
if (offset > capacity10)
this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
offset -= size;
value >>>= 0;
while (value >= 0x80) {
b = (value & 0x7f) | 0x80;
this.view[offset++] = b;
value >>>= 7;
}
this.view[offset++] = value;
if (relative) {
this.offset = offset;
return this;
}
return size;
};
/**
* Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
* @param {number} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
* @expose
*/
ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
};
/**
* Reads a 32bit base 128 variable-length integer.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
* and the actual number of bytes read.
* @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
* to fully decode the varint.
* @expose
*/
ByteBufferPrototype.readVarint32 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 1 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
}
var c = 0,
value = 0 >>> 0,
b;
do {
if (!this.noAssert && offset > this.limit) {
var err = Error("Truncated");
err['truncated'] = true;
throw err;
}
b = this.view[offset++];
if (c < 5)
value |= (b & 0x7f) << (7*c);
++c;
} while ((b & 0x80) !== 0);
value |= 0;
if (relative) {
this.offset = offset;
return value;
}
return {
"value": value,
"length": c
};
};
/**
* Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
* and the actual number of bytes read.
* @throws {Error} If it's not a valid varint
* @expose
*/
ByteBufferPrototype.readVarint32ZigZag = function(offset) {
var val = this.readVarint32(offset);
if (typeof val === 'object')
val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
else
val = ByteBuffer.zigZagDecode32(val);
return val;
};
// types/varints/varint64
if (Long) {
/**
* Maximum number of bytes required to store a 64bit base 128 variable-length integer.
* @type {number}
* @const
* @expose
*/
ByteBuffer.MAX_VARINT64_BYTES = 10;
/**
* Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
* @param {number|!Long} value Value to encode
* @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
* @expose
*/
ByteBuffer.calculateVarint64 = function(value) {
if (typeof value === 'number')
value = Long.fromNumber(value);
else if (typeof value === 'string')
value = Long.fromString(value);
// ref: src/google/protobuf/io/coded_stream.cc
var part0 = value.toInt() >>> 0,
part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
if (part2 == 0) {
if (part1 == 0) {
if (part0 < 1 << 14)
return part0 < 1 << 7 ? 1 : 2;
else
return part0 < 1 << 21 ? 3 : 4;
} else {
if (part1 < 1 << 14)
return part1 < 1 << 7 ? 5 : 6;
else
return part1 < 1 << 21 ? 7 : 8;
}
} else
return part2 < 1 << 7 ? 9 : 10;
};
/**
* Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
* @param {number|!Long} value Signed long
* @returns {!Long} Unsigned zigzag encoded long
* @expose
*/
ByteBuffer.zigZagEncode64 = function(value) {
if (typeof value === 'number')
value = Long.fromNumber(value, false);
else if (typeof value === 'string')
value = Long.fromString(value, false);
else if (value.unsigned !== false) value = value.toSigned();
// ref: src/google/protobuf/wire_format_lite.h
return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
};
/**
* Decodes a zigzag encoded signed 64bit integer.
* @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
* @returns {!Long} Signed long
* @expose
*/
ByteBuffer.zigZagDecode64 = function(value) {
if (typeof value === 'number')
value = Long.fromNumber(value, false);
else if (typeof value === 'string')
value = Long.fromString(value, false);
else if (value.unsigned !== false) value = value.toSigned();
// ref: src/google/protobuf/wire_format_lite.h
return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
};
/**
* Writes a 64bit base 128 variable-length integer.
* @param {number|Long} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
* @expose
*/
ByteBufferPrototype.writeVarint64 = function(value, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof value === 'number')
value = Long.fromNumber(value);
else if (typeof value === 'string')
value = Long.fromString(value);
else if (!(value && value instanceof Long))
throw TypeError("Illegal value: "+value+" (not an integer or Long)");
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
if (typeof value === 'number')
value = Long.fromNumber(value, false);
else if (typeof value === 'string')
value = Long.fromString(value, false);
else if (value.unsigned !== false) value = value.toSigned();
var size = ByteBuffer.calculateVarint64(value),
part0 = value.toInt() >>> 0,
part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
offset += size;
var capacity11 = this.buffer.byteLength;
if (offset > capacity11)
this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
offset -= size;
switch (size) {
case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
}
if (relative) {
this.offset += size;
return this;
} else {
return size;
}
};
/**
* Writes a zig-zag encoded 64bit base 128 variable-length integer.
* @param {number|Long} value Value to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
* @expose
*/
ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
};
/**
* Reads a 64bit base 128 variable-length integer. Requires Long.js.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
* the actual number of bytes read.
* @throws {Error} If it's not a valid varint
* @expose
*/
ByteBufferPrototype.readVarint64 = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 1 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
}
// ref: src/google/protobuf/io/coded_stream.cc
var start = offset,
part0 = 0,
part1 = 0,
part2 = 0,
b = 0;
b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
throw Error("Buffer overrun"); }}}}}}}}}}
var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
if (relative) {
this.offset = offset;
return value;
} else {
return {
'value': value,
'length': offset-start
};
}
};
/**
* Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
* the actual number of bytes read.
* @throws {Error} If it's not a valid varint
* @expose
*/
ByteBufferPrototype.readVarint64ZigZag = function(offset) {
var val = this.readVarint64(offset);
if (val && val['value'] instanceof Long)
val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
else
val = ByteBuffer.zigZagDecode64(val);
return val;
};
} // Long
// types/strings/cstring
/**
* Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
* characters itself.
* @param {string} str String to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* contained in `str` + 1 if omitted.
* @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
* @expose
*/
ByteBufferPrototype.writeCString = function(str, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
var i,
k = str.length;
if (!this.noAssert) {
if (typeof str !== 'string')
throw TypeError("Illegal str: Not a string");
for (i=0; i<k; ++i) {
if (str.charCodeAt(i) === 0)
throw RangeError("Illegal str: Contains NULL-characters");
}
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
// UTF8 strings do not contain zero bytes in between except for the zero character, so:
k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
offset += k+1;
var capacity12 = this.buffer.byteLength;
if (offset > capacity12)
this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
offset -= k+1;
utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
this.view[offset++] = b;
}.bind(this));
this.view[offset++] = 0;
if (relative) {
this.offset = offset;
return this;
}
return k;
};
/**
* Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
* itself.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
* read and the actual number of bytes read.
* @expose
*/
ByteBufferPrototype.readCString = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 1 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
}
var start = offset,
temp;
// UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
var sd, b = -1;
utfx.decodeUTF8toUTF16(function() {
if (b === 0) return null;
if (offset >= this.limit)
throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
b = this.view[offset++];
return b === 0 ? null : b;
}.bind(this), sd = stringDestination(), true);
if (relative) {
this.offset = offset;
return sd();
} else {
return {
"string": sd(),
"length": offset - start
};
}
};
// types/strings/istring
/**
* Writes a length as uint32 prefixed UTF8 encoded string.
* @param {string} str String to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
* @expose
* @see ByteBuffer#writeVarint32
*/
ByteBufferPrototype.writeIString = function(str, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof str !== 'string')
throw TypeError("Illegal str: Not a string");
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
var start = offset,
k;
k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
offset += 4+k;
var capacity13 = this.buffer.byteLength;
if (offset > capacity13)
this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
offset -= 4+k;
if (this.littleEndian) {
this.view[offset+3] = (k >>> 24) & 0xFF;
this.view[offset+2] = (k >>> 16) & 0xFF;
this.view[offset+1] = (k >>> 8) & 0xFF;
this.view[offset ] = k & 0xFF;
} else {
this.view[offset ] = (k >>> 24) & 0xFF;
this.view[offset+1] = (k >>> 16) & 0xFF;
this.view[offset+2] = (k >>> 8) & 0xFF;
this.view[offset+3] = k & 0xFF;
}
offset += 4;
utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
this.view[offset++] = b;
}.bind(this));
if (offset !== start + 4 + k)
throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
if (relative) {
this.offset = offset;
return this;
}
return offset - start;
};
/**
* Reads a length as uint32 prefixed UTF8 encoded string.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
* read and the actual number of bytes read.
* @expose
* @see ByteBuffer#readVarint32
*/
ByteBufferPrototype.readIString = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 4 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
}
var start = offset;
var len = this.readUint32(offset);
var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
offset += str['length'];
if (relative) {
this.offset = offset;
return str['string'];
} else {
return {
'string': str['string'],
'length': offset - start
};
}
};
// types/strings/utf8string
/**
* Metrics representing number of UTF8 characters. Evaluates to `c`.
* @type {string}
* @const
* @expose
*/
ByteBuffer.METRICS_CHARS = 'c';
/**
* Metrics representing number of bytes. Evaluates to `b`.
* @type {string}
* @const
* @expose
*/
ByteBuffer.METRICS_BYTES = 'b';
/**
* Writes an UTF8 encoded string.
* @param {string} str String to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
* @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
* @expose
*/
ByteBufferPrototype.writeUTF8String = function(str, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
var k;
var start = offset;
k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
offset += k;
var capacity14 = this.buffer.byteLength;
if (offset > capacity14)
this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
offset -= k;
utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
this.view[offset++] = b;
}.bind(this));
if (relative) {
this.offset = offset;
return this;
}
return offset - start;
};
/**
* Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
* @function
* @param {string} str String to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
* @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
* @expose
*/
ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
/**
* Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
* `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
* @param {string} str String to calculate
* @returns {number} Number of UTF8 characters
* @expose
*/
ByteBuffer.calculateUTF8Chars = function(str) {
return utfx.calculateUTF16asUTF8(stringSource(str))[0];
};
/**
* Calculates the number of UTF8 bytes of a string.
* @param {string} str String to calculate
* @returns {number} Number of UTF8 bytes
* @expose
*/
ByteBuffer.calculateUTF8Bytes = function(str) {
return utfx.calculateUTF16asUTF8(stringSource(str))[1];
};
/**
* Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
* @function
* @param {string} str String to calculate
* @returns {number} Number of UTF8 bytes
* @expose
*/
ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
/**
* Reads an UTF8 encoded string.
* @param {number} length Number of characters or bytes to read.
* @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
* {@link ByteBuffer.METRICS_CHARS}.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
* read and the actual number of bytes read.
* @expose
*/
ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
if (typeof metrics === 'number') {
offset = metrics;
metrics = undefined;
}
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
if (!this.noAssert) {
if (typeof length !== 'number' || length % 1 !== 0)
throw TypeError("Illegal length: "+length+" (not an integer)");
length |= 0;
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
var i = 0,
start = offset,
sd;
if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
sd = stringDestination();
utfx.decodeUTF8(function() {
return i < length && offset < this.limit ? this.view[offset++] : null;
}.bind(this), function(cp) {
++i; utfx.UTF8toUTF16(cp, sd);
});
if (i !== length)
throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
if (relative) {
this.offset = offset;
return sd();
} else {
return {
"string": sd(),
"length": offset - start
};
}
} else if (metrics === ByteBuffer.METRICS_BYTES) {
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + length > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
}
var k = offset + length;
utfx.decodeUTF8toUTF16(function() {
return offset < k ? this.view[offset++] : null;
}.bind(this), sd = stringDestination(), this.noAssert);
if (offset !== k)
throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
if (relative) {
this.offset = offset;
return sd();
} else {
return {
'string': sd(),
'length': offset - start
};
}
} else
throw TypeError("Unsupported metrics: "+metrics);
};
/**
* Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
* @function
* @param {number} length Number of characters or bytes to read
* @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
* {@link ByteBuffer.METRICS_CHARS}.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
* read and the actual number of bytes read.
* @expose
*/
ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
// types/strings/vstring
/**
* Writes a length as varint32 prefixed UTF8 encoded string.
* @param {string} str String to write
* @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
* @expose
* @see ByteBuffer#writeVarint32
*/
ByteBufferPrototype.writeVString = function(str, offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof str !== 'string')
throw TypeError("Illegal str: Not a string");
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
var start = offset,
k, l;
k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
l = ByteBuffer.calculateVarint32(k);
offset += l+k;
var capacity15 = this.buffer.byteLength;
if (offset > capacity15)
this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
offset -= l+k;
offset += this.writeVarint32(k, offset);
utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
this.view[offset++] = b;
}.bind(this));
if (offset !== start+k+l)
throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
if (relative) {
this.offset = offset;
return this;
}
return offset - start;
};
/**
* Reads a length as varint32 prefixed UTF8 encoded string.
* @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
* read and the actual number of bytes read.
* @expose
* @see ByteBuffer#readVarint32
*/
ByteBufferPrototype.readVString = function(offset) {
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 1 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
}
var start = offset;
var len = this.readVarint32(offset);
var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
offset += str['length'];
if (relative) {
this.offset = offset;
return str['string'];
} else {
return {
'string': str['string'],
'length': offset - start
};
}
};
/**
* Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
* data's length.
* @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
* will be modified according to the performed read operation.
* @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
* @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted.
* @returns {!ByteBuffer} this
* @expose
* @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
* @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
*/
ByteBufferPrototype.append = function(source, encoding, offset) {
if (typeof encoding === 'number' || typeof encoding !== 'string') {
offset = encoding;
encoding = undefined;
}
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
if (!(source instanceof ByteBuffer))
source = ByteBuffer.wrap(source, encoding);
var length = source.limit - source.offset;
if (length <= 0) return this; // Nothing to append
offset += length;
var capacity16 = this.buffer.byteLength;
if (offset > capacity16)
this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
offset -= length;
this.view.set(source.view.subarray(source.offset, source.limit), offset);
source.offset += length;
if (relative) this.offset += length;
return this;
};
/**
* Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
specified offset up to the length of this ByteBuffer's data.
* @param {!ByteBuffer} target Target ByteBuffer
* @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* read if omitted.
* @returns {!ByteBuffer} this
* @expose
* @see ByteBuffer#append
*/
ByteBufferPrototype.appendTo = function(target, offset) {
target.append(this, offset);
return this;
};
/**
* Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
* disable them if your code already makes sure that everything is valid.
* @param {boolean} assert `true` to enable assertions, otherwise `false`
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.assert = function(assert) {
this.noAssert = !assert;
return this;
};
/**
* Gets the capacity of this ByteBuffer's backing buffer.
* @returns {number} Capacity of the backing buffer
* @expose
*/
ByteBufferPrototype.capacity = function() {
return this.buffer.byteLength;
};
/**
* Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
* backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.clear = function() {
this.offset = 0;
this.limit = this.buffer.byteLength;
this.markedOffset = -1;
return this;
};
/**
* Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
* {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
* @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
* @returns {!ByteBuffer} Cloned instance
* @expose
*/
ByteBufferPrototype.clone = function(copy) {
var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
if (copy) {
bb.buffer = new ArrayBuffer(this.buffer.byteLength);
bb.view = new Uint8Array(bb.buffer);
} else {
bb.buffer = this.buffer;
bb.view = this.view;
}
bb.offset = this.offset;
bb.markedOffset = this.markedOffset;
bb.limit = this.limit;
return bb;
};
/**
* Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
* between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
* adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
* @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
* @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.compact = function(begin, end) {
if (typeof begin === 'undefined') begin = this.offset;
if (typeof end === 'undefined') end = this.limit;
if (!this.noAssert) {
if (typeof begin !== 'number' || begin % 1 !== 0)
throw TypeError("Illegal begin: Not an integer");
begin >>>= 0;
if (typeof end !== 'number' || end % 1 !== 0)
throw TypeError("Illegal end: Not an integer");
end >>>= 0;
if (begin < 0 || begin > end || end > this.buffer.byteLength)
throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
}
if (begin === 0 && end === this.buffer.byteLength)
return this; // Already compacted
var len = end - begin;
if (len === 0) {
this.buffer = EMPTY_BUFFER;
this.view = null;
if (this.markedOffset >= 0) this.markedOffset -= begin;
this.offset = 0;
this.limit = 0;
return this;
}
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
view.set(this.view.subarray(begin, end));
this.buffer = buffer;
this.view = view;
if (this.markedOffset >= 0) this.markedOffset -= begin;
this.offset = 0;
this.limit = len;
return this;
};
/**
* Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
* {@link ByteBuffer#limit}.
* @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
* @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
* @returns {!ByteBuffer} Copy
* @expose
*/
ByteBufferPrototype.copy = function(begin, end) {
if (typeof begin === 'undefined') begin = this.offset;
if (typeof end === 'undefined') end = this.limit;
if (!this.noAssert) {
if (typeof begin !== 'number' || begin % 1 !== 0)
throw TypeError("Illegal begin: Not an integer");
begin >>>= 0;
if (typeof end !== 'number' || end % 1 !== 0)
throw TypeError("Illegal end: Not an integer");
end >>>= 0;
if (begin < 0 || begin > end || end > this.buffer.byteLength)
throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
}
if (begin === end)
return new ByteBuffer(0, this.littleEndian, this.noAssert);
var capacity = end - begin,
bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
bb.offset = 0;
bb.limit = capacity;
if (bb.markedOffset >= 0) bb.markedOffset -= begin;
this.copyTo(bb, 0, begin, end);
return bb;
};
/**
* Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
* {@link ByteBuffer#limit}.
* @param {!ByteBuffer} target Target ByteBuffer
* @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
* by the number of bytes copied if omitted.
* @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
* number of bytes copied if omitted.
* @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
var relative,
targetRelative;
if (!this.noAssert) {
if (!ByteBuffer.isByteBuffer(target))
throw TypeError("Illegal target: Not a ByteBuffer");
}
targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
var len = sourceLimit - sourceOffset;
if (len === 0)
return target; // Nothing to copy
target.ensureCapacity(targetOffset + len);
target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
if (relative) this.offset += len;
if (targetRelative) target.offset += len;
return this;
};
/**
* Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
* current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
* the required capacity will be used instead.
* @param {number} capacity Required capacity
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.ensureCapacity = function(capacity) {
var current = this.buffer.byteLength;
if (current < capacity)
return this.resize((current *= 2) > capacity ? current : capacity);
return this;
};
/**
* Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
* {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
* @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
* @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
* written if omitted. defaults to {@link ByteBuffer#offset}.
* @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
* @returns {!ByteBuffer} this
* @expose
* @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
*/
ByteBufferPrototype.fill = function(value, begin, end) {
var relative = typeof begin === 'undefined';
if (relative) begin = this.offset;
if (typeof value === 'string' && value.length > 0)
value = value.charCodeAt(0);
if (typeof begin === 'undefined') begin = this.offset;
if (typeof end === 'undefined') end = this.limit;
if (!this.noAssert) {
if (typeof value !== 'number' || value % 1 !== 0)
throw TypeError("Illegal value: "+value+" (not an integer)");
value |= 0;
if (typeof begin !== 'number' || begin % 1 !== 0)
throw TypeError("Illegal begin: Not an integer");
begin >>>= 0;
if (typeof end !== 'number' || end % 1 !== 0)
throw TypeError("Illegal end: Not an integer");
end >>>= 0;
if (begin < 0 || begin > end || end > this.buffer.byteLength)
throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
}
if (begin >= end)
return this; // Nothing to fill
while (begin < end) this.view[begin++] = value;
if (relative) this.offset = begin;
return this;
};
/**
* Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
* `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.flip = function() {
this.limit = this.offset;
this.offset = 0;
return this;
};
/**
* Marks an offset on this ByteBuffer to be used later.
* @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
* @returns {!ByteBuffer} this
* @throws {TypeError} If `offset` is not a valid number
* @throws {RangeError} If `offset` is out of bounds
* @see ByteBuffer#reset
* @expose
*/
ByteBufferPrototype.mark = function(offset) {
offset = typeof offset === 'undefined' ? this.offset : offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
this.markedOffset = offset;
return this;
};
/**
* Sets the byte order.
* @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.order = function(littleEndian) {
if (!this.noAssert) {
if (typeof littleEndian !== 'boolean')
throw TypeError("Illegal littleEndian: Not a boolean");
}
this.littleEndian = !!littleEndian;
return this;
};
/**
* Switches (to) little endian byte order.
* @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.LE = function(littleEndian) {
this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
return this;
};
/**
* Switches (to) big endian byte order.
* @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.BE = function(bigEndian) {
this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
return this;
};
/**
* Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
* prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
* will be resized and its contents moved accordingly.
* @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
* modified according to the performed read operation.
* @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
* @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
* prepended if omitted.
* @returns {!ByteBuffer} this
* @expose
* @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
* @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
*/
ByteBufferPrototype.prepend = function(source, encoding, offset) {
if (typeof encoding === 'number' || typeof encoding !== 'string') {
offset = encoding;
encoding = undefined;
}
var relative = typeof offset === 'undefined';
if (relative) offset = this.offset;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: "+offset+" (not an integer)");
offset >>>= 0;
if (offset < 0 || offset + 0 > this.buffer.byteLength)
throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
}
if (!(source instanceof ByteBuffer))
source = ByteBuffer.wrap(source, encoding);
var len = source.limit - source.offset;
if (len <= 0) return this; // Nothing to prepend
var diff = len - offset;
if (diff > 0) { // Not enough space before offset, so resize + move
var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
var view = new Uint8Array(buffer);
view.set(this.view.subarray(offset, this.buffer.byteLength), len);
this.buffer = buffer;
this.view = view;
this.offset += diff;
if (this.markedOffset >= 0) this.markedOffset += diff;
this.limit += diff;
offset += diff;
} else {
var arrayView = new Uint8Array(this.buffer);
}
this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
source.offset = source.limit;
if (relative)
this.offset -= len;
return this;
};
/**
* Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
* prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
* will be resized and its contents moved accordingly.
* @param {!ByteBuffer} target Target ByteBuffer
* @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
* prepended if omitted.
* @returns {!ByteBuffer} this
* @expose
* @see ByteBuffer#prepend
*/
ByteBufferPrototype.prependTo = function(target, offset) {
target.prepend(this, offset);
return this;
};
/**
* Prints debug information about this ByteBuffer's contents.
* @param {function(string)=} out Output function to call, defaults to console.log
* @expose
*/
ByteBufferPrototype.printDebug = function(out) {
if (typeof out !== 'function') out = console.log.bind(console);
out(
this.toString()+"\n"+
"-------------------------------------------------------------------\n"+
this.toDebug(/* columns */ true)
);
};
/**
* Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
* {@link ByteBuffer#limit}, so this returns `limit - offset`.
* @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
* @expose
*/
ByteBufferPrototype.remaining = function() {
return this.limit - this.offset;
};
/**
* Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
* before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
* marked, sets `offset = 0`.
* @returns {!ByteBuffer} this
* @see ByteBuffer#mark
* @expose
*/
ByteBufferPrototype.reset = function() {
if (this.markedOffset >= 0) {
this.offset = this.markedOffset;
this.markedOffset = -1;
} else {
this.offset = 0;
}
return this;
};
/**
* Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
* large or larger.
* @param {number} capacity Capacity required
* @returns {!ByteBuffer} this
* @throws {TypeError} If `capacity` is not a number
* @throws {RangeError} If `capacity < 0`
* @expose
*/
ByteBufferPrototype.resize = function(capacity) {
if (!this.noAssert) {
if (typeof capacity !== 'number' || capacity % 1 !== 0)
throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
capacity |= 0;
if (capacity < 0)
throw RangeError("Illegal capacity: 0 <= "+capacity);
}
if (this.buffer.byteLength < capacity) {
var buffer = new ArrayBuffer(capacity);
var view = new Uint8Array(buffer);
view.set(this.view);
this.buffer = buffer;
this.view = view;
}
return this;
};
/**
* Reverses this ByteBuffer's contents.
* @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
* @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.reverse = function(begin, end) {
if (typeof begin === 'undefined') begin = this.offset;
if (typeof end === 'undefined') end = this.limit;
if (!this.noAssert) {
if (typeof begin !== 'number' || begin % 1 !== 0)
throw TypeError("Illegal begin: Not an integer");
begin >>>= 0;
if (typeof end !== 'number' || end % 1 !== 0)
throw TypeError("Illegal end: Not an integer");
end >>>= 0;
if (begin < 0 || begin > end || end > this.buffer.byteLength)
throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
}
if (begin === end)
return this; // Nothing to reverse
Array.prototype.reverse.call(this.view.subarray(begin, end));
return this;
};
/**
* Skips the next `length` bytes. This will just advance
* @param {number} length Number of bytes to skip. May also be negative to move the offset back.
* @returns {!ByteBuffer} this
* @expose
*/
ByteBufferPrototype.skip = function(length) {
if (!this.noAssert) {
if (typeof length !== 'number' || length % 1 !== 0)
throw TypeError("Illegal length: "+length+" (not an integer)");
length |= 0;
}
var offset = this.offset + length;
if (!this.noAssert) {
if (offset < 0 || offset > this.buffer.byteLength)
throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
}
this.offset = offset;
return this;
};
/**
* Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
* @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
* @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
* @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
* @expose
*/
ByteBufferPrototype.slice = function(begin, end) {
if (typeof begin === 'undefined') begin = this.offset;
if (typeof end === 'undefined') end = this.limit;
if (!this.noAssert) {
if (typeof begin !== 'number' || begin % 1 !== 0)
throw TypeError("Illegal begin: Not an integer");
begin >>>= 0;
if (typeof end !== 'number' || end % 1 !== 0)
throw TypeError("Illegal end: Not an integer");
end >>>= 0;
if (begin < 0 || begin > end || end > this.buffer.byteLength)
throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
}
var bb = this.clone();
bb.offset = begin;
bb.limit = end;
return bb;
};
/**
* Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
* {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
* @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
* possible. Defaults to `false`
* @returns {!ArrayBuffer} Contents as an ArrayBuffer
* @expose
*/
ByteBufferPrototype.toBuffer = function(forceCopy) {
var offset = this.offset,
limit = this.limit;
if (!this.noAssert) {
if (typeof offset !== 'number' || offset % 1 !== 0)
throw TypeError("Illegal offset: Not an integer");
offset >>>= 0;
if (typeof limit !== 'number' || limit % 1 !== 0)
throw TypeError("Illegal limit: Not an integer");
limit >>>= 0;
if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
}
// NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
// possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
return this.buffer;
if (offset === limit)
return EMPTY_BUFFER;
var buffer = new ArrayBuffer(limit - offset);
new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
return buffer;
};
/**
* Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
* {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
* @function
* @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
* Defaults to `false`
* @returns {!ArrayBuffer} Contents as an ArrayBuffer
* @expose
*/
ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
/**
* Converts the ByteBuffer's contents to a string.
* @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
* direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
* highlighted offsets.
* @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
* @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
* @returns {string} String representation
* @throws {Error} If `encoding` is invalid
* @expose
*/
ByteBufferPrototype.toString = function(encoding, begin, end) {
if (typeof encoding === 'undefined')
return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
if (typeof encoding === 'number')
encoding = "utf8",
begin = encoding,
end = begin;
switch (encoding) {
case "utf8":
return this.toUTF8(begin, end);
case "base64":
return this.toBase64(begin, end);
case "hex":
return this.toHex(begin, end);
case "binary":
return this.toBinary(begin, end);
case "debug":
return this.toDebug();
case "columns":
return this.toColumns();
default:
throw Error("Unsupported encoding: "+encoding);
}
};
// lxiv-embeddable
/**
* lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/lxiv for details
*/
var lxiv = function() {
"use strict";
/**
* lxiv namespace.
* @type {!Object.<string,*>}
* @exports lxiv
*/
var lxiv = {};
/**
* Character codes for output.
* @type {!Array.<number>}
* @inner
*/
var aout = [
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
];
/**
* Character codes for input.
* @type {!Array.<number>}
* @inner
*/
var ain = [];
for (var i=0, k=aout.length; i<k; ++i)
ain[aout[i]] = i;
/**
* Encodes bytes to base64 char codes.
* @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
* there are no more bytes left.
* @param {!function(number)} dst Characters destination as a function successively called with each encoded char
* code.
*/
lxiv.encode = function(src, dst) {
var b, t;
while ((b = src()) !== null) {
dst(aout[(b>>2)&0x3f]);
t = (b&0x3)<<4;
if ((b = src()) !== null) {
t |= (b>>4)&0xf;
dst(aout[(t|((b>>4)&0xf))&0x3f]);
t = (b&0xf)<<2;
if ((b = src()) !== null)
dst(aout[(t|((b>>6)&0x3))&0x3f]),
dst(aout[b&0x3f]);
else
dst(aout[t&0x3f]),
dst(61);
} else
dst(aout[t&0x3f]),
dst(61),
dst(61);
}
};
/**
* Decodes base64 char codes to bytes.
* @param {!function():number|null} src Characters source as a function returning the next char code respectively
* `null` if there are no more characters left.
* @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
* @throws {Error} If a character code is invalid
*/
lxiv.decode = function(src, dst) {
var c, t1, t2;
function fail(c) {
throw Error("Illegal character code: "+c);
}
while ((c = src()) !== null) {
t1 = ain[c];
if (typeof t1 === 'undefined') fail(c);
if ((c = src()) !== null) {
t2 = ain[c];
if (typeof t2 === 'undefined') fail(c);
dst((t1<<2)>>>0|(t2&0x30)>>4);
if ((c = src()) !== null) {
t1 = ain[c];
if (typeof t1 === 'undefined')
if (c === 61) break; else fail(c);
dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
if ((c = src()) !== null) {
t2 = ain[c];
if (typeof t2 === 'undefined')
if (c === 61) break; else fail(c);
dst(((t1&0x3)<<6)>>>0|t2);
}
}
}
}
};
/**
* Tests if a string is valid base64.
* @param {string} str String to test
* @returns {boolean} `true` if valid, otherwise `false`
*/
lxiv.test = function(str) {
return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
};
return lxiv;
}();
// encodings/base64
/**
* Encodes this ByteBuffer's contents to a base64 encoded string.
* @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
* @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
* @returns {string} Base64 encoded string
* @throws {RangeError} If `begin` or `end` is out of bounds
* @expose
*/
ByteBufferPrototype.toBase64 = function(begin, end) {
if (typeof begin === 'undefined')
begin = this.offset;
if (typeof end === 'undefined')
end = this.limit;
begin = begin | 0; end = end | 0;
if (begin < 0 || end > this.capacity || begin > end)
throw RangeError("begin, end");
var sd; lxiv.encode(function() {
return begin < end ? this.view[begin++] : null;
}.bind(this), sd = stringDestination());
return sd();
};
/**
* Decodes a base64 encoded string to a ByteBuffer.
* @param {string} str String to decode
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @returns {!ByteBuffer} ByteBuffer
* @expose
*/
ByteBuffer.fromBase64 = function(str, littleEndian) {
if (typeof str !== 'string')
throw TypeError("str");
var bb = new ByteBuffer(str.length/4*3, littleEndian),
i = 0;
lxiv.decode(stringSource(str), function(b) {
bb.view[i++] = b;
});
bb.limit = i;
return bb;
};
/**
* Encodes a binary string to base64 like `window.btoa` does.
* @param {string} str Binary string
* @returns {string} Base64 encoded string
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
* @expose
*/
ByteBuffer.btoa = function(str) {
return ByteBuffer.fromBinary(str).toBase64();
};
/**
* Decodes a base64 encoded string to binary like `window.atob` does.
* @param {string} b64 Base64 encoded string
* @returns {string} Binary string
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
* @expose
*/
ByteBuffer.atob = function(b64) {
return ByteBuffer.fromBase64(b64).toBinary();
};
// encodings/binary
/**
* Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
* @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
* @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
* @returns {string} Binary encoded string
* @throws {RangeError} If `offset > limit`
* @expose
*/
ByteBufferPrototype.toBinary = function(begin, end) {
if (typeof begin === 'undefined')
begin = this.offset;
if (typeof end === 'undefined')
end = this.limit;
begin |= 0; end |= 0;
if (begin < 0 || end > this.capacity() || begin > end)
throw RangeError("begin, end");
if (begin === end)
return "";
var chars = [],
parts = [];
while (begin < end) {
chars.push(this.view[begin++]);
if (chars.length >= 1024)
parts.push(String.fromCharCode.apply(String, chars)),
chars = [];
}
return parts.join('') + String.fromCharCode.apply(String, chars);
};
/**
* Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
* @param {string} str String to decode
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @returns {!ByteBuffer} ByteBuffer
* @expose
*/
ByteBuffer.fromBinary = function(str, littleEndian) {
if (typeof str !== 'string')
throw TypeError("str");
var i = 0,
k = str.length,
charCode,
bb = new ByteBuffer(k, littleEndian);
while (i<k) {
charCode = str.charCodeAt(i);
if (charCode > 0xff)
throw RangeError("illegal char code: "+charCode);
bb.view[i++] = charCode;
}
bb.limit = k;
return bb;
};
// encodings/debug
/**
* Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
* * `<` : offset,
* * `'` : markedOffset,
* * `>` : limit,
* * `|` : offset and limit,
* * `[` : offset and markedOffset,
* * `]` : markedOffset and limit,
* * `!` : offset, markedOffset and limit
* @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
* @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
* @expose
* @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
* @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
* @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
* @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
*/
ByteBufferPrototype.toDebug = function(columns) {
var i = -1,
k = this.buffer.byteLength,
b,
hex = "",
asc = "",
out = "";
while (i<k) {
if (i !== -1) {
b = this.view[i];
if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
else hex += b.toString(16).toUpperCase();
if (columns)
asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
}
++i;
if (columns) {
if (i > 0 && i % 16 === 0 && i !== k) {
while (hex.length < 3*16+3) hex += " ";
out += hex+asc+"\n";
hex = asc = "";
}
}
if (i === this.offset && i === this.limit)
hex += i === this.markedOffset ? "!" : "|";
else if (i === this.offset)
hex += i === this.markedOffset ? "[" : "<";
else if (i === this.limit)
hex += i === this.markedOffset ? "]" : ">";
else
hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
}
if (columns && hex !== " ") {
while (hex.length < 3*16+3)
hex += " ";
out += hex + asc + "\n";
}
return columns ? out : hex;
};
/**
* Decodes a hex encoded string with marked offsets to a ByteBuffer.
* @param {string} str Debug string to decode (not be generated with `columns = true`)
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
* {@link ByteBuffer.DEFAULT_NOASSERT}.
* @returns {!ByteBuffer} ByteBuffer
* @expose
* @see ByteBuffer#toDebug
*/
ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
var k = str.length,
bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
var i = 0, j = 0, ch, b,
rs = false, // Require symbol next
ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
fail = false;
while (i<k) {
switch (ch = str.charAt(i++)) {
case '!':
if (!noAssert) {
if (ho || hm || hl) {
fail = true;
break;
}
ho = hm = hl = true;
}
bb.offset = bb.markedOffset = bb.limit = j;
rs = false;
break;
case '|':
if (!noAssert) {
if (ho || hl) {
fail = true;
break;
}
ho = hl = true;
}
bb.offset = bb.limit = j;
rs = false;
break;
case '[':
if (!noAssert) {
if (ho || hm) {
fail = true;
break;
}
ho = hm = true;
}
bb.offset = bb.markedOffset = j;
rs = false;
break;
case '<':
if (!noAssert) {
if (ho) {
fail = true;
break;
}
ho = true;
}
bb.offset = j;
rs = false;
break;
case ']':
if (!noAssert) {
if (hl || hm) {
fail = true;
break;
}
hl = hm = true;
}
bb.limit = bb.markedOffset = j;
rs = false;
break;
case '>':
if (!noAssert) {
if (hl) {
fail = true;
break;
}
hl = true;
}
bb.limit = j;
rs = false;
break;
case "'":
if (!noAssert) {
if (hm) {
fail = true;
break;
}
hm = true;
}
bb.markedOffset = j;
rs = false;
break;
case ' ':
rs = false;
break;
default:
if (!noAssert) {
if (rs) {
fail = true;
break;
}
}
b = parseInt(ch+str.charAt(i++), 16);
if (!noAssert) {
if (isNaN(b) || b < 0 || b > 255)
throw TypeError("Illegal str: Not a debug encoded string");
}
bb.view[j++] = b;
rs = true;
}
if (fail)
throw TypeError("Illegal str: Invalid symbol at "+i);
}
if (!noAssert) {
if (!ho || !hl)
throw TypeError("Illegal str: Missing offset or limit");
if (j<bb.buffer.byteLength)
throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
}
return bb;
};
// encodings/hex
/**
* Encodes this ByteBuffer's contents to a hex encoded string.
* @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
* @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
* @returns {string} Hex encoded string
* @expose
*/
ByteBufferPrototype.toHex = function(begin, end) {
begin = typeof begin === 'undefined' ? this.offset : begin;
end = typeof end === 'undefined' ? this.limit : end;
if (!this.noAssert) {
if (typeof begin !== 'number' || begin % 1 !== 0)
throw TypeError("Illegal begin: Not an integer");
begin >>>= 0;
if (typeof end !== 'number' || end % 1 !== 0)
throw TypeError("Illegal end: Not an integer");
end >>>= 0;
if (begin < 0 || begin > end || end > this.buffer.byteLength)
throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
}
var out = new Array(end - begin),
b;
while (begin < end) {
b = this.view[begin++];
if (b < 0x10)
out.push("0", b.toString(16));
else out.push(b.toString(16));
}
return out.join('');
};
/**
* Decodes a hex encoded string to a ByteBuffer.
* @param {string} str String to decode
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
* {@link ByteBuffer.DEFAULT_NOASSERT}.
* @returns {!ByteBuffer} ByteBuffer
* @expose
*/
ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
if (!noAssert) {
if (typeof str !== 'string')
throw TypeError("Illegal str: Not a string");
if (str.length % 2 !== 0)
throw TypeError("Illegal str: Length not a multiple of 2");
}
var k = str.length,
bb = new ByteBuffer((k / 2) | 0, littleEndian),
b;
for (var i=0, j=0; i<k; i+=2) {
b = parseInt(str.substring(i, i+2), 16);
if (!noAssert)
if (!isFinite(b) || b < 0 || b > 255)
throw TypeError("Illegal str: Contains non-hex characters");
bb.view[j++] = b;
}
bb.limit = j;
return bb;
};
// utfx-embeddable
/**
* utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
* Released under the Apache License, Version 2.0
* see: https://github.com/dcodeIO/utfx for details
*/
var utfx = function() {
"use strict";
/**
* utfx namespace.
* @inner
* @type {!Object.<string,*>}
*/
var utfx = {};
/**
* Maximum valid code point.
* @type {number}
* @const
*/
utfx.MAX_CODEPOINT = 0x10FFFF;
/**
* Encodes UTF8 code points to UTF8 bytes.
* @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
* respectively `null` if there are no more code points left or a single numeric code point.
* @param {!function(number)} dst Bytes destination as a function successively called with the next byte
*/
utfx.encodeUTF8 = function(src, dst) {
var cp = null;
if (typeof src === 'number')
cp = src,
src = function() { return null; };
while (cp !== null || (cp = src()) !== null) {
if (cp < 0x80)
dst(cp&0x7F);
else if (cp < 0x800)
dst(((cp>>6)&0x1F)|0xC0),
dst((cp&0x3F)|0x80);
else if (cp < 0x10000)
dst(((cp>>12)&0x0F)|0xE0),
dst(((cp>>6)&0x3F)|0x80),
dst((cp&0x3F)|0x80);
else
dst(((cp>>18)&0x07)|0xF0),
dst(((cp>>12)&0x3F)|0x80),
dst(((cp>>6)&0x3F)|0x80),
dst((cp&0x3F)|0x80);
cp = null;
}
};
/**
* Decodes UTF8 bytes to UTF8 code points.
* @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
* are no more bytes left.
* @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
* @throws {RangeError} If a starting byte is invalid in UTF8
* @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
* remaining bytes.
*/
utfx.decodeUTF8 = function(src, dst) {
var a, b, c, d, fail = function(b) {
b = b.slice(0, b.indexOf(null));
var err = Error(b.toString());
err.name = "TruncatedError";
err['bytes'] = b;
throw err;
};
while ((a = src()) !== null) {
if ((a&0x80) === 0)
dst(a);
else if ((a&0xE0) === 0xC0)
((b = src()) === null) && fail([a, b]),
dst(((a&0x1F)<<6) | (b&0x3F));
else if ((a&0xF0) === 0xE0)
((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
else if ((a&0xF8) === 0xF0)
((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
else throw RangeError("Illegal starting byte: "+a);
}
};
/**
* Converts UTF16 characters to UTF8 code points.
* @param {!function():number|null} src Characters source as a function returning the next char code respectively
* `null` if there are no more characters left.
* @param {!function(number)} dst Code points destination as a function successively called with each converted code
* point.
*/
utfx.UTF16toUTF8 = function(src, dst) {
var c1, c2 = null;
while (true) {
if ((c1 = c2 !== null ? c2 : src()) === null)
break;
if (c1 >= 0xD800 && c1 <= 0xDFFF) {
if ((c2 = src()) !== null) {
if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
c2 = null; continue;
}
}
}
dst(c1);
}
if (c2 !== null) dst(c2);
};
/**
* Converts UTF8 code points to UTF16 characters.
* @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
* respectively `null` if there are no more code points left or a single numeric code point.
* @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
* @throws {RangeError} If a code point is out of range
*/
utfx.UTF8toUTF16 = function(src, dst) {
var cp = null;
if (typeof src === 'number')
cp = src, src = function() { return null; };
while (cp !== null || (cp = src()) !== null) {
if (cp <= 0xFFFF)
dst(cp);
else
cp -= 0x10000,
dst((cp>>10)+0xD800),
dst((cp%0x400)+0xDC00);
cp = null;
}
};
/**
* Converts and encodes UTF16 characters to UTF8 bytes.
* @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
* if there are no more characters left.
* @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
*/
utfx.encodeUTF16toUTF8 = function(src, dst) {
utfx.UTF16toUTF8(src, function(cp) {
utfx.encodeUTF8(cp, dst);
});
};
/**
* Decodes and converts UTF8 bytes to UTF16 characters.
* @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
* are no more bytes left.
* @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
* @throws {RangeError} If a starting byte is invalid in UTF8
* @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
*/
utfx.decodeUTF8toUTF16 = function(src, dst) {
utfx.decodeUTF8(src, function(cp) {
utfx.UTF8toUTF16(cp, dst);
});
};
/**
* Calculates the byte length of an UTF8 code point.
* @param {number} cp UTF8 code point
* @returns {number} Byte length
*/
utfx.calculateCodePoint = function(cp) {
return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
};
/**
* Calculates the number of UTF8 bytes required to store UTF8 code points.
* @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
* `null` if there are no more code points left.
* @returns {number} The number of UTF8 bytes required
*/
utfx.calculateUTF8 = function(src) {
var cp, l=0;
while ((cp = src()) !== null)
l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
return l;
};
/**
* Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
* @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
* `null` if there are no more characters left.
* @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
*/
utfx.calculateUTF16asUTF8 = function(src) {
var n=0, l=0;
utfx.UTF16toUTF8(src, function(cp) {
++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
});
return [n,l];
};
return utfx;
}();
// encodings/utf8
/**
* Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
* string.
* @returns {string} Hex encoded string
* @throws {RangeError} If `offset > limit`
* @expose
*/
ByteBufferPrototype.toUTF8 = function(begin, end) {
if (typeof begin === 'undefined') begin = this.offset;
if (typeof end === 'undefined') end = this.limit;
if (!this.noAssert) {
if (typeof begin !== 'number' || begin % 1 !== 0)
throw TypeError("Illegal begin: Not an integer");
begin >>>= 0;
if (typeof end !== 'number' || end % 1 !== 0)
throw TypeError("Illegal end: Not an integer");
end >>>= 0;
if (begin < 0 || begin > end || end > this.buffer.byteLength)
throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
}
var sd; try {
utfx.decodeUTF8toUTF16(function() {
return begin < end ? this.view[begin++] : null;
}.bind(this), sd = stringDestination());
} catch (e) {
if (begin !== end)
throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
}
return sd();
};
/**
* Decodes an UTF8 encoded string to a ByteBuffer.
* @param {string} str String to decode
* @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
* {@link ByteBuffer.DEFAULT_ENDIAN}.
* @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
* {@link ByteBuffer.DEFAULT_NOASSERT}.
* @returns {!ByteBuffer} ByteBuffer
* @expose
*/
ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
if (!noAssert)
if (typeof str !== 'string')
throw TypeError("Illegal str: Not a string");
var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
i = 0;
utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
bb.view[i++] = b;
});
bb.limit = i;
return bb;
};
return ByteBuffer;
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.