code stringlengths 2 1.05M |
|---|
const test = require('../../');
test.beforeEach(fail);
test(pass);
function pass(t) {
t.end();
}
function fail(t) {
t.fail();
t.end();
}
|
var should = require('should');
var ipt_new = require('../../../lib/iptables').new;
var deleteChain = require('../../../lib/iptables').deleteChain;
module.exports = function () {
describe('#new', function () {
it('should be defined', function () {
should.exist(ipt_new);
});
it('should throw an error when invoked without `options` argument', function () {
ipt_new.bind(null).should.throw();
});
describe('when executing with valid options', function () {
var chain_name;
// Resetting `iptables` state.
afterEach(function (done) {
deleteChain({
table: 'filter',
chain: 'new-user-chain-' + chain_name
}, function (error) {
if (error) {
done(error);
return;
}
done();
});
});
describe('with the full options', function () {
it('should correctly add the new chain', function (done) {
chain_name = Date.now();
ipt_new({
table: 'filter',
chain: 'new-user-chain-' + chain_name
}, function (error) {
if (error) {
done(error);
return;
}
done();
});
});
});
describe('without specifying `table`', function () {
it('should correctly add the new chain', function (done) {
chain_name = Date.now();
ipt_new({
chain: 'new-user-chain-' + chain_name
}, function (error) {
if (error) {
done(error);
return;
}
done();
});
});
});
});
describe('when executing with invalid options', function () {
describe('without specifying `chain`', function () {
it('should throw an error', function (done) {
ipt_new({
table: 'filter'
}, function (error) {
error.should.not.be.null;
done();
});
});
});
});
});
}; |
(function (angular) {
'use strict';
angular.module('StructureModule')
.controller('ListStructureController', ['$scope', '$location', 'moment', '$http', 'toastr', "$rootScope", '$state', 'Structures', '$window',
function ($scope, $location, moment, $http, toastr, vAccordion, $state, Structures) {
$scope.me = window.SAILS_LOCALS.me;
if (!$scope.me.kadr && !$scope.me.admin) $state.go('home');
$scope.query = {
// where: {}
// sortField: $scope.sortField,
// sortTrend: $scope.sortTrend,
// limit: $scope.limitAll,
// page: 0,
// sd: $scope.start,
// regex:'',
// property: 'name'
};
$scope.changed = function () {
let quest = '';
quest = angular.element(document.querySelector(".quest")).text();
if (!quest) return;
$http.get('/user/getUsersDepartment/' + quest)
.then(function (response) {
console.log('response: ', response);
$scope.users = response.data;
});
console.log('ups22:', quest);
};
/**
* VALUES
*/
$scope.defaultRows = 50;
$scope.limitRows = [50, 100, 300, 500, 700, 1000];
$scope.currentPage = 1; // инициализируем кнопку постраничной навигации
$scope.allRowsView = 'загружено:';
$scope.fioArea = 'ФИО';
$scope.loginArea = 'Логин';
$scope.dateArea = 'Дата';
$scope.startPeriodArea = 'Приход';
$scope.endPeriodArea = 'Уход';
$scope.factArea = 'Отработанное время';
$scope.added = 'Добавить сотрудника';
$scope.showBt = false; // показать кнопку добавления объекта
$scope.sortField = 'name'; // поле сортировки
$scope.sortTrend = 1; // направление сортировки
$scope.param = 'date';
$scope.fieldName = 'муж/жена';
$scope.charText = '';
$scope.searchText = '';
$scope.page_number = 0;
$scope.limitAll = '';
$scope.where = '^.';
$scope.sd = '';
$scope.enabledButton = false;
$scope.styleObj = {
color: false,
border: false,
size: false
};
$scope.vis = false;
$scope.data = [];
$scope.data['selectedOption'] = {};
$scope.propertyName = 'lastName';
$scope.propertyName2 = 'date';
$scope.reverse = false;
$scope.countChar = 3; // Кол-во знаков от фамилии
$scope.filedName = '_id';
$scope.sortRevers = function (field) {
$scope.sortTrend = (+$scope.sortTrend > 0) ? -1 : 1;
$scope.sortField = field;
};
$scope.options =
[
{display: "Древовидная структура", value: "structure"}
];
$scope.modeSelect = $scope.options[0];
$scope.structureView = "/js/private/admin/structures/views/home.admin.structures.html";
//$scope.workView = "/js/private/admin/skds/views/home.admin.skds.work.html";
// $scope.testView = "/js/private/admin/skds/views/test.html";
// $scope.tableView = "/js/private/admin/skds/views/home.admin.skds.table.html";
// $scope.listView = "/js/private/admin/skds/views/home.admin.skds.list.html";
// $scope.actionView = "/js/private/admin/skds/views/home.admin.skds.action.html";
$scope.$watch('where', function (value, old) {
// console.log('New val: ',value);
// console.log('Old val: ',old);
$scope.query.regex = value;
$scope.refresh();
});
$scope.toggleBlur = function (mx) {
$scope.query.sd = mx;
$scope.mx = mx;
$scope.refresh();
};
$scope.getPage = function (num) {
$scope.page_number = num;
};
$scope.sortBy = function (propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
/**
* Конструктор хлебных крошек
* @constructor
*/
function BreadCrumb() {
var name;
var path;
this.arr = [];
}
BreadCrumb.prototype.add = function () {
this.arr.push({name: this.name, path: this.path});
};
BreadCrumb.prototype.set = function (name, path) {
this.name = name;
this.path = path;
this.add();
};
BreadCrumb.prototype.getAll = function () {
return this.arr;
};
var breadcrumb = new BreadCrumb();
breadcrumb.set('Home', 'home');
breadcrumb.set('Admin', '/admin');
breadcrumb.set('Structures', '/admin/' + $state.current.url);
$scope.breadcrumbs = breadcrumb;
$scope.refresh = function () {
Structures.query($scope.query,
function (structures) {
$scope.items = structures;
}, function (err) {
toastr.error(err.data.details, 'Ошибка 7700! ' + err.data.message);
});
};
$scope.refresh();
}]);
})(window.angular); |
import {
buffer,
sampleFn
} from './Util';
import * as Arc from './geometry/Arc';
import * as Path from './geometry/Path';
import * as Point from './geometry/Point';
import * as MouseTelemetrics from './io/MouseTelemetrics';
// import * as MouseWheel from './io/MouseWheel';
// import * as VirtualScroll from './io/VirtualScroll';
// import * as WASD from './io/WASD';
import * as Analysis from './math/Analysis';
import * as Constants from './math/Constants';
import * as Random from './math/Random';
import * as Range from './math/Range';
import * as AnimationPlayer from './media/AnimationPlayer';
import * as CuePoint from './media/CuePoint';
import * as Timeline from './media/Timeline';
import * as SimplexNoise from './noise/SimplexNoise';
import * as Color from './pixels/Color';
import * as Colormap from './pixels/Colormap';
import * as RelativePosition from './position/RelativePosition';
import * as Telemetrics from './position/Telemetrics';
export default {
buffer,
sampleFn,
Arc,
Path,
Point,
MouseTelemetrics,
// MouseWheel,
// VirtualScroll,
// WASD,
Analysis,
Constants,
Random,
Range,
AnimationPlayer,
CuePoint,
Timeline,
SimplexNoise,
Color,
Colormap,
RelativePosition,
Telemetrics
};
|
define(function (require) {
var _ = require("underscore"),
BaseView = require("baseView"),
TrackEditorTemplateString = require("text!templates/trackEditor/trackEditor.html"),
SequenceProgressView = require("./views/sequenceProgressView"),
GridView = require("./views/gridView"),
InstrumentPanelView = require("./views/instrumentPanelView");
var TrackEditorView = BaseView.extend({
className: "track-editor",
trackEditorTemplate: _.template(TrackEditorTemplateString),
fadeTime: 170,
eventBusEvents: {
"trackSelected": "updateTrackModel"
},
render: function () {
this.$el.html(this.trackEditorTemplate());
this.sequenceProgressView = this.addChildView(SequenceProgressView, {
el: this.$(".sequence-progress:first")
});
this.instrumentPanelView = this.addChildView(InstrumentPanelView, {
el: this.$(".instrument-panel:first")
});
this.gridView = this.addChildView(GridView, {
el: this.$(".grid-container:first")
});
if (this.model)
this.updateTrackModel(this.model);
return this;
},
updateTrackModel: function (trackModel) {
this.setModel(trackModel);
this.sequenceProgressView.setModel(trackModel.get("sequencer"));
this.sequenceProgressView.render();
this.gridView.setModel(trackModel.get("sequence"));
this.gridView.render();
this.instrumentPanelView.setInstrumentManager(trackModel.get("instrumentManager"));
this.instrumentPanelView.render();
}
});
return TrackEditorView;
});
|
var os = require('os')
var fs = require('fs')
var im = require('imagemagick')
var path = require('path')
var async = require('async')
var imgMeta = require('./image-meta')
var pxToGeo = require('./px-to-geo')
var geoCoords = require('./geo-coords')
/**
* Splits an image into tiles
* @param {String} filename input image
* @param {Number} tileSize Square size for the resultant tiles (in pixels)
* @param {Number} overlap Amount by which to overlap tiles in x and y (in pixels)
* @param {Function} callback
*/
module.exports = function (filename, tileSize, overlap, callback){
var tile_wid = tileSize;
var tile_hei = tileSize;
var step_x = tile_wid - overlap;
var step_y = tile_hei - overlap;
var basename = path.basename(filename).split('.')[0]
var dirname = path.dirname(filename)
var metadata = geoCoords.getMetadata(filename)
var json_filename = dirname + '/' + basename + '.json'
geoCoords.writeMetaToJSON( json_filename, metadata ) // write metadata for coordinate interpolations
var content = JSON.parse( fs.readFileSync( dirname + '/' + basename + '.json' ) )
var size = content.metadata.size
var reference_coordinates = content.metadata.reference_coordinates
// Tile creator
var create_tile_task = function (task, done) {
var row = task.row
var col = task.col
var offset_x = task.offset_x
var offset_y = task.offset_y
// crop current tile
var outfilename = dirname + '/' + basename + '_' + row + '_' + col + '.jpeg'
var crop_option = tile_wid + 'x' + tile_hei + '+' + offset_x + '+' + offset_y
var extent_option = tile_wid + 'x' + tile_hei
/* Convert corner and center pixel coordinates to geo */
var coords = {
upper_left : pxToGeo( offset_x, offset_y, size.x, size.y, reference_coordinates),
upper_right : pxToGeo( offset_x + tile_wid, offset_y, size.x, size.y, reference_coordinates),
bottom_right : pxToGeo( offset_x + tile_wid, offset_y + tile_hei, size.x, size.y, reference_coordinates),
bottom_left : pxToGeo( offset_x, offset_y + tile_hei, size.x, size.y, reference_coordinates),
center : pxToGeo( offset_x + tile_wid / 2, offset_y + tile_hei / 2, size.x, size.y, reference_coordinates) // NOT (lower_right.lat - upper_left.lat, lower_right.lon - upper_left.lon) because meridians and parallels
}
// console.log('creating tile...', task) // DEBUG CODE
im.convert([ filename + '[0]', '-crop', crop_option, '-background', 'black', '-extent', extent_option, '-gravity', 'center', '-compose', 'Copy', '+repage', outfilename ], function (err, stdout) {
if (err) return done(err)
imgMeta.write(outfilename, '-userComment', coords, done) // write coordinates to tile image metadata
})
}
// Init task queue
var concurrency = os.cpus().length
var queue = async.queue(create_tile_task, concurrency)
// Completion callback
queue.drain = function (error, result) {
var prof2 = new Date().getTime() / 1000
console.log(' Finished tilizing mosaic: ' + filename);
callback(error, result)
}
// Push tile tasks into queue
for( var offset_x=0, row=0; offset_x<=size.x; offset_x+=step_x, row+=1) {
for( var offset_y=0, col=0; offset_y<=size.y; offset_y+=step_y, col+=1) {
queue.push({
row: row,
col: col,
offset_x: offset_x,
offset_y: offset_y
})
}
} // end outer for loop
}
|
mySyncSuite = {
name: 'mySyncSuite',
testSyncTest: function(test){
test.isTrue(true);
}
};
Munit.run(mySyncSuite);
myAsyncSuite = {
name: 'myAsyncSuite',
testAsyncTest: function(test, waitFor){
var onTimeout = function(){
test.isTrue(true);
};
Meteor.setTimeout(waitFor(onTimeout), 50);
}
};
Munit.run(myAsyncSuite);
tddTestSuite = {
name: "TDD test suite",
suiteSetup: function () {
// Let's do 'cleanup' in suiteSetup too, in case another suite didn't clean up properly
spies.restoreAll();
stubs.restoreAll();
log.info("I'm suiteSetup");
},
setup: function () {
log.info("I'm setup");
spies.create('log', console, 'log');
},
tearDown: function () {
spies.restoreAll();
log.info("I'm tearDown");
},
suiteTearDown: function () {
log.info("I'm suiteTearDown");
spies.restoreAll();
stubs.restoreAll();
},
testSpies: function (test) {
console.log('Hello world');
expect(spies.log).to.have.been.calledWith('Hello world');
},
clientTestIsClient: function (test) {
test.isTrue(Meteor.isClient);
test.isFalse(Meteor.isServer);
},
serverTestIsServer: function(test){
test.isTrue(Meteor.isServer);
test.isFalse(Meteor.isClient);
},
tests: [
{
name: "skipped client test",
type: 'client',
skip: true,
func: function (test) {
test.isTrue(true)
}
},
{
name: "async test with timeout",
timeout: 500,
func: function (test, waitFor) {
var onTimeout = function(){
test.isTrue(true);
};
Meteor.setTimeout(waitFor(onTimeout), 50);
}
}
]
};
Munit.run(tddTestSuite);
|
version https://git-lfs.github.com/spec/v1
oid sha256:bcdb15d55babb534c630cbc242a81c8e94982b6bd3ccb14a7c486b8ef4ca548e
size 173319
|
/**
* Sample VIEW script.
*
* @author Stagejs.CLI
* @created Wed May 17 2017 18:16:07 GMT-0700 (PDT)
*/
;(function(app){
app.view('Layout', {
template: '@view/ide/layout.html',
//[editors]: {...},
coop: [
'point-layout-reset-confirmed', //user confirm to delete a line attaches to a certain point
'delete-local-view', //remove a view from local storage
],
initialize: function(){
//indicate whether endpoint menu is current being shown or not
this.endpointMenuShown = false;
//indicate whether it is outline only
this.outlineOnly = false;
//indicate whether current view has been edited
this.modified = false;
},
onReady: function(){
},
onNavigateTo: function(path){
var that = this;
//remind the name for this view
if(path)
this.editingViewName = path.slice().pop();
else
this.editingViewName = '';
app.remote({
url: '/api/getViewList',
async: false,
}).done(function(data){
//locally stored configurations
var layouts = app.store.get('__layouts'),
//stored configuration for current view
current = app.store.get('__current');
if(path && !layouts[that.editingViewName] && !_.contains(data, that.editingViewName)){
app.get('Overlay.CreateNewView')
.create({
data: {
viewName: that.editingViewName
}
})
.overlay({
effect: false
});
return;
}//add newly created view to the collection
// layouts[that.editingViewName] = {
// layout: ['1'],
// };
//trim data, to show view list both for local stored layouts and remote layouts
var viewList = data.slice();
_.each(viewList, function(viewName, index){
viewList[index] = {
name: viewName,
source: 'remote'
};
});
_.each(layouts, function(cfg, viewName){
//not contain in the list, pre-pend to the list
if(!_.contains(data, viewName)){
viewList.unshift({
name: viewName,
source: 'local'
});
}
});
//add locally saved to view to viewList
that.show('menu', 'LayoutEditMenu', {
data: {
items: viewList,
layout: true,
method: 'Layout',
viewName: that.editingViewName,
},
});
if(path){
//check whether __current is pointing to the loading view,
//if not rewrite __current based on stored data
if(current.viewName !== that.editingViewName){
//clear __current in cache
app.store.remove('__current');
//overwrite current
current = app.store.set('__current', layouts[that.editingViewName] || {viewName: that.editingViewName});
}
//check if loading view is from backend
if(_.contains(data, that.editingViewName)){
//initialize app._global
that.initializeGlobal({});
//flip the outlineOnly flag
that.outlineOnly = true;
//show mesh only for first layer region outlines
that.show('mesh', 'Layout.Mesh', {
data: {
'outline-only': true
}
}).once('ready', function(){
//dipict first layer regions
that.show('preview', that.editingViewName).once('ready', function(){
that.genLayoutFromTemplate(that.getViewIn('preview'), that.getViewIn('preview').$el);
});
});
}else {
//checkout local storage for the loading view
//honor __current
that.initializeGlobal(current);
//honor __layouts
if(layouts[that.editingViewName]){
//show the view preview first, in order to pick up html and size
that.show('preview', app.view({
layout: layouts[that.editingViewName].layout
}))
.once('ready', function(){
that.genLayoutFromTemplate(that.getViewIn('preview'), that.getViewIn('preview').$el);
}); //!later on show saved configs
}
else{
//initialize an object for the new view in __layouts
layouts[that.editingViewName] = {};
//sync __layouts with local storage
app.store.remove('__layouts');
app.store.set('__layouts', _.deepClone(layouts));
//show a new blank view
that.show('preview', app.view({
template: 'NO TEMPLATE TBD',
}));
}
//show the mesh grids
that.show('mesh', 'Layout.Mesh');
}
}else{
//close preview and mesh view if no path is given
if(that.getViewIn('mesh'))
that.getViewIn('mesh').close();
if(that.getViewIn('preview'))
that.getViewIn('preview').close();
}
});
},
actions: {
slide: function(){
this.$el.find('.left-container').toggleClass('closed');
},
//action to delete a line in certain direction of an endpoint
'delete-line': function($self){
//if the line is deletable
if($self.find('i').hasClass('deletable')){
(new (app.get('Overlay.LayoutResetConfirm'))({
data: {
anchor: $self
}
})).overlay({
effect: false,
class: 'confirm-overlay warning-title',
});
}else{//NOT deletable
app.notify('Cannot Delete', 'This line cannot be deleted!', 'error', {icon: 'fa fa-reddit-alien'});
}
},
},
//========================================== coop event handlers ==========================================//
//open menu when clicked on endpoints
onEndpointClicked: function(e){
//call function:endpointClicked to handle this coop event
this.endpointClicked(e);
},
//close endpoint menu
onCloseEndpointMenu: function(){
this.closeMenu();
},
//user confirm to delete a certain line attached to a certain point
onPointLayoutResetConfirmed: function($anchor){
//delete line
this.deleteLine($anchor.data('direction'));
//sync local storage data
this.syncLocal();
//re-generate layout
this.onLayoutConfigChanged();
//setup dirty-bit since point has been deleted
if(!this.modified)
this.setDirtyBit(true);
},
//function to handle local storage syncing
onSyncLocal: function(){
this.syncLocal();
},
//function to handle saving current view layout configurations into cache
onSaveLayout: function(obj){
//cache
var layouts = app.store.get('__layouts');
//modified layouts[this.editingViewName]
layouts[this.editingViewName] = _.deepClone(app.store.get('__current'));//_.extend({viewName: this.editingViewName, layout: app.store.get('__current')}, app._global);
//save it to cache with a deep copy, avoid werid issue
app.store.set('__layouts', _.deepClone(layouts));
//once layout saved flip the dirty bit
if(this.modified)
this.setDirtyBit(false);
//show notification
app.notify('Success!', 'Layout configuration has been saved.', 'ok', {icon: 'fa fa-fort-awesome'});
//save from switching context, need to honor the switching
if(obj)
app.navigate('_IDE/' + obj.method + '/' + obj.next);
},
//on layout config changed, re-generate layout immedieately
onLayoutConfigChanged: function(){
//on closing generate layout if this is local view
var temp = this.generateLayout(),
that = this;
//once layout changed flip the dirty bit
if(!this.modified)
this.setDirtyBit(true);
//save the newly generated layout as a template for local view
this
.show('preview', app.view({
layout: _.extend({bars: false}, temp.layout)
}))
.once('ready', function(){
//update current
var current = app.store.get('__current');
current.layout = _.extend({bars: false}, temp.layout);
//current.template = that.getViewIn('preview').parentRegion.$el.html();
//sync local storage
app.store.set('__current', _.deepClone(current));
//add new marker
that.genLayoutFromTemplate(that.getViewIn('preview'), that.getViewIn('preview').$el);
});
},
//function to handle local view remove
onDeleteLocalView: function(viewName){
var layouts = app.store.get('__layouts');
//remove stored view
delete layouts[viewName];
//sync to local storage
app.store.remove('__layouts');
app.store.set('__layouts', _.deepClone(layouts));
//navigate to a view
app.navigate('_IDE/Layout/');
},
//========================================== helper functions ==========================================//
//functions to initialize app._global
initializeGlobal: function(obj){
//create a global object to store points, horizontal lines and vertical lines
app._global.endPoints = obj.endPoints || {};
app._global['vertical-line'] = obj['vertical-line'] || [];
app._global['horizontal-line'] = obj['horizontal-line'] || [];
},
//function to sync __current local storage
syncLocal: function(){//alias for the coop function, to be used in this view
var current = _.extend(app.store.get('__current'), {
endPoints: app._global.endPoints,
'horizontal-line': app._global['horizontal-line'],
'vertical-line': app._global['vertical-line'],
viewName: this.editingViewName //keep a reference for later comparison on loading
});
//remove old for a clean setup
app.store.remove('__current');
//save current, with a duplicated object not a reference
app.store.set('__current', _.deepClone(current));
},
//function to setup the dirty-bit for the saving button
setDirtyBit: function(modified){
if(modified){
this.modified = true;
this.$el.find('.view-layout-menu .dirty-bit').removeClass('hidden');
}else{
this.modified = false;
this.$el.find('.view-layout-menu .dirty-bit').addClass('hidden');
}
},
//function to depict first layer regions
genLayoutFromTemplate: function(viewInstance, $preview){
var previewLeft = viewInstance.$el.offset().left,
previewTop = viewInstance.$el.offset().top,
that = this;
//remove all the size marker
if($preview)
$preview.find('.size-marker').remove();
//get all first layer regions
_.each(viewInstance.$el.find('div.region'), function(el, index){
var $el = $(el), $parent = $el.parent(), firstLayer = true, top, left, width, height;
//trace every div with region tags, to see if any of its parents has class region
//if yes, then it is NOT a first layer region.
//if not, then it is a first layer region
while(!$parent.hasClass('region-preview')){
//not firstLayer
if($parent.hasClass('region')){
firstLayer = false;
break;
}else{//continue trace
$parent = $parent.parent();
}
}
//view from backend do not have layout, only mark the first layer regions
if(firstLayer){
top = $el.offset().top - previewTop;
left = $el.offset().left - previewLeft;
height = $el.height();
width = $el.width();
var previewHeight = $preview.height(),
previewWidth = $preview.width();
var markerBottom = previewHeight - height - top,
markerLeft = left;
//insert marker into preview view, but at the position of left corner of every region
$preview.append('<div class="size-marker" style="bottom:' + markerBottom + 'px;left:' + markerLeft + 'px;">W: '+ width +' H: ' + height + '</div>');
if(that.outlineOnly)
//draw a dashed path surrounding current div
that.getViewIn('mesh').drawPath('M' + left + ' ' + top + 'l' + width + ' 0l0 ' + height + 'l' + (-width) + ' 0l0 ' + - (height))
.attr('class', 'region-outline');
}
});
},
//function for generating layout
generateLayout: function(adjusting, overlay){
var x = [], y = [], that = this, returnData;
//generate a list of x and y coordinates from end points
_.each(app._global.endPoints, function(endPoint, pid){
var flag = false;
if(!_.contains(x, endPoint.x)){//not contained in the x
if(!that.checkContained(x, endPoint, 'x')){//adjust the coordinate if necessary
x.push(endPoint.x);
//sort
x = _.sortBy(x, function(num){ return num;});
}
}
if(!_.contains(y, endPoint.y)){//y
if(!that.checkContained(y, endPoint, 'y')){
y.push(endPoint.y);
//sort
y = _.sortBy(y, function(num){ return num;});
}
}
});
//augment horizontal lines and vertical lines based on coordiates extracted from end points
//horizontal
_.each(app._global['horizontal-line'], function(hline){
//left anchor
that.checkContained(x, hline, 'x1');
//right anchor
that.checkContained(x, hline, 'x2');
//y
that.checkContained(y, hline, 'y');
});
//vertical
_.each(app._global['vertical-line'], function(vline){
//top anchor
that.checkContained(y, vline, 'y1');
//bottom anchor
that.checkContained(y, vline, 'y2');
//x
that.checkContained(x, vline, 'x');
});
//acquire remote api for generating layout
app.remote({
url: '/api/generate',
async: false,
payload: {
endPoints: app._global.endPoints,
//max length h/v lines are 100 (%).
hlines: app._global['horizontal-line'],
vlines: app._global['vertical-line'],
}
})
.done(function(data){
//assign return data
returnData = data;
})
.fail(function(error){
app.notify('Error!', 'Generating error.', 'error', {icon: 'fa fa-reddit-alien'});
});
//debug log
app.debug('x array', x, 'y array', y);
app.debug('endPoints exported from generate action', app._global.endPoints);
app.debug('h-lines exported from generate action', app._global['horizontal-line']);
app.debug('v-lines exported from generate action', app._global['vertical-line']);
return returnData;
},
//function to align points within a certain margin of error(app._global.tolerance)
checkContained: function(arr, obj, key){
var flag = false;
//check whether in the margin of error
//if yes, correct it
_.each(arr, function(single){
if(
(single === 0 && obj[key] <= app._global.tolerance) ||//tolerance is 0.02 need to magnify it 100 times
(single === 100 && obj[key] >= 100 - app._global.tolerance) ||
(obj[key] >= (single - app._global.tolerance) && obj[key] <= (single + app._global.tolerance))
){
obj[key] = single;
flag = true;
}
});
return flag;
},
//========================================== functions for endpoint clicking ==========================================//
//endpoint click callback function
endpointClicked: function(e){
//reset
this.cleanIndication();
//vars
var $target = $(e.target),
radius = this.radius,
width = this.$el.find('.end-point-menu').width(),
height = this.$el.find('.end-point-menu').height(),
x = $target.attr('cx'),
y = $target.attr('cy');
var pid = $target.attr('point-id'),
point = app._global.endPoints[pid];
//store point object in View
this.pointClicked = point;
//check if point is on frame, if yes do not show menu
if(
point.x <= 0 + app._global.tolerance ||
point.y <= 0 + app._global.tolerance ||
point.x >= 100 - app._global.tolerance||
point.y >= 100 - app._global.tolerance
) {
//notification
app.notify('Cannot be Operated', 'End points on outter frame cannot be operated! Choose inside end points inside!', 'error', {icon: 'fa fa-reddit-alien'});
//close currently opened menu, if showing
if(this.endpointMenuShown)
//this.closeMenu(); //!!do not close menu after a 'wrong' click with menu currently showing somewhere else
return;
}
//add active tag to current element
//!!Note: jQuery2 does NOT support SVG element addClass. jQuery3 claims it has solved this problem.
$target.attr('class', 'end-point draggble active');
//show menu
this.$el.find('.end-point-menu').css({
left: (x - width / 2) + 'px',
top: (y - height / 2) + 'px'
}).removeClass('hidden');
//flip flag
this.endpointMenuShown = true;
//NOW check in four directions whether there is a line attached
//if no pass
//if yes check whether that line can be deleted or not
this.colorArrows(point);
},
//function for closing endpoint menu
closeMenu: function(){
//hide menu
this.$el.find('.end-point-menu').addClass('hidden');
this.endpointMenuShown = false;
//cleanup
this.cleanIndication();
},
//clear active class from endpoint and reset the styling of arrow
cleanIndication: function(){
//remove active class
this.parentCt.$el.find('.end-point.active').attr('class', 'end-point draggble');
//clean all the indication color
this.$el.find('.indicator > i').removeClass('text-muted text-danger deletable');
},
//color the arrows in the endpoint menu based on the result of checkDeletable()
colorArrows: function(point){
this.cleanIndication();
//top
if(point.top){
this.checkDeletable(point.top, 'up');
}else{
this.$el.find('.up > i').addClass('text-muted');
}
//bottom
if(point.bottom){
this.checkDeletable(point.bottom, 'down');
}else{
this.$el.find('.down > i').addClass('text-muted');
}
//left
if(point.left){
this.checkDeletable(point.left, 'left');
}else{
this.$el.find('.left > i').addClass('text-muted');
}
//right
if(point.right){
this.checkDeletable(point.right, 'right');
}else{
this.$el.find('.right > i').addClass('text-muted');
}
},
//check whether a single line is deletable or not
checkDeletable: function(lineId, position){
var line, dir, startPoint, endPoint,
that = this;
if(position === 'up' || position === 'down'){
line = _.find(app._global['vertical-line'], function(vline){ return vline.id === lineId; });
dir = 'v';
}
else{
dir = 'h';
line = _.find(app._global['horizontal-line'], function(hline){ return hline.id === lineId; });
}
//store line for later reference !!maybe need to change it later
//this.lines[position] = line;
//if horizontal line, two end points need to both have top and bottom
if(dir === 'h'){
startPoint = app._global.endPoints[line.left];
endPoint = app._global.endPoints[line.right];
if(startPoint.top && startPoint.bottom && endPoint.top && endPoint.bottom){//deletable
this.$el.find('.' + position + ' > i').addClass('text-danger deletable');
return true;
}
else//not deletable
this.$el.find('.' + position + ' > i').addClass('text-muted');
}
//if vertical line, two end points need to both have left and right
else{
startPoint = app._global.endPoints[line.top];
endPoint = app._global.endPoints[line.bottom];
if(startPoint.left && startPoint.right && endPoint.left && endPoint.right){//deletable
this.$el.find('.' + position + ' > i').addClass('text-danger deletable');
return true;
}
else//not deletable
this.$el.find('.' + position + ' > i').addClass('text-muted');
}
return false;
},
//========================================== functions to handle deleting lines ==========================================//
//function for deleting the from a point
deleteLine: function(position){
var startPoint, endPoint,
left, right, top, bottom,
line,
that = this;
//get the line object
if(position === 'up' || position === 'down')
line = _.find(app._global['vertical-line'], function(vline){ return vline.id === that.pointClicked[position === 'up' ? 'top' : position === 'down' ? 'bottom' : position];});
else
line = _.find(app._global['horizontal-line'], function(hline){ return hline.id === that.pointClicked[position === 'up' ? 'top' : position === 'down' ? 'bottom' : position];});
if(position === 'up' || position === 'down'){//deleting vertical line
//get end points
startPoint = app._global.endPoints[line.top];
endPoint = app._global.endPoints[line.bottom];
}else{//deleting horizontal line
//get end points
startPoint = app._global.endPoints[line.left];
endPoint = app._global.endPoints[line.right];
}
//start point not attached anymore
if(!this.checkAttached(startPoint, line.id, position)){
this.removeAttachedPoint(startPoint, (position === 'up' || position === 'down') ? 'v' : 'h');
}
//end point not attached anymore
if(!this.checkAttached(endPoint, line.id, position)){
this.removeAttachedPoint(endPoint, (position === 'up' || position === 'down') ? 'v' : 'h');
}
//remove current line
this.removeLineFromCollection(line.id, (position === 'up' || position === 'down') ? 'v' : 'h', true);
//redraw after line deleted
this.getViewIn('mesh').redrawAll();
//if point still exists re-color, if not hide
if(app._global.endPoints[this.pointClicked.id]){
this.colorArrows(this.pointClicked);
//add active class back
_.defer(function(){
_.each($('.end-point.draggble'), function(el){
var $el = $(el);
if($el.attr('point-id') === that.pointClicked.id)
$el.attr('class', 'end-point draggble active');
});
});
}
else{
this.$el.find('.end-point-menu').addClass('hidden');
//flip flag
this.shown = false;
}
app.notify('Success!', 'Line has been deleted.', 'ok', {icon: 'fa fa-fort-awesome'});
},
//function to check whether this will point still attached after deletion
checkAttached: function(point, selfId, position){
if(position === 'up' || position === 'down'){//check vertical lines
if(//4 attachments must have at least one that is not deleting line
(point.top && point.top !== selfId) ||
(point.bottom && point.bottom !== selfId)
)
return true;
}else{//check horizontal lines
if(//4 attachments must have at least one that is not deleting line
(point.left && point.left !== selfId) ||
(point.right && point.right !== selfId)
)
return true;
}
return false;
},
//function to remove a line from the global line collection
removeLineFromCollection: function(lineId, dir, updateEndpoint){
var line;
if(dir === 'h'){//horizontal line
if(updateEndpoint){
//delete end pointer point reference
line = _.find(app._global['horizontal-line'], function(hline){ return hline.id === lineId; });
app._global.endPoints[line.left] && delete app._global.endPoints[line.left].right;
app._global.endPoints[line.right] && delete app._global.endPoints[line.right].left;
}
//delete line
app._global['horizontal-line'] = _.without(app._global['horizontal-line'], _.find(app._global['horizontal-line'], function(hline){ return hline.id === lineId; }));
}else{//vertical line
if(updateEndpoint){
//delete end pointer point reference
line = _.find(app._global['vertical-line'], function(vline){ return vline.id === lineId; });
app._global.endPoints[line.top] && delete app._global.endPoints[line.top].bottom;
app._global.endPoints[line.bottom]&& delete app._global.endPoints[line.bottom].top;
}
//delete line
app._global['vertical-line'] = _.without(app._global['vertical-line'], _.find(app._global['vertical-line'], function(vline){ return vline.id === lineId; }));
}
},
//function to remove standalone point after deletion
removeAttachedPoint: function(point, dir){
var pre, after, x1, x2, y1, y2, startPoint, endPoint,
newLineId = _.uniqueId((dir === 'h') ? 'vertical-' + app._global.generation + '-' : 'horizontal-' + app._global.generation + '-');
if(dir === 'h'){//deleting horizontal line
//get two vertical segments
pre = _.find(app._global['vertical-line'], function(vline){ return vline.id === point.top;});
after = _.find(app._global['vertical-line'], function(vline){ return vline.id === point.bottom;});
//assign new line coords
x1 = x2 = pre.x;
y1 = pre.y1;
y2 = after.y2;
startPoint = pre.top;
endPoint = after.bottom;
//update end points' pointer to the new line
app._global.endPoints[pre.top].bottom = newLineId;
app._global.endPoints[after.bottom].top = newLineId;
}else{//deleting vertical line
//get two horizontal segments
pre = _.find(app._global['horizontal-line'], function(vline){ return vline.id === point.left;});
after = _.find(app._global['horizontal-line'], function(vline){ return vline.id === point.right;});
//assign new line coords
x1 = pre.x1;
x2 = after.x2;
y1 = y2 = pre.y;
startPoint = pre.left;
endPoint = after.right;
//update end points' pointer to the new line
app._global.endPoints[pre.left].right = newLineId;
app._global.endPoints[after.right].left = newLineId;
}
//remove old lines and the point
this.removeLineFromCollection(pre.id, (dir === 'h') ? 'v' : 'h');//flip
this.removeLineFromCollection(after.id, (dir === 'h') ? 'v' : 'h');
delete app._global.endPoints[point.id];
//gen new line use genLine in mesh.js
//information to send to genLine function
var info = {x1: x1, y1: y1, x2: x2, y2: y2, startPoint: startPoint, endPoint: endPoint, id: newLineId, dir: (dir === 'h') ? 'v' : 'h'};
if(info.dir === 'h'){//horizontal line
this.getViewIn('mesh').genLine('h', {x1: info.x1, x2: info.x2, y: info.y1}, {
left: info.startPoint,
right: info.endPoint
}, info.id);
}else{//vertical line
this.getViewIn('mesh').genLine('v', {y1: info.y1, y2: info.y2, x: info.x1}, {
top: info.startPoint,
bottom: info.endPoint
}, info.id);
}
},
});
})(Application); |
var http = require("http");
var url = require("url");
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response, request);
}
//http.createServer(onRequest).listen(3000, "192.168.56.101");
http.createServer(onRequest).listen(3000);
console.log("Server has started.");
}
exports.start = start;
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],2:[function(require,module,exports){
(function (process,global){
/*!
* Vue.js v2.1.10
* (c) 2014-2017 Evan You
* Released under the MIT License.
*/
'use strict';
/* */
/**
* Convert a value to a string that is actually rendered.
*/
function _toString (val) {
return val == null
? ''
: typeof val === 'object'
? JSON.stringify(val, null, 2)
: String(val)
}
/**
* Convert a input value to a number for persistence.
* If the conversion fails, return original string.
*/
function toNumber (val) {
var n = parseFloat(val);
return isNaN(n) ? val : n
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/
function makeMap (
str,
expectsLowerCase
) {
var map = Object.create(null);
var list = str.split(',');
for (var i = 0; i < list.length; i++) {
map[list[i]] = true;
}
return expectsLowerCase
? function (val) { return map[val.toLowerCase()]; }
: function (val) { return map[val]; }
}
/**
* Check if a tag is a built-in tag.
*/
var isBuiltInTag = makeMap('slot,component', true);
/**
* Remove an item from an array
*/
function remove$1 (arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) {
return arr.splice(index, 1)
}
}
}
/**
* Check whether the object has the property.
*/
var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn (obj, key) {
return hasOwnProperty.call(obj, key)
}
/**
* Check if value is primitive
*/
function isPrimitive (value) {
return typeof value === 'string' || typeof value === 'number'
}
/**
* Create a cached version of a pure function.
*/
function cached (fn) {
var cache = Object.create(null);
return (function cachedFn (str) {
var hit = cache[str];
return hit || (cache[str] = fn(str))
})
}
/**
* Camelize a hyphen-delimited string.
*/
var camelizeRE = /-(\w)/g;
var camelize = cached(function (str) {
return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; })
});
/**
* Capitalize a string.
*/
var capitalize = cached(function (str) {
return str.charAt(0).toUpperCase() + str.slice(1)
});
/**
* Hyphenate a camelCase string.
*/
var hyphenateRE = /([^-])([A-Z])/g;
var hyphenate = cached(function (str) {
return str
.replace(hyphenateRE, '$1-$2')
.replace(hyphenateRE, '$1-$2')
.toLowerCase()
});
/**
* Simple bind, faster than native
*/
function bind$1 (fn, ctx) {
function boundFn (a) {
var l = arguments.length;
return l
? l > 1
? fn.apply(ctx, arguments)
: fn.call(ctx, a)
: fn.call(ctx)
}
// record original fn length
boundFn._length = fn.length;
return boundFn
}
/**
* Convert an Array-like object to a real Array.
*/
function toArray (list, start) {
start = start || 0;
var i = list.length - start;
var ret = new Array(i);
while (i--) {
ret[i] = list[i + start];
}
return ret
}
/**
* Mix properties into target object.
*/
function extend (to, _from) {
for (var key in _from) {
to[key] = _from[key];
}
return to
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/
var toString = Object.prototype.toString;
var OBJECT_STRING = '[object Object]';
function isPlainObject (obj) {
return toString.call(obj) === OBJECT_STRING
}
/**
* Merge an Array of Objects into a single Object.
*/
function toObject (arr) {
var res = {};
for (var i = 0; i < arr.length; i++) {
if (arr[i]) {
extend(res, arr[i]);
}
}
return res
}
/**
* Perform no operation.
*/
function noop () {}
/**
* Always return false.
*/
var no = function () { return false; };
/**
* Return same value
*/
var identity = function (_) { return _; };
/**
* Generate a static keys string from compiler modules.
*/
function genStaticKeys (modules) {
return modules.reduce(function (keys, m) {
return keys.concat(m.staticKeys || [])
}, []).join(',')
}
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/
function looseEqual (a, b) {
var isObjectA = isObject(a);
var isObjectB = isObject(b);
if (isObjectA && isObjectB) {
return JSON.stringify(a) === JSON.stringify(b)
} else if (!isObjectA && !isObjectB) {
return String(a) === String(b)
} else {
return false
}
}
function looseIndexOf (arr, val) {
for (var i = 0; i < arr.length; i++) {
if (looseEqual(arr[i], val)) { return i }
}
return -1
}
/* */
var config = {
/**
* Option merge strategies (used in core/util/options)
*/
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/
silent: false,
/**
* Whether to enable devtools
*/
devtools: process.env.NODE_ENV !== 'production',
/**
* Error handler for watcher errors
*/
errorHandler: null,
/**
* Ignore certain custom elements
*/
ignoredElements: [],
/**
* Custom user key aliases for v-on
*/
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/
isReservedTag: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/
isUnknownElement: no,
/**
* Get the namespace of an element
*/
getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/
parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/
mustUseProp: no,
/**
* List of asset types that a component can own.
*/
_assetTypes: [
'component',
'directive',
'filter'
],
/**
* List of lifecycle hooks.
*/
_lifecycleHooks: [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated'
],
/**
* Max circular updates allowed in a scheduler flush cycle.
*/
_maxUpdateCount: 100
};
/* */
/**
* Check if a string starts with $ or _
*/
function isReserved (str) {
var c = (str + '').charCodeAt(0);
return c === 0x24 || c === 0x5F
}
/**
* Define a property.
*/
function def (obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: true,
configurable: true
});
}
/**
* Parse simple path.
*/
var bailRE = /[^\w.$]/;
function parsePath (path) {
if (bailRE.test(path)) {
return
} else {
var segments = path.split('.');
return function (obj) {
for (var i = 0; i < segments.length; i++) {
if (!obj) { return }
obj = obj[segments[i]];
}
return obj
}
}
}
/* */
/* globals MutationObserver */
// can we use __proto__?
var hasProto = '__proto__' in {};
// Browser environment sniffing
var inBrowser = typeof window !== 'undefined';
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = UA && UA.indexOf('android') > 0;
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);
// this needs to be lazy-evaled because vue may be required before
// vue-server-renderer can set VUE_ENV
var _isServer;
var isServerRendering = function () {
if (_isServer === undefined) {
/* istanbul ignore if */
if (!inBrowser && typeof global !== 'undefined') {
// detect presence of vue-server-renderer and avoid
// Webpack shimming the process
_isServer = global['process'].env.VUE_ENV === 'server';
} else {
_isServer = false;
}
}
return _isServer
};
// detect devtools
var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */
function isNative (Ctor) {
return /native code/.test(Ctor.toString())
}
/**
* Defer a task to execute it asynchronously.
*/
var nextTick = (function () {
var callbacks = [];
var pending = false;
var timerFunc;
function nextTickHandler () {
pending = false;
var copies = callbacks.slice(0);
callbacks.length = 0;
for (var i = 0; i < copies.length; i++) {
copies[i]();
}
}
// the nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore if */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
var p = Promise.resolve();
var logError = function (err) { console.error(err); };
timerFunc = function () {
p.then(nextTickHandler).catch(logError);
// in problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) { setTimeout(noop); }
};
} else if (typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// use MutationObserver where native Promise is not available,
// e.g. PhantomJS IE11, iOS7, Android 4.4
var counter = 1;
var observer = new MutationObserver(nextTickHandler);
var textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true
});
timerFunc = function () {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
} else {
// fallback to setTimeout
/* istanbul ignore next */
timerFunc = function () {
setTimeout(nextTickHandler, 0);
};
}
return function queueNextTick (cb, ctx) {
var _resolve;
callbacks.push(function () {
if (cb) { cb.call(ctx); }
if (_resolve) { _resolve(ctx); }
});
if (!pending) {
pending = true;
timerFunc();
}
if (!cb && typeof Promise !== 'undefined') {
return new Promise(function (resolve) {
_resolve = resolve;
})
}
}
})();
var _Set;
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
// use native Set when available.
_Set = Set;
} else {
// a non-standard Set polyfill that only works with primitive keys.
_Set = (function () {
function Set () {
this.set = Object.create(null);
}
Set.prototype.has = function has (key) {
return this.set[key] === true
};
Set.prototype.add = function add (key) {
this.set[key] = true;
};
Set.prototype.clear = function clear () {
this.set = Object.create(null);
};
return Set;
}());
}
var warn = noop;
var formatComponentName;
if (process.env.NODE_ENV !== 'production') {
var hasConsole = typeof console !== 'undefined';
warn = function (msg, vm) {
if (hasConsole && (!config.silent)) {
console.error("[Vue warn]: " + msg + " " + (
vm ? formatLocation(formatComponentName(vm)) : ''
));
}
};
formatComponentName = function (vm) {
if (vm.$root === vm) {
return 'root instance'
}
var name = vm._isVue
? vm.$options.name || vm.$options._componentTag
: vm.name;
return (
(name ? ("component <" + name + ">") : "anonymous component") +
(vm._isVue && vm.$options.__file ? (" at " + (vm.$options.__file)) : '')
)
};
var formatLocation = function (str) {
if (str === 'anonymous component') {
str += " - use the \"name\" option for better debugging messages.";
}
return ("\n(found in " + str + ")")
};
}
/* */
var uid$1 = 0;
/**
* A dep is an observable that can have multiple
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid$1++;
this.subs = [];
};
Dep.prototype.addSub = function addSub (sub) {
this.subs.push(sub);
};
Dep.prototype.removeSub = function removeSub (sub) {
remove$1(this.subs, sub);
};
Dep.prototype.depend = function depend () {
if (Dep.target) {
Dep.target.addDep(this);
}
};
Dep.prototype.notify = function notify () {
// stablize the subscriber list first
var subs = this.subs.slice();
for (var i = 0, l = subs.length; i < l; i++) {
subs[i].update();
}
};
// the current target watcher being evaluated.
// this is globally unique because there could be only one
// watcher being evaluated at any time.
Dep.target = null;
var targetStack = [];
function pushTarget (_target) {
if (Dep.target) { targetStack.push(Dep.target); }
Dep.target = _target;
}
function popTarget () {
Dep.target = targetStack.pop();
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/
var arrayProto = Array.prototype;
var arrayMethods = Object.create(arrayProto);[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function mutator () {
var arguments$1 = arguments;
// avoid leaking arguments:
// http://jsperf.com/closure-with-arguments
var i = arguments.length;
var args = new Array(i);
while (i--) {
args[i] = arguments$1[i];
}
var result = original.apply(this, args);
var ob = this.__ob__;
var inserted;
switch (method) {
case 'push':
inserted = args;
break
case 'unshift':
inserted = args;
break
case 'splice':
inserted = args.slice(2);
break
}
if (inserted) { ob.observeArray(inserted); }
// notify change
ob.dep.notify();
return result
});
});
/* */
var arrayKeys = Object.getOwnPropertyNames(arrayMethods);
/**
* By default, when a reactive property is set, the new value is
* also converted to become reactive. However when passing down props,
* we don't want to force conversion because the value may be a nested value
* under a frozen data structure. Converting it would defeat the optimization.
*/
var observerState = {
shouldConvert: true,
isSettingProps: false
};
/**
* Observer class that are attached to each observed
* object. Once attached, the observer converts target
* object's property keys into getter/setters that
* collect dependencies and dispatches updates.
*/
var Observer = function Observer (value) {
this.value = value;
this.dep = new Dep();
this.vmCount = 0;
def(value, '__ob__', this);
if (Array.isArray(value)) {
var augment = hasProto
? protoAugment
: copyAugment;
augment(value, arrayMethods, arrayKeys);
this.observeArray(value);
} else {
this.walk(value);
}
};
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
Observer.prototype.walk = function walk (obj) {
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
defineReactive$$1(obj, keys[i], obj[keys[i]]);
}
};
/**
* Observe a list of Array items.
*/
Observer.prototype.observeArray = function observeArray (items) {
for (var i = 0, l = items.length; i < l; i++) {
observe(items[i]);
}
};
// helpers
/**
* Augment an target Object or Array by intercepting
* the prototype chain using __proto__
*/
function protoAugment (target, src) {
/* eslint-disable no-proto */
target.__proto__ = src;
/* eslint-enable no-proto */
}
/**
* Augment an target Object or Array by defining
* hidden properties.
*/
/* istanbul ignore next */
function copyAugment (target, src, keys) {
for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
def(target, key, src[key]);
}
}
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/
function observe (value, asRootData) {
if (!isObject(value)) {
return
}
var ob;
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__;
} else if (
observerState.shouldConvert &&
!isServerRendering() &&
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value);
}
if (asRootData && ob) {
ob.vmCount++;
}
return ob
}
/**
* Define a reactive property on an Object.
*/
function defineReactive$$1 (
obj,
key,
val,
customSetter
) {
var dep = new Dep();
var property = Object.getOwnPropertyDescriptor(obj, key);
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
var getter = property && property.get;
var setter = property && property.set;
var childOb = observe(val);
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
var value = getter ? getter.call(obj) : val;
if (Dep.target) {
dep.depend();
if (childOb) {
childOb.dep.depend();
}
if (Array.isArray(value)) {
dependArray(value);
}
}
return value
},
set: function reactiveSetter (newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter();
}
if (setter) {
setter.call(obj, newVal);
} else {
val = newVal;
}
childOb = observe(newVal);
dep.notify();
}
});
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/
function set$1 (obj, key, val) {
if (Array.isArray(obj)) {
obj.length = Math.max(obj.length, key);
obj.splice(key, 1, val);
return val
}
if (hasOwn(obj, key)) {
obj[key] = val;
return
}
var ob = obj.__ob__;
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid adding reactive properties to a Vue instance or its root $data ' +
'at runtime - declare it upfront in the data option.'
);
return
}
if (!ob) {
obj[key] = val;
return
}
defineReactive$$1(ob.value, key, val);
ob.dep.notify();
return val
}
/**
* Delete a property and trigger change if necessary.
*/
function del (obj, key) {
var ob = obj.__ob__;
if (obj._isVue || (ob && ob.vmCount)) {
process.env.NODE_ENV !== 'production' && warn(
'Avoid deleting properties on a Vue instance or its root $data ' +
'- just set it to null.'
);
return
}
if (!hasOwn(obj, key)) {
return
}
delete obj[key];
if (!ob) {
return
}
ob.dep.notify();
}
/**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/
function dependArray (value) {
for (var e = (void 0), i = 0, l = value.length; i < l; i++) {
e = value[i];
e && e.__ob__ && e.__ob__.dep.depend();
if (Array.isArray(e)) {
dependArray(e);
}
}
}
/* */
/**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/
var strats = config.optionMergeStrategies;
/**
* Options with restrictions
*/
if (process.env.NODE_ENV !== 'production') {
strats.el = strats.propsData = function (parent, child, vm, key) {
if (!vm) {
warn(
"option \"" + key + "\" can only be used during instance " +
'creation with the `new` keyword.'
);
}
return defaultStrat(parent, child)
};
}
/**
* Helper that recursively merges two data objects together.
*/
function mergeData (to, from) {
if (!from) { return to }
var key, toVal, fromVal;
var keys = Object.keys(from);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
toVal = to[key];
fromVal = from[key];
if (!hasOwn(to, key)) {
set$1(to, key, fromVal);
} else if (isPlainObject(toVal) && isPlainObject(fromVal)) {
mergeData(toVal, fromVal);
}
}
return to
}
/**
* Data
*/
strats.data = function (
parentVal,
childVal,
vm
) {
if (!vm) {
// in a Vue.extend merge, both should be functions
if (!childVal) {
return parentVal
}
if (typeof childVal !== 'function') {
process.env.NODE_ENV !== 'production' && warn(
'The "data" option should be a function ' +
'that returns a per-instance value in component ' +
'definitions.',
vm
);
return parentVal
}
if (!parentVal) {
return childVal
}
// when parentVal & childVal are both present,
// we need to return a function that returns the
// merged result of both functions... no need to
// check if parentVal is a function here because
// it has to be a function to pass previous merges.
return function mergedDataFn () {
return mergeData(
childVal.call(this),
parentVal.call(this)
)
}
} else if (parentVal || childVal) {
return function mergedInstanceDataFn () {
// instance merge
var instanceData = typeof childVal === 'function'
? childVal.call(vm)
: childVal;
var defaultData = typeof parentVal === 'function'
? parentVal.call(vm)
: undefined;
if (instanceData) {
return mergeData(instanceData, defaultData)
} else {
return defaultData
}
}
}
};
/**
* Hooks and param attributes are merged as arrays.
*/
function mergeHook (
parentVal,
childVal
) {
return childVal
? parentVal
? parentVal.concat(childVal)
: Array.isArray(childVal)
? childVal
: [childVal]
: parentVal
}
config._lifecycleHooks.forEach(function (hook) {
strats[hook] = mergeHook;
});
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/
function mergeAssets (parentVal, childVal) {
var res = Object.create(parentVal || null);
return childVal
? extend(res, childVal)
: res
}
config._assetTypes.forEach(function (type) {
strats[type + 's'] = mergeAssets;
});
/**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/
strats.watch = function (parentVal, childVal) {
/* istanbul ignore if */
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = {};
extend(ret, parentVal);
for (var key in childVal) {
var parent = ret[key];
var child = childVal[key];
if (parent && !Array.isArray(parent)) {
parent = [parent];
}
ret[key] = parent
? parent.concat(child)
: [child];
}
return ret
};
/**
* Other object hashes.
*/
strats.props =
strats.methods =
strats.computed = function (parentVal, childVal) {
if (!childVal) { return parentVal }
if (!parentVal) { return childVal }
var ret = Object.create(null);
extend(ret, parentVal);
extend(ret, childVal);
return ret
};
/**
* Default strategy.
*/
var defaultStrat = function (parentVal, childVal) {
return childVal === undefined
? parentVal
: childVal
};
/**
* Validate component names
*/
function checkComponents (options) {
for (var key in options.components) {
var lower = key.toLowerCase();
if (isBuiltInTag(lower) || config.isReservedTag(lower)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + key
);
}
}
}
/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/
function normalizeProps (options) {
var props = options.props;
if (!props) { return }
var res = {};
var i, val, name;
if (Array.isArray(props)) {
i = props.length;
while (i--) {
val = props[i];
if (typeof val === 'string') {
name = camelize(val);
res[name] = { type: null };
} else if (process.env.NODE_ENV !== 'production') {
warn('props must be strings when using array syntax.');
}
}
} else if (isPlainObject(props)) {
for (var key in props) {
val = props[key];
name = camelize(key);
res[name] = isPlainObject(val)
? val
: { type: val };
}
}
options.props = res;
}
/**
* Normalize raw function directives into object format.
*/
function normalizeDirectives (options) {
var dirs = options.directives;
if (dirs) {
for (var key in dirs) {
var def = dirs[key];
if (typeof def === 'function') {
dirs[key] = { bind: def, update: def };
}
}
}
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/
function mergeOptions (
parent,
child,
vm
) {
if (process.env.NODE_ENV !== 'production') {
checkComponents(child);
}
normalizeProps(child);
normalizeDirectives(child);
var extendsFrom = child.extends;
if (extendsFrom) {
parent = typeof extendsFrom === 'function'
? mergeOptions(parent, extendsFrom.options, vm)
: mergeOptions(parent, extendsFrom, vm);
}
if (child.mixins) {
for (var i = 0, l = child.mixins.length; i < l; i++) {
var mixin = child.mixins[i];
if (mixin.prototype instanceof Vue$3) {
mixin = mixin.options;
}
parent = mergeOptions(parent, mixin, vm);
}
}
var options = {};
var key;
for (key in parent) {
mergeField(key);
}
for (key in child) {
if (!hasOwn(parent, key)) {
mergeField(key);
}
}
function mergeField (key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/
function resolveAsset (
options,
type,
id,
warnMissing
) {
/* istanbul ignore if */
if (typeof id !== 'string') {
return
}
var assets = options[type];
// check local registration variations first
if (hasOwn(assets, id)) { return assets[id] }
var camelizedId = camelize(id);
if (hasOwn(assets, camelizedId)) { return assets[camelizedId] }
var PascalCaseId = capitalize(camelizedId);
if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] }
// fallback to prototype chain
var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
if (process.env.NODE_ENV !== 'production' && warnMissing && !res) {
warn(
'Failed to resolve ' + type.slice(0, -1) + ': ' + id,
options
);
}
return res
}
/* */
function validateProp (
key,
propOptions,
propsData,
vm
) {
var prop = propOptions[key];
var absent = !hasOwn(propsData, key);
var value = propsData[key];
// handle boolean props
if (isType(Boolean, prop.type)) {
if (absent && !hasOwn(prop, 'default')) {
value = false;
} else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) {
value = true;
}
}
// check default value
if (value === undefined) {
value = getPropDefaultValue(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldConvert = observerState.shouldConvert;
observerState.shouldConvert = true;
observe(value);
observerState.shouldConvert = prevShouldConvert;
}
if (process.env.NODE_ENV !== 'production') {
assertProp(prop, key, value, vm, absent);
}
return value
}
/**
* Get the default value of a prop.
*/
function getPropDefaultValue (vm, prop, key) {
// no default, return undefined
if (!hasOwn(prop, 'default')) {
return undefined
}
var def = prop.default;
// warn against non-factory defaults for Object & Array
if (isObject(def)) {
process.env.NODE_ENV !== 'production' && warn(
'Invalid default value for prop "' + key + '": ' +
'Props with type Object/Array must use a factory function ' +
'to return the default value.',
vm
);
}
// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
if (vm && vm.$options.propsData &&
vm.$options.propsData[key] === undefined &&
vm[key] !== undefined) {
return vm[key]
}
// call factory function for non-Function types
return typeof def === 'function' && prop.type !== Function
? def.call(vm)
: def
}
/**
* Assert whether a prop is valid.
*/
function assertProp (
prop,
name,
value,
vm,
absent
) {
if (prop.required && absent) {
warn(
'Missing required prop: "' + name + '"',
vm
);
return
}
if (value == null && !prop.required) {
return
}
var type = prop.type;
var valid = !type || type === true;
var expectedTypes = [];
if (type) {
if (!Array.isArray(type)) {
type = [type];
}
for (var i = 0; i < type.length && !valid; i++) {
var assertedType = assertType(value, type[i]);
expectedTypes.push(assertedType.expectedType || '');
valid = assertedType.valid;
}
}
if (!valid) {
warn(
'Invalid prop: type check failed for prop "' + name + '".' +
' Expected ' + expectedTypes.map(capitalize).join(', ') +
', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.',
vm
);
return
}
var validator = prop.validator;
if (validator) {
if (!validator(value)) {
warn(
'Invalid prop: custom validator check failed for prop "' + name + '".',
vm
);
}
}
}
/**
* Assert the type of a value
*/
function assertType (value, type) {
var valid;
var expectedType = getType(type);
if (expectedType === 'String') {
valid = typeof value === (expectedType = 'string');
} else if (expectedType === 'Number') {
valid = typeof value === (expectedType = 'number');
} else if (expectedType === 'Boolean') {
valid = typeof value === (expectedType = 'boolean');
} else if (expectedType === 'Function') {
valid = typeof value === (expectedType = 'function');
} else if (expectedType === 'Object') {
valid = isPlainObject(value);
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return {
valid: valid,
expectedType: expectedType
}
}
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/
function getType (fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/);
return match && match[1]
}
function isType (type, fn) {
if (!Array.isArray(fn)) {
return getType(fn) === getType(type)
}
for (var i = 0, len = fn.length; i < len; i++) {
if (getType(fn[i]) === getType(type)) {
return true
}
}
/* istanbul ignore next */
return false
}
var util = Object.freeze({
defineReactive: defineReactive$$1,
_toString: _toString,
toNumber: toNumber,
makeMap: makeMap,
isBuiltInTag: isBuiltInTag,
remove: remove$1,
hasOwn: hasOwn,
isPrimitive: isPrimitive,
cached: cached,
camelize: camelize,
capitalize: capitalize,
hyphenate: hyphenate,
bind: bind$1,
toArray: toArray,
extend: extend,
isObject: isObject,
isPlainObject: isPlainObject,
toObject: toObject,
noop: noop,
no: no,
identity: identity,
genStaticKeys: genStaticKeys,
looseEqual: looseEqual,
looseIndexOf: looseIndexOf,
isReserved: isReserved,
def: def,
parsePath: parsePath,
hasProto: hasProto,
inBrowser: inBrowser,
UA: UA,
isIE: isIE,
isIE9: isIE9,
isEdge: isEdge,
isAndroid: isAndroid,
isIOS: isIOS,
isServerRendering: isServerRendering,
devtools: devtools,
nextTick: nextTick,
get _Set () { return _Set; },
mergeOptions: mergeOptions,
resolveAsset: resolveAsset,
get warn () { return warn; },
get formatComponentName () { return formatComponentName; },
validateProp: validateProp
});
/* not type checking this file because flow doesn't play well with Proxy */
var initProxy;
if (process.env.NODE_ENV !== 'production') {
var allowedGlobals = makeMap(
'Infinity,undefined,NaN,isFinite,isNaN,' +
'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' +
'require' // for Webpack/Browserify
);
var warnNonPresent = function (target, key) {
warn(
"Property or method \"" + key + "\" is not defined on the instance but " +
"referenced during render. Make sure to declare reactive data " +
"properties in the data option.",
target
);
};
var hasProxy =
typeof Proxy !== 'undefined' &&
Proxy.toString().match(/native code/);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta');
config.keyCodes = new Proxy(config.keyCodes, {
set: function set (target, key, value) {
if (isBuiltInModifier(key)) {
warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key));
return false
} else {
target[key] = value;
return true
}
}
});
}
var hasHandler = {
has: function has (target, key) {
var has = key in target;
var isAllowed = allowedGlobals(key) || key.charAt(0) === '_';
if (!has && !isAllowed) {
warnNonPresent(target, key);
}
return has || !isAllowed
}
};
var getHandler = {
get: function get (target, key) {
if (typeof key === 'string' && !(key in target)) {
warnNonPresent(target, key);
}
return target[key]
}
};
initProxy = function initProxy (vm) {
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
var handlers = options.render && options.render._withStripped
? getHandler
: hasHandler;
vm._renderProxy = new Proxy(vm, handlers);
} else {
vm._renderProxy = vm;
}
};
}
/* */
var VNode = function VNode (
tag,
data,
children,
text,
elm,
context,
componentOptions
) {
this.tag = tag;
this.data = data;
this.children = children;
this.text = text;
this.elm = elm;
this.ns = undefined;
this.context = context;
this.functionalContext = undefined;
this.key = data && data.key;
this.componentOptions = componentOptions;
this.componentInstance = undefined;
this.parent = undefined;
this.raw = false;
this.isStatic = false;
this.isRootInsert = true;
this.isComment = false;
this.isCloned = false;
this.isOnce = false;
};
var prototypeAccessors = { child: {} };
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */
prototypeAccessors.child.get = function () {
return this.componentInstance
};
Object.defineProperties( VNode.prototype, prototypeAccessors );
var createEmptyVNode = function () {
var node = new VNode();
node.text = '';
node.isComment = true;
return node
};
function createTextVNode (val) {
return new VNode(undefined, undefined, undefined, String(val))
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode (vnode) {
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isCloned = true;
return cloned
}
function cloneVNodes (vnodes) {
var res = new Array(vnodes.length);
for (var i = 0; i < vnodes.length; i++) {
res[i] = cloneVNode(vnodes[i]);
}
return res
}
/* */
var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy$1 };
var hooksToMerge = Object.keys(hooks);
function createComponent (
Ctor,
data,
context,
children,
tag
) {
if (!Ctor) {
return
}
var baseCtor = context.$options._base;
if (isObject(Ctor)) {
Ctor = baseCtor.extend(Ctor);
}
if (typeof Ctor !== 'function') {
if (process.env.NODE_ENV !== 'production') {
warn(("Invalid Component definition: " + (String(Ctor))), context);
}
return
}
// async component
if (!Ctor.cid) {
if (Ctor.resolved) {
Ctor = Ctor.resolved;
} else {
Ctor = resolveAsyncComponent(Ctor, baseCtor, function () {
// it's ok to queue this on every render because
// $forceUpdate is buffered by the scheduler.
context.$forceUpdate();
});
if (!Ctor) {
// return nothing if this is indeed an async component
// wait for the callback to trigger parent update.
return
}
}
}
// resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor);
data = data || {};
// extract props
var propsData = extractProps(data, Ctor);
// functional component
if (Ctor.options.functional) {
return createFunctionalComponent(Ctor, propsData, data, context, children)
}
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
// replace with listeners with .native modifier
data.on = data.nativeOn;
if (Ctor.options.abstract) {
// abstract components do not keep anything
// other than props & listeners
data = {};
}
// merge component management hooks onto the placeholder node
mergeHooks(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
var vnode = new VNode(
("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')),
data, undefined, undefined, undefined, context,
{ Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children }
);
return vnode
}
function createFunctionalComponent (
Ctor,
propsData,
data,
context,
children
) {
var props = {};
var propOptions = Ctor.options.props;
if (propOptions) {
for (var key in propOptions) {
props[key] = validateProp(key, propOptions, propsData);
}
}
// ensure the createElement function in functional components
// gets a unique context - this is necessary for correct named slot check
var _context = Object.create(context);
var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); };
var vnode = Ctor.options.render.call(null, h, {
props: props,
data: data,
parent: context,
children: children,
slots: function () { return resolveSlots(children, context); }
});
if (vnode instanceof VNode) {
vnode.functionalContext = context;
if (data.slot) {
(vnode.data || (vnode.data = {})).slot = data.slot;
}
}
return vnode
}
function createComponentInstanceForVnode (
vnode, // we know it's MountedComponentVNode but flow doesn't
parent, // activeInstance in lifecycle state
parentElm,
refElm
) {
var vnodeComponentOptions = vnode.componentOptions;
var options = {
_isComponent: true,
parent: parent,
propsData: vnodeComponentOptions.propsData,
_componentTag: vnodeComponentOptions.tag,
_parentVnode: vnode,
_parentListeners: vnodeComponentOptions.listeners,
_renderChildren: vnodeComponentOptions.children,
_parentElm: parentElm || null,
_refElm: refElm || null
};
// check inline-template render functions
var inlineTemplate = vnode.data.inlineTemplate;
if (inlineTemplate) {
options.render = inlineTemplate.render;
options.staticRenderFns = inlineTemplate.staticRenderFns;
}
return new vnodeComponentOptions.Ctor(options)
}
function init (
vnode,
hydrating,
parentElm,
refElm
) {
if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) {
var child = vnode.componentInstance = createComponentInstanceForVnode(
vnode,
activeInstance,
parentElm,
refElm
);
child.$mount(hydrating ? vnode.elm : undefined, hydrating);
} else if (vnode.data.keepAlive) {
// kept-alive components, treat as a patch
var mountedNode = vnode; // work around flow
prepatch(mountedNode, mountedNode);
}
}
function prepatch (
oldVnode,
vnode
) {
var options = vnode.componentOptions;
var child = vnode.componentInstance = oldVnode.componentInstance;
child._updateFromParent(
options.propsData, // updated props
options.listeners, // updated listeners
vnode, // new parent vnode
options.children // new children
);
}
function insert (vnode) {
if (!vnode.componentInstance._isMounted) {
vnode.componentInstance._isMounted = true;
callHook(vnode.componentInstance, 'mounted');
}
if (vnode.data.keepAlive) {
vnode.componentInstance._inactive = false;
callHook(vnode.componentInstance, 'activated');
}
}
function destroy$1 (vnode) {
if (!vnode.componentInstance._isDestroyed) {
if (!vnode.data.keepAlive) {
vnode.componentInstance.$destroy();
} else {
vnode.componentInstance._inactive = true;
callHook(vnode.componentInstance, 'deactivated');
}
}
}
function resolveAsyncComponent (
factory,
baseCtor,
cb
) {
if (factory.requested) {
// pool callbacks
factory.pendingCallbacks.push(cb);
} else {
factory.requested = true;
var cbs = factory.pendingCallbacks = [cb];
var sync = true;
var resolve = function (res) {
if (isObject(res)) {
res = baseCtor.extend(res);
}
// cache resolved
factory.resolved = res;
// invoke callbacks only if this is not a synchronous resolve
// (async resolves are shimmed as synchronous during SSR)
if (!sync) {
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i](res);
}
}
};
var reject = function (reason) {
process.env.NODE_ENV !== 'production' && warn(
"Failed to resolve async component: " + (String(factory)) +
(reason ? ("\nReason: " + reason) : '')
);
};
var res = factory(resolve, reject);
// handle promise
if (res && typeof res.then === 'function' && !factory.resolved) {
res.then(resolve, reject);
}
sync = false;
// return in case resolved synchronously
return factory.resolved
}
}
function extractProps (data, Ctor) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (!propOptions) {
return
}
var res = {};
var attrs = data.attrs;
var props = data.props;
var domProps = data.domProps;
if (attrs || props || domProps) {
for (var key in propOptions) {
var altKey = hyphenate(key);
checkProp(res, props, key, altKey, true) ||
checkProp(res, attrs, key, altKey) ||
checkProp(res, domProps, key, altKey);
}
}
return res
}
function checkProp (
res,
hash,
key,
altKey,
preserve
) {
if (hash) {
if (hasOwn(hash, key)) {
res[key] = hash[key];
if (!preserve) {
delete hash[key];
}
return true
} else if (hasOwn(hash, altKey)) {
res[key] = hash[altKey];
if (!preserve) {
delete hash[altKey];
}
return true
}
}
return false
}
function mergeHooks (data) {
if (!data.hook) {
data.hook = {};
}
for (var i = 0; i < hooksToMerge.length; i++) {
var key = hooksToMerge[i];
var fromParent = data.hook[key];
var ours = hooks[key];
data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours;
}
}
function mergeHook$1 (one, two) {
return function (a, b, c, d) {
one(a, b, c, d);
two(a, b, c, d);
}
}
/* */
function mergeVNodeHook (def, hookKey, hook, key) {
key = key + hookKey;
var injectedHash = def.__injected || (def.__injected = {});
if (!injectedHash[key]) {
injectedHash[key] = true;
var oldHook = def[hookKey];
if (oldHook) {
def[hookKey] = function () {
oldHook.apply(this, arguments);
hook.apply(this, arguments);
};
} else {
def[hookKey] = hook;
}
}
}
/* */
var normalizeEvent = cached(function (name) {
var once = name.charAt(0) === '~'; // Prefixed last, checked first
name = once ? name.slice(1) : name;
var capture = name.charAt(0) === '!';
name = capture ? name.slice(1) : name;
return {
name: name,
once: once,
capture: capture
}
});
function createEventHandle (fn) {
var handle = {
fn: fn,
invoker: function () {
var arguments$1 = arguments;
var fn = handle.fn;
if (Array.isArray(fn)) {
for (var i = 0; i < fn.length; i++) {
fn[i].apply(null, arguments$1);
}
} else {
fn.apply(null, arguments);
}
}
};
return handle
}
function updateListeners (
on,
oldOn,
add,
remove$$1,
vm
) {
var name, cur, old, event;
for (name in on) {
cur = on[name];
old = oldOn[name];
event = normalizeEvent(name);
if (!cur) {
process.env.NODE_ENV !== 'production' && warn(
"Invalid handler for event \"" + (event.name) + "\": got " + String(cur),
vm
);
} else if (!old) {
if (!cur.invoker) {
cur = on[name] = createEventHandle(cur);
}
add(event.name, cur.invoker, event.once, event.capture);
} else if (cur !== old) {
old.fn = cur;
on[name] = old;
}
}
for (name in oldOn) {
if (!on[name]) {
event = normalizeEvent(name);
remove$$1(event.name, oldOn[name].invoker, event.capture);
}
}
}
/* */
// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// nomralization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
function simpleNormalizeChildren (children) {
for (var i = 0; i < children.length; i++) {
if (Array.isArray(children[i])) {
return Array.prototype.concat.apply([], children)
}
}
return children
}
// 2. When the children contains constrcuts that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
function normalizeChildren (children) {
return isPrimitive(children)
? [createTextVNode(children)]
: Array.isArray(children)
? normalizeArrayChildren(children)
: undefined
}
function normalizeArrayChildren (children, nestedIndex) {
var res = [];
var i, c, last;
for (i = 0; i < children.length; i++) {
c = children[i];
if (c == null || typeof c === 'boolean') { continue }
last = res[res.length - 1];
// nested
if (Array.isArray(c)) {
res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i)));
} else if (isPrimitive(c)) {
if (last && last.text) {
last.text += String(c);
} else if (c !== '') {
// convert primitive to vnode
res.push(createTextVNode(c));
}
} else {
if (c.text && last && last.text) {
res[res.length - 1] = createTextVNode(last.text + c.text);
} else {
// default key for nested array children (likely generated by v-for)
if (c.tag && c.key == null && nestedIndex != null) {
c.key = "__vlist" + nestedIndex + "_" + i + "__";
}
res.push(c);
}
}
}
return res
}
/* */
function getFirstComponentChild (children) {
return children && children.filter(function (c) { return c && c.componentOptions; })[0]
}
/* */
var SIMPLE_NORMALIZE = 1;
var ALWAYS_NORMALIZE = 2;
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement (
context,
tag,
data,
children,
normalizationType,
alwaysNormalize
) {
if (Array.isArray(data) || isPrimitive(data)) {
normalizationType = children;
children = data;
data = undefined;
}
if (alwaysNormalize) { normalizationType = ALWAYS_NORMALIZE; }
return _createElement(context, tag, data, children, normalizationType)
}
function _createElement (
context,
tag,
data,
children,
normalizationType
) {
if (data && data.__ob__) {
process.env.NODE_ENV !== 'production' && warn(
"Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" +
'Always create fresh vnode data objects in each render!',
context
);
return createEmptyVNode()
}
if (!tag) {
// in case of component :is set to falsy value
return createEmptyVNode()
}
// support single function children as default scoped slot
if (Array.isArray(children) &&
typeof children[0] === 'function') {
data = data || {};
data.scopedSlots = { default: children[0] };
children.length = 0;
}
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children);
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children);
}
var vnode, ns;
if (typeof tag === 'string') {
var Ctor;
ns = config.getTagNamespace(tag);
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
);
} else if ((Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag);
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
);
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children);
}
if (vnode) {
if (ns) { applyNS(vnode, ns); }
return vnode
} else {
return createEmptyVNode()
}
}
function applyNS (vnode, ns) {
vnode.ns = ns;
if (vnode.tag === 'foreignObject') {
// use default namespace inside foreignObject
return
}
if (vnode.children) {
for (var i = 0, l = vnode.children.length; i < l; i++) {
var child = vnode.children[i];
if (child.tag && !child.ns) {
applyNS(child, ns);
}
}
}
}
/* */
function initRender (vm) {
vm.$vnode = null; // the placeholder node in parent tree
vm._vnode = null; // the root of the child tree
vm._staticTrees = null;
var parentVnode = vm.$options._parentVnode;
var renderContext = parentVnode && parentVnode.context;
vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext);
vm.$scopedSlots = {};
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); };
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); };
}
function renderMixin (Vue) {
Vue.prototype.$nextTick = function (fn) {
return nextTick(fn, this)
};
Vue.prototype._render = function () {
var vm = this;
var ref = vm.$options;
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
var _parentVnode = ref._parentVnode;
if (vm._isMounted) {
// clone slot nodes on re-renders
for (var key in vm.$slots) {
vm.$slots[key] = cloneVNodes(vm.$slots[key]);
}
}
if (_parentVnode && _parentVnode.data.scopedSlots) {
vm.$scopedSlots = _parentVnode.data.scopedSlots;
}
if (staticRenderFns && !vm._staticTrees) {
vm._staticTrees = [];
}
// set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
vm.$vnode = _parentVnode;
// render self
var vnode;
try {
vnode = render.call(vm._renderProxy, vm.$createElement);
} catch (e) {
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, vm);
} else {
if (process.env.NODE_ENV !== 'production') {
warn(("Error when rendering " + (formatComponentName(vm)) + ":"));
}
throw e
}
// return previous vnode to prevent render error causing blank component
vnode = vm._vnode;
}
// return empty vnode in case the render function errored out
if (!(vnode instanceof VNode)) {
if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) {
warn(
'Multiple root nodes returned from render function. Render function ' +
'should return a single root node.',
vm
);
}
vnode = createEmptyVNode();
}
// set parent
vnode.parent = _parentVnode;
return vnode
};
// toString for mustaches
Vue.prototype._s = _toString;
// convert text to vnode
Vue.prototype._v = createTextVNode;
// number conversion
Vue.prototype._n = toNumber;
// empty vnode
Vue.prototype._e = createEmptyVNode;
// loose equal
Vue.prototype._q = looseEqual;
// loose indexOf
Vue.prototype._i = looseIndexOf;
// render static tree by index
Vue.prototype._m = function renderStatic (
index,
isInFor
) {
var tree = this._staticTrees[index];
// if has already-rendered static tree and not inside v-for,
// we can reuse the same tree by doing a shallow clone.
if (tree && !isInFor) {
return Array.isArray(tree)
? cloneVNodes(tree)
: cloneVNode(tree)
}
// otherwise, render a fresh tree.
tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy);
markStatic(tree, ("__static__" + index), false);
return tree
};
// mark node as static (v-once)
Vue.prototype._o = function markOnce (
tree,
index,
key
) {
markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true);
return tree
};
function markStatic (tree, key, isOnce) {
if (Array.isArray(tree)) {
for (var i = 0; i < tree.length; i++) {
if (tree[i] && typeof tree[i] !== 'string') {
markStaticNode(tree[i], (key + "_" + i), isOnce);
}
}
} else {
markStaticNode(tree, key, isOnce);
}
}
function markStaticNode (node, key, isOnce) {
node.isStatic = true;
node.key = key;
node.isOnce = isOnce;
}
// filter resolution helper
Vue.prototype._f = function resolveFilter (id) {
return resolveAsset(this.$options, 'filters', id, true) || identity
};
// render v-for
Vue.prototype._l = function renderList (
val,
render
) {
var ret, i, l, keys, key;
if (Array.isArray(val) || typeof val === 'string') {
ret = new Array(val.length);
for (i = 0, l = val.length; i < l; i++) {
ret[i] = render(val[i], i);
}
} else if (typeof val === 'number') {
ret = new Array(val);
for (i = 0; i < val; i++) {
ret[i] = render(i + 1, i);
}
} else if (isObject(val)) {
keys = Object.keys(val);
ret = new Array(keys.length);
for (i = 0, l = keys.length; i < l; i++) {
key = keys[i];
ret[i] = render(val[key], key, i);
}
}
return ret
};
// renderSlot
Vue.prototype._t = function (
name,
fallback,
props,
bindObject
) {
var scopedSlotFn = this.$scopedSlots[name];
if (scopedSlotFn) { // scoped slot
props = props || {};
if (bindObject) {
extend(props, bindObject);
}
return scopedSlotFn(props) || fallback
} else {
var slotNodes = this.$slots[name];
// warn duplicate slot usage
if (slotNodes && process.env.NODE_ENV !== 'production') {
slotNodes._rendered && warn(
"Duplicate presence of slot \"" + name + "\" found in the same render tree " +
"- this will likely cause render errors.",
this
);
slotNodes._rendered = true;
}
return slotNodes || fallback
}
};
// apply v-bind object
Vue.prototype._b = function bindProps (
data,
tag,
value,
asProp
) {
if (value) {
if (!isObject(value)) {
process.env.NODE_ENV !== 'production' && warn(
'v-bind without argument expects an Object or Array value',
this
);
} else {
if (Array.isArray(value)) {
value = toObject(value);
}
for (var key in value) {
if (key === 'class' || key === 'style') {
data[key] = value[key];
} else {
var type = data.attrs && data.attrs.type;
var hash = asProp || config.mustUseProp(tag, type, key)
? data.domProps || (data.domProps = {})
: data.attrs || (data.attrs = {});
hash[key] = value[key];
}
}
}
}
return data
};
// check v-on keyCodes
Vue.prototype._k = function checkKeyCodes (
eventKeyCode,
key,
builtInAlias
) {
var keyCodes = config.keyCodes[key] || builtInAlias;
if (Array.isArray(keyCodes)) {
return keyCodes.indexOf(eventKeyCode) === -1
} else {
return keyCodes !== eventKeyCode
}
};
}
function resolveSlots (
children,
context
) {
var slots = {};
if (!children) {
return slots
}
var defaultSlot = [];
var name, child;
for (var i = 0, l = children.length; i < l; i++) {
child = children[i];
// named slots should only be respected if the vnode was rendered in the
// same context.
if ((child.context === context || child.functionalContext === context) &&
child.data && (name = child.data.slot)) {
var slot = (slots[name] || (slots[name] = []));
if (child.tag === 'template') {
slot.push.apply(slot, child.children);
} else {
slot.push(child);
}
} else {
defaultSlot.push(child);
}
}
// ignore single whitespace
if (defaultSlot.length && !(
defaultSlot.length === 1 &&
(defaultSlot[0].text === ' ' || defaultSlot[0].isComment)
)) {
slots.default = defaultSlot;
}
return slots
}
/* */
function initEvents (vm) {
vm._events = Object.create(null);
vm._hasHookEvent = false;
// init parent attached events
var listeners = vm.$options._parentListeners;
if (listeners) {
updateComponentListeners(vm, listeners);
}
}
var target;
function add$1 (event, fn, once) {
if (once) {
target.$once(event, fn);
} else {
target.$on(event, fn);
}
}
function remove$2 (event, fn) {
target.$off(event, fn);
}
function updateComponentListeners (
vm,
listeners,
oldListeners
) {
target = vm;
updateListeners(listeners, oldListeners || {}, add$1, remove$2, vm);
}
function eventsMixin (Vue) {
var hookRE = /^hook:/;
Vue.prototype.$on = function (event, fn) {
var vm = this;(vm._events[event] || (vm._events[event] = [])).push(fn);
// optimize hook:event cost by using a boolean flag marked at registration
// instead of a hash lookup
if (hookRE.test(event)) {
vm._hasHookEvent = true;
}
return vm
};
Vue.prototype.$once = function (event, fn) {
var vm = this;
function on () {
vm.$off(event, on);
fn.apply(vm, arguments);
}
on.fn = fn;
vm.$on(event, on);
return vm
};
Vue.prototype.$off = function (event, fn) {
var vm = this;
// all
if (!arguments.length) {
vm._events = Object.create(null);
return vm
}
// specific event
var cbs = vm._events[event];
if (!cbs) {
return vm
}
if (arguments.length === 1) {
vm._events[event] = null;
return vm
}
// specific handler
var cb;
var i = cbs.length;
while (i--) {
cb = cbs[i];
if (cb === fn || cb.fn === fn) {
cbs.splice(i, 1);
break
}
}
return vm
};
Vue.prototype.$emit = function (event) {
var vm = this;
var cbs = vm._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
var args = toArray(arguments, 1);
for (var i = 0, l = cbs.length; i < l; i++) {
cbs[i].apply(vm, args);
}
}
return vm
};
}
/* */
var activeInstance = null;
function initLifecycle (vm) {
var options = vm.$options;
// locate first non-abstract parent
var parent = options.parent;
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent;
}
parent.$children.push(vm);
}
vm.$parent = parent;
vm.$root = parent ? parent.$root : vm;
vm.$children = [];
vm.$refs = {};
vm._watcher = null;
vm._inactive = false;
vm._isMounted = false;
vm._isDestroyed = false;
vm._isBeingDestroyed = false;
}
function lifecycleMixin (Vue) {
Vue.prototype._mount = function (
el,
hydrating
) {
var vm = this;
vm.$el = el;
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode;
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
if (vm.$options.template && vm.$options.template.charAt(0) !== '#') {
warn(
'You are using the runtime-only build of Vue where the template ' +
'option is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
);
} else {
warn(
'Failed to mount component: template or render function not defined.',
vm
);
}
}
}
callHook(vm, 'beforeMount');
vm._watcher = new Watcher(vm, function updateComponent () {
vm._update(vm._render(), hydrating);
}, noop);
hydrating = false;
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true;
callHook(vm, 'mounted');
}
return vm
};
Vue.prototype._update = function (vnode, hydrating) {
var vm = this;
if (vm._isMounted) {
callHook(vm, 'beforeUpdate');
}
var prevEl = vm.$el;
var prevVnode = vm._vnode;
var prevActiveInstance = activeInstance;
activeInstance = vm;
vm._vnode = vnode;
// Vue.prototype.__patch__ is injected in entry points
// based on the rendering backend used.
if (!prevVnode) {
// initial render
vm.$el = vm.__patch__(
vm.$el, vnode, hydrating, false /* removeOnly */,
vm.$options._parentElm,
vm.$options._refElm
);
} else {
// updates
vm.$el = vm.__patch__(prevVnode, vnode);
}
activeInstance = prevActiveInstance;
// update __vue__ reference
if (prevEl) {
prevEl.__vue__ = null;
}
if (vm.$el) {
vm.$el.__vue__ = vm;
}
// if parent is an HOC, update its $el as well
if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) {
vm.$parent.$el = vm.$el;
}
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
};
Vue.prototype._updateFromParent = function (
propsData,
listeners,
parentVnode,
renderChildren
) {
var vm = this;
var hasChildren = !!(vm.$options._renderChildren || renderChildren);
vm.$options._parentVnode = parentVnode;
vm.$vnode = parentVnode; // update vm's placeholder node without re-render
if (vm._vnode) { // update child tree's parent
vm._vnode.parent = parentVnode;
}
vm.$options._renderChildren = renderChildren;
// update props
if (propsData && vm.$options.props) {
observerState.shouldConvert = false;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = true;
}
var propKeys = vm.$options._propKeys || [];
for (var i = 0; i < propKeys.length; i++) {
var key = propKeys[i];
vm[key] = validateProp(key, vm.$options.props, propsData, vm);
}
observerState.shouldConvert = true;
if (process.env.NODE_ENV !== 'production') {
observerState.isSettingProps = false;
}
vm.$options.propsData = propsData;
}
// update listeners
if (listeners) {
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners;
updateComponentListeners(vm, listeners, oldListeners);
}
// resolve slots + force update if has children
if (hasChildren) {
vm.$slots = resolveSlots(renderChildren, parentVnode.context);
vm.$forceUpdate();
}
};
Vue.prototype.$forceUpdate = function () {
var vm = this;
if (vm._watcher) {
vm._watcher.update();
}
};
Vue.prototype.$destroy = function () {
var vm = this;
if (vm._isBeingDestroyed) {
return
}
callHook(vm, 'beforeDestroy');
vm._isBeingDestroyed = true;
// remove self from parent
var parent = vm.$parent;
if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) {
remove$1(parent.$children, vm);
}
// teardown watchers
if (vm._watcher) {
vm._watcher.teardown();
}
var i = vm._watchers.length;
while (i--) {
vm._watchers[i].teardown();
}
// remove reference from data ob
// frozen object may not have observer.
if (vm._data.__ob__) {
vm._data.__ob__.vmCount--;
}
// call the last hook...
vm._isDestroyed = true;
callHook(vm, 'destroyed');
// turn off all instance listeners.
vm.$off();
// remove __vue__ reference
if (vm.$el) {
vm.$el.__vue__ = null;
}
// invoke destroy hooks on current rendered tree
vm.__patch__(vm._vnode, null);
};
}
function callHook (vm, hook) {
var handlers = vm.$options[hook];
if (handlers) {
for (var i = 0, j = handlers.length; i < j; i++) {
handlers[i].call(vm);
}
}
if (vm._hasHookEvent) {
vm.$emit('hook:' + hook);
}
}
/* */
var queue = [];
var has$1 = {};
var circular = {};
var waiting = false;
var flushing = false;
var index = 0;
/**
* Reset the scheduler's state.
*/
function resetSchedulerState () {
queue.length = 0;
has$1 = {};
if (process.env.NODE_ENV !== 'production') {
circular = {};
}
waiting = flushing = false;
}
/**
* Flush both queues and run the watchers.
*/
function flushSchedulerQueue () {
flushing = true;
var watcher, id, vm;
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function (a, b) { return a.id - b.id; });
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index];
id = watcher.id;
has$1[id] = null;
watcher.run();
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has$1[id] != null) {
circular[id] = (circular[id] || 0) + 1;
if (circular[id] > config._maxUpdateCount) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? ("in watcher with expression \"" + (watcher.expression) + "\"")
: "in a component render function."
),
watcher.vm
);
break
}
}
}
// call updated hooks
index = queue.length;
while (index--) {
watcher = queue[index];
vm = watcher.vm;
if (vm._watcher === watcher && vm._isMounted) {
callHook(vm, 'updated');
}
}
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush');
}
resetSchedulerState();
}
/**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/
function queueWatcher (watcher) {
var id = watcher.id;
if (has$1[id] == null) {
has$1[id] = true;
if (!flushing) {
queue.push(watcher);
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1;
while (i >= 0 && queue[i].id > watcher.id) {
i--;
}
queue.splice(Math.max(i, index) + 1, 0, watcher);
}
// queue the flush
if (!waiting) {
waiting = true;
nextTick(flushSchedulerQueue);
}
}
}
/* */
var uid$2 = 0;
/**
* A watcher parses an expression, collects dependencies,
* and fires callback when the expression value changes.
* This is used for both the $watch() api and directives.
*/
var Watcher = function Watcher (
vm,
expOrFn,
cb,
options
) {
this.vm = vm;
vm._watchers.push(this);
// options
if (options) {
this.deep = !!options.deep;
this.user = !!options.user;
this.lazy = !!options.lazy;
this.sync = !!options.sync;
} else {
this.deep = this.user = this.lazy = this.sync = false;
}
this.cb = cb;
this.id = ++uid$2; // uid for batching
this.active = true;
this.dirty = this.lazy; // for lazy watchers
this.deps = [];
this.newDeps = [];
this.depIds = new _Set();
this.newDepIds = new _Set();
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: '';
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn;
} else {
this.getter = parsePath(expOrFn);
if (!this.getter) {
this.getter = function () {};
process.env.NODE_ENV !== 'production' && warn(
"Failed watching path: \"" + expOrFn + "\" " +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
);
}
}
this.value = this.lazy
? undefined
: this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/
Watcher.prototype.get = function get () {
pushTarget(this);
var value = this.getter.call(this.vm, this.vm);
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value);
}
popTarget();
this.cleanupDeps();
return value
};
/**
* Add a dependency to this directive.
*/
Watcher.prototype.addDep = function addDep (dep) {
var id = dep.id;
if (!this.newDepIds.has(id)) {
this.newDepIds.add(id);
this.newDeps.push(dep);
if (!this.depIds.has(id)) {
dep.addSub(this);
}
}
};
/**
* Clean up for dependency collection.
*/
Watcher.prototype.cleanupDeps = function cleanupDeps () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
var dep = this$1.deps[i];
if (!this$1.newDepIds.has(dep.id)) {
dep.removeSub(this$1);
}
}
var tmp = this.depIds;
this.depIds = this.newDepIds;
this.newDepIds = tmp;
this.newDepIds.clear();
tmp = this.deps;
this.deps = this.newDeps;
this.newDeps = tmp;
this.newDeps.length = 0;
};
/**
* Subscriber interface.
* Will be called when a dependency changes.
*/
Watcher.prototype.update = function update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true;
} else if (this.sync) {
this.run();
} else {
queueWatcher(this);
}
};
/**
* Scheduler job interface.
* Will be called by the scheduler.
*/
Watcher.prototype.run = function run () {
if (this.active) {
var value = this.get();
if (
value !== this.value ||
// Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) ||
this.deep
) {
// set new value
var oldValue = this.value;
this.value = value;
if (this.user) {
try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
/* istanbul ignore else */
if (config.errorHandler) {
config.errorHandler.call(null, e, this.vm);
} else {
process.env.NODE_ENV !== 'production' && warn(
("Error in watcher \"" + (this.expression) + "\""),
this.vm
);
throw e
}
}
} else {
this.cb.call(this.vm, value, oldValue);
}
}
}
};
/**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/
Watcher.prototype.evaluate = function evaluate () {
this.value = this.get();
this.dirty = false;
};
/**
* Depend on all deps collected by this watcher.
*/
Watcher.prototype.depend = function depend () {
var this$1 = this;
var i = this.deps.length;
while (i--) {
this$1.deps[i].depend();
}
};
/**
* Remove self from all dependencies' subscriber list.
*/
Watcher.prototype.teardown = function teardown () {
var this$1 = this;
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
if (!this.vm._isBeingDestroyed) {
remove$1(this.vm._watchers, this);
}
var i = this.deps.length;
while (i--) {
this$1.deps[i].removeSub(this$1);
}
this.active = false;
}
};
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/
var seenObjects = new _Set();
function traverse (val) {
seenObjects.clear();
_traverse(val, seenObjects);
}
function _traverse (val, seen) {
var i, keys;
var isA = Array.isArray(val);
if ((!isA && !isObject(val)) || !Object.isExtensible(val)) {
return
}
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) {
return
}
seen.add(depId);
}
if (isA) {
i = val.length;
while (i--) { _traverse(val[i], seen); }
} else {
keys = Object.keys(val);
i = keys.length;
while (i--) { _traverse(val[keys[i]], seen); }
}
}
/* */
function initState (vm) {
vm._watchers = [];
var opts = vm.$options;
if (opts.props) { initProps(vm, opts.props); }
if (opts.methods) { initMethods(vm, opts.methods); }
if (opts.data) {
initData(vm);
} else {
observe(vm._data = {}, true /* asRootData */);
}
if (opts.computed) { initComputed(vm, opts.computed); }
if (opts.watch) { initWatch(vm, opts.watch); }
}
var isReservedProp = { key: 1, ref: 1, slot: 1 };
function initProps (vm, props) {
var propsData = vm.$options.propsData || {};
var keys = vm.$options._propKeys = Object.keys(props);
var isRoot = !vm.$parent;
// root instance props should be converted
observerState.shouldConvert = isRoot;
var loop = function ( i ) {
var key = keys[i];
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
if (isReservedProp[key]) {
warn(
("\"" + key + "\" is a reserved attribute and cannot be used as component prop."),
vm
);
}
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm), function () {
if (vm.$parent && !observerState.isSettingProps) {
warn(
"Avoid mutating a prop directly since the value will be " +
"overwritten whenever the parent component re-renders. " +
"Instead, use a data or computed property based on the prop's " +
"value. Prop being mutated: \"" + key + "\"",
vm
);
}
});
} else {
defineReactive$$1(vm, key, validateProp(key, props, propsData, vm));
}
};
for (var i = 0; i < keys.length; i++) loop( i );
observerState.shouldConvert = true;
}
function initData (vm) {
var data = vm.$options.data;
data = vm._data = typeof data === 'function'
? data.call(vm)
: data || {};
if (!isPlainObject(data)) {
data = {};
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
);
}
// proxy data on instance
var keys = Object.keys(data);
var props = vm.$options.props;
var i = keys.length;
while (i--) {
if (props && hasOwn(props, keys[i])) {
process.env.NODE_ENV !== 'production' && warn(
"The data property \"" + (keys[i]) + "\" is already declared as a prop. " +
"Use prop default value instead.",
vm
);
} else {
proxy(vm, keys[i]);
}
}
// observe data
observe(data, true /* asRootData */);
}
var computedSharedDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
};
function initComputed (vm, computed) {
for (var key in computed) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && key in vm) {
warn(
"existing instance property \"" + key + "\" will be " +
"overwritten by a computed property with the same name.",
vm
);
}
var userDef = computed[key];
if (typeof userDef === 'function') {
computedSharedDefinition.get = makeComputedGetter(userDef, vm);
computedSharedDefinition.set = noop;
} else {
computedSharedDefinition.get = userDef.get
? userDef.cache !== false
? makeComputedGetter(userDef.get, vm)
: bind$1(userDef.get, vm)
: noop;
computedSharedDefinition.set = userDef.set
? bind$1(userDef.set, vm)
: noop;
}
Object.defineProperty(vm, key, computedSharedDefinition);
}
}
function makeComputedGetter (getter, owner) {
var watcher = new Watcher(owner, getter, noop, {
lazy: true
});
return function computedGetter () {
if (watcher.dirty) {
watcher.evaluate();
}
if (Dep.target) {
watcher.depend();
}
return watcher.value
}
}
function initMethods (vm, methods) {
for (var key in methods) {
vm[key] = methods[key] == null ? noop : bind$1(methods[key], vm);
if (process.env.NODE_ENV !== 'production' && methods[key] == null) {
warn(
"method \"" + key + "\" has an undefined value in the component definition. " +
"Did you reference the function correctly?",
vm
);
}
}
}
function initWatch (vm, watch) {
for (var key in watch) {
var handler = watch[key];
if (Array.isArray(handler)) {
for (var i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i]);
}
} else {
createWatcher(vm, key, handler);
}
}
}
function createWatcher (vm, key, handler) {
var options;
if (isPlainObject(handler)) {
options = handler;
handler = handler.handler;
}
if (typeof handler === 'string') {
handler = vm[handler];
}
vm.$watch(key, handler, options);
}
function stateMixin (Vue) {
// flow somehow has problems with directly declared definition object
// when using Object.defineProperty, so we have to procedurally build up
// the object here.
var dataDef = {};
dataDef.get = function () {
return this._data
};
if (process.env.NODE_ENV !== 'production') {
dataDef.set = function (newData) {
warn(
'Avoid replacing instance root $data. ' +
'Use nested data properties instead.',
this
);
};
}
Object.defineProperty(Vue.prototype, '$data', dataDef);
Vue.prototype.$set = set$1;
Vue.prototype.$delete = del;
Vue.prototype.$watch = function (
expOrFn,
cb,
options
) {
var vm = this;
options = options || {};
options.user = true;
var watcher = new Watcher(vm, expOrFn, cb, options);
if (options.immediate) {
cb.call(vm, watcher.value);
}
return function unwatchFn () {
watcher.teardown();
}
};
}
function proxy (vm, key) {
if (!isReserved(key)) {
Object.defineProperty(vm, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return vm._data[key]
},
set: function proxySetter (val) {
vm._data[key] = val;
}
});
}
}
/* */
var uid = 0;
function initMixin (Vue) {
Vue.prototype._init = function (options) {
var vm = this;
// a uid
vm._uid = uid++;
// a flag to avoid this being observed
vm._isVue = true;
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options);
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
);
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm);
} else {
vm._renderProxy = vm;
}
// expose real self
vm._self = vm;
initLifecycle(vm);
initEvents(vm);
initRender(vm);
callHook(vm, 'beforeCreate');
initState(vm);
callHook(vm, 'created');
if (vm.$options.el) {
vm.$mount(vm.$options.el);
}
};
}
function initInternalComponent (vm, options) {
var opts = vm.$options = Object.create(vm.constructor.options);
// doing this because it's faster than dynamic enumeration.
opts.parent = options.parent;
opts.propsData = options.propsData;
opts._parentVnode = options._parentVnode;
opts._parentListeners = options._parentListeners;
opts._renderChildren = options._renderChildren;
opts._componentTag = options._componentTag;
opts._parentElm = options._parentElm;
opts._refElm = options._refElm;
if (options.render) {
opts.render = options.render;
opts.staticRenderFns = options.staticRenderFns;
}
}
function resolveConstructorOptions (Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = Ctor.super.options;
var cachedSuperOptions = Ctor.superOptions;
var extendOptions = Ctor.extendOptions;
if (superOptions !== cachedSuperOptions) {
// super option changed
Ctor.superOptions = superOptions;
extendOptions.render = options.render;
extendOptions.staticRenderFns = options.staticRenderFns;
extendOptions._scopeId = options._scopeId;
options = Ctor.options = mergeOptions(superOptions, extendOptions);
if (options.name) {
options.components[options.name] = Ctor;
}
}
}
return options
}
function Vue$3 (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue$3)) {
warn('Vue is a constructor and should be called with the `new` keyword');
}
this._init(options);
}
initMixin(Vue$3);
stateMixin(Vue$3);
eventsMixin(Vue$3);
lifecycleMixin(Vue$3);
renderMixin(Vue$3);
/* */
function initUse (Vue) {
Vue.use = function (plugin) {
/* istanbul ignore if */
if (plugin.installed) {
return
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else {
plugin.apply(null, args);
}
plugin.installed = true;
return this
};
}
/* */
function initMixin$1 (Vue) {
Vue.mixin = function (mixin) {
this.options = mergeOptions(this.options, mixin);
};
}
/* */
function initExtend (Vue) {
/**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/
Vue.cid = 0;
var cid = 1;
/**
* Class inheritance
*/
Vue.extend = function (extendOptions) {
extendOptions = extendOptions || {};
var Super = this;
var SuperId = Super.cid;
var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) {
return cachedCtors[SuperId]
}
var name = extendOptions.name || Super.options.name;
if (process.env.NODE_ENV !== 'production') {
if (!/^[a-zA-Z][\w-]*$/.test(name)) {
warn(
'Invalid component name: "' + name + '". Component names ' +
'can only contain alphanumeric characters and the hyphen, ' +
'and must start with a letter.'
);
}
}
var Sub = function VueComponent (options) {
this._init(options);
};
Sub.prototype = Object.create(Super.prototype);
Sub.prototype.constructor = Sub;
Sub.cid = cid++;
Sub.options = mergeOptions(
Super.options,
extendOptions
);
Sub['super'] = Super;
// allow further extension/mixin/plugin usage
Sub.extend = Super.extend;
Sub.mixin = Super.mixin;
Sub.use = Super.use;
// create asset registers, so extended classes
// can have their private assets too.
config._assetTypes.forEach(function (type) {
Sub[type] = Super[type];
});
// enable recursive self-lookup
if (name) {
Sub.options.components[name] = Sub;
}
// keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options;
Sub.extendOptions = extendOptions;
// cache constructor
cachedCtors[SuperId] = Sub;
return Sub
};
}
/* */
function initAssetRegisters (Vue) {
/**
* Create asset registration methods.
*/
config._assetTypes.forEach(function (type) {
Vue[type] = function (
id,
definition
) {
if (!definition) {
return this.options[type + 's'][id]
} else {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
if (type === 'component' && config.isReservedTag(id)) {
warn(
'Do not use built-in or reserved HTML elements as component ' +
'id: ' + id
);
}
}
if (type === 'component' && isPlainObject(definition)) {
definition.name = definition.name || id;
definition = this.options._base.extend(definition);
}
if (type === 'directive' && typeof definition === 'function') {
definition = { bind: definition, update: definition };
}
this.options[type + 's'][id] = definition;
return definition
}
};
});
}
/* */
var patternTypes = [String, RegExp];
function getComponentName (opts) {
return opts && (opts.Ctor.options.name || opts.tag)
}
function matches (pattern, name) {
if (typeof pattern === 'string') {
return pattern.split(',').indexOf(name) > -1
} else {
return pattern.test(name)
}
}
function pruneCache (cache, filter) {
for (var key in cache) {
var cachedNode = cache[key];
if (cachedNode) {
var name = getComponentName(cachedNode.componentOptions);
if (name && !filter(name)) {
pruneCacheEntry(cachedNode);
cache[key] = null;
}
}
}
}
function pruneCacheEntry (vnode) {
if (vnode) {
if (!vnode.componentInstance._inactive) {
callHook(vnode.componentInstance, 'deactivated');
}
vnode.componentInstance.$destroy();
}
}
var KeepAlive = {
name: 'keep-alive',
abstract: true,
props: {
include: patternTypes,
exclude: patternTypes
},
created: function created () {
this.cache = Object.create(null);
},
destroyed: function destroyed () {
var this$1 = this;
for (var key in this.cache) {
pruneCacheEntry(this$1.cache[key]);
}
},
watch: {
include: function include (val) {
pruneCache(this.cache, function (name) { return matches(val, name); });
},
exclude: function exclude (val) {
pruneCache(this.cache, function (name) { return !matches(val, name); });
}
},
render: function render () {
var vnode = getFirstComponentChild(this.$slots.default);
var componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
var name = getComponentName(componentOptions);
if (name && (
(this.include && !matches(this.include, name)) ||
(this.exclude && matches(this.exclude, name))
)) {
return vnode
}
var key = vnode.key == null
// same constructor may get registered as different local components
// so cid alone is not enough (#3269)
? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '')
: vnode.key;
if (this.cache[key]) {
vnode.componentInstance = this.cache[key].componentInstance;
} else {
this.cache[key] = vnode;
}
vnode.data.keepAlive = true;
}
return vnode
}
};
var builtInComponents = {
KeepAlive: KeepAlive
};
/* */
function initGlobalAPI (Vue) {
// config
var configDef = {};
configDef.get = function () { return config; };
if (process.env.NODE_ENV !== 'production') {
configDef.set = function () {
warn(
'Do not replace the Vue.config object, set individual fields instead.'
);
};
}
Object.defineProperty(Vue, 'config', configDef);
Vue.util = util;
Vue.set = set$1;
Vue.delete = del;
Vue.nextTick = nextTick;
Vue.options = Object.create(null);
config._assetTypes.forEach(function (type) {
Vue.options[type + 's'] = Object.create(null);
});
// this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue;
extend(Vue.options.components, builtInComponents);
initUse(Vue);
initMixin$1(Vue);
initExtend(Vue);
initAssetRegisters(Vue);
}
initGlobalAPI(Vue$3);
Object.defineProperty(Vue$3.prototype, '$isServer', {
get: isServerRendering
});
Vue$3.version = '2.1.10';
/* */
// attributes that should be using props for binding
var acceptValue = makeMap('input,textarea,option,select');
var mustUseProp = function (tag, type, attr) {
return (
(attr === 'value' && acceptValue(tag)) && type !== 'button' ||
(attr === 'selected' && tag === 'option') ||
(attr === 'checked' && tag === 'input') ||
(attr === 'muted' && tag === 'video')
)
};
var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck');
var isBooleanAttr = makeMap(
'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' +
'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' +
'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' +
'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' +
'required,reversed,scoped,seamless,selected,sortable,translate,' +
'truespeed,typemustmatch,visible'
);
var xlinkNS = 'http://www.w3.org/1999/xlink';
var isXlink = function (name) {
return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink'
};
var getXlinkProp = function (name) {
return isXlink(name) ? name.slice(6, name.length) : ''
};
var isFalsyAttrValue = function (val) {
return val == null || val === false
};
/* */
function genClassForVnode (vnode) {
var data = vnode.data;
var parentNode = vnode;
var childNode = vnode;
while (childNode.componentInstance) {
childNode = childNode.componentInstance._vnode;
if (childNode.data) {
data = mergeClassData(childNode.data, data);
}
}
while ((parentNode = parentNode.parent)) {
if (parentNode.data) {
data = mergeClassData(data, parentNode.data);
}
}
return genClassFromData(data)
}
function mergeClassData (child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: child.class
? [child.class, parent.class]
: parent.class
}
}
function genClassFromData (data) {
var dynamicClass = data.class;
var staticClass = data.staticClass;
if (staticClass || dynamicClass) {
return concat(staticClass, stringifyClass(dynamicClass))
}
/* istanbul ignore next */
return ''
}
function concat (a, b) {
return a ? b ? (a + ' ' + b) : a : (b || '')
}
function stringifyClass (value) {
var res = '';
if (!value) {
return res
}
if (typeof value === 'string') {
return value
}
if (Array.isArray(value)) {
var stringified;
for (var i = 0, l = value.length; i < l; i++) {
if (value[i]) {
if ((stringified = stringifyClass(value[i]))) {
res += stringified + ' ';
}
}
}
return res.slice(0, -1)
}
if (isObject(value)) {
for (var key in value) {
if (value[key]) { res += key + ' '; }
}
return res.slice(0, -1)
}
/* istanbul ignore next */
return res
}
/* */
var namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML'
};
var isHTMLTag = makeMap(
'html,body,base,head,link,meta,style,title,' +
'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' +
'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' +
'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' +
's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' +
'embed,object,param,source,canvas,script,noscript,del,ins,' +
'caption,col,colgroup,table,thead,tbody,td,th,tr,' +
'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' +
'output,progress,select,textarea,' +
'details,dialog,menu,menuitem,summary,' +
'content,element,shadow,template'
);
// this map is intentionally selective, only covering SVG elements that may
// contain child elements.
var isSVG = makeMap(
'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,' +
'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' +
'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view',
true
);
var isPreTag = function (tag) { return tag === 'pre'; };
var isReservedTag = function (tag) {
return isHTMLTag(tag) || isSVG(tag)
};
function getTagNamespace (tag) {
if (isSVG(tag)) {
return 'svg'
}
// basic support for MathML
// note it doesn't support other MathML elements being component roots
if (tag === 'math') {
return 'math'
}
}
var unknownElementCache = Object.create(null);
function isUnknownElement (tag) {
/* istanbul ignore if */
if (!inBrowser) {
return true
}
if (isReservedTag(tag)) {
return false
}
tag = tag.toLowerCase();
/* istanbul ignore if */
if (unknownElementCache[tag] != null) {
return unknownElementCache[tag]
}
var el = document.createElement(tag);
if (tag.indexOf('-') > -1) {
// http://stackoverflow.com/a/28210364/1070244
return (unknownElementCache[tag] = (
el.constructor === window.HTMLUnknownElement ||
el.constructor === window.HTMLElement
))
} else {
return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString()))
}
}
/* */
/**
* Query an element selector if it's not an element already.
*/
function query (el) {
if (typeof el === 'string') {
var selector = el;
el = document.querySelector(el);
if (!el) {
process.env.NODE_ENV !== 'production' && warn(
'Cannot find element: ' + selector
);
return document.createElement('div')
}
}
return el
}
/* */
function createElement$1 (tagName, vnode) {
var elm = document.createElement(tagName);
if (tagName !== 'select') {
return elm
}
if (vnode.data && vnode.data.attrs && 'multiple' in vnode.data.attrs) {
elm.setAttribute('multiple', 'multiple');
}
return elm
}
function createElementNS (namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName)
}
function createTextNode (text) {
return document.createTextNode(text)
}
function createComment (text) {
return document.createComment(text)
}
function insertBefore (parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode);
}
function removeChild (node, child) {
node.removeChild(child);
}
function appendChild (node, child) {
node.appendChild(child);
}
function parentNode (node) {
return node.parentNode
}
function nextSibling (node) {
return node.nextSibling
}
function tagName (node) {
return node.tagName
}
function setTextContent (node, text) {
node.textContent = text;
}
function setAttribute (node, key, val) {
node.setAttribute(key, val);
}
var nodeOps = Object.freeze({
createElement: createElement$1,
createElementNS: createElementNS,
createTextNode: createTextNode,
createComment: createComment,
insertBefore: insertBefore,
removeChild: removeChild,
appendChild: appendChild,
parentNode: parentNode,
nextSibling: nextSibling,
tagName: tagName,
setTextContent: setTextContent,
setAttribute: setAttribute
});
/* */
var ref = {
create: function create (_, vnode) {
registerRef(vnode);
},
update: function update (oldVnode, vnode) {
if (oldVnode.data.ref !== vnode.data.ref) {
registerRef(oldVnode, true);
registerRef(vnode);
}
},
destroy: function destroy (vnode) {
registerRef(vnode, true);
}
};
function registerRef (vnode, isRemoval) {
var key = vnode.data.ref;
if (!key) { return }
var vm = vnode.context;
var ref = vnode.componentInstance || vnode.elm;
var refs = vm.$refs;
if (isRemoval) {
if (Array.isArray(refs[key])) {
remove$1(refs[key], ref);
} else if (refs[key] === ref) {
refs[key] = undefined;
}
} else {
if (vnode.data.refInFor) {
if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) {
refs[key].push(ref);
} else {
refs[key] = [ref];
}
} else {
refs[key] = ref;
}
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
/*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/
var emptyNode = new VNode('', {}, []);
var hooks$1 = ['create', 'activate', 'update', 'remove', 'destroy'];
function isUndef (s) {
return s == null
}
function isDef (s) {
return s != null
}
function sameVnode (vnode1, vnode2) {
return (
vnode1.key === vnode2.key &&
vnode1.tag === vnode2.tag &&
vnode1.isComment === vnode2.isComment &&
!vnode1.data === !vnode2.data
)
}
function createKeyToOldIdx (children, beginIdx, endIdx) {
var i, key;
var map = {};
for (i = beginIdx; i <= endIdx; ++i) {
key = children[i].key;
if (isDef(key)) { map[key] = i; }
}
return map
}
function createPatchFunction (backend) {
var i, j;
var cbs = {};
var modules = backend.modules;
var nodeOps = backend.nodeOps;
for (i = 0; i < hooks$1.length; ++i) {
cbs[hooks$1[i]] = [];
for (j = 0; j < modules.length; ++j) {
if (modules[j][hooks$1[i]] !== undefined) { cbs[hooks$1[i]].push(modules[j][hooks$1[i]]); }
}
}
function emptyNodeAt (elm) {
return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm)
}
function createRmCb (childElm, listeners) {
function remove$$1 () {
if (--remove$$1.listeners === 0) {
removeNode(childElm);
}
}
remove$$1.listeners = listeners;
return remove$$1
}
function removeNode (el) {
var parent = nodeOps.parentNode(el);
// element may have already been removed due to v-html / v-text
if (parent) {
nodeOps.removeChild(parent, el);
}
}
var inPre = 0;
function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) {
vnode.isRootInsert = !nested; // for transition enter check
if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) {
return
}
var data = vnode.data;
var children = vnode.children;
var tag = vnode.tag;
if (isDef(tag)) {
if (process.env.NODE_ENV !== 'production') {
if (data && data.pre) {
inPre++;
}
if (
!inPre &&
!vnode.ns &&
!(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) &&
config.isUnknownElement(tag)
) {
warn(
'Unknown custom element: <' + tag + '> - did you ' +
'register the component correctly? For recursive components, ' +
'make sure to provide the "name" option.',
vnode.context
);
}
}
vnode.elm = vnode.ns
? nodeOps.createElementNS(vnode.ns, tag)
: nodeOps.createElement(tag, vnode);
setScope(vnode);
/* istanbul ignore if */
{
createChildren(vnode, children, insertedVnodeQueue);
if (isDef(data)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
}
insert(parentElm, vnode.elm, refElm);
}
if (process.env.NODE_ENV !== 'production' && data && data.pre) {
inPre--;
}
} else if (vnode.isComment) {
vnode.elm = nodeOps.createComment(vnode.text);
insert(parentElm, vnode.elm, refElm);
} else {
vnode.elm = nodeOps.createTextNode(vnode.text);
insert(parentElm, vnode.elm, refElm);
}
}
function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i = vnode.data;
if (isDef(i)) {
var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;
if (isDef(i = i.hook) && isDef(i = i.init)) {
i(vnode, false /* hydrating */, parentElm, refElm);
}
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(vnode.componentInstance)) {
initComponent(vnode, insertedVnodeQueue);
if (isReactivated) {
reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm);
}
return true
}
}
}
function initComponent (vnode, insertedVnodeQueue) {
if (vnode.data.pendingInsert) {
insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert);
}
vnode.elm = vnode.componentInstance.$el;
if (isPatchable(vnode)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
setScope(vnode);
} else {
// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode);
// make sure to invoke the insert hook
insertedVnodeQueue.push(vnode);
}
}
function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) {
var i;
// hack for #4339: a reactivated component with inner transition
// does not trigger because the inner node's created hooks are not called
// again. It's not ideal to involve module-specific logic in here but
// there doesn't seem to be a better way to do it.
var innerNode = vnode;
while (innerNode.componentInstance) {
innerNode = innerNode.componentInstance._vnode;
if (isDef(i = innerNode.data) && isDef(i = i.transition)) {
for (i = 0; i < cbs.activate.length; ++i) {
cbs.activate[i](emptyNode, innerNode);
}
insertedVnodeQueue.push(innerNode);
break
}
}
// unlike a newly created component,
// a reactivated keep-alive component doesn't insert itself
insert(parentElm, vnode.elm, refElm);
}
function insert (parent, elm, ref) {
if (parent) {
if (ref) {
nodeOps.insertBefore(parent, elm, ref);
} else {
nodeOps.appendChild(parent, elm);
}
}
}
function createChildren (vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
for (var i = 0; i < children.length; ++i) {
createElm(children[i], insertedVnodeQueue, vnode.elm, null, true);
}
} else if (isPrimitive(vnode.text)) {
nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text));
}
}
function isPatchable (vnode) {
while (vnode.componentInstance) {
vnode = vnode.componentInstance._vnode;
}
return isDef(vnode.tag)
}
function invokeCreateHooks (vnode, insertedVnodeQueue) {
for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) {
cbs.create[i$1](emptyNode, vnode);
}
i = vnode.data.hook; // Reuse variable
if (isDef(i)) {
if (i.create) { i.create(emptyNode, vnode); }
if (i.insert) { insertedVnodeQueue.push(vnode); }
}
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope (vnode) {
var i;
if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
if (isDef(i = activeInstance) &&
i !== vnode.context &&
isDef(i = i.$options._scopeId)) {
nodeOps.setAttribute(vnode.elm, i, '');
}
}
function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for (; startIdx <= endIdx; ++startIdx) {
createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm);
}
}
function invokeDestroyHook (vnode) {
var i, j;
var data = vnode.data;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); }
for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); }
}
if (isDef(i = vnode.children)) {
for (j = 0; j < vnode.children.length; ++j) {
invokeDestroyHook(vnode.children[j]);
}
}
}
function removeVnodes (parentElm, vnodes, startIdx, endIdx) {
for (; startIdx <= endIdx; ++startIdx) {
var ch = vnodes[startIdx];
if (isDef(ch)) {
if (isDef(ch.tag)) {
removeAndInvokeRemoveHook(ch);
invokeDestroyHook(ch);
} else { // Text node
removeNode(ch.elm);
}
}
}
}
function removeAndInvokeRemoveHook (vnode, rm) {
if (rm || isDef(vnode.data)) {
var listeners = cbs.remove.length + 1;
if (!rm) {
// directly removing
rm = createRmCb(vnode.elm, listeners);
} else {
// we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners;
}
// recursively invoke hooks on child component root node
if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) {
removeAndInvokeRemoveHook(i, rm);
}
for (i = 0; i < cbs.remove.length; ++i) {
cbs.remove[i](vnode, rm);
}
if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) {
i(vnode, rm);
} else {
rm();
}
} else {
removeNode(vnode.elm);
}
}
function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
var oldStartIdx = 0;
var newStartIdx = 0;
var oldEndIdx = oldCh.length - 1;
var oldStartVnode = oldCh[0];
var oldEndVnode = oldCh[oldEndIdx];
var newEndIdx = newCh.length - 1;
var newStartVnode = newCh[0];
var newEndVnode = newCh[newEndIdx];
var oldKeyToIdx, idxInOld, elmToMove, refElm;
// removeOnly is a special flag used only by <transition-group>
// to ensure removed elements stay in correct relative positions
// during leaving transitions
var canMove = !removeOnly;
while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {
if (isUndef(oldStartVnode)) {
oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left
} else if (isUndef(oldEndVnode)) {
oldEndVnode = oldCh[--oldEndIdx];
} else if (sameVnode(oldStartVnode, newStartVnode)) {
patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue);
oldStartVnode = oldCh[++oldStartIdx];
newStartVnode = newCh[++newStartIdx];
} else if (sameVnode(oldEndVnode, newEndVnode)) {
patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue);
oldEndVnode = oldCh[--oldEndIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right
patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm));
oldStartVnode = oldCh[++oldStartIdx];
newEndVnode = newCh[--newEndIdx];
} else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left
patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue);
canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm);
oldEndVnode = oldCh[--oldEndIdx];
newStartVnode = newCh[++newStartIdx];
} else {
if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); }
idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null;
if (isUndef(idxInOld)) { // New element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
elmToMove = oldCh[idxInOld];
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !elmToMove) {
warn(
'It seems there are duplicate keys that is causing an update error. ' +
'Make sure each v-for item has a unique key.'
);
}
if (sameVnode(elmToMove, newStartVnode)) {
patchVnode(elmToMove, newStartVnode, insertedVnodeQueue);
oldCh[idxInOld] = undefined;
canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
} else {
// same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm);
newStartVnode = newCh[++newStartIdx];
}
}
}
}
if (oldStartIdx > oldEndIdx) {
refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm;
addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue);
} else if (newStartIdx > newEndIdx) {
removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx);
}
}
function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) {
if (oldVnode === vnode) {
return
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (vnode.isStatic &&
oldVnode.isStatic &&
vnode.key === oldVnode.key &&
(vnode.isCloned || vnode.isOnce)) {
vnode.elm = oldVnode.elm;
vnode.componentInstance = oldVnode.componentInstance;
return
}
var i;
var data = vnode.data;
var hasData = isDef(data);
if (hasData && isDef(i = data.hook) && isDef(i = i.prepatch)) {
i(oldVnode, vnode);
}
var elm = vnode.elm = oldVnode.elm;
var oldCh = oldVnode.children;
var ch = vnode.children;
if (hasData && isPatchable(vnode)) {
for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); }
if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); }
}
if (isUndef(vnode.text)) {
if (isDef(oldCh) && isDef(ch)) {
if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); }
} else if (isDef(ch)) {
if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); }
addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue);
} else if (isDef(oldCh)) {
removeVnodes(elm, oldCh, 0, oldCh.length - 1);
} else if (isDef(oldVnode.text)) {
nodeOps.setTextContent(elm, '');
}
} else if (oldVnode.text !== vnode.text) {
nodeOps.setTextContent(elm, vnode.text);
}
if (hasData) {
if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); }
}
}
function invokeInsertHook (vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (initial && vnode.parent) {
vnode.parent.data.pendingInsert = queue;
} else {
for (var i = 0; i < queue.length; ++i) {
queue[i].data.hook.insert(queue[i]);
}
}
}
var bailed = false;
// list of modules that can skip create hook during hydration because they
// are already rendered on the client or has no need for initialization
var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key');
// Note: this is a browser-only function so we can assume elms are DOM nodes.
function hydrate (elm, vnode, insertedVnodeQueue) {
if (process.env.NODE_ENV !== 'production') {
if (!assertNodeMatch(elm, vnode)) {
return false
}
}
vnode.elm = elm;
var tag = vnode.tag;
var data = vnode.data;
var children = vnode.children;
if (isDef(data)) {
if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); }
if (isDef(i = vnode.componentInstance)) {
// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue);
return true
}
}
if (isDef(tag)) {
if (isDef(children)) {
// empty element, allow client to pick up and populate children
if (!elm.hasChildNodes()) {
createChildren(vnode, children, insertedVnodeQueue);
} else {
var childrenMatch = true;
var childNode = elm.firstChild;
for (var i$1 = 0; i$1 < children.length; i$1++) {
if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) {
childrenMatch = false;
break
}
childNode = childNode.nextSibling;
}
// if childNode is not null, it means the actual childNodes list is
// longer than the virtual children list.
if (!childrenMatch || childNode) {
if (process.env.NODE_ENV !== 'production' &&
typeof console !== 'undefined' &&
!bailed) {
bailed = true;
console.warn('Parent: ', elm);
console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
}
return false
}
}
}
if (isDef(data)) {
for (var key in data) {
if (!isRenderedModule(key)) {
invokeCreateHooks(vnode, insertedVnodeQueue);
break
}
}
}
} else if (elm.data !== vnode.text) {
elm.data = vnode.text;
}
return true
}
function assertNodeMatch (node, vnode) {
if (vnode.tag) {
return (
vnode.tag.indexOf('vue-component') === 0 ||
vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase())
)
} else {
return node.nodeType === (vnode.isComment ? 8 : 3)
}
}
return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) {
if (!vnode) {
if (oldVnode) { invokeDestroyHook(oldVnode); }
return
}
var isInitialPatch = false;
var insertedVnodeQueue = [];
if (!oldVnode) {
// empty mount (likely as component), create new root element
isInitialPatch = true;
createElm(vnode, insertedVnodeQueue, parentElm, refElm);
} else {
var isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) {
// patch existing root node
patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly);
} else {
if (isRealElement) {
// mounting to a real element
// check if this is server-rendered content and if we can perform
// a successful hydration.
if (oldVnode.nodeType === 1 && oldVnode.hasAttribute('server-rendered')) {
oldVnode.removeAttribute('server-rendered');
hydrating = true;
}
if (hydrating) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) {
invokeInsertHook(vnode, insertedVnodeQueue, true);
return oldVnode
} else if (process.env.NODE_ENV !== 'production') {
warn(
'The client-side rendered virtual DOM tree is not matching ' +
'server-rendered content. This is likely caused by incorrect ' +
'HTML markup, for example nesting block-level elements inside ' +
'<p>, or missing <tbody>. Bailing hydration and performing ' +
'full client-side render.'
);
}
}
// either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = emptyNodeAt(oldVnode);
}
// replacing existing element
var oldElm = oldVnode.elm;
var parentElm$1 = nodeOps.parentNode(oldElm);
createElm(
vnode,
insertedVnodeQueue,
// extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm$1,
nodeOps.nextSibling(oldElm)
);
if (vnode.parent) {
// component root element replaced.
// update parent placeholder node element, recursively
var ancestor = vnode.parent;
while (ancestor) {
ancestor.elm = vnode.elm;
ancestor = ancestor.parent;
}
if (isPatchable(vnode)) {
for (var i = 0; i < cbs.create.length; ++i) {
cbs.create[i](emptyNode, vnode.parent);
}
}
}
if (parentElm$1 !== null) {
removeVnodes(parentElm$1, [oldVnode], 0, 0);
} else if (isDef(oldVnode.tag)) {
invokeDestroyHook(oldVnode);
}
}
}
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch);
return vnode.elm
}
}
/* */
var directives = {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives (vnode) {
updateDirectives(vnode, emptyNode);
}
};
function updateDirectives (oldVnode, vnode) {
if (oldVnode.data.directives || vnode.data.directives) {
_update(oldVnode, vnode);
}
}
function _update (oldVnode, vnode) {
var isCreate = oldVnode === emptyNode;
var isDestroy = vnode === emptyNode;
var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context);
var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context);
var dirsWithInsert = [];
var dirsWithPostpatch = [];
var key, oldDir, dir;
for (key in newDirs) {
oldDir = oldDirs[key];
dir = newDirs[key];
if (!oldDir) {
// new directive, bind
callHook$1(dir, 'bind', vnode, oldVnode);
if (dir.def && dir.def.inserted) {
dirsWithInsert.push(dir);
}
} else {
// existing directive, update
dir.oldValue = oldDir.value;
callHook$1(dir, 'update', vnode, oldVnode);
if (dir.def && dir.def.componentUpdated) {
dirsWithPostpatch.push(dir);
}
}
}
if (dirsWithInsert.length) {
var callInsert = function () {
for (var i = 0; i < dirsWithInsert.length; i++) {
callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);
}
};
if (isCreate) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert, 'dir-insert');
} else {
callInsert();
}
}
if (dirsWithPostpatch.length) {
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () {
for (var i = 0; i < dirsWithPostpatch.length; i++) {
callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);
}
}, 'dir-postpatch');
}
if (!isCreate) {
for (key in oldDirs) {
if (!newDirs[key]) {
// no longer present, unbind
callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);
}
}
}
}
var emptyModifiers = Object.create(null);
function normalizeDirectives$1 (
dirs,
vm
) {
var res = Object.create(null);
if (!dirs) {
return res
}
var i, dir;
for (i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!dir.modifiers) {
dir.modifiers = emptyModifiers;
}
res[getRawDirName(dir)] = dir;
dir.def = resolveAsset(vm.$options, 'directives', dir.name, true);
}
return res
}
function getRawDirName (dir) {
return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.')))
}
function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) {
var fn = dir.def && dir.def[hook];
if (fn) {
fn(vnode.elm, dir, vnode, oldVnode, isDestroy);
}
}
var baseModules = [
ref,
directives
];
/* */
function updateAttrs (oldVnode, vnode) {
if (!oldVnode.data.attrs && !vnode.data.attrs) {
return
}
var key, cur, old;
var elm = vnode.elm;
var oldAttrs = oldVnode.data.attrs || {};
var attrs = vnode.data.attrs || {};
// clone observed objects, as the user probably wants to mutate it
if (attrs.__ob__) {
attrs = vnode.data.attrs = extend({}, attrs);
}
for (key in attrs) {
cur = attrs[key];
old = oldAttrs[key];
if (old !== cur) {
setAttr(elm, key, cur);
}
}
// #4391: in IE9, setting type can reset value for input[type=radio]
/* istanbul ignore if */
if (isIE9 && attrs.value !== oldAttrs.value) {
setAttr(elm, 'value', attrs.value);
}
for (key in oldAttrs) {
if (attrs[key] == null) {
if (isXlink(key)) {
elm.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else if (!isEnumeratedAttr(key)) {
elm.removeAttribute(key);
}
}
}
}
function setAttr (el, key, value) {
if (isBooleanAttr(key)) {
// set attribute for blank value
// e.g. <option disabled>Select one</option>
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, key);
}
} else if (isEnumeratedAttr(key)) {
el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true');
} else if (isXlink(key)) {
if (isFalsyAttrValue(value)) {
el.removeAttributeNS(xlinkNS, getXlinkProp(key));
} else {
el.setAttributeNS(xlinkNS, key, value);
}
} else {
if (isFalsyAttrValue(value)) {
el.removeAttribute(key);
} else {
el.setAttribute(key, value);
}
}
}
var attrs = {
create: updateAttrs,
update: updateAttrs
};
/* */
function updateClass (oldVnode, vnode) {
var el = vnode.elm;
var data = vnode.data;
var oldData = oldVnode.data;
if (!data.staticClass && !data.class &&
(!oldData || (!oldData.staticClass && !oldData.class))) {
return
}
var cls = genClassForVnode(vnode);
// handle transition classes
var transitionClass = el._transitionClasses;
if (transitionClass) {
cls = concat(cls, stringifyClass(transitionClass));
}
// set the class
if (cls !== el._prevClass) {
el.setAttribute('class', cls);
el._prevClass = cls;
}
}
var klass = {
create: updateClass,
update: updateClass
};
/* */
var target$1;
function add$2 (
event,
handler,
once,
capture
) {
if (once) {
var oldHandler = handler;
var _target = target$1; // save current target element in closure
handler = function (ev) {
remove$3(event, handler, capture, _target);
arguments.length === 1
? oldHandler(ev)
: oldHandler.apply(null, arguments);
};
}
target$1.addEventListener(event, handler, capture);
}
function remove$3 (
event,
handler,
capture,
_target
) {
(_target || target$1).removeEventListener(event, handler, capture);
}
function updateDOMListeners (oldVnode, vnode) {
if (!oldVnode.data.on && !vnode.data.on) {
return
}
var on = vnode.data.on || {};
var oldOn = oldVnode.data.on || {};
target$1 = vnode.elm;
updateListeners(on, oldOn, add$2, remove$3, vnode.context);
}
var events = {
create: updateDOMListeners,
update: updateDOMListeners
};
/* */
function updateDOMProps (oldVnode, vnode) {
if (!oldVnode.data.domProps && !vnode.data.domProps) {
return
}
var key, cur;
var elm = vnode.elm;
var oldProps = oldVnode.data.domProps || {};
var props = vnode.data.domProps || {};
// clone observed objects, as the user probably wants to mutate it
if (props.__ob__) {
props = vnode.data.domProps = extend({}, props);
}
for (key in oldProps) {
if (props[key] == null) {
elm[key] = '';
}
}
for (key in props) {
cur = props[key];
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if (key === 'textContent' || key === 'innerHTML') {
if (vnode.children) { vnode.children.length = 0; }
if (cur === oldProps[key]) { continue }
}
if (key === 'value') {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur;
// avoid resetting cursor position when value is the same
var strCur = cur == null ? '' : String(cur);
if (shouldUpdateValue(elm, vnode, strCur)) {
elm.value = strCur;
}
} else {
elm[key] = cur;
}
}
}
// check platforms/web/util/attrs.js acceptValue
function shouldUpdateValue (
elm,
vnode,
checkVal
) {
return (!elm.composing && (
vnode.tag === 'option' ||
isDirty(elm, checkVal) ||
isInputChanged(vnode, checkVal)
))
}
function isDirty (elm, checkVal) {
// return true when textbox (.number and .trim) loses focus and its value is not equal to the updated value
return document.activeElement !== elm && elm.value !== checkVal
}
function isInputChanged (vnode, newVal) {
var value = vnode.elm.value;
var modifiers = vnode.elm._vModifiers; // injected by v-model runtime
if ((modifiers && modifiers.number) || vnode.elm.type === 'number') {
return toNumber(value) !== toNumber(newVal)
}
if (modifiers && modifiers.trim) {
return value.trim() !== newVal.trim()
}
return value !== newVal
}
var domProps = {
create: updateDOMProps,
update: updateDOMProps
};
/* */
var parseStyleText = cached(function (cssText) {
var res = {};
var listDelimiter = /;(?![^(]*\))/g;
var propertyDelimiter = /:(.+)/;
cssText.split(listDelimiter).forEach(function (item) {
if (item) {
var tmp = item.split(propertyDelimiter);
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());
}
});
return res
});
// merge static and dynamic style data on the same vnode
function normalizeStyleData (data) {
var style = normalizeStyleBinding(data.style);
// static style is pre-processed into an object during compilation
// and is always a fresh object, so it's safe to merge into it
return data.staticStyle
? extend(data.staticStyle, style)
: style
}
// normalize possible array / string values into Object
function normalizeStyleBinding (bindingStyle) {
if (Array.isArray(bindingStyle)) {
return toObject(bindingStyle)
}
if (typeof bindingStyle === 'string') {
return parseStyleText(bindingStyle)
}
return bindingStyle
}
/**
* parent component style should be after child's
* so that parent component's style could override it
*/
function getStyle (vnode, checkChild) {
var res = {};
var styleData;
if (checkChild) {
var childNode = vnode;
while (childNode.componentInstance) {
childNode = childNode.componentInstance._vnode;
if (childNode.data && (styleData = normalizeStyleData(childNode.data))) {
extend(res, styleData);
}
}
}
if ((styleData = normalizeStyleData(vnode.data))) {
extend(res, styleData);
}
var parentNode = vnode;
while ((parentNode = parentNode.parent)) {
if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) {
extend(res, styleData);
}
}
return res
}
/* */
var cssVarRE = /^--/;
var importantRE = /\s*!important$/;
var setProp = function (el, name, val) {
/* istanbul ignore if */
if (cssVarRE.test(name)) {
el.style.setProperty(name, val);
} else if (importantRE.test(val)) {
el.style.setProperty(name, val.replace(importantRE, ''), 'important');
} else {
el.style[normalize(name)] = val;
}
};
var prefixes = ['Webkit', 'Moz', 'ms'];
var testEl;
var normalize = cached(function (prop) {
testEl = testEl || document.createElement('div');
prop = camelize(prop);
if (prop !== 'filter' && (prop in testEl.style)) {
return prop
}
var upper = prop.charAt(0).toUpperCase() + prop.slice(1);
for (var i = 0; i < prefixes.length; i++) {
var prefixed = prefixes[i] + upper;
if (prefixed in testEl.style) {
return prefixed
}
}
});
function updateStyle (oldVnode, vnode) {
var data = vnode.data;
var oldData = oldVnode.data;
if (!data.staticStyle && !data.style &&
!oldData.staticStyle && !oldData.style) {
return
}
var cur, name;
var el = vnode.elm;
var oldStaticStyle = oldVnode.data.staticStyle;
var oldStyleBinding = oldVnode.data.style || {};
// if static style exists, stylebinding already merged into it when doing normalizeStyleData
var oldStyle = oldStaticStyle || oldStyleBinding;
var style = normalizeStyleBinding(vnode.data.style) || {};
vnode.data.style = style.__ob__ ? extend({}, style) : style;
var newStyle = getStyle(vnode, true);
for (name in oldStyle) {
if (newStyle[name] == null) {
setProp(el, name, '');
}
}
for (name in newStyle) {
cur = newStyle[name];
if (cur !== oldStyle[name]) {
// ie9 setting to null has no effect, must use empty string
setProp(el, name, cur == null ? '' : cur);
}
}
}
var style = {
create: updateStyle,
update: updateStyle
};
/* */
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function addClass (el, cls) {
/* istanbul ignore if */
if (!cls || !cls.trim()) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); });
} else {
el.classList.add(cls);
}
} else {
var cur = ' ' + el.getAttribute('class') + ' ';
if (cur.indexOf(' ' + cls + ' ') < 0) {
el.setAttribute('class', (cur + cls).trim());
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/
function removeClass (el, cls) {
/* istanbul ignore if */
if (!cls || !cls.trim()) {
return
}
/* istanbul ignore else */
if (el.classList) {
if (cls.indexOf(' ') > -1) {
cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); });
} else {
el.classList.remove(cls);
}
} else {
var cur = ' ' + el.getAttribute('class') + ' ';
var tar = ' ' + cls + ' ';
while (cur.indexOf(tar) >= 0) {
cur = cur.replace(tar, ' ');
}
el.setAttribute('class', cur.trim());
}
}
/* */
var hasTransition = inBrowser && !isIE9;
var TRANSITION = 'transition';
var ANIMATION = 'animation';
// Transition property/event sniffing
var transitionProp = 'transition';
var transitionEndEvent = 'transitionend';
var animationProp = 'animation';
var animationEndEvent = 'animationend';
if (hasTransition) {
/* istanbul ignore if */
if (window.ontransitionend === undefined &&
window.onwebkittransitionend !== undefined) {
transitionProp = 'WebkitTransition';
transitionEndEvent = 'webkitTransitionEnd';
}
if (window.onanimationend === undefined &&
window.onwebkitanimationend !== undefined) {
animationProp = 'WebkitAnimation';
animationEndEvent = 'webkitAnimationEnd';
}
}
// binding to window is necessary to make hot reload work in IE in strict mode
var raf = inBrowser && window.requestAnimationFrame
? window.requestAnimationFrame.bind(window)
: setTimeout;
function nextFrame (fn) {
raf(function () {
raf(fn);
});
}
function addTransitionClass (el, cls) {
(el._transitionClasses || (el._transitionClasses = [])).push(cls);
addClass(el, cls);
}
function removeTransitionClass (el, cls) {
if (el._transitionClasses) {
remove$1(el._transitionClasses, cls);
}
removeClass(el, cls);
}
function whenTransitionEnds (
el,
expectedType,
cb
) {
var ref = getTransitionInfo(el, expectedType);
var type = ref.type;
var timeout = ref.timeout;
var propCount = ref.propCount;
if (!type) { return cb() }
var event = type === TRANSITION ? transitionEndEvent : animationEndEvent;
var ended = 0;
var end = function () {
el.removeEventListener(event, onEnd);
cb();
};
var onEnd = function (e) {
if (e.target === el) {
if (++ended >= propCount) {
end();
}
}
};
setTimeout(function () {
if (ended < propCount) {
end();
}
}, timeout + 1);
el.addEventListener(event, onEnd);
}
var transformRE = /\b(transform|all)(,|$)/;
function getTransitionInfo (el, expectedType) {
var styles = window.getComputedStyle(el);
var transitioneDelays = styles[transitionProp + 'Delay'].split(', ');
var transitionDurations = styles[transitionProp + 'Duration'].split(', ');
var transitionTimeout = getTimeout(transitioneDelays, transitionDurations);
var animationDelays = styles[animationProp + 'Delay'].split(', ');
var animationDurations = styles[animationProp + 'Duration'].split(', ');
var animationTimeout = getTimeout(animationDelays, animationDurations);
var type;
var timeout = 0;
var propCount = 0;
/* istanbul ignore if */
if (expectedType === TRANSITION) {
if (transitionTimeout > 0) {
type = TRANSITION;
timeout = transitionTimeout;
propCount = transitionDurations.length;
}
} else if (expectedType === ANIMATION) {
if (animationTimeout > 0) {
type = ANIMATION;
timeout = animationTimeout;
propCount = animationDurations.length;
}
} else {
timeout = Math.max(transitionTimeout, animationTimeout);
type = timeout > 0
? transitionTimeout > animationTimeout
? TRANSITION
: ANIMATION
: null;
propCount = type
? type === TRANSITION
? transitionDurations.length
: animationDurations.length
: 0;
}
var hasTransform =
type === TRANSITION &&
transformRE.test(styles[transitionProp + 'Property']);
return {
type: type,
timeout: timeout,
propCount: propCount,
hasTransform: hasTransform
}
}
function getTimeout (delays, durations) {
/* istanbul ignore next */
while (delays.length < durations.length) {
delays = delays.concat(delays);
}
return Math.max.apply(null, durations.map(function (d, i) {
return toMs(d) + toMs(delays[i])
}))
}
function toMs (s) {
return Number(s.slice(0, -1)) * 1000
}
/* */
function enter (vnode, toggleDisplay) {
var el = vnode.elm;
// call leave callback now
if (el._leaveCb) {
el._leaveCb.cancelled = true;
el._leaveCb();
}
var data = resolveTransition(vnode.data.transition);
if (!data) {
return
}
/* istanbul ignore if */
if (el._enterCb || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var enterClass = data.enterClass;
var enterToClass = data.enterToClass;
var enterActiveClass = data.enterActiveClass;
var appearClass = data.appearClass;
var appearToClass = data.appearToClass;
var appearActiveClass = data.appearActiveClass;
var beforeEnter = data.beforeEnter;
var enter = data.enter;
var afterEnter = data.afterEnter;
var enterCancelled = data.enterCancelled;
var beforeAppear = data.beforeAppear;
var appear = data.appear;
var afterAppear = data.afterAppear;
var appearCancelled = data.appearCancelled;
// activeInstance will always be the <transition> component managing this
// transition. One edge case to check is when the <transition> is placed
// as the root node of a child component. In that case we need to check
// <transition>'s parent for appear check.
var context = activeInstance;
var transitionNode = activeInstance.$vnode;
while (transitionNode && transitionNode.parent) {
transitionNode = transitionNode.parent;
context = transitionNode.context;
}
var isAppear = !context._isMounted || !vnode.isRootInsert;
if (isAppear && !appear && appear !== '') {
return
}
var startClass = isAppear ? appearClass : enterClass;
var activeClass = isAppear ? appearActiveClass : enterActiveClass;
var toClass = isAppear ? appearToClass : enterToClass;
var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter;
var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter;
var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter;
var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled;
var expectsCSS = css !== false && !isIE9;
var userWantsControl =
enterHook &&
// enterHook may be a bound method which exposes
// the length of original fn as _length
(enterHook._length || enterHook.length) > 1;
var cb = el._enterCb = once(function () {
if (expectsCSS) {
removeTransitionClass(el, toClass);
removeTransitionClass(el, activeClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, startClass);
}
enterCancelledHook && enterCancelledHook(el);
} else {
afterEnterHook && afterEnterHook(el);
}
el._enterCb = null;
});
if (!vnode.data.show) {
// remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () {
var parent = el.parentNode;
var pendingNode = parent && parent._pending && parent._pending[vnode.key];
if (pendingNode &&
pendingNode.tag === vnode.tag &&
pendingNode.elm._leaveCb) {
pendingNode.elm._leaveCb();
}
enterHook && enterHook(el, cb);
}, 'transition-insert');
}
// start enter transition
beforeEnterHook && beforeEnterHook(el);
if (expectsCSS) {
addTransitionClass(el, startClass);
addTransitionClass(el, activeClass);
nextFrame(function () {
addTransitionClass(el, toClass);
removeTransitionClass(el, startClass);
if (!cb.cancelled && !userWantsControl) {
whenTransitionEnds(el, type, cb);
}
});
}
if (vnode.data.show) {
toggleDisplay && toggleDisplay();
enterHook && enterHook(el, cb);
}
if (!expectsCSS && !userWantsControl) {
cb();
}
}
function leave (vnode, rm) {
var el = vnode.elm;
// call enter callback now
if (el._enterCb) {
el._enterCb.cancelled = true;
el._enterCb();
}
var data = resolveTransition(vnode.data.transition);
if (!data) {
return rm()
}
/* istanbul ignore if */
if (el._leaveCb || el.nodeType !== 1) {
return
}
var css = data.css;
var type = data.type;
var leaveClass = data.leaveClass;
var leaveToClass = data.leaveToClass;
var leaveActiveClass = data.leaveActiveClass;
var beforeLeave = data.beforeLeave;
var leave = data.leave;
var afterLeave = data.afterLeave;
var leaveCancelled = data.leaveCancelled;
var delayLeave = data.delayLeave;
var expectsCSS = css !== false && !isIE9;
var userWantsControl =
leave &&
// leave hook may be a bound method which exposes
// the length of original fn as _length
(leave._length || leave.length) > 1;
var cb = el._leaveCb = once(function () {
if (el.parentNode && el.parentNode._pending) {
el.parentNode._pending[vnode.key] = null;
}
if (expectsCSS) {
removeTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveActiveClass);
}
if (cb.cancelled) {
if (expectsCSS) {
removeTransitionClass(el, leaveClass);
}
leaveCancelled && leaveCancelled(el);
} else {
rm();
afterLeave && afterLeave(el);
}
el._leaveCb = null;
});
if (delayLeave) {
delayLeave(performLeave);
} else {
performLeave();
}
function performLeave () {
// the delayed leave may have already been cancelled
if (cb.cancelled) {
return
}
// record leaving element
if (!vnode.data.show) {
(el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode;
}
beforeLeave && beforeLeave(el);
if (expectsCSS) {
addTransitionClass(el, leaveClass);
addTransitionClass(el, leaveActiveClass);
nextFrame(function () {
addTransitionClass(el, leaveToClass);
removeTransitionClass(el, leaveClass);
if (!cb.cancelled && !userWantsControl) {
whenTransitionEnds(el, type, cb);
}
});
}
leave && leave(el, cb);
if (!expectsCSS && !userWantsControl) {
cb();
}
}
}
function resolveTransition (def$$1) {
if (!def$$1) {
return
}
/* istanbul ignore else */
if (typeof def$$1 === 'object') {
var res = {};
if (def$$1.css !== false) {
extend(res, autoCssTransition(def$$1.name || 'v'));
}
extend(res, def$$1);
return res
} else if (typeof def$$1 === 'string') {
return autoCssTransition(def$$1)
}
}
var autoCssTransition = cached(function (name) {
return {
enterClass: (name + "-enter"),
leaveClass: (name + "-leave"),
appearClass: (name + "-enter"),
enterToClass: (name + "-enter-to"),
leaveToClass: (name + "-leave-to"),
appearToClass: (name + "-enter-to"),
enterActiveClass: (name + "-enter-active"),
leaveActiveClass: (name + "-leave-active"),
appearActiveClass: (name + "-enter-active")
}
});
function once (fn) {
var called = false;
return function () {
if (!called) {
called = true;
fn();
}
}
}
function _enter (_, vnode) {
if (!vnode.data.show) {
enter(vnode);
}
}
var transition = inBrowser ? {
create: _enter,
activate: _enter,
remove: function remove (vnode, rm) {
/* istanbul ignore else */
if (!vnode.data.show) {
leave(vnode, rm);
} else {
rm();
}
}
} : {};
var platformModules = [
attrs,
klass,
events,
domProps,
style,
transition
];
/* */
// the directive module should be applied last, after all
// built-in modules have been applied.
var modules = platformModules.concat(baseModules);
var patch$1 = createPatchFunction({ nodeOps: nodeOps, modules: modules });
/**
* Not type checking this file because flow doesn't like attaching
* properties to Elements.
*/
var modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_-]*)?$/;
/* istanbul ignore if */
if (isIE9) {
// http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', function () {
var el = document.activeElement;
if (el && el.vmodel) {
trigger(el, 'input');
}
});
}
var model = {
inserted: function inserted (el, binding, vnode) {
if (process.env.NODE_ENV !== 'production') {
if (!modelableTagRE.test(vnode.tag)) {
warn(
"v-model is not supported on element type: <" + (vnode.tag) + ">. " +
'If you are working with contenteditable, it\'s recommended to ' +
'wrap a library dedicated for that purpose inside a custom component.',
vnode.context
);
}
}
if (vnode.tag === 'select') {
var cb = function () {
setSelected(el, binding, vnode.context);
};
cb();
/* istanbul ignore if */
if (isIE || isEdge) {
setTimeout(cb, 0);
}
} else if (vnode.tag === 'textarea' || el.type === 'text') {
el._vModifiers = binding.modifiers;
if (!binding.modifiers.lazy) {
if (!isAndroid) {
el.addEventListener('compositionstart', onCompositionStart);
el.addEventListener('compositionend', onCompositionEnd);
}
/* istanbul ignore if */
if (isIE9) {
el.vmodel = true;
}
}
}
},
componentUpdated: function componentUpdated (el, binding, vnode) {
if (vnode.tag === 'select') {
setSelected(el, binding, vnode.context);
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
var needReset = el.multiple
? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); })
: binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options);
if (needReset) {
trigger(el, 'change');
}
}
}
};
function setSelected (el, binding, vm) {
var value = binding.value;
var isMultiple = el.multiple;
if (isMultiple && !Array.isArray(value)) {
process.env.NODE_ENV !== 'production' && warn(
"<select multiple v-model=\"" + (binding.expression) + "\"> " +
"expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)),
vm
);
return
}
var selected, option;
for (var i = 0, l = el.options.length; i < l; i++) {
option = el.options[i];
if (isMultiple) {
selected = looseIndexOf(value, getValue(option)) > -1;
if (option.selected !== selected) {
option.selected = selected;
}
} else {
if (looseEqual(getValue(option), value)) {
if (el.selectedIndex !== i) {
el.selectedIndex = i;
}
return
}
}
}
if (!isMultiple) {
el.selectedIndex = -1;
}
}
function hasNoMatchingOption (value, options) {
for (var i = 0, l = options.length; i < l; i++) {
if (looseEqual(getValue(options[i]), value)) {
return false
}
}
return true
}
function getValue (option) {
return '_value' in option
? option._value
: option.value
}
function onCompositionStart (e) {
e.target.composing = true;
}
function onCompositionEnd (e) {
e.target.composing = false;
trigger(e.target, 'input');
}
function trigger (el, type) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, true, true);
el.dispatchEvent(e);
}
/* */
// recursively search for possible transition defined inside the component root
function locateNode (vnode) {
return vnode.componentInstance && (!vnode.data || !vnode.data.transition)
? locateNode(vnode.componentInstance._vnode)
: vnode
}
var show = {
bind: function bind (el, ref, vnode) {
var value = ref.value;
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
var originalDisplay = el.__vOriginalDisplay =
el.style.display === 'none' ? '' : el.style.display;
if (value && transition && !isIE9) {
vnode.data.show = true;
enter(vnode, function () {
el.style.display = originalDisplay;
});
} else {
el.style.display = value ? originalDisplay : 'none';
}
},
update: function update (el, ref, vnode) {
var value = ref.value;
var oldValue = ref.oldValue;
/* istanbul ignore if */
if (value === oldValue) { return }
vnode = locateNode(vnode);
var transition = vnode.data && vnode.data.transition;
if (transition && !isIE9) {
vnode.data.show = true;
if (value) {
enter(vnode, function () {
el.style.display = el.__vOriginalDisplay;
});
} else {
leave(vnode, function () {
el.style.display = 'none';
});
}
} else {
el.style.display = value ? el.__vOriginalDisplay : 'none';
}
},
unbind: function unbind (
el,
binding,
vnode,
oldVnode,
isDestroy
) {
if (!isDestroy) {
el.style.display = el.__vOriginalDisplay;
}
}
};
var platformDirectives = {
model: model,
show: show
};
/* */
// Provides transition support for a single element/component.
// supports transition mode (out-in / in-out)
var transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterToClass: String,
leaveToClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String,
appearToClass: String
};
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recursively retrieve the real component to be rendered
function getRealChild (vnode) {
var compOptions = vnode && vnode.componentOptions;
if (compOptions && compOptions.Ctor.options.abstract) {
return getRealChild(getFirstComponentChild(compOptions.children))
} else {
return vnode
}
}
function extractTransitionData (comp) {
var data = {};
var options = comp.$options;
// props
for (var key in options.propsData) {
data[key] = comp[key];
}
// events.
// extract listeners and pass them directly to the transition methods
var listeners = options._parentListeners;
for (var key$1 in listeners) {
data[camelize(key$1)] = listeners[key$1].fn;
}
return data
}
function placeholder (h, rawChild) {
return /\d-keep-alive$/.test(rawChild.tag)
? h('keep-alive')
: null
}
function hasParentTransition (vnode) {
while ((vnode = vnode.parent)) {
if (vnode.data.transition) {
return true
}
}
}
function isSameChild (child, oldChild) {
return oldChild.key === child.key && oldChild.tag === child.tag
}
var Transition = {
name: 'transition',
props: transitionProps,
abstract: true,
render: function render (h) {
var this$1 = this;
var children = this.$slots.default;
if (!children) {
return
}
// filter out text nodes (possible whitespaces)
children = children.filter(function (c) { return c.tag; });
/* istanbul ignore if */
if (!children.length) {
return
}
// warn multiple elements
if (process.env.NODE_ENV !== 'production' && children.length > 1) {
warn(
'<transition> can only be used on a single element. Use ' +
'<transition-group> for lists.',
this.$parent
);
}
var mode = this.mode;
// warn invalid mode
if (process.env.NODE_ENV !== 'production' &&
mode && mode !== 'in-out' && mode !== 'out-in') {
warn(
'invalid <transition> mode: ' + mode,
this.$parent
);
}
var rawChild = children[0];
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (hasParentTransition(this.$vnode)) {
return rawChild
}
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
var child = getRealChild(rawChild);
/* istanbul ignore if */
if (!child) {
return rawChild
}
if (this._leaving) {
return placeholder(h, rawChild)
}
// ensure a key that is unique to the vnode type and to this transition
// component instance. This key will be used to remove pending leaving nodes
// during entering.
var id = "__transition-" + (this._uid) + "-";
var key = child.key = child.key == null
? id + child.tag
: isPrimitive(child.key)
? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key)
: child.key;
var data = (child.data || (child.data = {})).transition = extractTransitionData(this);
var oldRawChild = this._vnode;
var oldChild = getRealChild(oldRawChild);
// mark v-show
// so that the transition module can hand over the control to the directive
if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) {
child.data.show = true;
}
if (oldChild && oldChild.data && !isSameChild(child, oldChild)) {
// replace old child transition data with fresh one
// important for dynamic transitions!
var oldData = oldChild && (oldChild.data.transition = extend({}, data));
// handle transition mode
if (mode === 'out-in') {
// return placeholder node and queue update when leave finishes
this._leaving = true;
mergeVNodeHook(oldData, 'afterLeave', function () {
this$1._leaving = false;
this$1.$forceUpdate();
}, key);
return placeholder(h, rawChild)
} else if (mode === 'in-out') {
var delayedLeave;
var performLeave = function () { delayedLeave(); };
mergeVNodeHook(data, 'afterEnter', performLeave, key);
mergeVNodeHook(data, 'enterCancelled', performLeave, key);
mergeVNodeHook(oldData, 'delayLeave', function (leave) {
delayedLeave = leave;
}, key);
}
}
return rawChild
}
};
/* */
// Provides transition support for list items.
// supports move transitions using the FLIP technique.
// Because the vdom's children update algorithm is "unstable" - i.e.
// it doesn't guarantee the relative positioning of removed elements,
// we force transition-group to update its children into two passes:
// in the first pass, we remove all nodes that need to be removed,
// triggering their leaving transition; in the second pass, we insert/move
// into the final disired state. This way in the second pass removed
// nodes will remain where they should be.
var props = extend({
tag: String,
moveClass: String
}, transitionProps);
delete props.mode;
var TransitionGroup = {
props: props,
render: function render (h) {
var tag = this.tag || this.$vnode.data.tag || 'span';
var map = Object.create(null);
var prevChildren = this.prevChildren = this.children;
var rawChildren = this.$slots.default || [];
var children = this.children = [];
var transitionData = extractTransitionData(this);
for (var i = 0; i < rawChildren.length; i++) {
var c = rawChildren[i];
if (c.tag) {
if (c.key != null && String(c.key).indexOf('__vlist') !== 0) {
children.push(c);
map[c.key] = c
;(c.data || (c.data = {})).transition = transitionData;
} else if (process.env.NODE_ENV !== 'production') {
var opts = c.componentOptions;
var name = opts
? (opts.Ctor.options.name || opts.tag)
: c.tag;
warn(("<transition-group> children must be keyed: <" + name + ">"));
}
}
}
if (prevChildren) {
var kept = [];
var removed = [];
for (var i$1 = 0; i$1 < prevChildren.length; i$1++) {
var c$1 = prevChildren[i$1];
c$1.data.transition = transitionData;
c$1.data.pos = c$1.elm.getBoundingClientRect();
if (map[c$1.key]) {
kept.push(c$1);
} else {
removed.push(c$1);
}
}
this.kept = h(tag, null, kept);
this.removed = removed;
}
return h(tag, null, children)
},
beforeUpdate: function beforeUpdate () {
// force removing pass
this.__patch__(
this._vnode,
this.kept,
false, // hydrating
true // removeOnly (!important, avoids unnecessary moves)
);
this._vnode = this.kept;
},
updated: function updated () {
var children = this.prevChildren;
var moveClass = this.moveClass || ((this.name || 'v') + '-move');
if (!children.length || !this.hasMove(children[0].elm, moveClass)) {
return
}
// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs);
children.forEach(recordPosition);
children.forEach(applyTranslation);
// force reflow to put everything in position
var f = document.body.offsetHeight; // eslint-disable-line
children.forEach(function (c) {
if (c.data.moved) {
var el = c.elm;
var s = el.style;
addTransitionClass(el, moveClass);
s.transform = s.WebkitTransform = s.transitionDuration = '';
el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) {
if (!e || /transform$/.test(e.propertyName)) {
el.removeEventListener(transitionEndEvent, cb);
el._moveCb = null;
removeTransitionClass(el, moveClass);
}
});
}
});
},
methods: {
hasMove: function hasMove (el, moveClass) {
/* istanbul ignore if */
if (!hasTransition) {
return false
}
if (this._hasMove != null) {
return this._hasMove
}
addTransitionClass(el, moveClass);
var info = getTransitionInfo(el);
removeTransitionClass(el, moveClass);
return (this._hasMove = info.hasTransform)
}
}
};
function callPendingCbs (c) {
/* istanbul ignore if */
if (c.elm._moveCb) {
c.elm._moveCb();
}
/* istanbul ignore if */
if (c.elm._enterCb) {
c.elm._enterCb();
}
}
function recordPosition (c) {
c.data.newPos = c.elm.getBoundingClientRect();
}
function applyTranslation (c) {
var oldPos = c.data.pos;
var newPos = c.data.newPos;
var dx = oldPos.left - newPos.left;
var dy = oldPos.top - newPos.top;
if (dx || dy) {
c.data.moved = true;
var s = c.elm.style;
s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)";
s.transitionDuration = '0s';
}
}
var platformComponents = {
Transition: Transition,
TransitionGroup: TransitionGroup
};
/* */
// install platform specific utils
Vue$3.config.isUnknownElement = isUnknownElement;
Vue$3.config.isReservedTag = isReservedTag;
Vue$3.config.getTagNamespace = getTagNamespace;
Vue$3.config.mustUseProp = mustUseProp;
// install platform runtime directives & components
extend(Vue$3.options.directives, platformDirectives);
extend(Vue$3.options.components, platformComponents);
// install platform patch function
Vue$3.prototype.__patch__ = inBrowser ? patch$1 : noop;
// wrap mount
Vue$3.prototype.$mount = function (
el,
hydrating
) {
el = el && inBrowser ? query(el) : undefined;
return this._mount(el, hydrating)
};
if (process.env.NODE_ENV !== 'production' &&
inBrowser && typeof console !== 'undefined') {
console[console.info ? 'info' : 'log'](
"You are running Vue in development mode.\n" +
"Make sure to turn on production mode when deploying for production.\n" +
"See more tips at https://vuejs.org/guide/deployment.html"
);
}
// devtools global hook
/* istanbul ignore next */
setTimeout(function () {
if (config.devtools) {
if (devtools) {
devtools.emit('init', Vue$3);
} else if (
process.env.NODE_ENV !== 'production' &&
inBrowser && !isEdge && /Chrome\/\d+/.test(window.navigator.userAgent)
) {
console[console.info ? 'info' : 'log'](
'Download the Vue Devtools extension for a better development experience:\n' +
'https://github.com/vuejs/vue-devtools'
);
}
}
}, 0);
/* */
// check whether current browser encodes a char inside attribute values
function shouldDecode (content, encoded) {
var div = document.createElement('div');
div.innerHTML = "<div a=\"" + content + "\">";
return div.innerHTML.indexOf(encoded) > 0
}
// #3663
// IE encodes newlines inside attribute values while other browsers don't
var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', ' ') : false;
/* */
var decoder;
function decode (html) {
decoder = decoder || document.createElement('div');
decoder.innerHTML = html;
return decoder.textContent
}
/* */
var isUnaryTag = makeMap(
'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' +
'link,meta,param,source,track,wbr',
true
);
// Elements that you can, intentionally, leave open
// (and which close themselves)
var canBeLeftOpenTag = makeMap(
'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source',
true
);
// HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3
// Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content
var isNonPhrasingTag = makeMap(
'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' +
'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' +
'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' +
'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' +
'title,tr,track',
true
);
/**
* Not type-checking this file because it's mostly vendor code.
*/
/*!
* HTML Parser By John Resig (ejohn.org)
* Modified by Juriy "kangax" Zaytsev
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*/
// Regular Expressions for parsing tags and attributes
var singleAttrIdentifier = /([^\s"'<>/=]+)/;
var singleAttrAssign = /(?:=)/;
var singleAttrValues = [
// attr value double quotes
/"([^"]*)"+/.source,
// attr value, single quotes
/'([^']*)'+/.source,
// attr value, no quotes
/([^\s"'=<>`]+)/.source
];
var attribute = new RegExp(
'^\\s*' + singleAttrIdentifier.source +
'(?:\\s*(' + singleAttrAssign.source + ')' +
'\\s*(?:' + singleAttrValues.join('|') + '))?'
);
// could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName
// but for Vue templates we can enforce a simple charset
var ncname = '[a-zA-Z_][\\w\\-\\.]*';
var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')';
var startTagOpen = new RegExp('^<' + qnameCapture);
var startTagClose = /^\s*(\/?)>/;
var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>');
var doctype = /^<!DOCTYPE [^>]+>/i;
var comment = /^<!--/;
var conditionalComment = /^<!\[/;
var IS_REGEX_CAPTURING_BROKEN = false;
'x'.replace(/x(.)?/g, function (m, g) {
IS_REGEX_CAPTURING_BROKEN = g === '';
});
// Special Elements (can contain anything)
var isScriptOrStyle = makeMap('script,style', true);
var reCache = {};
var ltRE = /</g;
var gtRE = />/g;
var nlRE = / /g;
var ampRE = /&/g;
var quoteRE = /"/g;
function decodeAttr (value, shouldDecodeNewlines) {
if (shouldDecodeNewlines) {
value = value.replace(nlRE, '\n');
}
return value
.replace(ltRE, '<')
.replace(gtRE, '>')
.replace(ampRE, '&')
.replace(quoteRE, '"')
}
function parseHTML (html, options) {
var stack = [];
var expectHTML = options.expectHTML;
var isUnaryTag$$1 = options.isUnaryTag || no;
var index = 0;
var last, lastTag;
while (html) {
last = html;
// Make sure we're not in a script or style element
if (!lastTag || !isScriptOrStyle(lastTag)) {
var textEnd = html.indexOf('<');
if (textEnd === 0) {
// Comment:
if (comment.test(html)) {
var commentEnd = html.indexOf('-->');
if (commentEnd >= 0) {
advance(commentEnd + 3);
continue
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
var conditionalEnd = html.indexOf(']>');
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2);
continue
}
}
// Doctype:
var doctypeMatch = html.match(doctype);
if (doctypeMatch) {
advance(doctypeMatch[0].length);
continue
}
// End tag:
var endTagMatch = html.match(endTag);
if (endTagMatch) {
var curIndex = index;
advance(endTagMatch[0].length);
parseEndTag(endTagMatch[1], curIndex, index);
continue
}
// Start tag:
var startTagMatch = parseStartTag();
if (startTagMatch) {
handleStartTag(startTagMatch);
continue
}
}
var text = (void 0), rest$1 = (void 0), next = (void 0);
if (textEnd > 0) {
rest$1 = html.slice(textEnd);
while (
!endTag.test(rest$1) &&
!startTagOpen.test(rest$1) &&
!comment.test(rest$1) &&
!conditionalComment.test(rest$1)
) {
// < in plain text, be forgiving and treat it as text
next = rest$1.indexOf('<', 1);
if (next < 0) { break }
textEnd += next;
rest$1 = html.slice(textEnd);
}
text = html.substring(0, textEnd);
advance(textEnd);
}
if (textEnd < 0) {
text = html;
html = '';
}
if (options.chars && text) {
options.chars(text);
}
} else {
var stackedTag = lastTag.toLowerCase();
var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i'));
var endTagLength = 0;
var rest = html.replace(reStackedTag, function (all, text, endTag) {
endTagLength = endTag.length;
if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') {
text = text
.replace(/<!--([\s\S]*?)-->/g, '$1')
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1');
}
if (options.chars) {
options.chars(text);
}
return ''
});
index += html.length - rest.length;
html = rest;
parseEndTag(stackedTag, index - endTagLength, index);
}
if (html === last && options.chars) {
options.chars(html);
break
}
}
// Clean up any remaining tags
parseEndTag();
function advance (n) {
index += n;
html = html.substring(n);
}
function parseStartTag () {
var start = html.match(startTagOpen);
if (start) {
var match = {
tagName: start[1],
attrs: [],
start: index
};
advance(start[0].length);
var end, attr;
while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) {
advance(attr[0].length);
match.attrs.push(attr);
}
if (end) {
match.unarySlash = end[1];
advance(end[0].length);
match.end = index;
return match
}
}
}
function handleStartTag (match) {
var tagName = match.tagName;
var unarySlash = match.unarySlash;
if (expectHTML) {
if (lastTag === 'p' && isNonPhrasingTag(tagName)) {
parseEndTag(lastTag);
}
if (canBeLeftOpenTag(tagName) && lastTag === tagName) {
parseEndTag(tagName);
}
}
var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash;
var l = match.attrs.length;
var attrs = new Array(l);
for (var i = 0; i < l; i++) {
var args = match.attrs[i];
// hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778
if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) {
if (args[3] === '') { delete args[3]; }
if (args[4] === '') { delete args[4]; }
if (args[5] === '') { delete args[5]; }
}
var value = args[3] || args[4] || args[5] || '';
attrs[i] = {
name: args[1],
value: decodeAttr(
value,
options.shouldDecodeNewlines
)
};
}
if (!unary) {
stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs });
lastTag = tagName;
unarySlash = '';
}
if (options.start) {
options.start(tagName, attrs, unary, match.start, match.end);
}
}
function parseEndTag (tagName, start, end) {
var pos, lowerCasedTagName;
if (start == null) { start = index; }
if (end == null) { end = index; }
if (tagName) {
lowerCasedTagName = tagName.toLowerCase();
}
// Find the closest opened tag of the same type
if (tagName) {
for (pos = stack.length - 1; pos >= 0; pos--) {
if (stack[pos].lowerCasedTag === lowerCasedTagName) {
break
}
}
} else {
// If no tag name is provided, clean shop
pos = 0;
}
if (pos >= 0) {
// Close all the open elements, up the stack
for (var i = stack.length - 1; i >= pos; i--) {
if (options.end) {
options.end(stack[i].tag, start, end);
}
}
// Remove the open elements from the stack
stack.length = pos;
lastTag = pos && stack[pos - 1].tag;
} else if (lowerCasedTagName === 'br') {
if (options.start) {
options.start(tagName, [], true, start, end);
}
} else if (lowerCasedTagName === 'p') {
if (options.start) {
options.start(tagName, [], false, start, end);
}
if (options.end) {
options.end(tagName, start, end);
}
}
}
}
/* */
function parseFilters (exp) {
var inSingle = false;
var inDouble = false;
var inTemplateString = false;
var inRegex = false;
var curly = 0;
var square = 0;
var paren = 0;
var lastFilterIndex = 0;
var c, prev, i, expression, filters;
for (i = 0; i < exp.length; i++) {
prev = c;
c = exp.charCodeAt(i);
if (inSingle) {
if (c === 0x27 && prev !== 0x5C) { inSingle = false; }
} else if (inDouble) {
if (c === 0x22 && prev !== 0x5C) { inDouble = false; }
} else if (inTemplateString) {
if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; }
} else if (inRegex) {
if (c === 0x2f && prev !== 0x5C) { inRegex = false; }
} else if (
c === 0x7C && // pipe
exp.charCodeAt(i + 1) !== 0x7C &&
exp.charCodeAt(i - 1) !== 0x7C &&
!curly && !square && !paren
) {
if (expression === undefined) {
// first filter, end of expression
lastFilterIndex = i + 1;
expression = exp.slice(0, i).trim();
} else {
pushFilter();
}
} else {
switch (c) {
case 0x22: inDouble = true; break // "
case 0x27: inSingle = true; break // '
case 0x60: inTemplateString = true; break // `
case 0x28: paren++; break // (
case 0x29: paren--; break // )
case 0x5B: square++; break // [
case 0x5D: square--; break // ]
case 0x7B: curly++; break // {
case 0x7D: curly--; break // }
}
if (c === 0x2f) { // /
var j = i - 1;
var p = (void 0);
// find first non-whitespace prev char
for (; j >= 0; j--) {
p = exp.charAt(j);
if (p !== ' ') { break }
}
if (!p || !/[\w$]/.test(p)) {
inRegex = true;
}
}
}
}
if (expression === undefined) {
expression = exp.slice(0, i).trim();
} else if (lastFilterIndex !== 0) {
pushFilter();
}
function pushFilter () {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim());
lastFilterIndex = i + 1;
}
if (filters) {
for (i = 0; i < filters.length; i++) {
expression = wrapFilter(expression, filters[i]);
}
}
return expression
}
function wrapFilter (exp, filter) {
var i = filter.indexOf('(');
if (i < 0) {
// _f: resolveFilter
return ("_f(\"" + filter + "\")(" + exp + ")")
} else {
var name = filter.slice(0, i);
var args = filter.slice(i + 1);
return ("_f(\"" + name + "\")(" + exp + "," + args)
}
}
/* */
var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g;
var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g;
var buildRegex = cached(function (delimiters) {
var open = delimiters[0].replace(regexEscapeRE, '\\$&');
var close = delimiters[1].replace(regexEscapeRE, '\\$&');
return new RegExp(open + '((?:.|\\n)+?)' + close, 'g')
});
function parseText (
text,
delimiters
) {
var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;
if (!tagRE.test(text)) {
return
}
var tokens = [];
var lastIndex = tagRE.lastIndex = 0;
var match, index;
while ((match = tagRE.exec(text))) {
index = match.index;
// push text token
if (index > lastIndex) {
tokens.push(JSON.stringify(text.slice(lastIndex, index)));
}
// tag token
var exp = parseFilters(match[1].trim());
tokens.push(("_s(" + exp + ")"));
lastIndex = index + match[0].length;
}
if (lastIndex < text.length) {
tokens.push(JSON.stringify(text.slice(lastIndex)));
}
return tokens.join('+')
}
/* */
function baseWarn (msg) {
console.error(("[Vue parser]: " + msg));
}
function pluckModuleFunction (
modules,
key
) {
return modules
? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; })
: []
}
function addProp (el, name, value) {
(el.props || (el.props = [])).push({ name: name, value: value });
}
function addAttr (el, name, value) {
(el.attrs || (el.attrs = [])).push({ name: name, value: value });
}
function addDirective (
el,
name,
rawName,
value,
arg,
modifiers
) {
(el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers });
}
function addHandler (
el,
name,
value,
modifiers,
important
) {
// check capture modifier
if (modifiers && modifiers.capture) {
delete modifiers.capture;
name = '!' + name; // mark the event as captured
}
if (modifiers && modifiers.once) {
delete modifiers.once;
name = '~' + name; // mark the event as once
}
var events;
if (modifiers && modifiers.native) {
delete modifiers.native;
events = el.nativeEvents || (el.nativeEvents = {});
} else {
events = el.events || (el.events = {});
}
var newHandler = { value: value, modifiers: modifiers };
var handlers = events[name];
/* istanbul ignore if */
if (Array.isArray(handlers)) {
important ? handlers.unshift(newHandler) : handlers.push(newHandler);
} else if (handlers) {
events[name] = important ? [newHandler, handlers] : [handlers, newHandler];
} else {
events[name] = newHandler;
}
}
function getBindingAttr (
el,
name,
getStatic
) {
var dynamicValue =
getAndRemoveAttr(el, ':' + name) ||
getAndRemoveAttr(el, 'v-bind:' + name);
if (dynamicValue != null) {
return parseFilters(dynamicValue)
} else if (getStatic !== false) {
var staticValue = getAndRemoveAttr(el, name);
if (staticValue != null) {
return JSON.stringify(staticValue)
}
}
}
function getAndRemoveAttr (el, name) {
var val;
if ((val = el.attrsMap[name]) != null) {
var list = el.attrsList;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i].name === name) {
list.splice(i, 1);
break
}
}
}
return val
}
var len;
var str;
var chr;
var index$1;
var expressionPos;
var expressionEndPos;
/**
* parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val)
*
* for loop possible cases:
*
* - test
* - test[idx]
* - test[test1[idx]]
* - test["a"][idx]
* - xxx.test[a[a].test1[idx]]
* - test.xxx.a["asa"][test1[idx]]
*
*/
function parseModel (val) {
str = val;
len = str.length;
index$1 = expressionPos = expressionEndPos = 0;
if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) {
return {
exp: val,
idx: null
}
}
while (!eof()) {
chr = next();
/* istanbul ignore if */
if (isStringStart(chr)) {
parseString(chr);
} else if (chr === 0x5B) {
parseBracket(chr);
}
}
return {
exp: val.substring(0, expressionPos),
idx: val.substring(expressionPos + 1, expressionEndPos)
}
}
function next () {
return str.charCodeAt(++index$1)
}
function eof () {
return index$1 >= len
}
function isStringStart (chr) {
return chr === 0x22 || chr === 0x27
}
function parseBracket (chr) {
var inBracket = 1;
expressionPos = index$1;
while (!eof()) {
chr = next();
if (isStringStart(chr)) {
parseString(chr);
continue
}
if (chr === 0x5B) { inBracket++; }
if (chr === 0x5D) { inBracket--; }
if (inBracket === 0) {
expressionEndPos = index$1;
break
}
}
}
function parseString (chr) {
var stringQuote = chr;
while (!eof()) {
chr = next();
if (chr === stringQuote) {
break
}
}
}
/* */
var dirRE = /^v-|^@|^:/;
var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/;
var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/;
var bindRE = /^:|^v-bind:/;
var onRE = /^@|^v-on:/;
var argRE = /:(.*)$/;
var modifierRE = /\.[^.]+/g;
var decodeHTMLCached = cached(decode);
// configurable state
var warn$1;
var platformGetTagNamespace;
var platformMustUseProp;
var platformIsPreTag;
var preTransforms;
var transforms;
var postTransforms;
var delimiters;
/**
* Convert HTML string to AST.
*/
function parse (
template,
options
) {
warn$1 = 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;
var stack = [];
var preserveWhitespace = options.preserveWhitespace !== false;
var root;
var currentParent;
var inVPre = false;
var inPre = false;
var warned = false;
parseHTML(template, {
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
start: function start (tag, attrs, unary) {
// check namespace.
// inherit parent ns if there is one
var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag);
// handle IE svg bug
/* istanbul ignore if */
if (isIE && ns === 'svg') {
attrs = guardIESVGBug(attrs);
}
var element = {
type: 1,
tag: 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$1(
'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 (var 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 (var i$1 = 0; i$1 < transforms.length; i$1++) {
transforms[i$1](element, options);
}
processAttrs(element);
}
function checkRootConstraints (el) {
if (process.env.NODE_ENV !== 'production' && !warned) {
if (el.tag === 'slot' || el.tag === 'template') {
warned = true;
warn$1(
"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$1(
'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$1(
"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;
var 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 (var i$2 = 0; i$2 < postTransforms.length; i$2++) {
postTransforms[i$2](element, options);
}
},
end: function end () {
// remove trailing whitespace
var element = stack[stack.length - 1];
var 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: function chars (text) {
if (!currentParent) {
if (process.env.NODE_ENV !== 'production' && !warned && text === template) {
warned = true;
warn$1(
'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
}
var 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) {
var expression;
if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) {
children.push({
type: 2,
expression: expression,
text: text
});
} else if (text !== ' ' || children[children.length - 1].text !== ' ') {
currentParent.children.push({
type: 3,
text: text
});
}
}
}
});
return root
}
function processPre (el) {
if (getAndRemoveAttr(el, 'v-pre') != null) {
el.pre = true;
}
}
function processRawAttrs (el) {
var l = el.attrsList.length;
if (l) {
var attrs = el.attrs = new Array(l);
for (var 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) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if (process.env.NODE_ENV !== 'production' && el.tag === 'template') {
warn$1("<template> cannot be keyed. Place the key on real elements instead.");
}
el.key = exp;
}
}
function processRef (el) {
var ref = getBindingAttr(el, 'ref');
if (ref) {
el.ref = ref;
el.refInFor = checkInFor(el);
}
}
function processFor (el) {
var exp;
if ((exp = getAndRemoveAttr(el, 'v-for'))) {
var inMatch = exp.match(forAliasRE);
if (!inMatch) {
process.env.NODE_ENV !== 'production' && warn$1(
("Invalid v-for expression: " + exp)
);
return
}
el.for = inMatch[2].trim();
var alias = inMatch[1].trim();
var 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) {
var 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;
}
var elseif = getAndRemoveAttr(el, 'v-else-if');
if (elseif) {
el.elseif = elseif;
}
}
}
function processIfConditions (el, parent) {
var prev = findPrevElement(parent.children);
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
});
} else if (process.env.NODE_ENV !== 'production') {
warn$1(
"v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " +
"used on element <" + (el.tag) + "> without corresponding v-if."
);
}
}
function findPrevElement (children) {
var i = children.length;
while (i--) {
if (children[i].type === 1) {
return children[i]
} else {
if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') {
warn$1(
"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) {
var 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$1(
"`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 {
var slotTarget = getBindingAttr(el, 'slot');
if (slotTarget) {
el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget;
}
if (el.tag === 'template') {
el.slotScope = getAndRemoveAttr(el, 'scope');
}
}
}
function processComponent (el) {
var binding;
if ((binding = getBindingAttr(el, 'is'))) {
el.component = binding;
}
if (getAndRemoveAttr(el, 'inline-template') != null) {
el.inlineTemplate = true;
}
}
function processAttrs (el) {
var list = el.attrsList;
var 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, el.attrsMap.type, 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
var 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') {
var expression = parseText(value, delimiters);
if (expression) {
warn$1(
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));
}
}
}
function checkInFor (el) {
var parent = el;
while (parent) {
if (parent.for !== undefined) {
return true
}
parent = parent.parent;
}
return false
}
function parseModifiers (name) {
var match = name.match(modifierRE);
if (match) {
var ret = {};
match.forEach(function (m) { ret[m.slice(1)] = true; });
return ret
}
}
function makeAttrsMap (attrs) {
var map = {};
for (var i = 0, l = attrs.length; i < l; i++) {
if (process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE) {
warn$1('duplicate attribute: ' + attrs[i].name);
}
map[attrs[i].name] = attrs[i].value;
}
return map
}
function isForbiddenTag (el) {
return (
el.tag === 'style' ||
(el.tag === 'script' && (
!el.attrsMap.type ||
el.attrsMap.type === 'text/javascript'
))
)
}
var ieNSBug = /^xmlns:NS\d+/;
var ieNSPrefix = /^NS\d+:/;
/* istanbul ignore next */
function guardIESVGBug (attrs) {
var res = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
if (!ieNSBug.test(attr.name)) {
attr.name = attr.name.replace(ieNSPrefix, '');
res.push(attr);
}
}
return res
}
function checkForAliasModel (el, value) {
var _el = el;
while (_el) {
if (_el.for && _el.alias === value) {
warn$1(
"<" + (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;
}
}
/* */
var isStaticKey;
var isPlatformReservedTag;
var genStaticKeysCached = cached(genStaticKeys$1);
/**
* Goal of the optimizer: walk the generated template AST tree
* and detect sub-trees that are purely static, i.e. parts of
* the DOM that never needs to change.
*
* Once we detect these sub-trees, we can:
*
* 1. Hoist them into constants, so that we no longer need to
* create fresh nodes for them on each re-render;
* 2. Completely skip them in the patching process.
*/
function optimize (root, options) {
if (!root) { return }
isStaticKey = genStaticKeysCached(options.staticKeys || '');
isPlatformReservedTag = options.isReservedTag || no;
// first pass: mark all non-static nodes.
markStatic(root);
// second pass: mark static roots.
markStaticRoots(root, false);
}
function genStaticKeys$1 (keys) {
return makeMap(
'type,tag,attrsList,attrsMap,plain,parent,children,attrs' +
(keys ? ',' + keys : '')
)
}
function markStatic (node) {
node.static = isStatic(node);
if (node.type === 1) {
// do not make component slot content static. this avoids
// 1. components not able to mutate slot nodes
// 2. static slot content fails for hot-reloading
if (
!isPlatformReservedTag(node.tag) &&
node.tag !== 'slot' &&
node.attrsMap['inline-template'] == null
) {
return
}
for (var i = 0, l = node.children.length; i < l; i++) {
var child = node.children[i];
markStatic(child);
if (!child.static) {
node.static = false;
}
}
}
}
function markStaticRoots (node, isInFor) {
if (node.type === 1) {
if (node.static || node.once) {
node.staticInFor = isInFor;
}
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if (node.static && node.children.length && !(
node.children.length === 1 &&
node.children[0].type === 3
)) {
node.staticRoot = true;
return
} else {
node.staticRoot = false;
}
if (node.children) {
for (var i = 0, l = node.children.length; i < l; i++) {
markStaticRoots(node.children[i], isInFor || !!node.for);
}
}
if (node.ifConditions) {
walkThroughConditionsBlocks(node.ifConditions, isInFor);
}
}
}
function walkThroughConditionsBlocks (conditionBlocks, isInFor) {
for (var i = 1, len = conditionBlocks.length; i < len; i++) {
markStaticRoots(conditionBlocks[i].block, isInFor);
}
}
function isStatic (node) {
if (node.type === 2) { // expression
return false
}
if (node.type === 3) { // text
return true
}
return !!(node.pre || (
!node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!isDirectChildOfTemplateFor(node) &&
Object.keys(node).every(isStaticKey)
))
}
function isDirectChildOfTemplateFor (node) {
while (node.parent) {
node = node.parent;
if (node.tag !== 'template') {
return false
}
if (node.for) {
return true
}
}
return false
}
/* */
var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/;
var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/;
// keyCode aliases
var keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
'delete': [8, 46]
};
var modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: 'if($event.target !== $event.currentTarget)return;',
ctrl: 'if(!$event.ctrlKey)return;',
shift: 'if(!$event.shiftKey)return;',
alt: 'if(!$event.altKey)return;',
meta: 'if(!$event.metaKey)return;'
};
function genHandlers (events, native) {
var res = native ? 'nativeOn:{' : 'on:{';
for (var name in events) {
res += "\"" + name + "\":" + (genHandler(name, events[name])) + ",";
}
return res.slice(0, -1) + '}'
}
function genHandler (
name,
handler
) {
if (!handler) {
return 'function(){}'
} else if (Array.isArray(handler)) {
return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]")
} else if (!handler.modifiers) {
return fnExpRE.test(handler.value) || simplePathRE.test(handler.value)
? handler.value
: ("function($event){" + (handler.value) + "}")
} else {
var code = '';
var keys = [];
for (var key in handler.modifiers) {
if (modifierCode[key]) {
code += modifierCode[key];
} else {
keys.push(key);
}
}
if (keys.length) {
code = genKeyFilter(keys) + code;
}
var handlerCode = simplePathRE.test(handler.value)
? handler.value + '($event)'
: handler.value;
return 'function($event){' + code + handlerCode + '}'
}
}
function genKeyFilter (keys) {
return ("if(" + (keys.map(genFilterCode).join('&&')) + ")return;")
}
function genFilterCode (key) {
var keyVal = parseInt(key, 10);
if (keyVal) {
return ("$event.keyCode!==" + keyVal)
}
var alias = keyCodes[key];
return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")")
}
/* */
function bind$2 (el, dir) {
el.wrapData = function (code) {
return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")")
};
}
/* */
var baseDirectives = {
bind: bind$2,
cloak: noop
};
/* */
// configurable state
var warn$2;
var transforms$1;
var dataGenFns;
var platformDirectives$1;
var isPlatformReservedTag$1;
var staticRenderFns;
var onceCount;
var currentOptions;
function generate (
ast,
options
) {
// save previous staticRenderFns so generate calls can be nested
var prevStaticRenderFns = staticRenderFns;
var currentStaticRenderFns = staticRenderFns = [];
var prevOnceCount = onceCount;
onceCount = 0;
currentOptions = options;
warn$2 = options.warn || baseWarn;
transforms$1 = pluckModuleFunction(options.modules, 'transformCode');
dataGenFns = pluckModuleFunction(options.modules, 'genData');
platformDirectives$1 = options.directives || {};
isPlatformReservedTag$1 = options.isReservedTag || no;
var code = ast ? genElement(ast) : '_c("div")';
staticRenderFns = prevStaticRenderFns;
onceCount = prevOnceCount;
return {
render: ("with(this){return " + code + "}"),
staticRenderFns: currentStaticRenderFns
}
}
function genElement (el) {
if (el.staticRoot && !el.staticProcessed) {
return genStatic(el)
} else if (el.once && !el.onceProcessed) {
return genOnce(el)
} else if (el.for && !el.forProcessed) {
return genFor(el)
} else if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.tag === 'template' && !el.slotTarget) {
return genChildren(el) || 'void 0'
} else if (el.tag === 'slot') {
return genSlot(el)
} else {
// component or element
var code;
if (el.component) {
code = genComponent(el.component, el);
} else {
var data = el.plain ? undefined : genData(el);
var children = el.inlineTemplate ? null : genChildren(el, true);
code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")";
}
// module transforms
for (var i = 0; i < transforms$1.length; i++) {
code = transforms$1[i](el, code);
}
return code
}
}
// hoist static sub-trees out
function genStatic (el) {
el.staticProcessed = true;
staticRenderFns.push(("with(this){return " + (genElement(el)) + "}"));
return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")")
}
// v-once
function genOnce (el) {
el.onceProcessed = true;
if (el.if && !el.ifProcessed) {
return genIf(el)
} else if (el.staticInFor) {
var key = '';
var parent = el.parent;
while (parent) {
if (parent.for) {
key = parent.key;
break
}
parent = parent.parent;
}
if (!key) {
process.env.NODE_ENV !== 'production' && warn$2(
"v-once can only be used inside v-for that is keyed. "
);
return genElement(el)
}
return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")")
} else {
return genStatic(el)
}
}
function genIf (el) {
el.ifProcessed = true; // avoid recursion
return genIfConditions(el.ifConditions.slice())
}
function genIfConditions (conditions) {
if (!conditions.length) {
return '_e()'
}
var condition = conditions.shift();
if (condition.exp) {
return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions)))
} else {
return ("" + (genTernaryExp(condition.block)))
}
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp (el) {
return el.once ? genOnce(el) : genElement(el)
}
}
function genFor (el) {
var exp = el.for;
var alias = el.alias;
var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : '';
var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : '';
el.forProcessed = true; // avoid recursion
return "_l((" + exp + ")," +
"function(" + alias + iterator1 + iterator2 + "){" +
"return " + (genElement(el)) +
'})'
}
function genData (el) {
var data = '{';
// directives first.
// directives may mutate the el's other properties before they are generated.
var dirs = genDirectives(el);
if (dirs) { data += dirs + ','; }
// key
if (el.key) {
data += "key:" + (el.key) + ",";
}
// ref
if (el.ref) {
data += "ref:" + (el.ref) + ",";
}
if (el.refInFor) {
data += "refInFor:true,";
}
// pre
if (el.pre) {
data += "pre:true,";
}
// record original tag name for components using "is" attribute
if (el.component) {
data += "tag:\"" + (el.tag) + "\",";
}
// module data generation functions
for (var i = 0; i < dataGenFns.length; i++) {
data += dataGenFns[i](el);
}
// attributes
if (el.attrs) {
data += "attrs:{" + (genProps(el.attrs)) + "},";
}
// DOM props
if (el.props) {
data += "domProps:{" + (genProps(el.props)) + "},";
}
// event handlers
if (el.events) {
data += (genHandlers(el.events)) + ",";
}
if (el.nativeEvents) {
data += (genHandlers(el.nativeEvents, true)) + ",";
}
// slot target
if (el.slotTarget) {
data += "slot:" + (el.slotTarget) + ",";
}
// scoped slots
if (el.scopedSlots) {
data += (genScopedSlots(el.scopedSlots)) + ",";
}
// inline-template
if (el.inlineTemplate) {
var inlineTemplate = genInlineTemplate(el);
if (inlineTemplate) {
data += inlineTemplate + ",";
}
}
data = data.replace(/,$/, '') + '}';
// v-bind data wrap
if (el.wrapData) {
data = el.wrapData(data);
}
return data
}
function genDirectives (el) {
var dirs = el.directives;
if (!dirs) { return }
var res = 'directives:[';
var hasRuntime = false;
var i, l, dir, needRuntime;
for (i = 0, l = dirs.length; i < l; i++) {
dir = dirs[i];
needRuntime = true;
var gen = platformDirectives$1[dir.name] || baseDirectives[dir.name];
if (gen) {
// compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
needRuntime = !!gen(el, dir, warn$2);
}
if (needRuntime) {
hasRuntime = true;
res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},";
}
}
if (hasRuntime) {
return res.slice(0, -1) + ']'
}
}
function genInlineTemplate (el) {
var ast = el.children[0];
if (process.env.NODE_ENV !== 'production' && (
el.children.length > 1 || ast.type !== 1
)) {
warn$2('Inline-template components must have exactly one child element.');
}
if (ast.type === 1) {
var inlineRenderFns = generate(ast, currentOptions);
return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}")
}
}
function genScopedSlots (slots) {
return ("scopedSlots:{" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "}")
}
function genScopedSlot (key, el) {
return key + ":function(" + (String(el.attrsMap.scope)) + "){" +
"return " + (el.tag === 'template'
? genChildren(el) || 'void 0'
: genElement(el)) + "}"
}
function genChildren (el, checkSkip) {
var children = el.children;
if (children.length) {
var el$1 = children[0];
// optimize single v-for
if (children.length === 1 &&
el$1.for &&
el$1.tag !== 'template' &&
el$1.tag !== 'slot') {
return genElement(el$1)
}
var normalizationType = getNormalizationType(children);
return ("[" + (children.map(genNode).join(',')) + "]" + (checkSkip
? normalizationType ? ("," + normalizationType) : ''
: ''))
}
}
// determine the normalization needed for the children array.
// 0: no normalization needed
// 1: simple normalization needed (possible 1-level deep nested array)
// 2: full normalization needed
function getNormalizationType (children) {
var res = 0;
for (var i = 0; i < children.length; i++) {
var el = children[i];
if (el.type !== 1) {
continue
}
if (needsNormalization(el) ||
(el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) {
res = 2;
break
}
if (maybeComponent(el) ||
(el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) {
res = 1;
}
}
return res
}
function needsNormalization (el) {
return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
}
function maybeComponent (el) {
return !isPlatformReservedTag$1(el.tag)
}
function genNode (node) {
if (node.type === 1) {
return genElement(node)
} else {
return genText(node)
}
}
function genText (text) {
return ("_v(" + (text.type === 2
? text.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(text.text))) + ")")
}
function genSlot (el) {
var slotName = el.slotName || '"default"';
var children = genChildren(el);
var res = "_t(" + slotName + (children ? ("," + children) : '');
var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}");
var bind$$1 = el.attrsMap['v-bind'];
if ((attrs || bind$$1) && !children) {
res += ",null";
}
if (attrs) {
res += "," + attrs;
}
if (bind$$1) {
res += (attrs ? '' : ',null') + "," + bind$$1;
}
return res + ')'
}
// componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (componentName, el) {
var children = el.inlineTemplate ? null : genChildren(el, true);
return ("_c(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")")
}
function genProps (props) {
var res = '';
for (var i = 0; i < props.length; i++) {
var prop = props[i];
res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ",";
}
return res.slice(0, -1)
}
// #3895, #4268
function transformSpecialNewlines (text) {
return text
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
}
/* */
/**
* Compile a template.
*/
function compile$1 (
template,
options
) {
var ast = parse(template.trim(), options);
optimize(ast, options);
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
}
}
/* */
// operators like typeof, instanceof and in are allowed
var prohibitedKeywordRE = new RegExp('\\b' + (
'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
'super,throw,while,yield,delete,export,import,return,switch,default,' +
'extends,finally,continue,debugger,function,arguments'
).split(',').join('\\b|\\b') + '\\b');
// check valid identifier for v-for
var identRE = /[A-Za-z_$][\w$]*/;
// strip strings in expressions
var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
// detect problematic expressions in a template
function detectErrors (ast) {
var errors = [];
if (ast) {
checkNode(ast, errors);
}
return errors
}
function checkNode (node, errors) {
if (node.type === 1) {
for (var name in node.attrsMap) {
if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
if (name === 'v-for') {
checkFor(node, ("v-for=\"" + value + "\""), errors);
} else {
checkExpression(value, (name + "=\"" + value + "\""), errors);
}
}
}
}
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
checkNode(node.children[i], errors);
}
}
} else if (node.type === 2) {
checkExpression(node.expression, node.text, errors);
}
}
function checkFor (node, text, errors) {
checkExpression(node.for || '', text, errors);
checkIdentifier(node.alias, 'v-for alias', text, errors);
checkIdentifier(node.iterator1, 'v-for iterator', text, errors);
checkIdentifier(node.iterator2, 'v-for iterator', text, errors);
}
function checkIdentifier (ident, type, text, errors) {
if (typeof ident === 'string' && !identRE.test(ident)) {
errors.push(("- invalid " + type + " \"" + ident + "\" in expression: " + text));
}
}
function checkExpression (exp, text, errors) {
try {
new Function(("return " + exp));
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
if (keywordMatch) {
errors.push(
"- avoid using JavaScript keyword as property name: " +
"\"" + (keywordMatch[0]) + "\" in expression " + text
);
} else {
errors.push(("- invalid expression: " + text));
}
}
}
/* */
function transformNode (el, options) {
var warn = options.warn || baseWarn;
var staticClass = getAndRemoveAttr(el, 'class');
if (process.env.NODE_ENV !== 'production' && staticClass) {
var expression = parseText(staticClass, options.delimiters);
if (expression) {
warn(
"class=\"" + staticClass + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div class="{{ val }}">, use <div :class="val">.'
);
}
}
if (staticClass) {
el.staticClass = JSON.stringify(staticClass);
}
var classBinding = getBindingAttr(el, 'class', false /* getStatic */);
if (classBinding) {
el.classBinding = classBinding;
}
}
function genData$1 (el) {
var data = '';
if (el.staticClass) {
data += "staticClass:" + (el.staticClass) + ",";
}
if (el.classBinding) {
data += "class:" + (el.classBinding) + ",";
}
return data
}
var klass$1 = {
staticKeys: ['staticClass'],
transformNode: transformNode,
genData: genData$1
};
/* */
function transformNode$1 (el, options) {
var warn = options.warn || baseWarn;
var staticStyle = getAndRemoveAttr(el, 'style');
if (staticStyle) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
var expression = parseText(staticStyle, options.delimiters);
if (expression) {
warn(
"style=\"" + staticStyle + "\": " +
'Interpolation inside attributes has been removed. ' +
'Use v-bind or the colon shorthand instead. For example, ' +
'instead of <div style="{{ val }}">, use <div :style="val">.'
);
}
}
el.staticStyle = JSON.stringify(parseStyleText(staticStyle));
}
var styleBinding = getBindingAttr(el, 'style', false /* getStatic */);
if (styleBinding) {
el.styleBinding = styleBinding;
}
}
function genData$2 (el) {
var data = '';
if (el.staticStyle) {
data += "staticStyle:" + (el.staticStyle) + ",";
}
if (el.styleBinding) {
data += "style:(" + (el.styleBinding) + "),";
}
return data
}
var style$1 = {
staticKeys: ['staticStyle'],
transformNode: transformNode$1,
genData: genData$2
};
var modules$1 = [
klass$1,
style$1
];
/* */
var warn$3;
function model$1 (
el,
dir,
_warn
) {
warn$3 = _warn;
var value = dir.value;
var modifiers = dir.modifiers;
var tag = el.tag;
var type = el.attrsMap.type;
if (process.env.NODE_ENV !== 'production') {
var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (tag === 'input' && dynamicType) {
warn$3(
"<input :type=\"" + dynamicType + "\" v-model=\"" + value + "\">:\n" +
"v-model does not support dynamic input types. Use v-if branches instead."
);
}
}
if (tag === 'select') {
genSelect(el, value, modifiers);
} else if (tag === 'input' && type === 'checkbox') {
genCheckboxModel(el, value, modifiers);
} else if (tag === 'input' && type === 'radio') {
genRadioModel(el, value, modifiers);
} else {
genDefaultModel(el, value, modifiers);
}
// ensure runtime directive metadata
return true
}
function genCheckboxModel (
el,
value,
modifiers
) {
if (process.env.NODE_ENV !== 'production' &&
el.attrsMap.checked != null) {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" +
"inline checked attributes will be ignored when using v-model. " +
'Declare initial values in the component\'s data option instead.'
);
}
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
var trueValueBinding = getBindingAttr(el, 'true-value') || 'true';
var falseValueBinding = getBindingAttr(el, 'false-value') || 'false';
addProp(el, 'checked',
"Array.isArray(" + value + ")" +
"?_i(" + value + "," + valueBinding + ")>-1" + (
trueValueBinding === 'true'
? (":(" + value + ")")
: (":_q(" + value + "," + trueValueBinding + ")")
)
);
addHandler(el, 'click',
"var $$a=" + value + "," +
'$$el=$event.target,' +
"$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" +
'if(Array.isArray($$a)){' +
"var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," +
'$$i=_i($$a,$$v);' +
"if($$c){$$i<0&&(" + value + "=$$a.concat($$v))}" +
"else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" +
"}else{" + value + "=$$c}",
null, true
);
}
function genRadioModel (
el,
value,
modifiers
) {
if (process.env.NODE_ENV !== 'production' &&
el.attrsMap.checked != null) {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" +
"inline checked attributes will be ignored when using v-model. " +
'Declare initial values in the component\'s data option instead.'
);
}
var number = modifiers && modifiers.number;
var valueBinding = getBindingAttr(el, 'value') || 'null';
valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding;
addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")"));
addHandler(el, 'click', genAssignmentCode(value, valueBinding), null, true);
}
function genDefaultModel (
el,
value,
modifiers
) {
if (process.env.NODE_ENV !== 'production') {
if (el.tag === 'input' && el.attrsMap.value) {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" value=\"" + (el.attrsMap.value) + "\">:\n" +
'inline value attributes will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
);
}
if (el.tag === 'textarea' && el.children.length) {
warn$3(
"<textarea v-model=\"" + value + "\">:\n" +
'inline content inside <textarea> will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
);
}
}
var type = el.attrsMap.type;
var ref = modifiers || {};
var lazy = ref.lazy;
var number = ref.number;
var trim = ref.trim;
var event = lazy || (isIE && type === 'range') ? 'change' : 'input';
var needCompositionGuard = !lazy && type !== 'range';
var isNative = el.tag === 'input' || el.tag === 'textarea';
var valueExpression = isNative
? ("$event.target.value" + (trim ? '.trim()' : ''))
: trim ? "(typeof $event === 'string' ? $event.trim() : $event)" : "$event";
valueExpression = number || type === 'number'
? ("_n(" + valueExpression + ")")
: valueExpression;
var code = genAssignmentCode(value, valueExpression);
if (isNative && needCompositionGuard) {
code = "if($event.target.composing)return;" + code;
}
// inputs with type="file" are read only and setting the input's
// value will throw an error.
if (process.env.NODE_ENV !== 'production' &&
type === 'file') {
warn$3(
"<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" +
"File inputs are read only. Use a v-on:change listener instead."
);
}
addProp(el, 'value', isNative ? ("_s(" + value + ")") : ("(" + value + ")"));
addHandler(el, event, code, null, true);
if (trim || number || type === 'number') {
addHandler(el, 'blur', '$forceUpdate()');
}
}
function genSelect (
el,
value,
modifiers
) {
if (process.env.NODE_ENV !== 'production') {
el.children.some(checkOptionWarning);
}
var number = modifiers && modifiers.number;
var assignment = "Array.prototype.filter" +
".call($event.target.options,function(o){return o.selected})" +
".map(function(o){var val = \"_value\" in o ? o._value : o.value;" +
"return " + (number ? '_n(val)' : 'val') + "})" +
(el.attrsMap.multiple == null ? '[0]' : '');
var code = genAssignmentCode(value, assignment);
addHandler(el, 'change', code, null, true);
}
function checkOptionWarning (option) {
if (option.type === 1 &&
option.tag === 'option' &&
option.attrsMap.selected != null) {
warn$3(
"<select v-model=\"" + (option.parent.attrsMap['v-model']) + "\">:\n" +
'inline selected attributes on <option> will be ignored when using v-model. ' +
'Declare initial values in the component\'s data option instead.'
);
return true
}
return false
}
function genAssignmentCode (value, assignment) {
var modelRs = parseModel(value);
if (modelRs.idx === null) {
return (value + "=" + assignment)
} else {
return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" +
"if (!Array.isArray($$exp)){" +
value + "=" + assignment + "}" +
"else{$$exp.splice($$idx, 1, " + assignment + ")}"
}
}
/* */
function text (el, dir) {
if (dir.value) {
addProp(el, 'textContent', ("_s(" + (dir.value) + ")"));
}
}
/* */
function html (el, dir) {
if (dir.value) {
addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")"));
}
}
var directives$1 = {
model: model$1,
text: text,
html: html
};
/* */
var cache = Object.create(null);
var baseOptions = {
expectHTML: true,
modules: modules$1,
staticKeys: genStaticKeys(modules$1),
directives: directives$1,
isReservedTag: isReservedTag,
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
getTagNamespace: getTagNamespace,
isPreTag: isPreTag
};
function compile$$1 (
template,
options
) {
options = options
? extend(extend({}, baseOptions), options)
: baseOptions;
return compile$1(template, options)
}
function compileToFunctions (
template,
options,
vm
) {
var _warn = (options && options.warn) || warn;
// detect possible CSP restriction
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production') {
try {
new Function('return 1');
} catch (e) {
if (e.toString().match(/unsafe-eval|CSP/)) {
_warn(
'It seems you are using the standalone build of Vue.js in an ' +
'environment with Content Security Policy that prohibits unsafe-eval. ' +
'The template compiler cannot work in this environment. Consider ' +
'relaxing the policy to allow unsafe-eval or pre-compiling your ' +
'templates into render functions.'
);
}
}
}
var key = options && options.delimiters
? String(options.delimiters) + template
: template;
if (cache[key]) {
return cache[key]
}
var res = {};
var compiled = compile$$1(template, options);
res.render = makeFunction(compiled.render);
var l = compiled.staticRenderFns.length;
res.staticRenderFns = new Array(l);
for (var i = 0; i < l; i++) {
res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i]);
}
if (process.env.NODE_ENV !== 'production') {
if (res.render === noop || res.staticRenderFns.some(function (fn) { return fn === noop; })) {
_warn(
"failed to compile template:\n\n" + template + "\n\n" +
detectErrors(compiled.ast).join('\n') +
'\n\n',
vm
);
}
}
return (cache[key] = res)
}
function makeFunction (code) {
try {
return new Function(code)
} catch (e) {
return noop
}
}
/* */
var idToTemplate = cached(function (id) {
var el = query(id);
return el && el.innerHTML
});
var mount = Vue$3.prototype.$mount;
Vue$3.prototype.$mount = function (
el,
hydrating
) {
el = el && query(el);
/* istanbul ignore if */
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
"Do not mount Vue to <html> or <body> - mount to normal elements instead."
);
return this
}
var options = this.$options;
// resolve template/el and convert to render function
if (!options.render) {
var template = options.template;
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template);
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
("Template element not found or is empty: " + (options.template)),
this
);
}
}
} else if (template.nodeType) {
template = template.innerHTML;
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this);
}
return this
}
} else if (el) {
template = getOuterHTML(el);
}
if (template) {
var ref = compileToFunctions(template, {
warn: warn,
shouldDecodeNewlines: shouldDecodeNewlines,
delimiters: options.delimiters
}, this);
var render = ref.render;
var staticRenderFns = ref.staticRenderFns;
options.render = render;
options.staticRenderFns = staticRenderFns;
}
}
return mount.call(this, el, hydrating)
};
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el) {
if (el.outerHTML) {
return el.outerHTML
} else {
var container = document.createElement('div');
container.appendChild(el.cloneNode(true));
return container.innerHTML
}
}
Vue$3.compile = compileToFunctions;
module.exports = Vue$3;
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":1}],3:[function(require,module,exports){
/**
* vuex v2.1.2
* (c) 2017 Evan You
* @license MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Vuex = factory());
}(this, (function () { 'use strict';
var devtoolHook =
typeof window !== 'undefined' &&
window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
function devtoolPlugin (store) {
if (!devtoolHook) { return }
store._devtoolHook = devtoolHook;
devtoolHook.emit('vuex:init', store);
devtoolHook.on('vuex:travel-to-state', function (targetState) {
store.replaceState(targetState);
});
store.subscribe(function (mutation, state) {
devtoolHook.emit('vuex:mutation', mutation, state);
});
}
var applyMixin = function (Vue) {
var version = Number(Vue.version.split('.')[0]);
if (version >= 2) {
var usesInit = Vue.config._lifecycleHooks.indexOf('init') > -1;
Vue.mixin(usesInit ? { init: vuexInit } : { beforeCreate: vuexInit });
} else {
// override init and inject vuex init procedure
// for 1.x backwards compatibility.
var _init = Vue.prototype._init;
Vue.prototype._init = function (options) {
if ( options === void 0 ) options = {};
options.init = options.init
? [vuexInit].concat(options.init)
: vuexInit;
_init.call(this, options);
};
}
/**
* Vuex init hook, injected into each instances init hooks list.
*/
function vuexInit () {
var options = this.$options;
// store injection
if (options.store) {
this.$store = options.store;
} else if (options.parent && options.parent.$store) {
this.$store = options.parent.$store;
}
}
};
var mapState = normalizeNamespace(function (namespace, states) {
var res = {};
normalizeMap(states).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
res[key] = function mappedState () {
var state = this.$store.state;
var getters = this.$store.getters;
if (namespace) {
var module = getModuleByNamespace(this.$store, 'mapState', namespace);
if (!module) {
return
}
state = module.context.state;
getters = module.context.getters;
}
return typeof val === 'function'
? val.call(this, state, getters)
: state[val]
};
});
return res
});
var mapMutations = normalizeNamespace(function (namespace, mutations) {
var res = {};
normalizeMap(mutations).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
val = namespace + val;
res[key] = function mappedMutation () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (namespace && !getModuleByNamespace(this.$store, 'mapMutations', namespace)) {
return
}
return this.$store.commit.apply(this.$store, [val].concat(args))
};
});
return res
});
var mapGetters = normalizeNamespace(function (namespace, getters) {
var res = {};
normalizeMap(getters).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
val = namespace + val;
res[key] = function mappedGetter () {
if (namespace && !getModuleByNamespace(this.$store, 'mapGetters', namespace)) {
return
}
if (!(val in this.$store.getters)) {
console.error(("[vuex] unknown getter: " + val));
return
}
return this.$store.getters[val]
};
});
return res
});
var mapActions = normalizeNamespace(function (namespace, actions) {
var res = {};
normalizeMap(actions).forEach(function (ref) {
var key = ref.key;
var val = ref.val;
val = namespace + val;
res[key] = function mappedAction () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
if (namespace && !getModuleByNamespace(this.$store, 'mapActions', namespace)) {
return
}
return this.$store.dispatch.apply(this.$store, [val].concat(args))
};
});
return res
});
function normalizeMap (map) {
return Array.isArray(map)
? map.map(function (key) { return ({ key: key, val: key }); })
: Object.keys(map).map(function (key) { return ({ key: key, val: map[key] }); })
}
function normalizeNamespace (fn) {
return function (namespace, map) {
if (typeof namespace !== 'string') {
map = namespace;
namespace = '';
} else if (namespace.charAt(namespace.length - 1) !== '/') {
namespace += '/';
}
return fn(namespace, map)
}
}
function getModuleByNamespace (store, helper, namespace) {
var module = store._modulesNamespaceMap[namespace];
if (!module) {
console.error(("[vuex] module namespace not found in " + helper + "(): " + namespace));
}
return module
}
/**
* Get the first item that pass the test
* by second argument function
*
* @param {Array} list
* @param {Function} f
* @return {*}
*/
/**
* Deep copy the given object considering circular structure.
* This function caches all nested objects and its copies.
* If it detects circular structure, use cached copy to avoid infinite loop.
*
* @param {*} obj
* @param {Array<Object>} cache
* @return {*}
*/
/**
* forEach for object
*/
function forEachValue (obj, fn) {
Object.keys(obj).forEach(function (key) { return fn(obj[key], key); });
}
function isObject (obj) {
return obj !== null && typeof obj === 'object'
}
function isPromise (val) {
return val && typeof val.then === 'function'
}
function assert (condition, msg) {
if (!condition) { throw new Error(("[vuex] " + msg)) }
}
var Module = function Module (rawModule, runtime) {
this.runtime = runtime;
this._children = Object.create(null);
this._rawModule = rawModule;
};
var prototypeAccessors$1 = { state: {},namespaced: {} };
prototypeAccessors$1.state.get = function () {
return this._rawModule.state || {}
};
prototypeAccessors$1.namespaced.get = function () {
return !!this._rawModule.namespaced
};
Module.prototype.addChild = function addChild (key, module) {
this._children[key] = module;
};
Module.prototype.removeChild = function removeChild (key) {
delete this._children[key];
};
Module.prototype.getChild = function getChild (key) {
return this._children[key]
};
Module.prototype.update = function update (rawModule) {
this._rawModule.namespaced = rawModule.namespaced;
if (rawModule.actions) {
this._rawModule.actions = rawModule.actions;
}
if (rawModule.mutations) {
this._rawModule.mutations = rawModule.mutations;
}
if (rawModule.getters) {
this._rawModule.getters = rawModule.getters;
}
};
Module.prototype.forEachChild = function forEachChild (fn) {
forEachValue(this._children, fn);
};
Module.prototype.forEachGetter = function forEachGetter (fn) {
if (this._rawModule.getters) {
forEachValue(this._rawModule.getters, fn);
}
};
Module.prototype.forEachAction = function forEachAction (fn) {
if (this._rawModule.actions) {
forEachValue(this._rawModule.actions, fn);
}
};
Module.prototype.forEachMutation = function forEachMutation (fn) {
if (this._rawModule.mutations) {
forEachValue(this._rawModule.mutations, fn);
}
};
Object.defineProperties( Module.prototype, prototypeAccessors$1 );
var ModuleCollection = function ModuleCollection (rawRootModule) {
var this$1 = this;
// register root module (Vuex.Store options)
this.root = new Module(rawRootModule, false);
// register all nested modules
if (rawRootModule.modules) {
forEachValue(rawRootModule.modules, function (rawModule, key) {
this$1.register([key], rawModule, false);
});
}
};
ModuleCollection.prototype.get = function get (path) {
return path.reduce(function (module, key) {
return module.getChild(key)
}, this.root)
};
ModuleCollection.prototype.getNamespace = function getNamespace (path) {
var module = this.root;
return path.reduce(function (namespace, key) {
module = module.getChild(key);
return namespace + (module.namespaced ? key + '/' : '')
}, '')
};
ModuleCollection.prototype.update = function update$1 (rawRootModule) {
update(this.root, rawRootModule);
};
ModuleCollection.prototype.register = function register (path, rawModule, runtime) {
var this$1 = this;
if ( runtime === void 0 ) runtime = true;
var parent = this.get(path.slice(0, -1));
var newModule = new Module(rawModule, runtime);
parent.addChild(path[path.length - 1], newModule);
// register nested modules
if (rawModule.modules) {
forEachValue(rawModule.modules, function (rawChildModule, key) {
this$1.register(path.concat(key), rawChildModule, runtime);
});
}
};
ModuleCollection.prototype.unregister = function unregister (path) {
var parent = this.get(path.slice(0, -1));
var key = path[path.length - 1];
if (!parent.getChild(key).runtime) { return }
parent.removeChild(key);
};
function update (targetModule, newModule) {
// update target module
targetModule.update(newModule);
// update nested modules
if (newModule.modules) {
for (var key in newModule.modules) {
if (!targetModule.getChild(key)) {
console.warn(
"[vuex] trying to add a new module '" + key + "' on hot reloading, " +
'manual reload is needed'
);
return
}
update(targetModule.getChild(key), newModule.modules[key]);
}
}
}
var Vue; // bind on install
var Store = function Store (options) {
var this$1 = this;
if ( options === void 0 ) options = {};
assert(Vue, "must call Vue.use(Vuex) before creating a store instance.");
assert(typeof Promise !== 'undefined', "vuex requires a Promise polyfill in this browser.");
var state = options.state; if ( state === void 0 ) state = {};
var plugins = options.plugins; if ( plugins === void 0 ) plugins = [];
var strict = options.strict; if ( strict === void 0 ) strict = false;
// store internal state
this._committing = false;
this._actions = Object.create(null);
this._mutations = Object.create(null);
this._wrappedGetters = Object.create(null);
this._modules = new ModuleCollection(options);
this._modulesNamespaceMap = Object.create(null);
this._subscribers = [];
this._watcherVM = new Vue();
// bind commit and dispatch to self
var store = this;
var ref = this;
var dispatch = ref.dispatch;
var commit = ref.commit;
this.dispatch = function boundDispatch (type, payload) {
return dispatch.call(store, type, payload)
};
this.commit = function boundCommit (type, payload, options) {
return commit.call(store, type, payload, options)
};
// strict mode
this.strict = strict;
// init root module.
// this also recursively registers all sub-modules
// and collects all module getters inside this._wrappedGetters
installModule(this, state, [], this._modules.root);
// initialize the store vm, which is responsible for the reactivity
// (also registers _wrappedGetters as computed properties)
resetStoreVM(this, state);
// apply plugins
plugins.concat(devtoolPlugin).forEach(function (plugin) { return plugin(this$1); });
};
var prototypeAccessors = { state: {} };
prototypeAccessors.state.get = function () {
return this._vm.$data.state
};
prototypeAccessors.state.set = function (v) {
assert(false, "Use store.replaceState() to explicit replace store state.");
};
Store.prototype.commit = function commit (_type, _payload, _options) {
var this$1 = this;
// check object-style commit
var ref = unifyObjectStyle(_type, _payload, _options);
var type = ref.type;
var payload = ref.payload;
var options = ref.options;
var mutation = { type: type, payload: payload };
var entry = this._mutations[type];
if (!entry) {
console.error(("[vuex] unknown mutation type: " + type));
return
}
this._withCommit(function () {
entry.forEach(function commitIterator (handler) {
handler(payload);
});
});
this._subscribers.forEach(function (sub) { return sub(mutation, this$1.state); });
if (options && options.silent) {
console.warn(
"[vuex] mutation type: " + type + ". Silent option has been removed. " +
'Use the filter functionality in the vue-devtools'
);
}
};
Store.prototype.dispatch = function dispatch (_type, _payload) {
// check object-style dispatch
var ref = unifyObjectStyle(_type, _payload);
var type = ref.type;
var payload = ref.payload;
var entry = this._actions[type];
if (!entry) {
console.error(("[vuex] unknown action type: " + type));
return
}
return entry.length > 1
? Promise.all(entry.map(function (handler) { return handler(payload); }))
: entry[0](payload)
};
Store.prototype.subscribe = function subscribe (fn) {
var subs = this._subscribers;
if (subs.indexOf(fn) < 0) {
subs.push(fn);
}
return function () {
var i = subs.indexOf(fn);
if (i > -1) {
subs.splice(i, 1);
}
}
};
Store.prototype.watch = function watch (getter, cb, options) {
var this$1 = this;
assert(typeof getter === 'function', "store.watch only accepts a function.");
return this._watcherVM.$watch(function () { return getter(this$1.state, this$1.getters); }, cb, options)
};
Store.prototype.replaceState = function replaceState (state) {
var this$1 = this;
this._withCommit(function () {
this$1._vm.state = state;
});
};
Store.prototype.registerModule = function registerModule (path, rawModule) {
if (typeof path === 'string') { path = [path]; }
assert(Array.isArray(path), "module path must be a string or an Array.");
this._modules.register(path, rawModule);
installModule(this, this.state, path, this._modules.get(path));
// reset store to update getters...
resetStoreVM(this, this.state);
};
Store.prototype.unregisterModule = function unregisterModule (path) {
var this$1 = this;
if (typeof path === 'string') { path = [path]; }
assert(Array.isArray(path), "module path must be a string or an Array.");
this._modules.unregister(path);
this._withCommit(function () {
var parentState = getNestedState(this$1.state, path.slice(0, -1));
Vue.delete(parentState, path[path.length - 1]);
});
resetStore(this);
};
Store.prototype.hotUpdate = function hotUpdate (newOptions) {
this._modules.update(newOptions);
resetStore(this, true);
};
Store.prototype._withCommit = function _withCommit (fn) {
var committing = this._committing;
this._committing = true;
fn();
this._committing = committing;
};
Object.defineProperties( Store.prototype, prototypeAccessors );
function resetStore (store, hot) {
store._actions = Object.create(null);
store._mutations = Object.create(null);
store._wrappedGetters = Object.create(null);
store._modulesNamespaceMap = Object.create(null);
var state = store.state;
// init all modules
installModule(store, state, [], store._modules.root, true);
// reset vm
resetStoreVM(store, state, hot);
}
function resetStoreVM (store, state, hot) {
var oldVm = store._vm;
// bind store public getters
store.getters = {};
var wrappedGetters = store._wrappedGetters;
var computed = {};
forEachValue(wrappedGetters, function (fn, key) {
// use computed to leverage its lazy-caching mechanism
computed[key] = function () { return fn(store); };
Object.defineProperty(store.getters, key, {
get: function () { return store._vm[key]; },
enumerable: true // for local getters
});
});
// use a Vue instance to store the state tree
// suppress warnings just in case the user has added
// some funky global mixins
var silent = Vue.config.silent;
Vue.config.silent = true;
store._vm = new Vue({
data: { state: state },
computed: computed
});
Vue.config.silent = silent;
// enable strict mode for new vm
if (store.strict) {
enableStrictMode(store);
}
if (oldVm) {
if (hot) {
// dispatch changes in all subscribed watchers
// to force getter re-evaluation for hot reloading.
store._withCommit(function () {
oldVm.state = null;
});
}
Vue.nextTick(function () { return oldVm.$destroy(); });
}
}
function installModule (store, rootState, path, module, hot) {
var isRoot = !path.length;
var namespace = store._modules.getNamespace(path);
// register in namespace map
if (namespace) {
store._modulesNamespaceMap[namespace] = module;
}
// set state
if (!isRoot && !hot) {
var parentState = getNestedState(rootState, path.slice(0, -1));
var moduleName = path[path.length - 1];
store._withCommit(function () {
Vue.set(parentState, moduleName, module.state);
});
}
var local = module.context = makeLocalContext(store, namespace, path);
module.forEachMutation(function (mutation, key) {
var namespacedType = namespace + key;
registerMutation(store, namespacedType, mutation, local);
});
module.forEachAction(function (action, key) {
var namespacedType = namespace + key;
registerAction(store, namespacedType, action, local);
});
module.forEachGetter(function (getter, key) {
var namespacedType = namespace + key;
registerGetter(store, namespacedType, getter, local);
});
module.forEachChild(function (child, key) {
installModule(store, rootState, path.concat(key), child, hot);
});
}
/**
* make localized dispatch, commit, getters and state
* if there is no namespace, just use root ones
*/
function makeLocalContext (store, namespace, path) {
var noNamespace = namespace === '';
var local = {
dispatch: noNamespace ? store.dispatch : function (_type, _payload, _options) {
var args = unifyObjectStyle(_type, _payload, _options);
var payload = args.payload;
var options = args.options;
var type = args.type;
if (!options || !options.root) {
type = namespace + type;
if (!store._actions[type]) {
console.error(("[vuex] unknown local action type: " + (args.type) + ", global type: " + type));
return
}
}
return store.dispatch(type, payload)
},
commit: noNamespace ? store.commit : function (_type, _payload, _options) {
var args = unifyObjectStyle(_type, _payload, _options);
var payload = args.payload;
var options = args.options;
var type = args.type;
if (!options || !options.root) {
type = namespace + type;
if (!store._mutations[type]) {
console.error(("[vuex] unknown local mutation type: " + (args.type) + ", global type: " + type));
return
}
}
store.commit(type, payload, options);
}
};
// getters and state object must be gotten lazily
// because they will be changed by vm update
Object.defineProperties(local, {
getters: {
get: noNamespace
? function () { return store.getters; }
: function () { return makeLocalGetters(store, namespace); }
},
state: {
get: function () { return getNestedState(store.state, path); }
}
});
return local
}
function makeLocalGetters (store, namespace) {
var gettersProxy = {};
var splitPos = namespace.length;
Object.keys(store.getters).forEach(function (type) {
// skip if the target getter is not match this namespace
if (type.slice(0, splitPos) !== namespace) { return }
// extract local getter type
var localType = type.slice(splitPos);
// Add a port to the getters proxy.
// Define as getter property because
// we do not want to evaluate the getters in this time.
Object.defineProperty(gettersProxy, localType, {
get: function () { return store.getters[type]; },
enumerable: true
});
});
return gettersProxy
}
function registerMutation (store, type, handler, local) {
var entry = store._mutations[type] || (store._mutations[type] = []);
entry.push(function wrappedMutationHandler (payload) {
handler(local.state, payload);
});
}
function registerAction (store, type, handler, local) {
var entry = store._actions[type] || (store._actions[type] = []);
entry.push(function wrappedActionHandler (payload, cb) {
var res = handler({
dispatch: local.dispatch,
commit: local.commit,
getters: local.getters,
state: local.state,
rootGetters: store.getters,
rootState: store.state
}, payload, cb);
if (!isPromise(res)) {
res = Promise.resolve(res);
}
if (store._devtoolHook) {
return res.catch(function (err) {
store._devtoolHook.emit('vuex:error', err);
throw err
})
} else {
return res
}
});
}
function registerGetter (store, type, rawGetter, local) {
if (store._wrappedGetters[type]) {
console.error(("[vuex] duplicate getter key: " + type));
return
}
store._wrappedGetters[type] = function wrappedGetter (store) {
return rawGetter(
local.state, // local state
local.getters, // local getters
store.state, // root state
store.getters // root getters
)
};
}
function enableStrictMode (store) {
store._vm.$watch('state', function () {
assert(store._committing, "Do not mutate vuex store state outside mutation handlers.");
}, { deep: true, sync: true });
}
function getNestedState (state, path) {
return path.length
? path.reduce(function (state, key) { return state[key]; }, state)
: state
}
function unifyObjectStyle (type, payload, options) {
if (isObject(type) && type.type) {
options = payload;
payload = type;
type = type.type;
}
assert(typeof type === 'string', ("Expects string as the type, but found " + (typeof type) + "."));
return { type: type, payload: payload, options: options }
}
function install (_Vue) {
if (Vue) {
console.error(
'[vuex] already installed. Vue.use(Vuex) should be called only once.'
);
return
}
Vue = _Vue;
applyMixin(Vue);
}
// auto install in dist mode
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
var index = {
Store: Store,
install: install,
version: '2.1.2',
mapState: mapState,
mapMutations: mapMutations,
mapGetters: mapGetters,
mapActions: mapActions
};
return index;
})));
},{}],4:[function(require,module,exports){
'use strict';
var _vue = require('vue');
var _vue2 = _interopRequireDefault(_vue);
var _store = require('./store');
var _store2 = _interopRequireDefault(_store);
var _vuex = require('vuex');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var app = new _vue2.default({
store: _store2.default,
computed: (0, _vuex.mapGetters)(['evenOrOdd']),
methods: (0, _vuex.mapActions)(['increment', 'decrement', 'incrementIfOdd', 'incrementAsync'])
});
app.$mount('#app');
},{"./store":5,"vue":2,"vuex":3}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _vue = require('vue');
var _vue2 = _interopRequireDefault(_vue);
var _vuex = require('vuex');
var _vuex2 = _interopRequireDefault(_vuex);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_vue2.default.use(_vuex2.default);
var state = {
count: 0
};
var mutations = {
increment: function increment(state) {
state.count++;
},
decrement: function decrement(state) {
state.count--;
}
};
var actions = {
increment: function increment(_ref) {
var commit = _ref.commit;
return commit('increment');
},
decrement: function decrement(_ref2) {
var commit = _ref2.commit;
return commit('decrement');
},
incrementIfOdd: function incrementIfOdd(_ref3) {
var commit = _ref3.commit,
state = _ref3.state;
if ((state.count + 1) % 2 === 0) {
commit('increment');
}
},
incrementAsync: function incrementAsync(_ref4) {
var commit = _ref4.commit;
return new Promise(function (resolve, reject) {
setTimeout(function () {
commit('increment');
resolve();
}, 1000);
});
}
};
var getters = {
evenOrOdd: function evenOrOdd(state) {
return state.count % 2 === 0 ? 'even' : 'odd';
}
};
exports.default = new _vuex2.default.Store({
state: state,
mutations: mutations,
actions: actions,
getters: getters
});
},{"vue":2,"vuex":3}]},{},[4]);
|
function Preview(color) {
this.color = color;
this.nextTile = document.getElementById('next');
this.nextTile.className = 'tile ' + this.currentColor;
}
Preview.prototype.render = function() {
this.nextTile.className = 'tile ' + this.color;
}; |
var should = require('should');
var assert = require('assert');
var mockSocket = require('./lib/mock_socket');
var Producer = require('../index').Producer;
var Message = require('../index').Message;
var ProduceRequest = require('../index').ProduceRequest;
var BufferMaker = require('buffermaker');
var binary = require('binary');
var net = require('net');
var EventEmitter = require('events').EventEmitter;
var sinon = require('./lib/sinonPatch');
function closeServer(server, cb){
var called = false;
function callback() {
if (!called) {
called = true;
cb();
}
}
if (!!server){
try {
server.close(function(){
callback();
});
server = null;
setTimeout(function(){callback();}, 1000);
} catch(ex){
server = null;
callback();
}
} else {
callback();
}
}
function testProducer(useConnCache) {
describe("Producer with" + (useConnCache ? "" : "out") + " connection cache", function() {
beforeEach(function(done){
Producer.clearConnectionCache();
this.producer = new Producer('test', {
connectionCache: useConnCache
});
if (!this.server) {
this.server = null;
}
closeServer(this.server, done);
});
afterEach(function(){
sinon.restoreAll();
});
describe("Kafka Producer", function(){
it("should have a default topic id", function(){
this.producer.topic.should.equal('test');
});
it("should have a default partition", function(){
this.producer.partition.should.equal(0);
});
it("should have a default host", function(){
this.producer.host.should.equal('localhost');
});
it("should have a default port", function(){
this.producer.port.should.equal(9092);
});
it("should error if topic is not supplied", function(){
try {
new Producer();
should.fail("expected exception was not raised");
} catch(ex){
ex.should.equal("the first parameter, topic, is mandatory.");
}
});
describe("no server is present", function(){
it("emits an error", function(done) {
this.producer.port = 8542;
this.producer.on('error', function(err) {
should.exist(err);
done();
});
this.producer.connect(function(err) {
});
});
});
describe("#connect", function() {
it("sets keep-alive on underlying socket on connect", function(done) {
/* decorate underlying Socket function to set a property */
var isSetKeepAliveSet = false;
var setKeepAlive = net.Socket.prototype.setKeepAlive;
net.Socket.prototype.setKeepAlive = function(setting, msecs) {
isSetKeepAliveSet = true;
setKeepAlive(setting, msecs);
};
this.server = net.createServer(function(connection) {
});
this.server.listen(9998);
this.producer.port = 9998;
this.producer.on('connect', function(){
done();
});
this.producer.connect();
isSetKeepAliveSet.should.equal(true);
net.Socket.prototype.setKeepAlive = setKeepAlive;
});
if (useConnCache) {
it("should reuse connections to the same host and port", function(done) {
this.server = net.createServer(function(connection) {
});
this.server.listen(9998);
var connected = 0;
function onConnect() {
++connected;
if (connected === 2) {
producer1.connection.should.equal(producer2.connection);
done();
}
}
var producer1 = new Producer('test1', {
port: 9998,
connectionCache: true
});
producer1.on('connect', onConnect);
var producer2 = new Producer('test2', {
port: 9998,
connectionCache: true
});
producer2.on('connect', onConnect);
producer1.connect();
producer2.connect();
});
}
});
describe("#send", function() {
it("should attempt a reconnect on send if disconnected", function(done) {
var connectionCount = 0;
sinon.stub(net, "createConnection", function(port, host){
host.should.equal("localhost");
port.should.equal(8544);
var fakeConn = new EventEmitter();
fakeConn.setKeepAlive = function(somebool, interval){
somebool.should.equal(true);
interval.should.equal(1000);
};
fakeConn.write = function(data, cb){
if (connectionCount === 0){
connectionCount = connectionCount + 1;
cb(new Error('This socket is closed.'));
} else {
connectionCount = connectionCount + 1;
cb();
}
};
setTimeout(function(){
fakeConn.emit('connect');
}, 1);
return fakeConn;
});
var that = this;
this.producer = new Producer('test', {
connectionCache: useConnCache
});
this.producer.port = 8544;
this.producer.once('connect', function(){
that.producer.send('foo', function(err) {
should.not.exist(err);
connectionCount.should.equal(2);
done();
});
});
this.producer.connect();
});
it("should coerce a non-Message object into a Message object before sending", function(done) {
var that = this;
this.server = net.createServer(function (socket) {
socket.on('data', function(data){
var unpacked = binary.parse(data)
.word32bu('length')
.word16bs('error')
.tap( function(vars) {
this.buffer('body', vars.length);
})
.vars;
var request = ProduceRequest.fromBytes(data);
request.messages.length.should.equal(1);
request.messages[0].payload.toString().should.equal('this is not a message');
done();
});
});
this.server.listen(8542, function() {
that.producer.port = 8542;
that.producer.on('error', function() {
});
that.producer.on('connect', function(){
var messages = ['this is not a message'];
that.producer.send(messages, function(err){
should.not.exist(err);
});
});
that.producer.connect();
});
});
it("if there's an error, report it in the callback", function(done) {
var that = this;
this.server = net.createServer(function(socket) {});
this.server.listen(8542, function() {
that.producer.port = 8542;
that.producer.on('connect', function(){
that.producer.connection.write = function(bytes, cb) {
should.exist(cb);
cb('some error');
};
var message = new Message('foo');
that.producer.send(message, function(err) {
err.toString().should.equal('some error');
done();
});
});
that.producer.connect();
});
});
it("should coerce a single message into a list", function(done) {
var that = this;
this.server = net.createServer(function (socket) {
socket.on('data', function(data){
var unpacked = binary.parse(data)
.word32bu('length')
.word16bs('error')
.tap( function(vars) {
this.buffer('body', vars.length);
})
.vars;
var request = ProduceRequest.fromBytes(data);
request.messages.length.should.equal(1);
request.messages[0].payload.toString().should.equal("foo");
});
});
this.server.listen(8542, function() {
that.producer.port = 8542;
that.producer.on('error', function(err) {
should.fail('should not get here');
});
that.producer.on('connect', function(){
var message = new Message('foo');
that.producer.send(message, function(err) {
should.not.exist(err);
done();
});
});
that.producer.connect();
});
});
it("should allow an options parameter to specify topic and partition", function(done) {
var that = this;
this.server = net.createServer(function (socket) {
socket.on('data', function(data){
var unpacked = binary.parse(data)
.word32bu('length')
.word16bs('error')
.tap( function(vars) {
this.buffer('body', vars.length);
})
.vars;
var request = ProduceRequest.fromBytes(data);
request.messages.length.should.equal(1);
request.messages[0].payload.toString().should.equal("foo");
request.topic.should.equal("newtopic");
request.partition.should.equal(1337);
});
});
this.server.listen(8542, function() {
that.producer.port = 8542;
that.producer.on('error', function(err) {
should.fail('should not get here');
});
that.producer.on('connect', function(){
var message = new Message('foo');
var options = {
topic : "newtopic",
partition : 1337
};
that.producer.send(message, options, function(err) {
should.not.exist(err);
done();
});
});
that.producer.connect();
});
});
it("handle non-ascii utf-8", function(done) {
var that = this;
var testString = "fo\u00a0o";
this.server = net.createServer(function (socket) {
socket.on('data', function(data){
var unpacked = binary.parse(data)
.word32bu('length')
.word16bs('error')
.tap( function(vars) {
this.buffer('body', vars.length);
})
.vars;
var request = ProduceRequest.fromBytes(data);
request.messages.length.should.equal(1);
request.messages[0].payload.toString().should.equal(testString);
});
});
this.server.listen(8542, function() {
that.producer.port = 8542;
that.producer.on('error', function(err) {
should.fail('should not get here');
});
that.producer.on('connect', function(){
var message = new Message(testString);
that.producer.send(message, function(err) {
should.not.exist(err);
done();
});
});
that.producer.connect();
});
});
});
describe("With mock sockets", function() {
before(function() {
mockSocket.install();
});
after(function() {
mockSocket.restore();
});
beforeEach(function() {
mockSocket.socketBehavior = {};
mockSocket.openSockets = {};
Producer.clearConnectionCache();
});
it("handles connection failure", function(done) {
mockSocket.socketBehavior["localhost:9092"] = {connect: {type: 'error'}};
var producer = new Producer("test", {
connectionCache: useConnCache
});
producer.on('error', function(err) {
done();
});
producer.on('connect', function() {
done(new Error("should fail"));
});
producer.connect();
});
it("handles write failure", function(done) {
mockSocket.socketBehavior["localhost:9092"] = {write: {type: 'error'}};
var producer = new Producer("test", {
connectionCache: useConnCache
});
producer.on('error', done);
producer.on('connect', function() {
producer.send("testingtesting", function(err) {
if (err) {
done();
} else {
done(true);
}
});
});
producer.connect();
});
it("reconnects on write failure", function(done) {
mockSocket.socketBehavior["localhost:9092"] = {write: {type: 'error', single: true}};
var producer = new Producer("test", {
connectionCache: useConnCache
});
producer.on('error', done);
producer.on('connect', function() {
producer.send("testingtesting", done);
});
producer.connect();
});
if (useConnCache) {
it("should work when two are connecting simultaneously", function(done) {
var producer1 = new Producer("test1", {
connectionCache: useConnCache
});
var producer2 = new Producer("test2", {
connectionCache: useConnCache
});
mockSocket.socketBehavior["localhost:9092"] = {
connect: {
type: 'wait',
wait: function(callback) {
// after producer1 started to connect
producer2.on('connect', function() {
producer2.send("testingtesting", done);
});
producer2.on('error', done);
producer2.connect();
callback();
}
}
};
producer1.connect();
});
it("should work when one is connecting while the other reconnects", function(done) {
var producer1 = new Producer("test1", {
connectionCache: useConnCache
});
var producer2 = new Producer("test2", {
connectionCache: useConnCache
});
mockSocket.socketBehavior["localhost:9092"] = {
write: {
type: 'error',
single: true
},
connect: {
type: 'series',
series: [
{type: 'ok'},
{
type: 'wait',
wait: function(callback) {
// after producer1 started to reconnect
producer2.on('connect', function() {
producer2.send("testingtesting", done);
});
producer2.on('error', done);
producer2.connect();
callback();
}
}
]
}
};
producer1.on('connect', function() {
producer1.send("testing", function(err) {
assert(!err);
});
});
producer1.connect();
});
it("should work when one is writing while the other reconnects", function(done) {
var producer1 = new Producer("test1", {
connectionCache: useConnCache
});
var producer2 = new Producer("test2", {
connectionCache: useConnCache
});
mockSocket.socketBehavior["localhost:9092"] = {
write: {
type: 'error',
single: true
},
connect: {
type: 'series',
series: [
{type: 'ok'},
{
type: 'wait',
wait: function(callback) {
// after producer1 started to reconnect
producer2.send("testingtesting", done);
callback();
}
}
]
}
};
var connected = 0;
function onConnect() {
++connected;
if (connected === 2) {
producer1.send("testing", function(err) {
assert(!err);
});
}
}
producer1.on('connect', onConnect);
producer2.on('connect', onConnect);
producer1.connect();
producer2.connect();
});
}
});
});
});
}
testProducer(false);
testProducer(true);
|
/**
* 本地缓存 类
*/
export default class LocalStorage {
constructor() {
}
/**
* 默认获取是否支持本地缓存
* @returns {Storage}
*/
static getLocalStorage() {
if (!localStorage) {
throw new Error('Need localStorage');
}
return localStorage;
}
/**
* 添加本地缓存
*/
static add(key, value, expired) {
if (value === undefined) {
value = null;
}
let localStorage = this.getLocalStorage();
let _expired = this.getExp(key, expired);
let obj = {
data: value,
expired: _expired,
time: +new Date().getTime()
};
localStorage.setItem(key, JSON.stringify(obj));
}
/**
* 获取本地缓存的KEY,过期的回调函数,返回过期前的数据.
* @param key
* @param callback
* @returns {null}
*/
static get(key, callback) {
let localStorage = this.getLocalStorage();
let _value = localStorage.getItem(key);
if (_value) {
let JSON_VALUE = JSON.parse(_value);
let now = new Date().getTime();
//如果过期执行的方法
if (JSON_VALUE.expired && JSON_VALUE.expired!=0&&JSON_VALUE.expired - now < 0) {
callback ? callback(JSON_VALUE):function(){};
this.remove(key);
} else {
return JSON_VALUE.data;
}
}
return null;
}
/**
* d更新本地缓存,存在就更新 不存在就返回NULL;
* @param key
* @param value
* @param expired
* @returns {null}
*/
static update(key, value, expired) {
let json = JSON.parse(localStorage.getItem(key));
console.log(json)
if (json != null) {
let _expired = this.getExp(expired, key);
let obj = {
data: value,
expired: _expired,
time: +new Date().getTime()
};
localStorage.setItem(key, JSON.stringify(obj));
} else {
return null;
}
}
/**
* 删除相对应KEY的本地缓存
* @param key
*/
static remove(key) {
let localStorage = this.getLocalStorage();
localStorage.removeItem(key);
}
/**
* 清除所有本地缓存
*/
static clear() {
let localStorage = this.getLocalStorage();
localStorage.clear();
}
static getExp(key, expired) {
//当过期
if (expired == 0) {
let _this = this;
window.onbeforeunload = function() {
_this.remove(key);
}
} else if (typeof expired == 'number' || !isNaN(Number(expired))) {
//expired = 1455033600000;
expired = new Date(new Date().getTime() + expired * (24 * 60 * 60 * 1000)).getTime();
}
return expired;
}
} |
module.exports =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/dist/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ({
/***/ 0:
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(249);
/***/ },
/***/ 3:
/***/ function(module, exports) {
/* globals __VUE_SSR_CONTEXT__ */
// this module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context = context || (this.$vnode && this.$vnode.ssrContext)
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
// inject component registration as beforeCreate hook
var existing = options.beforeCreate
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}
/***/ },
/***/ 14:
/***/ function(module, exports) {
module.exports = require("element-ui/lib/mixins/emitter");
/***/ },
/***/ 249:
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _radioGroup = __webpack_require__(250);
var _radioGroup2 = _interopRequireDefault(_radioGroup);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/* istanbul ignore next */
_radioGroup2.default.install = function (Vue) {
Vue.component(_radioGroup2.default.name, _radioGroup2.default);
};
exports.default = _radioGroup2.default;
/***/ },
/***/ 250:
/***/ function(module, exports, __webpack_require__) {
var Component = __webpack_require__(3)(
/* script */
__webpack_require__(251),
/* coreCode */
__webpack_require__(252),
/* styles */
null,
/* scopeId */
null,
/* moduleIdentifier (server only) */
null
)
module.exports = Component.exports
/***/ },
/***/ 251:
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _emitter = __webpack_require__(14);
var _emitter2 = _interopRequireDefault(_emitter);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
name: 'ElRadioGroup',
componentName: 'ElRadioGroup',
mixins: [_emitter2.default],
props: {
value: {},
size: String,
fill: String,
textColor: String,
disabled: Boolean
},
watch: {
value: function value(_value) {
this.$emit('change', _value);
this.dispatch('ElFormItem', 'el.form.change', [this.value]);
}
}
}; //
//
//
//
//
/***/ },
/***/ 252:
/***/ function(module, exports) {
module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;
return _c('div', {
staticClass: "el-radio-group"
}, [_vm._t("default")], 2)
},staticRenderFns: []}
/***/ }
/******/ }); |
import GraphQL from 'graphql';
import { Node } from './node.js';
import { Entity } from './entity.js';
import { Duration, ISRC } from './scalars.js';
import {
id,
mbid,
title,
disambiguation,
connectionWithExtras,
linkedQuery,
} from './helpers.js';
import { aliases } from './alias.js';
import { artists } from './artist.js';
import { artistCredit, artistCredits } from './artist-credit.js';
import { collections } from './collection.js';
import { tags } from './tag.js';
import { rating } from './rating.js';
import { relationships } from './relationship.js';
import { releases } from './release.js';
const { GraphQLObjectType, GraphQLList, GraphQLBoolean } = GraphQL;
export const Recording = new GraphQLObjectType({
name: 'Recording',
description: `A [recording](https://musicbrainz.org/doc/Recording) is an
entity in MusicBrainz which can be linked to tracks on releases. Each track must
always be associated with a single recording, but a recording can be linked to
any number of tracks.
A recording represents distinct audio that has been used to produce at least one
released track through copying or mastering. A recording itself is never
produced solely through copying or mastering.
Generally, the audio represented by a recording corresponds to the audio at a
stage in the production process before any final mastering but after any editing
or mixing.`,
interfaces: () => [Node, Entity],
fields: () => ({
id,
mbid,
title,
disambiguation,
aliases,
artistCredit,
artistCredits,
isrcs: {
type: new GraphQLList(ISRC),
description: `A list of [International Standard Recording Codes](https://musicbrainz.org/doc/ISRC)
(ISRCs) for this recording.`,
resolve: (source, args, context) => {
if (source.isrcs) {
return source.isrcs;
}
// TODO: Add support for parent entities knowing to include this `inc`
// parameter in their own calls by inspecting what fields are requested
// or batching things at the loader level.
return context.loaders.lookup
.load(['recording', source.id, { inc: 'isrcs' }])
.then((recording) => recording.isrcs);
},
},
length: {
type: Duration,
description: `An approximation to the length of the recording, calculated
from the lengths of the tracks using it.`,
},
video: {
type: GraphQLBoolean,
description: 'Whether this is a video recording.',
},
artists,
releases,
relationships,
collections,
rating,
tags,
}),
});
export const RecordingConnection = connectionWithExtras(Recording);
export const recordings = linkedQuery(RecordingConnection);
|
var DOCUMENTATION_OPTIONS = {
URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'),
VERSION: '1.0.0',
LANGUAGE: 'None',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt',
NAVIGATION_WITH_KEYS: false,
}; |
import React, { useState } from 'react';
import { Link, useRouteMatch, useHistory } from 'react-router-dom';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import Drawer from '@material-ui/core/Drawer';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import StatsIcon from '@material-ui/icons/Assessment';
import SearchIcon from '@material-ui/icons/Search';
import HomeIcon from '@material-ui/icons/Home';
import MapIcon from '@material-ui/icons/Map';
import { withStyles } from '@material-ui/core';
import { useAuth } from '../Auth';
import styles from './layout.module.css';
const NewListItemText = withStyles({
primary: {
color: '#222',
},
root: {
display: 'inline-block',
},
})(ListItemText);
const CentredListItem = withStyles({
root: {
display: 'flex',
alignItems: 'center',
paddingRight: '2rem',
},
})(ListItem);
function SidebarItem(props) {
const match = useRouteMatch();
return (
<CentredListItem button>
<Link
to={`${match.path}/${props.pathName}`}
style={{ textDecoration: 'none' }}
>
<div className={styles.centredLink}>
<ListItemIcon>{props.icon}</ListItemIcon>
<NewListItemText primary={props.name} />
</div>
</Link>
</CentredListItem>
);
}
function Layout(props) {
const { login, logout, isAuthenticated } = useAuth();
const history = useHistory();
const [isDrawerOpen, setDrawerOpen] = useState(false);
const handleLogout = () => {
logout();
history.push('/');
};
return (
<div style={{ flexGrow: 1 }}>
<AppBar position="static">
<Toolbar>
<IconButton
color="inherit"
aria-label="Menu"
onClick={() => setDrawerOpen(true)}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" color="inherit" style={{ flex: 1 }}>
Toilet Map Explorer
</Typography>
{isAuthenticated() ? (
<Button onClick={handleLogout} color="inherit">
Logout
</Button>
) : (
<Button onClick={login} color="inherit">
Login
</Button>
)}
</Toolbar>
</AppBar>
<Drawer open={isDrawerOpen} onClose={() => setDrawerOpen(false)}>
<div
tabIndex={0}
role="button"
onClick={() => setDrawerOpen(false)}
onKeyDown={() => setDrawerOpen(false)}
>
<div>
<List>
<SidebarItem name="Home" pathName="" icon={<HomeIcon />} />
<SidebarItem
name="Statistics"
pathName="statistics"
icon={<StatsIcon />}
/>
<SidebarItem
name="Statistics by Area"
pathName="areas"
icon={<StatsIcon />}
/>
<SidebarItem
name="Search"
pathName="search"
icon={<SearchIcon />}
/>
<SidebarItem name="Area Map" pathName="map" icon={<MapIcon />} />
</List>
</div>
</div>
</Drawer>
<div>{props.children}</div>
</div>
);
}
export default Layout;
|
var Klout = require("node_klout"),
klout = new Klout(process.env.KLOUT_APIV2_KEY);
var initUser = function(username, callback){
klout.getKloutIdentity(username, function(error, user) {
if(error){
callback(error, null);
}else{
callback(null, user.id);
}
});
}
var getScore = function(userId, callback){
klout.getUserScore(userId, function(error, klout_response) {
if(error){
callback(error, null);
}else{
callback(null, Math.floor(klout_response.score));
}
});
}
module.exports.initUser = initUser;
module.exports.getScore = getScore;
|
import {List, Map, fromJS } from 'immutable';
import max from 'lodash/math/max';
import min from 'lodash/math/min';
import Paper from '../records/paper';
export const CREATE = 'Gecko/paper/CREATE';
export const FETCH = 'Gecko/paper/FETCH';
export const SELECT = 'Gecko/paper/SELECT';
export const CREATE_CARD = 'Gecko/card/CREATE';
const initialState = new Map({
list: List.of(
new Paper({ title: 'Gecko'}),
),
currentPaperIndex: 0,
});
const revive = (state) => {
if (state instanceof Map) {
return state;
}
return fromJS(state);
};
const reducer = (originalState, action) => {
const state = revive(originalState);
switch (action.type) {
case FETCH:
return state;
case CREATE:
return state.updateIn(['list'], list => list.push(action.newRecord));
case SELECT:
let index = action.currentPaperIndex;
index = min([index, state.get('list').length - 1]);
index = max([index, 0]);
return state.set('currentPaperIndex', index);
default:
return state;
}
};
export function fetch() {
return {
type: FETCH,
};
}
export function create(newRecord) {
return {
type: CREATE,
newRecord: new Paper(newRecord),
};
}
export function select(index) {
return {
type: SELECT,
currentPaperIndex: parseInt(index, 10),
};
}
export function shift(currentIndex, direction) {
return select(parseInt(currentIndex, 10) + direction);
}
export default (state = initialState, action = {}) => (reducer(state, action).toJS());
|
/*
* Rejewski
*
* Copyright 2014 Jason Gerfen
* All rights reserved.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
*/
var keys = require('../lib/keys')
, config = require('../lib/config')
, chai = require('chai')
, fs = require('fs')
, should = chai.should()
, expect = chai.expect
describe('keys.js', function(){
var opts = config.init({}, {});
it('keys.sid()', function(done){
var sid = keys.sid();
expect(typeof(sid)).to.equal('string');
expect(sid.length).to.equal(128);
done();
});
it('keys.set(obj, salt, key, cb)', function(done){
var obj = false;
keys.set('{"test": "wuka wuka"}', 'xyz', 'abc', function (err, result){
obj = JSON.parse(result);
});
expect(obj).to.have.property('ct').with.length(42);
expect(obj).to.have.property('digest').with.length(128);
done();
});
it('keys.get(mem, salt, key, cb)', function(done){
var obj = false;
keys.set('{"test": "wuka wuka"}', 'xyz', 'abc', function(err, result){
obj = JSON.parse(result);
});
expect(obj).to.have.property('ct').with.length(42);
expect(obj).to.have.property('digest').with.length(128);
keys.get(obj, 'xyz', 'abc', function(err, result){
obj = result;
});
expect(obj).to.have.property('test').with.length(9);
expect(obj.test).to.equal('wuka wuka');
done();
});
});
|
import React, { Component, PropTypes } from 'react';
import MessageListItem from './MessageListItem';
import * as actions from '../actions/actions';
import { Modal, DropdownButton, MenuItem, Button } from 'react-bootstrap';
const activeChannel='Lobby';
import io from 'socket.io-client';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import uuid from 'node-uuid';
import moment from 'moment';
import List from 'material-ui/lib/lists/list';
import Table from 'material-ui/lib/table/table';
import ListItem from 'material-ui/lib/lists/list-item';
import Avatar from 'material-ui/lib/avatar';
var socket = io.connect('https://gigg.tv');
//var socket = io.connect('https://localhost:1338');
class Chat extends Component {
constructor(props, context) {
super(props, context);
this.state = {
text: '',
typing: false
};
// connect_socket(props.token);
}
componentWillMount() {
const {userDetails, dispatch, activeChannel } = this.props;
dispatch(actions.fetchMessages(activeChannel));
}
componentDidMount() {
const {userDetails, dispatch, activeChannel}= this.props;
if(!userDetails|| userDetails.display_name===undefined) {
var userName= 'Guest';
} else {
var userName= userDetails.user_name;
}
socket.on('receive socket', socketID =>{
dispatch(actions.receiveSocket(socketID))
});
socket.emit('chat mounted', userName);
socket.on('new bc message', msg =>
dispatch(actions.receiveRawMessage(msg))
);
socket.on('typing bc', user =>
dispatch(actions.typing(user))
);
socket.on('stop typing bc', user =>
dispatch(actions.stopTyping(user))
);
socket.on('new channel', channel =>
dispatch(actions.receiveRawChannel(channel))
);
socket.on('receive socket', socketID =>{
dispatch(actions.receiveSocket(socketID))
});
}
componentDidUpdate() {
const messageList = this.refs.messageList;
messageList.scrollTop = messageList.scrollHeight;
}
handleSave(newMessage) {
const { dispatch } = this.props;
if (newMessage.text.length !== 0) {
dispatch(actions.createMessage(newMessage));
}
}
handleSubmit(event) {
const { userDetails, activeChannel} = this.props;
if(!userDetails|| userDetails.display_name===undefined) {
var userName= 'Guest';
var user_image= null;
} else {
var userName= userDetails.user_name;
var user_image= userDetails.user_image;
}
const text = event.target.value.trim();
if (event.which === 13) { //carriage return
event.preventDefault();
var newMessage = {
id: `${Date.now()}${uuid.v4()}`,
channelID: activeChannel,
text: text,
user: userName,
time: moment().calendar(),
user_image: user_image
};
socket.emit('new message', newMessage);
socket.emit('stop typing', { user: userName, channel: activeChannel });
this.setState({ text: '', typing: false });
this.handleSave(newMessage);
}
}
handleChange(event) {
const { userDetails, activeChannel } = this.props;
if(!userDetails) {
var userName= 'Guest';
} else {
userName= userDetails.user_name;
}
this.setState({ text: event.target.value });
if (event.target.value.length > 0 && !this.state.typing) {
socket.emit('typing', { user: userName, channel: activeChannel });
this.setState({ typing: true});
}
if (event.target.value.length === 0 && this.state.typing) {
socket.emit('stop typing', { user: user.userName, channel: activeChannel });
this.setState({ typing: false});
}
}
render() {
const {messages, dispatch,userDetails, activeChannel}= this.props;
const filteredMessages = messages.filter(message => message.channelID === activeChannel);
const styles = {
propContainerStyle: {
width: 200,
overflow: 'hidden',
margin: '20px auto 0',
},
propToggleHeader: {
margin: '20px auto 10px',
},
};
return (
<div className="chatWrapper">
<div className="main" >
<div className="messageContainer" ref="messageList">
{filteredMessages.map(message =>
<MessageListItem message={message} key={message.id} />
)}
</div>
<div className="chatFieldWrapper">
<input
className="chatInput"
type="textarea"
name="message"
ref="messageComposer"
autoFocus="true"
placeholder="Type here to chat!"
value={this.state.text}
onSave={this.handleSave.bind(this)}
onChange={this.handleChange.bind(this)}
onKeyDown={this.handleSubmit.bind(this)}/>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
messages: state.messages.data,
activeChannel: state.activeChannel.name,
userDetails: state.auth.userDetails,
token: state.auth.token
}
}
export default connect(mapStateToProps)(Chat) |
export user from './auth'
export todoList from './database' |
Demo.LongProcessDialog = function DemoLongProcessDialog( config ) {
Demo.LongProcessDialog.super.call( this, config );
};
OO.inheritClass( Demo.LongProcessDialog, OO.ui.ProcessDialog );
Demo.LongProcessDialog.static.title = 'Process dialog';
Demo.LongProcessDialog.static.actions = [
{ action: 'save', label: 'Done', icon: 'check', flags: [ 'primary', 'progressive' ] },
{ action: 'cancel', label: 'Abort', flags: [ 'safe' ] },
{ action: 'other', label: 'Other' },
{ action: 'other2', label: 'Additional other' }
];
Demo.LongProcessDialog.prototype.initialize = function () {
Demo.LongProcessDialog.super.prototype.initialize.apply( this, arguments );
this.content = new OO.ui.PanelLayout( { padded: true, expanded: false } );
for ( var i = 0; i < 100; i++ ) {
// eslint-disable-next-line no-jquery/no-parse-html-literal
this.content.$element.append( '<p>Dialog content</p>' );
}
this.$body.append( this.content.$element );
};
Demo.LongProcessDialog.prototype.getActionProcess = function ( action ) {
var dialog = this;
if ( action ) {
return new OO.ui.Process( function () {
dialog.close( { action: action } );
} );
}
return Demo.LongProcessDialog.super.prototype.getActionProcess.call( this, action );
};
Demo.LongProcessDialog.prototype.getBodyHeight = function () {
return this.content.$element.outerHeight( true );
};
|
'use strict';
const mockgoose = require('mockgoose');
const mongoose = require('mongoose');
mockgoose(mongoose, {port: 6666});
const co = require('co');
const _ = require('lodash');
const sinon = require('sinon');
const assert = require('assert');
const XeConsumer = require('../../worker/consumers/xe_consumer');
const XeScraper = require('../../worker/consumers/xe_scraper');
const XeProducer = require('../../worker/producers/xe_producer');
const ExchangeRate = require('../../worker/models/exchange_rate');
describe('XeConsumer', function () {
this.timeout(10000);
let config;
let mock_beanstakld_client;
let mock_scrape;
let mock_xe_producer_use;
let mock_xe_producer_produce;
const mockBeanstalkdClient = (reserve_data) => {
const reserve_return = reserve_data instanceof Error ? Promise.reject(reserve_data) : Promise.resolve(reserve_data);
const reserveAsync = sinon.stub();
reserveAsync.onFirstCall().returns(reserve_return);
reserveAsync.onSecondCall().returns(Promise.reject(Error('error')));
reserveAsync.returns(Promise.reject(Error('TIMED_OUT')));
mock_beanstakld_client = {
watchAsync: sinon.stub().returns(Promise.resolve([])),
destroyAsync: sinon.stub().returns(Promise.resolve([])),
reserveAsync: reserveAsync,
buryAsync: sinon.stub().returns(Promise.resolve([]))
};
};
const mockScrape = (exchange_rate) => {
const exchange_rate_return = exchange_rate instanceof Error ? Promise.reject(exchange_rate) : Promise.resolve(exchange_rate);
mock_scrape = sinon.stub(XeScraper.prototype, 'scrape', () => exchange_rate_return);
};
const mockXeProducer = () => {
mock_xe_producer_use = sinon.stub(XeProducer.prototype, 'use', () => Promise.resolve());
mock_xe_producer_produce = sinon.stub(XeProducer.prototype, 'produce', () => Promise.resolve());
};
before((done) => {
config = {
// tube name
tube: 'raymondsze',
consume: {
// the priority to put the job
priority: 0,
// time to run in second
ttr: 10,
// after success, the delay in second to release the job (retry)
success_delay: 0,
// after fail, the delay in second to release the job (retry)
failure_delay: 0,
// total trials
success_trials: 10,
// the minimum number of failure. If exceeds, the job buried.
tolerance: 2
}
};
mongoose.connect('mongodb://localhost/test', (err) => {
console.log('connected');
done(err);
});
});
beforeEach((done) => {
mockgoose.reset((err) => {
done(err);
});
});
afterEach(() => {
mock_scrape && mock_scrape.restore();
mock_xe_producer_use && mock_xe_producer_use.restore();
mock_xe_producer_produce && mock_xe_producer_produce.restore();
});
after(() => {
mongoose.disconnect();
});
describe('#constructor()', () => {
it('tube_name and client should set correctly after instantiation', () => {
mockBeanstalkdClient();
const xe_consumer = new XeConsumer(mock_beanstakld_client, config.tube);
assert.equal(mock_beanstakld_client, xe_consumer.client);
assert.equal(config.tube, xe_consumer.tube_name);
});
});
describe('#watch()', () => {
it('should trigger beanstalkd watch', co.wrap(function* () {
mockBeanstalkdClient();
const xe_consumer = new XeConsumer(mock_beanstakld_client, config.tube);
yield xe_consumer.watch();
assert(mock_beanstakld_client.watchAsync.calledOnce);
assert(mock_beanstakld_client.watchAsync.calledWith(config.tube));
}));
});
describe('#consume()', () => {
const default_payload = {
from: 'HKD',
to: 'USD'
};
it('reput job with success_count + 1 if scrape successfully', co.wrap(function* () {
mockBeanstalkdClient(['0', JSON.stringify(default_payload)]);
mockScrape('0.13');
mockXeProducer();
yield new XeConsumer(mock_beanstakld_client, config.tube).consume(config.consume);
assert(mock_beanstakld_client.reserveAsync.called);
assert(mock_xe_producer_use.calledOnce);
assert(mock_xe_producer_produce.calledOnce);
const produce_options = mock_xe_producer_produce.args[0][0];
assert(_.isEqual(produce_options, {
priority: config.consume.priority,
ttr: config.consume.ttr,
payload: {
from: default_payload.from, to: default_payload.to, success_count: 1, failure_count: 0
},
delay: config.consume.success_delay
}));
}));
it('save one exchange_rate to mongodb if scrape successfully', co.wrap(function* () {
mockBeanstalkdClient(['0', JSON.stringify(default_payload)]);
mockScrape('0.13');
mockXeProducer();
yield new XeConsumer(mock_beanstakld_client, config.tube).consume(config.consume);
const count = yield ExchangeRate.count();
assert.equal(count, 1);
}));
it('should not scrape and put job if success_count >= success_trials', co.wrap(function* () {
const payload = _.merge({
success_count: config.consume.success_trials
}, default_payload);
mockBeanstalkdClient(['0', JSON.stringify(payload)]);
mockScrape('0.13');
mockXeProducer();
yield new XeConsumer(mock_beanstakld_client, config.tube).consume(config.consume);
assert(!mock_scrape.called);
assert(!mock_xe_producer_use.called);
assert(!mock_xe_producer_produce.called);
}));
it('do not reput job if scrape successfully when payload success_count = success_trials - 1', co.wrap(function* () {
const payload = _.merge({
success_count: config.consume.success_trials - 1
}, default_payload);
mockBeanstalkdClient(['0', JSON.stringify(payload)]);
mockScrape('0.13');
mockXeProducer();
yield new XeConsumer(mock_beanstakld_client, config.tube).consume(config.consume);
assert(mock_scrape.calledOnce);
assert(!mock_xe_producer_use.called);
assert(!mock_xe_producer_produce.called);
}));
it('reput job with failure_count + 1 if scrape with error', co.wrap(function* () {
mockBeanstalkdClient(['0', JSON.stringify(default_payload)]);
mockScrape(Error('error'));
mockXeProducer();
yield new XeConsumer(mock_beanstakld_client, config.tube).consume(config.consume);
assert(mock_beanstakld_client.reserveAsync.called);
assert(mock_xe_producer_use.calledOnce);
assert(mock_xe_producer_produce.calledOnce);
const produce_options = mock_xe_producer_produce.args[0][0];
assert(_.isEqual(produce_options, {
priority: config.consume.priority,
ttr: config.consume.ttr,
payload: {
from: default_payload.from, to: default_payload.to, success_count: 0, failure_count: 1
},
delay: config.consume.success_delay
}));
}));
it('bury job if scrape with error when payload failure_count = tolerance', co.wrap(function* () {
const payload = _.merge({
failure_count: config.consume.tolerance
}, default_payload);
mockBeanstalkdClient(['0', JSON.stringify(payload)]);
mockScrape(Error('error'));
mockXeProducer();
yield new XeConsumer(mock_beanstakld_client, config.tube).consume(config.consume);
assert(mock_beanstakld_client.buryAsync.calledOnce);
assert(mock_beanstakld_client.buryAsync.calledWith('0'));
}));
it('do not reput job if scrape with error when payload failure_count = tolerance', co.wrap(function* () {
const payload = _.merge({
failure_count: config.consume.tolerance
}, default_payload);
mockBeanstalkdClient(['0', JSON.stringify(payload)]);
mockScrape(Error('error'));
mockXeProducer();
yield new XeConsumer(mock_beanstakld_client, config.tube).consume(config.consume);
assert(mock_beanstakld_client.buryAsync.calledOnce);
assert(mock_beanstakld_client.buryAsync.calledWith('0'));
assert(mock_scrape.calledOnce);
assert(!mock_xe_producer_use.called);
assert(!mock_xe_producer_produce.called);
}));
});
});
|
/**
* mock.js 提供应用截获ajax请求,为脱离后台测试使用
* 模拟查询更改内存中mockData,并返回数据
*/
import { fetch } from 'mk-utils'
const mockData = fetch.mockData
function initMockData() {
if (!mockData.home) {
mockData.home = {}
}
if(!mockData.home.messages){
mockData.home.messages = []
for (let i = 0; i < 50; i++) {
mockData.home.messages.push({
id: i,
message: '通知消息' + i,
date: `2017-${i % 11 + 1}-${i % 28 + 1}`,
})
}
}
}
fetch.mock('/v1/homeMessage/query', (option) => {
initMockData()
return {result: true, value: mockData.home.messages}
})
|
/**
* @author alteredq / http://alteredqualia.com/
*/
THREE.MD2CharacterComplex = function () {
var scope = this;
this.scale = 1;
// animation parameters
this.animationFPS = 6;
this.transitionFrames = 15;
// movement model parameters
this.maxSpeed = 275;
this.maxReverseSpeed = -275;
this.frontAcceleration = 600;
this.backAcceleration = 600;
this.frontDecceleration = 600;
this.angularSpeed = 2.5;
// rig
this.root = new THREE.Object3D();
this.meshBody = null;
this.meshWeapon = null;
this.controls = null;
// skins
this.skinsBody = [];
this.skinsWeapon = [];
this.weapons = [];
this.currentSkin = undefined;
//
this.onLoadComplete = function () {};
// internals
this.meshes = [];
this.animations = {};
this.loadCounter = 0;
// internal movement control variables
this.speed = 0;
this.bodyOrientation = 0;
this.walkSpeed = this.maxSpeed;
this.crouchSpeed = this.maxSpeed * 0.5;
// internal animation parameters
this.activeAnimation = null;
this.oldAnimation = null;
// API
this.enableShadows = function ( enable ) {
for ( var i = 0; i < this.meshes.length; i ++ ) {
this.meshes[ i ].castShadow = enable;
this.meshes[ i ].receiveShadow = enable;
}
};
this.setVisible = function ( enable ) {
for ( var i = 0; i < this.meshes.length; i ++ ) {
this.meshes[ i ].visible = enable;
this.meshes[ i ].visible = enable;
}
};
this.shareParts = function ( original ) {
this.animations = original.animations;
this.walkSpeed = original.walkSpeed;
this.crouchSpeed = original.crouchSpeed;
this.skinsBody = original.skinsBody;
this.skinsWeapon = original.skinsWeapon;
// BODY
var mesh = createPart( original.meshBody.geometry, this.skinsBody[ 0 ] );
mesh.scale.set( this.scale, this.scale, this.scale );
this.root.position.y = original.root.position.y;
this.root.add( mesh );
this.meshBody = mesh;
this.meshes.push( mesh );
// WEAPONS
for ( var i = 0; i < original.weapons.length; i ++ ) {
var mesh = createPart( original.weapons[ i ].geometry, this.skinsWeapon[ i ] );
mesh.scale.set( this.scale, this.scale, this.scale );
mesh.visible = false;
mesh.name = name;
this.root.add( mesh );
this.weapons[ i ] = mesh;
this.meshWeapon = mesh;
this.meshes.push( mesh );
}
};
this.loadParts = function ( config ) {
this.animations = config.animations;
this.walkSpeed = config.walkSpeed;
this.crouchSpeed = config.crouchSpeed;
this.loadCounter = config.weapons.length * 2 + config.skins.length + 1;
var weaponsTextures = []
for ( var i = 0; i < config.weapons.length; i ++ ) weaponsTextures[ i ] = config.weapons[ i ][ 1 ];
// SKINS
this.skinsBody = loadTextures( config.baseUrl + "skins/", config.skins );
this.skinsWeapon = loadTextures( config.baseUrl + "skins/", weaponsTextures );
// BODY
var loader = new THREE.JSONLoader();
loader.load( config.baseUrl + config.body, function( geo ) {
geo.computeBoundingBox();
scope.root.position.y = - scope.scale * geo.boundingBox.min.y;
var mesh = createPart( geo, scope.skinsBody[ 0 ] );
mesh.scale.set( scope.scale, scope.scale, scope.scale );
scope.root.add( mesh );
scope.meshBody = mesh;
scope.meshes.push( mesh );
checkLoadingComplete();
} );
// WEAPONS
var generateCallback = function ( index, name ) {
return function( geo ) {
var mesh = createPart( geo, scope.skinsWeapon[ index ] );
mesh.scale.set( scope.scale, scope.scale, scope.scale );
mesh.visible = false;
mesh.name = name;
scope.root.add( mesh );
scope.weapons[ index ] = mesh;
scope.meshWeapon = mesh;
scope.meshes.push( mesh );
checkLoadingComplete();
}
}
for ( var i = 0; i < config.weapons.length; i ++ ) {
loader.load( config.baseUrl + config.weapons[ i ][ 0 ], generateCallback( i, config.weapons[ i ][ 0 ] ) );
}
};
this.setPlaybackRate = function ( rate ) {
if ( this.meshBody ) this.meshBody.duration = this.meshBody.baseDuration / rate;
if ( this.meshWeapon ) this.meshWeapon.duration = this.meshWeapon.baseDuration / rate;
};
this.setWireframe = function ( wireframeEnabled ) {
if ( wireframeEnabled ) {
if ( this.meshBody ) this.meshBody.material = this.meshBody.materialWireframe;
if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialWireframe;
} else {
if ( this.meshBody ) this.meshBody.material = this.meshBody.materialTexture;
if ( this.meshWeapon ) this.meshWeapon.material = this.meshWeapon.materialTexture;
}
};
this.setSkin = function( index ) {
if ( this.meshBody && this.meshBody.material.wireframe === false ) {
this.meshBody.material.map = this.skinsBody[ index ];
this.currentSkin = index;
}
};
this.setWeapon = function ( index ) {
for ( var i = 0; i < this.weapons.length; i ++ ) this.weapons[ i ].visible = false;
var activeWeapon = this.weapons[ index ];
if ( activeWeapon ) {
activeWeapon.visible = true;
this.meshWeapon = activeWeapon;
if ( this.activeAnimation ) {
activeWeapon.playAnimation( this.activeAnimation );
this.meshWeapon.setAnimationTime( this.activeAnimation, this.meshBody.getAnimationTime( this.activeAnimation ) );
}
}
};
this.setAnimation = function ( animationName ) {
if ( animationName === this.activeAnimation || !animationName ) return;
if ( this.meshBody ) {
this.meshBody.setAnimationWeight( animationName, 0 );
this.meshBody.playAnimation( animationName );
this.oldAnimation = this.activeAnimation;
this.activeAnimation = animationName;
this.blendCounter = this.transitionFrames;
}
if ( this.meshWeapon ) {
this.meshWeapon.setAnimationWeight( animationName, 0 );
this.meshWeapon.playAnimation( animationName );
}
};
this.update = function ( delta ) {
if ( this.controls ) this.updateMovementModel( delta );
if ( this.animations ) {
this.updateBehaviors( delta );
this.updateAnimations( delta );
}
};
this.updateAnimations = function ( delta ) {
var mix = 1;
if ( this.blendCounter > 0 ) {
mix = ( this.transitionFrames - this.blendCounter ) / this.transitionFrames;
this.blendCounter -= 1;
}
if ( this.meshBody ) {
this.meshBody.update( delta );
this.meshBody.setAnimationWeight( this.activeAnimation, mix );
this.meshBody.setAnimationWeight( this.oldAnimation, 1 - mix );
}
if ( this.meshWeapon ) {
this.meshWeapon.update( delta );
this.meshWeapon.setAnimationWeight( this.activeAnimation, mix );
this.meshWeapon.setAnimationWeight( this.oldAnimation, 1 - mix );
}
};
this.updateBehaviors = function ( delta ) {
var controls = this.controls;
var animations = this.animations;
var moveAnimation, idleAnimation;
// crouch vs stand
if ( controls.crouch ) {
moveAnimation = animations[ "crouchMove" ];
idleAnimation = animations[ "crouchIdle" ];
} else {
moveAnimation = animations[ "move" ];
idleAnimation = animations[ "idle" ];
}
// actions
if ( controls.jump ) {
moveAnimation = animations[ "jump" ];
idleAnimation = animations[ "jump" ];
}
if ( controls.attack ) {
if ( controls.crouch ) {
moveAnimation = animations[ "crouchAttack" ];
idleAnimation = animations[ "crouchAttack" ];
} else {
moveAnimation = animations[ "attack" ];
idleAnimation = animations[ "attack" ];
}
}
// set animations
if ( controls.moveForward || controls.moveBackward || controls.moveLeft || controls.moveRight ) {
if ( this.activeAnimation !== moveAnimation ) {
this.setAnimation( moveAnimation );
}
}
if ( Math.abs( this.speed ) < 0.2 * this.maxSpeed && !( controls.moveLeft || controls.moveRight ) ) {
if ( this.activeAnimation !== idleAnimation ) {
this.setAnimation( idleAnimation );
}
}
// set animation direction
if ( controls.moveForward ) {
if ( this.meshBody ) {
this.meshBody.setAnimationDirectionForward( this.activeAnimation );
this.meshBody.setAnimationDirectionForward( this.oldAnimation );
}
if ( this.meshWeapon ) {
this.meshWeapon.setAnimationDirectionForward( this.activeAnimation );
this.meshWeapon.setAnimationDirectionForward( this.oldAnimation );
}
}
if ( controls.moveBackward ) {
if ( this.meshBody ) {
this.meshBody.setAnimationDirectionBackward( this.activeAnimation );
this.meshBody.setAnimationDirectionBackward( this.oldAnimation );
}
if ( this.meshWeapon ) {
this.meshWeapon.setAnimationDirectionBackward( this.activeAnimation );
this.meshWeapon.setAnimationDirectionBackward( this.oldAnimation );
}
}
};
this.updateMovementModel = function ( delta ) {
var controls = this.controls;
// speed based on controls
if ( controls.crouch ) this.maxSpeed = this.crouchSpeed;
else this.maxSpeed = this.walkSpeed;
this.maxReverseSpeed = -this.maxSpeed;
if ( controls.moveForward ) this.speed = THREE.Math.clamp( this.speed + delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
if ( controls.moveBackward ) this.speed = THREE.Math.clamp( this.speed - delta * this.backAcceleration, this.maxReverseSpeed, this.maxSpeed );
// orientation based on controls
// (don't just stand while turning)
var dir = 1;
if ( controls.moveLeft ) {
this.bodyOrientation += delta * this.angularSpeed;
this.speed = THREE.Math.clamp( this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
}
if ( controls.moveRight ) {
this.bodyOrientation -= delta * this.angularSpeed;
this.speed = THREE.Math.clamp( this.speed + dir * delta * this.frontAcceleration, this.maxReverseSpeed, this.maxSpeed );
}
// speed decay
if ( ! ( controls.moveForward || controls.moveBackward ) ) {
if ( this.speed > 0 ) {
var k = exponentialEaseOut( this.speed / this.maxSpeed );
this.speed = THREE.Math.clamp( this.speed - k * delta * this.frontDecceleration, 0, this.maxSpeed );
} else {
var k = exponentialEaseOut( this.speed / this.maxReverseSpeed );
this.speed = THREE.Math.clamp( this.speed + k * delta * this.backAcceleration, this.maxReverseSpeed, 0 );
}
}
// displacement
var forwardDelta = this.speed * delta;
this.root.position.x += Math.sin( this.bodyOrientation ) * forwardDelta;
this.root.position.z += Math.cos( this.bodyOrientation ) * forwardDelta;
// steering
this.root.rotation.y = this.bodyOrientation;
};
// internal helpers
function loadTextures( baseUrl, textureUrls ) {
var mapping = new THREE.UVMapping();
var textures = [];
for ( var i = 0; i < textureUrls.length; i ++ ) {
textures[ i ] = THREE.ImageUtils.loadTexture( baseUrl + textureUrls[ i ], mapping, checkLoadingComplete );
textures[ i ].name = textureUrls[ i ];
}
return textures;
};
function createPart( geometry, skinMap ) {
geometry.computeMorphNormals();
var whiteMap = THREE.ImageUtils.generateDataTexture( 1, 1, new THREE.Color( 0xffffff ) );
var materialWireframe = new THREE.MeshPhongMaterial( { color: 0xffaa00, specular: 0x111111, shininess: 50, wireframe: true, shading: THREE.SmoothShading, map: whiteMap, morphTargets: true, morphNormals: true, perPixel: true, metal: true } );
var materialTexture = new THREE.MeshPhongMaterial( { color: 0xffffff, specular: 0x111111, shininess: 50, wireframe: false, shading: THREE.SmoothShading, map: skinMap, morphTargets: true, morphNormals: true, perPixel: true, metal: true } );
materialTexture.wrapAround = true;
//
var mesh = new THREE.MorphBlendMesh( geometry, materialTexture );
mesh.rotation.y = -Math.PI/2;
//
mesh.materialTexture = materialTexture;
mesh.materialWireframe = materialWireframe;
//
mesh.autoCreateAnimations( scope.animationFPS );
return mesh;
};
function checkLoadingComplete() {
scope.loadCounter -= 1;
if ( scope.loadCounter === 0 ) scope.onLoadComplete();
};
function exponentialEaseOut( k ) { return k === 1 ? 1 : - Math.pow( 2, - 10 * k ) + 1; }
};
|
/*
* gulp-po2json-angular-translate
* https://github.com/rocwong/gulp-po2json-angular-translate
*
* based on grunt-po2json-angular-translate v0.0.3
* https://github.com/angular-translate/grunt-po2json-angular-translate
*
* Copyright (c) 2015 rocwong
* Licensed under the MIT license.
*/
'use strict';
var through = require('through2');
var pluginError = require('gulp-util').PluginError;
var _ = require('lodash');
var po = require('node-po');
var path = require('path');
var PLUGIN_NAME = 'gulp-po2json-angular-translate';
function po2Json(options) {
options = _.extend({
pretty: false,
fuzzy: false,
upperCaseId : false,
stringify : true,
offset : 0,
enableAltPlaceholders: true,
placeholderStructure: ['{','}']
}, options);
var replacePlaceholder = function(string, openingMark, closingMark,altEnabled){
if (closingMark !== undefined &&
altEnabled &&
string.indexOf(closingMark !== -1)){
if (string.indexOf(openingMark) !== -1){
var regOpening = new RegExp(openingMark,'g');
string = string.replace(regOpening,'{{');
}
if (string.indexOf(closingMark) !== -1){
var regClosing = new RegExp(closingMark,'g');
string = string.replace(regClosing,'}}');
}
}
//If there is no closing mark, then we have standard format: %0,
//if(string.indexOf(closingMark === -1)){
// var pattern ='\\%([0-9]|[a-z])';
// var re = new RegExp(pattern,'g');
// var index = string.indexOf(re);
// var substr = string.substr(index,index+2);
// string = string.replace(re, '{{'+substr+'}}');
//}
return string;
};
return through.obj(function(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new pluginError(PLUGIN_NAME, 'Streaming not supported'));
return cb();
}
var singleFile = false;
var singleFileStrings = {};
var catalog = po.parse(file.contents.toString());
var strings = {};
for (var i = 0; i < catalog.items.length; i++) {
var item = catalog.items[i];
if (options.upperCaseId){
item.msgid = item.msgid.toUpperCase();
}
if (item.msgid_plural!== null && item.msgstr.length > 1){
var singular_words = item.msgstr[0].split(' ');
var plural_words = item.msgstr[1].split(' ');
var pluralizedStr = '';
var numberPlaceHolder = false;
if (singular_words.length !== plural_words.length){
this.emit('error', new pluginError(PLUGIN_NAME, 'Either the singular or plural string had more words in the msgid: ' + item.msgid + ', the extra words were omitted'));
}
for (var x = 0; x < singular_words.length; x++){
if(singular_words[x] === undefined || plural_words[x] === undefined){
continue;
}
if (plural_words[x].indexOf('%d') !== -1){
numberPlaceHolder = true;
continue;
}
if (singular_words[x] !== plural_words[x]){
var p = '';
if (numberPlaceHolder){
p = '# ';
numberPlaceHolder = false;
}
var strPl = 'PLURALIZE, plural, offset:'+options.offset;
pluralizedStr += '{'+ strPl + ' =1{' + p + singular_words[x]+'}' +
' other{' + p + plural_words[x] +'}}';
}else{
pluralizedStr += singular_words[x];
}
if (x !== singular_words.length - 1 ){
pluralizedStr += ' ';
}
}
//pluralizedStr = replacePlaceholder(pluralizedStr,options.placeholderStructure[0],options.placeholderStructure[1],options.enableAltPlaceholders);
strings[item.msgid] = pluralizedStr ;
if (singleFile){
singleFileStrings[item.msgid]= pluralizedStr;
}
}else{
var message = item.msgstr.length === 1 ? item.msgstr[0] : item.msgstr;
message = replacePlaceholder(message,options.placeholderStructure[0],options.placeholderStructure[1],options.enableAltPlaceholders);
strings[item.msgid] = message;
if (singleFile){
singleFileStrings[item.msgid]=message;
}
}
}
file.contents = new Buffer(JSON.stringify(strings, null, (options.pretty) ? 2: ''));
var dirname = path.dirname(file.path);
var basename = path.basename(file.path, '.po');
file.path = path.join(dirname, basename + '.json');
this.push(file);
cb();
});
}
module.exports = po2Json; |
import React from 'react'
const ForeverPage = () => <p>This page was rendered for a while!</p>
ForeverPage.getInitialProps = async () => {
await new Promise(resolve => {
setTimeout(resolve, 3000)
})
return {}
}
export default ForeverPage
|
/**
* Author: froncheek
* Date: 7/8/12
* Time: 4:49 PM
* To change this template use File | Settings | File Templates.
**/
// {js:leya}
(function(undefined) {
var CONST = {
complete: 'complete'
};
var win = window,
doc = document,
loc = location,
nav = navigator,
ua = nav.userAgent,
ly = function() {},
eventListeners = {};
ly.fn = ly.prototype;
ly.fn.version = '1.1';
ly.fn.extend = function(/*source, [,(abstract,sealed...]*/) {
var args = arguments,
d = args[0],
s;
if(Object.prototype.isExtensible && !Object.isExtensible(d)) {
return false;
}
for(var i=1, len = args.length; i < len;) {
s = args[i++];
for(var p in s) {
d[p] = s[p];
}
}
return d;
};
ly.fn.extend(ly.fn, {
onlyIn1_1: function() {
console.log('This version is ' + leya.version);
},
addEvent: function(/*type, listener, [useCapture], [aWantsUntrusted]*/) {
if(document.addEventListener) {
eventListeners.ready = 'DOMContentLoaded';
return function(t, l, u, a) {
document.addEventListener(t, l, u, a);
return this;
};
} else {
eventListeners.ready = 'readystatechange';
return function(t, l) {
document.attachEvent('on' + t, l);
return this;
};
}
}(),
removeEvent: function() {
if(document.removeEventListener) {
return function(t, l, u, a) {
document.removeEventListener(t, l, u, a);
return this;
};
} else {
return function(t, l) {
document.detachEvent('on' + t, l);
return this;
};
}
}(),
ready: function(fn) {
if(leya.isDocReady && document.body) {
fn.call(window);
return;
}
leya.isDocReady = true;
leya.addEvent(eventListeners.ready, function() {
if (document.readyState === CONST.complete || document.body) {
leya.removeEvent(eventListeners.ready, arguments.callee);
fn.call(window);
}
}, false);
},
each: function(o, fn, sc) {
var len = o.length,
isObj = len === undefined || this.isObject(o);
if(isObj) {
for(var key in o) {
var val = o[key];
if(fn.call(sc || val, val, key) === false) {
return val;
}
}
} else {
for(var i = 0; i < len;) {
if(fn.call(sc || o, o[i], i++) === false) {
return o;
}
}
}
},
isArray: function(o) {
return Array.isArray(o);
},
isFunction: function(f) {
return !!(f && f.constructor && f.call && f.apply);
},
isNumber: function(n) {
return (typeof n == 'string' || typeof n == 'number') && !isNaN(n - 0) && n !== '';
},
isString: function(s) {
return (typeof(s) === 'string');
},
isObject: function(o) {
return (o instanceof Object) && !this.isArray(o) && !this.isFunction(o);
},
isNs: function(ns) {
return /^[a-zA-Z]+([a-zA-Z\.]+([a-zA-Z]+))$/.test(ns);
},
isClass: function() {
var ns;
return (arguments.length >= 2 && this.isString(ns = arguments[0]) && ns && this.isNs(ns));
},
isDefProp: function() {
},
/*getBrowserEvent: function() {
if(arguments.length) {
return eventListeners[arguments[0]];
}
return eventListeners;
},*/
getBody: function() {
/*var body;
if(!body = document.body) {
} else {
return body;
}*/
},
ns: function(n, o) {
o = o || window;
if(n) {
n = n.split('.');
for(var i=0, len = n.length; i < len;) {
o = o[n[i]] = o[n[i++]] || {};
}
}
return o;
},
splitns: function(n) {
var ns1 = (n = n.trim()).substr(0, n.lastIndexOf('.')),
len = ns1.length;
return [ns1, n.substr(ns1 ? len + 1 : 0, n.length - len)];
},
setVersion: function(/* Version */) {
var v = arguments[0],
lyv;
if(leya.version != v) {
if(v = leya.ly[v]) {
lyv = leya.ly;
delete leya.ly;
lyv[leya.version] = leya;
leya = v;
leya.ly = lyv;
}
}
},
useVersion: function(v, fn) {
var otherVersion, temp;
if(!(otherVersion = leya.ly[v]) && !fn && ! leya.isFunction(fn)) {
return;
}
temp = leya;
leya = otherVersion;
fn.call(leya, otherVersion, temp);
leya = temp;
},
initClass: function() {
var _createConstructor = function() {
return function() {
this.init.apply(
leya.extend(this, leya.isObject(arguments[0]) ? arguments[0] : {})
);
};
}, fn;
ly.fn.extend(ly.fn, {
abstract: function(ns, o) {
if(this.isClass.apply(this, arguments)) {
fn = _createConstructor();
ns = this.splitns(ns);
fn.prototype = o;
o = this.ns(ns[0], o.copyTo);
o[ns[1]] = fn;
}
},
override: function() {
return function() {
if(this.isClass.apply(this, arguments)) {
fn = _createConstructor();
//this.extend({}, )
}
};
}()
});
return true;
}()
});
if(window.leya) {
var version;
if(leya.version != (version = ly.fn.version)) {
leya.ly = leya.ly || {};
if(!leya.ly[version]) {
leya.ly[version] = new ly();
}
}
} else {
window.leya = new ly();
}
})(); |
'use strict';
angular.module("ngLocale", [], ["$provide", function ($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u05dc\u05e4\u05e0\u05d4\u05f4\u05e6",
"\u05d0\u05d7\u05d4\u05f4\u05e6"
],
"DAY": [
"\u05d9\u05d5\u05dd \u05e8\u05d0\u05e9\u05d5\u05df",
"\u05d9\u05d5\u05dd \u05e9\u05e0\u05d9",
"\u05d9\u05d5\u05dd \u05e9\u05dc\u05d9\u05e9\u05d9",
"\u05d9\u05d5\u05dd \u05e8\u05d1\u05d9\u05e2\u05d9",
"\u05d9\u05d5\u05dd \u05d7\u05de\u05d9\u05e9\u05d9",
"\u05d9\u05d5\u05dd \u05e9\u05d9\u05e9\u05d9",
"\u05d9\u05d5\u05dd \u05e9\u05d1\u05ea"
],
"ERANAMES": [
"\u05dc\u05e4\u05e0\u05d9 \u05d4\u05e1\u05e4\u05d9\u05e8\u05d4",
"\u05dc\u05e1\u05e4\u05d9\u05e8\u05d4"
],
"ERAS": [
"\u05dc\u05e4\u05e0\u05d4\u05f4\u05e1",
"\u05dc\u05e1\u05e4\u05d9\u05e8\u05d4"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"\u05d9\u05e0\u05d5\u05d0\u05e8",
"\u05e4\u05d1\u05e8\u05d5\u05d0\u05e8",
"\u05de\u05e8\u05e5",
"\u05d0\u05e4\u05e8\u05d9\u05dc",
"\u05de\u05d0\u05d9",
"\u05d9\u05d5\u05e0\u05d9",
"\u05d9\u05d5\u05dc\u05d9",
"\u05d0\u05d5\u05d2\u05d5\u05e1\u05d8",
"\u05e1\u05e4\u05d8\u05de\u05d1\u05e8",
"\u05d0\u05d5\u05e7\u05d8\u05d5\u05d1\u05e8",
"\u05e0\u05d5\u05d1\u05de\u05d1\u05e8",
"\u05d3\u05e6\u05de\u05d1\u05e8"
],
"SHORTDAY": [
"\u05d9\u05d5\u05dd \u05d0\u05f3",
"\u05d9\u05d5\u05dd \u05d1\u05f3",
"\u05d9\u05d5\u05dd \u05d2\u05f3",
"\u05d9\u05d5\u05dd \u05d3\u05f3",
"\u05d9\u05d5\u05dd \u05d4\u05f3",
"\u05d9\u05d5\u05dd \u05d5\u05f3",
"\u05e9\u05d1\u05ea"
],
"SHORTMONTH": [
"\u05d9\u05e0\u05d5\u05f3",
"\u05e4\u05d1\u05e8\u05f3",
"\u05de\u05e8\u05e5",
"\u05d0\u05e4\u05e8\u05f3",
"\u05de\u05d0\u05d9",
"\u05d9\u05d5\u05e0\u05d9",
"\u05d9\u05d5\u05dc\u05d9",
"\u05d0\u05d5\u05d2\u05f3",
"\u05e1\u05e4\u05d8\u05f3",
"\u05d0\u05d5\u05e7\u05f3",
"\u05e0\u05d5\u05d1\u05f3",
"\u05d3\u05e6\u05de\u05f3"
],
"STANDALONEMONTH": [
"\u05d9\u05e0\u05d5\u05d0\u05e8",
"\u05e4\u05d1\u05e8\u05d5\u05d0\u05e8",
"\u05de\u05e8\u05e5",
"\u05d0\u05e4\u05e8\u05d9\u05dc",
"\u05de\u05d0\u05d9",
"\u05d9\u05d5\u05e0\u05d9",
"\u05d9\u05d5\u05dc\u05d9",
"\u05d0\u05d5\u05d2\u05d5\u05e1\u05d8",
"\u05e1\u05e4\u05d8\u05de\u05d1\u05e8",
"\u05d0\u05d5\u05e7\u05d8\u05d5\u05d1\u05e8",
"\u05e0\u05d5\u05d1\u05de\u05d1\u05e8",
"\u05d3\u05e6\u05de\u05d1\u05e8"
],
"WEEKENDRANGE": [
4,
5
],
"fullDate": "EEEE, d \u05d1MMMM y",
"longDate": "d \u05d1MMMM y",
"medium": "d \u05d1MMM y H:mm:ss",
"mediumDate": "d \u05d1MMM y",
"mediumTime": "H:mm:ss",
"short": "d.M.y H:mm",
"shortDate": "d.M.y",
"shortTime": "H:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20aa",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "he",
"localeID": "he",
"pluralCat": function (n, opt_precision) {
var i = n | 0;
var vf = getVF(n, opt_precision);
if (i == 1 && vf.v == 0) {
return PLURAL_CATEGORY.ONE;
}
if (i == 2 && vf.v == 0) {
return PLURAL_CATEGORY.TWO;
}
if (vf.v == 0 && (n < 0 || n > 10) && n % 10 == 0) {
return PLURAL_CATEGORY.MANY;
}
return PLURAL_CATEGORY.OTHER;
}
});
}]);
|
/**
* @title WET-BOEW Events Calendar
* @overview Dynamically generates a calendar interface for navigating a list of events.
* @license wet-boew.github.io/wet-boew/License-en.html / wet-boew.github.io/wet-boew/Licence-fr.html
* @author WET Community
*/
(function( $, window, wb ) {
"use strict";
/*
* Variable and function definitions.
* These are global to the plugin - meaning that they will be initialized once per page,
* not once per instance of plugin on the page. So, this is a good place to define
* variables that are common to all instances of the plugin on a page.
*/
var componentName = "wb-calevt",
selector = "." + componentName,
initEvent = "wb-init" + selector,
evDetails = "ev-details",
$document = wb.doc,
i18n, i18nText,
/**
* @method init
* @param {jQuery Event} event Event that triggered this handler
*/
init = function( event ) {
// Start initialization
// returns DOM object = proceed with init
// returns undefined = do not proceed with init (e.g., already initialized)
var elm = wb.init( event, componentName, selector ),
$elm;
if ( elm ) {
$elm = $( elm );
// Only initialize the i18nText once
if ( !i18nText ) {
i18n = wb.i18n;
i18nText = {
monthNames: i18n( "mnths" ),
calendar: i18n( "cal" )
};
}
// Load ajax content
$.when.apply( $, $.map( $elm.find( "[data-calevt]" ), getAjax ) )
.always( function() {
processEvents( $elm );
// Identify that initialization has completed
wb.ready( $elm, componentName );
});
}
},
getAjax = function( ajaxContainer ) {
var $ajaxContainer = $( ajaxContainer ),
urls = $ajaxContainer.data( "calevt" ).split( /\s+/ ),
dfd = $.Deferred(),
len = urls.length,
promises = [],
i, appendData;
appendData = function( data ) {
$ajaxContainer.append( $.trim( data ) );
};
for ( i = 0; i < len; i += 1 ) {
promises.push( $.get( urls[ i ], appendData, "html" ) );
}
$.when.apply( $, promises ).always(function() {
dfd.resolve();
});
return dfd.promise();
},
processEvents = function( $elm ) {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth(),
elmYear = $elm.find( ".year" ),
elmMonth = $elm.find( ".month" ),
events, containerId, $container;
if ( elmYear.length > 0 && elmMonth.length > 0 ) {
// We are going to assume this is always a number.
year = elmYear.text();
month = elmMonth.hasClass( "textformat" ) ? $.inArray( elmMonth.text(), i18nText.monthNames ) : elmMonth.text() - 1;
}
events = getEvents( $elm );
containerId = $elm.data( "calevtSrc" );
$container = $( "#" + containerId )
.addClass( componentName + "-cal" )
.data( "calEvents", events );
$document.trigger( "create.wb-cal", [
containerId,
year,
month,
true,
events.minDate,
events.maxDate
]
);
$container.attr( "aria-label", i18nText.calendar );
},
daysBetween = function( dateLow, dateHigh ) {
// Simplified conversion to date object
var date1 = wb.date.convert( dateLow ),
date2 = wb.date.convert( dateHigh ),
dstAdjust = 0,
oneMinute = 1000 * 60,
oneDay = oneMinute * 60 * 24,
diff;
// Equalize times in case date objects have them
date1.setHours( 0 );
date1.setMinutes( 0 );
date1.setSeconds( 0 );
date2.setHours( 0 );
date2.setMinutes( 0 );
date2.setSeconds( 0 );
// Take care of spans across Daylight Saving Time changes
if ( date2 > date1 ) {
dstAdjust = ( date2.getTimezoneOffset() - date1.getTimezoneOffset() ) * oneMinute;
} else {
dstAdjust = ( date1.getTimezoneOffset() - date2.getTimezoneOffset() ) * oneMinute;
}
diff = Math.abs( date2.getTime() - date1.getTime() ) - dstAdjust;
return Math.ceil( diff / oneDay );
},
getEvents = function( obj ) {
var directLinking = !( $( obj ).hasClass( "evt-anchor" ) ),
events = {
minDate: null,
maxDate: null,
iCount: 0,
list: [
{
a: 1
}
]
},
objEventsList = null;
if ( obj.find( "ol" ).length > 0 ) {
objEventsList = obj.find( "ol" );
} else if ( obj.find( "ul" ).length > 0 ) {
objEventsList = obj.find( "ul" );
}
if ( objEventsList.length > 0 ) {
objEventsList.children( "li" ).each(function() {
var event = $( this ),
objTitle = event.find( "*:header:first" ),
title = objTitle.text(),
origLink = event.find( "a" ).first(),
link = origLink.attr( "href" ),
linkId, date, tCollection, $tCollection, tCollectionTemp,
strDate1, strDate2, strDate, z, zLen, className;
/*
* Modification direct-linking or page-linking
* - added the ability to have class set the behaviour of the links
* - default is to use the link of the item as the event link in the calendar
* - 'evt-anchor' class dynamically generates page anchors on the links it maps to the event
*/
if ( !directLinking ) {
linkId = event.attr( "id" ) || wb.guid();
event.attr( "id", linkId );
/*
* Fixes IE tabbing error:
* http://www.earthchronicle.com/ECv1point8/Accessibility01IEAnchoredKeyboardNavigation.aspx
*/
if ( wb.ie ) {
event.attr( "tabindex", "-1" );
}
link = "#" + linkId;
}
date = new Date();
date.setHours( 0, 0, 0, 0 );
tCollection = event.find( "time" );
/*
* Date spanning capability
* - since there maybe some dates that are capable of spanning over months we need to identify them
* the process is see how many time nodes are in the event. 2 nodes will trigger a span
*/
if ( tCollection.length > 1 ) {
// This is a spanning event
tCollectionTemp = tCollection[ 0 ];
strDate1 = tCollectionTemp.nodeName.toLowerCase() === "time" ?
$( tCollectionTemp ).attr( "datetime" ).substr( 0, 10 ).split( "-" ) :
$( tCollectionTemp ).attr( "class" ).match( /datetime\s+\{date\:\s*(\d+-\d+-\d+)\}/ )[ 1 ].substr( 0, 10 ).split( "-" );
tCollectionTemp = tCollection[ 1 ];
strDate2 = tCollectionTemp.nodeName.toLowerCase() === "time" ?
$( tCollectionTemp ).attr( "datetime" ).substr( 0, 10 ).split( "-" ) :
$( tCollectionTemp ).attr( "class" ).match( /datetime\s+\{date\:\s*(\d+-\d+-\d+)\}/ )[ 1 ].substr( 0, 10 ).split( "-" );
// Convert to zero-base month
strDate1[ 1 ] = strDate1[ 1 ] - 1;
strDate2[ 1 ] = strDate2[ 1 ] - 1;
date.setFullYear( strDate1[ 0 ], strDate1[ 1 ], strDate1[ 2 ] );
// Now loop in events to load up all the days that it would be on tomorrow.setDate(tomorrow.getDate() + 1);
for ( z = 0, zLen = daysBetween( strDate1, strDate2 ); z <= zLen; z += 1 ) {
if ( events.minDate === null || date < events.minDate ) {
events.minDate = date;
}
if ( events.maxDate === null || date > events.maxDate ) {
events.maxDate = date;
}
events.list[ events.iCount ] = {
title: title,
date: new Date( date.getTime() ),
href: link
};
date = new Date( date.setDate( date.getDate() + 1 ) );
// Add a viewfilter
className = "filter-" + ( date.getFullYear() ) + "-" +
wb.string.pad( date.getMonth() + 1, 2 );
if ( !objTitle.hasClass( className ) ) {
objTitle.addClass( className );
}
events.iCount += 1;
}
} else if ( tCollection.length === 1 ) {
$tCollection = $( tCollection[ 0 ] );
strDate = ( $tCollection.get( 0 ).nodeName.toLowerCase() === "time" ) ?
$tCollection.attr( "datetime" ).substr( 0, 10 ).split( "-" ) :
$tCollection.attr( "class" ).match(/datetime\s+\{date\:\s*(\d+-\d+-\d+)\}/)[ 1 ].substr( 0, 10 ).split( "-" );
date.setFullYear( strDate[ 0 ], strDate[ 1 ] - 1, strDate[ 2 ] );
if ( events.minDate === null || date < events.minDate ) {
events.minDate = date;
}
if ( events.maxDate === null || date > events.maxDate ) {
events.maxDate = date;
}
events.list[ events.iCount ] = {
title: title,
date: date,
href: link
};
// Add a viewfilter
className = "filter-" + ( date.getFullYear() ) + "-" + wb.string.pad( date.getMonth() + 1, 2 );
if ( !objTitle.hasClass( className ) ) {
objTitle.addClass( className );
}
events.iCount += 1;
}
// End of loop through objects/events
});
}
window.events = events;
return events;
},
addEvents = function( year, month, days, containerId, eventsList ) {
var i, eLen, date, day, dayEvents, content;
// Fix required to make up with the IE z-index behaviour mismatch
for ( i = 0, eLen = days.length; i !== eLen; i += 1 ) {
days.eq( i ).css( "z-index", 31 - i );
}
/*
* Determines for each event, if it occurs in the display month
* Modification - the author used a jQuery native $.each function for
* looping. This is a great function, but has a tendency to like
* HTMLELEMENTS and jQuery objects better. We have modified this
* to a for loop to ensure that all the elements are accounted for.
*/
for ( i = 0, eLen = eventsList.length; i !== eLen; i += 1 ) {
date = new Date( eventsList[ i ].date );
if ( date.getMonth() === month && date.getFullYear() === year ) {
day = $( days[ date.getDate() - 1 ] );
// Lets see if the cell is empty. If so lets create the cell
if ( day.children( "a" ).length === 0 ) {
dayEvents = $( "<ul class='wb-inv'></ul>" );
content = day.children( "div" ).html();
day
.empty()
.append(
"<a href='#ev-" + day.attr( "id" ) +
"' class='cal-evt' tabindex='-1'>" +
content + "</a>",
dayEvents
);
} else {
/*
* Modification - added an else to the date find due to
* event collisions not being handled. So the pointer was
* getting lost.
*/
dayEvents = day.find( "ul.wb-inv" );
}
dayEvents.append( "<li><a tabindex='-1' class='cal-evt-lnk' href='" +
eventsList[ i ].href + "'>" + eventsList[ i ].title + "</a></li>" );
day.data( "dayEvents", dayEvents );
}
}
days.find( ".cal-evt" ).first().attr( "tabindex", "0" );
},
showOnlyEventsFor = function( year, month, calendarId ) {
$( "." + calendarId + " li.cal-disp-onshow" )
.addClass( "wb-inv" )
.has( ":header[class*=filter-" + year + "-" +
wb.string.pad( parseInt( month, 10 ) + 1, 2 ) + "]" )
.removeClass( "wb-inv" );
};
// Bind the init event of the plugin
$document.on( "timerpoke.wb " + initEvent, selector, init );
$document.on( "displayed.wb-cal", selector + "-cal", function( event, year, month, days, day ) {
// Filter out any events triggered by descendants
if ( event.currentTarget === event.target ) {
var target = event.target,
$target = $( target ),
containerId = target.id,
events = $target.data( "calEvents" );
addEvents( year, month, days, containerId, events.list );
showOnlyEventsFor( year, month, containerId );
$target.find( ".cal-index-" + day + " .cal-evt" ).trigger( "setfocus.wb" );
// Fire the wb-updated event on the wb-calevt element
$( selector ).filter( "[data-calevt-src='" + $target[ 0 ].id + "']" )
.trigger( "wb-updated" + selector );
}
});
$document.on( "focusin focusout", ".wb-calevt-cal .cal-days a", function( event ) {
var eventType = event.type,
dayEvents = $( event.target ).closest( "td" ).data( "dayEvents" );
switch ( eventType ) {
case "focusin":
dayEvents
.closest( ".cal-days" )
.find( "a[tabindex=0]" )
.attr( "tabindex", "-1" );
dayEvents
.removeClass( "wb-inv" )
.addClass( evDetails )
.find( "a" )
.attr( "tabindex", "0" );
dayEvents.prev( "a" ).attr( "tabindex", "0" );
break;
case "focusout":
setTimeout(function() {
if ( dayEvents.find( "a:focus" ).length === 0 ) {
dayEvents.removeClass( evDetails )
.addClass( "wb-inv" )
.find( "a" )
.attr( "tabindex", "-1" );
}
}, 5 );
break;
}
});
$document.on( "mouseover mouseout", ".wb-calevt-cal .cal-days td", function( event ) {
var target = event.currentTarget,
eventType = event.type,
dayEvents;
// Only handle calendar cells with events
if ( target.getElementsByTagName( "a" ).length !== 0 ) {
dayEvents = $( target ).data( "dayEvents" );
switch ( eventType ) {
case "mouseover":
dayEvents.dequeue()
.removeClass( "wb-inv" )
.addClass( evDetails );
break;
case "mouseout":
dayEvents.delay( 100 ).queue(function() {
$( this ).removeClass( evDetails )
.addClass( "wb-inv" )
.dequeue();
});
break;
}
}
});
// Add the timer poke to initialize the plugin
wb.add( selector );
})( jQuery, window, wb );
|
var path = require('path');
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 5000);
app.use(express.static(path.join(__dirname, 'public')));
app.listen(app.get('port'), function() {
console.log('Server listening on port', app.get('port'));
});
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function() {
$('#bEliminar').click(function() {
$('#dEliminarConfirmar').dialog('open');
});
$('#bBuscar')
.click(function() {
$('#dBuscar').dialog('open');
});
$('#bBuscar2').click(function() {
if (fValidarMinimo($('#buscar').val(), 3)) {
fBuscar();
} else {
fAlerta('Ingrese como mínimo 3 caracteres.');
}
});
$('#buscar').keypress(function(event) {
var key = event.charCode ? event.charCode : (event.keyCode ? event.keyCode : 0);
if (key == 13) {
if (fValidarMinimo($('#buscar').val(), 3)) {
fBuscar();
} else {
fAlerta('Ingrese como mínimo 3 caracteres.');
}
event.preventDefault();//para el caso de ie se ejecuta como enter al boton y se cerraba el dialog.
}
});
});
$(function() {
$('#dEliminarConfirmar').dialog({
autoOpen: false,
modal: true,
resizable: true,
height: 200,
width: 400,
buttons: {
Cancelar: function() {
$(this).dialog('close');
},
Borrar: function() {
fEliminar();
}
},
close: function() {
$(this).dialog('close');
}
});
$('#dBuscar').dialog({
autoOpen: false,
modal: true,
resizable: true,
height: 550,
width: 1000,
buttons: {
Cerrar: function() {
$(this).dialog('close');
}
},
close: function() {
$(this).dialog('close');
}
});
});
function fEliminar() {
var data = {
cDN: $('#codDocumentoNotificacion').val(),
accion: 'eliminar'
};
var url = '../sDN';
try {
$.ajax({
type: 'post',
url: url,
data: data,
beforeSend: function() {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
fAlerta(errorThrown + '()');
},
success: function(ajaxResponse, textStatus) {
$('#dEliminarConfirmar').dialog('close');
if ($.isNumeric(ajaxResponse)) {
$(location).attr('href', '../sDN?accion=mantenimiento¶metro=ultimo');
} else {
fAlerta(ajaxResponse);
}
},
statusCode: {
404: function() {
fErrorServidor('Página no encontrada(' + url + ').');
}
}
});
}
catch (ex) {
fErrorServidor(ex);
}
}
;
function fBuscar() {
var data = {
term: $('#buscar').val()
};
var url = 'ajax/buscar.jsp';
try {
$.ajax({
type: 'post',
url: url,
data: data,
beforeSend: function() {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
fAlerta(errorThrown + '()');
},
success: function(ajaxResponse, textStatus) {
$('#dCuerpo').empty().append(ajaxResponse);
},
statusCode: {
404: function() {
fErrorServidor('Página no encontrada(' + url + ').');
}
}
});
}
catch (ex) {
fErrorServidor(ex);
}
}
;
|
$(function () {
var loaded = false;
var sid = $('#vulnerability-container').data('scan');
fetch_analytics();
function fetch_analytics() {
if (sid == undefined) {
return;
}
$.ajax({
url: '/scan/' + sid + '/vulnerabilities/chart',
method: 'GET',
success: function(data) {
render_graph(data);
}
});
}
function render_graph(data) {
Highcharts.getOptions().colors = Highcharts.map(Highcharts.getOptions().colors, function (color) {
return {
radialGradient: {
cx: 0.5,
cy: 0.3,
r: 0.7
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.3).get('rgb')] // darken
]
};
});
Highcharts.setOptions({
colors: ['#50B432', '#ED561B', '#24CBE5', '#64E572', '#F3076B']
});
$('#vulnerability-container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: ''
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.y}',
style: {
color: 'black'
}
}
}
},
series: [{
name: 'Severity',
data: data
}]
});
}
});
|
import React from 'react';
import { shallow } from 'enzyme';
import Dialog, {
DialogActions,
} from 'material-ui/Dialog';
import IconButton from 'material-ui/IconButton';
import CategoryDeleter from './CategoryDeleter.js';
const setup = propOverrides => {
const props = Object.assign({
url: "path/to/resource",
handleDelete: jest.fn(),
}, propOverrides);
const wrapper = shallow(<CategoryDeleter {...props} />);
return wrapper;
}
// Smoke test:
it('renders without crashing', () => {
setup();
});
// Content:
it('displays a dialog only after clicking the delete button', () => {
let wrapper = setup();
let delBtn = wrapper.find(IconButton);
let dialog = wrapper.find(Dialog);
expect(dialog.prop('open')).toBeFalsy();
delBtn.simulate('click');
let postClickDialog = wrapper.find(Dialog);
expect(postClickDialog.prop('open')).toBeTruthy();
});
it('calls delete handler upon dialog confirmation', () => {
let wrapper = setup();
let confirmBtn = wrapper.find(DialogActions).childAt(1);
confirmBtn.simulate('click');
let handleDelete = wrapper.instance().props.handleDelete;
expect(handleDelete.mock.calls.length).toBe(1);
});
//
// it('closes a dialog after clicking Cancel button', () => {
// let wrapper = setup();
// let cancelBtn = wrapper.find(DialogActions).at(0);
// cancelBtn.simulate('click');
// let handleClose =
// })
|
var async = require('async')
var GitHub = require('github')
exports.child_process = require('child_process')
var parseRange = function(lines, done) {
var matches = lines.first().match(/^(@@.+@@\s?)(.+)?/)
lines[0] = matches[2] || null
//lines = lines.compact()
var scopes = matches[1].match(/^@@\s\-(\d+),(\d+)\s\+(\d+),(\d+)\s@@\s?$/)
var result = {
before: {
start: parseInt(scopes[1], 10),
total: parseInt(scopes[2], 10),
lines: []
},
after: {
start: parseInt(scopes[3], 10),
total: parseInt(scopes[4], 10),
lines: []
},
lines: lines
};
[result.before, result.after].each(function(s) {
s.end = s.start + s.total
})
lines.each(function(line, index) {
if (line) {
var blocks = [result.before, result.after];
if(line[0] == '+') blocks = [result.after];
else if(line[0] == '-') blocks = [result.before];
blocks.each(function(block) {
block.lines.push({
action: line[0],
diffindex: index + 1,
text: line.slice(1)
});
})
}
});
done(null, result)
}
var parseFile = function(lines, done) {
var name = lines.first().split(' ').last().remove(/^.\//)
var ranges = []
lines.each(function(line) {
if(line.startsWith('@@')) {
ranges.push([]) // start of a new range
}
if(ranges.last()) ranges.last().push(line)
})
async.mapSeries(ranges, parseRange, function(err, result) {
if(err) return done(err)
var diffindex = 0;
result.each(function(range) {
range.before.lines.each(function(line) {
line.diffindex = diffindex + line.diffindex;
});
range.after.lines.each(function(line) {
line.diffindex = diffindex + line.diffindex;
});
diffindex += range.lines.length;
});
done(null, {
name: name,
ranges: result
})
})
}
var parseDiff = function(diff, done) {
var files = []
var lines = diff.toString().split('\n')
lines.each(function(line) {
if(line.startsWith('diff')) {
files.push([]) // start of a new file to compare
}
files.last().push(line)
})
async.map(files, parseFile, done)
}
exports.diff = function(branch, base, done) {
exports.child_process.exec('git diff ' + base + ' origin/' + branch, function(err, stdout) {
if(err) return done(err)
parseDiff(stdout, done)
})
};
exports.filterComments = function(diff, comments, done) {
var githubcomments = comments.map(function(comment) {
var file = diff.find(function(file) {
return file.name == comment.file;
});
if(!file) return null;
var range = file.ranges.find(function(range) {
return range.after.start <= comment.error.line && comment.error.line < range.after.end;
});
if(!range) return null;
// console.log("Comment passed - range");
// console.dir(range)
// console.log("Comment passed - comment");
// console.dir(comment)
// console.log("Range after passed - comment- line")
// console.dir(range.after.lines)
// console.log("comment.error.line ")
// console.dir(comment.error.line )
var line = range.after.lines[comment.error.line - range.after.start]
// console.log("line")
// console.dir(line)
if(!line || line.action != '+') return null;
// console.log("Comment passed - line");
// console.dir(line)
comment.diffindex = line.diffindex;
return comment;
}).compact();
done(null, githubcomments);
}
exports.postComments = function(auth, githubcomments, done) {
var github = new GitHub({ version: '3.0.0', debug:true })
github.authenticate({
type: 'oauth',
token: auth.token
})
async.eachSeries(githubcomments, function(comment, next) {
if (!comment.file) {
console.log('A comment without file specified');
console.log(JSON.stringify(comment));
return next();
}
github.pullRequests.createComment({
user: auth.user,
repo: auth.repo,
number: auth.number,
commit_id: auth.commit_id,
body: comment.error.code + ': ' + comment.error.reason + '\n' + '```js\n' + (comment.error.evidence || '').trim(),
path: comment.file,
position: [comment.diffindex - 1, 0].max()
}, function(err, comment) {
if(err) console.log(err);
next(null, comment);
})
}, done);
}
exports.pullRequest = function(auth, done) {
var github = new GitHub({ version: '3.0.0' , debug: true })
github.authenticate({
type: 'oauth',
token: auth.token
})
github.pullRequests.get(auth, done);
}
|
function getArticleGenerator(arts) {
return function() {
if (arts.length === 0) {
return;
}
let article = $("<article>");
article.append($(`<p>${arts.shift()}</p>`))
$("#content").append(article);
}
} |
/*
* Copyright (c) 2015-2016 Chukong Technologies Inc.
*
* 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.
*/
//
// cocos2d boot
//
'use strict';
//+++++++++++++++++++++++++Engine initialization function begin+++++++++++++++++++++++++++
// Define singleton objects
cc.director = cc.Director.getInstance();
cc.director._actionManager = cc.director.getActionManager();
cc.director._scheduler = cc.director.getScheduler();
cc.winSize = cc.director.getWinSize();
cc.view = cc.director.getOpenGLView();
cc.view.getDevicePixelRatio = cc.view.getRetinaFactor;
cc.view.convertToLocationInView = function (tx, ty, relatedPos) {
var _devicePixelRatio = cc.view.getDevicePixelRatio();
return {x: _devicePixelRatio * (tx - relatedPos.left), y: _devicePixelRatio * (relatedPos.top + relatedPos.height - ty)};
};
cc.view.enableRetina = function(enabled) {};
cc.view.isRetinaEnabled = function() {
var sys = cc.sys;
return (sys.os === sys.OS_IOS || sys.os === sys.OS_OSX) ? true : false;
};
cc.view.adjustViewPort = function() {};
cc.view.resizeWithBrowserSize = function () {return;};
cc.view.setResizeCallback = function() {return;};
cc.view.enableAutoFullScreen = function () {return;};
cc.view.isAutoFullScreenEnabled = function() {return true;};
cc.view._setDesignResolutionSize = cc.view.setDesignResolutionSize;
cc.view.setDesignResolutionSize = function(width,height,resolutionPolicy){
cc.view._setDesignResolutionSize(width,height,resolutionPolicy);
cc.winSize = cc.director.getWinSize();
cc.visibleRect.init();
};
cc.view.setRealPixelResolution = cc.view.setDesignResolutionSize;
cc.view.setResolutionPolicy = function(resolutionPolicy){
var size = cc.view.getDesignResolutionSize();
cc.view.setDesignResolutionSize(size.width,size.height,resolutionPolicy);
};
cc.view.getCanvasSize = cc.view.getFrameSize;
cc.view.getVisibleSizeInPixel = cc.view.getVisibleSize;
cc.view.getVisibleOriginInPixel = cc.view.getVisibleOrigin;
cc.view.setContentTranslateLeftTop = function(){return;};
cc.view.getContentTranslateLeftTop = function(){return null;};
cc.view.setFrameZoomFactor = function(){return;};
cc.view.setOrientation = function () {};
cc.view.setTargetDensityDPI = function() {};
cc.view.getTargetDensityDPI = function() {return cc.macro.DENSITYDPI_DEVICE;};
cc.eventManager = cc.director.getEventDispatcher();
cc.eventManager.addCustomListener('window-resize', function () {
cc.winSize = cc.director.getWinSize();
cc.visibleRect.init();
});
cc.audioEngine = cc.AudioEngine.getInstance();
cc.audioEngine.end = function(){
this.stopMusic();
this.stopAllEffects();
};
cc.audioEngine.features = {
MULTI_CHANNEL: true,
AUTOPLAY: true
};
cc.configuration = cc.Configuration.getInstance();
cc.textureCache = cc.director.getTextureCache();
cc.shaderCache = cc.ShaderCache.getInstance();
cc.plistParser = cc.PlistParser.getInstance();
// File utils (Temporary, won't be accessible)
cc.fileUtils = cc.FileUtils.getInstance();
cc.fileUtils.setPopupNotify(false);
cc.screen = {
init: function() {},
fullScreen: function() {
return true;
},
requestFullScreen: function(element, onFullScreenChange) {
onFullScreenChange.call();
},
exitFullScreen: function() {
return false;
},
autoFullScreen: function(element, onFullScreenChange) {
onFullScreenChange.call();
}
};
/**
* @type {Object}
* @name jsb.fileUtils
* jsb.fileUtils is the native file utils singleton object,
* please refer to Cocos2d-x API to know how to use it.
* Only available in JSB
*/
jsb.fileUtils = cc.fileUtils;
delete cc.FileUtils;
delete cc.fileUtils;
/**
* @type {Object}
* @name jsb.reflection
* jsb.reflection is a bridge to let you invoke Java static functions.
* please refer to this document to know how to use it: http://www.cocos2d-x.org/docs/manual/framework/html5/v3/reflection/en
* Only available on Android platform
*/
jsb.reflection = {
callStaticMethod : function(){
cc.log("not supported on current platform");
}
};
//+++++++++++++++++++++++++Redefine JSB only APIs+++++++++++++++++++++++++++++
//+++++++++++++++++++++++++something about window events begin+++++++++++++++++++++++++++
cc.winEvents = {//TODO register hidden and show callback for window
hiddens : [],
shows : []
};
//+++++++++++++++++++++++++something about window events end+++++++++++++++++++++++++++++
//+++++++++++++++++++++++++something about sys begin+++++++++++++++++++++++++++++
var _initSys = function () {
cc.sys = window.sys || {};
var sys = cc.sys;
/**
* English language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_ENGLISH = "en";
/**
* Chinese language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_CHINESE = "zh";
/**
* French language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_FRENCH = "fr";
/**
* Italian language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_ITALIAN = "it";
/**
* German language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_GERMAN = "de";
/**
* Spanish language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_SPANISH = "es";
/**
* Netherlands language code
* @type {string}
*/
sys.LANGUAGE_DUTCH = "nl";
/**
* Dutch language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_DUTCH = "du";
/**
* Russian language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_RUSSIAN = "ru";
/**
* Korean language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_KOREAN = "ko";
/**
* Japanese language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_JAPANESE = "ja";
/**
* Hungarian language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_HUNGARIAN = "hu";
/**
* Portuguese language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_PORTUGUESE = "pt";
/**
* Arabic language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_ARABIC = "ar";
/**
* Norwegian language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_NORWEGIAN = "no";
/**
* Polish language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_POLISH = "pl";
/**
* Turkish language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_TURKISH = "tr";
/**
* Ukrainian language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_UKRAINIAN = "uk";
/**
* Romanian language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_ROMANIAN = "ro";
/**
* Bulgarian language code
* @constant
* @default
* @type {Number}
*/
sys.LANGUAGE_BULGARIAN = "bg";
/**
* Unknown language code
* @memberof cc.sys
* @name LANGUAGE_UNKNOWN
* @constant
* @type {Number}
*/
sys.LANGUAGE_UNKNOWN = "unknown";
/**
* @memberof cc.sys
* @name OS_IOS
* @constant
* @type {string}
*/
sys.OS_IOS = "iOS";
/**
* @memberof cc.sys
* @name OS_ANDROID
* @constant
* @type {string}
*/
sys.OS_ANDROID = "Android";
/**
* @memberof cc.sys
* @name OS_WINDOWS
* @constant
* @type {string}
*/
sys.OS_WINDOWS = "Windows";
/**
* @memberof cc.sys
* @name OS_MARMALADE
* @constant
* @type {string}
*/
sys.OS_MARMALADE = "Marmalade";
/**
* @memberof cc.sys
* @name OS_LINUX
* @constant
* @type {string}
*/
sys.OS_LINUX = "Linux";
/**
* @memberof cc.sys
* @name OS_BADA
* @constant
* @type {string}
*/
sys.OS_BADA = "Bada";
/**
* @memberof cc.sys
* @name OS_BLACKBERRY
* @constant
* @type {string}
*/
sys.OS_BLACKBERRY = "Blackberry";
/**
* @memberof cc.sys
* @name OS_OSX
* @constant
* @type {string}
*/
sys.OS_OSX = "OS X";
/**
* @memberof cc.sys
* @name OS_WP8
* @constant
* @type {string}
*/
sys.OS_WP8 = "WP8";
/**
* @memberof cc.sys
* @name OS_WINRT
* @constant
* @type {string}
*/
sys.OS_WINRT = "WINRT";
/**
* @memberof cc.sys
* @name OS_UNKNOWN
* @constant
* @type {string}
*/
sys.OS_UNKNOWN = "Unknown";
/**
* @memberof cc.sys
* @name UNKNOWN
* @constant
* @default
* @type {Number}
*/
sys.UNKNOWN = -1;
/**
* @memberof cc.sys
* @name WIN32
* @constant
* @default
* @type {Number}
*/
sys.WIN32 = 0;
/**
* @memberof cc.sys
* @name LINUX
* @constant
* @default
* @type {Number}
*/
sys.LINUX = 1;
/**
* @memberof cc.sys
* @name MACOS
* @constant
* @default
* @type {Number}
*/
sys.MACOS = 2;
/**
* @memberof cc.sys
* @name ANDROID
* @constant
* @default
* @type {Number}
*/
sys.ANDROID = 3;
/**
* @memberof cc.sys
* @name IOS
* @constant
* @default
* @type {Number}
*/
sys.IPHONE = 4;
/**
* @memberof cc.sys
* @name IOS
* @constant
* @default
* @type {Number}
*/
sys.IPAD = 5;
/**
* @memberof cc.sys
* @name BLACKBERRY
* @constant
* @default
* @type {Number}
*/
sys.BLACKBERRY = 6;
/**
* @memberof cc.sys
* @name NACL
* @constant
* @default
* @type {Number}
*/
sys.NACL = 7;
/**
* @memberof cc.sys
* @name EMSCRIPTEN
* @constant
* @default
* @type {Number}
*/
sys.EMSCRIPTEN = 8;
/**
* @memberof cc.sys
* @name TIZEN
* @constant
* @default
* @type {Number}
*/
sys.TIZEN = 9;
/**
* @memberof cc.sys
* @name WINRT
* @constant
* @default
* @type {Number}
*/
sys.WINRT = 10;
/**
* @memberof cc.sys
* @name WP8
* @constant
* @default
* @type {Number}
*/
sys.WP8 = 11;
/**
* @memberof cc.sys
* @name MOBILE_BROWSER
* @constant
* @default
* @type {Number}
*/
sys.MOBILE_BROWSER = 100;
/**
* @memberof cc.sys
* @name DESKTOP_BROWSER
* @constant
* @default
* @type {Number}
*/
sys.DESKTOP_BROWSER = 101;
sys.BROWSER_TYPE_WECHAT = "wechat";
sys.BROWSER_TYPE_ANDROID = "androidbrowser";
sys.BROWSER_TYPE_IE = "ie";
sys.BROWSER_TYPE_QQ = "qqbrowser";
sys.BROWSER_TYPE_MOBILE_QQ = "mqqbrowser";
sys.BROWSER_TYPE_UC = "ucbrowser";
sys.BROWSER_TYPE_360 = "360browser";
sys.BROWSER_TYPE_BAIDU_APP = "baiduboxapp";
sys.BROWSER_TYPE_BAIDU = "baidubrowser";
sys.BROWSER_TYPE_MAXTHON = "maxthon";
sys.BROWSER_TYPE_OPERA = "opera";
sys.BROWSER_TYPE_OUPENG = "oupeng";
sys.BROWSER_TYPE_MIUI = "miuibrowser";
sys.BROWSER_TYPE_FIREFOX = "firefox";
sys.BROWSER_TYPE_SAFARI = "safari";
sys.BROWSER_TYPE_CHROME = "chrome";
sys.BROWSER_TYPE_LIEBAO = "liebao";
sys.BROWSER_TYPE_QZONE = "qzone";
sys.BROWSER_TYPE_SOUGOU = "sogou";
sys.BROWSER_TYPE_UNKNOWN = "unknown";
/**
* Is native ? This is set to be true in jsb auto.
* @constant
* @default
* @type {Boolean}
*/
sys.isNative = true;
var platform = sys.platform = __getPlatform();
/**
* Indicate whether system is mobile system
* @memberof cc.sys
* @name isMobile
* @type {Boolean}
*/
sys.isMobile = (platform === sys.ANDROID ||
platform === sys.IPAD ||
platform === sys.IPHONE ||
platform === sys.WP8 ||
platform === sys.TIZEN ||
platform === sys.BLACKBERRY) ? true : false;
sys._application = cc.Application.getInstance();
/**
* Indicate the current language of the running system
* @memberof cc.sys
* @name language
* @type {String}
*/
sys.language = (function(){
var language = sys._application.getCurrentLanguage();
switch(language){
case 0: return sys.LANGUAGE_ENGLISH;
case 1: return sys.LANGUAGE_CHINESE;
case 2: return sys.LANGUAGE_FRENCH;
case 3: return sys.LANGUAGE_ITALIAN;
case 4: return sys.LANGUAGE_GERMAN;
case 5: return sys.LANGUAGE_SPANISH;
case 6: return sys.LANGUAGE_DUTCH;
case 7: return sys.LANGUAGE_RUSSIAN;
case 8: return sys.LANGUAGE_KOREAN;
case 9: return sys.LANGUAGE_JAPANESE;
case 10: return sys.LANGUAGE_HUNGARIAN;
case 11: return sys.LANGUAGE_PORTUGUESE;
case 12: return sys.LANGUAGE_ARABIC;
case 13: return sys.LANGUAGE_NORWEGIAN;
case 14: return sys.LANGUAGE_POLISH;
case 15: return sys.LANGUAGE_TURKISH;
case 16: return sys.LANGUAGE_UKRAINIAN;
case 17: return sys.LANGUAGE_ROMANIAN;
case 18: return sys.LANGUAGE_BULGARIAN;
default: return sys.LANGUAGE_ENGLISH;
}
})();
sys.os = __getOS();
sys.browserType = null; //null in jsb
sys.browserVersion = null; //null in jsb
sys.windowPixelResolution = cc.view.getFrameSize();
var capabilities = sys.capabilities = {
"canvas": false,
"opengl": true
};
if( sys.isMobile ) {
capabilities["accelerometer"] = true;
capabilities["touches"] = true;
if (platform === sys.WINRT || platform === sys.WP8) {
capabilities["keyboard"] = true;
}
} else {
// desktop
capabilities["keyboard"] = true;
capabilities["mouse"] = true;
// winrt can't suppot mouse in current version
if (platform === sys.WINRT || platform === sys.WP8)
{
capabilities["touches"] = true;
capabilities["mouse"] = false;
}
}
/**
* Forces the garbage collection, only available in JSB
* @memberof cc.sys
* @name garbageCollect
* @function
*/
sys.garbageCollect = function() {
__jsc__.garbageCollect();
};
/**
* Dumps rooted objects, only available in JSB
* @memberof cc.sys
* @name dumpRoot
* @function
*/
sys.dumpRoot = function() {
__jsc__.dumpRoot();
};
/**
* Restart the JS VM, only available in JSB
* @memberof cc.sys
* @name restartVM
* @function
*/
sys.restartVM = function() {
__restartVM();
};
/**
* Clean a script in the JS VM, only available in JSB
* @memberof cc.sys
* @name cleanScript
* @param {String} jsfile
* @function
*/
sys.cleanScript = function(jsFile) {
__cleanScript(jsFile);
};
/**
* Check whether an object is valid,
* In web engine, it will return true if the object exist
* In native engine, it will return true if the JS object and the correspond native object are both valid
* @memberof cc.sys
* @name isObjectValid
* @param {Object} obj
* @return {boolean} Validity of the object
* @function
*/
sys.isObjectValid = function(obj) {
return __isObjectValid(obj);
};
/**
* Dump system informations
* @memberof cc.sys
* @name dump
* @function
*/
sys.dump = function () {
var self = this;
var str = "";
str += "isMobile : " + self.isMobile + "\r\n";
str += "language : " + self.language + "\r\n";
str += "browserType : " + self.browserType + "\r\n";
str += "capabilities : " + JSON.stringify(self.capabilities) + "\r\n";
str += "os : " + self.os + "\r\n";
str += "platform : " + self.platform + "\r\n";
cc.log(str);
};
/**
* Open a url in browser
* @memberof cc.sys
* @name openURL
* @param {String} url
*/
sys.openURL = function(url){
sys._application.openURL(url);
};
sys.now = function () {
return Date.now();
};
// JS to Native bridges
if(window.JavascriptJavaBridge && cc.sys.os == cc.sys.OS_ANDROID){
jsb.reflection = new JavascriptJavaBridge();
cc.sys.capabilities["keyboard"] = true;
}
else if(window.JavaScriptObjCBridge && (cc.sys.os == cc.sys.OS_IOS || cc.sys.os == cc.sys.OS_OSX)){
jsb.reflection = new JavaScriptObjCBridge();
}
};
_initSys();
//+++++++++++++++++++++++++something about CCGame end+++++++++++++++++++++++++++++
// Original bind in Spidermonkey v33 will trigger object life cycle track issue in our memory model and cause crash
Function.prototype.bind = function (oThis, ...aArgs) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var fToBind = this,
fNOP = function () {},
fBound = function (...args) {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis,
aArgs.concat(args));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
jsb.urlRegExp = new RegExp("^(?:https?|ftp)://\\S*$", "i");
cc._engineLoaded = false;
(function (config) {
require("script/jsb.js");
cc._engineLoaded = true;
console.log(cc.ENGINE_VERSION);
})();
|
version https://git-lfs.github.com/spec/v1
oid sha256:bed48975c30bba7aa601e45077459d8262e0ea8612c89e57efd0461007cc0862
size 703916
|
require('babel-register');
require('./JoiModel'); |
const split = (separator, str) => str.split(separator);
export { split };
|
/**
* Rangy, a cross-browser JavaScript range and selection library
* http://code.google.com/p/rangy/
*
* Copyright 2013, Tim Down
* Licensed under the MIT license.
* Version: 1.3alpha.799
* Build date: 27 November 2013
*/
(function(global) {
var amdSupported = (typeof global.define == "function" && global.define.amd);
var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined";
// Minimal set of properties required for DOM Level 2 Range compliance. Comparison constants such as START_TO_START
// are omitted because ranges in KHTML do not have them but otherwise work perfectly well. See issue 113.
var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
"commonAncestorContainer"];
// Minimal set of methods required for DOM Level 2 Range compliance
var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore",
"setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents",
"extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"];
var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"];
// Subset of TextRange's full set of methods that we're interested in
var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "moveToElementText", "parentElement", "select",
"setEndPoint", "getBoundingClientRect"];
/*----------------------------------------------------------------------------------------------------------------*/
// Trio of functions taken from Peter Michaux's article:
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(o, p) {
var t = typeof o[p];
return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown";
}
function isHostObject(o, p) {
return !!(typeof o[p] == OBJECT && o[p]);
}
function isHostProperty(o, p) {
return typeof o[p] != UNDEFINED;
}
// Creates a convenience function to save verbose repeated calls to tests functions
function createMultiplePropertyTest(testFunc) {
return function(o, props) {
var i = props.length;
while (i--) {
if (!testFunc(o, props[i])) {
return false;
}
}
return true;
};
}
// Next trio of functions are a convenience to save verbose repeated calls to previous two functions
var areHostMethods = createMultiplePropertyTest(isHostMethod);
var areHostObjects = createMultiplePropertyTest(isHostObject);
var areHostProperties = createMultiplePropertyTest(isHostProperty);
function isTextRange(range) {
return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties);
}
function getBody(doc) {
return isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0];
}
var modules = {};
var api = {
version: "1.3alpha.799",
initialized: false,
supported: true,
util: {
isHostMethod: isHostMethod,
isHostObject: isHostObject,
isHostProperty: isHostProperty,
areHostMethods: areHostMethods,
areHostObjects: areHostObjects,
areHostProperties: areHostProperties,
isTextRange: isTextRange,
getBody: getBody
},
features: {},
modules: modules,
config: {
alertOnFail: true,
alertOnWarn: false,
preferTextRange: false
}
};
function consoleLog(msg) {
if (isHostObject(window, "console") && isHostMethod(window.console, "log")) {
window.console.log(msg);
}
}
function alertOrLog(msg, shouldAlert) {
if (shouldAlert) {
window.alert(msg);
} else {
consoleLog(msg);
}
}
function fail(reason) {
api.initialized = true;
api.supported = false;
alertOrLog("Rangy is not supported on this page in your browser. Reason: " + reason, api.config.alertOnFail);
}
api.fail = fail;
function warn(msg) {
alertOrLog("Rangy warning: " + msg, api.config.alertOnWarn);
}
api.warn = warn;
// Add utility extend() method
if ({}.hasOwnProperty) {
api.util.extend = function(obj, props, deep) {
var o, p;
for (var i in props) {
if (props.hasOwnProperty(i)) {
o = obj[i];
p = props[i];
//if (deep) alert([o !== null, typeof o == "object", p !== null, typeof p == "object"])
if (deep && o !== null && typeof o == "object" && p !== null && typeof p == "object") {
api.util.extend(o, p, true);
}
obj[i] = p;
}
}
return obj;
};
} else {
fail("hasOwnProperty not supported");
}
// Test whether Array.prototype.slice can be relied on for NodeLists and use an alternative toArray() if not
(function() {
var el = document.createElement("div");
el.appendChild(document.createElement("span"));
var slice = [].slice;
var toArray;
try {
if (slice.call(el.childNodes, 0)[0].nodeType == 1) {
toArray = function(arrayLike) {
return slice.call(arrayLike, 0);
};
}
} catch (e) {}
if (!toArray) {
toArray = function(arrayLike) {
var arr = [];
for (var i = 0, len = arrayLike.length; i < len; ++i) {
arr[i] = arrayLike[i];
}
return arr;
};
}
api.util.toArray = toArray;
})();
// Very simple event handler wrapper function that doesn't attempt to solve issues such as "this" handling or
// normalization of event properties
var addListener;
if (isHostMethod(document, "addEventListener")) {
addListener = function(obj, eventType, listener) {
obj.addEventListener(eventType, listener, false);
};
} else if (isHostMethod(document, "attachEvent")) {
addListener = function(obj, eventType, listener) {
obj.attachEvent("on" + eventType, listener);
};
} else {
fail("Document does not have required addEventListener or attachEvent method");
}
api.util.addListener = addListener;
var initListeners = [];
function getErrorDesc(ex) {
return ex.message || ex.description || String(ex);
}
// Initialization
function init() {
if (api.initialized) {
return;
}
var testRange;
var implementsDomRange = false, implementsTextRange = false;
// First, perform basic feature tests
if (isHostMethod(document, "createRange")) {
testRange = document.createRange();
if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) {
implementsDomRange = true;
}
testRange.detach();
}
var body = getBody(document);
if (!body || body.nodeName.toLowerCase() != "body") {
fail("No body element found");
return;
}
if (body && isHostMethod(body, "createTextRange")) {
testRange = body.createTextRange();
if (isTextRange(testRange)) {
implementsTextRange = true;
}
}
if (!implementsDomRange && !implementsTextRange) {
fail("Neither Range nor TextRange are available");
return;
}
api.initialized = true;
api.features = {
implementsDomRange: implementsDomRange,
implementsTextRange: implementsTextRange
};
// Initialize modules
var module, errorMessage;
for (var moduleName in modules) {
if ( (module = modules[moduleName]) instanceof Module ) {
module.init(module, api);
}
}
// Call init listeners
for (var i = 0, len = initListeners.length; i < len; ++i) {
try {
initListeners[i](api);
} catch (ex) {
errorMessage = "Rangy init listener threw an exception. Continuing. Detail: " + getErrorDesc(ex);
consoleLog(errorMessage);
}
}
}
// Allow external scripts to initialize this library in case it's loaded after the document has loaded
api.init = init;
// Execute listener immediately if already initialized
api.addInitListener = function(listener) {
if (api.initialized) {
listener(api);
} else {
initListeners.push(listener);
}
};
var createMissingNativeApiListeners = [];
api.addCreateMissingNativeApiListener = function(listener) {
createMissingNativeApiListeners.push(listener);
};
function createMissingNativeApi(win) {
win = win || window;
init();
// Notify listeners
for (var i = 0, len = createMissingNativeApiListeners.length; i < len; ++i) {
createMissingNativeApiListeners[i](win);
}
}
api.createMissingNativeApi = createMissingNativeApi;
function Module(name, dependencies, initializer) {
this.name = name;
this.dependencies = dependencies;
this.initialized = false;
this.supported = false;
this.initializer = initializer;
}
Module.prototype = {
init: function(api) {
var requiredModuleNames = this.dependencies || [];
for (var i = 0, len = requiredModuleNames.length, requiredModule, moduleName; i < len; ++i) {
moduleName = requiredModuleNames[i];
requiredModule = modules[moduleName];
if (!requiredModule || !(requiredModule instanceof Module)) {
throw new Error("required module '" + moduleName + "' not found");
}
requiredModule.init();
if (!requiredModule.supported) {
throw new Error("required module '" + moduleName + "' not supported");
}
}
// Now run initializer
this.initializer(this)
},
fail: function(reason) {
this.initialized = true;
this.supported = false;
throw new Error("Module '" + this.name + "' failed to load: " + reason);
},
warn: function(msg) {
api.warn("Module " + this.name + ": " + msg);
},
deprecationNotice: function(deprecated, replacement) {
api.warn("DEPRECATED: " + deprecated + " in module " + this.name + "is deprecated. Please use "
+ replacement + " instead");
},
createError: function(msg) {
return new Error("Error in Rangy " + this.name + " module: " + msg);
}
};
function createModule(isCore, name, dependencies, initFunc) {
var newModule = new Module(name, dependencies, function(module) {
if (!module.initialized) {
module.initialized = true;
try {
initFunc(api, module);
module.supported = true;
} catch (ex) {
var errorMessage = "Module '" + name + "' failed to load: " + getErrorDesc(ex);
consoleLog(errorMessage);
}
}
});
modules[name] = newModule;
/*
// Add module AMD support
if (!isCore && amdSupported) {
global.define(["rangy-core"], function(rangy) {
});
}
*/
}
api.createModule = function(name) {
// Allow 2 or 3 arguments (second argument is an optional array of dependencies)
var initFunc, dependencies;
if (arguments.length == 2) {
initFunc = arguments[1];
dependencies = [];
} else {
initFunc = arguments[2];
dependencies = arguments[1];
}
createModule(false, name, dependencies, initFunc);
};
api.createCoreModule = function(name, dependencies, initFunc) {
createModule(true, name, dependencies, initFunc);
};
/*----------------------------------------------------------------------------------------------------------------*/
// Ensure rangy.rangePrototype and rangy.selectionPrototype are available immediately
function RangePrototype() {}
api.RangePrototype = RangePrototype;
api.rangePrototype = new RangePrototype();
function SelectionPrototype() {}
api.selectionPrototype = new SelectionPrototype();
/*----------------------------------------------------------------------------------------------------------------*/
// Wait for document to load before running tests
var docReady = false;
var loadHandler = function(e) {
if (!docReady) {
docReady = true;
if (!api.initialized) {
init();
}
}
};
// Test whether we have window and document objects that we will need
if (typeof window == UNDEFINED) {
fail("No window found");
return;
}
if (typeof document == UNDEFINED) {
fail("No document found");
return;
}
if (isHostMethod(document, "addEventListener")) {
document.addEventListener("DOMContentLoaded", loadHandler, false);
}
// Add a fallback in case the DOMContentLoaded event isn't supported
addListener(window, "load", loadHandler);
/*----------------------------------------------------------------------------------------------------------------*/
// AMD, for those who like this kind of thing
if (amdSupported) {
// AMD. Register as an anonymous module.
global.define(function() {
api.amd = true;
return api;
});
}
// Create a "rangy" property of the global object in any case. Other Rangy modules (which use Rangy's own simple
// module system) rely on the existence of this global property
global.rangy = api;
})(this);
rangy.createCoreModule("DomUtil", [], function(api, module) {
var UNDEF = "undefined";
var util = api.util;
// Perform feature tests
if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) {
module.fail("document missing a Node creation method");
}
if (!util.isHostMethod(document, "getElementsByTagName")) {
module.fail("document missing getElementsByTagName method");
}
var el = document.createElement("div");
if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] ||
!util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) {
module.fail("Incomplete Element implementation");
}
// innerHTML is required for Range's createContextualFragment method
if (!util.isHostProperty(el, "innerHTML")) {
module.fail("Element is missing innerHTML property");
}
var textNode = document.createTextNode("test");
if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] ||
!util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) ||
!util.areHostProperties(textNode, ["data"]))) {
module.fail("Incomplete Text Node implementation");
}
/*----------------------------------------------------------------------------------------------------------------*/
// Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been
// able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that
// contains just the document as a single element and the value searched for is the document.
var arrayContains = /*Array.prototype.indexOf ?
function(arr, val) {
return arr.indexOf(val) > -1;
}:*/
function(arr, val) {
var i = arr.length;
while (i--) {
if (arr[i] === val) {
return true;
}
}
return false;
};
// Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI
function isHtmlNamespace(node) {
var ns;
return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml");
}
function parentElement(node) {
var parent = node.parentNode;
return (parent.nodeType == 1) ? parent : null;
}
function getNodeIndex(node) {
var i = 0;
while( (node = node.previousSibling) ) {
++i;
}
return i;
}
function getNodeLength(node) {
switch (node.nodeType) {
case 7:
case 10:
return 0;
case 3:
case 8:
return node.length;
default:
return node.childNodes.length;
}
}
function getCommonAncestor(node1, node2) {
var ancestors = [], n;
for (n = node1; n; n = n.parentNode) {
ancestors.push(n);
}
for (n = node2; n; n = n.parentNode) {
if (arrayContains(ancestors, n)) {
return n;
}
}
return null;
}
function isAncestorOf(ancestor, descendant, selfIsAncestor) {
var n = selfIsAncestor ? descendant : descendant.parentNode;
while (n) {
if (n === ancestor) {
return true;
} else {
n = n.parentNode;
}
}
return false;
}
function isOrIsAncestorOf(ancestor, descendant) {
return isAncestorOf(ancestor, descendant, true);
}
function getClosestAncestorIn(node, ancestor, selfIsAncestor) {
var p, n = selfIsAncestor ? node : node.parentNode;
while (n) {
p = n.parentNode;
if (p === ancestor) {
return n;
}
n = p;
}
return null;
}
function isCharacterDataNode(node) {
var t = node.nodeType;
return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment
}
function isTextOrCommentNode(node) {
if (!node) {
return false;
}
var t = node.nodeType;
return t == 3 || t == 8 ; // Text or Comment
}
function insertAfter(node, precedingNode) {
var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode;
if (nextNode) {
parent.insertBefore(node, nextNode);
} else {
parent.appendChild(node);
}
return node;
}
// Note that we cannot use splitText() because it is bugridden in IE 9.
function splitDataNode(node, index, positionsToPreserve) {
var newNode = node.cloneNode(false);
newNode.deleteData(0, index);
node.deleteData(index, node.length - index);
insertAfter(newNode, node);
// Preserve positions
if (positionsToPreserve) {
for (var i = 0, position; position = positionsToPreserve[i++]; ) {
// Handle case where position was inside the portion of node after the split point
if (position.node == node && position.offset > index) {
position.node = newNode;
position.offset -= index;
}
// Handle the case where the position is a node offset within node's parent
else if (position.node == node.parentNode && position.offset > getNodeIndex(node)) {
++position.offset;
}
}
}
return newNode;
}
function getDocument(node) {
if (node.nodeType == 9) {
return node;
} else if (typeof node.ownerDocument != UNDEF) {
return node.ownerDocument;
} else if (typeof node.document != UNDEF) {
return node.document;
} else if (node.parentNode) {
return getDocument(node.parentNode);
} else {
throw module.createError("getDocument: no document found for node");
}
}
function getWindow(node) {
var doc = getDocument(node);
if (typeof doc.defaultView != UNDEF) {
return doc.defaultView;
} else if (typeof doc.parentWindow != UNDEF) {
return doc.parentWindow;
} else {
throw module.createError("Cannot get a window object for node");
}
}
function getIframeDocument(iframeEl) {
if (typeof iframeEl.contentDocument != UNDEF) {
return iframeEl.contentDocument;
} else if (typeof iframeEl.contentWindow != UNDEF) {
return iframeEl.contentWindow.document;
} else {
throw module.createError("getIframeDocument: No Document object found for iframe element");
}
}
function getIframeWindow(iframeEl) {
if (typeof iframeEl.contentWindow != UNDEF) {
return iframeEl.contentWindow;
} else if (typeof iframeEl.contentDocument != UNDEF) {
return iframeEl.contentDocument.defaultView;
} else {
throw module.createError("getIframeWindow: No Window object found for iframe element");
}
}
// This looks bad. Is it worth it?
function isWindow(obj) {
return obj && util.isHostMethod(obj, "setTimeout") && util.isHostObject(obj, "document");
}
function getContentDocument(obj, module, methodName) {
var doc;
if (!obj) {
doc = document;
}
// Test if a DOM node has been passed and obtain a document object for it if so
else if (util.isHostProperty(obj, "nodeType")) {
doc = (obj.nodeType == 1 && obj.tagName.toLowerCase() == "iframe")
? getIframeDocument(obj) : getDocument(obj);
}
// Test if the doc parameter appears to be a Window object
else if (isWindow(obj)) {
doc = obj.document;
}
if (!doc) {
throw module.createError(methodName + "(): Parameter must be a Window object or DOM node");
}
return doc;
}
function getRootContainer(node) {
var parent;
while ( (parent = node.parentNode) ) {
node = parent;
}
return node;
}
function comparePoints(nodeA, offsetA, nodeB, offsetB) {
// See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing
var nodeC, root, childA, childB, n;
if (nodeA == nodeB) {
// Case 1: nodes are the same
return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1;
} else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) {
// Case 2: node C (container B or an ancestor) is a child node of A
return offsetA <= getNodeIndex(nodeC) ? -1 : 1;
} else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) {
// Case 3: node C (container A or an ancestor) is a child node of B
return getNodeIndex(nodeC) < offsetB ? -1 : 1;
} else {
root = getCommonAncestor(nodeA, nodeB);
if (!root) {
throw new Error("comparePoints error: nodes have no common ancestor");
}
// Case 4: containers are siblings or descendants of siblings
childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true);
childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true);
if (childA === childB) {
// This shouldn't be possible
throw module.createError("comparePoints got to case 4 and childA and childB are the same!");
} else {
n = root.firstChild;
while (n) {
if (n === childA) {
return -1;
} else if (n === childB) {
return 1;
}
n = n.nextSibling;
}
}
}
}
/*----------------------------------------------------------------------------------------------------------------*/
// Test for IE's crash (IE 6/7) or exception (IE >= 8) when a reference to garbage-collected text node is queried
var crashyTextNodes = false;
function isBrokenNode(node) {
try {
node.parentNode;
return false;
} catch (e) {
return true;
}
}
(function() {
var el = document.createElement("b");
el.innerHTML = "1";
var textNode = el.firstChild;
el.innerHTML = "<br>";
crashyTextNodes = isBrokenNode(textNode);
api.features.crashyTextNodes = crashyTextNodes;
})();
/*----------------------------------------------------------------------------------------------------------------*/
function inspectNode(node) {
if (!node) {
return "[No node]";
}
if (crashyTextNodes && isBrokenNode(node)) {
return "[Broken node]";
}
if (isCharacterDataNode(node)) {
return '"' + node.data + '"';
}
if (node.nodeType == 1) {
var idAttr = node.id ? ' id="' + node.id + '"' : "";
return "<" + node.nodeName + idAttr + ">[" + getNodeIndex(node) + "][" + node.childNodes.length + "][" + (node.innerHTML || "[innerHTML not supported]").slice(0, 25) + "]";
}
return node.nodeName;
}
function fragmentFromNodeChildren(node) {
var fragment = getDocument(node).createDocumentFragment(), child;
while ( (child = node.firstChild) ) {
fragment.appendChild(child);
}
return fragment;
}
var getComputedStyleProperty;
if (typeof window.getComputedStyle != UNDEF) {
getComputedStyleProperty = function(el, propName) {
return getWindow(el).getComputedStyle(el, null)[propName];
};
} else if (typeof document.documentElement.currentStyle != UNDEF) {
getComputedStyleProperty = function(el, propName) {
return el.currentStyle[propName];
};
} else {
module.fail("No means of obtaining computed style properties found");
}
function NodeIterator(root) {
this.root = root;
this._next = root;
}
NodeIterator.prototype = {
_current: null,
hasNext: function() {
return !!this._next;
},
next: function() {
var n = this._current = this._next;
var child, next;
if (this._current) {
child = n.firstChild;
if (child) {
this._next = child;
} else {
next = null;
while ((n !== this.root) && !(next = n.nextSibling)) {
n = n.parentNode;
}
this._next = next;
}
}
return this._current;
},
detach: function() {
this._current = this._next = this.root = null;
}
};
function createIterator(root) {
return new NodeIterator(root);
}
function DomPosition(node, offset) {
this.node = node;
this.offset = offset;
}
DomPosition.prototype = {
equals: function(pos) {
return !!pos && this.node === pos.node && this.offset == pos.offset;
},
inspect: function() {
return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]";
},
toString: function() {
return this.inspect();
}
};
function DOMException(codeName) {
this.code = this[codeName];
this.codeName = codeName;
this.message = "DOMException: " + this.codeName;
}
DOMException.prototype = {
INDEX_SIZE_ERR: 1,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INVALID_STATE_ERR: 11
};
DOMException.prototype.toString = function() {
return this.message;
};
api.dom = {
arrayContains: arrayContains,
isHtmlNamespace: isHtmlNamespace,
parentElement: parentElement,
getNodeIndex: getNodeIndex,
getNodeLength: getNodeLength,
getCommonAncestor: getCommonAncestor,
isAncestorOf: isAncestorOf,
isOrIsAncestorOf: isOrIsAncestorOf,
getClosestAncestorIn: getClosestAncestorIn,
isCharacterDataNode: isCharacterDataNode,
isTextOrCommentNode: isTextOrCommentNode,
insertAfter: insertAfter,
splitDataNode: splitDataNode,
getDocument: getDocument,
getWindow: getWindow,
getIframeWindow: getIframeWindow,
getIframeDocument: getIframeDocument,
getBody: util.getBody,
isWindow: isWindow,
getContentDocument: getContentDocument,
getRootContainer: getRootContainer,
comparePoints: comparePoints,
isBrokenNode: isBrokenNode,
inspectNode: inspectNode,
getComputedStyleProperty: getComputedStyleProperty,
fragmentFromNodeChildren: fragmentFromNodeChildren,
createIterator: createIterator,
DomPosition: DomPosition
};
api.DOMException = DOMException;
});
rangy.createCoreModule("DomRange", ["DomUtil"], function(api, module) {
var dom = api.dom;
var util = api.util;
var DomPosition = dom.DomPosition;
var DOMException = api.DOMException;
var isCharacterDataNode = dom.isCharacterDataNode;
var getNodeIndex = dom.getNodeIndex;
var isOrIsAncestorOf = dom.isOrIsAncestorOf;
var getDocument = dom.getDocument;
var comparePoints = dom.comparePoints;
var splitDataNode = dom.splitDataNode;
var getClosestAncestorIn = dom.getClosestAncestorIn;
var getNodeLength = dom.getNodeLength;
var arrayContains = dom.arrayContains;
var getRootContainer = dom.getRootContainer;
var crashyTextNodes = api.features.crashyTextNodes;
/*----------------------------------------------------------------------------------------------------------------*/
// Utility functions
function isNonTextPartiallySelected(node, range) {
return (node.nodeType != 3) &&
(isOrIsAncestorOf(node, range.startContainer) || isOrIsAncestorOf(node, range.endContainer));
}
function getRangeDocument(range) {
return range.document || getDocument(range.startContainer);
}
function getBoundaryBeforeNode(node) {
return new DomPosition(node.parentNode, getNodeIndex(node));
}
function getBoundaryAfterNode(node) {
return new DomPosition(node.parentNode, getNodeIndex(node) + 1);
}
function insertNodeAtPosition(node, n, o) {
var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node;
if (isCharacterDataNode(n)) {
if (o == n.length) {
dom.insertAfter(node, n);
} else {
n.parentNode.insertBefore(node, o == 0 ? n : splitDataNode(n, o));
}
} else if (o >= n.childNodes.length) {
n.appendChild(node);
} else {
n.insertBefore(node, n.childNodes[o]);
}
return firstNodeInserted;
}
function rangesIntersect(rangeA, rangeB, touchingIsIntersecting) {
assertRangeValid(rangeA);
assertRangeValid(rangeB);
if (getRangeDocument(rangeB) != getRangeDocument(rangeA)) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
var startComparison = comparePoints(rangeA.startContainer, rangeA.startOffset, rangeB.endContainer, rangeB.endOffset),
endComparison = comparePoints(rangeA.endContainer, rangeA.endOffset, rangeB.startContainer, rangeB.startOffset);
return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
}
function cloneSubtree(iterator) {
var partiallySelected;
for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
partiallySelected = iterator.isPartiallySelectedSubtree();
node = node.cloneNode(!partiallySelected);
if (partiallySelected) {
subIterator = iterator.getSubtreeIterator();
node.appendChild(cloneSubtree(subIterator));
subIterator.detach(true);
}
if (node.nodeType == 10) { // DocumentType
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
frag.appendChild(node);
}
return frag;
}
function iterateSubtree(rangeIterator, func, iteratorState) {
var it, n;
iteratorState = iteratorState || { stop: false };
for (var node, subRangeIterator; node = rangeIterator.next(); ) {
if (rangeIterator.isPartiallySelectedSubtree()) {
if (func(node) === false) {
iteratorState.stop = true;
return;
} else {
// The node is partially selected by the Range, so we can use a new RangeIterator on the portion of
// the node selected by the Range.
subRangeIterator = rangeIterator.getSubtreeIterator();
iterateSubtree(subRangeIterator, func, iteratorState);
subRangeIterator.detach(true);
if (iteratorState.stop) {
return;
}
}
} else {
// The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its
// descendants
it = dom.createIterator(node);
while ( (n = it.next()) ) {
if (func(n) === false) {
iteratorState.stop = true;
return;
}
}
}
}
}
function deleteSubtree(iterator) {
var subIterator;
while (iterator.next()) {
if (iterator.isPartiallySelectedSubtree()) {
subIterator = iterator.getSubtreeIterator();
deleteSubtree(subIterator);
subIterator.detach(true);
} else {
iterator.remove();
}
}
}
function extractSubtree(iterator) {
for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) {
if (iterator.isPartiallySelectedSubtree()) {
node = node.cloneNode(false);
subIterator = iterator.getSubtreeIterator();
node.appendChild(extractSubtree(subIterator));
subIterator.detach(true);
} else {
iterator.remove();
}
if (node.nodeType == 10) { // DocumentType
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
frag.appendChild(node);
}
return frag;
}
function getNodesInRange(range, nodeTypes, filter) {
var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex;
var filterExists = !!filter;
if (filterNodeTypes) {
regex = new RegExp("^(" + nodeTypes.join("|") + ")$");
}
var nodes = [];
iterateSubtree(new RangeIterator(range, false), function(node) {
if (filterNodeTypes && !regex.test(node.nodeType)) {
return;
}
if (filterExists && !filter(node)) {
return;
}
// Don't include a boundary container if it is a character data node and the range does not contain any
// of its character data. See issue 190.
var sc = range.startContainer;
if (node == sc && isCharacterDataNode(sc) && range.startOffset == sc.length) {
return;
}
var ec = range.endContainer;
if (node == ec && isCharacterDataNode(ec) && range.endOffset == 0) {
return;
}
nodes.push(node);
});
return nodes;
}
function inspect(range) {
var name = (typeof range.getName == "undefined") ? "Range" : range.getName();
return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " +
dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]";
}
/*----------------------------------------------------------------------------------------------------------------*/
// RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange)
function RangeIterator(range, clonePartiallySelectedTextNodes) {
this.range = range;
this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes;
if (!range.collapsed) {
this.sc = range.startContainer;
this.so = range.startOffset;
this.ec = range.endContainer;
this.eo = range.endOffset;
var root = range.commonAncestorContainer;
if (this.sc === this.ec && isCharacterDataNode(this.sc)) {
this.isSingleCharacterDataNode = true;
this._first = this._last = this._next = this.sc;
} else {
this._first = this._next = (this.sc === root && !isCharacterDataNode(this.sc)) ?
this.sc.childNodes[this.so] : getClosestAncestorIn(this.sc, root, true);
this._last = (this.ec === root && !isCharacterDataNode(this.ec)) ?
this.ec.childNodes[this.eo - 1] : getClosestAncestorIn(this.ec, root, true);
}
}
}
RangeIterator.prototype = {
_current: null,
_next: null,
_first: null,
_last: null,
isSingleCharacterDataNode: false,
reset: function() {
this._current = null;
this._next = this._first;
},
hasNext: function() {
return !!this._next;
},
next: function() {
// Move to next node
var current = this._current = this._next;
if (current) {
this._next = (current !== this._last) ? current.nextSibling : null;
// Check for partially selected text nodes
if (isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) {
if (current === this.ec) {
(current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo);
}
if (this._current === this.sc) {
(current = current.cloneNode(true)).deleteData(0, this.so);
}
}
}
return current;
},
remove: function() {
var current = this._current, start, end;
if (isCharacterDataNode(current) && (current === this.sc || current === this.ec)) {
start = (current === this.sc) ? this.so : 0;
end = (current === this.ec) ? this.eo : current.length;
if (start != end) {
current.deleteData(start, end - start);
}
} else {
if (current.parentNode) {
current.parentNode.removeChild(current);
} else {
}
}
},
// Checks if the current node is partially selected
isPartiallySelectedSubtree: function() {
var current = this._current;
return isNonTextPartiallySelected(current, this.range);
},
getSubtreeIterator: function() {
var subRange;
if (this.isSingleCharacterDataNode) {
subRange = this.range.cloneRange();
subRange.collapse(false);
} else {
subRange = new Range(getRangeDocument(this.range));
var current = this._current;
var startContainer = current, startOffset = 0, endContainer = current, endOffset = getNodeLength(current);
if (isOrIsAncestorOf(current, this.sc)) {
startContainer = this.sc;
startOffset = this.so;
}
if (isOrIsAncestorOf(current, this.ec)) {
endContainer = this.ec;
endOffset = this.eo;
}
updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset);
}
return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes);
},
detach: function(detachRange) {
if (detachRange) {
this.range.detach();
}
this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null;
}
};
/*----------------------------------------------------------------------------------------------------------------*/
// Exceptions
function RangeException(codeName) {
this.code = this[codeName];
this.codeName = codeName;
this.message = "RangeException: " + this.codeName;
}
RangeException.prototype = {
BAD_BOUNDARYPOINTS_ERR: 1,
INVALID_NODE_TYPE_ERR: 2
};
RangeException.prototype.toString = function() {
return this.message;
};
/*----------------------------------------------------------------------------------------------------------------*/
var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10];
var rootContainerNodeTypes = [2, 9, 11];
var readonlyNodeTypes = [5, 6, 10, 12];
var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11];
var surroundNodeTypes = [1, 3, 4, 5, 7, 8];
function createAncestorFinder(nodeTypes) {
return function(node, selfIsAncestor) {
var t, n = selfIsAncestor ? node : node.parentNode;
while (n) {
t = n.nodeType;
if (arrayContains(nodeTypes, t)) {
return n;
}
n = n.parentNode;
}
return null;
};
}
var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] );
var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes);
var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] );
function assertNoDocTypeNotationEntityAncestor(node, allowSelf) {
if (getDocTypeNotationEntityAncestor(node, allowSelf)) {
throw new RangeException("INVALID_NODE_TYPE_ERR");
}
}
function assertNotDetached(range) {
if (!range.startContainer) {
throw new DOMException("INVALID_STATE_ERR");
}
}
function assertValidNodeType(node, invalidTypes) {
if (!arrayContains(invalidTypes, node.nodeType)) {
throw new RangeException("INVALID_NODE_TYPE_ERR");
}
}
function assertValidOffset(node, offset) {
if (offset < 0 || offset > (isCharacterDataNode(node) ? node.length : node.childNodes.length)) {
throw new DOMException("INDEX_SIZE_ERR");
}
}
function assertSameDocumentOrFragment(node1, node2) {
if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
}
function assertNodeNotReadOnly(node) {
if (getReadonlyAncestor(node, true)) {
throw new DOMException("NO_MODIFICATION_ALLOWED_ERR");
}
}
function assertNode(node, codeName) {
if (!node) {
throw new DOMException(codeName);
}
}
function isOrphan(node) {
return (crashyTextNodes && dom.isBrokenNode(node)) ||
!arrayContains(rootContainerNodeTypes, node.nodeType) && !getDocumentOrFragmentContainer(node, true);
}
function isValidOffset(node, offset) {
return offset <= (isCharacterDataNode(node) ? node.length : node.childNodes.length);
}
function isRangeValid(range) {
return (!!range.startContainer && !!range.endContainer
&& !isOrphan(range.startContainer)
&& !isOrphan(range.endContainer)
&& isValidOffset(range.startContainer, range.startOffset)
&& isValidOffset(range.endContainer, range.endOffset));
}
function assertRangeValid(range) {
assertNotDetached(range);
if (!isRangeValid(range)) {
throw new Error("Range error: Range is no longer valid after DOM mutation (" + range.inspect() + ")");
}
}
/*----------------------------------------------------------------------------------------------------------------*/
// Test the browser's innerHTML support to decide how to implement createContextualFragment
var styleEl = document.createElement("style");
var htmlParsingConforms = false;
try {
styleEl.innerHTML = "<b>x</b>";
htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node
} catch (e) {
// IE 6 and 7 throw
}
api.features.htmlParsingConforms = htmlParsingConforms;
var createContextualFragment = htmlParsingConforms ?
// Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See
// discussion and base code for this implementation at issue 67.
// Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface
// Thanks to Aleks Williams.
function(fragmentStr) {
// "Let node the context object's start's node."
var node = this.startContainer;
var doc = getDocument(node);
// "If the context object's start's node is null, raise an INVALID_STATE_ERR
// exception and abort these steps."
if (!node) {
throw new DOMException("INVALID_STATE_ERR");
}
// "Let element be as follows, depending on node's interface:"
// Document, Document Fragment: null
var el = null;
// "Element: node"
if (node.nodeType == 1) {
el = node;
// "Text, Comment: node's parentElement"
} else if (isCharacterDataNode(node)) {
el = dom.parentElement(node);
}
// "If either element is null or element's ownerDocument is an HTML document
// and element's local name is "html" and element's namespace is the HTML
// namespace"
if (el === null || (
el.nodeName == "HTML"
&& dom.isHtmlNamespace(getDocument(el).documentElement)
&& dom.isHtmlNamespace(el)
)) {
// "let element be a new Element with "body" as its local name and the HTML
// namespace as its namespace.""
el = doc.createElement("body");
} else {
el = el.cloneNode(false);
}
// "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm."
// "If the node's document is an XML document: Invoke the XML fragment parsing algorithm."
// "In either case, the algorithm must be invoked with fragment as the input
// and element as the context element."
el.innerHTML = fragmentStr;
// "If this raises an exception, then abort these steps. Otherwise, let new
// children be the nodes returned."
// "Let fragment be a new DocumentFragment."
// "Append all new children to fragment."
// "Return fragment."
return dom.fragmentFromNodeChildren(el);
} :
// In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that
// previous versions of Rangy used (with the exception of using a body element rather than a div)
function(fragmentStr) {
assertNotDetached(this);
var doc = getRangeDocument(this);
var el = doc.createElement("body");
el.innerHTML = fragmentStr;
return dom.fragmentFromNodeChildren(el);
};
function splitRangeBoundaries(range, positionsToPreserve) {
assertRangeValid(range);
var sc = range.startContainer, so = range.startOffset, ec = range.endContainer, eo = range.endOffset;
var startEndSame = (sc === ec);
if (isCharacterDataNode(ec) && eo > 0 && eo < ec.length) {
splitDataNode(ec, eo, positionsToPreserve);
}
if (isCharacterDataNode(sc) && so > 0 && so < sc.length) {
sc = splitDataNode(sc, so, positionsToPreserve);
if (startEndSame) {
eo -= so;
ec = sc;
} else if (ec == sc.parentNode && eo >= getNodeIndex(sc)) {
eo++;
}
so = 0;
}
range.setStartAndEnd(sc, so, ec, eo);
}
/*----------------------------------------------------------------------------------------------------------------*/
var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed",
"commonAncestorContainer"];
var s2s = 0, s2e = 1, e2e = 2, e2s = 3;
var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3;
util.extend(api.rangePrototype, {
compareBoundaryPoints: function(how, range) {
assertRangeValid(this);
assertSameDocumentOrFragment(this.startContainer, range.startContainer);
var nodeA, offsetA, nodeB, offsetB;
var prefixA = (how == e2s || how == s2s) ? "start" : "end";
var prefixB = (how == s2e || how == s2s) ? "start" : "end";
nodeA = this[prefixA + "Container"];
offsetA = this[prefixA + "Offset"];
nodeB = range[prefixB + "Container"];
offsetB = range[prefixB + "Offset"];
return comparePoints(nodeA, offsetA, nodeB, offsetB);
},
insertNode: function(node) {
assertRangeValid(this);
assertValidNodeType(node, insertableNodeTypes);
assertNodeNotReadOnly(this.startContainer);
if (isOrIsAncestorOf(node, this.startContainer)) {
throw new DOMException("HIERARCHY_REQUEST_ERR");
}
// No check for whether the container of the start of the Range is of a type that does not allow
// children of the type of node: the browser's DOM implementation should do this for us when we attempt
// to add the node
var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset);
this.setStartBefore(firstNodeInserted);
},
cloneContents: function() {
assertRangeValid(this);
var clone, frag;
if (this.collapsed) {
return getRangeDocument(this).createDocumentFragment();
} else {
if (this.startContainer === this.endContainer && isCharacterDataNode(this.startContainer)) {
clone = this.startContainer.cloneNode(true);
clone.data = clone.data.slice(this.startOffset, this.endOffset);
frag = getRangeDocument(this).createDocumentFragment();
frag.appendChild(clone);
return frag;
} else {
var iterator = new RangeIterator(this, true);
clone = cloneSubtree(iterator);
iterator.detach();
}
return clone;
}
},
canSurroundContents: function() {
assertRangeValid(this);
assertNodeNotReadOnly(this.startContainer);
assertNodeNotReadOnly(this.endContainer);
// Check if the contents can be surrounded. Specifically, this means whether the range partially selects
// no non-text nodes.
var iterator = new RangeIterator(this, true);
var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
(iterator._last && isNonTextPartiallySelected(iterator._last, this)));
iterator.detach();
return !boundariesInvalid;
},
surroundContents: function(node) {
assertValidNodeType(node, surroundNodeTypes);
if (!this.canSurroundContents()) {
throw new RangeException("BAD_BOUNDARYPOINTS_ERR");
}
// Extract the contents
var content = this.extractContents();
// Clear the children of the node
if (node.hasChildNodes()) {
while (node.lastChild) {
node.removeChild(node.lastChild);
}
}
// Insert the new node and add the extracted contents
insertNodeAtPosition(node, this.startContainer, this.startOffset);
node.appendChild(content);
this.selectNode(node);
},
cloneRange: function() {
assertRangeValid(this);
var range = new Range(getRangeDocument(this));
var i = rangeProperties.length, prop;
while (i--) {
prop = rangeProperties[i];
range[prop] = this[prop];
}
return range;
},
toString: function() {
assertRangeValid(this);
var sc = this.startContainer;
if (sc === this.endContainer && isCharacterDataNode(sc)) {
return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : "";
} else {
var textParts = [], iterator = new RangeIterator(this, true);
iterateSubtree(iterator, function(node) {
// Accept only text or CDATA nodes, not comments
if (node.nodeType == 3 || node.nodeType == 4) {
textParts.push(node.data);
}
});
iterator.detach();
return textParts.join("");
}
},
// The methods below are all non-standard. The following batch were introduced by Mozilla but have since
// been removed from Mozilla.
compareNode: function(node) {
assertRangeValid(this);
var parent = node.parentNode;
var nodeIndex = getNodeIndex(node);
if (!parent) {
throw new DOMException("NOT_FOUND_ERR");
}
var startComparison = this.comparePoint(parent, nodeIndex),
endComparison = this.comparePoint(parent, nodeIndex + 1);
if (startComparison < 0) { // Node starts before
return (endComparison > 0) ? n_b_a : n_b;
} else {
return (endComparison > 0) ? n_a : n_i;
}
},
comparePoint: function(node, offset) {
assertRangeValid(this);
assertNode(node, "HIERARCHY_REQUEST_ERR");
assertSameDocumentOrFragment(node, this.startContainer);
if (comparePoints(node, offset, this.startContainer, this.startOffset) < 0) {
return -1;
} else if (comparePoints(node, offset, this.endContainer, this.endOffset) > 0) {
return 1;
}
return 0;
},
createContextualFragment: createContextualFragment,
toHtml: function() {
assertRangeValid(this);
var container = this.commonAncestorContainer.parentNode.cloneNode(false);
container.appendChild(this.cloneContents());
return container.innerHTML;
},
// touchingIsIntersecting determines whether this method considers a node that borders a range intersects
// with it (as in WebKit) or not (as in Gecko pre-1.9, and the default)
intersectsNode: function(node, touchingIsIntersecting) {
assertRangeValid(this);
assertNode(node, "NOT_FOUND_ERR");
if (getDocument(node) !== getRangeDocument(this)) {
return false;
}
var parent = node.parentNode, offset = getNodeIndex(node);
assertNode(parent, "NOT_FOUND_ERR");
var startComparison = comparePoints(parent, offset, this.endContainer, this.endOffset),
endComparison = comparePoints(parent, offset + 1, this.startContainer, this.startOffset);
return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0;
},
isPointInRange: function(node, offset) {
assertRangeValid(this);
assertNode(node, "HIERARCHY_REQUEST_ERR");
assertSameDocumentOrFragment(node, this.startContainer);
return (comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) &&
(comparePoints(node, offset, this.endContainer, this.endOffset) <= 0);
},
// The methods below are non-standard and invented by me.
// Sharing a boundary start-to-end or end-to-start does not count as intersection.
intersectsRange: function(range) {
return rangesIntersect(this, range, false);
},
// Sharing a boundary start-to-end or end-to-start does count as intersection.
intersectsOrTouchesRange: function(range) {
return rangesIntersect(this, range, true);
},
intersection: function(range) {
if (this.intersectsRange(range)) {
var startComparison = comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset),
endComparison = comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset);
var intersectionRange = this.cloneRange();
if (startComparison == -1) {
intersectionRange.setStart(range.startContainer, range.startOffset);
}
if (endComparison == 1) {
intersectionRange.setEnd(range.endContainer, range.endOffset);
}
return intersectionRange;
}
return null;
},
union: function(range) {
if (this.intersectsOrTouchesRange(range)) {
var unionRange = this.cloneRange();
if (comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) {
unionRange.setStart(range.startContainer, range.startOffset);
}
if (comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) {
unionRange.setEnd(range.endContainer, range.endOffset);
}
return unionRange;
} else {
throw new RangeException("Ranges do not intersect");
}
},
containsNode: function(node, allowPartial) {
if (allowPartial) {
return this.intersectsNode(node, false);
} else {
return this.compareNode(node) == n_i;
}
},
containsNodeContents: function(node) {
return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, getNodeLength(node)) <= 0;
},
containsRange: function(range) {
var intersection = this.intersection(range);
return intersection !== null && range.equals(intersection);
},
containsNodeText: function(node) {
var nodeRange = this.cloneRange();
nodeRange.selectNode(node);
var textNodes = nodeRange.getNodes([3]);
if (textNodes.length > 0) {
nodeRange.setStart(textNodes[0], 0);
var lastTextNode = textNodes.pop();
nodeRange.setEnd(lastTextNode, lastTextNode.length);
var contains = this.containsRange(nodeRange);
nodeRange.detach();
return contains;
} else {
return this.containsNodeContents(node);
}
},
getNodes: function(nodeTypes, filter) {
assertRangeValid(this);
return getNodesInRange(this, nodeTypes, filter);
},
getDocument: function() {
return getRangeDocument(this);
},
collapseBefore: function(node) {
assertNotDetached(this);
this.setEndBefore(node);
this.collapse(false);
},
collapseAfter: function(node) {
assertNotDetached(this);
this.setStartAfter(node);
this.collapse(true);
},
getBookmark: function(containerNode) {
var doc = getRangeDocument(this);
var preSelectionRange = api.createRange(doc);
containerNode = containerNode || dom.getBody(doc);
preSelectionRange.selectNodeContents(containerNode);
var range = this.intersection(preSelectionRange);
var start = 0, end = 0;
if (range) {
preSelectionRange.setEnd(range.startContainer, range.startOffset);
start = preSelectionRange.toString().length;
end = start + range.toString().length;
preSelectionRange.detach();
}
return {
start: start,
end: end,
containerNode: containerNode
};
},
moveToBookmark: function(bookmark) {
var containerNode = bookmark.containerNode;
var charIndex = 0;
this.setStart(containerNode, 0);
this.collapse(true);
var nodeStack = [containerNode], node, foundStart = false, stop = false;
var nextCharIndex, i, childNodes;
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType == 3) {
nextCharIndex = charIndex + node.length;
if (!foundStart && bookmark.start >= charIndex && bookmark.start <= nextCharIndex) {
this.setStart(node, bookmark.start - charIndex);
foundStart = true;
}
if (foundStart && bookmark.end >= charIndex && bookmark.end <= nextCharIndex) {
this.setEnd(node, bookmark.end - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
childNodes = node.childNodes;
i = childNodes.length;
while (i--) {
nodeStack.push(childNodes[i]);
}
}
}
},
getName: function() {
return "DomRange";
},
equals: function(range) {
return Range.rangesEqual(this, range);
},
isValid: function() {
return isRangeValid(this);
},
inspect: function() {
return inspect(this);
}
});
function copyComparisonConstantsToObject(obj) {
obj.START_TO_START = s2s;
obj.START_TO_END = s2e;
obj.END_TO_END = e2e;
obj.END_TO_START = e2s;
obj.NODE_BEFORE = n_b;
obj.NODE_AFTER = n_a;
obj.NODE_BEFORE_AND_AFTER = n_b_a;
obj.NODE_INSIDE = n_i;
}
function copyComparisonConstants(constructor) {
copyComparisonConstantsToObject(constructor);
copyComparisonConstantsToObject(constructor.prototype);
}
function createRangeContentRemover(remover, boundaryUpdater) {
return function() {
assertRangeValid(this);
var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer;
var iterator = new RangeIterator(this, true);
// Work out where to position the range after content removal
var node, boundary;
if (sc !== root) {
node = getClosestAncestorIn(sc, root, true);
boundary = getBoundaryAfterNode(node);
sc = boundary.node;
so = boundary.offset;
}
// Check none of the range is read-only
iterateSubtree(iterator, assertNodeNotReadOnly);
iterator.reset();
// Remove the content
var returnValue = remover(iterator);
iterator.detach();
// Move to the new position
boundaryUpdater(this, sc, so, sc, so);
return returnValue;
};
}
function createPrototypeRange(constructor, boundaryUpdater, detacher) {
function createBeforeAfterNodeSetter(isBefore, isStart) {
return function(node) {
assertNotDetached(this);
assertValidNodeType(node, beforeAfterNodeTypes);
assertValidNodeType(getRootContainer(node), rootContainerNodeTypes);
var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node);
(isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset);
};
}
function setRangeStart(range, node, offset) {
var ec = range.endContainer, eo = range.endOffset;
if (node !== range.startContainer || offset !== range.startOffset) {
// Check the root containers of the range and the new boundary, and also check whether the new boundary
// is after the current end. In either case, collapse the range to the new position
if (getRootContainer(node) != getRootContainer(ec) || comparePoints(node, offset, ec, eo) == 1) {
ec = node;
eo = offset;
}
boundaryUpdater(range, node, offset, ec, eo);
}
}
function setRangeEnd(range, node, offset) {
var sc = range.startContainer, so = range.startOffset;
if (node !== range.endContainer || offset !== range.endOffset) {
// Check the root containers of the range and the new boundary, and also check whether the new boundary
// is after the current end. In either case, collapse the range to the new position
if (getRootContainer(node) != getRootContainer(sc) || comparePoints(node, offset, sc, so) == -1) {
sc = node;
so = offset;
}
boundaryUpdater(range, sc, so, node, offset);
}
}
// Set up inheritance
var F = function() {};
F.prototype = api.rangePrototype;
constructor.prototype = new F();
util.extend(constructor.prototype, {
setStart: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
setRangeStart(this, node, offset);
},
setEnd: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
setRangeEnd(this, node, offset);
},
/**
* Convenience method to set a range's start and end boundaries. Overloaded as follows:
* - Two parameters (node, offset) creates a collapsed range at that position
* - Three parameters (node, startOffset, endOffset) creates a range contained with node starting at
* startOffset and ending at endOffset
* - Four parameters (startNode, startOffset, endNode, endOffset) creates a range starting at startOffset in
* startNode and ending at endOffset in endNode
*/
setStartAndEnd: function() {
assertNotDetached(this);
var args = arguments;
var sc = args[0], so = args[1], ec = sc, eo = so;
switch (args.length) {
case 3:
eo = args[2];
break;
case 4:
ec = args[2];
eo = args[3];
break;
}
boundaryUpdater(this, sc, so, ec, eo);
},
setBoundary: function(node, offset, isStart) {
this["set" + (isStart ? "Start" : "End")](node, offset);
},
setStartBefore: createBeforeAfterNodeSetter(true, true),
setStartAfter: createBeforeAfterNodeSetter(false, true),
setEndBefore: createBeforeAfterNodeSetter(true, false),
setEndAfter: createBeforeAfterNodeSetter(false, false),
collapse: function(isStart) {
assertRangeValid(this);
if (isStart) {
boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset);
} else {
boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset);
}
},
selectNodeContents: function(node) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
boundaryUpdater(this, node, 0, node, getNodeLength(node));
},
selectNode: function(node) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, false);
assertValidNodeType(node, beforeAfterNodeTypes);
var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node);
boundaryUpdater(this, start.node, start.offset, end.node, end.offset);
},
extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater),
deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater),
canSurroundContents: function() {
assertRangeValid(this);
assertNodeNotReadOnly(this.startContainer);
assertNodeNotReadOnly(this.endContainer);
// Check if the contents can be surrounded. Specifically, this means whether the range partially selects
// no non-text nodes.
var iterator = new RangeIterator(this, true);
var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) ||
(iterator._last && isNonTextPartiallySelected(iterator._last, this)));
iterator.detach();
return !boundariesInvalid;
},
detach: function() {
detacher(this);
},
splitBoundaries: function() {
splitRangeBoundaries(this);
},
splitBoundariesPreservingPositions: function(positionsToPreserve) {
splitRangeBoundaries(this, positionsToPreserve);
},
normalizeBoundaries: function() {
assertRangeValid(this);
var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset;
var mergeForward = function(node) {
var sibling = node.nextSibling;
if (sibling && sibling.nodeType == node.nodeType) {
ec = node;
eo = node.length;
node.appendData(sibling.data);
sibling.parentNode.removeChild(sibling);
}
};
var mergeBackward = function(node) {
var sibling = node.previousSibling;
if (sibling && sibling.nodeType == node.nodeType) {
sc = node;
var nodeLength = node.length;
so = sibling.length;
node.insertData(0, sibling.data);
sibling.parentNode.removeChild(sibling);
if (sc == ec) {
eo += so;
ec = sc;
} else if (ec == node.parentNode) {
var nodeIndex = getNodeIndex(node);
if (eo == nodeIndex) {
ec = node;
eo = nodeLength;
} else if (eo > nodeIndex) {
eo--;
}
}
}
};
var normalizeStart = true;
if (isCharacterDataNode(ec)) {
if (ec.length == eo) {
mergeForward(ec);
}
} else {
if (eo > 0) {
var endNode = ec.childNodes[eo - 1];
if (endNode && isCharacterDataNode(endNode)) {
mergeForward(endNode);
}
}
normalizeStart = !this.collapsed;
}
if (normalizeStart) {
if (isCharacterDataNode(sc)) {
if (so == 0) {
mergeBackward(sc);
}
} else {
if (so < sc.childNodes.length) {
var startNode = sc.childNodes[so];
if (startNode && isCharacterDataNode(startNode)) {
mergeBackward(startNode);
}
}
}
} else {
sc = ec;
so = eo;
}
boundaryUpdater(this, sc, so, ec, eo);
},
collapseToPoint: function(node, offset) {
assertNotDetached(this);
assertNoDocTypeNotationEntityAncestor(node, true);
assertValidOffset(node, offset);
this.setStartAndEnd(node, offset);
}
});
copyComparisonConstants(constructor);
}
/*----------------------------------------------------------------------------------------------------------------*/
// Updates commonAncestorContainer and collapsed after boundary change
function updateCollapsedAndCommonAncestor(range) {
range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
range.commonAncestorContainer = range.collapsed ?
range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer);
}
function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) {
range.startContainer = startContainer;
range.startOffset = startOffset;
range.endContainer = endContainer;
range.endOffset = endOffset;
range.document = dom.getDocument(startContainer);
updateCollapsedAndCommonAncestor(range);
}
function detach(range) {
assertNotDetached(range);
range.startContainer = range.startOffset = range.endContainer = range.endOffset = range.document = null;
range.collapsed = range.commonAncestorContainer = null;
}
function Range(doc) {
this.startContainer = doc;
this.startOffset = 0;
this.endContainer = doc;
this.endOffset = 0;
this.document = doc;
updateCollapsedAndCommonAncestor(this);
}
createPrototypeRange(Range, updateBoundaries, detach);
util.extend(Range, {
rangeProperties: rangeProperties,
RangeIterator: RangeIterator,
copyComparisonConstants: copyComparisonConstants,
createPrototypeRange: createPrototypeRange,
inspect: inspect,
getRangeDocument: getRangeDocument,
rangesEqual: function(r1, r2) {
return r1.startContainer === r2.startContainer &&
r1.startOffset === r2.startOffset &&
r1.endContainer === r2.endContainer &&
r1.endOffset === r2.endOffset;
}
});
api.DomRange = Range;
api.RangeException = RangeException;
});
rangy.createCoreModule("WrappedRange", ["DomRange"], function(api, module) {
var WrappedRange, WrappedTextRange;
var dom = api.dom;
var util = api.util;
var DomPosition = dom.DomPosition;
var DomRange = api.DomRange;
var getBody = dom.getBody;
var getContentDocument = dom.getContentDocument;
var isCharacterDataNode = dom.isCharacterDataNode;
/*----------------------------------------------------------------------------------------------------------------*/
if (api.features.implementsDomRange) {
// This is a wrapper around the browser's native DOM Range. It has two aims:
// - Provide workarounds for specific browser bugs
// - provide convenient extensions, which are inherited from Rangy's DomRange
(function() {
var rangeProto;
var rangeProperties = DomRange.rangeProperties;
function updateRangeProperties(range) {
var i = rangeProperties.length, prop;
while (i--) {
prop = rangeProperties[i];
range[prop] = range.nativeRange[prop];
}
// Fix for broken collapsed property in IE 9.
range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
}
function updateNativeRange(range, startContainer, startOffset, endContainer, endOffset) {
var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset);
var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset);
var nativeRangeDifferent = !range.equals(range.nativeRange);
// Always set both boundaries for the benefit of IE9 (see issue 35)
if (startMoved || endMoved || nativeRangeDifferent) {
range.setEnd(endContainer, endOffset);
range.setStart(startContainer, startOffset);
}
}
function detach(range) {
range.nativeRange.detach();
range.detached = true;
var i = rangeProperties.length;
while (i--) {
range[ rangeProperties[i] ] = null;
}
}
var createBeforeAfterNodeSetter;
WrappedRange = function(range) {
if (!range) {
throw module.createError("WrappedRange: Range must be specified");
}
this.nativeRange = range;
updateRangeProperties(this);
};
DomRange.createPrototypeRange(WrappedRange, updateNativeRange, detach);
rangeProto = WrappedRange.prototype;
rangeProto.selectNode = function(node) {
this.nativeRange.selectNode(node);
updateRangeProperties(this);
};
rangeProto.cloneContents = function() {
return this.nativeRange.cloneContents();
};
// Due to a long-standing Firefox bug that I have not been able to find a reliable way to detect,
// insertNode() is never delegated to the native range.
rangeProto.surroundContents = function(node) {
this.nativeRange.surroundContents(node);
updateRangeProperties(this);
};
rangeProto.collapse = function(isStart) {
this.nativeRange.collapse(isStart);
updateRangeProperties(this);
};
rangeProto.cloneRange = function() {
return new WrappedRange(this.nativeRange.cloneRange());
};
rangeProto.refresh = function() {
updateRangeProperties(this);
};
rangeProto.toString = function() {
return this.nativeRange.toString();
};
// Create test range and node for feature detection
var testTextNode = document.createTextNode("test");
getBody(document).appendChild(testTextNode);
var range = document.createRange();
/*--------------------------------------------------------------------------------------------------------*/
// Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and
// correct for it
range.setStart(testTextNode, 0);
range.setEnd(testTextNode, 0);
try {
range.setStart(testTextNode, 1);
rangeProto.setStart = function(node, offset) {
this.nativeRange.setStart(node, offset);
updateRangeProperties(this);
};
rangeProto.setEnd = function(node, offset) {
this.nativeRange.setEnd(node, offset);
updateRangeProperties(this);
};
createBeforeAfterNodeSetter = function(name) {
return function(node) {
this.nativeRange[name](node);
updateRangeProperties(this);
};
};
} catch(ex) {
rangeProto.setStart = function(node, offset) {
try {
this.nativeRange.setStart(node, offset);
} catch (ex) {
this.nativeRange.setEnd(node, offset);
this.nativeRange.setStart(node, offset);
}
updateRangeProperties(this);
};
rangeProto.setEnd = function(node, offset) {
try {
this.nativeRange.setEnd(node, offset);
} catch (ex) {
this.nativeRange.setStart(node, offset);
this.nativeRange.setEnd(node, offset);
}
updateRangeProperties(this);
};
createBeforeAfterNodeSetter = function(name, oppositeName) {
return function(node) {
try {
this.nativeRange[name](node);
} catch (ex) {
this.nativeRange[oppositeName](node);
this.nativeRange[name](node);
}
updateRangeProperties(this);
};
};
}
rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore");
rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter");
rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore");
rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter");
/*--------------------------------------------------------------------------------------------------------*/
// Always use DOM4-compliant selectNodeContents implementation: it's simpler and less code than testing
// whether the native implementation can be trusted
rangeProto.selectNodeContents = function(node) {
this.setStartAndEnd(node, 0, dom.getNodeLength(node));
};
/*--------------------------------------------------------------------------------------------------------*/
// Test for and correct WebKit bug that has the behaviour of compareBoundaryPoints round the wrong way for
// constants START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738
range.selectNodeContents(testTextNode);
range.setEnd(testTextNode, 3);
var range2 = document.createRange();
range2.selectNodeContents(testTextNode);
range2.setEnd(testTextNode, 4);
range2.setStart(testTextNode, 2);
if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 &&
range.compareBoundaryPoints(range.END_TO_START, range2) == 1) {
// This is the wrong way round, so correct for it
rangeProto.compareBoundaryPoints = function(type, range) {
range = range.nativeRange || range;
if (type == range.START_TO_END) {
type = range.END_TO_START;
} else if (type == range.END_TO_START) {
type = range.START_TO_END;
}
return this.nativeRange.compareBoundaryPoints(type, range);
};
} else {
rangeProto.compareBoundaryPoints = function(type, range) {
return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range);
};
}
/*--------------------------------------------------------------------------------------------------------*/
// Test for IE 9 deleteContents() and extractContents() bug and correct it. See issue 107.
var el = document.createElement("div");
el.innerHTML = "123";
var textNode = el.firstChild;
var body = getBody(document);
body.appendChild(el);
range.setStart(textNode, 1);
range.setEnd(textNode, 2);
range.deleteContents();
if (textNode.data == "13") {
// Behaviour is correct per DOM4 Range so wrap the browser's implementation of deleteContents() and
// extractContents()
rangeProto.deleteContents = function() {
this.nativeRange.deleteContents();
updateRangeProperties(this);
};
rangeProto.extractContents = function() {
var frag = this.nativeRange.extractContents();
updateRangeProperties(this);
return frag;
};
} else {
}
body.removeChild(el);
body = null;
/*--------------------------------------------------------------------------------------------------------*/
// Test for existence of createContextualFragment and delegate to it if it exists
if (util.isHostMethod(range, "createContextualFragment")) {
rangeProto.createContextualFragment = function(fragmentStr) {
return this.nativeRange.createContextualFragment(fragmentStr);
};
}
/*--------------------------------------------------------------------------------------------------------*/
// Clean up
getBody(document).removeChild(testTextNode);
range.detach();
range2.detach();
rangeProto.getName = function() {
return "WrappedRange";
};
api.WrappedRange = WrappedRange;
api.createNativeRange = function(doc) {
doc = getContentDocument(doc, module, "createNativeRange");
return doc.createRange();
};
})();
}
if (api.features.implementsTextRange) {
/*
This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement()
method. For example, in the following (where pipes denote the selection boundaries):
<ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul>
var range = document.selection.createRange();
alert(range.parentElement().id); // Should alert "ul" but alerts "b"
This method returns the common ancestor node of the following:
- the parentElement() of the textRange
- the parentElement() of the textRange after calling collapse(true)
- the parentElement() of the textRange after calling collapse(false)
*/
var getTextRangeContainerElement = function(textRange) {
var parentEl = textRange.parentElement();
var range = textRange.duplicate();
range.collapse(true);
var startEl = range.parentElement();
range = textRange.duplicate();
range.collapse(false);
var endEl = range.parentElement();
var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl);
return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer);
};
var textRangeIsCollapsed = function(textRange) {
return textRange.compareEndPoints("StartToEnd", textRange) == 0;
};
// Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started out as
// an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) but has
// grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange bugs, handling
// for inputs and images, plus optimizations.
var getTextRangeBoundaryPosition = function(textRange, wholeRangeContainerElement, isStart, isCollapsed, startInfo) {
var workingRange = textRange.duplicate();
workingRange.collapse(isStart);
var containerElement = workingRange.parentElement();
// Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so
// check for that
if (!dom.isOrIsAncestorOf(wholeRangeContainerElement, containerElement)) {
containerElement = wholeRangeContainerElement;
}
// Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and
// similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx
if (!containerElement.canHaveHTML) {
var pos = new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement));
return {
boundaryPosition: pos,
nodeInfo: {
nodeIndex: pos.offset,
containerElement: pos.node
}
};
}
var workingNode = dom.getDocument(containerElement).createElement("span");
// Workaround for HTML5 Shiv's insane violation of document.createElement(). See Rangy issue 104 and HTML5
// Shiv issue 64: https://github.com/aFarkas/html5shiv/issues/64
if (workingNode.parentNode) {
workingNode.parentNode.removeChild(workingNode);
}
var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd";
var previousNode, nextNode, boundaryPosition, boundaryNode;
var start = (startInfo && startInfo.containerElement == containerElement) ? startInfo.nodeIndex : 0;
var childNodeCount = containerElement.childNodes.length;
var end = childNodeCount;
// Check end first. Code within the loop assumes that the endth child node of the container is definitely
// after the range boundary.
var nodeIndex = end;
while (true) {
if (nodeIndex == childNodeCount) {
containerElement.appendChild(workingNode);
} else {
containerElement.insertBefore(workingNode, containerElement.childNodes[nodeIndex]);
}
workingRange.moveToElementText(workingNode);
comparison = workingRange.compareEndPoints(workingComparisonType, textRange);
if (comparison == 0 || start == end) {
break;
} else if (comparison == -1) {
if (end == start + 1) {
// We know the endth child node is after the range boundary, so we must be done.
break;
} else {
start = nodeIndex;
}
} else {
end = (end == start + 1) ? start : nodeIndex;
}
nodeIndex = Math.floor((start + end) / 2);
containerElement.removeChild(workingNode);
}
// We've now reached or gone past the boundary of the text range we're interested in
// so have identified the node we want
boundaryNode = workingNode.nextSibling;
if (comparison == -1 && boundaryNode && isCharacterDataNode(boundaryNode)) {
// This is a character data node (text, comment, cdata). The working range is collapsed at the start of the
// node containing the text range's boundary, so we move the end of the working range to the boundary point
// and measure the length of its text to get the boundary's offset within the node.
workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange);
var offset;
if (/[\r\n]/.test(boundaryNode.data)) {
/*
For the particular case of a boundary within a text node containing rendered line breaks (within a <pre>
element, for example), we need a slightly complicated approach to get the boundary's offset in IE. The
facts:
- Each line break is represented as \r in the text node's data/nodeValue properties
- Each line break is represented as \r\n in the TextRange's 'text' property
- The 'text' property of the TextRange does not contain trailing line breaks
To get round the problem presented by the final fact above, we can use the fact that TextRange's
moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily
the same as the number of characters it was instructed to move. The simplest approach is to use this to
store the characters moved when moving both the start and end of the range to the start of the document
body and subtracting the start offset from the end offset (the "move-negative-gazillion" method).
However, this is extremely slow when the document is large and the range is near the end of it. Clearly
doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same
problem.
Another approach that works is to use moveStart() to move the start boundary of the range up to the end
boundary one character at a time and incrementing a counter with the value returned by the moveStart()
call. However, the check for whether the start boundary has reached the end boundary is expensive, so
this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of
the range within the document).
The method below is a hybrid of the two methods above. It uses the fact that a string containing the
TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the
text of the TextRange, so the start of the range is moved that length initially and then a character at
a time to make up for any trailing line breaks not contained in the 'text' property. This has good
performance in most situations compared to the previous two methods.
*/
var tempRange = workingRange.duplicate();
var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length;
offset = tempRange.moveStart("character", rangeLength);
while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) {
offset++;
tempRange.moveStart("character", 1);
}
} else {
offset = workingRange.text.length;
}
boundaryPosition = new DomPosition(boundaryNode, offset);
} else {
// If the boundary immediately follows a character data node and this is the end boundary, we should favour
// a position within that, and likewise for a start boundary preceding a character data node
previousNode = (isCollapsed || !isStart) && workingNode.previousSibling;
nextNode = (isCollapsed || isStart) && workingNode.nextSibling;
if (nextNode && isCharacterDataNode(nextNode)) {
boundaryPosition = new DomPosition(nextNode, 0);
} else if (previousNode && isCharacterDataNode(previousNode)) {
boundaryPosition = new DomPosition(previousNode, previousNode.data.length);
} else {
boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode));
}
}
// Clean up
workingNode.parentNode.removeChild(workingNode);
return {
boundaryPosition: boundaryPosition,
nodeInfo: {
nodeIndex: nodeIndex,
containerElement: containerElement
}
};
};
// Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that node.
// This function started out as an optimized version of code found in Tim Cameron Ryan's IERange
// (http://code.google.com/p/ierange/)
var createBoundaryTextRange = function(boundaryPosition, isStart) {
var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset;
var doc = dom.getDocument(boundaryPosition.node);
var workingNode, childNodes, workingRange = getBody(doc).createTextRange();
var nodeIsDataNode = isCharacterDataNode(boundaryPosition.node);
if (nodeIsDataNode) {
boundaryNode = boundaryPosition.node;
boundaryParent = boundaryNode.parentNode;
} else {
childNodes = boundaryPosition.node.childNodes;
boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null;
boundaryParent = boundaryPosition.node;
}
// Position the range immediately before the node containing the boundary
workingNode = doc.createElement("span");
// Making the working element non-empty element persuades IE to consider the TextRange boundary to be within the
// element rather than immediately before or after it
workingNode.innerHTML = "&#feff;";
// insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report
// for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12
if (boundaryNode) {
boundaryParent.insertBefore(workingNode, boundaryNode);
} else {
boundaryParent.appendChild(workingNode);
}
workingRange.moveToElementText(workingNode);
workingRange.collapse(!isStart);
// Clean up
boundaryParent.removeChild(workingNode);
// Move the working range to the text offset, if required
if (nodeIsDataNode) {
workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset);
}
return workingRange;
};
/*------------------------------------------------------------------------------------------------------------*/
// This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a
// prototype
WrappedTextRange = function(textRange) {
this.textRange = textRange;
this.refresh();
};
WrappedTextRange.prototype = new DomRange(document);
WrappedTextRange.prototype.refresh = function() {
var start, end, startBoundary;
// TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that.
var rangeContainerElement = getTextRangeContainerElement(this.textRange);
if (textRangeIsCollapsed(this.textRange)) {
end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true,
true).boundaryPosition;
} else {
startBoundary = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false);
start = startBoundary.boundaryPosition;
// An optimization used here is that if the start and end boundaries have the same parent element, the
// search scope for the end boundary can be limited to exclude the portion of the element that precedes
// the start boundary
end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false,
startBoundary.nodeInfo).boundaryPosition;
}
this.setStart(start.node, start.offset);
this.setEnd(end.node, end.offset);
};
WrappedTextRange.prototype.getName = function() {
return "WrappedTextRange";
};
DomRange.copyComparisonConstants(WrappedTextRange);
WrappedTextRange.rangeToTextRange = function(range) {
if (range.collapsed) {
return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
} else {
var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true);
var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false);
var textRange = getBody( DomRange.getRangeDocument(range) ).createTextRange();
textRange.setEndPoint("StartToStart", startRange);
textRange.setEndPoint("EndToEnd", endRange);
return textRange;
}
};
api.WrappedTextRange = WrappedTextRange;
// IE 9 and above have both implementations and Rangy makes both available. The next few lines sets which
// implementation to use by default.
if (!api.features.implementsDomRange || api.config.preferTextRange) {
// Add WrappedTextRange as the Range property of the global object to allow expression like Range.END_TO_END to work
var globalObj = (function() { return this; })();
if (typeof globalObj.Range == "undefined") {
globalObj.Range = WrappedTextRange;
}
api.createNativeRange = function(doc) {
doc = getContentDocument(doc, module, "createNativeRange");
return getBody(doc).createTextRange();
};
api.WrappedRange = WrappedTextRange;
}
}
api.createRange = function(doc) {
doc = getContentDocument(doc, module, "createRange");
return new api.WrappedRange(api.createNativeRange(doc));
};
api.createRangyRange = function(doc) {
doc = getContentDocument(doc, module, "createRangyRange");
return new DomRange(doc);
};
api.createIframeRange = function(iframeEl) {
module.deprecationNotice("createIframeRange()", "createRange(iframeEl)");
return api.createRange(iframeEl);
};
api.createIframeRangyRange = function(iframeEl) {
module.deprecationNotice("createIframeRangyRange()", "createRangyRange(iframeEl)");
return api.createRangyRange(iframeEl);
};
api.addCreateMissingNativeApiListener(function(win) {
var doc = win.document;
if (typeof doc.createRange == "undefined") {
doc.createRange = function() {
return api.createRange(doc);
};
}
doc = win = null;
});
});
// This module creates a selection object wrapper that conforms as closely as possible to the Selection specification
// in the HTML Editing spec (http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#selections)
rangy.createCoreModule("WrappedSelection", ["DomRange", "WrappedRange"], function(api, module) {
api.config.checkSelectionRanges = true;
var BOOLEAN = "boolean";
var NUMBER = "number";
var dom = api.dom;
var util = api.util;
var isHostMethod = util.isHostMethod;
var DomRange = api.DomRange;
var WrappedRange = api.WrappedRange;
var DOMException = api.DOMException;
var DomPosition = dom.DomPosition;
var getNativeSelection;
var selectionIsCollapsed;
var features = api.features;
var CONTROL = "Control";
var getDocument = dom.getDocument;
var getBody = dom.getBody;
var rangesEqual = DomRange.rangesEqual;
// Utility function to support direction parameters in the API that may be a string ("backward" or "forward") or a
// Boolean (true for backwards).
function isDirectionBackward(dir) {
return (typeof dir == "string") ? /^backward(s)?$/i.test(dir) : !!dir;
}
function getWindow(win, methodName) {
if (!win) {
return window;
} else if (dom.isWindow(win)) {
return win;
} else if (win instanceof WrappedSelection) {
return win.win;
} else {
var doc = dom.getContentDocument(win, module, methodName);
return dom.getWindow(doc);
}
}
function getWinSelection(winParam) {
return getWindow(winParam, "getWinSelection").getSelection();
}
function getDocSelection(winParam) {
return getWindow(winParam, "getDocSelection").document.selection;
}
function winSelectionIsBackward(sel) {
var backward = false;
if (sel.anchorNode) {
backward = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1);
}
return backward;
}
// Test for the Range/TextRange and Selection features required
// Test for ability to retrieve selection
var implementsWinGetSelection = isHostMethod(window, "getSelection"),
implementsDocSelection = util.isHostObject(document, "selection");
features.implementsWinGetSelection = implementsWinGetSelection;
features.implementsDocSelection = implementsDocSelection;
var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange);
if (useDocumentSelection) {
getNativeSelection = getDocSelection;
api.isSelectionValid = function(winParam) {
var doc = getWindow(winParam, "isSelectionValid").document, nativeSel = doc.selection;
// Check whether the selection TextRange is actually contained within the correct document
return (nativeSel.type != "None" || getDocument(nativeSel.createRange().parentElement()) == doc);
};
} else if (implementsWinGetSelection) {
getNativeSelection = getWinSelection;
api.isSelectionValid = function() {
return true;
};
} else {
module.fail("Neither document.selection or window.getSelection() detected.");
}
api.getNativeSelection = getNativeSelection;
var testSelection = getNativeSelection();
var testRange = api.createNativeRange(document);
var body = getBody(document);
// Obtaining a range from a selection
var selectionHasAnchorAndFocus = util.areHostProperties(testSelection,
["anchorNode", "focusNode", "anchorOffset", "focusOffset"]);
features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus;
// Test for existence of native selection extend() method
var selectionHasExtend = isHostMethod(testSelection, "extend");
features.selectionHasExtend = selectionHasExtend;
// Test if rangeCount exists
var selectionHasRangeCount = (typeof testSelection.rangeCount == NUMBER);
features.selectionHasRangeCount = selectionHasRangeCount;
var selectionSupportsMultipleRanges = false;
var collapsedNonEditableSelectionsSupported = true;
var addRangeBackwardToNative = selectionHasExtend ?
function(nativeSelection, range) {
var doc = DomRange.getRangeDocument(range);
var endRange = api.createRange(doc);
endRange.collapseToPoint(range.endContainer, range.endOffset);
nativeSelection.addRange(getNativeRange(endRange));
nativeSelection.extend(range.startContainer, range.startOffset);
} : null;
if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) &&
typeof testSelection.rangeCount == NUMBER && features.implementsDomRange) {
(function() {
// Previously an iframe was used but this caused problems in some circumstances in IE, so tests are
// performed on the current document's selection. See issue 109.
// Note also that if a selection previously existed, it is wiped by these tests. This should usually be fine
// because initialization usually happens when the document loads, but could be a problem for a script that
// loads and initializes Rangy later. If anyone complains, code could be added to save and restore the
// selection.
var sel = window.getSelection();
if (sel) {
// Store the current selection
var originalSelectionRangeCount = sel.rangeCount;
var selectionHasMultipleRanges = (originalSelectionRangeCount > 1);
var originalSelectionRanges = [];
var originalSelectionBackward = winSelectionIsBackward(sel);
for (var i = 0; i < originalSelectionRangeCount; ++i) {
originalSelectionRanges[i] = sel.getRangeAt(i);
}
// Create some test elements
var body = getBody(document);
var testEl = body.appendChild( document.createElement("div") );
testEl.contentEditable = "false";
var textNode = testEl.appendChild( document.createTextNode("\u00a0\u00a0\u00a0") );
// Test whether the native selection will allow a collapsed selection within a non-editable element
var r1 = document.createRange();
r1.setStart(textNode, 1);
r1.collapse(true);
sel.addRange(r1);
collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1);
sel.removeAllRanges();
// Test whether the native selection is capable of supporting multiple ranges
if (!selectionHasMultipleRanges) {
var r2 = r1.cloneRange();
r1.setStart(textNode, 0);
r2.setEnd(textNode, 3);
r2.setStart(textNode, 2);
sel.addRange(r1);
sel.addRange(r2);
selectionSupportsMultipleRanges = (sel.rangeCount == 2);
r2.detach();
}
// Clean up
body.removeChild(testEl);
sel.removeAllRanges();
r1.detach();
for (i = 0; i < originalSelectionRangeCount; ++i) {
if (i == 0 && originalSelectionBackward) {
if (addRangeBackwardToNative) {
addRangeBackwardToNative(sel, originalSelectionRanges[i]);
} else {
api.warn("Rangy initialization: original selection was backwards but selection has been restored forwards because browser does not support Selection.extend");
sel.addRange(originalSelectionRanges[i])
}
} else {
sel.addRange(originalSelectionRanges[i])
}
}
}
})();
}
features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges;
features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported;
// ControlRanges
var implementsControlRange = false, testControlRange;
if (body && isHostMethod(body, "createControlRange")) {
testControlRange = body.createControlRange();
if (util.areHostProperties(testControlRange, ["item", "add"])) {
implementsControlRange = true;
}
}
features.implementsControlRange = implementsControlRange;
// Selection collapsedness
if (selectionHasAnchorAndFocus) {
selectionIsCollapsed = function(sel) {
return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset;
};
} else {
selectionIsCollapsed = function(sel) {
return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false;
};
}
function updateAnchorAndFocusFromRange(sel, range, backward) {
var anchorPrefix = backward ? "end" : "start", focusPrefix = backward ? "start" : "end";
sel.anchorNode = range[anchorPrefix + "Container"];
sel.anchorOffset = range[anchorPrefix + "Offset"];
sel.focusNode = range[focusPrefix + "Container"];
sel.focusOffset = range[focusPrefix + "Offset"];
}
function updateAnchorAndFocusFromNativeSelection(sel) {
var nativeSel = sel.nativeSelection;
sel.anchorNode = nativeSel.anchorNode;
sel.anchorOffset = nativeSel.anchorOffset;
sel.focusNode = nativeSel.focusNode;
sel.focusOffset = nativeSel.focusOffset;
}
function updateEmptySelection(sel) {
sel.anchorNode = sel.focusNode = null;
sel.anchorOffset = sel.focusOffset = 0;
sel.rangeCount = 0;
sel.isCollapsed = true;
sel._ranges.length = 0;
}
function getNativeRange(range) {
var nativeRange;
if (range instanceof DomRange) {
nativeRange = api.createNativeRange(range.getDocument());
nativeRange.setEnd(range.endContainer, range.endOffset);
nativeRange.setStart(range.startContainer, range.startOffset);
} else if (range instanceof WrappedRange) {
nativeRange = range.nativeRange;
} else if (features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) {
nativeRange = range;
}
return nativeRange;
}
function rangeContainsSingleElement(rangeNodes) {
if (!rangeNodes.length || rangeNodes[0].nodeType != 1) {
return false;
}
for (var i = 1, len = rangeNodes.length; i < len; ++i) {
if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) {
return false;
}
}
return true;
}
function getSingleElementFromRange(range) {
var nodes = range.getNodes();
if (!rangeContainsSingleElement(nodes)) {
throw module.createError("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element");
}
return nodes[0];
}
// Simple, quick test which only needs to distinguish between a TextRange and a ControlRange
function isTextRange(range) {
return !!range && typeof range.text != "undefined";
}
function updateFromTextRange(sel, range) {
// Create a Range from the selected TextRange
var wrappedRange = new WrappedRange(range);
sel._ranges = [wrappedRange];
updateAnchorAndFocusFromRange(sel, wrappedRange, false);
sel.rangeCount = 1;
sel.isCollapsed = wrappedRange.collapsed;
}
function updateControlSelection(sel) {
// Update the wrapped selection based on what's now in the native selection
sel._ranges.length = 0;
if (sel.docSelection.type == "None") {
updateEmptySelection(sel);
} else {
var controlRange = sel.docSelection.createRange();
if (isTextRange(controlRange)) {
// This case (where the selection type is "Control" and calling createRange() on the selection returns
// a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected
// ControlRange have been removed from the ControlRange and removed from the document.
updateFromTextRange(sel, controlRange);
} else {
sel.rangeCount = controlRange.length;
var range, doc = getDocument(controlRange.item(0));
for (var i = 0; i < sel.rangeCount; ++i) {
range = api.createRange(doc);
range.selectNode(controlRange.item(i));
sel._ranges.push(range);
}
sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed;
updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false);
}
}
}
function addRangeToControlSelection(sel, range) {
var controlRange = sel.docSelection.createRange();
var rangeElement = getSingleElementFromRange(range);
// Create a new ControlRange containing all the elements in the selected ControlRange plus the element
// contained by the supplied range
var doc = getDocument(controlRange.item(0));
var newControlRange = getBody(doc).createControlRange();
for (var i = 0, len = controlRange.length; i < len; ++i) {
newControlRange.add(controlRange.item(i));
}
try {
newControlRange.add(rangeElement);
} catch (ex) {
throw module.createError("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)");
}
newControlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(sel);
}
var getSelectionRangeAt;
if (isHostMethod(testSelection, "getRangeAt")) {
// try/catch is present because getRangeAt() must have thrown an error in some browser and some situation.
// Unfortunately, I didn't write a comment about the specifics and am now scared to take it out. Let that be a
// lesson to us all, especially me.
getSelectionRangeAt = function(sel, index) {
try {
return sel.getRangeAt(index);
} catch (ex) {
return null;
}
};
} else if (selectionHasAnchorAndFocus) {
getSelectionRangeAt = function(sel) {
var doc = getDocument(sel.anchorNode);
var range = api.createRange(doc);
range.setStartAndEnd(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset);
// Handle the case when the selection was selected backwards (from the end to the start in the
// document)
if (range.collapsed !== this.isCollapsed) {
range.setStartAndEnd(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset);
}
return range;
};
}
function WrappedSelection(selection, docSelection, win) {
this.nativeSelection = selection;
this.docSelection = docSelection;
this._ranges = [];
this.win = win;
this.refresh();
}
WrappedSelection.prototype = api.selectionPrototype;
function deleteProperties(sel) {
sel.win = sel.anchorNode = sel.focusNode = sel._ranges = null;
sel.rangeCount = sel.anchorOffset = sel.focusOffset = 0;
sel.detached = true;
}
var cachedRangySelections = [];
function actOnCachedSelection(win, action) {
var i = cachedRangySelections.length, cached, sel;
while (i--) {
cached = cachedRangySelections[i];
sel = cached.selection;
if (action == "deleteAll") {
deleteProperties(sel);
} else if (cached.win == win) {
if (action == "delete") {
cachedRangySelections.splice(i, 1);
return true;
} else {
return sel;
}
}
}
if (action == "deleteAll") {
cachedRangySelections.length = 0;
}
return null;
}
var getSelection = function(win) {
// Check if the parameter is a Rangy Selection object
if (win && win instanceof WrappedSelection) {
win.refresh();
return win;
}
win = getWindow(win, "getNativeSelection");
var sel = actOnCachedSelection(win);
var nativeSel = getNativeSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null;
if (sel) {
sel.nativeSelection = nativeSel;
sel.docSelection = docSel;
sel.refresh();
} else {
sel = new WrappedSelection(nativeSel, docSel, win);
cachedRangySelections.push( { win: win, selection: sel } );
}
return sel;
};
api.getSelection = getSelection;
api.getIframeSelection = function(iframeEl) {
module.deprecationNotice("getIframeSelection()", "getSelection(iframeEl)");
return api.getSelection(dom.getIframeWindow(iframeEl));
};
var selProto = WrappedSelection.prototype;
function createControlSelection(sel, ranges) {
// Ensure that the selection becomes of type "Control"
var doc = getDocument(ranges[0].startContainer);
var controlRange = getBody(doc).createControlRange();
for (var i = 0, el, len = ranges.length; i < len; ++i) {
el = getSingleElementFromRange(ranges[i]);
try {
controlRange.add(el);
} catch (ex) {
throw module.createError("setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)");
}
}
controlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(sel);
}
// Selecting a range
if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) {
selProto.removeAllRanges = function() {
this.nativeSelection.removeAllRanges();
updateEmptySelection(this);
};
var addRangeBackward = function(sel, range) {
addRangeBackwardToNative(sel.nativeSelection, range);
sel.refresh();
};
if (selectionHasRangeCount) {
selProto.addRange = function(range, direction) {
if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
addRangeToControlSelection(this, range);
} else {
if (isDirectionBackward(direction) && selectionHasExtend) {
addRangeBackward(this, range);
} else {
var previousRangeCount;
if (selectionSupportsMultipleRanges) {
previousRangeCount = this.rangeCount;
} else {
this.removeAllRanges();
previousRangeCount = 0;
}
// Clone the native range so that changing the selected range does not affect the selection.
// This is contrary to the spec but is the only way to achieve consistency between browsers. See
// issue 80.
this.nativeSelection.addRange(getNativeRange(range).cloneRange());
// Check whether adding the range was successful
this.rangeCount = this.nativeSelection.rangeCount;
if (this.rangeCount == previousRangeCount + 1) {
// The range was added successfully
// Check whether the range that we added to the selection is reflected in the last range extracted from
// the selection
if (api.config.checkSelectionRanges) {
var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1);
if (nativeRange && !rangesEqual(nativeRange, range)) {
// Happens in WebKit with, for example, a selection placed at the start of a text node
range = new WrappedRange(nativeRange);
}
}
this._ranges[this.rangeCount - 1] = range;
updateAnchorAndFocusFromRange(this, range, selectionIsBackward(this.nativeSelection));
this.isCollapsed = selectionIsCollapsed(this);
} else {
// The range was not added successfully. The simplest thing is to refresh
this.refresh();
}
}
}
};
} else {
selProto.addRange = function(range, direction) {
if (isDirectionBackward(direction) && selectionHasExtend) {
addRangeBackward(this, range);
} else {
this.nativeSelection.addRange(getNativeRange(range));
this.refresh();
}
};
}
selProto.setRanges = function(ranges) {
if (implementsControlRange && ranges.length > 1) {
createControlSelection(this, ranges);
} else {
this.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
this.addRange(ranges[i]);
}
}
};
} else if (isHostMethod(testSelection, "empty") && isHostMethod(testRange, "select") &&
implementsControlRange && useDocumentSelection) {
selProto.removeAllRanges = function() {
// Added try/catch as fix for issue #21
try {
this.docSelection.empty();
// Check for empty() not working (issue #24)
if (this.docSelection.type != "None") {
// Work around failure to empty a control selection by instead selecting a TextRange and then
// calling empty()
var doc;
if (this.anchorNode) {
doc = getDocument(this.anchorNode);
} else if (this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
if (controlRange.length) {
doc = getDocument( controlRange.item(0) );
}
}
if (doc) {
var textRange = getBody(doc).createTextRange();
textRange.select();
this.docSelection.empty();
}
}
} catch(ex) {}
updateEmptySelection(this);
};
selProto.addRange = function(range) {
if (this.docSelection.type == CONTROL) {
addRangeToControlSelection(this, range);
} else {
api.WrappedTextRange.rangeToTextRange(range).select();
this._ranges[0] = range;
this.rangeCount = 1;
this.isCollapsed = this._ranges[0].collapsed;
updateAnchorAndFocusFromRange(this, range, false);
}
};
selProto.setRanges = function(ranges) {
this.removeAllRanges();
var rangeCount = ranges.length;
if (rangeCount > 1) {
createControlSelection(this, ranges);
} else if (rangeCount) {
this.addRange(ranges[0]);
}
};
} else {
module.fail("No means of selecting a Range or TextRange was found");
return false;
}
selProto.getRangeAt = function(index) {
if (index < 0 || index >= this.rangeCount) {
throw new DOMException("INDEX_SIZE_ERR");
} else {
// Clone the range to preserve selection-range independence. See issue 80.
return this._ranges[index].cloneRange();
}
};
var refreshSelection;
if (useDocumentSelection) {
refreshSelection = function(sel) {
var range;
if (api.isSelectionValid(sel.win)) {
range = sel.docSelection.createRange();
} else {
range = getBody(sel.win.document).createTextRange();
range.collapse(true);
}
if (sel.docSelection.type == CONTROL) {
updateControlSelection(sel);
} else if (isTextRange(range)) {
updateFromTextRange(sel, range);
} else {
updateEmptySelection(sel);
}
};
} else if (isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == NUMBER) {
refreshSelection = function(sel) {
if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) {
updateControlSelection(sel);
} else {
sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount;
if (sel.rangeCount) {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i));
}
updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackward(sel.nativeSelection));
sel.isCollapsed = selectionIsCollapsed(sel);
} else {
updateEmptySelection(sel);
}
}
};
} else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && features.implementsDomRange) {
refreshSelection = function(sel) {
var range, nativeSel = sel.nativeSelection;
if (nativeSel.anchorNode) {
range = getSelectionRangeAt(nativeSel, 0);
sel._ranges = [range];
sel.rangeCount = 1;
updateAnchorAndFocusFromNativeSelection(sel);
sel.isCollapsed = selectionIsCollapsed(sel);
} else {
updateEmptySelection(sel);
}
};
} else {
module.fail("No means of obtaining a Range or TextRange from the user's selection was found");
return false;
}
selProto.refresh = function(checkForChanges) {
var oldRanges = checkForChanges ? this._ranges.slice(0) : null;
var oldAnchorNode = this.anchorNode, oldAnchorOffset = this.anchorOffset;
refreshSelection(this);
if (checkForChanges) {
// Check the range count first
var i = oldRanges.length;
if (i != this._ranges.length) {
return true;
}
// Now check the direction. Checking the anchor position is the same is enough since we're checking all the
// ranges after this
if (this.anchorNode != oldAnchorNode || this.anchorOffset != oldAnchorOffset) {
return true;
}
// Finally, compare each range in turn
while (i--) {
if (!rangesEqual(oldRanges[i], this._ranges[i])) {
return true;
}
}
return false;
}
};
// Removal of a single range
var removeRangeManually = function(sel, range) {
var ranges = sel.getAllRanges();
sel.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
if (!rangesEqual(range, ranges[i])) {
sel.addRange(ranges[i]);
}
}
if (!sel.rangeCount) {
updateEmptySelection(sel);
}
};
if (implementsControlRange) {
selProto.removeRange = function(range) {
if (this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
var rangeElement = getSingleElementFromRange(range);
// Create a new ControlRange containing all the elements in the selected ControlRange minus the
// element contained by the supplied range
var doc = getDocument(controlRange.item(0));
var newControlRange = getBody(doc).createControlRange();
var el, removed = false;
for (var i = 0, len = controlRange.length; i < len; ++i) {
el = controlRange.item(i);
if (el !== rangeElement || removed) {
newControlRange.add(controlRange.item(i));
} else {
removed = true;
}
}
newControlRange.select();
// Update the wrapped selection based on what's now in the native selection
updateControlSelection(this);
} else {
removeRangeManually(this, range);
}
};
} else {
selProto.removeRange = function(range) {
removeRangeManually(this, range);
};
}
// Detecting if a selection is backward
var selectionIsBackward;
if (!useDocumentSelection && selectionHasAnchorAndFocus && features.implementsDomRange) {
selectionIsBackward = winSelectionIsBackward;
selProto.isBackward = function() {
return selectionIsBackward(this);
};
} else {
selectionIsBackward = selProto.isBackward = function() {
return false;
};
}
// Create an alias for backwards compatibility. From 1.3, everything is "backward" rather than "backwards"
selProto.isBackwards = selProto.isBackward;
// Selection stringifier
// This is conformant to the old HTML5 selections draft spec but differs from WebKit and Mozilla's implementation.
// The current spec does not yet define this method.
selProto.toString = function() {
var rangeTexts = [];
for (var i = 0, len = this.rangeCount; i < len; ++i) {
rangeTexts[i] = "" + this._ranges[i];
}
return rangeTexts.join("");
};
function assertNodeInSameDocument(sel, node) {
if (sel.win.document != getDocument(node)) {
throw new DOMException("WRONG_DOCUMENT_ERR");
}
}
// No current browser conforms fully to the spec for this method, so Rangy's own method is always used
selProto.collapse = function(node, offset) {
assertNodeInSameDocument(this, node);
var range = api.createRange(node);
range.collapseToPoint(node, offset);
this.setSingleRange(range);
this.isCollapsed = true;
};
selProto.collapseToStart = function() {
if (this.rangeCount) {
var range = this._ranges[0];
this.collapse(range.startContainer, range.startOffset);
} else {
throw new DOMException("INVALID_STATE_ERR");
}
};
selProto.collapseToEnd = function() {
if (this.rangeCount) {
var range = this._ranges[this.rangeCount - 1];
this.collapse(range.endContainer, range.endOffset);
} else {
throw new DOMException("INVALID_STATE_ERR");
}
};
// The spec is very specific on how selectAllChildren should be implemented so the native implementation is
// never used by Rangy.
selProto.selectAllChildren = function(node) {
assertNodeInSameDocument(this, node);
var range = api.createRange(node);
range.selectNodeContents(node);
console.log("before", range.inspect());
this.setSingleRange(range);
console.log("after", this._ranges[0].inspect());
};
selProto.deleteFromDocument = function() {
// Sepcial behaviour required for IE's control selections
if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) {
var controlRange = this.docSelection.createRange();
var element;
while (controlRange.length) {
element = controlRange.item(0);
controlRange.remove(element);
element.parentNode.removeChild(element);
}
this.refresh();
} else if (this.rangeCount) {
var ranges = this.getAllRanges();
if (ranges.length) {
this.removeAllRanges();
for (var i = 0, len = ranges.length; i < len; ++i) {
ranges[i].deleteContents();
}
// The spec says nothing about what the selection should contain after calling deleteContents on each
// range. Firefox moves the selection to where the final selected range was, so we emulate that
this.addRange(ranges[len - 1]);
}
}
};
// The following are non-standard extensions
selProto.eachRange = function(func, returnValue) {
for (var i = 0, len = this._ranges.length; i < len; ++i) {
if ( func( this.getRangeAt(i) ) ) {
return returnValue;
}
}
};
selProto.getAllRanges = function() {
var ranges = [];
this.eachRange(function(range) {
ranges.push(range);
});
return ranges;
};
selProto.setSingleRange = function(range, direction) {
this.removeAllRanges();
this.addRange(range, direction);
};
selProto.callMethodOnEachRange = function(methodName, params) {
var results = [];
this.eachRange( function(range) {
results.push( range[methodName].apply(range, params) );
} );
return results;
};
function createStartOrEndSetter(isStart) {
return function(node, offset) {
var range;
if (this.rangeCount) {
range = this.getRangeAt(0);
range["set" + (isStart ? "Start" : "End")](node, offset);
} else {
range = api.createRange(this.win.document);
range.setStartAndEnd(node, offset);
}
this.setSingleRange(range, this.isBackward());
};
}
selProto.setStart = createStartOrEndSetter(true);
selProto.setEnd = createStartOrEndSetter(false);
// Add select() method to Range prototype. Any existing selection will be removed.
api.rangePrototype.select = function(direction) {
getSelection( this.getDocument() ).setSingleRange(this, direction);
};
selProto.changeEachRange = function(func) {
var ranges = [];
var backward = this.isBackward();
this.eachRange(function(range) {
func(range);
ranges.push(range);
});
this.removeAllRanges();
if (backward && ranges.length == 1) {
this.addRange(ranges[0], "backward");
} else {
this.setRanges(ranges);
}
};
selProto.containsNode = function(node, allowPartial) {
return this.eachRange( function(range) {
return range.containsNode(node, allowPartial);
}, true );
};
selProto.getBookmark = function(containerNode) {
return {
backward: this.isBackward(),
rangeBookmarks: this.callMethodOnEachRange("getBookmark", [containerNode])
};
};
selProto.moveToBookmark = function(bookmark) {
var selRanges = [];
for (var i = 0, rangeBookmark, range; rangeBookmark = bookmark.rangeBookmarks[i++]; ) {
range = api.createRange(this.win);
range.moveToBookmark(rangeBookmark);
selRanges.push(range);
}
if (bookmark.backward) {
this.setSingleRange(selRanges[0], "backward");
} else {
this.setRanges(selRanges);
}
};
selProto.toHtml = function() {
return this.callMethodOnEachRange("toHtml").join("");
};
function inspect(sel) {
var rangeInspects = [];
var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset);
var focus = new DomPosition(sel.focusNode, sel.focusOffset);
var name = (typeof sel.getName == "function") ? sel.getName() : "Selection";
if (typeof sel.rangeCount != "undefined") {
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i));
}
}
return "[" + name + "(Ranges: " + rangeInspects.join(", ") +
")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]";
}
selProto.getName = function() {
return "WrappedSelection";
};
selProto.inspect = function() {
return inspect(this);
};
selProto.detach = function() {
actOnCachedSelection(this.win, "delete");
deleteProperties(this);
};
WrappedSelection.detachAll = function() {
actOnCachedSelection(null, "deleteAll");
};
WrappedSelection.inspect = inspect;
WrappedSelection.isDirectionBackward = isDirectionBackward;
api.Selection = WrappedSelection;
api.selectionPrototype = selProto;
api.addCreateMissingNativeApiListener(function(win) {
if (typeof win.getSelection == "undefined") {
win.getSelection = function() {
return getSelection(win);
};
}
win = null;
});
});
|
import toDate from '../toDate/index.js'
/**
* @name isBefore
* @category Common Helpers
* @summary Is the first date before the second one?
*
* @description
* Is the first date before the second one?
*
* @param {Date|String|Number} date - the date that should be before the other one to return true
* @param {Date|String|Number} dateToCompare - the date to compare with
* @param {Options} [options] - the object with options. See [Options]{@link https://date-fns.org/docs/Options}
* @param {0|1|2} [options.additionalDigits=2] - passed to `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
* @returns {Boolean} the first date is before the second date
* @throws {TypeError} 2 arguments required
* @throws {RangeError} `options.additionalDigits` must be 0, 1 or 2
*
* @example
* // Is 10 July 1989 before 11 February 1987?
* var result = isBefore(new Date(1989, 6, 10), new Date(1987, 1, 11))
* //=> false
*/
export default function isBefore (dirtyDate, dirtyDateToCompare, dirtyOptions) {
if (arguments.length < 2) {
throw new TypeError('2 arguments required, but only ' + arguments.length + ' present')
}
var date = toDate(dirtyDate, dirtyOptions)
var dateToCompare = toDate(dirtyDateToCompare, dirtyOptions)
return date.getTime() < dateToCompare.getTime()
}
|
var fs = require('fs');
var path = require('path');
var jsdom = require('jsdom').jsdom;
var sinon = global.sinon = require('sinon');
require("sinon/lib/sinon/util/event");
require("sinon/lib/sinon/util/fake_xml_http_request");
module.exports = fakedom;
/**
* Options
* Callback
*/
function fakedom(options, onInit) {
if (arguments.length === 1) {
onInit = options;
options = {};
}
var window = getWindow(options.html, options.jsdomOptions);
augmentWindow.call(
this,
window,
options.disableConsole,
options.disableXhr
);
initRequire(window, options.requireOptions, function(err) {
if (!options.module) {
return onInit(err, window);
}
this.amdrequire(options.module, function(err, module) {
if (err) {
return onInit(err);
}
return onInit(null, window, module);
});
}.bind(this));
this.amdrequire = function(deps, onAmdLoad) {
if (!window) {
return onAmdLoad(new Error(
'Could not require module because load() has not been run'
));
}
if (!window.require || typeof window.require !== 'function') {
return onAmdLoad(new Error('requirejs failed to initialise'));
}
deps = Array.isArray(deps) ? deps : [ deps ];
makeSetTimeoutSafe(window);
window.require(deps, function() {
restoreSetTimeout(window);
var args = Array.prototype.slice.call(arguments);
args.unshift(null);
onAmdLoad.apply(null, args);
}, function(err) {
onAmdLoad(err);
});
return this;
}
this.stub = function(name, module) {
if (arguments.length === 2 ) {
var stubs = {};
stubs[name] = module;
name = stubs;
}
Object.keys(name).forEach(function(moduleName) {
window.define(moduleName, name[moduleName]);
});
return this;
}
}
function getWindow(html, jsdomOptions) {
html = html || '';
if (html.indexOf('<body') === -1) {
html = '<html><head></head><body>' + html + '</body></html>';
}
var level = null; // defaults to 3
var options = jsdomOptions || {};
var doc = jsdom(html, options);
return doc.parentWindow;
}
function augmentWindow(window, disableConsole, disableXhr) {
// Allow AMD modules to use console to log to STDOUT/ERR
if (!disableConsole) {
window.console = console;
}
// Provide fake XHR
if (!disableXhr) {
this.requests = [];
xhr = sinon.useFakeXMLHttpRequest();
xhr.onCreate = function(req) {
this.requests.push(req);
}.bind(this);
window.XMLHttpRequest = xhr;
}
}
function initRequire(window, options, onRequireLoad) {
// Set require.js options
window.require = options;
var requirePath = path.resolve(
__dirname,
'./node_modules/requirejs/require.js'
);
fs.exists(requirePath, function(exists) {
if (!exists) {
var err = new Error(
'Could not load require.js at path ' + requirePath
);
return onRequireLoad(err);
}
makeSetTimeoutSafe(window);
var scriptEl = window.document.createElement('script');
scriptEl.src = requirePath;
scriptEl.onload = function() {
restoreSetTimeout(window);
onRequireLoad();
}
window.document.body.appendChild(scriptEl);
});
}
// Nasty stuff to ensure that requirejs can still load modules even when
// setTimeout has been stubbed
var oldTimeout;
function makeSetTimeoutSafe(window) {
oldTimeout = window.setTimeout;
window.setTimeout = function(fn) {
fn();
}
}
function restoreSetTimeout(window) {
window.setTimeout = oldTimeout;
}
|
import Modifier from 'ember-class-based-modifier';
import { getOwner } from '@ember/application';
export default class RecognizeGestureModifier extends Modifier {
constructor() {
super(...arguments);
this.recognizers = null;
this.manager = null;
this.gestures = getOwner(this).lookup('service:-gestures');
if (this.args.positional) {
this.recognizers = this.gestures.retrieve(this.args.positional);
}
this.managerOptions = (this.args.named && (Object.keys(this.args.named).length > 0)) ? Object.assign({}, this.args.named) : { domEvents: true };
this.managerOptions.useCapture = this.gestures.useCapture;
}
didInstall() {
if (!this.recognizers) return;
this.element.style['touch-action'] = 'manipulation';
this.element.style['-ms-touch-action'] = 'manipulation';
this.recognizers.then ( (recognizers) => {
if (this.isDestroyed) return;
this.sortRecognizers(recognizers);
this.manager = new Hammer.Manager(this.element, this.managerOptions);
recognizers.forEach((recognizer) => { this.manager.add(recognizer); });
});
}
willRemove() {
this.manager.destroy();
this.manager = null;
}
// Move each recognizer after all recognizers it excludes in the list - why?
sortRecognizers(recognizers) {
for (let i = 0; i < recognizers.length; i++) {
const r = recognizers[i];
let currentIndex = i;
if (r.exclude.length) {
for (let j = 0; j < r.exclude.length; j++) {
const newIndex = recognizers.indexOf(r.exclude[j]);
if (newIndex > 0 && currentIndex < newIndex) {
recognizers.splice(currentIndex, 1);
recognizers.splice(newIndex, 0, r);
currentIndex = newIndex;
}
}
}
}
}
}
|
// sends an SMS with the name of a friend and the friend's phone number to another number authorized to receive SMS's
var twilioSID = process.env.TWILIO_ACCOUNT_SID;
var twilioAuthToken = process.env.TWILIO_AUTH_TOKEN;
var Promise = require('bluebird');
var sendMessage = Promise.promisify(require('twilio')(twilioSID, twilioAuthToken).sendMessage);
var FROM_PHONE_NUMBER = process.env.TWILIO_FROM_NUMBER;
/**
* Sends an SMS message to the recipient with the body "name: phoneNumber"
* @param recipient {String} phone number of the recipipient (e.g. '+16515556677')
* @param name {String} name of the friend (e.g. Sagar Batchu)
* @param phoneNumber {String} phone number of the friend (e.g. '+16515556677')
* @returns {Response} reponse object from Twilio
*/
exports = module.exports = function(recipient, name, phoneNumber) {
// make sure credentials are set
if (!FROM_PHONE_NUMBER) {
throw Error('must set TWILIO_FROM_NUMBER environment variable');
}
return sendMessage({
to: recipient,
from: FROM_PHONE_NUMBER,
body: name + ": " + phoneNumber
});
};
|
import TwilioVideo from "TwilioVideo"
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<TwilioVideo />
);
}); |
(function (Controllers, undefined)
{
Controllers.GeneralCtrl = ['$scope', '$routeParams', '$location', '$http', 'generalFactory', function ($scope, $routeParams, $location, $http, generalFactory)
{
var scope = $scope;
scope.location = $location;
scope.routeParams = $routeParams;
scope.mainNav = [];
/**
* Factory for obtaining navigation from json file
**/
generalFactory.getMainLinks(function (results)
{
scope.mainNav = results[0].bookItems;
});
}];
}(DorianDelmontez.Controllers = DorianDelmontez.Controllers || {} )); |
'use strict';
/**
* Module dependencies.
*/
var config = require('../config'),
express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
multer = require('multer'),
favicon = require('serve-favicon'),
compress = require('compression'),
methodOverride = require('method-override'),
cookieParser = require('cookie-parser'),
helmet = require('helmet'),
flash = require('connect-flash'),
consolidate = require('consolidate'),
path = require('path');
/**
* Initialize local variables
*/
module.exports.initLocalVariables = function (app) {
// Setting application local variables
app.locals.title = config.app.title;
app.locals.description = config.app.description;
if (config.secure && config.secure.ssl === true) {
app.locals.secure = config.secure.ssl;
}
app.locals.keywords = config.app.keywords;
app.locals.googleAnalyticsTrackingID = config.app.googleAnalyticsTrackingID;
app.locals.facebookAppId = config.facebook.clientID;
app.locals.jsFiles = config.files.client.js;
app.locals.cssFiles = config.files.client.css;
app.locals.livereload = config.livereload;
app.locals.logo = config.logo;
app.locals.favicon = config.favicon;
// Passing the request url to environment locals
app.use(function (req, res, next) {
res.locals.host = req.protocol + '://' + req.hostname;
res.locals.url = req.protocol + '://' + req.headers.host + req.originalUrl;
next();
});
};
/**
* Initialize application middleware
*/
module.exports.initMiddleware = function (app) {
// Showing stack errors
app.set('showStackError', true);
// Enable jsonp
app.enable('jsonp callback');
// Should be placed before express.static
app.use(compress({
filter: function (req, res) {
return (/json|text|javascript|css|font|svg/).test(res.getHeader('Content-Type'));
},
level: 9
}));
// Initialize favicon middleware
app.use(favicon('./modules/core/client/img/brand/favicon.ico'));
// Environment dependent middleware
if (process.env.NODE_ENV === 'development') {
// Enable logger (morgan)
app.use(morgan('dev'));
// Disable views cache
app.set('view cache', false);
} else if (process.env.NODE_ENV === 'production') {
app.locals.cache = 'memory';
}
// Request body parsing middleware should be above methodOverride
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
// Add the cookie parser and flash middleware
app.use(cookieParser());
app.use(flash());
// Add multipart handling middleware
app.use(multer({
dest: './uploads/',
inMemory: true
}));
};
/**
* Configure view engine
*/
module.exports.initViewEngine = function (app) {
// Set swig as the template engine
app.engine('server.view.html', consolidate[config.templateEngine]);
// Set views path and view engine
app.set('view engine', 'server.view.html');
app.set('views', './');
};
/**
* Configure Express session
*/
module.exports.initSession = function (app, db) {
// Express MongoDB session storage
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
cookie: {
maxAge: config.sessionCookie.maxAge,
httpOnly: config.sessionCookie.httpOnly,
secure: config.sessionCookie.secure && config.secure.ssl
},
key: config.sessionKey,
store: new MongoStore({
mongooseConnection: db.connection,
collection: config.sessionCollection
})
}));
};
/**
* Invoke modules server configuration
*/
module.exports.initModulesConfiguration = function (app, db) {
config.files.server.configs.forEach(function (configPath) {
require(path.resolve(configPath))(app, db);
});
};
/**
* Configure Helmet headers configuration
*/
module.exports.initHelmetHeaders = function (app) {
// Use helmet to secure Express headers
var SIX_MONTHS = 15778476000;
app.use(helmet.xframe());
app.use(helmet.xssFilter());
app.use(helmet.nosniff());
app.use(helmet.ienoopen());
app.use(helmet.hsts({
maxAge: SIX_MONTHS,
includeSubdomains: true,
force: true
}));
app.disable('x-powered-by');
};
/**
* Configure the modules static routes
*/
module.exports.initModulesClientRoutes = function (app) {
// Setting the app router and static folder
app.use('/', express.static(path.resolve('./public')));
// Globbing static routing
config.folders.client.forEach(function (staticPath) {
app.use(staticPath, express.static(path.resolve('./' + staticPath)));
});
};
/**
* Configure the modules ACL policies
*/
module.exports.initModulesServerPolicies = function (app) {
// Globbing policy files
config.files.server.policies.forEach(function (policyPath) {
require(path.resolve(policyPath)).invokeRolesPolicies();
});
};
/**
* Configure the modules server routes
*/
module.exports.initModulesServerRoutes = function (app) {
// Globbing routing files
config.files.server.routes.forEach(function (routePath) {
require(path.resolve(routePath))(app);
});
};
/**
* Configure error handling
*/
module.exports.initErrorRoutes = function (app) {
app.use(function (err, req, res, next) {
// If the error object doesn't exists
if (!err) {
return next();
}
// Log it
console.error(err.stack);
// Redirect to error page
res.redirect('/server-error');
});
};
/**
* Configure Socket.io
*/
module.exports.configureSocketIO = function (app, db) {
// Load the Socket.io configuration
var server = require('./socket.io')(app, db);
// Return server object
return server;
};
/**
* Initialize the Express application
*/
module.exports.init = function (db) {
// Initialize express app
var app = express();
// Initialize local variables
this.initLocalVariables(app);
// Initialize Express middleware
this.initMiddleware(app);
// Initialize Express view engine
this.initViewEngine(app);
// Initialize Express session
this.initSession(app, db);
// Initialize Modules configuration
this.initModulesConfiguration(app);
// Initialize Helmet security headers
this.initHelmetHeaders(app);
// Initialize modules static client routes
this.initModulesClientRoutes(app);
// Initialize modules server authorization policies
this.initModulesServerPolicies(app);
// Initialize modules server routes
this.initModulesServerRoutes(app);
// Initialize error routes
this.initErrorRoutes(app);
// Configure Socket.io
app = this.configureSocketIO(app, db);
return app;
};
|
/* =========================================================
* bootstrap-datepicker.js
* http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Copyright 2012 Stefan Petre
* Improvements by Andrew Rowls
*
* 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.
* ========================================================= */
!function( $ ) {
function UTCDate(){
return new Date(Date.UTC.apply(Date, arguments));
}
function UTCToday(){
var today = new Date();
return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate());
}
// Picker object
var Datepicker = function(element, options) {
var that = this;
this.element = $(element);
this.language = options.language||this.element.data('date-language')||"en";
this.language = this.language in dates ? this.language : "en";
this.isRTL = dates[this.language].rtl||false;
this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||dates[this.language].format||'mm/dd/yyyy');
this.isInline = false;
this.isInput = this.element.is('input');
this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
this.hasInput = this.component && this.element.find('input').length;
if(this.component && this.component.length === 0)
this.component = false;
this._attachEvents();
this.forceParse = true;
if ('forceParse' in options) {
this.forceParse = options.forceParse;
} else if ('dateForceParse' in this.element.data()) {
this.forceParse = this.element.data('date-force-parse');
}
this.picker = $(DPGlobal.template)
.appendTo(this.isInline ? this.element : 'body')
.on({
click: $.proxy(this.click, this),
mousedown: $.proxy(this.mousedown, this)
});
if(this.isInline) {
this.picker.addClass('datepicker-inline');
} else {
this.picker.addClass('datepicker-dropdown dropdown-menu');
}
if (this.isRTL){
this.picker.addClass('datepicker-rtl');
this.picker.find('.prev i, .next i')
.toggleClass('icon-arrow-left icon-arrow-right');
}
$(document).on('mousedown', function (e) {
// Clicked outside the datepicker, hide it
if ($(e.target).closest('.datepicker.datepicker-inline, .datepicker.datepicker-dropdown').length === 0) {
that.hide();
}
});
this.autoclose = false;
if ('autoclose' in options) {
this.autoclose = options.autoclose;
} else if ('dateAutoclose' in this.element.data()) {
this.autoclose = this.element.data('date-autoclose');
}
this.keyboardNavigation = true;
if ('keyboardNavigation' in options) {
this.keyboardNavigation = options.keyboardNavigation;
} else if ('dateKeyboardNavigation' in this.element.data()) {
this.keyboardNavigation = this.element.data('date-keyboard-navigation');
}
this.viewMode = this.startViewMode = 0;
switch(options.startView || this.element.data('date-start-view')){
case 2:
case 'decade':
this.viewMode = this.startViewMode = 2;
break;
case 1:
case 'year':
this.viewMode = this.startViewMode = 1;
break;
}
this.targetInput = options.targetInput;
this.todayBtn = (options.todayBtn||this.element.data('date-today-btn')||false);
this.todayHighlight = (options.todayHighlight||this.element.data('date-today-highlight')||false);
this.calendarWeeks = false;
if ('calendarWeeks' in options) {
this.calendarWeeks = options.calendarWeeks;
} else if ('dateCalendarWeeks' in this.element.data()) {
this.calendarWeeks = this.element.data('date-calendar-weeks');
}
if (this.calendarWeeks)
this.picker.find('tfoot th.today')
.attr('colspan', function(i, val){
return parseInt(val) + 1;
});
this.weekStart = ((options.weekStart||this.element.data('date-weekstart')||dates[this.language].weekStart||0) % 7);
this.weekEnd = ((this.weekStart + 6) % 7);
this.startDate = -Infinity;
this.endDate = Infinity;
this.daysOfWeekDisabled = [];
this.setStartDate(options.startDate||this.element.data('date-startdate'));
this.setEndDate(options.endDate||this.element.data('date-enddate'));
this.setDaysOfWeekDisabled(options.daysOfWeekDisabled||this.element.data('date-days-of-week-disabled'));
this.fillDow();
this.fillMonths();
this.update();
this.showMode();
if(this.isInline) {
this.show();
}
};
Datepicker.prototype = {
constructor: Datepicker,
_events: [],
_attachEvents: function(){
this._detachEvents();
if (this.isInput) { // single input
this._events = [
[this.element, {
focus: $.proxy(this.show, this),
keyup: $.proxy(this.update, this),
keydown: $.proxy(this.keydown, this)
}]
];
}
else if (this.component && this.hasInput){ // component: input + button
this._events = [
// For components that are not readonly, allow keyboard nav
[this.element.find('input'), {
focus: $.proxy(this.show, this),
keyup: $.proxy(this.update, this),
keydown: $.proxy(this.keydown, this)
}],
[this.component, {
click: $.proxy(this.show, this)
}]
];
}
else if (this.element.is('div')) { // inline datepicker
this.isInline = true;
}
else {
this._events = [
[this.element, {
click: $.proxy(this.show, this)
}]
];
}
for (var i=0, el, ev; i<this._events.length; i++){
el = this._events[i][0];
ev = this._events[i][1];
el.on(ev);
}
},
_detachEvents: function(){
for (var i=0, el, ev; i<this._events.length; i++){
el = this._events[i][0];
ev = this._events[i][1];
el.off(ev);
}
this._events = [];
},
show: function(e) {
this.picker.show();
this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
this.update();
this.place();
$(window).on('resize', $.proxy(this.place, this));
if (e ) {
e.stopPropagation();
e.preventDefault();
}
this.element.trigger({
type: 'show',
date: this.date
});
},
hide: function(e){
if(this.isInline) return;
if (!this.picker.is(':visible')) return;
this.picker.hide();
$(window).off('resize', this.place);
this.viewMode = this.startViewMode;
this.showMode();
if (!this.isInput) {
$(document).off('mousedown', this.hide);
}
if (
this.forceParse &&
(
this.isInput && this.element.val() ||
this.hasInput && this.element.find('input').val()
)
)
this.setValue();
this.element.trigger({
type: 'hide',
date: this.date
});
},
remove: function() {
this._detachEvents();
this.picker.remove();
delete this.element.data().datepicker;
},
getDate: function() {
var d = this.getUTCDate();
return new Date(d.getTime() + (d.getTimezoneOffset()*60000));
},
getUTCDate: function() {
return this.date;
},
setDate: function(d) {
this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000)));
},
setUTCDate: function(d) {
this.date = d;
this.setValue();
},
setValue: function() {
var formatted = this.getFormattedDate();
if (this.targetInput) {
this.targetInput.val(formatted);
}
if (!this.isInput) {
if (this.component){
this.element.find('input').val(formatted);
}
this.element.data('date', formatted);
} else {
this.element.val(formatted);
}
},
getFormattedDate: function(format) {
if (format === undefined)
format = this.format;
return DPGlobal.formatDate(this.date, format, this.language);
},
setStartDate: function(startDate){
this.startDate = startDate||-Infinity;
if (this.startDate !== -Infinity) {
this.startDate = DPGlobal.parseDate(this.startDate, this.format, this.language);
}
this.update();
this.updateNavArrows();
},
setEndDate: function(endDate){
this.endDate = endDate||Infinity;
if (this.endDate !== Infinity) {
this.endDate = DPGlobal.parseDate(this.endDate, this.format, this.language);
}
this.update();
this.updateNavArrows();
},
setDaysOfWeekDisabled: function(daysOfWeekDisabled){
this.daysOfWeekDisabled = daysOfWeekDisabled||[];
if (!$.isArray(this.daysOfWeekDisabled)) {
this.daysOfWeekDisabled = this.daysOfWeekDisabled.split(/,\s*/);
}
this.daysOfWeekDisabled = $.map(this.daysOfWeekDisabled, function (d) {
return parseInt(d, 10);
});
this.update();
this.updateNavArrows();
},
place: function(){
if(this.isInline) return;
var zIndex = parseInt(this.element.parents().filter(function() {
return $(this).css('z-index') != 'auto';
}).first().css('z-index'))+10;
var offset = this.component ? this.component.offset() : this.element.offset();
var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true);
this.picker.css({
top: offset.top + height,
left: offset.left,
zIndex: zIndex
});
},
update: function(){
var date, fromArgs = false;
if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) {
date = arguments[0];
fromArgs = true;
} else {
date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val();
}
this.date = DPGlobal.parseDate(date, this.format, this.language);
if(fromArgs) this.setValue();
var oldViewDate = this.viewDate;
if (this.date < this.startDate) {
this.viewDate = new Date(this.startDate);
} else if (this.date > this.endDate) {
this.viewDate = new Date(this.endDate);
} else {
this.viewDate = new Date(this.date);
}
if (oldViewDate && oldViewDate.getTime() != this.viewDate.getTime()){
this.element.trigger({
type: 'changeDate',
date: this.viewDate
});
}
this.fill();
},
fillDow: function(){
var dowCnt = this.weekStart,
html = '<tr>';
if(this.calendarWeeks){
var cell = '<th class="cw"> </th>';
html += cell;
this.picker.find('.datepicker-days thead tr:first-child').prepend(cell);
}
while (dowCnt < this.weekStart + 7) {
html += '<th class="dow">'+dates[this.language].daysMin[(dowCnt++)%7]+'</th>';
}
html += '</tr>';
this.picker.find('.datepicker-days thead').append(html);
},
fillMonths: function(){
var html = '',
i = 0;
while (i < 12) {
html += '<span class="month">'+dates[this.language].monthsShort[i++]+'</span>';
}
this.picker.find('.datepicker-months td').html(html);
},
fill: function() {
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth(),
startYear = this.startDate !== -Infinity ? this.startDate.getUTCFullYear() : -Infinity,
startMonth = this.startDate !== -Infinity ? this.startDate.getUTCMonth() : -Infinity,
endYear = this.endDate !== Infinity ? this.endDate.getUTCFullYear() : Infinity,
endMonth = this.endDate !== Infinity ? this.endDate.getUTCMonth() : Infinity,
currentDate = this.date && this.date.valueOf(),
today = new Date();
this.picker.find('.datepicker-days thead th.switch')
.text(dates[this.language].months[month]+' '+year);
this.picker.find('tfoot th.today')
.text(dates[this.language].today)
.toggle(this.todayBtn !== false);
this.updateNavArrows();
this.fillMonths();
var prevMonth = UTCDate(year, month-1, 28,0,0,0,0),
day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth());
prevMonth.setUTCDate(day);
prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.weekStart + 7)%7);
var nextMonth = new Date(prevMonth);
nextMonth.setUTCDate(nextMonth.getUTCDate() + 42);
nextMonth = nextMonth.valueOf();
var html = [];
var clsName;
while(prevMonth.valueOf() < nextMonth) {
if (prevMonth.getUTCDay() == this.weekStart) {
html.push('<tr>');
if(this.calendarWeeks){
// adapted from https://github.com/timrwood/moment/blob/master/moment.js#L128
var a = new Date(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth(), prevMonth.getUTCDate() - prevMonth.getDay() + 10 - (this.weekStart && this.weekStart%7 < 5 && 7)),
b = new Date(a.getFullYear(), 0, 4),
calWeek = ~~((a - b) / 864e5 / 7 + 1.5);
html.push('<td class="cw">'+ calWeek +'</td>');
}
}
clsName = '';
if (prevMonth.getUTCFullYear() < year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() < month)) {
clsName += ' old';
} else if (prevMonth.getUTCFullYear() > year || (prevMonth.getUTCFullYear() == year && prevMonth.getUTCMonth() > month)) {
clsName += ' new';
}
// Compare internal UTC date with local today, not UTC today
if (this.todayHighlight &&
prevMonth.getUTCFullYear() == today.getFullYear() &&
prevMonth.getUTCMonth() == today.getMonth() &&
prevMonth.getUTCDate() == today.getDate()) {
clsName += ' today';
}
if (currentDate && prevMonth.valueOf() == currentDate) {
clsName += ' active';
}
if (prevMonth.valueOf() < this.startDate || prevMonth.valueOf() > this.endDate ||
$.inArray(prevMonth.getUTCDay(), this.daysOfWeekDisabled) !== -1) {
clsName += ' disabled';
}
html.push('<td class="day'+clsName+'">'+prevMonth.getUTCDate() + '</td>');
if (prevMonth.getUTCDay() == this.weekEnd) {
html.push('</tr>');
}
prevMonth.setUTCDate(prevMonth.getUTCDate()+1);
}
this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
var currentYear = this.date && this.date.getUTCFullYear();
var months = this.picker.find('.datepicker-months')
.find('th:eq(1)')
.text(year)
.end()
.find('span').removeClass('active');
if (currentYear && currentYear == year) {
months.eq(this.date.getUTCMonth()).addClass('active');
}
if (year < startYear || year > endYear) {
months.addClass('disabled');
}
if (year == startYear) {
months.slice(0, startMonth).addClass('disabled');
}
if (year == endYear) {
months.slice(endMonth+1).addClass('disabled');
}
html = '';
year = parseInt(year/10, 10) * 10;
var yearCont = this.picker.find('.datepicker-years')
.find('th:eq(1)')
.text(year + '-' + (year + 9))
.end()
.find('td');
year -= 1;
for (var i = -1; i < 11; i++) {
html += '<span class="year'+(i == -1 || i == 10 ? ' old' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>';
year += 1;
}
yearCont.html(html);
},
updateNavArrows: function() {
var d = new Date(this.viewDate),
year = d.getUTCFullYear(),
month = d.getUTCMonth();
switch (this.viewMode) {
case 0:
if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear() && month <= this.startDate.getUTCMonth()) {
this.picker.find('.prev').css({visibility: 'hidden'});
} else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear() && month >= this.endDate.getUTCMonth()) {
this.picker.find('.next').css({visibility: 'hidden'});
} else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
case 1:
case 2:
if (this.startDate !== -Infinity && year <= this.startDate.getUTCFullYear()) {
this.picker.find('.prev').css({visibility: 'hidden'});
} else {
this.picker.find('.prev').css({visibility: 'visible'});
}
if (this.endDate !== Infinity && year >= this.endDate.getUTCFullYear()) {
this.picker.find('.next').css({visibility: 'hidden'});
} else {
this.picker.find('.next').css({visibility: 'visible'});
}
break;
}
},
click: function(e) {
e.stopPropagation();
e.preventDefault();
var target = $(e.target).closest('span, td, th');
if (target.length == 1) {
switch(target[0].nodeName.toLowerCase()) {
case 'th':
switch(target[0].className) {
case 'switch':
this.showMode(1);
break;
case 'prev':
case 'next':
var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1);
switch(this.viewMode){
case 0:
this.viewDate = this.moveMonth(this.viewDate, dir);
break;
case 1:
case 2:
this.viewDate = this.moveYear(this.viewDate, dir);
break;
}
this.fill();
break;
case 'today':
var date = new Date();
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
this.showMode(-2);
var which = this.todayBtn == 'linked' ? null : 'view';
this._setDate(date, which);
break;
}
break;
case 'span':
if (!target.is('.disabled')) {
this.viewDate.setUTCDate(1);
if (target.is('.month')) {
var month = target.parent().find('span').index(target);
this.viewDate.setUTCMonth(month);
this.element.trigger({
type: 'changeMonth',
date: this.viewDate
});
} else {
var year = parseInt(target.text(), 10)||0;
this.viewDate.setUTCFullYear(year);
this.element.trigger({
type: 'changeYear',
date: this.viewDate
});
}
this.showMode(-1);
this.fill();
}
break;
case 'td':
if (target.is('.day') && !target.is('.disabled')){
var day = parseInt(target.text(), 10)||1;
var year = this.viewDate.getUTCFullYear(),
month = this.viewDate.getUTCMonth();
if (target.is('.old')) {
if (month === 0) {
month = 11;
year -= 1;
} else {
month -= 1;
}
} else if (target.is('.new')) {
if (month == 11) {
month = 0;
year += 1;
} else {
month += 1;
}
}
this._setDate(UTCDate(year, month, day,0,0,0,0));
}
break;
}
}
},
_setDate: function(date, which){
if (!which || which == 'date')
this.date = date;
if (!which || which == 'view')
this.viewDate = date;
this.fill();
this.setValue();
this.element.trigger({
type: 'changeDate',
date: this.date
});
var element;
if (this.isInput) {
element = this.element;
} else if (this.component){
element = this.element.find('input');
}
if (element) {
element.change();
if (this.autoclose && (!which || which == 'date')) {
this.hide();
}
}
},
moveMonth: function(date, dir){
if (!dir) return date;
var new_date = new Date(date.valueOf()),
day = new_date.getUTCDate(),
month = new_date.getUTCMonth(),
mag = Math.abs(dir),
new_month, test;
dir = dir > 0 ? 1 : -1;
if (mag == 1){
test = dir == -1
// If going back one month, make sure month is not current month
// (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02)
? function(){ return new_date.getUTCMonth() == month; }
// If going forward one month, make sure month is as expected
// (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02)
: function(){ return new_date.getUTCMonth() != new_month; };
new_month = month + dir;
new_date.setUTCMonth(new_month);
// Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11
if (new_month < 0 || new_month > 11)
new_month = (new_month + 12) % 12;
} else {
// For magnitudes >1, move one month at a time...
for (var i=0; i<mag; i++)
// ...which might decrease the day (eg, Jan 31 to Feb 28, etc)...
new_date = this.moveMonth(new_date, dir);
// ...then reset the day, keeping it in the new month
new_month = new_date.getUTCMonth();
new_date.setUTCDate(day);
test = function(){ return new_month != new_date.getUTCMonth(); };
}
// Common date-resetting loop -- if date is beyond end of month, make it
// end of month
while (test()){
new_date.setUTCDate(--day);
new_date.setUTCMonth(new_month);
}
return new_date;
},
moveYear: function(date, dir){
return this.moveMonth(date, dir*12);
},
dateWithinRange: function(date){
return date >= this.startDate && date <= this.endDate;
},
keydown: function(e){
if (this.picker.is(':not(:visible)')){
if (e.keyCode == 27) // allow escape to hide and re-show picker
this.show();
return;
}
var dateChanged = false,
dir, day, month,
newDate, newViewDate;
switch(e.keyCode){
case 27: // escape
this.hide();
e.preventDefault();
break;
case 37: // left
case 39: // right
if (!this.keyboardNavigation) break;
dir = e.keyCode == 37 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.date, dir);
newViewDate = this.moveYear(this.viewDate, dir);
} else if (e.shiftKey){
newDate = this.moveMonth(this.date, dir);
newViewDate = this.moveMonth(this.viewDate, dir);
} else {
newDate = new Date(this.date);
newDate.setUTCDate(this.date.getUTCDate() + dir);
newViewDate = new Date(this.viewDate);
newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir);
}
if (this.dateWithinRange(newDate)){
this.date = newDate;
this.viewDate = newViewDate;
this.setValue();
this.update();
e.preventDefault();
dateChanged = true;
}
break;
case 38: // up
case 40: // down
if (!this.keyboardNavigation) break;
dir = e.keyCode == 38 ? -1 : 1;
if (e.ctrlKey){
newDate = this.moveYear(this.date, dir);
newViewDate = this.moveYear(this.viewDate, dir);
} else if (e.shiftKey){
newDate = this.moveMonth(this.date, dir);
newViewDate = this.moveMonth(this.viewDate, dir);
} else {
newDate = new Date(this.date);
newDate.setUTCDate(this.date.getUTCDate() + dir * 7);
newViewDate = new Date(this.viewDate);
newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7);
}
if (this.dateWithinRange(newDate)){
this.date = newDate;
this.viewDate = newViewDate;
this.setValue();
this.update();
e.preventDefault();
dateChanged = true;
}
break;
case 13: // enter
this.hide();
e.preventDefault();
break;
case 9: // tab
this.hide();
break;
}
if (dateChanged){
this.element.trigger({
type: 'changeDate',
date: this.date
});
var element;
if (this.isInput) {
element = this.element;
} else if (this.component){
element = this.element.find('input');
}
if (element) {
element.change();
}
}
},
showMode: function(dir) {
if (dir) {
this.viewMode = Math.max(0, Math.min(2, this.viewMode + dir));
}
/*
vitalets: fixing bug of very special conditions:
jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover.
Method show() does not set display css correctly and datepicker is not shown.
Changed to .css('display', 'block') solve the problem.
See https://github.com/vitalets/x-editable/issues/37
In jquery 1.7.2+ everything works fine.
*/
//this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block');
this.updateNavArrows();
}
};
$.fn.datepicker = function ( option ) {
var args = Array.apply(null, arguments);
args.shift();
return this.each(function () {
var $this = $(this),
data = $this.data('datepicker'),
options = typeof option == 'object' && option;
if (!data) {
$this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
}
if (typeof option == 'string' && typeof data[option] == 'function') {
data[option].apply(data, args);
}
});
};
$.fn.datepicker.defaults = {
};
$.fn.datepicker.Constructor = Datepicker;
var dates = $.fn.datepicker.dates = {
en: {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today"
}
};
var DPGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'Month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'FullYear',
navStep: 1
},
{
clsName: 'years',
navFnc: 'FullYear',
navStep: 10
}],
isLeapYear: function (year) {
return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
},
getDaysInMonth: function (year, month) {
return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g,
parseFormat: function(format){
// IE treats \0 as a string end in inputs (truncating the value),
// so it's a bad format delimiter, anyway
var separators = format.replace(this.validParts, '\0').split('\0'),
parts = format.match(this.validParts);
if (!separators || !separators.length || !parts || parts.length === 0){
throw new Error("Invalid date format.");
}
return {separators: separators, parts: parts};
},
parseDate: function(date, format, language) {
if (date instanceof Date) return date;
if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) {
var part_re = /([\-+]\d+)([dmwy])/,
parts = date.match(/([\-+]\d+)([dmwy])/g),
part, dir;
date = new Date();
for (var i=0; i<parts.length; i++) {
part = part_re.exec(parts[i]);
dir = parseInt(part[1]);
switch(part[2]){
case 'd':
date.setUTCDate(date.getUTCDate() + dir);
break;
case 'm':
date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir);
break;
case 'w':
date.setUTCDate(date.getUTCDate() + dir * 7);
break;
case 'y':
date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir);
break;
}
}
return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0);
}
var parts = date && date.match(this.nonpunctuation) || [],
date = new Date(),
parsed = {},
setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'],
setters_map = {
yyyy: function(d,v){ return d.setUTCFullYear(v); },
yy: function(d,v){ return d.setUTCFullYear(2000+v); },
m: function(d,v){
v -= 1;
while (v<0) v += 12;
v %= 12;
d.setUTCMonth(v);
while (d.getUTCMonth() != v)
d.setUTCDate(d.getUTCDate()-1);
return d;
},
d: function(d,v){ return d.setUTCDate(v); }
},
val, filtered, part;
setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m'];
setters_map['dd'] = setters_map['d'];
date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
var fparts = format.parts.slice();
// Remove noop parts
if (parts.length != fparts.length) {
fparts = $(fparts).filter(function(i,p){
return $.inArray(p, setters_order) !== -1;
}).toArray();
}
// Process remainder
if (parts.length == fparts.length) {
for (var i=0, cnt = fparts.length; i < cnt; i++) {
val = parseInt(parts[i], 10);
part = fparts[i];
if (isNaN(val)) {
switch(part) {
case 'MM':
filtered = $(dates[language].months).filter(function(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m == p;
});
val = $.inArray(filtered[0], dates[language].months) + 1;
break;
case 'M':
filtered = $(dates[language].monthsShort).filter(function(){
var m = this.slice(0, parts[i].length),
p = parts[i].slice(0, m.length);
return m == p;
});
val = $.inArray(filtered[0], dates[language].monthsShort) + 1;
break;
}
}
parsed[part] = val;
}
for (var i=0, s; i<setters_order.length; i++){
s = setters_order[i];
if (s in parsed && !isNaN(parsed[s]))
setters_map[s](date, parsed[s]);
}
}
return date;
},
formatDate: function(date, format, language){
var val = {
d: date.getUTCDate(),
D: dates[language].daysShort[date.getUTCDay()],
DD: dates[language].days[date.getUTCDay()],
m: date.getUTCMonth() + 1,
M: dates[language].monthsShort[date.getUTCMonth()],
MM: dates[language].months[date.getUTCMonth()],
yy: date.getUTCFullYear().toString().substring(2),
yyyy: date.getUTCFullYear()
};
val.dd = (val.d < 10 ? '0' : '') + val.d;
val.mm = (val.m < 10 ? '0' : '') + val.m;
var date = [],
seps = $.extend([], format.separators);
for (var i=0, cnt = format.parts.length; i < cnt; i++) {
if (seps.length)
date.push(seps.shift());
date.push(val[format.parts[i]]);
}
return date.join('');
},
headTemplate: '<thead>'+
'<tr>'+
'<th class="prev"><i class="icon-arrow-left"/></th>'+
'<th colspan="5" class="switch"></th>'+
'<th class="next"><i class="icon-arrow-right"/></th>'+
'</tr>'+
'</thead>',
contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>',
footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr></tfoot>'
};
DPGlobal.template = '<div class="datepicker">'+
'<div class="datepicker-days">'+
'<table class=" table-condensed">'+
DPGlobal.headTemplate+
'<tbody></tbody>'+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-months">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'<div class="datepicker-years">'+
'<table class="table-condensed">'+
DPGlobal.headTemplate+
DPGlobal.contTemplate+
DPGlobal.footTemplate+
'</table>'+
'</div>'+
'</div>';
$.fn.datepicker.DPGlobal = DPGlobal;
}( window.jQuery );
|
import {addBeforeInterceptor} from '../../utils/state/confluxes'
export function Before() {
let actionTypes = [...arguments]
return (managerPrototype, methodName, methodDescriptor) => {
let beforeInterceptor = managerPrototype[methodName]
actionTypes.forEach(actionType =>
addBeforeInterceptor(managerPrototype, actionType, beforeInterceptor)
)
return methodDescriptor
}
}
|
const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin');
const extractSass = new ExtractTextPlugin({
filename: "[name].[contenthash].css",
disable: process.env.NODE_ENV === "dev"
});
module.exports = {
entry: ['react-hot-loader/patch',
'webpack-hot-middleware/client',
'./app/app.js'
],
output: {
path: __dirname + '/static',
filename: '[name].js',
publicPath: 'http://localhost:3000/'
},
plugins: [
new ExtractTextPlugin('style.css'),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, './app/index.tmpl'),
inject: true,
hash: false,
filename: 'index.html',
minify: false,
favicon: false,
}),
new webpack.HotModuleReplacementPlugin()
],
module: {
rules: [
{
test: /\.scss$/,
loader: extractSass.extract({
use: [{
loader: "css-loader"
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
},
{
test: /\.css$/,
use: 'css-loader',
use: ExtractTextPlugin.extract({
use:'css-loader'
})
},
{
test: /\.js$/,
loaders: [ 'babel-loader' ],
exclude: /(node_modules|quagga\.js)/
},
]
}
}
|
exports.version="6.17.1" |
/**
* test-asyncbuilder
* Copyright (c) 2015-2022 Jürgen Leschner - github.com/jldec - MIT license
*
**/
/*eslint no-unused-vars: ["error", { "args": "none" }]*/
var test = require('tape');
var partial = require('lodash.partial');
var builder = require('../asyncbuilder');
test('instanceof', function(t) {
t.true(builder() instanceof builder);
t.end();
});
test('no append or asyncAppend', function(t) {
var completed = false;
var ab = builder(function(err, data) {
t.deepEqual(data, []);
t.equal(err, null);
t.true(completed);
t.end();
});
ab.complete();
completed = true;
});
test('append only without async', function(t) {
var completed = false;
var ab = builder(function(err, data) {
t.deepEqual(data, [1,2,3,4]);
t.equal(err, null);
t.true(completed);
t.end();
});
ab.append(1);
ab.append(2);
ab.append(3);
ab.append(4);
ab.complete();
completed = true;
});
test('append/asyncAppend ordering is preserved', function(t) {
var ab = builder(function(err, data) {
t.deepEqual(data, [1,2,3,4]);
t.equal(err, null);
t.end();
});
ab.append(1);
var cb1 = partial(ab.asyncAppend(), null, 2);
ab.append(3);
var cb2 = partial(ab.asyncAppend(), null, 4);
ab.complete();
setTimeout(cb1, 20); // first async operation finishes last
setTimeout(cb2, 10); // last async operation finishes first
});
test('async error after other callback', function(t) {
var callbackCalled = false;
var ab = builder(function(err, data) {
t.false(callbackCalled);
callbackCalled = true;
t.true(err instanceof Error);
t.end();
});
ab.append(1);
var cb1 = partial(ab.asyncAppend(), null, 2);
ab.append(3);
var cb2 = partial(ab.asyncAppend(), new Error('error in cb2'));
ab.complete();
setTimeout(cb1, 10);
setTimeout(cb2, 20);
});
test('async error before other callback', function(t) {
var callbackCalled = false;
var ab = builder(function(err, data) {
t.false(callbackCalled);
callbackCalled = true;
t.true(err instanceof Error);
t.end();
});
ab.append(1);
var cb1 = partial(ab.asyncAppend(), null, 2);
ab.append(3);
var cb2 = partial(ab.asyncAppend(), new Error('error in cb2'));
ab.complete();
setTimeout(cb1, 20);
setTimeout(cb2, 10);
});
test('multiple async errors', function(t) {
var callbackCalled = false;
var ab = builder(function(err, data) {
t.false(callbackCalled);
callbackCalled = true;
t.true(err instanceof Error);
t.end();
});
ab.append(1);
var cb1 = partial(ab.asyncAppend(), new Error('error in cb1'));
ab.append(3);
var cb2 = partial(ab.asyncAppend(), new Error('error in cb2'));
ab.complete();
setTimeout(cb1, 20);
setTimeout(cb2, 10);
});
test('callback after async error', function(t) {
var callbackCalled = false;
var ab = builder(function(err, data) {
t.false(callbackCalled);
callbackCalled = true;
t.true(err instanceof Error);
setTimeout(function() { t.end(); }, 40);
});
ab.append(1);
var cb1 = partial(ab.asyncAppend(), new Error('error in cb1'));
ab.append(3);
var cb2 = partial(ab.asyncAppend(), null, 4);
ab.complete();
setTimeout(cb1, 10);
setTimeout(cb2, 20);
});
test('also works with new', function(t) {
var Builder = require('../asyncbuilder');
var ab = new Builder(function(err, data) {
t.true(ab instanceof Builder);
t.deepEqual(data, [1,2,3,4]);
t.equal(err, null);
t.end();
});
var cb1 = partial(ab.asyncAppend(), null, 1);
ab.append(2);
var cb2 = partial(ab.asyncAppend(), null, 3);
ab.append(4);
ab.complete();
setTimeout(cb1, 20);
setTimeout(cb2, 10);
});
test('noop builder returns []', function(t) {
var ab = builder(function(err, data) {
t.deepEqual(data, []);
t.equal(err, null);
t.end();
});
ab.complete();
});
test('asyncAppend() after complete() returns error', function(t) {
var ab = builder(function(err, data) {
t.true(err instanceof Error);
t.end();
});
var cb1 = partial(ab.asyncAppend(), null, 1);
ab.complete();
var cb2 = partial(ab.asyncAppend(), null, 2);
setTimeout(cb1, 20);
setTimeout(cb2, 10);
});
test('append() after mainCallBack throws', function(t) {
var ab = builder(function(err, data) {
t.deepEqual(data, [1,2]);
t.equal(err, null);
t.end();
});
ab.append(1);
ab.append(2);
ab.complete();
t.throws(function() { ab.append(3); });
});
test('asyncAppend() after mainCallBack throws', function(t) {
var ab = builder(function(err, data) {
t.deepEqual(data, [1,2]);
t.equal(err, null);
t.end();
});
ab.append(1);
ab.append(2);
ab.complete();
t.throws(function() { ab.asyncAppend(); });
});
test('missing complete() times out', function(t) {
var callbackCalled = false;
setTimeout(function() {
t.false(callbackCalled);
t.end();
}, 100);
var ab = builder(function(err, data) {
callbackCalled = true;
});
ab.append(1);
ab.append(2);
ab.append(3);
});
test('multiple complete() ok', function(t) {
var callbackCalled = false;
var ab = builder(function(err, data) {
t.false(callbackCalled);
callbackCalled = true;
t.deepEqual(data, [1,2,3,4]);
t.equal(err, null);
t.end();
});
ab.append(1);
var cb1 = partial(ab.asyncAppend(), null, 2);
ab.append(3);
ab.append(4);
ab.complete();
ab.complete();
ab.complete();
setTimeout(cb1, 20);
});
test('duplicate callbacks ok', function(t) {
var callbackCalled = false;
var ab = builder(function(err, data) {
t.false(callbackCalled);
callbackCalled = true;
t.deepEqual(data, [1,2,3,4]);
t.equal(err, null);
t.end();
});
ab.append(1);
var cb1 = partial(ab.asyncAppend(), null, 2);
ab.append(3);
ab.append(4);
ab.complete();
setTimeout(cb1, 20);
setTimeout(cb1, 20);
});
test('premature non-error callback ok', function(t) {
var callbackCalled = false;
var ab = builder(function(err, data) {
t.false(callbackCalled);
callbackCalled = true;
t.deepEqual(data, [1,2,3,4]);
t.equal(err, null);
t.end();
});
ab.append(1);
ab.asyncAppend()(null, 2);
ab.append(3);
ab.append(4);
ab.complete();
});
test('premature callback error ok', function(t) {
var callbackCalled = false;
var ab = builder(function(err, data) {
t.false(callbackCalled);
callbackCalled = true;
t.true(err instanceof Error);
t.end();
});
ab.append(1);
ab.asyncAppend()(new Error('premature callback error'));
ab.append(3);
ab.append(4);
ab.complete();
});
|
if (!String.prototype.format) {
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) { return (typeof args[number] != 'undefined'
? args[number]
: match); });
};
}
var map;
var locations;
var baseUrl;
var targetDate;
var colorTable = [
'http://maps.google.com/mapfiles/ms/icons/yellow.png',
'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png',
'http://maps.google.com/mapfiles/ms/icons/red.png',
'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
'http://maps.google.com/mapfiles/ms/icons/blue.png',
'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
'http://maps.google.com/mapfiles/ms/icons/green.png',
'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
'http://maps.google.com/mapfiles/ms/icons/purple.png',
'http://maps.google.com/mapfiles/ms/icons/purple-dot.png'];
var MapLocation = (function () {
function MapLocation(id, latitude, longitude, type, time, user) {
this.id = id;
this.latitude = latitude;
this.longitude = longitude;
this.type = type;
this.time = time;
this.user = user;
console.log(this.toString());
}
MapLocation.prototype.toString = function () {
return "{0}: {1}, {2}<br />type: {3}<br />{4}<br />{5}".format(this.id.toString(), this.latitude.toString(), this.longitude.toString(), this.type, this.user.toString(), this.time.toString());
};
MapLocation.fromJson = function (j) {
return new MapLocation(j.Id, j.Latitude, j.Longitude, j.Type, j.Time, User.fromJson(j.User));
};
return MapLocation;
})();
var User = (function () {
function User(id, displayName) {
this.id = id;
this.displayName = displayName;
}
User.prototype.toString = function () {
return "{0} ({1})".format(this.displayName, this.id.toString());
};
User.fromJson = function (j) {
return new User(j.Id, j.DisplayName);
};
return User;
})();
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(35.65597440083904, 139.6530764476981),
zoom: 10
});
load("hoge");
}
function load(v) {
locations = [];
var url = baseUrl + "locations";
if (targetDate != null && targetDate.length > 0) {
url = "{0}?date={1}".format(url, targetDate);
}
jQuery.getJSON(url, function (ls) {
for (var i = 0; i < ls.length; i++) {
var l = MapLocation.fromJson(ls[i]);
var latlng = new google.maps.LatLng(l.latitude, l.longitude);
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: colorTable[l.user.id % (colorTable.length / 2) * 2 + (l.type == 'significant_change' ? 0 : 1)]
});
bindInfoWindow(marker, l.toString());
}
});
}
function bindInfoWindow(marker, description) {
google.maps.event.addListener(marker, 'click', function () {
new google.maps.InfoWindow({
content: description
}).open(map, marker);
});
}
//# sourceMappingURL=map.js.map |
const fs = require('fs');
const util = require('util');
// First 40 bytes are RIFF header
const WAVEHEADERSIZE = 40;
// Header tags to be parsed
const WAVETAGS = [
['id', 'string', 4, true],
['idSize', 'uinteger', 4, true],
['formatTag', 'string', 4, true],
['fmtId', 'string', 4, true],
['fmtIdSize', 'integer', 4, false],
['formatTag', 'integer', 2, true],
['nChannels', 'integer', 2, true],
['sampleRate', 'uinteger', 4, true],
['byte_rate', 'integer', 4, true],
['blockAlign', 'integer', 2, true],
['bitsPerSample', 'integer', 2, true],
['dataId', 'string', 4, true]
];
/**
* Parse WAVE info from specified file.
*
* @param {*} filename WAVE file path.
* @returns WAVE info object.
*/
async function WaveParser(filename) {
const header = {};
const fd = await util.promisify(fs.open)(filename, 'r');
async function parseHeader() {
const buffer = Buffer.alloc(WAVEHEADERSIZE);
await util.promisify(fs.read)(fd, buffer, 0, WAVEHEADERSIZE, 0);
let readIndex = 0;
WAVETAGS.forEach(item => {
if (item[3] === true) {
if (item[1] === 'string') {
header[item[0]] = buffer.toString('ascii', readIndex, readIndex + item[2]);
} else if (item[1] === 'integer') {
header[item[0]] = buffer.readUInt16LE(readIndex, item[2]);
} else if (item[1] === 'uinteger') {
header[item[0]] = buffer.readInt32LE(readIndex, item[2]);
}
}
readIndex += item[2];
});
const bytesPerSample = header.bitsPerSample / 8;
const bytesPerSec = header.nChannels * header.sampleRate * bytesPerSample;
header.duration = parseFloat((header.idSize / bytesPerSec).toFixed(2), 10);
}
await parseHeader();
await util.promisify(fs.close)(fd);
return header;
}
module.exports = {
WaveParser
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function stringify(arg) {
if (typeof arg === "string")
return arg;
return JSON.stringify(arg);
}
exports.stringify = stringify;
function log(message) {
var optionalParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
optionalParams[_i - 1] = arguments[_i];
}
console.log(message, optionalParams);
}
exports.log = log;
function debug(message) {
var optionalParams = [];
for (var _i = 1; _i < arguments.length; _i++) {
optionalParams[_i - 1] = arguments[_i];
}
console.log(message, optionalParams);
}
exports.debug = debug;
/**
* @private
* Given a min and max, restrict the given number
* to the range.
* @param min the minimum
* @param n the value
* @param max the maximum
*/
function clamp(min, n, max) {
return Math.max(min, Math.min(n, max));
}
exports.clamp = clamp;
/** @private */
function deepCopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
exports.deepCopy = deepCopy;
/** @private */
function debounce(fn, wait, immediate) {
if (immediate === void 0) { immediate = false; }
var timeout, args, context, timestamp, result;
return function () {
context = this;
args = arguments;
timestamp = Date.now();
var later = function () {
var last = Date.now() - timestamp;
if (last < wait) {
timeout = setTimeout(later, wait - last);
}
else {
timeout = null;
if (!immediate)
result = fn.apply(context, args);
}
};
var callNow = immediate && !timeout;
if (!timeout) {
timeout = setTimeout(later, wait);
}
if (callNow)
result = fn.apply(context, args);
return result;
};
}
exports.debounce = debounce;
/**
* @private
* Apply default arguments if they don't exist in
* the first object.
* @param the destination to apply defaults to.
*/
function defaults(dest) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
for (var i = arguments.length - 1; i >= 1; i--) {
var source = arguments[i];
if (source) {
for (var key in source) {
if (source.hasOwnProperty(key) && !dest.hasOwnProperty(key)) {
dest[key] = source[key];
}
}
}
}
return dest;
}
exports.defaults = defaults;
/** @private */
function isBoolean(val) { return typeof val === 'boolean'; }
exports.isBoolean = isBoolean;
/** @private */
function isString(val) { return typeof val === 'string'; }
exports.isString = isString;
/** @private */
function isNumber(val) { return typeof val === 'number'; }
exports.isNumber = isNumber;
/** @private */
function isFunction(val) { return typeof val === 'function'; }
exports.isFunction = isFunction;
/** @private */
function isDefined(val) { return typeof val !== 'undefined'; }
exports.isDefined = isDefined;
/** @private */
function isUndefined(val) { return typeof val === 'undefined'; }
exports.isUndefined = isUndefined;
/** @private */
function isPresent(val) { return val !== undefined && val !== null; }
exports.isPresent = isPresent;
/** @private */
function isBlank(val) { return val === undefined || val === null; }
exports.isBlank = isBlank;
/** @private */
function isObject(val) { return typeof val === 'object'; }
exports.isObject = isObject;
/** @private */
function isArray(val) { return Array.isArray(val); }
exports.isArray = isArray;
;
/** @private */
function isPrimitive(val) {
return isString(val) || isBoolean(val) || (isNumber(val) && !isNaN(val));
}
exports.isPrimitive = isPrimitive;
;
/** @private */
function isTrueProperty(val) {
if (typeof val === 'string') {
val = val.toLowerCase().trim();
return (val === 'true' || val === 'on' || val === '');
}
return !!val;
}
exports.isTrueProperty = isTrueProperty;
;
/** @private */
function isCheckedProperty(a, b) {
if (a === undefined || a === null || a === '') {
return (b === undefined || b === null || b === '');
}
else if (a === true || a === 'true') {
return (b === true || b === 'true');
}
else if (a === false || a === 'false') {
return (b === false || b === 'false');
}
else if (a === 0 || a === '0') {
return (b === 0 || b === '0');
}
// not using strict comparison on purpose
return (a == b); // tslint:disable-line
}
exports.isCheckedProperty = isCheckedProperty;
;
/** @private */
function reorderArray(array, indexes) {
var element = array[indexes.from];
array.splice(indexes.from, 1);
array.splice(indexes.to, 0, element);
return array;
}
exports.reorderArray = reorderArray;
/** @private */
function removeArrayItem(array, item) {
var index = array.indexOf(item);
return !!~index && !!array.splice(index, 1);
}
exports.removeArrayItem = removeArrayItem;
/** @private */
function swipeShouldReset(isResetDirection, isMovingFast, isOnResetZone) {
// The logic required to know when the sliding item should close (openAmount=0)
// depends on three booleans (isCloseDirection, isMovingFast, isOnCloseZone)
// and it ended up being too complicated to be written manually without errors
// so the truth table is attached below: (0=false, 1=true)
// isCloseDirection | isMovingFast | isOnCloseZone || shouldClose
// 0 | 0 | 0 || 0
// 0 | 0 | 1 || 1
// 0 | 1 | 0 || 0
// 0 | 1 | 1 || 0
// 1 | 0 | 0 || 0
// 1 | 0 | 1 || 1
// 1 | 1 | 0 || 1
// 1 | 1 | 1 || 1
// The resulting expression was generated by resolving the K-map (Karnaugh map):
var shouldClose = (!isMovingFast && isOnResetZone) || (isResetDirection && isMovingFast);
return shouldClose;
}
exports.swipeShouldReset = swipeShouldReset;
/** @private */
var ASSERT_ENABLED = true;
/** @private */
function _runInDev(fn) {
if (ASSERT_ENABLED === true) {
return fn();
}
}
exports.runInDev = _runInDev;
/** @private */
function _assert(actual, reason) {
if (!actual && ASSERT_ENABLED === true) {
var message = 'IONIC ASSERT: ' + reason;
console.error(message);
debugger; // tslint:disable-line
throw new Error(message);
}
}
exports.assert = _assert;
|
module.exports = function(ngModule) {
/**********
<ohs-blogpost-callout config="::{
slug: 'make-adverts-interactive',
message: 'Well worth the read next'
}">
</ohs-blogpost-callout>
**********/
require('./ohs-blogpost-callout.less');
const angular = require('angular');
ngModule
.directive('ohsBlogpostCallout', ohsBlogpostCallout);
function ohsBlogpostCallout(DEFAULT_BLOGPOST_CALLOUT_CONFIG, $parse) {
return {
restrict: 'E',
replace: true,
scope: {
config: '='
},
template: require('./ohs-blogpost-callout.html'),
controller: 'OhsBlogpostCallout as vm',
bindToController: true,
link($scope, elem, attrs) {
let default_config = angular.copy(DEFAULT_BLOGPOST_CALLOUT_CONFIG);
if (!attrs.config) {
throw new Error(`Please specify a 'config' attribute.`);
}
const local_config = $parse(attrs.config)();
if (!local_config.slug) {
throw new Error(`Please specify a 'config.slug' attribute.`);
}
$scope.config = angular.extend(default_config, local_config);
}
};
}
ngModule.controller('OhsBlogpostCallout', OhsBlogpostCallout);
function OhsBlogpostCallout(BlogContentService) {
let vm = this;
BlogContentService.one(vm.config.slug).then((post) => {
vm.model = post;
});
}
}; |
/* A component that renders one or more columns of vertical time slots
----------------------------------------------------------------------------------------------------------------------*/
var TimeGrid = Grid.extend({
slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines
snapDuration: null, // granularity of time for dragging and selecting
minTime: null, // Duration object that denotes the first visible time of any given day
maxTime: null, // Duration object that denotes the exclusive visible end time of any given day
colDates: null, // whole-day dates for each column. left to right
axisFormat: null, // formatting string for times running along vertical axis
dayEls: null, // cells elements in the day-row background
slatEls: null, // elements running horizontally across all columns
slatTops: null, // an array of top positions, relative to the container. last item holds bottom of last slot
helperEl: null, // cell skeleton element for rendering the mock event "helper"
businessHourSegs: null,
constructor: function() {
Grid.apply(this, arguments); // call the super-constructor
this.processOptions();
},
// Renders the time grid into `this.el`, which should already be assigned.
// Relies on the view's colCnt. In the future, this component should probably be self-sufficient.
renderDates: function() {
this.el.html(this.renderHtml());
this.dayEls = this.el.find('.fc-day');
this.slatEls = this.el.find('.fc-slats tr');
for (i = 0; i < this.colCnt; i++) {
cell = this.getCell(i);
this.view.trigger('agendaRender', null, cell.start, this.dayEls.eq(i));
}
},
renderBusinessHours: function() {
var events = this.view.calendar.getBusinessHoursEvents();
this.businessHourSegs = this.renderFill('businessHours', this.eventsToSegs(events), 'bgevent');
},
// Renders the basic HTML skeleton for the grid
renderHtml: function() {
return '' +
'<div class="fc-bg">' +
'<table>' +
this.rowHtml('slotBg') + // leverages RowRenderer, which will call slotBgCellHtml
'</table>' +
'</div>' +
'<div class="fc-slats">' +
'<table>' +
this.slatRowHtml() +
'</table>' +
'</div>';
},
// Renders the HTML for a vertical background cell behind the slots.
// This method is distinct from 'bg' because we wanted a new `rowType` so the View could customize the rendering.
slotBgCellHtml: function(cell) {
return this.bgCellHtml(cell);
},
// Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL.
slatRowHtml: function() {
var view = this.view;
var isRTL = this.isRTL;
var html = '';
var slotNormal = this.slotDuration.asMinutes() % 15 === 0;
var slotTime = moment.duration(+this.minTime); // wish there was .clone() for durations
var slotDate; // will be on the view's first day, but we only care about its time
var minutes;
var axisHtml;
// Calculate the time for each slot
while (slotTime < this.maxTime) {
slotDate = this.start.clone().time(slotTime); // will be in UTC but that's good. to avoid DST issues
minutes = slotDate.minutes();
axisHtml =
'<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
((!slotNormal || !minutes) ? // if irregular slot duration, or on the hour, then display the time
'<span>' + // for matchCellWidths
htmlEscape(slotDate.format(this.axisFormat)) +
'</span>' :
''
) +
'</td>';
html +=
'<tr ' + (!minutes ? '' : 'class="fc-minor"') + '>' +
(!isRTL ? axisHtml : '') +
'<td class="' + view.widgetContentClass + '"/>' +
(isRTL ? axisHtml : '') +
"</tr>";
slotTime.add(this.slotDuration);
}
return html;
},
/* Options
------------------------------------------------------------------------------------------------------------------*/
// Parses various options into properties of this object
processOptions: function() {
var view = this.view;
var slotDuration = view.opt('slotDuration');
var snapDuration = view.opt('snapDuration');
slotDuration = moment.duration(slotDuration);
snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
this.slotDuration = slotDuration;
this.snapDuration = snapDuration;
this.cellDuration = snapDuration; // for Grid system
this.minTime = moment.duration(view.opt('minTime'));
this.maxTime = moment.duration(view.opt('maxTime'));
this.axisFormat = view.opt('axisFormat') || view.opt('smallTimeFormat');
},
// Computes a default column header formatting string if `colFormat` is not explicitly defined
computeColHeadFormat: function() {
if (this.colCnt > 1) { // multiple days, so full single date string WON'T be in title text
return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
}
else { // single day, so full single date string will probably be in title text
return 'dddd'; // "Saturday"
}
},
// Computes a default event time formatting string if `timeFormat` is not explicitly defined
computeEventTimeFormat: function() {
return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM)
},
// Computes a default `displayEventEnd` value if one is not expliclty defined
computeDisplayEventEnd: function() {
return true;
},
/* Cell System
------------------------------------------------------------------------------------------------------------------*/
rangeUpdated: function() {
var view = this.view;
var colDates = [];
var date;
date = this.start.clone();
while (date.isBefore(this.end)) {
colDates.push(date.clone());
date.add(1, 'day');
date = view.skipHiddenDays(date);
}
if (this.isRTL) {
colDates.reverse();
}
this.colDates = colDates;
this.colCnt = colDates.length;
this.rowCnt = Math.ceil((this.maxTime - this.minTime) / this.snapDuration); // # of vertical snaps
},
// Given a cell object, generates its start date. Returns a reference-free copy.
computeCellDate: function(cell) {
var date = this.colDates[cell.col];
var time = this.computeSnapTime(cell.row);
date = this.view.calendar.rezoneDate(date); // give it a 00:00 time
date.time(time);
return date;
},
// Retrieves the element representing the given column
getColEl: function(col) {
return this.dayEls.eq(col);
},
/* Dates
------------------------------------------------------------------------------------------------------------------*/
// Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day
computeSnapTime: function(row) {
return moment.duration(this.minTime + this.snapDuration * row);
},
// Slices up a date range by column into an array of segments
rangeToSegs: function(range) {
var colCnt = this.colCnt;
var segs = [];
var seg;
var col;
var colDate;
var colRange;
// normalize :(
range = {
start: range.start.clone().stripZone(),
end: range.end.clone().stripZone()
};
for (col = 0; col < colCnt; col++) {
colDate = this.colDates[col]; // will be ambig time/timezone
colRange = {
start: colDate.clone().time(this.minTime),
end: colDate.clone().time(this.maxTime)
};
seg = intersectionToSeg(range, colRange); // both will be ambig timezone
if (seg) {
seg.col = col;
segs.push(seg);
}
}
return segs;
},
/* Coordinates
------------------------------------------------------------------------------------------------------------------*/
updateSize: function(isResize) { // NOT a standard Grid method
this.computeSlatTops();
if (isResize) {
this.updateSegVerticals();
}
},
// Computes the top/bottom coordinates of each "snap" rows
computeRowCoords: function() {
var originTop = this.el.offset().top;
var items = [];
var i;
var item;
for (i = 0; i < this.rowCnt; i++) {
item = {
top: originTop + this.computeTimeTop(this.computeSnapTime(i))
};
if (i > 0) {
items[i - 1].bottom = item.top;
}
items.push(item);
}
item.bottom = item.top + this.computeTimeTop(this.computeSnapTime(i));
return items;
},
// Computes the top coordinate, relative to the bounds of the grid, of the given date.
// A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.
computeDateTop: function(date, startOfDayDate) {
return this.computeTimeTop(
moment.duration(
date.clone().stripZone() - startOfDayDate.clone().stripTime()
)
);
},
// Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).
computeTimeTop: function(time) {
var slatCoverage = (time - this.minTime) / this.slotDuration; // floating-point value of # of slots covered
var slatIndex;
var slatRemainder;
var slatTop;
var slatBottom;
// constrain. because minTime/maxTime might be customized
slatCoverage = Math.max(0, slatCoverage);
slatCoverage = Math.min(this.slatEls.length, slatCoverage);
slatIndex = Math.floor(slatCoverage); // an integer index of the furthest whole slot
slatRemainder = slatCoverage - slatIndex;
slatTop = this.slatTops[slatIndex]; // the top position of the furthest whole slot
if (slatRemainder) { // time spans part-way into the slot
slatBottom = this.slatTops[slatIndex + 1];
return slatTop + (slatBottom - slatTop) * slatRemainder; // part-way between slots
}
else {
return slatTop;
}
},
// Queries each `slatEl` for its position relative to the grid's container and stores it in `slatTops`.
// Includes the the bottom of the last slat as the last item in the array.
computeSlatTops: function() {
var tops = [];
var top;
this.slatEls.each(function(i, node) {
top = $(node).position().top;
tops.push(top);
});
tops.push(top + this.slatEls.last().outerHeight()); // bottom of the last slat
this.slatTops = tops;
},
});
|
var config = require('../config');
/*var rdb = config.rdb;
var rdbLogger = config.rdbLogger;
var io = config.io;*/
var sessionSingleton = require('../singleton').SessionSingleton.getInstance();
var sessionExpiration = config.sessionExpiration;
var logger = require('../logger');
var sendMail = require('../email').sendMail;
//var db = require('../db');
//var User = db.User;
exports.index = function (req, res) {
if (req.session.loggedIn) {
req.session.touch();
res.redirect('/chat');
}
res.render('index', {development: req.development});
};
exports.partials = function (req, res) {
var name = req.params.name;
res.render('partials/' + name);
};
module.exports.emailTest = function (req, res) {
data = {
to: 'itz.s1na@gmail.com',
subject: 'عضویت',
template: 'email-verification',
vars: {verificationUrl: 'http://horin.ir/something'}
};
setTimeout(function () { sendMail(data); }, 2);
res.send('Sent');
};
module.exports.about = function (req, res) {
res.render('about');
};
module.exports.rules = function (req, res) {
res.render('rules');
};
|
var async = require('async');
var fs = require('fs');
var restler = require('restler');
var zip = require('./routes/util/zip');
var path = require('path');
require('colors');
function uploadtgz(zippath, options, done){
console.log("uploadtgz".cyan,zippath);
fs.stat(zippath, function(err, stats){
if(err){return done(err);}
restler.post(options.server + "/tgz", {
multipart: true,
data: {
"remote": options.remote,
"dirname": options.dirname,
"file": restler.file(zippath, null, stats.size, null, "application/x-tgz")
}
}).on("success", function(data) {
fs.unlink(zippath, function(err){
if(err){return done(err);}
done(null, data);
});
}).on("fail", function(data, response){
done(data);
}).on("error", done);
});
}
function extract(options, done){
console.log("extract".cyan, path.join(options.server,options.remote,options.dirname)) ;
restler.post(options.server + "/extract", {
data:{
"remote": options.remote,
"dirname": options.dirname
}
}).on("success", function(data) {
done(null, data);
}).on("fail", function(data, response){
done(data);
}).on("error", done);
}
var simpleupload = function(options, done){
async.waterfall([
function(done){
zip(options.dir, null, done);
},
function(zippath, done){
uploadtgz(zippath, options, done);
},
function(message, done){
extract(options, done);
}
], done);
}
simpleupload.uploadtgz = function(options, done){
async.waterfall([
function(done){
zip(options.dir, null, done);
},
function(zippath, done){
uploadtgz(zippath, options, done);
}
], done);
};
simpleupload.extract = extract;
module.exports = simpleupload; |
import { t as _t } from "marko/src/runtime/vdom/index.js";
const _marko_componentType = "packages/translator-default/test/fixtures/tag-with-default-attr/template.marko",
_marko_template = _t(_marko_componentType);
export default _marko_template;
import _marko_renderer from "marko/src/runtime/components/renderer.js";
import { r as _marko_registerComponent } from "marko/src/runtime/components/registry";
_marko_registerComponent(_marko_componentType, () => _marko_template);
const _marko_component = {};
_marko_template._ = _marko_renderer(function (input, out, _componentDef, _component, state) {
out.e("div", {
"default": ""
}, "0", _component, 0, 0);
out.e("div", null, "1", _component, 0, 0);
out.e("div", {
"default": abc
}, "2", _component, 0, 0);
}, {
t: _marko_componentType,
i: true,
d: true
}, _marko_component);
import _marko_defineComponent from "marko/src/runtime/components/defineComponent.js";
_marko_template.Component = _marko_defineComponent(_marko_component, _marko_template._); |
define([], function(){
function MainFunctions() {};
MainFunctions.prototype.render = function() {
var viewsWithPrepareRender = ['productVariation', 'renderReminderConfirm', 'renderReminder'];
this.view = new this.view({el: this.el, product: this.product, account: this.account, controller: this, step: this.step});
if (viewsWithPrepareRender.indexOf(this.step) !== -1) this.view.prepareRender()
else this.view.render()
};
MainFunctions.prototype.clear = function(){
this.view.remove();
};
MainFunctions.prototype.makeTransaction = function(){
this.parent.createOrder();
this.parent.order.fetch({
function: "makeTransaction",
success: this.success.bind(this),
error: this.error.bind(this)
})
};
MainFunctions.prototype.close = function(){
window.eventCollector.track(['custom'], 'Widget: Click close', {step: this.step});
console.log('Widget: Click close');
this.parent.initView('productVariation');
};
return MainFunctions;
});
|
var spicomm_8h =
[
[ "SPI_RECVQUEUE_SIZE", "group__SPI.html#ga6177ab4ab1e1790508797c4987003b3c", null ],
[ "SPI_SENDQUEUE_SIZE", "group__SPI.html#ga046708bf8b10b373fc94bf9b92b45649", null ],
[ "spiDebug", "group__SPI.html#gaa1915f59d12c36b3c1955a05186d46c6", null ],
[ "spiQueueInit", "group__SPI.html#ga9efb05b0b48169d9ad99cead17797f1b", null ],
[ "spiReceive", "group__SPI.html#ga1e164d454a07b0d5eb590e5dc7e9c70c", null ],
[ "spiSend", "group__SPI.html#gae7a5ae0fcd4d456fa8341756fd3f5c37", null ]
]; |
var Backbone = require('backbone');
var BotModel = Backbone.Model.extend({
idAttribute: 'bot_id'
});
module.exports = BotModel;
|
// # **PertDetailView**
// A Backbone.View that shows information about a small molecule compound or gene. This view is
// frequently paired with a PertDetailModel.
// pert_detail_view = new PertDetailView({el: $("target_selector")});
// optional arguments:
// 1. {string} **bg\_color** the hex color code to use as the backgound of the view, defaults to *#ffffff*
// 2. {string} **span\_class** a bootstrap span class to size the width of the view, defaults to *"col-lg-12"*
// pert_detail_view = new PertDetailView({el: $("target_selector"),
// model: PertDetailModel,
// bg_color: "#ffffff",
// span_class: "col-lg-12"});
Barista.Views.PertDetailView = Barista.Views.BaristaBaseView.extend({
// ### name
// give the view a name to be used throughout the View's functions when it needs to know what its class name is
name: "PertDetailView",
// ### model
// set up the view's default model
model: new Barista.Models.PertDetailModel(),
// ### initialize
// overide the defualt Backbone.View initialize method to bind the view to model changes, bind
// window resize events to view re-draws, compile the template, and render the view
initialize: function(){
var self = this;
// set up the plot height
this.options.plot_height = 260;
// set up the open and closed state heights
this.open_height = this.options.plot_height;
this.closed_height = this.options.plot_height;
this.panel_open = false;
//populate the model with an initial compound and then render the view
this.model.fetch("war","compound").then(function(){
console.log(self.model.attibutes);
self.base_initialize();
});
},
// ### render
// completely render the view. Updates both static and dynamic content in the view.
render: function(){
// keep track of our scope at this level
var self = this;
// render the base view components
this.base_render();
// (re)draw the pert_iname text
this.fg_layer.selectAll('.pert_iname_text').data([]).exit().remove();
this.fg_layer.selectAll('.pert_iname_text').data([1])
.enter().append("text")
.attr("class","pert_iname_text")
.attr("x",10)
.attr("y",75)
.attr("font-family","Helvetica Neue")
.attr("font-weight","bold")
.attr("font-size","36pt")
.text(this.model.get('pert_iname'));
// (re)draw the pert_summary or clear it if there pert_summary is null
if (this.model.get('pert_summary')){
this.render_summary({summary_string: this.model.get('pert_summary'),
top: 45,
bottom: 100,
left: this.fg_layer.selectAll('.pert_iname_text').node().getComputedTextLength() + 30});
}else{
this.clear_summary();
}
// add a png export overlay
this.controls_layer.selectAll("." + this.div_string + "png_export").data([]).exit().remove();
this.controls_layer.selectAll("." + this.div_string + "png_export").data([1]).enter().append("text")
.attr("class", this.div_string + "png_export no_png_export")
.attr("x",10)
.attr("y",this.height - 20)
.attr("opacity",0.25)
.style("cursor","pointer")
.text("png")
.on("mouseover",function(){d3.select(this).transition().duration(500).attr("opacity",1).attr("fill","#56B4E9");})
.on("mouseout",function(){d3.select(this).transition().duration(500).attr("opacity",0.25).attr("fill","#000000");})
.on("click",function(){self.save_png();});
// render an image that will to indicate that the user can click the content to unfold the panel
this.cevron_image_link = (this.panel_open) ? '//coreyflynn.github.io/Bellhop/img/up_arrow_select.png' : '//coreyflynn.github.io/Bellhop/img/down_arrow_select.png';
this.controls_layer.selectAll('.cevron_icon').data([]).exit().remove();
this.controls_layer.selectAll('.cevron_icon').data([1])
.enter().append("svg:image")
.attr("class","cevron_icon")
.attr("xlink:href", this.cevron_image_link)
.attr("x",this.width/2 - 9)
.attr("y",function(){
if (self.panel_open){
return self.height - 15;
}else{
return self.height - 20;
}
})
.attr("height",20)
.attr("width", 18)
.attr("transform", "rotate(0)")
.style("cursor","pointer")
.on("click", function(){self.toggle_panel_state()});
// render a button to allow the user to expand the view to show its full content
this.controls_layer.selectAll("." + this.div_string + "more_button").data([]).exit().remove();
this.controls_layer.selectAll("." + this.div_string + "more_button").data([1]).enter()
.append("rect")
.attr("x",0)
.attr("y",this.height - 15)
.attr("class",this.div_string + "more_button")
.attr("height",15)
.attr("width",this.width)
.attr("opacity",0)
.style("cursor","pointer")
.attr("fill","#BDBDBD")
.on("mouseover",function(){d3.select(this).transition().duration(500).attr("opacity",0.25);})
.on("mouseout",function(){d3.select(this).transition().duration(500).attr("opacity",0);})
.on("click", function(){self.toggle_panel_state()})
// render the compound or gene specfic portion of the view
switch (this.model.get("pert_type")){
case "trt_cp":
this.render_compound();
break;
case "gene":
this.render_gene();
break;
};
return this;
},
// ### render_compound
// utility to render the compound specific parts of the view
render_compound: function(){
this.clear_label_and_text();
var self = this;
// (re)draw the pert_id text
this.fg_layer.selectAll('.pert_id_text').data([]).exit().remove();
this.fg_layer.selectAll('.pert_id_text').data([1])
.enter()
.append("text")
.attr("class","pert_id_text")
.attr("x",10)
.attr("y",100)
.attr("font-family","Helvetica Neue")
.attr("font-size","14pt")
.text(this.model.get('pert_id'));
// draw compound structure if there is one
if (this.model.get("structure_url")){
this.fg_layer.selectAll('.index_text_icon').data([]).exit().remove();
this.fg_layer.selectAll('.index_text_icon').data([1])
.enter().append("svg:image")
.attr("class","index_text_icon")
.attr("xlink:href", this.model.get("structure_url"))
.attr("x",10)
.attr("y",100)
.attr("height",150)
.attr("width",300)
.style("cursor","pointer")
.on("click", function(){window.location = self.model.get('structure_url')});
}
// draw the static index reagent text
this.fg_layer.selectAll('.index_text').data([]).exit().remove();
this.fg_layer.selectAll('.index_text').data([1])
.enter().append("text")
.attr("class","index_text")
.attr("x",10)
.attr("y",30)
.attr("fill","#E69F00")
.attr("font-family","Helvetica Neue")
.attr("font-size","20pt")
.text('Small Molecule Compound');
// render additional labels
this.label_y_position = 100;
// (re)draw the in_summly annotation
this.render_label_and_value('collection', 'Collection', 'pert_icollection', false, 320);
// (re)draw the gold signatures annotation
this.render_label_and_value('num_sig', 'Signatures', 'num_sig', false, 320);
// (re)draw the gold signatures annotation
this.render_label_and_value('gold_sig', 'Gold Signatures', 'num_gold', false, 320);
// (re)draw the gold signatures annotation
this.render_label_and_value('num_inst', 'Experiments', 'num_inst', false, 320);
// (re)draw the in_summly annotation
this.render_label_and_value('summly', 'In Summly', 'in_summly', false, 320);
// set the y position to be below the fold
this.label_y_position = 260;
// (re)draw the weight label and weight
this.render_label_and_value('weight', 'Weight', 'molecular_wt');
// (re)draw the formula and label
this.render_label_and_value('formula', 'Formula', Barista.NumbersToSubscript(this.model.get('molecular_formula')),true);
// (re)draw the logp and label
this.render_label_and_value('logp', 'LogP', 'logp');
// (re)draw the formula and label
this.render_label_and_value('vendor', 'Vendor', 'pert_vendor');
// (re)draw the pubchem_cid and label
this.render_label_and_value('pubchem_cid', 'PubChem CID', 'pubchem_cid', false, 10, "//pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=" + self.model.get('pubchem_cid'));
// (re)draw the InChIKey label and InChIKey
if(this.model.get("inchi_key")){
this.render_label_and_value('inchi_key', 'InChIKey', this.model.get("inchi_key").split("InChIKey=")[1], true);
}
// (re)draw the InChI string
// this.render_label_and_value('inchi_string', 'InChI String', this.model.get("inchi_string").split("InChI=")[1], true);
// (re)draw the SMILES
this.render_label_and_value('smiles', 'SMILES', 'canonical_smiles');
// draw alternate names
this.label_y_position += 20;
if (this.model.get('alt_name')){
this.render_label_and_value('alt_name_label', 'Alternate Names', '', true);
this.label_y_position += 5;
this.draw_tags('alt_name', 'Alternate Names', this.model.get('alt_name'), 'white', '#BDBDBD');
}
// draw the cell lines that the compound has been profiled in
if (this.model.get('cell_id')){
this.render_label_and_value('cell_id_label', 'Cell Lines', '', true);
this.label_y_position += 5;
this.draw_tags('cell_id', 'Cell Lines', this.model.get('cell_id'), 'white', '#CC79A7');
}
// draw the signatures for the compound
if (this.model.get('sig_id')){
this.render_label_and_value('sig_id_label', 'Signature IDs', '', true);
this.label_y_position += 5;
this.draw_tags('sig_id', 'Signature IDs', this.model.get('sig_id'), 'white', '#BDBDBD');
}
// draw the gold signatures for the compound
if (this.model.get('sig_id_gold')){
this.render_label_and_value('gold_sig_id_label', 'Gold Signature IDs', '', true);
this.label_y_position += 5;
this.draw_tags('gold_sig_id', 'Gold Signature IDs', this.model.get('sig_id_gold'), 'white', '#BDBDBD');
}
// check to see if there is a pubchem id and draw a link for it if there
// is one
this.controls_layer.selectAll("." + this.div_string + "pubchem_link").data([]).exit().remove();
if (this.model.get('pubchem_cid')){
this.controls_layer.selectAll("." + this.div_string + "pubchem_link").data([1]).enter().append("text")
.attr("class", this.div_string + "pubchem_link no_png_export")
.attr("x",this.width - 10)
.attr("y",this.height - 20)
.attr("opacity",0.25)
.attr("text-anchor","end")
.style("cursor","pointer")
.text("PubChem")
.on("mouseover",function(){d3.select(this).transition().duration(500).attr("opacity",1).attr("fill","#56B4E9");})
.on("mouseout",function(){d3.select(this).transition().duration(500).attr("opacity",0.25).attr("fill","#000000");})
.on("click", function(){window.location = "//pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=" + self.model.get('pubchem_cid')});
}
// check to see if there is a wikipedia url and draw a link for it if there
// is one
this.controls_layer.selectAll("." + this.div_string + "wiki_link").data([]).exit().remove();
if (this.model.get('wiki_url')){
this.controls_layer.selectAll("." + this.div_string + "wiki_link").data([1]).enter().append("text")
.attr("class", this.div_string + "wiki_link no_png_export")
.attr("x",this.width - 80)
.attr("y",this.height - 20)
.attr("opacity",0.25)
.attr("text-anchor","end")
.style("cursor","pointer")
.text("Wiki")
.on("mouseover",function(){d3.select(this).transition().duration(500).attr("opacity",1).attr("fill","#56B4E9");})
.on("mouseout",function(){d3.select(this).transition().duration(500).attr("opacity",0.25).attr("fill","#000000");})
.on("click", function(){window.location = self.model.get('wiki_url')});
}
},
// ### render_gene
// utility to render the gene specific parts of the view
render_gene: function(){
this.clear_label_and_text();
var self = this;
// draw the static index reagent text
this.fg_layer.selectAll('.index_text').data([]).exit().remove();
this.fg_layer.selectAll('.index_text').data([1])
.enter().append("text")
.attr("class","index_text")
.attr("x",10)
.attr("y",30)
.attr("fill","#0072B2")
.attr("font-family","Helvetica Neue")
.attr("font-size","20pt")
.text('Gene');
// (re)draw the static knockdown text
this.fg_layer.selectAll('.pert_id_text').data([]).exit().remove();
var static_text_enter = this.fg_layer.selectAll('.pert_id_text').data([1]).enter();
if (this.model.get("has_kd")){
this.fg_layer.selectAll('.kd_pert_id_text').data([]).exit().remove();
this.fg_layer.selectAll('.kd_pert_id_text').data([1])
.enter()
.append("text")
.attr("class","kd_pert_id_text pert_id_text")
.attr("x",10)
.attr("y",100)
.attr("fill","#56B4E8")
.attr("font-family","Helvetica Neue")
.attr("font-size","14pt")
.text("Knockdown");
}
// (re)draw the static overexpression text
if (this.model.get("has_oe")){
this.fg_layer.selectAll('.oe_pert_id_text').data([]).exit().remove();
this.fg_layer.selectAll('.oe_pert_id_text').data([1])
.enter()
.append("text")
.attr("class","oe_pert_id_text pert_id_text")
.attr("x",350)
.attr("y",100)
.attr("fill","#D55E00")
.attr("font-family","Helvetica Neue")
.attr("font-size","14pt")
.text("Over Expression");
}
// render additional labels
this.label_y_position = 100;
// (re)draw the pert_id annotation
this.render_label_and_value('trt_sh_pert_id', 'ID', 'trt_sh_pert_id');
this.render_label_and_value('trt_oe_pert_id', 'ID', 'trt_oe_pert_id', false, 350, null,false);
// (re)draw the signatures annotation
this.render_label_and_value('trt_sh_num_sig', 'Signatures', 'trt_sh_num_sig');
this.render_label_and_value('trt_oe_num_sig', 'Signatures', 'trt_oe_num_sig', false, 350, null,false);
// (re)draw the gold signatures annotation
this.render_label_and_value('trt_sh_num_gold', 'Gold Signatures', 'trt_sh_num_gold');
this.render_label_and_value('trt_oe_num_gold', 'Gold Signatures', 'trt_oe_num_gold', false, 350, null,false);
// (re)draw the experiments annotation
this.render_label_and_value('trt_sh_num_inst', 'Experiments', 'trt_sh_num_inst');
this.render_label_and_value('trt_oe_num_inst', 'Experiments', 'trt_oe_num_inst', false, 350, null,false);
// set the y position to be below the fold
this.label_y_position = 260;
// (re)draw the vector_id annotation
this.render_label_and_value('trt_sh_vector_id', 'Knockdown Vector', 'trt_sh_vector_id');
// (re)draw the target region annotation
this.render_label_and_value('trt_sh_target_region', 'Knockdown Target Region', 'trt_sh_target_region');
// (re)draw the 6 base seed annotation
this.render_label_and_value('trt_sh_seed_seq6', 'Knockdown 6 Base Seed Sequence', 'trt_sh_seed_seq6');
// (re)draw the 7 base seed annotation
this.render_label_and_value('trt_sh_seed_seq7', 'Knockdown 7 Base Seed Sequence', 'trt_sh_seed_seq7');
// (re)draw the target sequence annotation
this.render_label_and_value('trt_sh_target_seq', 'Knockdown Target Sequence', 'trt_sh_target_seq');
// (re)draw the oligo sequence annotation
this.render_label_and_value('trt_sh_oligo_seq', 'Knockdown Oligo Sequence', 'trt_sh_oligo_seq');
// draw the cell lines that the knockdown has been profiled in
this.label_y_position += 20;
if (this.model.get('trt_sh_cell_id')){
this.render_label_and_value('trt_sh_cell_id_label', 'Knockdown Cell Lines', '', true);
this.label_y_position += 5;
this.draw_tags('trt_sh_cell_id', 'Cell Lines', this.model.get('trt_sh_cell_id'), 'white', '#CC79A7');
}
// draw the signatures for the knockknockdown
if (this.model.get('trt_sh_sig_id')){
this.render_label_and_value('trt_sh_sig_id_label', 'Knockdown Signature IDs', '', true);
this.label_y_position += 5;
this.draw_tags('trt_sh_sig_id', 'Signature IDs', this.model.get('trt_sh_sig_id'), 'white', '#BDBDBD');
}
// draw the gold signatures for the knockdown
if (this.model.get('trt_sh_sig_id_gold')){
this.render_label_and_value('trt_sh_sig_id_gold_label', 'Gold Signature IDs', '', true);
this.label_y_position += 5;
this.draw_tags('trt_sh_sig_id_gold', 'Knockdown Gold Signature IDs', this.model.get('trt_sh_sig_id_gold'), 'white', '#BDBDBD');
}
// draw the cell lines that the over expression has been profiled in
this.label_y_position += 20;
if (this.model.get('trt_oe_cell_id')){
this.render_label_and_value('trt_oe_cell_id_label', 'Over Expression Cell Lines', '', true);
this.label_y_position += 5;
this.draw_tags('trt_oe_cell_id', 'Cell Lines', this.model.get('trt_oe_cell_id'), 'white', '#CC79A7');
}
// draw the signatures for the over expression
if (this.model.get('trt_oe_sig_id')){
this.render_label_and_value('trt_oe_sig_id_label', 'Over Expression Signature IDs', '', true);
this.label_y_position += 5;
this.draw_tags('trt_oe_sig_id', 'Signature IDs', this.model.get('trt_oe_sig_id'), 'white', '#BDBDBD');
}
// draw the gold signatures for the over expression
if (this.model.get('trt_oe_sig_id_gold')){
this.render_label_and_value('trt_oe_sig_id_gold_label', 'Gold Signature IDs', '', true);
this.label_y_position += 5;
this.draw_tags('trt_oe_sig_id_gold', 'Over Expression Gold Signature IDs', this.model.get('trt_oe_sig_id_gold'), 'white', '#BDBDBD');
}
return this;
},
// ### update
// update the dynamic potions of the view
update: function(){
this.render();
return this;
},
// ### render_label_and_value
// utility function to draw a standard label and value for that label under
// the main pert_iname and pert_id text. If pass_model_field_as_text is true,
// pass the value in model_field as text instead of serching for it in the model
render_label_and_value: function(class_name_base, label_text, model_field, pass_model_field_as_text, x_pos_base, value_link,increment_y){
// set up a local variable to keep our scope straight
var self = this;
// make sure that we have a label_y_position set
this.label_y_position = (this.label_y_position !== undefined) ? this.label_y_position: 100;
if (increment_y === undefined){
increment_y = true;
}
if (increment_y){
this.label_y_position += 25;
}
// make sure that there is a base position for the x_label set
var x_pos_base = (x_pos_base !== undefined) ? x_pos_base: 10;
// update the open_height to the total height of all that we have drawn
this.open_height = (this.options.plot_height > this.label_y_position + 40) ? this.options.plot_height : this.label_y_position + 40;
// (re)draw the label
this.fg_layer.selectAll('.' + class_name_base + '_label_text').data([]).exit().remove();
this.fg_layer.selectAll('.' + class_name_base + '_label_text').data([1])
.enter()
.append("text")
.attr("class",class_name_base + '_label_text label_and_text')
.attr("x",x_pos_base)
.attr("y",this.label_y_position)
.attr("font-family","Helvetica Neue")
.attr("font-size","14pt")
.text(label_text + ':');
// (re)draw the text
this.fg_layer.selectAll('.' + class_name_base + '_text').data([]).exit().remove();
var model_text = '';
if (pass_model_field_as_text){
model_text = model_field;
}else{
model_text = this.model.get(model_field);
}
var x_pos = x_pos_base + this.fg_layer.selectAll('.' + class_name_base + '_label_text').node().getComputedTextLength() + 10;
// if there is a value link supplied, use it as a link on the text, otherwise, render plain text
if (value_link){
this.fg_layer.selectAll('.' + class_name_base + '_text').data([1])
.enter()
.append("text")
.attr("class",class_name_base + '_text label_and_text')
.attr("x",x_pos)
.attr("y",this.label_y_position)
.attr("font-family","Helvetica Neue")
.attr("font-size","14pt")
.attr("fill","#BDBDBD")
.style("cursor","pointer")
.on("mouseover",function(){d3.select(this).transition().duration(500).attr("fill","#56B4E9");})
.on("mouseout",function(){d3.select(this).transition().duration(500).attr("fill","#BDBDBD");})
.on("click", function(){window.location = value_link})
.text(model_text);
}else{
this.fg_layer.selectAll('.' + class_name_base + '_text').data([1])
.enter()
.append("text")
.attr("class",class_name_base + '_text label_and_text')
.attr("x",x_pos)
.attr("y",this.label_y_position)
.attr("font-family","Helvetica Neue")
.attr("font-size","14pt")
.attr("fill","#BDBDBD")
.text(model_text);
}
},
// ### render_summary
// utility function to break a long summary string into a multiline
// and draw it at the desired location
// options
// 1. {string} **summary_string** the string to be displayed, defaults to *""*
// 2. {right} **right** the x position to place the **right** edge of text, defaults to *this.width*
// 3. {left} **left** the x position to place the **left** edge of text, defaults to *this.width - 500*
// 4. {top} **top** the y position to place the **top** edge of text, defaults to *0*
// 5. {bottom} **bottom** the y position to place the **bottom** edge of text, defaults to *100*
render_summary: function(options){
var self = this;
// default arguments if they are not present
summary_string = this.model.get("pert_summary");
top_edge = (options.top !== undefined) ? options.top : 0;
bottom_edge = (options.bottom !== undefined) ? options.bottom : 100;
right_edge = (options.right !== undefined) ? options.right : this.width;
left_edge = (options.left !== undefined) ? options.left : this.width - 500;
// clear existing summary
this.clear_summary();
// compute the number of lines we have room for
this.line_height = 15;
this.num_lines_allowed = Math.floor((bottom_edge - top_edge) / this.line_height);
// compute the number of characters per line we will allow and how
// many lines the summary would need if we rendered all of it
this.line_width = right_edge - left_edge;
this.num_char = Math.floor(this.line_width / 13 / .75);
this.num_char = (this.num_char > 60) ? 60 : this.num_char;
this.num_lines = Math.ceil(summary_string.length / this.num_char);
// compute the line splits to display in the summary
this.lines = [];
for (var i=0; i<this.num_lines; i++){
if (i < this.num_lines_allowed - 1){
var l = (summary_string.slice(i*this.num_char,(i+1)*this.num_char).slice(-1) != " " && summary_string.slice(i*this.num_char,(i+1)*this.num_char).slice(this.num_char-1,this.num_char) != "") ? summary_string.slice(i*this.num_char,(i+1)*this.num_char) + '-': summary_string.slice(i*this.num_char,(i+1)*this.num_char);
this.lines.push(l);
}else{
var l = summary_string.slice(i*this.num_char,(i+1)*this.num_char - 3) + '...';
this.lines.push(l);
break;
}
}
// draw lines
self.fg_layer.selectAll('.' + self.div_string + 'summary_text' + i).data(this.lines)
.enter()
.append("text")
.attr("class",self.div_string + "summary_text")
.attr("x",left_edge)
.attr("y",function(d,i){return top_edge + 13 + i*15;})
.attr("font-family","Helvetica Neue")
.attr("font-size","13pt")
.attr("fill","#BDBDBD")
// .attr("text-anchor", "middle")
.text(function(d){return d;});
},
// ### toggle_panel_state
// utility to open or close the view
toggle_panel_state: function(){
var self = this;
var h;
if (this.panel_open){
h = this.options.plot_height;
$("#" + this.div_string).animate({height:h},500);
this.panel_open = false;
this.controls_layer.selectAll(".cevron_icon").attr("xlink:href", '//coreyflynn.github.io/Bellhop/img/down_arrow_select.png')
this.controls_layer.selectAll('.cevron_icon').transition().duration(500).attr("y",h - 20);
}else{
h = this.open_height
$("#" + this.div_string).animate({height:h},500);
this.panel_open = true;
this.controls_layer.selectAll(".cevron_icon").attr("xlink:href", '//coreyflynn.github.io/Bellhop/img/up_arrow_select.png')
this.controls_layer.selectAll('.cevron_icon').transition().duration(500).attr("y",h - 15);
}
this.controls_layer.selectAll("." + this.div_string + "more_button").transition().duration(500).attr("y",h - 15);
this.controls_layer.selectAll("." + this.div_string + "wiki_link").transition().duration(500).attr("y",h - 20);
this.controls_layer.selectAll("." + this.div_string + "pubchem_link").transition().duration(500).attr("y",h - 20);
this.controls_layer.selectAll("." + this.div_string + "png_export").transition().duration(500).attr("y",h - 20);
this.vis.transition().duration(500).attr("height",h);
},
// ### draw tags
// utility function to draw tags given an array.
draw_tags: function(class_name_base, label_text, data, fg_color, tag_color){
var x_offsets = [10];
var row_number = 0;
var y_offsets = [];
var lengths = [];
var tags = [];
var self = this;
var EmSize = Barista.getEmSizeInPixels(this.div_string);
// draw the foreground text of all the tags
this.fg_layer.selectAll('.' + class_name_base + 'tag_list_text').data([]).exit().remove();
this.fg_layer.selectAll('.' + class_name_base + 'tag_list_text').data(data).enter().append('text')
.attr("class", class_name_base + "tag_list_text")
.text(function(d){return d;})
.attr("x",function(d,i){
lengths.push(this.getComputedTextLength() + 15);
var current_x_offset = x_offsets[i];
if (current_x_offset + lengths[i] > self.width){
x_offsets[i] = 5;
x_offsets.push(lengths[i] + x_offsets[i]);
row_number += 1;
}else{
x_offsets.push(lengths[i] + x_offsets[i]);
}
y_offsets.push((row_number * 1.5 + 1));
return x_offsets[i];
})
.attr("y",function(d,i){return self.label_y_position + y_offsets[i] * EmSize;})
.attr("opacity",1)
.attr("fill",fg_color)
// draw the background of all the tags
this.bg_layer.selectAll('.' + class_name_base + 'tag_list_rect').data([]).exit().remove();
this.bg_layer.selectAll('.' + class_name_base + 'tag_list_rect').data(data).enter().append('rect')
.attr("class", class_name_base + "tag_list_rect")
.attr("x",function(d,i){return x_offsets[i] - 5;})
.attr("y",function(d,i){return self.label_y_position + (y_offsets[i] - 1) * EmSize;})
.attr("rx",4)
.attr("ry",4)
.attr('width',function(d,i){return lengths[i] - 4;})
.attr('height','1.2em')
.attr("opacity",1)
.attr("fill",tag_color);
// update the label_y_position
this.label_y_position += 10 + y_offsets.slice(-1)[0] * EmSize;
// update the open_height to the total height of all that we have drawn
this.open_height = (this.options.plot_height > this.label_y_position + 40) ? this.options.plot_height : this.label_y_position + 40;
return this
},
// ### clear_summary
// utility function to clear the pert summary
clear_summary: function(){
this.fg_layer.selectAll('.summary_text').data([]).exit().remove();
},
// ### clear_label_and_text
// utility function to clear all of the labels and text generated with the
// render_label_and_value function
clear_label_and_text: function(){
this.fg_layer.selectAll('.label_and_text').data([]).exit().remove();
}
});
|
(function(angular) {
'use strict';
angular.module('gymApp.directives')
.directive('membershipList', function() {
return {
restrict: 'A',
scope: {
memberInfo: '=info'
},
link: function(scope, element, attrs) {
// cool way to get some data... ;)
// console.log(scope.memberInfo);
element.on('click', function() {
element.parent().find('ul').toggleClass('active');
});
}
};
});
})(window.angular);
|
import expect from 'expect';
import { Mongo } from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';
const productSchema = new SimpleSchema({
_id: {
type: String,
optional: true
},
title: {
type: String,
defaultValue: ""
},
type: {
label: "Product Type",
type: String,
defaultValue: "simple"
},
description: {
type: String,
defaultValue: "This is a simple product."
}
});
const productVariantSchema = new SimpleSchema({
_id: {
type: String,
optional: true
},
title: {
type: String,
defaultValue: ""
},
optionTitle: {
label: "Option",
type: String,
optional: true
},
type: {
label: "Product Variant Type",
type: String,
defaultValue: "variant"
},
price: {
label: "Price",
type: Number,
min: 0,
optional: true,
defaultValue: 5
},
createdAt: {
type: Date,
}
});
const extendedProductSchema = new SimpleSchema(productSchema);
extendedProductSchema.extend({
barcode: {
type: String,
defaultValue: "ABC123"
}
});
/* Products */
// Need to define the client one on both client and server
let products = new Mongo.Collection('TestProductsClient');
products.attachSchema(productSchema, { selector: { type: 'simple' } });
products.attachSchema(productVariantSchema, { selector: { type: 'variant' } });
if (Meteor.isServer) {
products = new Mongo.Collection('TestProductsServer');
products.attachSchema(productSchema, { selector: { type: 'simple' } });
products.attachSchema(productVariantSchema, { selector: { type: 'variant' } });
}
/* Extended Products */
// Need to define the client one on both client and server
let extendedProducts = new Mongo.Collection('ExtendedProductsClient');
extendedProducts.attachSchema(productSchema, {selector: {type: 'simple'}});
extendedProducts.attachSchema(productVariantSchema, {selector: {type: 'variant'}});
extendedProducts.attachSchema(extendedProductSchema, {selector: {type: 'simple'}});
if (Meteor.isServer) {
extendedProducts = new Mongo.Collection('ExtendedProductsServer');
extendedProducts.attachSchema(productSchema, {selector: {type: 'simple'}});
extendedProducts.attachSchema(productVariantSchema, {selector: {type: 'variant'}});
extendedProducts.attachSchema(extendedProductSchema, {selector: {type: 'simple'}});
}
export default function addMultiTests() {
describe('multiple top-level schemas', function () {
beforeEach(function () {
products.find({}).forEach(doc => {
products.remove(doc._id);
});
extendedProducts.find({}).forEach(doc => {
products.remove(doc._id);
});
});
it('works', function () {
const c = new Mongo.Collection('multiSchema');
// Attach two different schemas
c.attachSchema(new SimpleSchema({
one: { type: String }
}));
c.attachSchema(new SimpleSchema({
two: { type: String }
}));
// Check the combined schema
let combinedSchema = c.simpleSchema();
expect(combinedSchema._schemaKeys.includes('one')).toBe(true);
expect(combinedSchema._schemaKeys.includes('two')).toBe(true);
expect(combinedSchema.schema('two').type).toEqual(SimpleSchema.oneOf(String));
// Attach a third schema and make sure that it extends/overwrites the others
c.attachSchema(new SimpleSchema({
two: { type: SimpleSchema.Integer }
}));
combinedSchema = c.simpleSchema();
expect(combinedSchema._schemaKeys.includes('one')).toBe(true);
expect(combinedSchema._schemaKeys.includes('two')).toBe(true);
expect(combinedSchema.schema('two').type).toEqual(SimpleSchema.oneOf(SimpleSchema.Integer));
// Ensure that we've only attached two deny functions
expect(c._validators.insert.deny.length).toBe(2);
expect(c._validators.update.deny.length).toBe(2);
});
it('inserts doc correctly with selector passed via doc', function (done) {
const productId = products.insert({
title: 'Product one',
type: 'simple' // selector in doc
}, () => {
const product = products.findOne(productId);
expect(product.description).toBe('This is a simple product.');
expect(product.price).toBe(undefined);
const productId3 = products.insert({
title: 'Product three',
createdAt: new Date(),
type: 'variant' // other selector in doc
}, () => {
const product3 = products.findOne(productId3);
expect(product3.description).toBe(undefined);
expect(product3.price).toBe(5);
done();
});
});
});
if (Meteor.isServer) {
// Passing selector in options works only on the server because
// client options are not sent to the server and made availabe in
// the deny functions, where we call .simpleSchema()
//
// Also synchronous only works on server
it('insert selects the correct schema', function () {
const productId = products.insert({
title: 'Product one'
}, { selector: { type: 'simple' } });
const productVariantId = products.insert({
title: 'Product variant one',
createdAt: new Date()
}, { selector: { type: 'variant' } });
const product = products.findOne(productId);
const productVariant = products.findOne(productVariantId);
// we should receive new docs with correct property set for each type of doc
expect(product.description).toBe('This is a simple product.');
expect(product.price).toBe(undefined);
expect(productVariant.description).toBe(undefined);
expect(productVariant.price).toBe(5)
});
it('inserts doc correctly with selector passed via doc and via <option>', function () {
const productId = products.insert({
title: 'Product one',
type: 'simple' // selector in doc
});
const product = products.findOne(productId);
expect(product.description).toBe('This is a simple product.');
expect(product.price).toBe(undefined);
const productId2 = products.insert({
title: 'Product two'
}, { selector: { type: 'simple' } }); // selector in option
const product2 = products.findOne(productId2);
expect(product2.description).toBe('This is a simple product.');
expect(product2.price).toBe(undefined);
const productId3 = products.insert({
title: 'Product three',
createdAt: new Date(),
type: 'variant' // other selector in doc
});
const product3 = products.findOne(productId3);
expect(product3.description).toBe(undefined);
expect(product3.price).toBe(5);
});
it('upsert selects the correct schema', function () {
products.insert({ title: 'Product one' }, { selector: { type: 'simple' } });
products.upsert({ title: 'Product one', type: 'simple' },
{ $set: { description: 'This is a modified product one.' }},
{ selector: { type: 'simple' } });
products.upsert({ title: 'Product two', type: 'simple' },
{ $set: { description: 'This is a product two.' }},
{ selector: { type: 'simple' } });
const productsList = products.find().fetch();
expect(productsList.length).toBe(2);
expect(productsList[0].description).toBe('This is a modified product one.');
expect(productsList[0].price).toBe(undefined);
expect(productsList[1].description).toBe('This is a product two.');
expect(productsList[1].price).toBe(undefined);
});
it('upserts doc correctly with selector passed via <query>, via <update> and via <option>', function () {
const productId = products.insert({
title: 'Product one'
}, { selector: { type: 'simple' } });
products.upsert(
{ title: 'Product one', type: 'simple' }, // selector in <query>
{ $set: { description: 'This is a modified product one.' }}
);
let product = products.findOne(productId);
expect(product.description).toBe('This is a modified product one.');
expect(product.price).toBe(undefined);
products.upsert(
{ title: 'Product one' },
{ $set: {
description: 'This is a modified product two.',
type: 'simple' // selector in <update>
}}
);
product = products.findOne(productId);
expect(product.description).toBe('This is a modified product two.');
expect(product.price).toBe(undefined);
// we have to pass selector directly because it is required field
products.upsert(
{ title: 'Product one', type: 'simple' },
{ $set: {
description: 'This is a modified product three.'
} },
{ selector: { type: 'simple' } }
);
product = products.findOne(productId);
expect(product.description).toBe('This is a modified product three.');
expect(product.price).toBe(undefined);
});
it('update selects the correct schema', function () {
const productId = products.insert({
title: 'Product one'
}, { selector: { type: 'simple' } });
const productVariantId = products.insert({
title: 'Product variant one',
createdAt: new Date()
}, { selector: { type: 'variant' } });
products.update(productId, {
$set: { title: 'New product one' }
}, { selector: { type: 'simple' } });
products.update(productVariantId, {
$set: { title: 'New productVariant one' }
}, { selector: { type: 'simple' } });
const product = products.findOne(productId);
const productVariant = products.findOne(productVariantId);
// we should receive new docs with the same properties as before update
expect(product.description).toBe('This is a simple product.');
expect(product.price).toBe(undefined);
expect(productVariant.description).toBe(undefined);
expect(productVariant.price).toBe(5);
});
it('updates doc correctly with selector passed via <query>, via <update> and via <option>', function () {
const productId = products.insert({
title: 'Product one'
}, { selector: { type: 'simple' } });
products.update(
{ title: 'Product one', type: 'simple' }, // selector in <query>
{ $set: { description: 'This is a modified product one.' }}
);
let product = products.findOne(productId);
expect(product.description).toBe('This is a modified product one.');
expect(product.price).toBe(undefined);
products.update(
{ title: 'Product one' },
{ $set: {
description: 'This is a modified product two.',
type: 'simple' // selector in <update>
}}
);
product = products.findOne(productId);
expect(product.description).toBe('This is a modified product two.');
expect(product.price).toBe(undefined);
// we have to pass selector directly because it is required field
products.update(
{ title: 'Product one', type: 'simple' },
{ $set: {
description: 'This is a modified product three.'
} },
{ selector: { type: 'simple' } }
);
product = products.findOne(productId);
expect(product.description).toBe('This is a modified product three.');
expect(product.price).toBe(undefined);
});
it('allows changing schema on update operation', function () {
const productId = products.insert({
title: 'Product one'
}, { selector: { type: 'simple' } });
let product = products.findOne(productId);
products.update({ _id: product._id }, {
$set: {
price: 10, // validating against new schema
type: 'variant'
}
});
products.update({ _id: product._id }, {
$unset: { description: '' }
}, { selector: { type: 'variant' }, validate: false });
product = products.findOne(productId);
expect(product.description).toBe(undefined);
expect(product.price).toBe(10);
expect(product.type).toBe('variant');
});
}
it('returns the correct schema on `MyCollection.simpleSchema(object)`', function () {
const schema = products.simpleSchema({
title: 'Product one',
type: 'variant'
});
expect(schema._schema.type.label).toBe('Product Variant Type');
});
if (Meteor.isServer) {
// Passing selector in options works only on the server because
// client options are not sent to the server and made availabe in
// the deny functions, where we call .simpleSchema()
it('insert selects the correct extended schema', function () {
const productId = extendedProducts.insert({
title: 'Extended Product one'
}, { selector: { type: 'simple' } });
const productVariantId = extendedProducts.insert({
title: 'Product variant one',
createdAt: new Date()
}, { selector: { type: 'variant' } });
const extendedProduct = extendedProducts.findOne(productId);
const extendedProductVariant = extendedProducts.findOne(productVariantId);
// we should receive new docs with correct property set for each type of doc
expect(extendedProduct.description).toBe('This is a simple product.');
expect(extendedProduct.title).toBe('Extended Product one');
expect(extendedProduct.barcode).toBe('ABC123');
expect(extendedProduct.price).toBe(undefined);
expect(extendedProductVariant.description).toBe(undefined);
expect(extendedProductVariant.price).toBe(5);
expect(extendedProductVariant.barcode).toBe(undefined);
});
it('update selects the correct extended schema', function () {
const productId = extendedProducts.insert({
title: 'Product one'
}, { selector: { type: 'simple' } });
const productVariantId = extendedProducts.insert({
title: 'Product variant one',
createdAt: new Date()
}, { selector: { type: 'variant' } });
extendedProducts.update(productId, {
$set: { barcode: 'XYZ456' }
}, { selector: { type: 'simple' } });
extendedProducts.update(productVariantId, {
$set: { title: 'New productVariant one' }
}, { selector: { type: 'simple' } });
const product = extendedProducts.findOne(productId);
const productVariant = extendedProducts.findOne(productVariantId);
// we should receive new docs with the same properties as before update
expect(product.description).toBe('This is a simple product.');
expect(product.barcode).toBe('XYZ456')
expect(product.price).toBe(undefined);
expect(productVariant.description).toBe(undefined);
expect(productVariant.price).toBe(5);
expect(productVariant.barcode).toBe(undefined);
});
}
});
} |
'use strict';
angular.module('themeGreen').controller('HomeController', ['$scope', 'Authentication',
function($scope, Authentication) {
// This provides Authentication context.
$scope.authentication = Authentication;
}
]);
|
import React, { PropTypes as T } from 'react';
import classnames from 'classnames';
import Map, { Marker } from 'google-maps-react';
import styles from './styles.module.css';
export class MapComponent extends React.Component {
renderChildren() {
const {children} = this.props;
}
renderMarkers() {
if (!this.props.places) { return null; }
return this.props.places.map(place => {
return <Marker key={place.id}
name={place.id}
place={place}
onClick={this.props.onMarkerClick.bind(this)}
position={place.geometry.location} />
})
}
render() {
return (
<Map google={this.props.google}
className={styles.map} >
</Map>
)
}
}
export default MapComponent; |
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(
<App />,
document.getElementById( 'root' )
);
|
(function() {
var clone = fabric.util.object.clone;
fabric.util.object.extend(fabric.IText.prototype, /** @lends fabric.IText.prototype */ {
/**
* Initializes all the interactive behavior of IText
*/
initBehavior: function() {
this.initKeyHandlers();
this.initCursorSelectionHandlers();
this.initDoubleClickSimulation();
this.initHiddenTextarea();
},
/**
* Initializes "selected" event handler
*/
initSelectedHandler: function() {
this.on('selected', function() {
var _this = this;
setTimeout(function() {
_this.selected = true;
}, 100);
if (!this._hasCanvasHandlers) {
this._initCanvasHandlers();
this._hasCanvasHandlers = true;
}
});
},
/**
* @private
*/
_initCanvasHandlers: function() {
var _this = this;
this.canvas.on('selection:cleared', function(options) {
// do not exit editing if event fired
// when clicking on an object again (in editing mode)
if (options.e && _this.canvas.containsPoint(options.e, _this)) return;
_this.exitEditing();
});
this.canvas.on('mouse:up', function() {
this.getObjects('i-text').forEach(function(obj) {
obj.__isMousedown = false;
});
});
},
/**
* @private
*/
_tick: function() {
var _this = this;
if (this._abortCursorAnimation) return;
this.animate('_currentCursorOpacity', 1, {
duration: this.cursorDuration,
onComplete: function() {
_this._onTickComplete();
},
onChange: function() {
_this.canvas && _this.canvas.renderAll();
},
abort: function() {
return _this._abortCursorAnimation;
}
});
},
/**
* @private
*/
_onTickComplete: function() {
if (this._abortCursorAnimation) return;
var _this = this;
if (this._cursorTimeout1) {
clearTimeout(this._cursorTimeout1);
}
this._cursorTimeout1 = setTimeout(function() {
_this.animate('_currentCursorOpacity', 0, {
duration: this.cursorDuration / 2,
onComplete: function() {
_this._tick();
},
onChange: function() {
_this.canvas && _this.canvas.renderAll();
},
abort: function() {
return _this._abortCursorAnimation;
}
});
}, 100);
},
/**
* Initializes delayed cursor
*/
initDelayedCursor: function() {
var _this = this;
if (this._cursorTimeout2) {
clearTimeout(this._cursorTimeout2);
}
this._cursorTimeout2 = setTimeout(function() {
_this._abortCursorAnimation = false;
_this._tick();
}, this.cursorDelay);
},
/**
* Aborts cursor animation and clears all timeouts
*/
abortCursorAnimation: function() {
this._abortCursorAnimation = true;
clearTimeout(this._cursorTimeout1);
clearTimeout(this._cursorTimeout2);
this._currentCursorOpacity = 0;
this.canvas && this.canvas.renderAll();
var _this = this;
setTimeout(function() {
_this._abortCursorAnimation = false;
}, 10);
},
/**
* Selects entire text
*/
selectAll: function() {
this.selectionStart = 0;
this.selectionEnd = this.text.length;
},
/**
* Returns selected text
* @return {String}
*/
getSelectedText: function() {
return this.text.slice(this.selectionStart, this.selectionEnd);
},
/**
* Find new selection index representing start of current word according to current selection index
* @param {Number} startFrom Surrent selection index
* @return {Number} New selection index
*/
findWordBoundaryLeft: function(startFrom) {
var offset = 0, index = startFrom - 1;
// remove space before cursor first
if (this._reSpace.test(this.text.charAt(index))) {
while (this._reSpace.test(this.text.charAt(index))) {
offset++;
index--;
}
}
while (/\S/.test(this.text.charAt(index)) && index > -1) {
offset++;
index--;
}
return startFrom - offset;
},
/**
* Find new selection index representing end of current word according to current selection index
* @param {Number} startFrom Current selection index
* @return {Number} New selection index
*/
findWordBoundaryRight: function(startFrom) {
var offset = 0, index = startFrom;
// remove space after cursor first
if (this._reSpace.test(this.text.charAt(index))) {
while (this._reSpace.test(this.text.charAt(index))) {
offset++;
index++;
}
}
while (/\S/.test(this.text.charAt(index)) && index < this.text.length) {
offset++;
index++;
}
return startFrom + offset;
},
/**
* Find new selection index representing start of current line according to current selection index
* @param {Number} current selection index
*/
findLineBoundaryLeft: function(startFrom) {
var offset = 0, index = startFrom - 1;
while (!/\n/.test(this.text.charAt(index)) && index > -1) {
offset++;
index--;
}
return startFrom - offset;
},
/**
* Find new selection index representing end of current line according to current selection index
* @param {Number} current selection index
*/
findLineBoundaryRight: function(startFrom) {
var offset = 0, index = startFrom;
while (!/\n/.test(this.text.charAt(index)) && index < this.text.length) {
offset++;
index++;
}
return startFrom + offset;
},
/**
* Returns number of newlines in selected text
* @return {Number} Number of newlines in selected text
*/
getNumNewLinesInSelectedText: function() {
var selectedText = this.getSelectedText();
var numNewLines = 0;
for (var i = 0, chars = selectedText.split(''), len = chars.length; i < len; i++) {
if (chars[i] === '\n') {
numNewLines++;
}
}
return numNewLines;
},
/**
* Finds index corresponding to beginning or end of a word
* @param {Number} selectionStart Index of a character
* @param {Number} direction: 1 or -1
*/
searchWordBoundary: function(selectionStart, direction) {
var index = selectionStart;
var _char = this.text.charAt(index);
var reNonWord = /[ \n\.,;!\?\-]/;
while (!reNonWord.test(_char) && index > 0 && index < this.text.length) {
index += direction;
_char = this.text.charAt(index);
}
if (reNonWord.test(_char) && _char !== '\n') {
index += direction === 1 ? 0 : 1;
}
return index;
},
/**
* Selects a word based on the index
* @param {Number} selectionStart Index of a character
*/
selectWord: function(selectionStart) {
var newSelectionStart = this.searchWordBoundary(selectionStart, -1); /* search backwards */
var newSelectionEnd = this.searchWordBoundary(selectionStart, 1); /* search forward */
this.setSelectionStart(newSelectionStart);
this.setSelectionEnd(newSelectionEnd);
},
/**
* Selects a line based on the index
* @param {Number} selectionStart Index of a character
*/
selectLine: function(selectionStart) {
var newSelectionStart = this.findLineBoundaryLeft(selectionStart);
var newSelectionEnd = this.findLineBoundaryRight(selectionStart);
this.setSelectionStart(newSelectionStart);
this.setSelectionEnd(newSelectionEnd);
},
/**
* Enters editing state
* @return {fabric.IText} thisArg
* @chainable
*/
enterEditing: function() {
if (this.isEditing || !this.editable) return;
this.exitEditingOnOthers();
this.isEditing = true;
this._updateTextarea();
this._saveEditingProps();
this._setEditingProps();
this._tick();
this.canvas && this.canvas.renderAll();
this.fire('editing:entered');
return this;
},
exitEditingOnOthers: function() {
fabric.IText.instances.forEach(function(obj) {
if (obj === this) return;
obj.exitEditing();
}, this);
},
/**
* @private
*/
_setEditingProps: function() {
this.hoverCursor = 'text';
if (this.canvas) {
this.canvas.defaultCursor = this.canvas.moveCursor = 'text';
}
this.borderColor = this.editingBorderColor;
this.hasControls = this.selectable = false;
this.lockMovementX = this.lockMovementY = true;
},
/**
* @private
*/
_updateTextarea: function() {
if (!this.hiddenTextarea) return;
this.hiddenTextarea.value = this.text;
this.hiddenTextarea.selectionStart = this.selectionStart;
this.hiddenTextarea.focus();
},
/**
* @private
*/
_saveEditingProps: function() {
this._savedProps = {
hasControls: this.hasControls,
borderColor: this.borderColor,
lockMovementX: this.lockMovementX,
lockMovementY: this.lockMovementY,
hoverCursor: this.hoverCursor,
defaultCursor: this.canvas && this.canvas.defaultCursor,
moveCursor: this.canvas && this.canvas.moveCursor
};
},
/**
* @private
*/
_restoreEditingProps: function() {
if (!this._savedProps) return;
this.hoverCursor = this._savedProps.overCursor;
this.hasControls = this._savedProps.hasControls;
this.borderColor = this._savedProps.borderColor;
this.lockMovementX = this._savedProps.lockMovementX;
this.lockMovementY = this._savedProps.lockMovementY;
if (this.canvas) {
this.canvas.defaultCursor = this._savedProps.defaultCursor;
this.canvas.moveCursor = this._savedProps.moveCursor;
}
},
/**
* Exits from editing state
* @return {fabric.IText} thisArg
* @chainable
*/
exitEditing: function() {
this.selected = false;
this.isEditing = false;
this.selectable = true;
this.selectionEnd = this.selectionStart;
this.hiddenTextarea && this.hiddenTextarea.blur();
this.abortCursorAnimation();
this._restoreEditingProps();
this._currentCursorOpacity = 0;
this.fire('editing:exited');
return this;
},
/**
* @private
*/
_removeExtraneousStyles: function() {
var textLines = this.text.split(this._reNewline);
for (var prop in this.styles) {
if (!textLines[prop]) {
delete this.styles[prop];
}
}
},
/**
* @private
*/
_removeCharsFromTo: function(start, end) {
var i = end;
while (i !== start) {
var prevIndex = this.get2DCursorLocation(i).charIndex;
i--;
var index = this.get2DCursorLocation(i).charIndex;
var isNewline = index > prevIndex;
if (isNewline) {
this.removeStyleObject(isNewline, i + 1);
}
else {
this.removeStyleObject(this.get2DCursorLocation(i).charIndex === 0, i);
}
}
this.text = this.text.slice(0, start) +
this.text.slice(end);
},
/**
* Inserts a character where cursor is (replacing selection if one exists)
* @param {String} _chars Characters to insert
*/
insertChars: function(_chars) {
var isEndOfLine = this.text.slice(this.selectionStart, this.selectionStart + 1) === '\n';
this.text = this.text.slice(0, this.selectionStart) +
_chars +
this.text.slice(this.selectionEnd);
if (this.selectionStart === this.selectionEnd) {
this.insertStyleObjects(_chars, isEndOfLine, this.copiedStyles);
}
else if (this.selectionEnd - this.selectionStart > 1) {
// TODO: replace styles properly
console.log('replacing MORE than 1 char');
}
this.selectionStart += _chars.length;
this.selectionEnd = this.selectionStart;
if (this.canvas) {
// TODO: double renderAll gets rid of text box shift happenning sometimes
// need to find out what exactly causes it and fix it
this.canvas.renderAll().renderAll();
}
this.setCoords();
this.fire('text:changed');
},
/**
* Inserts new style object
* @param {Number} lineIndex Index of a line
* @param {Number} charIndex Index of a char
* @param {Boolean} isEndOfLine True if it's end of line
*/
insertNewlineStyleObject: function(lineIndex, charIndex, isEndOfLine) {
this.shiftLineStyles(lineIndex, +1);
if (!this.styles[lineIndex + 1]) {
this.styles[lineIndex + 1] = { };
}
var currentCharStyle = this.styles[lineIndex][charIndex - 1],
newLineStyles = { };
// if there's nothing after cursor,
// we clone current char style onto the next (otherwise empty) line
if (isEndOfLine) {
newLineStyles[0] = clone(currentCharStyle);
this.styles[lineIndex + 1] = newLineStyles;
}
// otherwise we clone styles of all chars
// after cursor onto the next line, from the beginning
else {
for (var index in this.styles[lineIndex]) {
if (parseInt(index, 10) >= charIndex) {
newLineStyles[parseInt(index, 10) - charIndex] = this.styles[lineIndex][index];
// remove lines from the previous line since they're on a new line now
delete this.styles[lineIndex][index];
}
}
this.styles[lineIndex + 1] = newLineStyles;
}
},
/**
* Inserts style object for a given line/char index
* @param {Number} lineIndex Index of a line
* @param {Number} charIndex Index of a char
* @param {Object} [style] Style object to insert, if given
*/
insertCharStyleObject: function(lineIndex, charIndex, style) {
var currentLineStyles = this.styles[lineIndex],
currentLineStylesCloned = clone(currentLineStyles);
if (charIndex === 0 && !style) {
charIndex = 1;
}
// shift all char styles by 1 forward
// 0,1,2,3 -> (charIndex=2) -> 0,1,3,4 -> (insert 2) -> 0,1,2,3,4
for (var index in currentLineStylesCloned) {
var numericIndex = parseInt(index, 10);
if (numericIndex >= charIndex) {
currentLineStyles[numericIndex + 1] = currentLineStylesCloned[numericIndex];
//delete currentLineStyles[index];
}
}
this.styles[lineIndex][charIndex] =
style || clone(currentLineStyles[charIndex - 1]);
},
/**
* Inserts style object(s)
* @param {String} _chars Characters at the location where style is inserted
* @param {Boolean} isEndOfLine True if it's end of line
* @param {Array} [styles] Styles to insert
*/
insertStyleObjects: function(_chars, isEndOfLine, styles) {
// short-circuit
if (this.isEmptyStyles()) return;
var cursorLocation = this.get2DCursorLocation(),
lineIndex = cursorLocation.lineIndex,
charIndex = cursorLocation.charIndex;
if (!this.styles[lineIndex]) {
this.styles[lineIndex] = { };
}
if (_chars === '\n') {
this.insertNewlineStyleObject(lineIndex, charIndex, isEndOfLine);
}
else {
if (styles) {
this._insertStyles(styles);
}
else {
// TODO: support multiple style insertion if _chars.length > 1
this.insertCharStyleObject(lineIndex, charIndex);
}
}
},
/**
* @private
*/
_insertStyles: function(styles) {
for (var i = 0, len = styles.length; i < len; i++) {
var cursorLocation = this.get2DCursorLocation(this.selectionStart + i),
lineIndex = cursorLocation.lineIndex,
charIndex = cursorLocation.charIndex;
this.insertCharStyleObject(lineIndex, charIndex, styles[i]);
}
},
/**
* Shifts line styles up or down
* @param {Number} lineIndex Index of a line
* @param {Number} offset Can be -1 or +1
*/
shiftLineStyles: function(lineIndex, offset) {
// shift all line styles by 1 upward
var clonedStyles = clone(this.styles);
for (var line in this.styles) {
var numericLine = parseInt(line, 10);
if (numericLine > lineIndex) {
this.styles[numericLine + offset] = clonedStyles[numericLine];
}
}
},
/**
* Removes style object
* @param {Boolean} isBeginningOfLine True if cursor is at the beginning of line
* @param {Number} [index] Optional index. When not given, current selectionStart is used.
*/
removeStyleObject: function(isBeginningOfLine, index) {
var cursorLocation = this.get2DCursorLocation(index),
lineIndex = cursorLocation.lineIndex,
charIndex = cursorLocation.charIndex;
if (isBeginningOfLine) {
var textLines = this.text.split(this._reNewline),
textOnPreviousLine = textLines[lineIndex - 1],
newCharIndexOnPrevLine = textOnPreviousLine.length;
if (!this.styles[lineIndex - 1]) {
this.styles[lineIndex - 1] = { };
}
for (charIndex in this.styles[lineIndex]) {
this.styles[lineIndex - 1][parseInt(charIndex, 10) + newCharIndexOnPrevLine]
= this.styles[lineIndex][charIndex];
}
this.shiftLineStyles(lineIndex, -1);
}
else {
var currentLineStyles = this.styles[lineIndex];
if (currentLineStyles) {
var offset = this.selectionStart === this.selectionEnd ? -1 : 0;
delete currentLineStyles[charIndex + offset];
// console.log('deleting', lineIndex, charIndex + offset);
}
var currentLineStylesCloned = clone(currentLineStyles);
// shift all styles by 1 backwards
for (var i in currentLineStylesCloned) {
var numericIndex = parseInt(i, 10);
if (numericIndex >= charIndex && numericIndex !== 0) {
currentLineStyles[numericIndex - 1] = currentLineStylesCloned[numericIndex];
delete currentLineStyles[numericIndex];
}
}
}
},
/**
* Inserts new line
*/
insertNewline: function() {
this.insertChars('\n');
}
});
})();
|
// Load the global common runtime for build/test/tools
require('./etc/global-env')
const
gulp = require('gulp'),
del = require('del'),
// tsdoc = require('gulp-typedoc'),
runSequence = require('run-sequence'),
git = require('gulp-git'),
ghRelease = require('gulp-github-release'),
ts = require('gulp-typescript'),
glob = require('glob')
Object.assign(global,{
glob,
ts,
gulp,
runSequence,
//tsdoc,
del,
git,
ghRelease
})
// Now map and configure all the projects/plugins
global.projects = projectNames.map(require('./etc/gulp/project-tasks'))
/**
* Load auxillary tasks
*/
require('./etc/gulp/tasks')
|
//@flow
import React from 'react'
import type { TodoListProps } from '../definitions/TodoTypeDefinition.js'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { onItemFilterOut, onItemSort } from '../actions/items'
const TodoList = ({children, onItemFilterOut, onItemSort, sortType}: TodoListProps) => {
//找出索引值,共有三種值,要對應顯示字串用的
let sortTypeIndex: number = ['no', 'asc', 'desc'].findIndex((value) => value === sortType )
return (
<div>
<label>
<input
type="checkbox"
defaultChecked
onClick={onItemFilterOut}
/>
包含已完成的項目
</label>
<button
className={(sortTypeIndex === 0)? 'btn btn-default': 'btn btn-success'}
onClick={() => { onItemSort({direction: (sortType === 'asc')? 'desc': 'asc'}) }}
disabled={(React.Children.count(children))? false: true}
>
按筆劃排序: {['沒有','少 -> 多','多 -> 少'][sortTypeIndex]}
</button>
<ul className="list-group">{children}</ul>
</div>
)
}
// 準備綁定用的mapStateToProps方法,
// 只需要sortType中的direction值
const mapStateToProps = store => ({ sortType: store.sortType.direction })
// 準備綁定用的DispatchToProps方法,
// 只需要onItemFilterOut與onItemSort這個方法
const mapDispatchToProps = (dispatch) => (
bindActionCreators({ onItemFilterOut, onItemSort }, dispatch)
)
//匯出TodoList模組
export default connect(mapStateToProps, mapDispatchToProps)(TodoList)
|
/* jshint expr: true */
/* globals before: false, describe: false, it: false */
'use strict';
import {expect} from 'chai';
import * as jettison from '../src/jettison.js';
let StreamView = jettison._StreamView;
class Approx {
constructor(value, epsilon) {
this.value = value;
this.epsilon = epsilon;
}
}
function describeJettison({withPolyfills}={}) {
describe(`jettison${withPolyfills ? ' with polyfills' : ''}`, () => {
before(() => {
if (withPolyfills) {
jettison._config.ArrayBuffer = jettison._polyfill.ArrayBufferPolyfill;
jettison._config.DataView = jettison._polyfill.DataViewPolyfill;
} else {
jettison._config.ArrayBuffer = global.ArrayBuffer;
jettison._config.DataView = global.DataView;
}
});
function testEndianCodec(codec, inValue, expectedBytes, expectedOutValue,
littleEndian)
{
let expectedByteLength = (codec.byteLength != null ? codec.byteLength :
codec.getByteLength(inValue));
let streamView = StreamView.create(expectedByteLength);
codec.set(streamView, inValue, littleEndian);
expect(streamView.byteOffset).to.equal(expectedByteLength);
let bytes = streamView.toArray();
if (littleEndian) {
expectedBytes = expectedBytes.slice().reverse();
}
expect(bytes).to.deep.equal(expectedBytes);
streamView.byteOffset = 0;
let outValue = codec.get(streamView, littleEndian);
if (expectedOutValue instanceof Approx) {
expect(Math.abs(outValue - expectedOutValue.value))
.to.be.lessThan(expectedOutValue.epsilon);
} else if (isNaN(expectedOutValue)) {
expect(isNaN(outValue)).to.be.true;
} else if (expectedOutValue instanceof Array) {
expect(outValue).to.deep.equal(expectedOutValue);
} else {
expect(outValue).to.equal(expectedOutValue);
}
}
function testCodec(codec, inValue, expectedBytes, expectedOutValue) {
testEndianCodec(codec, inValue, expectedBytes, expectedOutValue, false);
testEndianCodec(codec, inValue, expectedBytes, expectedOutValue, true);
}
it('should convert boolean values', () => {
let codec = jettison._codecs.boolean;
testCodec(codec, false, [0], false);
testCodec(codec, true, [1], true);
});
it('should convert boolean array values', () => {
let codec = jettison._codecs.booleanArray;
const f = false;
const t = true;
// Don't bother testing the little endian version, as this is all bytes
// and the endian type doesn't matter.
testEndianCodec(codec, [], [0], []);
testEndianCodec(codec, [f], [1, 0], [f]);
testEndianCodec(codec, [t], [1, 1], [t]);
testEndianCodec(codec, [t, t, t, t, t, t, t, f], [8, 127],
[t, t, t, t, t, t, t, f]);
let bigBooleanArray = [];
for (let i = 0; i < 255; i++) {
bigBooleanArray.push(true);
}
let expectedBytes = [
// First the length
255, 1,
// Then the 255 bits (32 bytes)
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, 127,
];
testEndianCodec(codec, bigBooleanArray, expectedBytes, bigBooleanArray);
});
it('should convert int8 values', () => {
let codec = jettison._codecs.int8;
testCodec(codec, 0, [0], 0);
testCodec(codec, 1, [1], 1);
testCodec(codec, -1, [255], -1);
testCodec(codec, -128, [128], -128);
testCodec(codec, 127, [127], 127);
testCodec(codec, -129, [128], -128);
testCodec(codec, 128, [127], 127);
});
it('should convert int16 values', () => {
let codec = jettison._codecs.int16;
testCodec(codec, 0, [0, 0], 0);
testCodec(codec, 1, [0, 1], 1);
testCodec(codec, -1, [255, 255], -1);
testCodec(codec, -32768, [128, 0], -32768);
testCodec(codec, 32767, [127, 255], 32767);
testCodec(codec, -32769, [128, 0], -32768);
testCodec(codec, 32768, [127, 255], 32767);
});
it('should convert int32 values', () => {
let codec = jettison._codecs.int32;
testCodec(codec, 0, [0, 0, 0, 0], 0);
testCodec(codec, 1, [0, 0, 0, 1], 1);
testCodec(codec, -1, [255, 255, 255, 255], -1);
testCodec(codec, -2147483648, [128, 0, 0, 0], -2147483648);
testCodec(codec, 2147483647, [127, 255, 255, 255], 2147483647);
testCodec(codec, -2147483649, [128, 0, 0, 0], -2147483648);
testCodec(codec, 2147483648, [127, 255, 255, 255], 2147483647);
});
it('should convert uint8 values', () => {
let codec = jettison._codecs.uint8;
testCodec(codec, 0, [0], 0);
testCodec(codec, 1, [1], 1);
testCodec(codec, 255, [255], 255);
testCodec(codec, -1, [0], 0);
testCodec(codec, 256, [255], 255);
});
it('should convert uint16 values', () => {
let codec = jettison._codecs.uint16;
testCodec(codec, 0, [0, 0], 0);
testCodec(codec, 1, [0, 1], 1);
testCodec(codec, 65535, [255, 255], 65535);
testCodec(codec, -1, [0, 0], 0);
testCodec(codec, 65536, [255, 255], 65535);
});
it('should convert uint32 values', () => {
let codec = jettison._codecs.uint32;
testCodec(codec, 0, [0, 0, 0, 0], 0);
testCodec(codec, 1, [0, 0, 0, 1], 1);
testCodec(codec, 4294967295, [255, 255, 255, 255], 4294967295);
testCodec(codec, -1, [0, 0, 0, 0], 0);
testCodec(codec, 4294967296, [255, 255, 255, 255], 4294967295);
});
it('should convert float32 values', () => {
let codec = jettison._codecs.float32;
testCodec(codec, NaN, [127, 192, 0, 0], NaN);
testCodec(codec, Infinity, [127, 128, 0, 0], Infinity);
testCodec(codec, -Infinity, [255, 128, 0, 0], -Infinity);
testCodec(codec, 0, [0, 0, 0, 0], 0);
testCodec(codec, -0, [128, 0, 0, 0], 0);
testCodec(codec, 1, [63, 128, 0, 0], 1);
testCodec(codec, -1, [191, 128, 0, 0], -1);
// Negative exponent
testCodec(codec, 0.5, [63, 0, 0, 0], 0.5);
// Normalized value with a decimal component
testCodec(codec, 10.5, [65, 40, 0, 0], 10.5);
// Denormalized value
testCodec(codec, 1e-40, [0, 1, 22, 194], new Approx(1e-40, 0.001));
// Overflow should become infinity
testCodec(codec, 1e+39, [127, 128, 0, 0], Infinity);
// Rounding
testCodec(codec, 1.00001, [63, 128, 0, 84], new Approx(1.00001, 1e-7));
});
it('should convert float64 values', () => {
let codec = jettison._codecs.float64;
testCodec(codec, NaN, [127, 248, 0, 0, 0, 0, 0, 0], NaN);
testCodec(codec, Infinity, [127, 240, 0, 0, 0, 0, 0, 0], Infinity);
testCodec(codec, -Infinity, [255, 240, 0, 0, 0, 0, 0, 0], -Infinity);
testCodec(codec, 0, [0, 0, 0, 0, 0, 0, 0, 0], 0);
testCodec(codec, -0, [128, 0, 0, 0, 0, 0, 0, 0], 0);
testCodec(codec, 1, [63, 240, 0, 0, 0, 0, 0, 0], 1);
testCodec(codec, -1, [191, 240, 0, 0, 0, 0, 0, 0], -1);
// Negative exponent
testCodec(codec, 0.5, [63, 224, 0, 0, 0, 0, 0, 0], 0.5);
// Normalized value with a decimal component
testCodec(codec, 10.234, [64, 36, 119, 206, 217, 22, 135, 43], 10.234);
// Denormalized value
testCodec(codec, 1e-310, [0, 0, 18, 104, 139, 112, 230, 43], 1e-310);
});
it('should convert string values', () => {
let codec = jettison._codecs.string;
expect(codec).to.exist;
let streamView = StreamView.create(codec.getByteLength('hodør'));
expect(streamView.arrayBuffer.byteLength).to.equal(7);
codec.set(streamView, 'hodør', false);
expect(streamView.byteOffset).to.equal(7);
expect(streamView.toArray()).to.deep.equal([
6, 104, 111, 100, 195, 184, 114]);
streamView.byteOffset = 0;
let unpacked = codec.get(streamView, false);
expect(unpacked).to.equal('hodør');
});
it('should convert between byte arrays and strings', () => {
let codec = jettison._codecs.float64;
let streamView = StreamView.create(codec.byteLength);
codec.set(streamView, 1.0000001);
let encoded = streamView.toString();
expect(typeof encoded).to.equal('string');
let decodedStreamView = StreamView.createFromString(encoded);
expect(decodedStreamView.toArray()).to.deep.equal(streamView.toArray());
});
describe('definitions', () => {
let definition = jettison.define('object', [
{key: 'id', type: 'int32'},
{key: 'x', type: 'float64'},
{key: 'y', type: 'float64'},
{key: 'points', type: 'array', valueType: 'float64'},
{key: 'flags', type: 'booleanArray'},
{key: 'health', type: 'int16'},
]);
let expectedValue = {
id: 1,
x: 0.5,
y: 1.5,
points: [0.1, 0.2, 0.3, 0.4],
flags: [true, false, true],
health: 100,
};
let streamView = StreamView.create(
definition.codec.getByteLength(expectedValue));
definition.codec.set(streamView, expectedValue);
let string = definition.stringify(expectedValue);
before(() => {
streamView.byteOffset = 0;
});
it('should convert native values to byte arrays', () => {
expect(streamView.toArray()).to.deep.equal([
0, 0, 0, 1,
63, 224, 0, 0, 0, 0, 0, 0,
63, 248, 0, 0, 0, 0, 0, 0,
4,
63, 185, 153, 153, 153, 153, 153, 154,
63, 201, 153, 153, 153, 153, 153, 154,
63, 211, 51, 51, 51, 51, 51, 51,
63, 217, 153, 153, 153, 153, 153, 154,
3, 5,
0, 100,
]);
});
it('should convert byte arrays back to native values', () => {
const value = definition.codec.get(streamView);
expect(value).to.deep.equal(expectedValue);
});
it('should convert native values to strings', () => {
expect(typeof string).to.equal('string');
});
it('should convert strings back to native values', () => {
const value = definition.parse(string);
expect(value).to.deep.equal(expectedValue);
});
it('should allow you to use other types for the definition', () => {
const definition = jettison.define('array', 'string');
const expectedValue = ['foo', 'bar', 'baz'];
let streamView = StreamView.create(
definition.codec.getByteLength(expectedValue));
definition.codec.set(streamView, expectedValue);
expect(streamView.toArray()).to.deep.equal([
3,
3, 102, 111, 111,
3, 98, 97, 114,
3, 98, 97, 122
]);
const string = definition.stringify(['foo', 'bar', 'baz']);
const value = definition.parse(string);
expect(value).to.deep.equal(expectedValue);
});
});
describe('schemas', () => {
let schema = jettison.createSchema();
schema.define('spawn', 'object', [
{key: 'id', type: 'int32'},
{key: 'x', type: 'float64'},
{key: 'y', type: 'float64'},
{key: 'points', type: 'array', valueType: 'float64'},
{key: 'flags', type: 'booleanArray'},
]);
schema.define('position', 'object', [
{key: 'id', type: 'int32'},
{key: 'x', type: 'float64'},
{key: 'y', type: 'float64'},
]);
it('should convert to and from strings', () => {
let expectedValue = {
key: 'spawn',
data: {
id: 1,
x: 0.5,
y: 1.5,
points: [-0.1, 0.2, -0.3, 0.4],
flags: [true, false, true],
},
};
let string = schema.stringify(expectedValue.key, expectedValue.data);
expect(typeof string).to.equal('string');
let value = schema.parse(string);
expect(value).to.deep.equal(expectedValue);
expectedValue = {
key: 'position',
data: {
id: 1,
x: -123.456,
y: 7.89,
},
};
string = schema.stringify(expectedValue.key, expectedValue.data);
expect(typeof string).to.equal('string');
value = schema.parse(string);
expect(value).to.deep.equal(expectedValue);
});
});
});
}
if (global.ArrayBuffer != null && global.DataView != null) {
describeJettison();
}
describeJettison({withPolyfills: true});
|
import Ember from 'ember';
import DS from 'ember-data';
let roleUrlRegex = new RegExp('/roles/([a-zA-Z0-9\-]+)$');
function getRoleIdFromPermission(permission){
var roleUrl = permission.get('data.links.role');
return roleUrlRegex.exec(roleUrl)[1];
}
export default DS.Model.extend({
// properties
name: DS.attr('string'),
handle: DS.attr('string'),
number: DS.attr('string'),
type: DS.attr('string'),
syslogHost: DS.attr('string'),
syslogPort: DS.attr('string'),
organizationUrl: DS.attr('string'),
activated: DS.attr('boolean'),
containerCount: DS.attr('number'),
appContainerCount: DS.attr('number'),
databaseContainerCount: DS.attr('number'),
domainCount: DS.attr('number'),
totalAppCount: DS.attr('number'),
totalDatabaseCount: DS.attr('number'),
totalDiskSize: DS.attr('number'),
// relationships
apps: DS.hasMany('app', {async: true}),
certificates: DS.hasMany('certificate', {async: true}),
databases: DS.hasMany('database', {async: true}),
permissions: DS.hasMany('permission', {async:true}),
organization: DS.belongsTo('organization', {async:true}),
logDrains: DS.hasMany('log-drain', {async:true}),
vhosts: DS.hasMany('vhost', {async:true}),
// computed properties
pending: Ember.computed.not('activated'),
allowPHI: Ember.computed.match('type', /production/),
appContainerCentsPerHour: 8,
getUsageByResourceType(type) {
let usageAttr = { container: 'containerCount', disk: 'totalDiskSize',
domain: 'domainCount' }[type];
return this.get(usageAttr);
},
permitsRole(role, scope){
let permissions;
if (role.get('privileged') &&
role.get('data.links.organization') === this.get('data.links.organization')) {
return new Ember.RSVP.Promise((resolve) => {
resolve(true);
});
}
return this.get('permissions').then(function(_permissions){
permissions = _permissions;
return permissions.map(function(perm){
return {
roleId: getRoleIdFromPermission(perm),
scope: perm.get('scope')
};
});
}).then(function(stackRoleScopes){
return Ember.A(Ember.A(stackRoleScopes).filter((stackRoleScope) => {
return role.get('id') === stackRoleScope.roleId;
})).any((stackRoleScope) => {
return stackRoleScope.scope === 'manage' ||
stackRoleScope.scope === scope;
});
});
}
});
|
/**
* Created by obzerg on 16/1/5.
*/
var should = require('should');
var Yhsd = require('../index');
describe('test/webhook.test.js', function () {
var webHook;
before(function () {
webHook = new Yhsd.WebHook('fbc7f83524f14e358a325a5066acd741');
});
it('get webhook instance should be fail', function () {
(function () {
new Yhsd.WebHook()
}).should.throw('缺少参数');
});
it('verifyHmac should be throw error', function () {
(function () {
webHook.verifyHmac()
}).should.throw('缺少参数');
});
it('verifyHmac should be fail', function () {
webHook.verifyHmac('123', '123').should.be.false();
});
it('should verify hmac as correct', function () {
webHook.verifyHmac('Fp6SL4UABMWhXojvSGBneRs0h0wEnqxQrqT/ko/mqg0=', '12345qwert').should.be.true();
});
it('should verify hmac in Chinese as correct', function () {
webHook.verifyHmac('FXX5JR4sC7Z6kktz/vhxLcy3ydEdIHWpAHnqOxnXhJU=', '12345qwert友好速搭很棒').should.be.true();
})
}); |
var started = false,
callbacks = [],
oldContents = null;
request = require('request'),
chokidar = require('chokidar'),
processFunc = null,
parser = require('./parser');
module.exports = function(logPath) {
function invokeCallbacks() {
processFunc(logPath, function(err, logs) {
callbacks.forEach(function(callback) {
typeof callback === 'function' && callback(err, logs);
});
});
}
if (!started) {
started = true;
if (global.isUrl.test(logPath)) {
setInterval(function() {
request({
url: logPath,
encoding: "utf8"
}, function (err, res, body) {
if (err) throw err;
if (oldContents != body) {
oldContents = body;
invokeCallbacks();
}
});
}, 1000);
processFunc = parser.processURL.bind(parser);
} else {
var watcher = chokidar.watch(logPath);
watcher.on('change', function() {
invokeCallbacks();
});
processFunc = parser.processFile.bind(parser);
}
}
return {
change: function(callback) {
callbacks.push(callback);
invokeCallbacks();
},
invoke: invokeCallbacks
};
};
|
/*
Copyright (c) Microsoft Open Technologies, Inc.
All Rights Reserved
Apache License 2.0
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.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*_test.js']
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
examples: {
src: ['examples/*/*.js']
},
test: {
src: ['test/**/*.js']
}
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'nodeunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'nodeunit']
}
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task.
grunt.registerTask('default', ['jshint', 'nodeunit']);
};
|
//Router
openNote.config(function($routeProvider){
$routeProvider
.when("/folder/:id?",
{
controller: "folderController",
templateUrl: "openNote/partials/folderPartial.html",
})
.when("/note/:id?",
{
controller: "noteController",
templateUrl: "openNote/partials/notePartial.html"
})
.when("/search/:id?",
{
controller: "searchController",
templateUrl: "openNote/partials/searchPartial.html"
})
.when("/settings/",
{
controller: "settingsController",
templateUrl: "openNote/partials/settings/settingsPartial.html"
})
.when("/settings/database/",
{
controller: "databaseController",
templateUrl: "openNote/partials/settings/databasePartial.html"
})
.when("/settings/legacy/",
{
controller: "legacyController",
templateUrl: "openNote/partials/settings/legacyPartial.html"
})
.otherwise({ redirectTo: "/folder" });
}); |
var express = require('express');
var router = express.Router();
var Song = require('../models/song')
var iph = require('./iph')
//create new song
router.post('/create/', function(req, res, next){
var song = new Song({
title: req.body.title,
verses: req.body.verses,
CCLI: req.body.CCLI,
chorus: req.body.chorus,
position: req.body.position,
type: req.body.type
})
song.save(function(err, song){
if(err){return next(err)}
res.status(201).json(song)
})
})
//return all songs
router.get('/find/', function(req, res){
// Song.find(function(err, songs){
// if(err){return next(err)}
// res.json(songs)
// })
res.json(iph);
})
//return all titles of songs
router.get('/find/titles/:type', function(req, res){
// Song.find({type: req.params.type},'title', function(err, songs){
// if(err){return next(err)}
// res.json(songs)
// })
var songs = iph.filter(song => song.type === req.params.type);
res.json(songs);
})
//return all types of songs
router.get('/find/types/', function(req, res){
Song.find({},'type', function(err, songs){
if(err){return next(err)}
res.json(songs)
})
})
//return song by title
router.get('/find/:title', function(req, res){
// Song.find({title: req.params.title },function(err, songs){
// if(err){return next(err)}
// res.json(songs)
// })
var titles = iph.filter(song => song.title === req.params.title);
res.json(titles);
})
//return song by id
router.get('/find/:id', function(req, res){
// Song.find({_id: req.params.id },function(err, songs){
// if(err){return next(err)}
// res.json(songs)
// })
var songs = iph.filter(song => song.id === req.params.id);
res.json(songs);
})
//Delete songs by title
router.delete('/remove/:title', function (req, res) {
Song.remove({title: req.params.title}, function(err, songs){
if(err){return next(err)}
res.send('Songs with title: '+ req.params.title +' have been deleted');
})
});
//Delete songs by id
router.delete('/remove/id/:id', function (req, res) {
Song.remove({_id: req.params.id}, function(err, songs){
if(err){return next(err)}
res.send('Song with id: '+ req.params.id +' has been deleted');
})
});
//Update song by title
router.post('/update/:title', function(req, res, next){
var update = {
title: req.body.title,
verses: req.body.verses,
CCLI: req.body.CCLI,
chorus: req.body.chorus,
position: req.body.position,
type: req.body.type
}
var conditions = {title: req.params.title}
var options = {multi: false, upsert: true}
Song.findOneAndUpdate(conditions, update, options, function(err, song){
if(err){return next(err)}
res.status(200).json(update)
})
})
module.exports = router;
|
/**
* Command for mutating an update expression
* Created by Martin Koster on 2/16/15.
*/
(function(module) {
'use strict';
var _ = require('lodash'),
MutationOperator = require('./MutationOperator'),
MutationUtils = require('../utils/MutationUtils'),
updateOperatorReplacements = {
'++': '--',
'--': '++'
};
var code = 'UPDATE_EXPRESSION';
function UpdateExpressionMO (astNode) {
MutationOperator.call(this, astNode);
this.code = code;
this._replacement = updateOperatorReplacements[astNode.operator];
}
UpdateExpressionMO.prototype.apply = function () {
var astNode = this._astNode,
mutationInfo;
if (!this._original) {
this._original = astNode.operator;
astNode.operator = this._replacement;
if (astNode.prefix) {
// e.g. ++x
mutationInfo = MutationUtils.createMutation(astNode, astNode.argument.range[0], this._original, this._replacement);
} else {
// e.g. x++
mutationInfo = _.merge(MutationUtils.createMutation(astNode, astNode.argument.range[1], this._original, this._replacement), {
begin: astNode.argument.range[1],
line: astNode.loc.end.line,
col: astNode.argument.loc.end.column
});
}
}
return mutationInfo;
};
UpdateExpressionMO.prototype.revert = function() {
this._astNode.operator = this._original || this._astNode.operator;
this._original = null;
};
UpdateExpressionMO.prototype.getReplacement = function() {
var astNode = this._astNode,
coordinates = astNode.prefix ?
{begin: astNode.range[0], end: astNode.argument.range[0]} :
{begin: astNode.argument.range[1], end: astNode.range[1]};
return _.merge({value: this._replacement}, coordinates);
};
module.exports.create = function(astNode) {
if (updateOperatorReplacements.hasOwnProperty(astNode.operator)) {
return [new UpdateExpressionMO(astNode)];
} else {
return [];
}
};
module.exports.code = code;
})(module);
|
import { Mongo } from 'meteor/mongo';
import { CommentSchema } from './schema.js';
export const collectionName = 'comments';
const Comments = new Mongo.Collection(collectionName);
Comments.attachSchema(CommentSchema);
export { Comments };
|
var Backbone = require('backbone')
var L = require('leaflet')
var StopsResponseMapView = Backbone.View.extend({
initialize: function (options) {
_.bindAll(this, 'mapViewChanged')
this.options = options || {}
this.markerLayer = new L.LayerGroup()
this.options.map.addLayer(this.markerLayer)
this.options.map.on('viewreset dragend', this.mapViewChanged)
},
render: function () {
this.markerLayer.clearLayers()
_.each(this.model.get('stops').models, function (stop) {
var stopMarker = new L.CircleMarker([stop.get('lat'), stop.get(
'lon')], {
color: '#666',
stroke: 2,
radius: 4,
fillColor: '#eee',
opacity: 1.0,
fillOpacity: 1.0
})
stopMarker.bindLabel(stop.get('name'))
this.markerLayer.addLayer(stopMarker)
}, this)
},
newResponse: function (response) {
this.model = response
this.render()
},
mapViewChanged: function (e) {
this.markerLayer.clearLayers()
}
})
module.exports = StopsResponseMapView
|
const utils = require('./utils');
module.exports = handler => async (req, res) => {
try {
await handler(req, res);
} catch (err) {
return utils.sendJSONresponse(res, 401, err);
}
};
|
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const merge = require('webpack-merge')
const parts = require('./webpack.parts')
const PATHS = {
app: path.join(__dirname, 'app'),
build: path.join(__dirname, 'build')
}
const commonConfig = merge([
{
entry: {
babel: "babel-polyfill",
app: PATHS.app,
},
output: {
path: PATHS.build,
filename: '[name].js',
},
plugins: [
new HtmlWebpackPlugin({
hash: true,
title: 'Weather App',
template: '!!ejs-compiled-loader!' + PATHS.app + '/index.ejs',
}),
new CopyWebpackPlugin([
{ from: 'app/assets', to: 'assets' },
])
],
},
parts.babel({exclude: /node_modules/}),
])
const productionConfig = merge([
parts.extractCSS({
use: ['css-loader', parts.autoprefix()],
}),
parts.loadImages({
options: {
limit: 15000,
name: '[name].[ext]',
},
}),
])
const developmentConfig = merge([
parts.devServer({
host: process.env.HOST,
port: process.env.PORT,
}),
parts.loadCSS(),
parts.loadImages(),
])
module.exports = (env) => {
if (env === 'production') {
return merge(commonConfig, productionConfig)
}
return merge(commonConfig, developmentConfig)
}
|
var assert = require('assert');
var sinon = require('sinon');
var adventure = require('../');
describe('adventure', () => {
before(() => {
this.shop = adventure('test-adventure');
this.shop.add('test', () => { return {}});
});
describe('#add', () => {
it('add new adventure', () => {
assert.equal(this.shop._adventures.length, 1);
});
});
describe('#find', () => {
it('return adventure selected', () => {
this.shop.add('other-test', () => {});
assert.equal(this.shop._adventures.length, 2);
assert.equal(this.shop.find('test'), this.shop._adventures[0]);
});
});
describe('#select', () => {
it('show adventure problem', () => {
var dinosaurs = require('./../example/dinosaurs');
this.shop.add('dinosaurs', () => dinosaurs);
var stub = sinon.stub(this.shop, '_show');
this.shop.select('dinosaurs');
assert(stub.calledOnce);
assert(stub.calledWith(dinosaurs.problem));
this.shop._show.restore();
});
});
describe('with verify stubed', () => {
before(() => {
this.dinosaurs = require('./../example/dinosaurs');
this.stub = sinon.stub(this.dinosaurs, 'verify');
this.shop.add('dinosaurs', () => this.dinosaurs);
this.shop.select('dinosaurs');
});
after(() => {
this.dinosaurs.verify.restore();
});
describe('#verify', () => {
it('run adventure verify', () => {
this.shop.verify('rawr', 'dinosaurs');
assert(this.stub.calledOnce);
});
});
describe('#execute', () => {
it('command', () => {
this.shop.execute(['verify']);
assert(this.stub.called);
});
});
});
});
|
export App from './App/App';
export Chat from './Chat/Chat';
export Home from './Home/Home';
export Widgets from './Widgets/Widgets';
export Scrap from './Scrap/Scrap';
export About from './About/About';
export Login from './Login/Login';
export LoginSuccess from './LoginSuccess/LoginSuccess';
export Survey from './Survey/Survey';
export NotFound from './NotFound/NotFound';
|
<!-- 变量->表达式->语句->程序 -->
<!-- 基本语法 -->
1.直接量
var number = 1;
这里1就是一个直接量。
直接量还可以是:
1.2
"字符串"
true
false
null
[]
{name:'js'}
...
2.变量
var number = 1;
number就是变量
相当于一个盒子,
名字叫number(标识符)
把直接量放进去(赋值)。
声明:
var 变量名1,变量名2;
3.标识符
var number;
变量的名称,函数名,参数名,对象名称等;
必须以字母,下划线或$开头,组成上可以有数字
大小写敏感
4.关键字和保留字
关键字,保留字不能做标识符
5.语句
加分号,可以嵌套
{复合语句}
//单行注释
/**/块级注释,不可嵌套
|
/*eslint es6:true */
/*global o_o, expect*/
describe('errors.test.js', function () {
var expect = chai.expect;
// XXX: don't know how to handle it,
it.skip('should throw when no callback is specified', function (done) {
o_o.run(function *() { throw new Error('zork'); })
});
it('breaks before first yield', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var fnc = o_o(function *() {
throw new Error(msg);
});
fnc(function (err) {
expect(err.message).to.be.equal(msg);
return done();
});
});
it('breaks after first yield before second yield', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var fnc = o_o(function *() {
var cb = yield;
throw new Error(msg);
});
fnc(function (err) {
expect(err.message).to.be.equal(msg);
return done();
});
});
it('breaks after second yield in async', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var fnc = o_o(function *() {
var cb = yield;
setTimeout(cb, 50);
var result = yield;
throw new Error(msg);
});
fnc(function (err) {
expect(err.message).to.be.equal(msg);
return done();
});
});
it('breaks after second yield in sync', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var fnc = o_o(function *() {
var cb = yield;
cb();
var result = yield;
throw new Error(msg);
});
fnc(function (err) {
expect(err.message).to.be.equal(msg);
return done();
});
});
it('breaks after third yield', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var fnc = o_o(function *() {
var cb = yield;
cb();
var result = yield;
var cb1 = yield;
throw new Error(msg);
});
fnc(function (err) {
expect(err.message).to.be.equal(msg);
return done();
});
});
it('breaks after fourth yield', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var fnc = o_o(function *() {
var cb = yield;
cb();
var result = yield;
var cb1 = yield;
cb1();
result = yield;
throw new Error(msg);
});
fnc(function (err) {
expect(err.message).to.be.equal(msg);
return done();
});
});
it('breaks after fourth yield in async', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var fnc = o_o(function *() {
var cb = yield;
cb();
var result = yield;
var cb1 = yield;
setTimeout(cb1, 50);
result = yield;
throw new Error(msg);
});
fnc(function (err) {
expect(err.message).to.be.equal(msg);
return done();
});
});
it('should show error if cb is called twice after second yield sync', function (done) {
var counter = 0;
var finished = false;
o_o(function *() {
var cb = yield;
cb();
var ret = yield;
expect(function () {
cb();
}).to.throw('Callback is called twice');
finished = true;
})(function (err) {
counter++;
expect(counter).to.equal(1);
expect(finished).to.be.true;
return done();
});
});
it('should show error if cb is called twice after second yield async', function (done) {
var counter = 0;
o_o(function *() {
var cb = yield;
cb();
var ret = yield;
setTimeout(function () {
expect(function () {
cb();
}).to.throw('Callback is called twice');
}, 50);
})(function (err) {
expect(err).to.be.not.ok;
counter++;
expect(counter).to.equal(1);
return done();
});
});
it('should show error if cb is called twice before yield in sync', function (done) {
var finished = false;
o_o(function *() {
var cb = yield;
cb();
expect(function () {
cb();
}).to.throw('Callback is called twice');
yield;
finished = true;
})(function (err) {
expect(finished).to.be.true;
return done();
});
});
it('should show error when generator returns before in sync', function (done) {
var fnc = o_o(function *() {
var cb = yield;
cb(null, 'result one');
return;
});
fnc(function (err) {
expect(err.message).to.include('Generator has no second yield statement');
return done();
});
});
it('should show error when generator returns before in async', function (done) {
var fnc = o_o(function *() {
var cb = yield;
setTimeout(function () {
cb(null, 'result one');
}, 50);
return;
});
fnc(function (err) {
expect(err.message).to.include('Generator has no second yield statement');
return done();
});
});
it('should give error that function is not a generator', function () {
expect(function () {
o_o({});
}).to.throw('Generator is not a function');
});
it('should throw and catch an error when callback recieves error as first argument', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var method = function (cb) {
setTimeout(function () {
cb(new Error(msg));
}, 50);
};
var result = null;
var gen = o_o(function *() {
var cb = yield;
try {
yield method(cb);
} catch (e) {
result = e;
}
return;
});
gen(function () {
expect(result).to.have.property('message').and.be.equal(msg);
return done();
});
});
it('should throw an error when callback receives error as first argument', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var method = function (cb) {
setTimeout(function () {
cb(new Error(msg));
}, 50);
};
var gen = o_o(function *() {
var cb = yield;
yield method(cb);
return;
});
gen(function (result) {
expect(result).to.have.property('message').and.be.equal(msg);
return done();
});
});
it('should NOT block generator after error is thrown', function (done) {
var msg = 'error #' + ~~(Math.random() * 1000);
var method = function (cb) {
setTimeout(function () {
cb(new Error(msg));
}, 50);
};
var flag = 'bad';
var gen = o_o(function *() {
var cb = yield;
try {
yield method(cb);
} catch(e) {
flag = 'processed';
}
cb = yield;
yield setTimeout(function () {
cb();
}, 50);
flag = 'good';
return;
});
gen(function () {
expect(flag).to.be.equal('good');
return done();
});
});
it('should break with raw generator', function (done) {
var id = new Date().getTime().toString(16);
var rawGenerator = function *(a) {
var cb = yield;
yield setTimeout(function () {
return cb();
}, 20);
throw new Error(id);
};
o_o.run(function *() {
var result;
try {
yield rawGenerator(id);
} catch(e) {
result = e;
}
expect(result.message).to.be.equal(id);
done();
});
});
it('should break when too much arguments are specified', function () {
var fnc = o_o(function *(one, two) {
console.log('hoho', one);
});
expect(function () {
fnc('bla', 'two', 'three');
}).to.throw('Arguments mismatch, too much arguments passed.');
});
// it('should detach from the main thread when calling cb', function (done) {
//
// var counter = 0;
//
// o_o(function *() {
// yield (yield)();
// })(function (err) {
// counter++;
// expect(counter).to.be.equal(1);
// done();
// throw new Error();
// });
//
// });
});
|
import { mount } from '@vue/test-utils'
import Banner from '@/components/banner'
describe('Banner', () => {
let wrapper
beforeEach(() => {
wrapper = mount(Banner, { sync: true })
})
it('is a Vue instance', () => {
expect(wrapper.isVueInstance()).toBeTruthy()
})
it('has data properties', () => {
const expected = ['I18n']
const received = Object.keys(wrapper.vm.$data)
expect(received).toEqual(expected)
})
it('renders correctly', () => {
expect(wrapper).toMatchSnapshot()
})
})
|
/// <reference path="../scripts/jquery-1.8.3.js" />
/// <reference path="../scripts/jquery.signalR-1.0.0.js" />
/*!
ASP.NET SignalR Stock Ticker Sample
*/
// Crockford's supplant method (poor man's templating)
if (!String.prototype.supplant) {
String.prototype.supplant = function (o) {
return this.replace(/{([^{}]*)}/g,
function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
}
// A simple background color flash effect that uses jQuery Color plugin
jQuery.fn.flash = function (color, duration) {
var current = this.css('backgroundColor');
this.animate({ backgroundColor: 'rgb(' + color + ')' }, duration / 2)
.animate({ backgroundColor: current }, duration / 2);
}
$(function () {
var ticker = $.connection.stockTicker, // the generated client-side hub proxy
up = '▲',
down = '▼',
$stockTable = $('#stockTable'),
$stockTableBody = $stockTable.find('tbody'),
rowTemplate = '<tr data-symbol="{Symbol}"><td>{Symbol}</td><td>{Price}</td><td>{DayOpen}</td><td>{DayHigh}</td><td>{DayLow}</td><td><span class="dir {DirectionClass}">{Direction}</span> {Change}</td><td>{PercentChange}</td></tr>',
$stockTicker = $('#stockTicker'),
$stockTickerUl = $stockTicker.find('ul'),
liTemplate = '<li data-symbol="{Symbol}"><span class="symbol">{Symbol}</span> <span class="price">{Price}</span> <span class="change"><span class="dir {DirectionClass}">{Direction}</span> {Change} ({PercentChange})</span></li>';
function formatStock(stock) {
return $.extend(stock, {
Price: stock.Price.toFixed(2),
PercentChange: (stock.PercentChange * 100).toFixed(2) + '%',
Direction: stock.Change === 0 ? '' : stock.Change >= 0 ? up : down,
DirectionClass: stock.Change === 0 ? 'even' : stock.Change >= 0 ? 'up' : 'down'
});
}
function scrollTicker() {
var w = $stockTickerUl.width();
$stockTickerUl.css({ marginLeft: w });
$stockTickerUl.animate({ marginLeft: -w }, 15000, 'linear', scrollTicker);
}
function stopTicker() {
$stockTickerUl.stop();
}
function init() {
return ticker.server.getAllStocks().done(function (stocks) {
$stockTableBody.empty();
$stockTickerUl.empty();
$.each(stocks, function () {
var stock = formatStock(this);
$stockTableBody.append(rowTemplate.supplant(stock));
$stockTickerUl.append(liTemplate.supplant(stock));
});
});
}
// Add client-side hub methods that the server will call
$.extend(ticker.client, {
updateStockPrice: function (stock) {
var displayStock = formatStock(stock),
$row = $(rowTemplate.supplant(displayStock)),
$li = $(liTemplate.supplant(displayStock)),
bg = stock.LastChange === 0
? '255,216,0' // yellow
: stock.LastChange > 0
? '154,240,117' // green
: '255,148,148'; // red
$stockTableBody.find('tr[data-symbol=' + stock.Symbol + ']')
.replaceWith($row);
$stockTickerUl.find('li[data-symbol=' + stock.Symbol + ']')
.replaceWith($li);
$row.flash(bg, 1000);
$li.flash(bg, 1000);
},
marketOpened: function () {
$("#open").prop("disabled", true);
$("#close").prop("disabled", false);
$("#reset").prop("disabled", true);
scrollTicker();
},
marketClosed: function () {
$("#open").prop("disabled", false);
$("#close").prop("disabled", true);
$("#reset").prop("disabled", false);
stopTicker();
},
marketReset: function () {
return init();
}
});
// Start the connection
$.connection.hub.start()
.pipe(init)
.pipe(function () {
return ticker.server.getMarketState();
})
.done(function (state) {
if (state === 'Open') {
ticker.client.marketOpened();
} else {
ticker.client.marketClosed();
}
// Wire up the buttons
$("#open").click(function () {
ticker.server.openMarket();
});
$("#close").click(function () {
ticker.server.closeMarket();
});
$("#reset").click(function () {
ticker.server.reset();
});
});
}); |
(function () {
'use strict';
angular.module('gAnalytics').controller('HomeController', HomeController);
/** @ngInject */
function HomeController(CONFIG, CONFIG_QUERIES, $http, configService) {
var vm = this;
vm.selectedProperty = CONFIG.selectedProperty;
vm.navbar = {};
var configQueries = configService.getConfig() || CONFIG_QUERIES;
vm.navbar.items = configQueries.analyticsItems;
}
})();
|
var gulp = require("gulp");
var webserver = require("gulp-webserver");
var mochaPhantomJS = require("gulp-mocha-phantomjs");
var browserify = require("browserify");
var source = require("vinyl-source-stream");
var jshint = require("gulp-jshint");
var stylish = require("jshint-stylish");
var header = require('gulp-header');
var pkg = require('./package.json');
var date = new Date();
var today = date.toDateString() + " " + date.toLocaleTimeString();
var banner = "/*! <%= pkg.name %> v<%= pkg.version %> - " + today + ". (c) " + date.getFullYear() + " Miguel Castillo. Licensed under MIT */\n";
gulp.task("test", ["build-debug"], function() {
return gulp.src("test/SpecRunner.html")
.pipe(mochaPhantomJS({
reporter: 'tap',
mocha: {
grep: 'pattern'
},
phantomjs: {
viewportSize: {
width: 1024,
height: 768
}
}
}));
});
gulp.task("serve", ["build-release", "build-debug"], function() {
gulp.src(".")
.pipe(webserver({
livereload: true,
open: "test/SpecRunner.html"
}));
gulp.watch(["src/**/*.js", "test/**/*.js"], ["build"]);
});
gulp.task("build-release", ["jshint"], function() {
return browserify({
debug: true, // Add source maps to output to allow minifyify convert them to minified source maps
standalone: "amdresolver",
detectGlobals: false
})
.plugin("minifyify", {
map: "dist/amd-resolver.min.js.map",
output: "dist/amd-resolver.min.js.map"
})
.ignore("process")
.add("./src/resolver.js")
.bundle()
.pipe(source("amd-resolver.min.js"))
.pipe(header(banner, {pkg: pkg}))
.pipe(gulp.dest("dist"));
});
gulp.task("build-debug", ["jshint"], function() {
return browserify("./src/resolver.js", {
standalone: "amdresolver",
detectGlobals: false
})
.ignore("process")
.bundle()
.pipe(source("amd-resolver.js"))
.pipe(header(banner, {pkg: pkg}))
.pipe(gulp.dest("dist"));
});
gulp.task("build-debug-watch", function() {
gulp.watch("src/**/*.js", ["build-debug"]);
});
gulp.task("jshint", function() {
return gulp.src(["src/**/*.js", "test/**/*.js", "gulpfile.js"])
.pipe(jshint())
.pipe(jshint.reporter(stylish))
.pipe(jshint.reporter("fail"));
});
gulp.task("build", ["jshint", "build-release", "build-debug"]);
|
(function(){var a={months:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),monthsShort:"1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"),weekdays:"일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"),weekdaysShort:"일_월_화_수_목_금_토".split("_"),longDateFormat:{LT:"A h시 mm분",L:"YYYY.MM.DD",LL:"YYYY년 MMMM D일",LLL:"YYYY년 MMMM D일 LT",LLLL:"YYYY년 MMMM D일 dddd LT"},meridiem:function(a,b,c){return a<12?"오전":"오후"},calendar:{sameDay:"오늘 LT",nextDay:"내일 LT",nextWeek:"dddd LT",lastDay:"어제 LT",lastWeek:"지난주 dddd LT",sameElse:"L"},relativeTime:{future:"%s 후",past:"%s 전",s:"몇초",ss:"%d초",m:"일분",mm:"%d분",h:"한시간",hh:"%d시간",d:"하루",dd:"%d일",M:"한달",MM:"%d달",y:"일년",yy:"%d년"},ordinal:function(a){return"일"}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("kr",a)})(); |
'use strict';
let Fingdex = require('../');
module.exports = function indexByType (docIndex, type) {
let index = new Fingdex(docIndex);
index.ids = new Set();
index.through = function (entry) {
// only update the index when a new doc is created and matches the type
if (!entry.isNew) { return; }
if (entry._type !== type) { return; }
this.ids.add(entry._id);
};
return index;
};
|
'use strict';
const _ = require('lodash'),
chalk = require('chalk'),
debugCreate = require('debug'),
http = require('http'),
rp = require('request-promise'),
supportsColor = require('supports-color'),
util = require('util');
const API_BASE_ROUTE = '/api/v4',
ROUTE_PARAM_PATTERN = /:([^/:]+)/g;
const debug = debugCreate('gitlab-slack:api');
/**
* Defines a wrapper for the GitLab API.
*/
class GitLabApi {
/**
* Creates an instance of `GitLabApi`.
* @param {String} baseUrl The API base URL.
* @param {String} token The API token.
*/
constructor(baseUrl, token) {
this._baseUrl = baseUrl + API_BASE_ROUTE;
this._token = token;
}
/**
* Gets user information by ID.
* @param {String|Number} userId The user ID.
* @returns {Promise} A promise that will be resolved with the user information.
*/
getUserById(userId) {
return this.sendRequest(
'/users/:userId',
{ userId }
);
}
/**
* Searches for a user by username or email address.
* @param {String} search Search term.
* @returns {Promise} A promise that will be resolved with a list of matching users.
*/
searchUsers(search) {
// The provided search terms should not be returning more than 100 users.
return this.sendRequest(
'/users',
/* eslint-disable camelcase */ // Required property naming.
{
per_page: 100,
search
}
/* eslint-enable camelcase */
);
}
/**
* Gets a project by ID.
* @param {String|Number} projectId The project ID.
* @returns {Promise<Object>} A promise that will be resolved with the project information.
*/
getProject(projectId) {
return this.sendRequest(
'/projects/:projectId',
{ projectId }
);
}
/**
* Gets a page of open issues for a project.
* @param {String|Number} projectId The project ID.
* @param {Number} [page] The page to get.
* @returns {Promise.<{data: *, page: Number, totalPages: Number}>} A promise that will be resolved with a page of open issues.
*/
getOpenIssues(projectId, page) {
return this.sendPaginatedRequest(
'/projects/:projectId/issues',
{
projectId,
state: 'opened'
},
page
);
}
/**
* Gets the labels for a project.
* @param {Number} projectId The project ID.
* @returns {Promise} A promise that will be resolved with project labels.
*/
getLabels(projectId) {
// Technically the labels API is paginated, but who has more than 100 labels?
return this.sendRequest(
'/projects/:projectId/labels',
/* eslint-disable camelcase */ // Required property naming.
{
per_page: 100,
projectId
}
/* eslint-enable camelcase */
);
}
/**
* Gets a milestone.
* @param {Number} projectId The project ID.
* @param {Number} milestoneId The milestone ID.
* @returns {Promise} A promise that will be resolved with the milestone.
*/
getMilestone(projectId, milestoneId) {
return this.sendRequest(
'/projects/:projectId/milestones/:milestoneId',
{ projectId, milestoneId }
);
}
/**
* Sends a request to a paginated resource.
* @param {String} route The route.
* @param {Object} [params] A map of parameters.
* @param {Number} [page] The page to get. (default = `1`)
* @returns {Promise<{ data: *, page: Number, totalPages: Number }>} A promise that will be resolved with the paginated result.
*/
async sendPaginatedRequest(route, params = {}, page = 1) {
/* eslint-disable camelcase */ // Required property naming.
params.per_page = 100;
params.page = page;
/* eslint-enable camelcase */
const response = await this.sendRequest(route, params, true);
return {
data: response.body,
page: parseInt(response.headers['x-page'], 10),
totalPages: parseInt(response.headers['x-total-pages'], 10)
};
}
/**
* Sends a request to the GitLab API.
* @param {String} route The route.
* @param {Object} [params] A map of parameters.
* @param {Boolean} [full] Indicates whether the full response should be returned.
* @returns {Promise<*>} A promise that will be resolved with the API result.
*/
async sendRequest(route, params, full) {
if (!route) {
throw new Error('GitLabApi sendRequest - route is required.');
}
if (!params) {
params = {};
}
// We drain any route parameters out of params first; the rest are query string parameters.
const filledRoute = route.replace(ROUTE_PARAM_PATTERN, function (match, name) {
const value = params[name];
if (_.isNil(value)) {
throw new Error(`GitLabApi ${route} - Route parameter ${name} was not present in params.`);
}
delete params[name];
return value.toString();
});
if (_.isEmpty(params)) {
debug(chalk`{cyan SEND} -> GET {gray %s}`, filledRoute);
} else {
debug(chalk`{cyan SEND} -> GET {gray %s} %o`, filledRoute, !_.isEmpty(params) ? params : undefined);
}
try {
const response = await rp({
url: this._baseUrl + filledRoute,
qs: params,
headers: {
Accept: 'application/json',
'Private-Token': this._token
},
json: true,
rejectUnauthorized: false,
resolveWithFullResponse: true
});
debug(chalk`{cyan RECV} <- GET {gray %s} -> {green %d %s}`, filledRoute, response.statusCode, http.STATUS_CODES[response.statusCode]);
return full ? response : response.body;
} catch (e) {
let output, message;
if (!e.response) {
message = e.message;
} else {
output = e.response.toJSON();
message = output.body.error || output.body.message || output.body;
}
const failure = new Error(`GitLabApi ${filledRoute} - ${message}`);
failure.statusCode = e.statusCode;
if (output) {
debug(chalk`{red FAIL} <- GET {gray %s} -> {red %d} {redBright %s} ! %s`, filledRoute, failure.statusCode, http.STATUS_CODES[failure.statusCode], message);
console.log(chalk`{red FAIL} {yellow Response Body ---------------------}`, '\n', util.inspect(output, { colors: supportsColor.stdout.level > 0, depth: 5 }));
} else {
debug(chalk`{red FAIL} <- GET {gray %s} -> {red %s} ! %s`, filledRoute, e.name, message);
}
throw failure;
}
}
}
exports.GitLabApi = GitLabApi;
|
var execFile = require('child_process').execFile,
expect = require("chai").expect,
path = require('path');
describe('Multiple questions', function() {
it('What is your name ?', function(done) {
var cp = execFile('node', [path.join(__dirname, './questions.command.js')], null),
i = 1;
cp.stdout.on('data', function(data) {
if (i == 1) {
expect(data)
.to.contain('firstname:');
}
if (i == 2) {
expect(data)
.to.contain('lastname:');
}
if (i == 3) {
expect(data)
.to.contain('My name is chuck norris');
}
i++;
});
setTimeout(function() {
cp.stdin.write('chuck\n');
}, 500);
setTimeout(function() {
cp.stdin.write('norris\n');
cp.stdin.end();
done();
}, 1000);
});
});
|
search_result['1019']=["topic_000000000000024F.html","SystemManagementController.ManageBadges Method",""]; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.